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 node
= modelbuilder
.mpropdef2node
(mpropdef
)
284 if node
isa AMethPropdef then
285 self.parameter_check
(node
, mpropdef
, args
)
286 return node
.rt_call
(self, mpropdef
, args
)
287 else if node
isa AClassdef then
288 self.parameter_check
(node
, mpropdef
, args
)
289 return node
.call
(self, mpropdef
, args
)
291 fatal
("Fatal Error: method {mpropdef} not found in the AST")
296 # Evaluates dynamically a snippet of Nit code
297 # `nit_code` : Nit code to be executed
298 fun eval
(nit_code
: String)
300 var local_toolctx
= modelbuilder
.toolcontext
301 local_toolctx
.dbg
= self
302 var e
= local_toolctx
.parse_something
(nit_code
)
303 if e
isa ABlockExpr then
304 nit_code
= "module rt_module\n" + nit_code
305 e
= local_toolctx
.parse_something
(nit_code
)
308 nit_code
= "module rt_module\nprint " + nit_code
309 e
= local_toolctx
.parse_something
(nit_code
)
311 if e
isa AModule then
312 local_toolctx
.had_error
= false
313 modelbuilder
.load_rt_module
(self.mainmodule
, e
, "rt_module")
314 local_toolctx
.run_phases
([e
])
315 if local_toolctx
.had_error
then
316 modelbuilder
.model
.try_remove_module
(e
.mmodule
.as(not null))
317 local_toolctx
.dbg
= null
322 self.mainmodule
= mmod
323 var sys_type
= mmod
.sys_type
324 if sys_type
== null then
325 print
"Fatal error, cannot find Class Sys !\nAborting"
328 var mobj
= new MutableInstance(sys_type
)
330 var initprop
= mmod
.try_get_primitive_method
("init", sys_type
.mclass
)
331 if initprop
!= null then
332 self.send
(initprop
, [mobj
])
334 var mainprop
= mmod
.try_get_primitive_method
("run", sys_type
.mclass
) or else
335 mmod
.try_get_primitive_method
("main", sys_type
.mclass
)
336 if mainprop
!= null then
337 self.rt_send
(mainprop
, [mobj
])
340 print
"Error while loading_rt_module"
343 print
"Error when parsing, e = {e.class_name}"
345 local_toolctx
.dbg
= null
348 # Encpasulates the behaviour for step over/out
349 private fun steps_fun_call
(n
: AExpr)
351 if self.stop_after_step_over_trigger
then
352 if self.frames
.length
<= self.step_stack_count
then
353 n
.debug
("Execute stmt {n.to_s}")
354 while read_cmd
do end
356 else if self.stop_after_step_out_trigger
then
357 if frames
.length
< self.step_stack_count
then
358 n
.debug
("Execute stmt {n.to_s}")
359 while read_cmd
do end
361 else if step_in_trigger
then
362 n
.debug
("Execute stmt {n.to_s}")
363 while read_cmd
do end
367 # Checks if a breakpoint is encountered, and launches the debugging prompt if true
368 private fun breakpoint_check
(n
: AExpr)
370 var currFileNameSplit
= self.frame
.current_node
.location
.file
.filename
.to_s
.split_with
("/")
372 self.curr_file
= currFileNameSplit
[currFileNameSplit
.length-1
]
374 var breakpoint
= find_breakpoint
(curr_file
, n
.location
.line_start
)
376 if breakpoints
.keys
.has
(curr_file
) and breakpoint
!= null then
377 n
.debug
("Execute stmt {n.to_s}")
378 while read_cmd
do end
382 # Check if a variable of current expression is traced
383 # Then prints and/or breaks for command prompt
384 private fun check_if_vars_are_traced
(n
: AExpr)
386 var identifiers_in_instruction
= get_identifiers_in_current_instruction
(n
.location
.text
)
388 for i
in identifiers_in_instruction
do
389 for j
in self.traces
do
390 if j
.is_variable_traced_in_frame
(i
, frame
) then
391 n
.debug
("Traced variable {i} used")
392 if j
.break_on_encounter
then while read_cmd
do end
399 # Function remapping all the traced objects to match their name in the local context
400 private fun remap
(n
: AExpr)
402 if self.aftermath
then
404 # Trace every argument variable pre-specified
405 if self.frame_count_aftermath
< frames
.length
and fun_call_arguments_positions
.length
> 0 then
407 var ids_in_fun_def
= get_identifiers_in_current_instruction
(get_function_arguments
(frame
.mpropdef
.location
.text
))
409 for i
in fun_call_arguments_positions
.keys
do
410 self.fun_call_arguments_positions
[i
].add_frame_variable
(frame
, ids_in_fun_def
[i
])
414 self.aftermath
= false
418 # If the current instruction is a function call
419 # We analyse its signature and the position of traced arguments if the call
420 # For future remapping when inside the function
421 private fun check_funcall_and_traced_args
(n
: AExpr) do
422 # If we have a function call, we need to see if any of the arguments is traced (including the caller)
423 # if it is, next time we face an instruction, we'll trace the local version on the traced variable in the next frame
424 if n
isa ACallExpr then
425 self.aftermath
= true
426 self.frame_count_aftermath
= frames
.length
427 fun_call_arguments_positions
.clear
428 var fun_arguments
= get_identifiers_in_current_instruction
(get_function_arguments
(n
.location
.text
))
430 for i
in self.traces
do
431 for j
in [0 .. fun_arguments
.length
- 1] do
432 if i
.is_variable_traced_in_frame
(fun_arguments
[j
],frame
) then
433 fun_call_arguments_positions
[j
] = i
440 #######################################################################
441 ## Processing commands functions ##
442 #######################################################################
447 return process_debug_command
(gets
)
450 # Takes a user command as a parameter
452 # Returns a boolean value, representing whether or not to
453 # continue reading commands from the console input
454 fun process_debug_command
(command
: String): Bool
457 if command
== "finish"
461 else if command
== "s"
465 else if command
== "n" then
468 else if command
== "help" then
471 # Opens a new NitIndex prompt on current model
472 else if command
== "nitx" then
473 new NitIndex.with_infos
(modelbuilder
, self.mainmodule
).prompt
475 else if command
== "bt" or command
== "backtrack" then
478 # Continues execution until the end
479 else if command
== "c" then
481 else if command
== "nit" then
484 var nit_buf
= new FlatBuffer
485 while not command
== ":q" do
486 nit_buf
.append
(command
)
493 else if command
== "quit" then
495 else if command
== "abort" then
499 var parts
= command
.split_with
(' ')
500 var cname
= parts
.first
501 # Shows the value of a variable in the current frame
502 if cname
== "p" or cname
== "print" then
504 # Places a breakpoint on line x of file y
505 else if cname
== "break" or cname
== "b" then
506 process_place_break_fun
(parts
)
507 # Removes a breakpoint on line x of file y
508 else if cname
== "d" or cname
== "delete" then
509 process_remove_break_fun
(parts
)
510 # Sets an alias for a variable
511 else if parts
.length
== 2 and parts
[1] == "as" then
513 # Modifies the value of a variable in the current frame
514 else if parts
.length
== 3 and parts
[1] == "=" then
515 process_mod_function
(parts
)
516 # Traces the modifications on a variable
517 else if cname
== "trace" then
518 process_trace_command
(parts
)
519 # Untraces the modifications on a variable
520 else if cname
== "untrace" then
521 process_untrace_command
(parts
)
529 # Produces help for the commands of the debugger
533 print
"-----------------------------------"
536 print
" * Modification: var_name = value (Warning: var_name must be primitive)"
537 print
" * Alias: var_name as alias"
540 print
" * Variables: p(rint) var_name (Use * to print all local variables)"
541 print
" * Collections: p(rint) var_name '[' start_index (.. end_index) ']'"
544 print
" * File/line: b(reak) file_name line_number"
545 print
" * Remove: d(elete) id"
548 print
" * Variable: trace var_name break/print"
549 print
" * Untrace variable: untrace var_name"
552 print
" * Next instruction (same-level): n"
553 print
" * Next instruction: s"
554 print
" * Finish current method: finish"
555 print
" * Continue until next breakpoint or end: c"
557 print
"General commands"
558 print
" * quit: Quits the debugger"
559 print
" * abort: Aborts the interpretation, prints the stack trace before leaving"
560 print
" * nitx: Ask questions to the model about its entities (classes, methods, etc.)"
561 print
" * nit: Inject dynamic code for interpretation"
565 #######################################################################
566 ## Processing specific command functions ##
567 #######################################################################
569 # Sets the flags to step-over an instruction in the current file
572 self.step_stack_count
= frames
.length
573 self.stop_after_step_over_trigger
= true
574 self.stop_after_step_out_trigger
= false
575 self.step_in_trigger
= false
579 #Sets the flags to step-out of a function
582 self.stop_after_step_over_trigger
= false
583 self.stop_after_step_out_trigger
= true
584 self.step_in_trigger
= false
585 self.step_stack_count
= frames
.length
589 # Sets the flags to step-in an instruction
592 self.step_in_trigger
= true
593 self.stop_after_step_over_trigger
= false
594 self.stop_after_step_out_trigger
= false
598 # Sets the flags to continue execution
599 fun continue_exec
: Bool
601 self.stop_after_step_over_trigger
= false
602 self.stop_after_step_out_trigger
= false
603 self.step_in_trigger
= false
607 fun bad_command
(cmd
: String) do
608 print
"Unrecognized command {cmd}. Use 'help' to show help."
611 # Prints the demanded variable in the command
613 # The name of the variable in in position 1 of the array 'parts_of_command'
614 fun print_command
(parts
: Array[String])
616 if parts
.length
!= 2 then
617 bad_command
(parts
.join
(" "))
620 if parts
[1] == "*" then
621 var map_of_instances
= frame
.map
623 var self_var
= seek_variable
("self", frame
)
624 print
"self: {self_var.to_s}"
626 for instance
in map_of_instances
.keys
do
627 print
"{instance.to_s}: {map_of_instances[instance].to_s}"
629 else if parts
[1].chars
.has
('[') and parts
[1].chars
.has
(']') then
630 process_array_command
(parts
)
632 var instance
= seek_variable
(get_real_variable_name
(parts
[1]), frame
)
636 print_instance
(instance
)
638 print
"Cannot find variable {parts[1]}"
643 # Process the input command to set an alias for a variable
644 fun process_alias
(parts
: Array[String]) do
645 if parts
.length
!= 3 then
646 bad_command
(parts
.join
(" "))
649 add_alias
(parts
.first
, parts
.last
)
652 # Processes the input string to know where to put a breakpoint
653 fun process_place_break_fun
(parts
: Array[String])
655 if parts
.length
!= 3 then
656 bad_command
(parts
.join
(" "))
659 var bp
= get_breakpoint_from_command
(parts
)
665 # Returns a breakpoint containing the informations stored in the command
666 fun get_breakpoint_from_command
(parts
: Array[String]): nullable Breakpoint
668 if parts
[1].is_numeric
then
669 return new Breakpoint(parts
[1].to_i
, curr_file
)
670 else if parts
.length
>= 3 and parts
[2].is_numeric
then
671 return new Breakpoint(parts
[2].to_i
, parts
[1])
677 # Processes the command of removing a breakpoint on specified line and file
678 fun process_remove_break_fun
(parts
: Array[String])
680 if parts
.length
!= 2 then
681 bad_command
(parts
.join
(" "))
684 if parts
[1].is_numeric
then
685 remove_breakpoint
(self.curr_file
, parts
[1].to_i
)
686 else if parts
.length
>= 3 and parts
[2].is_numeric
then
687 remove_breakpoint
(parts
[1], parts
[2].to_i
)
691 # Processes an array print command
692 fun process_array_command
(parts
: Array[String])
694 var index_of_first_brace
= parts
[1].chars
.index_of
('[')
695 var variable_name
= get_real_variable_name
(parts
[1].substring
(0,index_of_first_brace
))
696 var braces
= parts
[1].substring_from
(index_of_first_brace
)
698 var indexes
= remove_braces
(braces
)
700 var index_array
= new Array[Array[Int]]
702 if indexes
!= null then
703 for index
in indexes
do
704 var temp_indexes_array
= process_index
(index
)
705 if temp_indexes_array
!= null then
706 index_array
.push
(temp_indexes_array
)
707 #print index_array.last
712 var instance
= seek_variable
(variable_name
, frame
)
714 if instance
!= null then
715 print_nested_collection
(instance
, index_array
, 0, variable_name
, "")
717 print
"Cannot find variable {variable_name}"
721 # Processes the modification function to modify a variable dynamically
723 # Command of type variable = value
724 fun process_mod_function
(parts
: Array[String])
726 if parts
.length
!= 3 then
727 bad_command
(parts
.join
(" "))
731 p0
= get_real_variable_name
(p0
)
732 var parts_of_variable
= p0
.split_with
(".")
734 if parts_of_variable
.length
> 1 then
735 var last_part
= parts_of_variable
.pop
736 var first_part
= p0
.substring
(0,p0
.length
- last_part
.length
- 1)
737 var papa
= seek_variable
(first_part
, frame
)
739 if papa
!= null and papa
isa MutableInstance then
740 var attribute
= get_attribute_in_mutable_instance
(papa
, last_part
)
742 if attribute
!= null then
743 modify_argument_of_complex_type
(papa
, attribute
, parts
[2])
747 var target
= seek_variable
(parts_of_variable
[0], frame
)
748 if target
!= null then
749 modify_in_frame
(target
, parts
[2])
754 # Processes the untrace variable command
756 # Command pattern : "untrace variable"
757 fun process_untrace_command
(parts
: Array[String])
759 if parts
.length
!= 2 then
760 bad_command
(parts
.join
(" "))
763 var variable_name
= get_real_variable_name
(parts
[1])
764 if untrace_variable
(variable_name
) then
765 print
"Untraced variable {parts[1]}"
767 print
"{parts[1]} is not traced"
771 # Processes the trace variable command
773 # Command pattern : "trace variable [break/print]"
774 fun process_trace_command
(parts
: Array[String])
776 if parts
.length
!= 3 then
777 bad_command
(parts
.join
(" "))
780 var variable_name
= get_real_variable_name
(parts
[1])
783 if seek_variable
(variable_name
, frame
) == null then
784 print
"Cannot find a variable called {parts[1]}"
788 if parts
[2] == "break" then
794 trace_variable
(variable_name
, breaker
)
796 print
"Successfully tracing {parts[1]}"
799 #######################################################################
800 ## Trace Management functions ##
801 #######################################################################
803 # Effectively untraces the variable called *variable_name*
805 # Returns true if the variable exists, false otherwise
806 private fun untrace_variable
(variable_name
: String): Bool
808 var to_remove
: nullable TraceObject = null
809 for i
in self.traces
do
810 if i
.is_variable_traced_in_frame
(variable_name
, frame
) then
815 if to_remove
!= null then
816 self.traces
.remove
(to_remove
)
823 # Effectively traces the variable *variable_name* either in print or break mode depending on the value of breaker (break if true, print if false)
825 private fun trace_variable
(variable_name
: String, breaker
: Bool)
827 for i
in self.traces
do
828 if i
.is_variable_traced_in_frame
(variable_name
, frame
) then
829 print
"This variable is already traced"
834 var trace_object
: TraceObject
837 trace_object
= new TraceObject(true)
839 trace_object
= new TraceObject(false)
842 # We trace the current variable found for the current frame
843 trace_object
.add_frame_variable
(self.frame
, variable_name
)
845 var position_of_variable_in_arguments
= get_position_of_variable_in_arguments
(frame
, variable_name
)
847 # Start parsing the frames starting with the parent of the current one, until the highest
848 # When the variable traced is declared locally, the loop stops
849 for i
in [1 .. frames
.length-1
] do
851 # If the variable was reported to be an argument of the previous frame
852 if position_of_variable_in_arguments
!= -1 then
854 var local_name
= get_identifiers_in_current_instruction
(get_function_arguments
(frames
[i
].current_node
.location
.text
))[position_of_variable_in_arguments
]
856 position_of_variable_in_arguments
= get_position_of_variable_in_arguments
(frames
[i
], local_name
)
858 trace_object
.add_frame_variable
(frames
[i
], local_name
)
864 self.traces
.add
(trace_object
)
867 # If the variable *variable_name* is an argument of the function being executed in the frame *frame*
868 # The function returns its position in the arguments
869 # Else, it returns -1
870 private fun get_position_of_variable_in_arguments
(frame
: Frame, variable_name
: String): Int
872 var identifiers
= get_identifiers_in_current_instruction
(get_function_arguments
(frame
.mpropdef
.location
.text
))
873 for i
in [0 .. identifiers
.length-1
] do
874 # If the current traced variable is an argument of the current function, we trace its parent (at least)
875 if identifiers
[i
] == variable_name
then return i
880 # Gets all the identifiers of an instruction (uses the rules of Nit as of Mar 05 2013)
882 fun get_identifiers_in_current_instruction
(instruction
: Text): Array[String]
884 var result_array
= new Array[String]
885 var instruction_buffer
= new FlatBuffer
887 var trigger_char_escape
= false
888 var trigger_string_escape
= false
890 for i
in instruction
.chars
do
891 if trigger_char_escape
then
892 if i
== '\'' then trigger_char_escape = false
893 else if trigger_string_escape then
895 trigger_string_escape = false
896 else if i == '\
"' then trigger_string_escape = false
898 if i.is_alphanumeric or i == '_' then
899 instruction_buffer.add(i)
900 else if i == '.' then
901 if instruction_buffer.is_numeric or (instruction_buffer.chars[0] >= 'A' and instruction_buffer.chars[0] <= 'Z') then
902 instruction_buffer.clear
904 result_array.push(instruction_buffer.to_s)
905 instruction_buffer.add(i)
907 else if i == '\'' then
908 trigger_char_escape = true
909 else if i == '\"' then
910 trigger_string_escape = true
911 else if i == '}' then
912 trigger_string_escape = true
914 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)
915 instruction_buffer.clear
920 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)
925 # Takes a function call or declaration and strips all but the arguments
927 fun get_function_arguments(function: Text): String
929 var buf = new FlatBuffer
930 var trigger_copy = false
932 for i in function.chars do
933 if i == ')' then break
934 if trigger_copy then buf.add(i)
935 if i == '(' then trigger_copy = true
941 #######################################################################
942 ## Alias management functions ##
943 #######################################################################
945 # Adds a new alias to the tables
946 fun add_alias(var_represented: String, alias: String)
948 self.aliases[alias] = var_represented
951 # Gets the real name of a variable hidden by an alias
952 fun get_variable_name_by_alias(alias: String): nullable String
954 if self.aliases.keys.has(alias) then
955 return self.aliases[alias]
961 # Gets the variable named by name, whether it is an alias or not
962 fun get_real_variable_name(name: String): String
964 var explode_string = name.split_with(".")
965 var final_string = new FlatBuffer
966 for i in explode_string do
967 var alias_resolved = get_variable_name_by_alias(i)
968 if alias_resolved != null then
969 final_string.append(get_real_variable_name(alias_resolved))
971 final_string.append(i)
973 final_string.append(".")
976 return final_string.substring(0,final_string.length-1).to_s
979 #######################################################################
980 ## Print functions ##
981 #######################################################################
983 # Prints an object instance and its attributes if it has some
985 # If it is a primitive type, its value is directly printed
986 fun print_instance(instance: Instance)
988 if instance isa MutableInstance then
990 print "\ttype : {instance},"
994 print instance.attributes.join(",\n\t"," : ")
1002 # Prints the attributes demanded in a SequenceRead
1003 # Used recursively to print nested collections
1004 fun print_nested_collection(instance: Instance, indexes: Array[Array[Int]], depth: Int, variable_name: String, depth_string: String)
1006 var collection: nullable SequenceRead[Object] = null
1007 var real_collection_length: nullable Int = null
1009 if instance isa MutableInstance then
1010 real_collection_length = get_collection_instance_real_length(instance)
1011 collection = get_primary_collection(instance)
1014 if collection != null and real_collection_length != null then
1015 for i in indexes[depth] do
1016 if i >= 0 and i < real_collection_length then
1017 if depth == indexes.length-1 then
1018 print "{variable_name}{depth_string}[{i}] = {collection[i]}"
1020 var item_i = collection[i]
1022 if item_i isa MutableInstance then
1023 print_nested_collection(item_i, indexes, depth+1, variable_name, depth_string+"[{i}]")
1025 print "The item at {variable_name}{depth_string}[{i}] is not a collection"
1030 print "Out of bounds exception : i = {i} and collection_length = {real_collection_length.to_s}"
1034 else if i >= real_collection_length then
1040 if collection == null then
1041 print "Cannot find {variable_name}{depth_string}"
1042 else if real_collection_length != null then
1043 print "Cannot find attribute length in {instance}"
1045 print "Unknown error."
1051 #######################################################################
1052 ## Variable Exploration functions ##
1053 #######################################################################
1055 # Seeks a variable from the current frame called 'variable_path
', can introspect complex objects using function get_variable_in_mutable_instance
1056 private fun seek_variable(variable_path: String, frame: Frame): nullable Instance
1058 var full_variable = variable_path.split_with(".")
1060 var full_variable_iterator = full_variable.iterator
1062 var first_instance = get_variable_in_frame(full_variable_iterator.item, frame)
1064 if first_instance == null then return null
1066 if full_variable.length <= 1 then return first_instance
1068 full_variable_iterator.next
1070 if not (first_instance isa MutableInstance and full_variable_iterator.is_ok) then return null
1072 return get_variable_in_mutable_instance(first_instance, full_variable_iterator)
1075 # Gets a variable 'variable_name
' contained in the frame 'frame
'
1076 private fun get_variable_in_frame(variable_name: String, frame: Frame): nullable Instance
1078 if variable_name == "self" then
1079 if frame.arguments.length >= 1 then return frame.arguments.first
1082 var map_of_instances = frame.map
1084 for key in map_of_instances.keys do
1085 if key.to_s == variable_name then
1086 return map_of_instances[key]
1093 # Gets an attribute 'attribute_name
' contained in variable 'variable
'
1094 fun get_attribute_in_mutable_instance(variable: MutableInstance, attribute_name: String): nullable MAttribute
1096 var map_of_attributes = variable.attributes
1098 for key in map_of_attributes.keys do
1099 if key.to_s.substring_from(1) == attribute_name then
1107 # Recursive function, returns the variable described by 'total_chain
'
1108 fun get_variable_in_mutable_instance(variable: MutableInstance, iterator: Iterator[String]): nullable Instance
1110 var attribute = get_attribute_in_mutable_instance(variable, iterator.item)
1112 if attribute == null then return null
1116 if iterator.is_ok then
1117 var new_variable = variable.attributes[attribute]
1118 if new_variable isa MutableInstance then
1119 return get_variable_in_mutable_instance(new_variable, iterator)
1124 return variable.attributes[attribute]
1128 #######################################################################
1129 ## Array exploring functions ##
1130 #######################################################################
1132 # Gets the length of a collection
1133 # Used by the debugger, else if we call Collection.length, it returns the capacity instead
1134 fun get_collection_instance_real_length(collection: MutableInstance): nullable Int
1136 var collection_length_attribute = get_attribute_in_mutable_instance(collection, "length")
1138 if collection_length_attribute != null then
1139 var primitive_length_instance = collection.attributes[collection_length_attribute]
1140 if primitive_length_instance isa PrimitiveInstance[Int] then
1141 return primitive_length_instance.val
1148 # Processes the indexes of a print array call
1149 # Returns an array containing all the indexes demanded
1150 fun process_index(index_string: String): nullable Array[Int]
1152 var from_end_index = index_string.chars.index_of('.')
1153 var to_start_index = index_string.chars.last_index_of('.')
1155 if from_end_index != -1 and to_start_index != -1 then
1156 var index_from_string = index_string.substring(0,from_end_index)
1157 var index_to_string = index_string.substring_from(to_start_index+1)
1159 if index_from_string.is_numeric and index_to_string.is_numeric then
1160 var result_array = new Array[Int]
1162 var index_from = index_from_string.to_i
1163 var index_to = index_to_string.to_i
1165 for i in [index_from..index_to] do
1166 result_array.push(i)
1172 if index_string.is_numeric
1174 var result_array = new Array[Int]
1176 result_array.push(index_string.to_i)
1187 # Gets a collection in a MutableInstance
1188 fun get_primary_collection(container: MutableInstance): nullable SequenceRead[Object]
1190 var items_of_array = get_attribute_in_mutable_instance(container, "items")
1191 if items_of_array != null then
1192 var array = container.attributes[items_of_array]
1194 if array isa PrimitiveInstance[Object] then
1195 var sequenceRead_final = array.val
1196 if sequenceRead_final isa SequenceRead[Object] then
1197 return sequenceRead_final
1205 # Removes the braces '[' ']' in a print array command
1206 # Returns an array containing their content
1207 fun remove_braces(braces: String): nullable Array[String]
1209 var buffer = new FlatBuffer
1211 var result_array = new Array[String]
1213 var number_of_opening_brackets = 0
1214 var number_of_closing_brackets = 0
1216 var last_was_opening_bracket = false
1218 for i in braces.chars do
1220 if last_was_opening_bracket then
1224 number_of_opening_brackets += 1
1225 last_was_opening_bracket = true
1226 else if i == ']' then
1227 if not last_was_opening_bracket then
1231 result_array.push(buffer.to_s)
1233 number_of_closing_brackets += 1
1234 last_was_opening_bracket = false
1235 else if i.is_numeric or i == '.' then
1236 buffer.append(i.to_s)
1237 else if not i == ' ' then
1242 if number_of_opening_brackets != number_of_closing_brackets then
1249 #######################################################################
1250 ## Breakpoint placing functions ##
1251 #######################################################################
1253 # Places a breakpoint on line 'line_to_break
' for file 'file_to_break
'
1254 fun place_breakpoint(breakpoint: Breakpoint)
1256 if not self.breakpoints.keys.has(breakpoint.file) then
1257 self.breakpoints[breakpoint.file] = new HashSet[Breakpoint]
1259 if find_breakpoint(breakpoint.file, breakpoint.line) == null then
1260 self.breakpoints[breakpoint.file].add(breakpoint)
1261 print "Breakpoint added on line {breakpoint.line} for file {breakpoint.file}"
1263 print "Breakpoint already present on line {breakpoint.line} for file {breakpoint.file}"
1267 #######################################################################
1268 ## Breakpoint removing functions ##
1269 #######################################################################
1271 # Removes a breakpoint on line 'line_to_break
' for file 'file_to_break
'
1272 fun remove_breakpoint(file_to_break: String, line_to_break: Int)
1274 if self.breakpoints.keys.has(file_to_break) then
1275 var bp = find_breakpoint(file_to_break, line_to_break)
1278 self.breakpoints[file_to_break].remove(bp)
1279 print "Breakpoint removed on line {line_to_break} for file {file_to_break}"
1284 print "No breakpoint existing on line {line_to_break} for file {file_to_break}"
1287 #######################################################################
1288 ## Breakpoint searching functions ##
1289 #######################################################################
1291 # Finds a breakpoint for 'file
' and 'line
' in the class HashMap
1292 fun find_breakpoint(file: String, line: Int): nullable Breakpoint
1294 if self.breakpoints.keys.has(file)
1296 for i in self.breakpoints[file]
1308 #######################################################################
1309 ## Runtime modification functions ##
1310 #######################################################################
1312 # Modifies the value of a variable contained in a frame
1313 fun modify_in_frame(variable: Instance, value: String)
1315 var new_variable = get_variable_of_type_with_value(variable.mtype.to_s, value)
1316 if new_variable != null
1318 var keys = frame.map.keys
1321 if frame.map[key] == variable
1323 frame.map[key] = new_variable
1329 # Modifies the value of a variable contained in a MutableInstance
1330 fun modify_argument_of_complex_type(papa: MutableInstance, attribute: MAttribute, value: String)
1332 var final_variable = papa.attributes[attribute]
1333 var type_of_variable = final_variable.mtype.to_s
1334 var new_variable = get_variable_of_type_with_value(type_of_variable, value)
1335 if new_variable != null
1337 papa.attributes[attribute] = new_variable
1341 #######################################################################
1342 ## Variable generator functions ##
1343 #######################################################################
1345 # Returns a new variable of the type 'type_of_variable
' with a value of 'value
'
1346 fun get_variable_of_type_with_value(type_of_variable: String, value: String): nullable Instance
1348 if type_of_variable == "Int" then
1349 return get_int(value)
1350 else if type_of_variable == "Float" then
1351 return get_float(value)
1352 else if type_of_variable == "Bool" then
1353 return get_bool(value)
1354 else if type_of_variable == "Char" then
1355 return get_char(value)
1361 # Returns a new int instance with value 'value
'
1362 fun get_int(value: String): nullable Instance
1364 if value.is_numeric then
1365 return int_instance(value.to_i)
1371 # Returns a new float instance with value 'value
'
1372 fun get_float(value:String): nullable Instance
1374 if value.is_numeric then
1375 return float_instance(value.to_f)
1381 # Returns a new char instance with value 'value
'
1382 fun get_char(value: String): nullable Instance
1384 if value.length >= 1 then
1385 return char_instance(value.chars[0])
1391 # Returns a new bool instance with value 'value
'
1392 fun get_bool(value: String): nullable Instance
1394 if value.to_lower == "true" then
1395 return self.true_instance
1396 else if value.to_lower == "false" then
1397 return self.false_instance
1399 print "Invalid value, a boolean must be set at \"true\" or \"false\""
1406 redef class AMethPropdef
1408 # Same as call except it will copy local variables of the parent frame to the frame defined in this call.
1409 # Not supposed to be used by anyone else than the Debugger.
1410 private fun rt_call(v: Debugger, mpropdef: MMethodDef, args: Array[Instance]): nullable Instance
1412 var f = new Frame(self, self.mpropdef.as(not null), args)
1413 var curr_instances = v.frame.map
1414 for i in curr_instances.keys do
1415 f.map[i] = curr_instances[i]
1417 call_commons(v,mpropdef,args,f)
1418 var currFra = v.frames.shift
1419 for i in curr_instances.keys do
1420 if currFra.map.keys.has(i) then
1421 curr_instances[i] = currFra.map[i]
1424 if v.returnmark == f then
1426 var res = v.escapevalue
1427 v.escapevalue = null
1435 # Traces the modifications of an object linked to a certain frame
1436 private class TraceObject
1438 # Map of the local names bound to a frame
1439 var trace_map = new HashMap[Frame, String]
1441 # Decides if breaking or printing statement when the variable is encountered
1442 var break_on_encounter: Bool
1444 # Adds the local alias for a variable and the frame bound to it
1445 fun add_frame_variable(frame: Frame, variable_name: String)
1447 self.trace_map[frame] = variable_name
1450 # Checks if the prompted variable is traced in the specified frame
1451 fun is_variable_traced_in_frame(variable_name: String, frame: Frame): Bool
1453 if self.trace_map.has_key(frame) then
1454 if self.trace_map[frame] == variable_name then
1466 # Breaks automatically when encountering an error
1467 # Permits the injunction of commands before crashing
1468 redef fun fatal(v: NaiveInterpreter, message: String)
1470 if v isa Debugger then
1471 print "An error was encountered, the program will stop now."
1473 while v.process_debug_command(gets) do end