Class: NCPP::REPL

Inherits:
Interpreter show all
Defined in:
lib/ncpp/interpreter.rb

Overview

A read–eval–print loop environment for testing/learning the language

Instance Method Summary collapse

Methods inherited from Interpreter

#call, #commands, #def_command, #def_variable, #eval_expr, #eval_str, #get_binding, #get_cacheable_cache, #get_command, #get_new_commands, #get_new_variables, #get_variable, #node_impure?, #unknown_command_error, #unknown_variable_error, #variables

Constructor Details

#initialize(cmd_prefix = COMMAND_PREFIX, extra_cmds = {}, extra_vars = {}, safe: false, puritan: false, no_cache: false, cmd_cache: {}) ⇒ REPL

Returns a new instance of REPL.



735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
# File 'lib/ncpp/interpreter.rb', line 735

def initialize(cmd_prefix = COMMAND_PREFIX, extra_cmds = {}, extra_vars = {}, safe: false, puritan: false,
               no_cache: false, cmd_cache: {})
  @EXTRA_CMDS, @EXTRA_VARS = extra_cmds, extra_vars
  super(cmd_prefix, extra_cmds, extra_vars, safe: safe, puritan: puritan, no_cache: no_cache, cmd_cache: cmd_cache)

  @running = true

  @commands.merge!({
    write: ->(x, filename)  {
      File.open(filename, "w") do |file|
        @out_stack << x unless x.nil?
        file.write(@out_stack.join("\n"))
        @out_stack.clear
        nil
      end
    }.impure
      .describe(
      "Writes the contents of the out-stack and the given argument to the file specified. " \
      "This command is unique to the REPL interpreter."
    ),

    embed: ->(filename, newline_steps=nil) {
      raise "File not found: #{filename}" unless File.exist? filename
      File.binread(filename).bytes.join(',')
    }.returns(String).impure
     .describe('Reads all bytes from the given file and joins them into a comma-separated String representation.'),

    embed_hex: ->(filename, newline_steps=nil) {
      raise "File not found: #{filename}" unless File.exist? filename
      bytes = File.binread(filename).bytes
      bytes.map! {|b| b.to_i.to_hex }.join(',')
    }.returns(String).impure
     .describe(
      'Reads all bytes from the given file and joins them as hex into a comma-separated String representation.'
    ),

    read: ->(filename) {
      raise "File not found: #{filename}" unless File.exist? filename
      File.read(filename)
    }.returns(String).impure
      .describe('Reads the file given and returns its contents as a String.'),

    read_lines: ->(filename) {
      raise "File not found: #{filename}" unless File.exist? filename
      File.readlines(filename)
    }.returns(Array).impure
      .describe('Reads the file specified and returns an Array containing each line.'),

    read_bytes: ->(filename) {
      raise "File not found: #{filename}" unless File.exist? filename
      File.binread(filename).bytes
    }.returns(Array).impure
      .describe('Reads the file specified and returns an Array containing each byte.'),

    import: ->(template_file, *arg_vals) {
      t_interpreter = CFileInterpreter.new(nil,nil,@COMMAND_PREFIX,@EXTRA_CMDS,@EXTRA_VARS,[*arg_vals])
      ret, _, t_args = t_interpreter.process_file(template_file)
      if t_args.length > 0
        puts "WARNING".underline_yellow + ': '.yellow + "#{t_args.length} template arg#{'s' if t_args.length != 1}"\
             "not used.".yellow
      end
      ret
    }.returns(String).impure
     .describe(
      "Takes a template file name and a value for each arg exported by the template. The template file is " \
      "processed by the interpreter, and the generated code is embedded into the current file."
    ),

     exit: -> { @running = false }.impure
      .describe('Exits the current REPL interpreter session. This command is specific to the REPL interpreter.')
  })

end

Instance Method Details

#run(debug: false) ⇒ Object



809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
# File 'lib/ncpp/interpreter.rb', line 809

def run(debug: false)
  loop do
    begin
      print '> '.purple; expr = STDIN.gets&.chomp&.strip
      next if expr.nil? || expr.empty?

      parsed_tree = @parser.parse(expr, root: :expression)
      puts "Parsed tree: #{parsed_tree.inspect}".blue if debug

      ast = @transformer.apply(parsed_tree)
      puts "Transf tree: #{ast.inspect}".blue if debug

      out = eval_expr(ast)

      @out_stack << out unless out.nil?
      output = @out_stack.join("\n")

      output = "#<struct NCPP::Block ..." if output.start_with?("#<struct NCPP::Block")

      puts output.cyan
      @out_stack.clear

      break unless @running

    rescue Interrupt # Ctrl+C on windows to exit
      break
    rescue Parslet::ParseFailed => e
      puts 'ERROR'.underline_red + ": #{e.parse_failure_cause.ascii_tree}".red
    rescue Exception => e
      puts 'ERROR'.underline_red + ": #{debug ? e.detailed_message : e.to_s }".red
    end
  end
end