Class: Nendo::Evaluator

Inherits:
Object
  • Object
show all
Includes:
BuiltinFunctions
Defined in:
lib/nendo/ruby/evaluator.rb,
lib/nendo/ruby/optimized_func.rb

Overview

Translate S expression to Ruby expression and Evaluation

Constant Summary collapse

EXEC_TYPE_NORMAL =
1
EXEC_TYPE_ANONYMOUS =
2
EXEC_TYPE_TAILCALL =
3
LINENO_TIMES =
100
INITIAL_LINENO =

header comment of compiled code

6

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from BuiltinFunctions

#__ASMARK, #__ASMARKFILE_ASMARK, #__ASMARKLINE_ASMARK, #__ASMARK_ARGS0, #__ASMARK_ARGS1, #__ASMARK_ARGS2, #__ASMARK_ARGS3, #__ASMARKruntime_MIMARKcheck_ASMARK, #__EQMARK, #__GTMARK, #__GTMARK_EQMARK, #__LTMARK, #__LTMARK_EQMARK, #__MIMARK, #__MIMARK_ARGS0, #__MIMARK_ARGS1, #__MIMARK_ARGS2, #__MIMARK_ARGS3, #__PAMARK, #__PAMARKlist_QUMARK, #__PAMARKraise, #__PLMARK, #__PLMARK_ARGS0, #__PLMARK_ARGS1, #__PLMARK_ARGS2, #__PLMARK_ARGS3, #__SLMARK, #__assertFlat, #__assertList, #_apply1, #_car, #_cdr, #_cons, #_core_MIMARKsyntax_QUMARK, #_display, #_eq_QUMARK, #_equal_QUMARK, #_eqv_QUMARK, #_exit, #_ge_QUMARK, #_global_MIMARKvariables, #_gt_QUMARK, #_hash_MIMARKtable_MIMARKexist_QUMARK, #_hash_MIMARKtable_MIMARKget, #_hash_MIMARKtable_MIMARKput_EXMARK, #_integer_QUMARK, #_intern, #_keyword_MIMARK_GTMARKstring, #_keyword_QUMARK, #_le_QUMARK, #_length, #_list, #_lt_QUMARK, #_macro_QUMARK, #_macroexpand_MIMARK1, #_make_MIMARKkeyword, #_make_MIMARKrecord_MIMARKtype, #_make_MIMARKvalues, #_modulo, #_newline, #_nil_QUMARK, #_not, #_null_QUMARK, #_number_QUMARK, #_pair_QUMARK, #_print, #_printf, #_procedure_QUMARK, #_quotient, #_range, #_read, #_read_MIMARKfrom_MIMARKstring, #_remainder, #_require, #_reverse, #_set_MIMARKcar_EXMARK, #_set_MIMARKcdr_EXMARK, #_sprintf, #_string_MIMARK_GTMARKsymbol, #_string_MIMARKjoin, #_string_QUMARK, #_symbol_MIMARK_GTMARKstring, #_symbol_QUMARK, #_syntax_QUMARK, #_to_MIMARKarr, #_to_MIMARKi, #_to_MIMARKlist, #_to_MIMARKs, #_to_arr, #_to_i, #_to_list, #_to_s, #_uniq, #_values_MIMARKvalues, #_values_QUMARK, #_vector_MIMARKset_EXMARK, #_write, #_write_MIMARKto_MIMARKstring

Constructor Details

#initialize(core, debug = false) ⇒ Evaluator

Returns a new instance of Evaluator.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/nendo/ruby/evaluator.rb', line 48

def initialize( core, debug = false )
  @compiledLineno = INITIAL_LINENO
  @compiledLinenoStack = []
  @core    = core
  @indent  = "  "
  @binding = binding
  @debug   = debug
  @trace_debug = false
  @lexicalVars = []
  @syntaxHash = {}
  @optimize_level = 2
  @runtimeCheck = true
  @backtrace = []
  @backtrace_last = ""
  @displayErrorsFlag = true;
  @char_table_lisp_to_ruby = {
    # list     (! $ % & * + - . / : < = > ? @ ^ _ ~ ...)
    '!'   => '_EXMARK',
    '$'   => '_DOMARK',
    '%'   => '_PAMARK',
    '&'   => '_ANMARK',
    '*'   => '_ASMARK',
    '+'   => '_PLMARK',
    '-'   => '_MIMARK',
    # '.'
    '/'   => '_SLMARK',
    ':'   => '_COMARK',
    '<'   => '_LTMARK',
    '='   => '_EQMARK',
    '>'   => '_GTMARK',
    '?'   => '_QUMARK',
    '@'   => '_ATMARK',
    '^'   => '_NKMARK',
    # '_'
    '~'   => '_CHMARK',
    '...' => '_DOTDOTDOT',
  }
  @char_table_ruby_to_lisp = @char_table_lisp_to_ruby.invert

  @core_syntax_list = [ :quote, :"syntax-quote", :if , :begin , :lambda , :macro , :"&block" , :"%let" , :letrec , :define, :set!, :error, :"%syntax", :"define-syntax", :"let-syntax", :"%guard" ]
  @core_syntax_hash = Hash.new
  @core_syntax_list.each { |x|
    renamed = ("/nendo/core/" + x.to_s).intern
    @core_syntax_hash[ x ] = renamed
  }

  # toplevel binding
  @global_lisp_binding = Hash.new

  # initialize builtin functions as Proc objects
  rubyExp = self.methods.select { |x|
    x.to_s.match( /^_/ )
  }.map { |name|
    [
     defMethodStr( name, false ),
     sprintf( "@%s                        = self.method( :%s        ).to_proc", name, name ),
     sprintf( "@global_lisp_binding['%s'] = self.method( :%s_METHOD ).to_proc", name, name ),
    ].join( " ; " )
  }.join( " ; " )
  eval( rubyExp, @binding )

  # initialize builtin syntax as LispCoreSyntax
  rubyExp = @core_syntax_hash.map { |k,v|
    name1 = toRubySymbol( k )
    name2 = toRubySymbol( v )
    [ sprintf( "@%s                        = LispCoreSyntax.new( :\"%s\" ) ", name1, k ),
      sprintf( "@global_lisp_binding['%s'] = @%s ", name1, name1 ),
      sprintf( "@%s                        = @%s ", name2, name1 ),
      sprintf( "@global_lisp_binding['%s'] = @%s ", name1, name2 ) ].join( " ; " )
  }.join( " ; " )
  eval( rubyExp, @binding )

  # reset gensym counter
  @gensym_counter = 0

  # call depth counter
  @call_depth     = 0
  @call_counters  = Hash.new

  # compiled ruby code
  #  { 'filename1' => [ 'code1' 'code2' ... ],
  #    'filename2' => [ 'code1' 'code2' ... ], ... }
  @compiled_code    = Hash.new
  @source_info_hash = Hash.new

  global_lisp_define( toRubySymbol( "%compile-phase-functions" ), Cell.new())
  load_path = $LOAD_PATH + [ File.dirname(__FILE__) ]
  global_lisp_define( toRubySymbol( "*load-path*"     ), load_path.to_list )
  global_lisp_define( toRubySymbol( "*nendo-version*" ), Nendo::Core.version )
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



302
303
304
305
306
307
308
# File 'lib/nendo/ruby/evaluator.rb', line 302

def method_missing( name, *args )
  if @global_lisp_binding[name].is_a? Proc
    @global_lisp_binding[name].call( args[0], args[1], args[2] )
  else
    callProcedure( name, args[0], args[1], args[2] )
  end
end

Instance Attribute Details

#runtimeCheckObject

Returns the value of attribute runtimeCheck.



46
47
48
# File 'lib/nendo/ruby/evaluator.rb', line 46

def runtimeCheck
  @runtimeCheck
end

Instance Method Details

#__evalSyntaxRules(rules, lexicalVars) ⇒ Object

eval (syntax-rules …) sexp

return:

(%syntax-rules
 ((v1 <<@syntaxHash's key1>>)
  (v2 <<@syntaxHash's key2>>)
  body))

example:
(%syntax-rules
 ((v1 "x = 10 // (+ x v1)")
  (v2 "y = 20 // (+ y v2)"))
 (+ v1 v2))


938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
# File 'lib/nendo/ruby/evaluator.rb', line 938

def __evalSyntaxRules( rules, lexicalVars )
  if :"%syntax-rules" == rules.car
    rules.second
  else
    lexvars = lexicalVars.select { |x|
      if _symbol_MIMARKinclude_QUMARK( rules, x[0].intern )
        x
      elsif lexicalVars.find {|y| _symbol_MIMARKinclude_QUMARK( y[1], x[0].intern ) }
        x
      else
        false
      end
    }

    __setupLexicalScopeVariables( lexvars )
    keyStr = lexvars.map {|z|
      z[0].to_s + " / " +  write_to_string( z[1] )
    }.join( " / " )
    keyStr += " // " + write_to_string( rules )
    if @syntaxHash.has_key?( keyStr )
      true
    else
      @syntaxHash[ keyStr ] = [ lexvars,
        self.lispEval( rules, "dynamic syntax-rules sexp (no source) ", 1 ) ]
    end
    __setupLexicalScopeVariables( [] )
    keyStr
  end
end

#__expandSyntaxRules(rules, syntaxArray, lexicalVars) ⇒ Object

expand (syntax-rules …) => (%syntax-rules …)



903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
# File 'lib/nendo/ruby/evaluator.rb', line 903

def __expandSyntaxRules( rules, syntaxArray, lexicalVars )
  if :"%syntax-rules" == rules.car
    rules
  else
    ellipse = rules.second
    pattern_body_list = rules.cdr.cdr

    lst = []
    lst << :"syntax-rules"
    lst << ellipse
    pattern_body_list.each {|xx|
      pattern_body = xx.car
      pattern = pattern_body.first
      body = pattern_body.second
      new_pattern_body = [ pattern, macroexpandEngine( body, syntaxArray, lexicalVars ) ].to_list
      lst << new_pattern_body
    }
    lst.to_list
  end
end

#__macroexpandEngine(sexp, syntaxArray, lexicalVars) ⇒ Object

args:

syntaxArray ... let-syntax's identifiers
                [
                   [ identifier-name, key of @syntaxHash, sexp of (syntax-rules ...), frame_of_let-syntax ],
                     .
                     .
                ]
lexicalVars ... let's identifiers
                [
                   [ identifier-name, macroexpandEngine( let's body ) ],
                ]


982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
# File 'lib/nendo/ruby/evaluator.rb', line 982

def __macroexpandEngine( sexp, syntaxArray, lexicalVars )
  sexp == castParsedSymbol( sexp )
  case sexp
  when Cell
    car = castParsedSymbol( sexp.car )
    if :quote == car or :"syntax-quote" == car or @core_syntax_hash[ :quote ] == car or @core_syntax_hash[ :"syntax-quote" ] == car
      sexp
    elsif :"%let" == car or :letrec == car or @core_syntax_hash[ :"%let" ] == car or @core_syntax_hash[ :letrec ] == car
      # catch lexical identifiers of `let' and `letrec'.
      arr = sexp.second.map { |x|
        [ castParsedSymbol( x.car.car ), macroexpandEngine( x.car.cdr, syntaxArray, lexicalVars ) ]
      }
      lst = arr.map {|x| Cell.new( x[0], x[1] ) }.to_list
      ret = Cell.new( car,
                 Cell.new( lst,
                      macroexpandEngine( sexp.cdr.cdr, syntaxArray, lexicalVars + arr )))
      ret
    elsif :"let-syntax" == car
      sexp.second.each {|x|
        if not x.car.second.is_a? Cell
          raise SyntaxError, "Error: let-syntax get only '((name (syntax-rules ...)))' form but got: " + write_to_string( x )
        elsif not ( castParsedSymbol( x.car.second.first ) == :"syntax-rules" or castParsedSymbol( x.car.second.first ) == :"%syntax-rules")
          raise SyntaxError, "Error: let-syntax get only '((name (syntax-rules ...)))' form but got: " + write_to_string( x )
        end
      }
      arr_tmp = sexp.second.map { |x|
        [ castParsedSymbol( x.car.first ), castParsedSymbol( __expandSyntaxRules( x.car.second, syntaxArray, lexicalVars )) ]
      }
      arr = arr_tmp.map {|x|
        [ castParsedSymbol( x[0] ), castParsedSymbol( __evalSyntaxRules( x[1], lexicalVars )), castParsedSymbol( x[1] ), castParsedSymbol( lexicalVars ) ]
      }

      # trial (expand recursively)
      arr_tmp = arr.map { |x|
        [ castParsedSymbol( x[0] ), castParsedSymbol( __expandSyntaxRules( x[2], syntaxArray + arr, lexicalVars )) ]
      }
      arr = arr_tmp.map {|x|
        [ castParsedSymbol( x[0] ), castParsedSymbol( __evalSyntaxRules( x[1], lexicalVars )), castParsedSymbol( x[1] ), castParsedSymbol( lexicalVars ) ]
      }

      # keywords = ((let-syntax-keyword ( let-syntax-body ))
      #             (let-syntax-keyword ( let-syntax-body ))
      #             ..)
      newKeywords = arr.map { |e|
        [ castParsedSymbol(e[0]), [ :"%syntax-rules", e[1]].to_list ].to_list
      }.to_list

      ret = Cell.new( :"let-syntax",
                 Cell.new( newKeywords, macroexpandEngine( sexp.cdr.cdr, syntaxArray + arr, lexicalVars )))

      ret
    else
      car = castParsedSymbol( car )
      sym = toRubySymbol( car.to_s )
      newSexp = sexp
      if isRubyInterface( sym )
        # do nothing
        sexp
      elsif _symbol_QUMARK( car ) and eval( sprintf( "(defined? @%s and LispMacro == @%s.class)", sym,sym ), @binding )
        eval( sprintf( "@__macro = @%s", sym ), @binding )
        newSexp = trampCall( callProcedure( nil, sym, @__macro, sexp.cdr.to_arr ))
      elsif _symbol_QUMARK( car ) and eval( sprintf( "(defined? @%s and LispSyntax == @%s.class)", sym,sym ), @binding )
        # expected input is
        #   (syntaxName arg1 arg2 ...)
        # will be transformed
        #   (syntaxName (syntaxName arg1 arg2 ...) () (global-variables))
        eval( sprintf( "@__syntax = @%s", sym ), @binding )
        newSexp = trampCall( callProcedure( nil, sym, @__syntax, [ sexp, Cell.new(), _global_MIMARKvariables( ) ] ))
      elsif _symbol_QUMARK( car ) and syntaxArray.map {|arr|
          arr[0].intern
        }.include?( car.intern )
        # lexical macro expandeding
        symbol_and_syntaxObj = syntaxArray.reverse.find {|arr|
          car == castParsedSymbol( arr[0] )
        }
        keys    = syntaxArray.reverse.map { |arr| castParsedSymbol( arr[0] ) }
        if not symbol_and_syntaxObj
          raise "can't find valid syntaxObject"
        end
        vars       = symbol_and_syntaxObj[3].map { |arr| castParsedSymbol( arr[0] ) }
        lexvars    = @syntaxHash[ symbol_and_syntaxObj[1] ][0]
        lispSyntax = @syntaxHash[ symbol_and_syntaxObj[1] ][1]
        newSexp = trampCall( callProcedure( nil, castParsedSymbol( symbol_and_syntaxObj[0] ), lispSyntax, [
                                              sexp,
                                              Cell.new(),
                                              (_global_MIMARKvariables( ).to_arr + keys + vars).to_list ] ))
        newSexp = __wrapNestedLet( newSexp, __removeSameLexicalScopeVariables( lexicalVars + lexvars ))
      end
      if _equal_QUMARK( newSexp, sexp )
        sexp.map { |x|
          if x.car.is_a? Cell
            macroexpandEngine( x.car, syntaxArray, lexicalVars )
          else
            x.car
          end
        }.to_list( sexp.lastAtom, sexp.getLastAtom )
      else
        @macroExpandCount -= 1
        newSexp
      end
    end
  else
    sexp
  end
end

#__PAMARKexport_MIMARKto_MIMARKruby(origname, pred) ⇒ Object



1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
# File 'lib/nendo/ruby/evaluator.rb', line 1377

def __PAMARKexport_MIMARKto_MIMARKruby( origname, pred )
  if toRubySymbol( origname ) != ("_" + origname)
    raise ArgumentError, "Error: %export-to-ruby requires function name in ruby method naming rule."
  end
  if not _procedure_QUMARK( pred )
    raise ArgumentError, "Error: %export-to-ruby requires 'pred' as a Proc instance."
  end
  if 0 > pred.arity
    raise ArgumentError, "Error: %export-to-ruby requires only a function that have fixed length argument."
  end
  if self.methods.include?( origname.intern ) or @core.methods.include?( origname.intern )
    raise RuntimeError, "Error: %export-to-ruby: Nendo::Core." + origname + " method was already deifned."
  end

  argsStr = (1..(pred.arity)).map { |n| "arg" + n.to_s }.join( "," )
  str = [ "def self." + origname + "(" + argsStr + ")",
          sprintf( "  trampCall( callProcedure( nil, '%s', @_%s, [ " + argsStr + " ] )) ",
                   origname, origname ),
          "end",
          ";",
          "def @core." + origname + "(" + argsStr + ")",
          "  @evaluator." + origname + "(" + argsStr + ") ",
          "end"
        ].join
  eval( str, @binding )
  true
end

#__PAMARKload(filename) ⇒ Object



1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
# File 'lib/nendo/ruby/evaluator.rb', line 1292

def __PAMARKload( filename )
  pushCompiledLineno(@compiledLineno)
  @compiledLineno = INITIAL_LINENO
  printer = Printer.new( @debug )
  open( filename, "r:utf-8" ) {|f|
    reader = Reader.new( f, filename, false )
    while true
      lineno = reader.lineno
      s = reader._read
      if s[1] # EOF?
        break
      elsif Nil != s[0].class
        printf( "\n          readExp=<<< %s >>>\n", printer._print(s[0]) ) if @debug
        self.lispEval( s[0], reader.sourcefile, lineno )
      end
    end
  }
  forward_gensym_counter()
  @compiledLineno = popCompiledLineno()
end

#__PAMARKload_MIMARKcompiled_MIMARKcode(filename) ⇒ Object



1318
1319
1320
1321
1322
1323
# File 'lib/nendo/ruby/evaluator.rb', line 1318

def __PAMARKload_MIMARKcompiled_MIMARKcode( filename )
  open( filename, "r:utf-8" ) { |f|
    eval( f.read, @binding, filename, 1 )
  }
  forward_gensym_counter()
end

#__removeSameLexicalScopeVariables(frame) ⇒ Object



864
865
866
867
868
869
870
871
872
873
874
875
876
# File 'lib/nendo/ruby/evaluator.rb', line 864

def __removeSameLexicalScopeVariables( frame )
  frame.select {|x|
    # search same varname and different value
    found = frame.any? {|y|
      x[0] == y[0] and (not _equal_QUMARK( x[1], y[1] ))
    }
    if found
      x
    else
      false
    end
  }
end

#__setupLexicalScopeVariables(lexicalVars) ⇒ Object



1405
1406
1407
# File 'lib/nendo/ruby/evaluator.rb', line 1405

def __setupLexicalScopeVariables( lexicalVars )
  @lexicalVars = lexicalVars.clone
end

#__wrapNestedLet(sexp, lexicalVars) ⇒ Object

warp sexp by lexicalVars



851
852
853
854
855
856
857
858
859
860
861
862
# File 'lib/nendo/ruby/evaluator.rb', line 851

def __wrapNestedLet( sexp, lexicalVars )
  if 0 == lexicalVars.size
    sexp
  else
    elem  = lexicalVars.shift
    Cell.new( :"%let",
         Cell.new(
              Cell.new(
                   Cell.new( elem[0], elem[1] )),
              Cell.new( __wrapNestedLet( sexp, lexicalVars ) )))
  end
end

#_clean_MIMARKcompiled_MIMARKcodeObject



1325
1326
1327
# File 'lib/nendo/ruby/evaluator.rb', line 1325

def _clean_MIMARKcompiled_MIMARKcode
  @compiled_code = Hash.new
end

#_disable_MIMARKidebugObject



1346
1347
1348
# File 'lib/nendo/ruby/evaluator.rb', line 1346

def _disable_MIMARKidebug()
  @debug = false
end

#_disable_MIMARKtraceObject



1352
1353
1354
# File 'lib/nendo/ruby/evaluator.rb', line 1352

def _disable_MIMARKtrace()
  @trace_debug = false
end

#_enable_MIMARKidebugObject



1343
1344
1345
# File 'lib/nendo/ruby/evaluator.rb', line 1343

def _enable_MIMARKidebug()
  @debug = true
end

#_enable_MIMARKtraceObject



1349
1350
1351
# File 'lib/nendo/ruby/evaluator.rb', line 1349

def _enable_MIMARKtrace()
  @trace_debug = true
end

#_eval(sexp) ⇒ Object



1339
1340
1341
# File 'lib/nendo/ruby/evaluator.rb', line 1339

def _eval( sexp )
  self.lispEval( sexp, "dynamic S-expression ( no source )", 1 )
end

#_gensymObject



183
184
185
186
187
188
189
190
191
# File 'lib/nendo/ruby/evaluator.rb', line 183

def _gensym( )
  @gensym_counter += 1
  filename = if @lastSourcefile.is_a? String
               Digest::SHA1.hexdigest( @lastSourcefile )
             else
               ""
             end
  sprintf( "__gensym__%s_%d", filename, @gensym_counter ).intern
end

#_get_MIMARKcompiled_MIMARKcodeObject



1329
1330
1331
1332
1333
1334
1335
1336
1337
# File 'lib/nendo/ruby/evaluator.rb', line 1329

def _get_MIMARKcompiled_MIMARKcode
  @compiled_code
  ret = Hash.new
  @compiled_code.each_key { |key|
    ret[key] = @compiled_code[key].to_list
    ret[key]
  }
  ret.to_list
end

#_get_MIMARKoptimize_MIMARKlevelObject



1358
1359
1360
# File 'lib/nendo/ruby/evaluator.rb', line 1358

def _get_MIMARKoptimize_MIMARKlevel()
  self.getOptimizeLevel
end

#_get_MIMARKsource_MIMARKinfo(varname) ⇒ Object



1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
# File 'lib/nendo/ruby/evaluator.rb', line 1362

def _get_MIMARKsource_MIMARKinfo( varname )
  info = @source_info_hash[ varname.to_s ]
  if info
    [
     Cell.new( "varname",           info.varname ),
     Cell.new( "sourcefile",        info.sourcefile ),
     Cell.new( "lineno",            info.lineno ),
     Cell.new( "source",            info.source_sexp ),
     Cell.new( "expanded",          info.expanded_sexp ),
     Cell.new( "compiled_str",      info.compiled_str ) ].to_list
  else
    raise NameError, sprintf( "Error: not found variable [%s]. \n", varname.to_s )
  end
end

#_load_MIMARKcompiled_MIMARKcode_MIMARKfrom_MIMARKstring(rubyExp) ⇒ Object



1313
1314
1315
1316
# File 'lib/nendo/ruby/evaluator.rb', line 1313

def _load_MIMARKcompiled_MIMARKcode_MIMARKfrom_MIMARKstring( rubyExp )
  eval( rubyExp, @binding )
  forward_gensym_counter()
end

#_make_MIMARKsyntactic_MIMARKclosure(mac_env, use_env, identifier) ⇒ Object



1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
# File 'lib/nendo/ruby/evaluator.rb', line 1409

def _make_MIMARKsyntactic_MIMARKclosure( mac_env, use_env, identifier )
  if _pair_QUMARK( identifier )
    if :"syntax-quote" == castParsedSymbol( identifier.car )
      identifier
    else
      raise TypeError, "make-syntactic-closure requires symbol or (syntax-quote sexp) only. but got: " + write_to_string( identifier )
    end
  elsif _symbol_QUMARK( identifier )
    # pp [ "identifier: ", identifier, "include?=", mac_env.to_arr.include?( identifier.intern ) ]
    # pp [ "mac_env: ",    mac_env.to_arr ]
    if mac_env.to_arr.include?( identifier.intern )
      found = @lexicalVars.find { |x| identifier == x[0] }
      if found
        lexvars = @lexicalVars.clone
        __wrapNestedLet( identifier, lexvars )
      else
        identifier
      end
    else
      SyntacticClosure.new( identifier, (toRubySymbol( identifier ) + _gensym( ).to_s).intern )
    end
  else
    raise TypeError, "make-syntactic-closure requires symbol or (syntax-quote sexp) type."
  end
end

#_set_MIMARKoptimize_MIMARKlevel(level) ⇒ Object



1355
1356
1357
# File 'lib/nendo/ruby/evaluator.rb', line 1355

def _set_MIMARKoptimize_MIMARKlevel(level)
  self.setOptimizeLevel( level )
end

#_strip_MIMARKlet_MIMARKsyntax_MIMARKkeyword(sexp) ⇒ Object



1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
# File 'lib/nendo/ruby/evaluator.rb', line 1456

def _strip_MIMARKlet_MIMARKsyntax_MIMARKkeyword( sexp )
  case sexp
  when Cell
    if _null_QUMARK( sexp )
      sexp
    else
      car = sexp.car
      if :"quote" == car or @core_syntax_hash[ :"quote" ] == car
        sexp
      elsif :"let-syntax" == car or @core_syntax_hash[ :"let-syntax" ] == car
        Cell.new( :begin,
             _strip_MIMARKlet_MIMARKsyntax_MIMARKkeyword( sexp.cdr.cdr ))
      else
        Cell.new(
             _strip_MIMARKlet_MIMARKsyntax_MIMARKkeyword( sexp.car ),
             _strip_MIMARKlet_MIMARKsyntax_MIMARKkeyword( sexp.cdr ))
      end
    end
  else
    sexp
  end
end

#_strip_MIMARKsyntactic_MIMARKclosures(sexp) ⇒ Object



1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
# File 'lib/nendo/ruby/evaluator.rb', line 1479

def _strip_MIMARKsyntactic_MIMARKclosures( sexp )
  case sexp
  when Cell
    if _null_QUMARK( sexp )
      sexp
    else
      Cell.new(
             _strip_MIMARKsyntactic_MIMARKclosures( sexp.car ),
             _strip_MIMARKsyntactic_MIMARKclosures( sexp.cdr ))
    end
  else
    if sexp.is_a? SyntacticClosure
      sexp.intern
    else
      sexp
    end
  end
end

#_strip_MIMARKsyntax_MIMARKquote(sexp) ⇒ Object



1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
# File 'lib/nendo/ruby/evaluator.rb', line 1435

def _strip_MIMARKsyntax_MIMARKquote( sexp )
  case sexp
  when Cell
    if _null_QUMARK( sexp )
      sexp
    else
      car = sexp.car
      car = castParsedSymbol( car )
      if :"syntax-quote" == car or @core_syntax_hash[ :"syntax-quote" ] == car
        Cell.new( :quote, sexp.cdr )
      else
        Cell.new(
             _strip_MIMARKsyntax_MIMARKquote( sexp.car ),
             _strip_MIMARKsyntax_MIMARKquote( sexp.cdr ))
      end
    end
  else
    sexp
  end
end

#_symbol_MIMARKinclude_QUMARK(sexp, sym) ⇒ Object



1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
# File 'lib/nendo/ruby/evaluator.rb', line 1498

def _symbol_MIMARKinclude_QUMARK( sexp, sym )
  case sexp
  when Cell
    if _null_QUMARK( sexp )
      false
    else
      _symbol_MIMARKinclude_QUMARK( sexp.car, sym ) or _symbol_MIMARKinclude_QUMARK( sexp.cdr, sym )
    end
  else
    if _symbol_QUMARK( sexp )
      sym.intern == sexp.intern
    else
      false
    end
  end
end

#adjustLineno(target_lineno, compiledLineno) ⇒ Object



1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
# File 'lib/nendo/ruby/evaluator.rb', line 1103

def adjustLineno( target_lineno, compiledLineno )
  str = ""
  if compiledLineno < target_lineno
    while compiledLineno < target_lineno
      str += "\n"
      compiledLineno += 1
    end
  end
  return str
end

#apply(car, cdr, sourcefile, lineno, locals, sourceInfo, execType) ⇒ Object



642
643
644
645
646
647
648
649
# File 'lib/nendo/ruby/evaluator.rb', line 642

def apply( car, cdr, sourcefile, lineno, locals, sourceInfo, execType )
  cdr.each { |x|
    if Cell == x.class
      x.car = translate( x.car, locals, sourceInfo )
    end
  }
  execFunc( car, cdr, sourcefile, lineno, locals, sourceInfo, execType )
end

#callProcedure(rubysym, origname, pred, args) ⇒ Object



319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# File 'lib/nendo/ruby/evaluator.rb', line 319

def callProcedure( rubysym, origname, pred, args )
  if pred.nil?
    raise RuntimeError, sprintf( "Error: function `%s' is undefined.", origname )
  end

  if @runtimeCheck
    if @call_counters.has_key?( origname )
      @call_counters[ origname ] += 1
    else
      @call_counters[ origname ]  = 1
    end
  end

  result = pred.call( *toRubyArgument( origname, pred, args ))

  if @runtimeCheck
    @call_counters[ origname ]   -= 1
  end

  result
end

#castParsedSymbol(arg) ⇒ Object



1088
1089
1090
1091
1092
1093
1094
# File 'lib/nendo/ruby/evaluator.rb', line 1088

def castParsedSymbol( arg )
  if arg.class == ParsedSymbol
    arg.intern
  else
    arg
  end
end

#defMethodStr(name, _log) ⇒ Object



174
175
176
177
178
179
180
181
# File 'lib/nendo/ruby/evaluator.rb', line 174

def defMethodStr( name, _log )
  [ "def self." + name.to_s + "_METHOD( origname, pred, args ) ",
    "  lispMethodEntry( origname, " + _log.to_s + " ) ; ",
    "  ret = callProcedure( '" + name.to_s + "', origname, pred, args ) ;",
    "  lispMethodExit( origname,  " + _log.to_s + " ) ; ",
    "  return ret ",
    "end" ].join
end

#delayCall(rubysym, origname, pred, args) ⇒ Object



310
311
312
313
314
315
316
317
# File 'lib/nendo/ruby/evaluator.rb', line 310

def delayCall( rubysym, origname, pred, args )
  case @optimize_level
  when 0 # no optimize
    callProcedure( rubysym, origname, pred, args )
  else # tail call optimization
    DelayedCallPacket.new( rubysym, origname, pred, args )
  end
end

#displayBacktrace(exception) ⇒ Object



1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
# File 'lib/nendo/ruby/evaluator.rb', line 1183

def displayBacktrace( exception )
  if @displayErrorsFlag
    STDERR.printf("-------------- Nendo backtrace ---------------\n")
    STDERR.printf("%s\n",exception.to_s)
    exception.backtrace.each {|str|
      line = normalizeBacktrace(str)
      if line
        STDERR.printf("	from %s\n",line)
      end
    }
    STDERR.printf("\n")
    STDERR.printf("-------------- Ruby  backtrace ---------------\n")
  end
end

#displayTopOfCalls(exception) ⇒ Object



1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
# File 'lib/nendo/ruby/evaluator.rb', line 1168

def displayTopOfCalls( exception )
  if @displayErrorsFlag
    STDERR.puts( "\n  <<< Top of calls >>>" )
    strs = []
    @call_counters.each_key { |funcname|
      if 0 < @call_counters[ funcname ]
        strs << sprintf( "  %7d : %-20s", @call_counters[ funcname ], funcname )
      end
    }
    strs.sort.reverse.each { |str|
      STDERR.puts( str )
    }
  end
end

#embedBacktraceInfo(sourcefile, lineno) ⇒ Object



362
363
364
365
366
367
368
369
370
371
372
# File 'lib/nendo/ruby/evaluator.rb', line 362

def embedBacktraceInfo( sourcefile, lineno )
  str = sourcefile + ":" + lineno.to_s
  if @backtrace_last != str
    @backtrace << str
    if ( 10 < @backtrace.size )
      @backtrace.shift
    end
    #p @backtrace
  end
  @backtrace_last = str
end

#errorMessageOf_toRubyArgument(origname, no, req, got) ⇒ Object



253
254
255
# File 'lib/nendo/ruby/evaluator.rb', line 253

def errorMessageOf_toRubyArgument( origname, no, req, got )
  sprintf( "Error: [%s] wrong number of arguments for closure `%s' (requires %d, but got %d)", no, origname, req, got )
end

#execFunc(funcname, args, sourcefile, lineno, locals, sourceInfo, execType) ⇒ Object



391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
# File 'lib/nendo/ruby/evaluator.rb', line 391

def execFunc( funcname, args, sourcefile, lineno, locals, sourceInfo, execType )
  funcname = castParsedSymbol( funcname )
  if isDefines( funcname )
    ar = args.cdr.map { |x| x.car }
    variable_sym = toRubySymbol( args.car.to_s.sub( /^:/, "" ))
    global_cap = locals.flatten.include?( variable_sym.split( /[.]/ )[0] ) ? nil : "@"
    if global_cap and sourceInfo
      sourceInfo.setVarname( toLispSymbol( variable_sym ))
    end
    [ "begin ",
      makeComment("#execFunc"),
      [
       if global_cap
         [
          defMethodStr( variable_sym, true ),
          sprintf( "@global_lisp_binding['%s'] = self.method( :%s_METHOD )", variable_sym, variable_sym )
         ]
       else
         #kiyoka
         ""
       end,
       makeComment(sprintf("#execFunc(funcname=%s)",funcname)),
       sprintf( "%s%s = ", global_cap, variable_sym ),
       "trampCall(", [ ar ], ")"],
      "end"
    ]
  elsif :error == funcname or  @core_syntax_hash[ :error ] == funcname
    arr = if args.length < 2
            args.car
          else
            [ args.car + " ' ' + ",
              "_write_MIMARKto_MIMARKstring(",
              args.cdr.car,
              ")" ]
          end
    [
     'begin raise RuntimeError, ',
     arr,
     "rescue => __e ",
     sprintf( "  __e.set_backtrace( [\"%s:%d\"] + __e.backtrace )", sourcefile, lineno ),
     "  raise __e",
     "end"]
  else
    if (EXEC_TYPE_ANONYMOUS != execType) and isRubyInterface( funcname )
      # Ruby method
      #   1) convert arguments
      translatedArr  = args.map { |x| x.car }
      #   2) generate caller code part
      lispSymbolReference( toRubySymbol( funcname ), locals, translatedArr, sourcefile, lineno )
    else
      # Nendo function
      arr = separateWith( args.map { |x| x.car }, "," )
      origname = funcname.to_s
      sym   = toRubySymbol( origname )
      if EXEC_TYPE_ANONYMOUS == execType
        [sprintf( "trampCall( callProcedure( nil, 'anonymouse', " ),
          [ funcname ] + [ "," ],
          "[", arr, "]",
          "          ))"]
      else
        result = false
        if (execType == EXEC_TYPE_NORMAL) and (not locals.flatten.include?( sym ))
          if 1 < @optimize_level
            result = optimizedFunc( origname, sym, arr )
          end
        end
        if result
#              puts "result:"
#              pp result
          generateEmbedBacktraceInfo( sourcefile, lineno, result )
        else
          _call = case execType
                  when EXEC_TYPE_NORMAL
                    if locals.flatten.include?( sym )
                      [          "trampCall( callProcedure(  '" + sym + "', ", "))" ] # local function
                    else
                      [ sprintf( "trampCall( self.%s_METHOD( ", sym ), "))" ]         # toplevel function
                    end
                  when EXEC_TYPE_TAILCALL
                    [ sprintf( "delayCall( '%s', ", sym ),  ")"  ]
                  end

          temp = [
            sprintf( "%s '%s',", _call[0], origname ),
            [lispSymbolReference( sym, locals, nil, sourcefile, lineno )] + [","],
            "[", arr, "]",
            sprintf( "             %s", _call[1] )]
          generateEmbedBacktraceInfo( sourcefile, lineno, temp )
        end
      end
    end
  end
end

#forward_gensym_counterObject



193
194
195
# File 'lib/nendo/ruby/evaluator.rb', line 193

def forward_gensym_counter( )
  @gensym_counter += 10000
end

#generateEmbedBacktraceInfo(sourcefile, lineno, arr) ⇒ Object



374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'lib/nendo/ruby/evaluator.rb', line 374

def generateEmbedBacktraceInfo( sourcefile, lineno, arr )
  if sourcefile and lineno
    if @runtimeCheck
      ["begin",
       [
         sprintf( 'embedBacktraceInfo( "%s", %s );', sourcefile, lineno ),
         arr],
       "end"
      ]
    else
      [arr]
    end
  else
    arr
  end
end

#genQuote(sexp, str = "") ⇒ Object



651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
# File 'lib/nendo/ruby/evaluator.rb', line 651

def genQuote( sexp, str = "" )
  origStr = str
  case sexp
  when Cell
    if sexp.isNull
      str += "Cell.new()"
    else
      arr = sexp.map { |x| genQuote( x.car ) }
      str += "Cell.new("
      str += arr.join( ",Cell.new(" )
      str += "," + genQuote( sexp.getLastAtom )  if sexp.lastAtom
      str += arr.map{ |e| ")" }.join
    end
  when Array
    arr = sexp.map { |x| genQuote( x ) }
    str += "[" +  arr.join(",") + "]"
  when Symbol
    str += sprintf( ":\"%s\"", sexp.to_s )
  when ParsedSymbol
    str += sprintf( ":\"%s\"", sexp.to_s )
  when String, LispString
    str += sprintf( "\"%s\"", LispString.escape( sexp ))
  when LispKeyword
    str += sprintf( "LispKeyword.new( \"%s\" )", sexp.key.to_s )
  when TrueClass, FalseClass, NilClass  # reserved symbols
    str += toRubyValue( sexp )
  when SyntacticClosure
    str += sprintf( ":\"%s\"", sexp.originalSymbol.to_s )
  when Nil
    str += "Cell.new()"
  else
    str += sprintf( "%s", sexp )
  end
  str
end

#getOptimizeLevelObject



153
154
155
# File 'lib/nendo/ruby/evaluator.rb', line 153

def getOptimizeLevel
  @optimize_level
end

#global_lisp_define(rubySymbol, val) ⇒ Object



139
140
141
142
143
# File 'lib/nendo/ruby/evaluator.rb', line 139

def global_lisp_define( rubySymbol, val )
  @___tmp = val
  eval( sprintf( "@%s = @___tmp;", rubySymbol ), @binding )
  eval( sprintf( "@global_lisp_binding['%s'] = @___tmp;", rubySymbol ), @binding )
end

#isDefines(sym) ⇒ Object



356
357
358
359
360
# File 'lib/nendo/ruby/evaluator.rb', line 356

def isDefines( sym )
  sym = castParsedSymbol( sym )
  result = [ :define, :set!, :"define-syntax", @core_syntax_hash[ :define ], @core_syntax_hash[ :set! ], @core_syntax_hash[ :"define-syntax" ] ].include?( sym )
  return result
end

#isRubyInterface(name) ⇒ Object



238
239
240
# File 'lib/nendo/ruby/evaluator.rb', line 238

def isRubyInterface( name )
  name.to_s.match( /[.]/ )
end

#lispEval(sexp, sourcefile, lineno) ⇒ Object



1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
# File 'lib/nendo/ruby/evaluator.rb', line 1235

def lispEval( sexp, sourcefile, lineno )
  begin
    sourceInfo = SourceInfo.new
    @lastSourcefile = sourcefile
    @lastLineno     = lineno
    sourceInfo.setSource( sourcefile, lineno, sexp )

    # macro expand phase
    sexp = macroexpandPhase( sexp )
    if @debug
      printf( "\n          expaneded=<<< %s >>>\n", (Printer.new())._print(sexp))
    end

    # compiling phase written
    origsym = "%compile-phase"
    sym = toRubySymbol( origsym )
    if ( eval( sprintf( "(defined? @%s and Proc == @%s.class)", sym,sym ), @binding ))
      eval( sprintf( "@___tmp = @%s", sym ), @binding )
      sexp = trampCall( callProcedure( nil, origsym, @___tmp, [ sexp ]))
      if @debug
        printf( "\n          compiled= <<< %s >>>\n", (Printer.new())._print(sexp))
      end
    end
    sourceInfo.setExpanded( sexp )

    arr = [ "trampCall( ", translate( sexp, [], sourceInfo ), " )" ]
    rubyExp = ppRubyExp( 0, arr, lineno ).flatten.join
    sourceInfo.setCompiled( rubyExp )
    if not @compiled_code.has_key?( sourcefile )
      @compiled_code[ sourcefile ] = Array.new
    end
    @compiled_code[ sourcefile ] << rubyExp
    if sourceInfo.varname
      @source_info_hash[ sourceInfo.varname ] = sourceInfo
    end
    printf( "          rubyExp=<<<\n%s\n>>>\n", rubyExp ) if @debug
    eval( rubyExp, @binding, @lastSourcefile, @compiledLineno )
  rescue SystemStackError => e
    displayTopOfCalls( e )
    raise e
  rescue => e
    displayBacktrace( e )
    raise e
  end
end

#lispMethodEntry(name, _log) ⇒ Object



161
162
163
164
165
166
# File 'lib/nendo/ruby/evaluator.rb', line 161

def lispMethodEntry( name, _log )
  @call_depth += 1
  if @trace_debug and _log
    puts " " * @call_depth + "ENTRY: " + name
  end
end

#lispMethodExit(name, _log) ⇒ Object



167
168
169
170
171
172
# File 'lib/nendo/ruby/evaluator.rb', line 167

def lispMethodExit( name, _log )
  if @trace_debug and _log
    puts " " * @call_depth + "exit:  " + name
  end
  @call_depth -= 1
end

#lispSymbolReference(sym, locals, translatedArr, sourcefile, lineno) ⇒ Object



697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
# File 'lib/nendo/ruby/evaluator.rb', line 697

def lispSymbolReference( sym, locals, translatedArr, sourcefile, lineno )
  variable_sym = sym.split( /[.]/ )[0]
  global_cap = if variable_sym.match( /^[A-Z]/ )
                 nil
               else
                 locals.flatten.include?( variable_sym ) ? nil : "@"
               end
  expression = if translatedArr
                 [trampCallCap( sprintf( "%s%s(", global_cap, sym )),
                  separateWith( translatedArr, "," ),
                  sprintf( "  )" )]
               else
                 [trampCallCap( sprintf( "%s%s", global_cap, sym ))]
               end
  if global_cap
    if @runtimeCheck
      ["begin",
       [sprintf( "if @global_lisp_binding.has_key?('%s') then", variable_sym ),
        expression,
        sprintf( 'else raise NameError.new( "%s:%d: Error: undefined variable %s", "%s" ) end', sourcefile, lineno, toLispSymbol( variable_sym ), toLispSymbol( variable_sym )),
        sprintf( 'rescue => __e ; __e.set_backtrace( ["%s:%d"] + __e.backtrace ) ; raise __e',  sourcefile, lineno  )],
       "end"]
    else
      expression
    end
  else
    if @runtimeCheck
      ["begin",
       [expression,
        sprintf( 'rescue => __e ; __e.set_backtrace( ["%s:%d"] + __e.backtrace ) ; raise __e', sourcefile, lineno )],
       "end"]
    else
      expression
    end
  end
end

#macroexpandEngine(sexp, syntaxArray, lexicalVars) ⇒ Object



892
893
894
895
896
897
898
# File 'lib/nendo/ruby/evaluator.rb', line 892

def macroexpandEngine( sexp, syntaxArray, lexicalVars )
  if @macroExpandCount <= 0
    sexp
  else
    __macroexpandEngine( sexp, syntaxArray, lexicalVars )
  end
end

#macroexpandEngineLoop(sexp, syntaxArray, lexicalVars) ⇒ Object



882
883
884
885
886
887
888
889
890
# File 'lib/nendo/ruby/evaluator.rb', line 882

def macroexpandEngineLoop( sexp, syntaxArray, lexicalVars )
  converge = true
  begin
    newSexp  = macroexpandEngine( sexp, syntaxArray, lexicalVars )
    converge = _equal_QUMARK( newSexp, sexp )
    sexp = newSexp
  end until converge or (@macroExpandCount <= 0)
  sexp
end

#macroexpandInit(initVal) ⇒ Object



878
879
880
# File 'lib/nendo/ruby/evaluator.rb', line 878

def macroexpandInit( initVal )
  @macroExpandCount = initVal
end

#macroexpandPhase(sexp) ⇒ Object



1096
1097
1098
1099
1100
1101
# File 'lib/nendo/ruby/evaluator.rb', line 1096

def macroexpandPhase( sexp )
  macroexpandInit( 100000 )
  _strip_MIMARKlet_MIMARKsyntax_MIMARKkeyword(
     _strip_MIMARKsyntax_MIMARKquote(
        macroexpandEngineLoop( sexp, [], [] )))
end

#makeBegin(args, locals) ⇒ Object



498
499
500
501
502
503
504
505
506
507
# File 'lib/nendo/ruby/evaluator.rb', line 498

def makeBegin( args, locals )
  ar = args.map { |e|
    translate( e.car, locals )
  }
  if ar.size < 2
    ar
  else
    ["begin ", makeComment("#makeBegin"), ar, "end"]
  end
end

#makeClosure(sym, args, locals) ⇒ Object



533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
# File 'lib/nendo/ruby/evaluator.rb', line 533

def makeClosure( sym, args, locals )
  first = args.car
  rest  = args.cdr
  ( _locals, argStr ) = toRubyParameter( first )
  str = case sym
        when :macro
          sprintf( "LispMacro.new { %s ", argStr )
        when :lambda
          sprintf( "Proc.new { %s ", argStr )
        when :"%syntax"
          sprintf( "LispSyntax.new { %s ", argStr )
        when :"&block"
          sprintf( "&Proc.new { %s ", argStr )
        else
          raise "Error: makeClosure: unknown symbol type " + sym
        end
  ar = rest.map { |e|
    translate( e.car, locals.clone + [_locals])
  }
  [ str, ar, "}" ]
end

#makeComment(commentStr) ⇒ Object



485
486
487
# File 'lib/nendo/ruby/evaluator.rb', line 485

def makeComment( commentStr )
  [ commentStr ]
end

#makeGuard(args, locals) ⇒ Object



629
630
631
632
633
634
635
636
637
638
639
640
# File 'lib/nendo/ruby/evaluator.rb', line 629

def makeGuard( args, locals )
  _var        = toRubySymbol( args.car )
  _locals     = locals.clone + [_var]
  _case       = translate( args.cdr.car,         _locals )
  _thunk      = translate( args.cdr.cdr.car,     _locals )
  ["begin ",
   makeComment("#makeGuard"),
   [ _thunk ],
   "rescue => " + _var,
   [ _case ],
   "end" ]
end

#makeIf(args, locals) ⇒ Object



555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
# File 'lib/nendo/ruby/evaluator.rb', line 555

def makeIf( args, locals )
  _condition = translate( args.car,         locals )
  _then      = translate( args.cdr.car,     locals )
  _else      = nil
  if 2 < args.length
    _else    = translate( args.cdr.cdr.car, locals )
  end
  if _else
    ["if ( ", _condition, " ) then",
     [ _then ],
     "else",
     [ _else ],
     "end"]
  else
    ["if ( ", _condition, " ) then",
     [ _then ],
     "end"]
  end
end

#makeLet(args, locals) ⇒ Object



575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
# File 'lib/nendo/ruby/evaluator.rb', line 575

def makeLet( args, locals )
  _name = "___lambda"
  argvals = []
  rest = args.cdr
  if _null_QUMARK( args.car )
    # nothing to do
    lambda_head = sprintf( "%s = lambda { || ", _name )
  else
    argsyms = args.car.map { |x|
      toRubySymbol( x.car.car.to_s )
    }
    argvals = args.car.map.with_index { |x,i|
      translate( x.car.cdr.car, locals )
    }
    lambda_head = sprintf( "%s = lambda { |%s| ", _name, argsyms.join( "," ))
  end
  ["begin",
   makeComment("#makeLet"),
   [lambda_head,
    rest.map { |e|  translate( e.car, locals.clone + [argsyms] ) },
    sprintf( "} ; %s.call(", _name ),
    separateWith( argvals, "," ),
    sprintf( "           )")],
   "end"]
end

#makeLetrec(args, locals) ⇒ Object



601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
# File 'lib/nendo/ruby/evaluator.rb', line 601

def makeLetrec( args, locals )
  _name = "___lambda"
  argvals = []
  argsyms = []
  rest = args.cdr
  if _null_QUMARK( args.car )
    # nothing to do
    lambda_head = sprintf( "%s = lambda { || ", _name )
  else
    argsyms = args.car.map { |x|
      toRubySymbol( x.car.car.to_s )
    }
    argvals = args.car.map { |x|
      translate( x.car.cdr.car, locals.clone + [argsyms] )
    }
    lambda_head = sprintf( "%s = lambda { |%s| ", _name, argsyms.join( "," ))
  end
  ["begin ",
   makeComment("#makeLetrec"),
   [lambda_head,
    argsyms.zip( argvals ).map { |x| [ x[0], " = ", x[1] ] },
    rest.map { |e|  translate( e.car, locals.clone + [argsyms] ) },
    sprintf( "} ; %s.call(", _name ),
    argsyms.map { |x| "nil" }.join( "," ),
    sprintf( "           )")],
   "end"]
end

#makeSetVariable(car, cdr, locals, sourceInfo) ⇒ Object



489
490
491
492
493
494
495
496
# File 'lib/nendo/ruby/evaluator.rb', line 489

def makeSetVariable( car, cdr, locals, sourceInfo )
  cdr.cdr.each { |x|
    if Cell == x.class
      x.car = translate( x.car, locals, sourceInfo )
    end
  }
  execFunc( car, cdr, car.sourcefile, car.lineno, locals, sourceInfo, EXEC_TYPE_ANONYMOUS )
end

#normalizeBacktrace(str) ⇒ Object



1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
# File 'lib/nendo/ruby/evaluator.rb', line 1198

def normalizeBacktrace( str )
  fields = str.split(/:/)
  if 3 <= fields.size()
    (filename,compiled_lineno,funcname) = fields
    if filename.match( ".nnd$" ) or filename.match( ".nndc$" ) or filename.match( ".nndc.nc$" ) or filename.match( ".scm$" )

      filename = filename.sub( /.nndc.nc$/, ".nnd" )
      filename = filename.sub( /.nndc$/,    ".nnd" )
      
      lineno = 1
      if compiled_lineno
        compiled_lineno = compiled_lineno.to_i
        lineno = compiled_lineno / LINENO_TIMES
        if lineno < 1
          lineno = 1
        end
      end
      
      funcname = funcname.sub(/^in [`]/,"")
      funcname = funcname.sub(/[']$/,"")
      if funcname.match(/_METHOD$/)
        funcname = funcname.sub(/_METHOD$/,"")
      else
        return nil
      end
      if '_' == funcname[0]
        funcname = toLispSymbol(funcname)
      end
      return sprintf( "%s:%s:in `%s' <nendo function> (compiled lineno=%d)",filename,lineno,funcname,compiled_lineno)
    else
      return nil
    end
  else
    return nil
  end
end

#optimizedFunc(origname, rubysym, args) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/nendo/ruby/optimized_func.rb', line 39

def optimizedFunc( origname, rubysym, args )
  case origname
  when '+'
    case args.length
    when 0
      [ "#{rubysym}_ARGS0()" ]
    when 1
      ["( ", args[0][0]," ) "]
    when 2
      ["( ", args[0][0], "+", args[1][0], " ) "]
    when 3
      ["( ", args[0][0], "+", args[1][0], "+", args[2][0], " ) "]
    else
      false
    end
  when '-'
    case args.length
    when 0
      [ "#{rubysym}_ARGS0()" ]
    when 1
      ["( - ", args[0][0]," ) "]
    when 2
      ["( ", args[0][0], "-", args[1][0], " ) "]
    when 3
      ["( ", args[0][0], "-", args[1][0], "-", args[2][0], " ) "]
    else
      false
    end
  when '*'
    case args.length
    when 0
      [ "#{rubysym}_ARGS0()" ]
    when 1
      ["( ", args[0][0]," ) "]
    when 2
      ["( ", args[0][0], "*", args[1][0], " ) "]
    when 3
      ["( ", args[0][0], "*", args[1][0], "*", args[2][0], " ) "]
    else
      false
    end
  when 'car', 'cdr', 'not', 'length', 'null?', 'reverse', 'uniq',
    'write', 'write-to-string', 'display', 'print',
    'procedure?', 'macro?', 'symbol?', 'keyword?', 'syntax?', 'core-syntax?',
    'pair?', '%list?', 'integer?', 'number?', 'string?', 'macroexpand-1',
    'to-s', 'to-i', 'nil?', 'to-list', 'to-arr',
    'intern', 'string->symbol', 'symbol->string', 'read-from-string'
    raise ArgumentError, "Error: #{origname} requires 1 argument. "  unless 1 == args.length
    [ "#{rubysym}(",              args[0],         ")" ]
  when ">", ">=", "<", "<="
    ["( ", args[0][0], origname, args[1][0], " ) "]
  when 'cons', '=', "eq?", "equal?", 'set-car!', 'set-cdr!'
    raise ArgumentError, "Error: #{origname} requires 2 arguments. " unless 2 == args.length
    [ "#{rubysym}(",            args[0], args[1], ")" ]
  else
    false
  end
end

#popCompiledLinenoObject



1285
1286
1287
1288
1289
1290
# File 'lib/nendo/ruby/evaluator.rb', line 1285

def popCompiledLineno( )
  if 1 < @compiledLinenoStack.size()
    return @compiledLinenoStack.pop()
  end
  return 0
end

#ppRubyExp(level, exp, lineno) ⇒ Object



1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
# File 'lib/nendo/ruby/evaluator.rb', line 1114

def ppRubyExp( level, exp, lineno )
  cur_lineno = (lineno - 1) * LINENO_TIMES

  first_crs = adjustLineno( cur_lineno, @compiledLineno )
  @compiledLineno += first_crs.size()

  head = [ first_crs,  sprintf( "\n#line %d curLineno=%d compiledLineno=%d\n", lineno, cur_lineno, @compiledLineno ) ]
  @compiledLineno += 2
           
  indent = @indent * level
  body = exp.map { |x|
    if Array == x.class
      ppRubyExp( level+1, x, lineno )
    else
      str = sprintf( "%s", x )
      arr = str.split( /\n/ )
      if 0 < arr.size()
        @compiledLineno += arr.size() - 1
      end

      if str.match(/embedBacktraceInfo.+;/)
        m = str.match(/^embedBacktraceInfo[(] \"([^\"]+)\", ([0-9]+).+;/)
        if m
          fn = m[1]
          cur_lineno = (m[2].to_i-1) * LINENO_TIMES
        else
          fn = ""
          cur_lineno = 0
        end
        crs = adjustLineno( cur_lineno, @compiledLineno )
        @compiledLineno += crs.size()
        @compiledLineno += 1 # #embedBacktraceInfo(...) line
        sprintf( "%s#embedBacktraceInfo  %s  %d  target=%d  cur=%d  %s \n%s%s",
                 indent, fn, cur_lineno / LINENO_TIMES,
                 @compiledLineno, cur_lineno, crs,
                 indent, str)
      elsif str == 'end'
        @compiledLineno += 1
        sprintf( "\n%s%s", indent, str )
      elsif str.match( /^[*+-]$/ )
        sprintf( "%s%s", indent, str )
      elsif str == ">" or str == ">=" or str == "<" or str == "<="
        sprintf( "%s%s", indent, str )
      elsif str.match( /^[,]/ ) or str.match( /^ = / )
        sprintf( "%s%s", indent, str )
      else
        @compiledLineno += 1
        sprintf( "\n%s%s", indent, str )
      end
    end
  }
  return head + body
end

#pushCompiledLineno(lineno) ⇒ Object



1281
1282
1283
# File 'lib/nendo/ruby/evaluator.rb', line 1281

def pushCompiledLineno(lineno)
  @compiledLinenoStack.push(lineno)
end

#separateWith(arr, str) ⇒ Object

for code generation of Ruby’s argument values in case: str = “,”

1,“2”,3

> [

  [ 1,  ","]
  ["2", ","]
  [ 3 ]
]


348
349
350
351
352
353
354
# File 'lib/nendo/ruby/evaluator.rb', line 348

def separateWith( arr, str )
  seps = []
  (arr.length-1).times {|n| seps << str }
  arr.zip( seps ).map{ |x|
    x.select { |elem| elem }
  }
end

#setArgv(argv) ⇒ Object



145
146
147
# File 'lib/nendo/ruby/evaluator.rb', line 145

def setArgv( argv )
  self.global_lisp_define( toRubySymbol( "*argv*"), argv.to_list )
end

#setDisplayErrors(flag) ⇒ Object



157
158
159
# File 'lib/nendo/ruby/evaluator.rb', line 157

def setDisplayErrors( flag )
  @displayErrorsFlag = flag
end

#setOptimizeLevel(level) ⇒ Object



149
150
151
# File 'lib/nendo/ruby/evaluator.rb', line 149

def setOptimizeLevel( level )
  @optimize_level = level
end

#toLispSymbol(name) ⇒ Object

Raises:

  • (ArgumentError)


242
243
244
245
246
247
248
249
250
251
# File 'lib/nendo/ruby/evaluator.rb', line 242

def toLispSymbol( name )
  name = name.to_s   if Symbol == name.class
  name = name.to_s   if ParsedSymbol == name.class
  raise ArgumentError, sprintf( "Error: `%s' is not a lisp symbol", name ) if not ('_' == name[0])
  name = name[1..-1]
  @char_table_ruby_to_lisp.each_pair { |key,val|
    name = name.gsub( Regexp.new( key ), val )
  }
  name
end

#toRubyArgument(origname, pred, args) ⇒ Object



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/nendo/ruby/evaluator.rb', line 257

def toRubyArgument( origname, pred, args )
  len = args.length
  num = pred.arity
  if 0 == num
    raise ArgumentError, errorMessageOf_toRubyArgument( origname, 1, num, len ) if 0 != len
    []
  elsif 0 < num
    if 0 == len
      raise ArgumentError, errorMessageOf_toRubyArgument( origname, 4, num, len )
    else
      raise ArgumentError, errorMessageOf_toRubyArgument( origname, 2, num, len ) if num != len
      args
    end
  else
    num = num.abs( )-1
    raise ArgumentError, errorMessageOf_toRubyArgument( origname, 3, num, len ) if num > len
    params = []
    rest = []
    args.each_with_index { |x,i|
      if i < num
        params << x
      else
        rest   << x
      end
    }
    result = []
    if 0 < params.length
      result = params
    end
    if 0 == rest.length
      result << Cell.new
    else
      result << rest.to_list
    end
    result
  end
end

#toRubyParameter(argform) ⇒ Object

returns [ argsyms[], string ]



510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
# File 'lib/nendo/ruby/evaluator.rb', line 510

def toRubyParameter( argform )
  argsyms = []
  locals = []
  rest = false
  if _symbol_QUMARK( argform )
    rest       = argform
  else
    argsyms    = argform.map { |x|  toRubySymbol( x.car ) }
    locals     = argsyms.clone
    if argform.lastAtom
      rest = argform.getLastAtom
    end
  end
  if rest
    rest       = toRubySymbol( rest )
    locals     << rest
    argsyms    << "*__rest__"
    [ locals, sprintf( "|%s| %s = __rest__[0] ; ", argsyms.join( "," ), rest ) ]
  else
    [ locals, sprintf( "|%s|",                     argsyms.join( "," ))        ]
  end
end

#toRubySymbol(name) ⇒ Object



209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/nendo/ruby/evaluator.rb', line 209

def toRubySymbol( name )
  if SyntacticClosure == name.class
    "_" + name.to_s
  else
    name = name.to_s   if Symbol == name.class
    name = name.to_s   if ParsedSymbol == name.class
    if 0 == name.length
      ""
    else
      name.gsub!( Regexp.new( Regexp.escape( '...' )), @char_table_lisp_to_ruby[ '...' ] )
      arr = name.gsub( /["]/, '' ).split( /[.]/ )
      tmp = arr[0]
      tmp.gsub!( /[:][:]/, "  " ) # save '::'
      @char_table_lisp_to_ruby.each_pair { |key,val|
        tmp.gsub!( Regexp.new( Regexp.escape( key )), val )
      }
      arr[0] = tmp.gsub( /[ ][ ]/, "::" )
      if arr[0].match( /^[A-Z]/ )
        # nothing to do
      elsif arr[0] == ""
        arr[0] = 'Kernel'
      else
        arr[0] = '_' + arr[0]
      end
      arr.join( "." )
    end
  end
end

#toRubyValue(val) ⇒ Object



197
198
199
200
201
202
203
204
205
206
207
# File 'lib/nendo/ruby/evaluator.rb', line 197

def toRubyValue( val )
  if NilClass == val.class
    "nil"
  elsif TrueClass == val.class
    val.to_s
  elsif FalseClass == val.class
    val.to_s
  else
    val.to_s
  end
end

#trampCall(result) ⇒ Object



295
296
297
298
299
300
# File 'lib/nendo/ruby/evaluator.rb', line 295

def trampCall( result )
  while result.class == DelayedCallPacket
    result = __send__( result.rubysym + "_METHOD", result.origname, result.pred, result.args )
  end
  result
end

#trampCallCap(sym) ⇒ Object



687
688
689
690
691
692
693
694
695
# File 'lib/nendo/ruby/evaluator.rb', line 687

def trampCallCap( sym )
  if isRubyInterface( sym )
    arr = sym.split( /[.]/ )
    arr[0] = sprintf( "trampCall(%s)", arr[0] )
    arr.join( "." )
  else
    "trampCall(" + sym + ")"
  end
end

#translate(sexpArg, locals, sourceInfo = nil) ⇒ Object

Lisp->Ruby translater

- locals is array of closure's local variable list
  when S-expression is
  (let ((a 1)
        (b 2))
    (let ((c 3))
        (print (+ a b c))))
     => locals must be  [["_a" "_b"]["_c"]] value.


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
808
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
842
843
844
845
846
847
# File 'lib/nendo/ruby/evaluator.rb', line 742

def translate( sexpArg, locals, sourceInfo = nil )
  sexp = castParsedSymbol( sexpArg )
  case sexp
  when Cell
    inv = @core_syntax_hash.invert
#        if sexp.car.to_s.match( /begin/ ) and sexp.car.to_s.match( /core/ )
#          p inv
#          p inv.keys
#          p sexp.car.class
#          p castParsedSymbol( sexp.car ).intern, inv.has_key?( castParsedSymbol( sexp.car ).intern )
#          p inv[ castParsedSymbol( sexp.car ).intern ]
#        end
    if ParsedSymbol == sexp.car.class or Symbol == sexp.car.class
      car = if inv.has_key?( castParsedSymbol( sexp.car ).intern )
              inv[ castParsedSymbol( sexp.car ).intern ]
            else
              castParsedSymbol( sexp.car )
            end
    else
      car = sexp.car
    end
    car = castParsedSymbol( car )

    if :quote == car
      genQuote( sexp.second )
    elsif :"syntax-quote" == car
      [ "Cell.new(:\"syntax-quote\", ", genQuote( sexp.cdr ), ")" ]
    elsif sexp.isDotted
      raise NameError, "Error: can't eval dotted pair."
    elsif sexp.isNull
      [ "Cell.new()" ]
    elsif isDefines( car )
      self.makeSetVariable( car, sexp.cdr, locals, sourceInfo )
    elsif :begin == car
      self.makeBegin( sexp.cdr, locals )
    elsif :lambda == car
      self.makeClosure( :lambda, sexp.cdr, locals )
    elsif :macro == car
      self.makeClosure( :macro, sexp.cdr, locals )
    elsif :"%syntax" == car
      self.makeClosure( :"%syntax", sexp.cdr, locals )
    elsif :"&block" == car
      self.makeClosure( :"&block", sexp.cdr, locals )
    elsif :if == car
      self.makeIf( sexp.cdr,    locals )
    elsif :"%let" == car
      self.makeLet( sexp.cdr,   locals )
    elsif :letrec == car
      self.makeLetrec( sexp.cdr,   locals )
    elsif :"%guard" == car
      self.makeGuard( sexp.cdr,   locals )
    elsif :"%tailcall" == car
      if sexp.cdr.car.is_a? Cell
        sexp = sexp.cdr.car
        if isDefines( sexp.car )
          translate( sexp, locals, sourceInfo )
        else
          if sexp.car.is_a? Cell
            self.apply( translate( sexp.car, locals, sourceInfo ), sexp.cdr, sexp.car.car.sourcefile, sexp.car.car.lineno, locals, sourceInfo, EXEC_TYPE_ANONYMOUS )
          else
            self.apply( sexp.car, sexp.cdr, sexp.car.sourcefile, sexp.car.lineno, locals, sourceInfo, EXEC_TYPE_TAILCALL )
          end
        end
      else
        raise RuntimeError, "Error: special form tailcall expects function call expression."
      end
    elsif Cell == sexp.car.class
      self.apply( translate( sexp.car, locals, sourceInfo ), sexp.cdr, sexp.car.car.sourcefile, sexp.car.car.lineno, locals, sourceInfo, EXEC_TYPE_ANONYMOUS )
    else
      self.apply( sexp.car, sexp.cdr, sexp.car.sourcefile, sexp.car.lineno, locals, sourceInfo, EXEC_TYPE_NORMAL )
    end
  when Array
    raise RuntimeError, "Error: can't eval unquoted vector."
  else
    case sexpArg
    when Symbol
      sym = sexp.to_s
      sym = toRubySymbol( sym )
      lispSymbolReference( sym, locals, nil, sexp.sourcefile, sexp.lineno )
    when ParsedSymbol
      sym = sexp.to_s
      sym = toRubySymbol( sym )
      lispSymbolReference( sym, locals, nil, sexpArg.sourcefile, sexpArg.lineno )
    when 1.class
      sexp.to_s
    when String, LispString
      sprintf( "\"%s\"", LispString.escape( sexp ))
    when LispRegexp
      if sexp.ignoreCase
        sprintf( "Regexp.new( \"%s\", Regexp::IGNORECASE)", sexp.escape )
      else
        sprintf( "Regexp.new( \"%s\")", sexp.escape )
      end
    when LispKeyword
      sprintf( "LispKeyword.new( \"%s\" )", sexp.key )
    when Nil
      "Nil.new"
    when TrueClass, FalseClass, NilClass  # reserved symbols
      toRubyValue( sexp )
    when SyntacticClosure
      toRubySymbol( sexp )
    else
      sexp.to_s
    end
  end
end