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
21 intrude import semantize
::local_var_init
22 intrude import semantize
::scope
23 intrude import toolcontext
24 private import parser_util
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
31 for i
in [0 .. mmodules
.length
[ do
32 if mmodules
[i
] == m
then
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
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
58 prop
.mpropdefs
.remove_at
(index
)
65 redef class ScopeVisitor
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
80 redef class LocalVarInitVisitor
81 redef fun mark_is_unset
(node
: AExpr, variable
: nullable Variable)
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
)
97 redef class ToolContext
98 private var dbg
: nullable Debugger = null
100 private var had_error
: Bool = false
102 redef fun check_errors
107 if messages
.length
> 0 then
108 message_sorter
.sort
(messages
)
111 if m
.text
.search
("Warning") == null then had_error
= true
112 sys
.stderr
.write
("{m.to_color_string}\n")
122 var opt_debugger_mode
= new OptionBool("Launches the target program with the debugger attached to it", "-d")
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")
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 interpreter
.start
(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 interpreter
.start
(mainmodule
)
165 self.toolcontext
.info
("*** END INTERPRETING: {time1-time0} ***", 2)
169 # Contains all the informations of a Breakpoint for the Debugger
175 # File concerned by the breakpoint
179 if not file
.has_suffix
(".nit") then file
+= ".nit"
183 # The class extending `NaiveInterpreter` by adding debugging methods
185 super NaiveInterpreter
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
191 # Triggers a step over an instruction in a nit program
192 var stop_after_step_over_trigger
= true
194 # Triggers a step out of an instruction
195 var stop_after_step_out_trigger
= false
197 # Triggers a step in a instruction (enters a function
198 # if the instruction is a function call)
199 var step_in_trigger
= false
201 # HashMap containing the breakpoints bound to a file
202 var breakpoints
= new HashMap[String, HashSet[Breakpoint]]
204 # Contains the current file
207 # Aliases hashmap (maps an alias to a variable name)
208 var aliases
= new HashMap[String, String]
210 # Set containing all the traced variables and their related frame
211 private var traces
= new HashSet[TraceObject]
213 # Map containing all the positions for the positions of the arguments traced
215 private var fun_call_arguments_positions
= new HashMap[Int, TraceObject]
217 # Triggers the remapping of a trace object in the local context after a function call
218 var aftermath
= false
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
224 # Auto continues the execution until the end or until an error is encountered
225 var autocontinue
= false
227 redef type FRAME: InterpreterFrame
229 #######################################################################
230 ## Execution of statement function ##
231 #######################################################################
233 # Main loop, every call to a debug command is done here
234 redef fun stmt
(n
: nullable AExpr)
236 if n
== null then return
238 var frame
= self.frame
239 var old
= frame
.current_node
240 frame
.current_node
= n
242 if sys
.stdin
.poll_in
then process_debug_command
(gets
)
244 if not self.autocontinue
then
245 if not n
isa ABlockExpr then
250 check_funcall_and_traced_args
(n
)
254 check_if_vars_are_traced
(n
)
259 frame
.current_node
= old
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
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
)
274 # Same as a regular call but for a runtime injected module
275 fun rt_call
(mpropdef
: MMethodDef, args
: Array[Instance]): nullable Instance
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}")
281 assert args
.length
== mpropdef
.msignature
.arity
+ 1 else debug
("Invalid arity for {mpropdef}. {args.length} arguments given.")
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
)
292 fatal
("Fatal Error: method {mpropdef} not found in the AST")
297 # Evaluates dynamically a snippet of Nit code
298 # `nit_code` : Nit code to be executed
299 fun eval
(nit_code
: String)
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
)
309 nit_code
= "module rt_module\nprint " + nit_code
310 e
= local_toolctx
.parse_something
(nit_code
)
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
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"
329 var mobj
= new MutableInstance(sys_type
)
331 var initprop
= mmod
.try_get_primitive_method
("init", sys_type
.mclass
)
332 if initprop
!= null then
333 self.send
(initprop
, [mobj
])
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
])
341 print
"Error while loading_rt_module"
344 print
"Error when parsing, e = {e.class_name}"
346 local_toolctx
.dbg
= null
349 # Encpasulates the behaviour for step over/out
350 private fun steps_fun_call
(n
: AExpr)
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
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
362 else if step_in_trigger
then
363 n
.debug
("Execute stmt {n.to_s}")
364 while read_cmd
do end
368 # Checks if a breakpoint is encountered, and launches the debugging prompt if true
369 private fun breakpoint_check
(n
: AExpr)
371 var currFileNameSplit
= self.frame
.current_node
.location
.file
.filename
.to_s
.split_with
("/")
373 self.curr_file
= currFileNameSplit
[currFileNameSplit
.length-1
]
375 var breakpoint
= find_breakpoint
(curr_file
, n
.location
.line_start
)
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
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)
387 var identifiers_in_instruction
= get_identifiers_in_current_instruction
(n
.location
.text
)
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
400 # Function remapping all the traced objects to match their name in the local context
401 private fun remap
(n
: AExpr)
403 if self.aftermath
then
405 # Trace every argument variable pre-specified
406 if self.frame_count_aftermath
< frames
.length
and fun_call_arguments_positions
.length
> 0 then
408 var ids_in_fun_def
= get_identifiers_in_current_instruction
(get_function_arguments
(frame
.mpropdef
.location
.text
))
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
])
415 self.aftermath
= false
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
))
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
441 #######################################################################
442 ## Processing commands functions ##
443 #######################################################################
448 return process_debug_command
(gets
)
451 # Takes a user command as a parameter
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
458 if command
== "finish"
462 else if command
== "s"
466 else if command
== "n" then
469 else if command
== "help" then
472 else if command
== "bt" or command
== "backtrack" then
475 # Continues execution until the end
476 else if command
== "c" then
478 else if command
== "nit" then
481 var nit_buf
= new FlatBuffer
482 while not command
== ":q" do
483 nit_buf
.append
(command
)
490 else if command
== "quit" then
492 else if command
== "abort" then
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
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
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
)
526 # Produces help for the commands of the debugger
530 print
"-----------------------------------"
533 print
" * Modification: var_name = value (Warning: var_name must be primitive)"
534 print
" * Alias: var_name as alias"
537 print
" * Variables: p(rint) var_name (Use * to print all local variables)"
538 print
" * Collections: p(rint) var_name '[' start_index (.. end_index) ']'"
541 print
" * File/line: b(reak) file_name line_number"
542 print
" * Remove: d(elete) id"
545 print
" * Variable: trace var_name break/print"
546 print
" * Untrace variable: untrace var_name"
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"
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"
562 #######################################################################
563 ## Processing specific command functions ##
564 #######################################################################
566 # Sets the flags to step-over an instruction in the current file
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
576 #Sets the flags to step-out of a function
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
586 # Sets the flags to step-in an instruction
589 self.step_in_trigger
= true
590 self.stop_after_step_over_trigger
= false
591 self.stop_after_step_out_trigger
= false
595 # Sets the flags to continue execution
596 fun continue_exec
: Bool
598 self.stop_after_step_over_trigger
= false
599 self.stop_after_step_out_trigger
= false
600 self.step_in_trigger
= false
604 fun bad_command
(cmd
: String) do
605 print
"Unrecognized command {cmd}. Use 'help' to show help."
608 # Prints the demanded variable in the command
610 # The name of the variable in in position 1 of the array 'parts_of_command'
611 fun print_command
(parts
: Array[String])
613 if parts
.length
!= 2 then
614 bad_command
(parts
.join
(" "))
617 if parts
[1] == "*" then
618 var map_of_instances
= frame
.map
620 var self_var
= seek_variable
("self", frame
)
621 print
"self: {self_var.to_s}"
623 for instance
in map_of_instances
.keys
do
624 print
"{instance.to_s}: {map_of_instances[instance].to_s}"
626 else if parts
[1].chars
.has
('[') and parts
[1].chars
.has
(']') then
627 process_array_command
(parts
)
629 var instance
= seek_variable
(get_real_variable_name
(parts
[1]), frame
)
633 print_instance
(instance
)
635 print
"Cannot find variable {parts[1]}"
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
(" "))
646 add_alias
(parts
.first
, parts
.last
)
649 # Processes the input string to know where to put a breakpoint
650 fun process_place_break_fun
(parts
: Array[String])
652 if parts
.length
!= 3 then
653 bad_command
(parts
.join
(" "))
656 var bp
= get_breakpoint_from_command
(parts
)
662 # Returns a breakpoint containing the informations stored in the command
663 fun get_breakpoint_from_command
(parts
: Array[String]): nullable Breakpoint
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])
674 # Processes the command of removing a breakpoint on specified line and file
675 fun process_remove_break_fun
(parts
: Array[String])
677 if parts
.length
!= 2 then
678 bad_command
(parts
.join
(" "))
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
)
688 # Processes an array print command
689 fun process_array_command
(parts
: Array[String])
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
)
695 var indexes
= remove_braces
(braces
)
697 var index_array
= new Array[Array[Int]]
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
709 var instance
= seek_variable
(variable_name
, frame
)
711 if instance
!= null then
712 print_nested_collection
(instance
, index_array
, 0, variable_name
, "")
714 print
"Cannot find variable {variable_name}"
718 # Processes the modification function to modify a variable dynamically
720 # Command of type variable = value
721 fun process_mod_function
(parts
: Array[String])
723 if parts
.length
!= 3 then
724 bad_command
(parts
.join
(" "))
728 p0
= get_real_variable_name
(p0
)
729 var parts_of_variable
= p0
.split_with
(".")
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
)
736 if papa
!= null and papa
isa MutableInstance then
737 var attribute
= get_attribute_in_mutable_instance
(papa
, last_part
)
739 if attribute
!= null then
740 modify_argument_of_complex_type
(papa
, attribute
, parts
[2])
744 var target
= seek_variable
(parts_of_variable
[0], frame
)
745 if target
!= null then
746 modify_in_frame
(target
, parts
[2])
751 # Processes the untrace variable command
753 # Command pattern : "untrace variable"
754 fun process_untrace_command
(parts
: Array[String])
756 if parts
.length
!= 2 then
757 bad_command
(parts
.join
(" "))
760 var variable_name
= get_real_variable_name
(parts
[1])
761 if untrace_variable
(variable_name
) then
762 print
"Untraced variable {parts[1]}"
764 print
"{parts[1]} is not traced"
768 # Processes the trace variable command
770 # Command pattern : "trace variable [break/print]"
771 fun process_trace_command
(parts
: Array[String])
773 if parts
.length
!= 3 then
774 bad_command
(parts
.join
(" "))
777 var variable_name
= get_real_variable_name
(parts
[1])
780 if seek_variable
(variable_name
, frame
) == null then
781 print
"Cannot find a variable called {parts[1]}"
785 if parts
[2] == "break" then
791 trace_variable
(variable_name
, breaker
)
793 print
"Successfully tracing {parts[1]}"
796 #######################################################################
797 ## Trace Management functions ##
798 #######################################################################
800 # Effectively untraces the variable called *variable_name*
802 # Returns true if the variable exists, false otherwise
803 private fun untrace_variable
(variable_name
: String): Bool
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
812 if to_remove
!= null then
813 self.traces
.remove
(to_remove
)
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)
822 private fun trace_variable
(variable_name
: String, breaker
: Bool)
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"
831 var trace_object
: TraceObject
834 trace_object
= new TraceObject(true)
836 trace_object
= new TraceObject(false)
839 # We trace the current variable found for the current frame
840 trace_object
.add_frame_variable
(self.frame
, variable_name
)
842 var position_of_variable_in_arguments
= get_position_of_variable_in_arguments
(frame
, variable_name
)
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
848 # If the variable was reported to be an argument of the previous frame
849 if position_of_variable_in_arguments
!= -1 then
851 var local_name
= get_identifiers_in_current_instruction
(get_function_arguments
(frames
[i
].current_node
.location
.text
))[position_of_variable_in_arguments
]
853 position_of_variable_in_arguments
= get_position_of_variable_in_arguments
(frames
[i
], local_name
)
855 trace_object
.add_frame_variable
(frames
[i
], local_name
)
861 self.traces
.add
(trace_object
)
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
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
877 # Gets all the identifiers of an instruction (uses the rules of Nit as of Mar 05 2013)
879 fun get_identifiers_in_current_instruction
(instruction
: Text): Array[String]
881 var result_array
= new Array[String]
882 var instruction_buffer
= new FlatBuffer
884 var trigger_char_escape
= false
885 var trigger_string_escape
= false
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
892 trigger_string_escape = false
893 else if i == '\
"' then trigger_string_escape = false
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
901 result_array.push(instruction_buffer.to_s)
902 instruction_buffer.add(i)
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
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
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)
922 # Takes a function call or declaration and strips all but the arguments
924 fun get_function_arguments(function: Text): String
926 var buf = new FlatBuffer
927 var trigger_copy = false
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
938 #######################################################################
939 ## Alias management functions ##
940 #######################################################################
942 # Adds a new alias to the tables
943 fun add_alias(var_represented: String, alias: String)
945 self.aliases[alias] = var_represented
948 # Gets the real name of a variable hidden by an alias
949 fun get_variable_name_by_alias(alias: String): nullable String
951 if self.aliases.keys.has(alias) then
952 return self.aliases[alias]
958 # Gets the variable named by name, whether it is an alias or not
959 fun get_real_variable_name(name: String): String
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))
968 final_string.append(i)
970 final_string.append(".")
973 return final_string.substring(0,final_string.length-1).to_s
976 #######################################################################
977 ## Print functions ##
978 #######################################################################
980 # Prints an object instance and its attributes if it has some
982 # If it is a primitive type, its value is directly printed
983 fun print_instance(instance: Instance)
985 if instance isa MutableInstance then
987 print "\ttype : {instance},"
991 print instance.attributes.join(",\n\t"," : ")
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)
1003 var collection: nullable SequenceRead[Object] = null
1004 var real_collection_length: nullable Int = null
1006 if instance isa MutableInstance then
1007 real_collection_length = get_collection_instance_real_length(instance)
1008 collection = get_primary_collection(instance)
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]}"
1017 var item_i = collection[i]
1019 if item_i isa MutableInstance then
1020 print_nested_collection(item_i, indexes, depth+1, variable_name, depth_string+"[{i}]")
1022 print "The item at {variable_name}{depth_string}[{i}] is not a collection"
1027 print "Out of bounds exception : i = {i} and collection_length = {real_collection_length.to_s}"
1031 else if i >= real_collection_length then
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}"
1042 print "Unknown error."
1048 #######################################################################
1049 ## Variable Exploration functions ##
1050 #######################################################################
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
1055 var full_variable = variable_path.split_with(".")
1057 var full_variable_iterator = full_variable.iterator
1059 var first_instance = get_variable_in_frame(full_variable_iterator.item, frame)
1061 if first_instance == null then return null
1063 if full_variable.length <= 1 then return first_instance
1065 full_variable_iterator.next
1067 if not (first_instance isa MutableInstance and full_variable_iterator.is_ok) then return null
1069 return get_variable_in_mutable_instance(first_instance, full_variable_iterator)
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
1075 if variable_name == "self" then
1076 if frame.arguments.length >= 1 then return frame.arguments.first
1079 var map_of_instances = frame.map
1081 for key in map_of_instances.keys do
1082 if key.to_s == variable_name then
1083 return map_of_instances[key]
1090 # Gets an attribute 'attribute_name
' contained in variable 'variable
'
1091 fun get_attribute_in_mutable_instance(variable: MutableInstance, attribute_name: String): nullable MAttribute
1093 var map_of_attributes = variable.attributes
1095 for key in map_of_attributes.keys do
1096 if key.to_s.substring_from(1) == attribute_name then
1104 # Recursive function, returns the variable described by 'total_chain
'
1105 fun get_variable_in_mutable_instance(variable: MutableInstance, iterator: Iterator[String]): nullable Instance
1107 var attribute = get_attribute_in_mutable_instance(variable, iterator.item)
1109 if attribute == null then return null
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)
1121 return variable.attributes[attribute]
1125 #######################################################################
1126 ## Array exploring functions ##
1127 #######################################################################
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
1133 var collection_length_attribute = get_attribute_in_mutable_instance(collection, "length")
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
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]
1149 var from_end_index = index_string.chars.index_of('.')
1150 var to_start_index = index_string.chars.last_index_of('.')
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)
1156 if index_from_string.is_numeric and index_to_string.is_numeric then
1157 var result_array = new Array[Int]
1159 var index_from = index_from_string.to_i
1160 var index_to = index_to_string.to_i
1162 for i in [index_from..index_to] do
1163 result_array.push(i)
1169 if index_string.is_numeric
1171 var result_array = new Array[Int]
1173 result_array.push(index_string.to_i)
1184 # Gets a collection in a MutableInstance
1185 fun get_primary_collection(container: MutableInstance): nullable SequenceRead[Object]
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]
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
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]
1206 var buffer = new FlatBuffer
1208 var result_array = new Array[String]
1210 var number_of_opening_brackets = 0
1211 var number_of_closing_brackets = 0
1213 var last_was_opening_bracket = false
1215 for i in braces.chars do
1217 if last_was_opening_bracket then
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
1228 result_array.push(buffer.to_s)
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
1239 if number_of_opening_brackets != number_of_closing_brackets then
1246 #######################################################################
1247 ## Breakpoint placing functions ##
1248 #######################################################################
1250 # Places a breakpoint on line 'line_to_break
' for file 'file_to_break
'
1251 fun place_breakpoint(breakpoint: Breakpoint)
1253 if not self.breakpoints.keys.has(breakpoint.file) then
1254 self.breakpoints[breakpoint.file] = new HashSet[Breakpoint]
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}"
1260 print "Breakpoint already present on line {breakpoint.line} for file {breakpoint.file}"
1264 #######################################################################
1265 ## Breakpoint removing functions ##
1266 #######################################################################
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)
1271 if self.breakpoints.keys.has(file_to_break) then
1272 var bp = find_breakpoint(file_to_break, line_to_break)
1275 self.breakpoints[file_to_break].remove(bp)
1276 print "Breakpoint removed on line {line_to_break} for file {file_to_break}"
1281 print "No breakpoint existing on line {line_to_break} for file {file_to_break}"
1284 #######################################################################
1285 ## Breakpoint searching functions ##
1286 #######################################################################
1288 # Finds a breakpoint for 'file
' and 'line
' in the class HashMap
1289 fun find_breakpoint(file: String, line: Int): nullable Breakpoint
1291 if self.breakpoints.keys.has(file)
1293 for i in self.breakpoints[file]
1305 #######################################################################
1306 ## Runtime modification functions ##
1307 #######################################################################
1309 # Modifies the value of a variable contained in a frame
1310 fun modify_in_frame(variable: Instance, value: String)
1312 var new_variable = get_variable_of_type_with_value(variable.mtype.to_s, value)
1313 if new_variable != null
1315 var keys = frame.map.keys
1318 if frame.map[key] == variable
1320 frame.map[key] = new_variable
1326 # Modifies the value of a variable contained in a MutableInstance
1327 fun modify_argument_of_complex_type(papa: MutableInstance, attribute: MAttribute, value: String)
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
1334 papa.attributes[attribute] = new_variable
1338 #######################################################################
1339 ## Variable generator functions ##
1340 #######################################################################
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
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)
1358 # Returns a new int instance with value 'value
'
1359 fun get_int(value: String): nullable Instance
1361 if value.is_numeric then
1362 return int_instance(value.to_i)
1368 # Returns a new float instance with value 'value
'
1369 fun get_float(value:String): nullable Instance
1371 if value.is_numeric then
1372 return float_instance(value.to_f)
1378 # Returns a new char instance with value 'value
'
1379 fun get_char(value: String): nullable Instance
1381 if value.length >= 1 then
1382 return char_instance(value.chars[0])
1388 # Returns a new bool instance with value 'value
'
1389 fun get_bool(value: String): nullable Instance
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
1396 print "Invalid value, a boolean must be set at \"true\" or \"false\""
1403 redef class AMethPropdef
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
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]
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]
1421 if v.returnmark == f then
1423 var res = v.escapevalue
1424 v.escapevalue = null
1432 # Traces the modifications of an object linked to a certain frame
1433 private class TraceObject
1435 # Map of the local names bound to a frame
1436 var trace_map = new HashMap[Frame, String]
1438 # Decides if breaking or printing statement when the variable is encountered
1439 var break_on_encounter: Bool
1441 # Adds the local alias for a variable and the frame bound to it
1442 fun add_frame_variable(frame: Frame, variable_name: String)
1444 self.trace_map[frame] = variable_name
1447 # Checks if the prompted variable is traced in the specified frame
1448 fun is_variable_traced_in_frame(variable_name: String, frame: Frame): Bool
1450 if self.trace_map.has_key(frame) then
1451 if self.trace_map[frame] == variable_name then
1463 # Breaks automatically when encountering an error
1464 # Permits the injunction of commands before crashing
1465 redef fun fatal(v: NaiveInterpreter, message: String)
1467 if v isa Debugger then
1468 print "An error was encountered, the program will stop now."
1470 while v.process_debug_command(gets) do end