Ignore:
Timestamp:
Jan 21, 2018, 12:10:09 AM (6 years ago)
Author:
coas-nagasima
Message:

prototoolに関連するプロジェクトをnewlibからmuslを使うよう変更・更新
ntshellをnewlibの下位の実装から、muslのsyscallの実装に変更・更新
以下のOSSをアップデート
・mruby-1.3.0
・musl-1.1.18
・onigmo-6.1.3
・tcc-0.9.27
以下のOSSを追加
・openssl-1.1.0e
・curl-7.57.0
・zlib-1.2.11
以下のmrbgemsを追加
・iij/mruby-digest
・iij/mruby-env
・iij/mruby-errno
・iij/mruby-iijson
・iij/mruby-ipaddr
・iij/mruby-mock
・iij/mruby-require
・iij/mruby-tls-openssl

Location:
EcnlProtoTool/trunk/mruby-1.3.0
Files:
13 added
87 edited
1 moved

Legend:

Unmodified
Added
Removed
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/default.gembox

    r270 r331  
    5454  conf.gem :core => "mruby-enumerator"
    5555
    56   # Use Enumerable::Lazy class (require mruby-enumerator)
     56  # Use Enumerator::Lazy class (require mruby-enumerator)
    5757  conf.gem :core => "mruby-enum-lazy"
    5858
     
    7272  conf.gem :core => "mruby-kernel-ext"
    7373
     74  # Use class/module extension
     75  conf.gem :core => "mruby-class-ext"
     76
    7477  # Use mruby-compiler to build other mrbgems
    7578  conf.gem :core => "mruby-compiler"
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-array-ext/mrblib/array.rb

    r321 r331  
    11class Array
     2  ##
     3  # call-seq:
     4  #    Array.try_convert(obj) -> array or nil
     5  #
     6  # Tries to convert +obj+ into an array, using +to_ary+ method.
     7  # converted array or +nil+ if +obj+ cannot be converted for any reason.
     8  # This method can be used to check if an argument is an array.
     9  #
     10  #    Array.try_convert([1])   #=> [1]
     11  #    Array.try_convert("1")   #=> nil
     12  #
     13  #    if tmp = Array.try_convert(arg)
     14  #      # the argument is an array
     15  #    elsif tmp = String.try_convert(arg)
     16  #      # the argument is a string
     17  #    end
     18  #
     19  def self.try_convert(obj)
     20    if obj.respond_to?(:to_ary)
     21      obj.to_ary
     22    else
     23      nil
     24    end
     25  end
     26
    227  ##
    328  # call-seq:
     
    251276  #
    252277  #  Alternatively, if a block is given it will only be executed when an
    253   #  invalid +index+ is referenced.  Negative values of +index+ count from the
    254   #  end of the array.
     278  #  invalid +index+ is referenced.
     279  #
     280  #  Negative values of +index+ count from the end of the array.
    255281  #
    256282  #     a = [ 11, 22, 33, 44 ]
     
    710736    nil
    711737  end
     738
     739  ##
     740  #  call-seq:
     741  #     ary.to_ary -> ary
     742  #
     743  #  Returns +self+.
     744  #
     745  def to_ary
     746    self
     747  end
     748
     749  ##
     750  # call-seq:
     751  #   ary.dig(idx, ...)                 -> object
     752  #
     753  # Extracts the nested value specified by the sequence of <i>idx</i>
     754  # objects by calling +dig+ at each step, returning +nil+ if any
     755  # intermediate step is +nil+.
     756  #
     757  def dig(idx,*args)
     758    n = self[idx]
     759    if args.size > 0
     760      n&.dig(*args)
     761    else
     762      n
     763    end
     764  end
    712765end
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-array-ext/src/array.c

    r321 r331  
    1 #include "mruby.h"
    2 #include "mruby/value.h"
    3 #include "mruby/array.h"
    4 #include "mruby/range.h"
    5 #include "mruby/hash.h"
     1#include <mruby.h>
     2#include <mruby/value.h>
     3#include <mruby/array.h>
     4#include <mruby/range.h>
     5#include <mruby/hash.h>
    66
    77/*
     
    132132    if (mrb_nil_p(v)) {
    133133      mrb_raisef(mrb, E_TYPE_ERROR, "wrong element type %S at %S (expected array)",
    134         mrb_str_new_cstr(mrb,  mrb_obj_classname(mrb, RARRAY_PTR(ary)[i])),
     134        mrb_str_new_cstr(mrb,  mrb_obj_classname(mrb, ary_elt(ary, i))),
    135135        mrb_fixnum_value(i)
    136136      );
     
    150150}
    151151
     152/*
     153 *  call-seq:
     154 *     ary.slice!(index)         -> obj or nil
     155 *     ary.slice!(start, length) -> new_ary or nil
     156 *     ary.slice!(range)         -> new_ary or nil
     157 *
     158 *  Deletes the element(s) given by an +index+ (optionally up to +length+
     159 *  elements) or by a +range+.
     160 *
     161 *  Returns the deleted object (or objects), or +nil+ if the +index+ is out of
     162 *  range.
     163 *
     164 *     a = [ "a", "b", "c" ]
     165 *     a.slice!(1)     #=> "b"
     166 *     a               #=> ["a", "c"]
     167 *     a.slice!(-1)    #=> "c"
     168 *     a               #=> ["a"]
     169 *     a.slice!(100)   #=> nil
     170 *     a               #=> ["a"]
     171 */
     172
     173static mrb_value
     174mrb_ary_slice_bang(mrb_state *mrb, mrb_value self)
     175{
     176  struct RArray *a = mrb_ary_ptr(self);
     177  mrb_int i, j, k, len;
     178  mrb_value index;
     179  mrb_value val;
     180  mrb_value *ptr;
     181  mrb_value ary;
     182
     183  mrb_ary_modify(mrb, a);
     184
     185  if (mrb_get_args(mrb, "o|i", &index, &len) == 1) {
     186    switch (mrb_type(index)) {
     187    case MRB_TT_RANGE:
     188      if (mrb_range_beg_len(mrb, index, &i, &len, a->len, TRUE) == 1) {
     189        goto delete_pos_len;
     190      }
     191      else {
     192        return mrb_nil_value();
     193      }
     194    case MRB_TT_FIXNUM:
     195      val = mrb_funcall(mrb, self, "delete_at", 1, index);
     196      return val;
     197    default:
     198      val = mrb_funcall(mrb, self, "delete_at", 1, index);
     199      return val;
     200    }
     201  }
     202
     203  i = mrb_fixnum(index);
     204 delete_pos_len:
     205  if (i < 0) i += a->len;
     206  if (i < 0 || a->len < i) return mrb_nil_value();
     207  if (len < 0) return mrb_nil_value();
     208  if (a->len == i) return mrb_ary_new(mrb);
     209  if (len > a->len - i) len = a->len - i;
     210
     211  ary = mrb_ary_new_capa(mrb, len);
     212
     213  for (j = i, k = 0; k < len; ++j, ++k) {
     214    mrb_ary_push(mrb, ary, a->ptr[j]);
     215  }
     216
     217  ptr = a->ptr + i;
     218  for (j = i; j < a->len - len; ++j) {
     219    *ptr = *(ptr+len);
     220    ++ptr;
     221  }
     222
     223  mrb_ary_resize(mrb, self, a->len - len);
     224  return ary;
     225}
     226
    152227void
    153228mrb_mruby_array_ext_gem_init(mrb_state* mrb)
     
    160235  mrb_define_method(mrb, a, "values_at", mrb_ary_values_at, MRB_ARGS_ANY());
    161236  mrb_define_method(mrb, a, "to_h",   mrb_ary_to_h, MRB_ARGS_REQ(0));
     237  mrb_define_method(mrb, a, "slice!", mrb_ary_slice_bang,   MRB_ARGS_ANY());
    162238}
    163239
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-array-ext/test/array.rb

    r321 r331  
    11##
    22# Array(Ext) Test
     3
     4assert("Array.try_convert") do
     5  assert_nil Array.try_convert(0)
     6  assert_nil Array.try_convert(nil)
     7  assert_equal [], Array.try_convert([])
     8  assert_equal [1,2,3], Array.try_convert([1,2,3])
     9end
    310
    411assert("Array#assoc") do
     
    295302end
    296303
     304assert('Array#to_h (Modified)') do
     305  class A
     306    def to_ary
     307      $a.clear
     308      nil
     309    end
     310  end
     311  $a = [A.new]
     312  assert_raise(TypeError) { $a.to_h }
     313end
     314
    297315assert("Array#index (block)") do
    298316  assert_nil (1..10).to_a.index { |i| i % 5 == 0 and i % 7 == 0 }
    299317  assert_equal 34, (1..100).to_a.index { |i| i % 5 == 0 and i % 7 == 0 }
    300318end
     319
     320assert("Array#to_ary") do
     321  assert_equal [], [].to_ary
     322  assert_equal [1,2,3], [1,2,3].to_ary
     323end
     324
     325assert("Array#dig") do
     326  h = [[[1]], 0]
     327  assert_equal(1, h.dig(0, 0, 0))
     328  assert_nil(h.dig(2, 0))
     329  assert_raise(TypeError) {h.dig(:a)}
     330end
     331
     332assert("Array#slice!") do
     333  a = [1, 2, 3]
     334  b = a.slice!(0)
     335  c = [1, 2, 3, 4, 5]
     336  d = c.slice!(0, 2)
     337  e = [1, 2, 3, 4, 5]
     338  f = e.slice!(1..3)
     339  g = [1, 2, 3]
     340  h = g.slice!(-1)
     341  i = [1, 2, 3]
     342  j = i.slice!(0, -1)
     343
     344  assert_equal(a, [2, 3])
     345  assert_equal(b, 1)
     346  assert_equal(c, [3, 4, 5])
     347  assert_equal(d, [1, 2])
     348  assert_equal(e, [1, 5])
     349  assert_equal(f, [2, 3, 4])
     350  assert_equal(g, [1, 2])
     351  assert_equal(h, 3)
     352  assert_equal(i, [1, 2, 3])
     353  assert_equal(j, nil)
     354end
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-debugger/bintest/mrdb.rb

    r321 r331  
    1515    # compile
    1616    `./bin/mrbc -g -o "#{bin.path}" "#{script.path}"`
    17    
     17
    1818    # add mrdb quit
    1919    testcase << {:cmd=>"quit"}
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-debugger/bintest/print.rb

    r321 r331  
    1414    # compile
    1515    `./bin/mrbc -g -o "#{bin.path}" "#{script.path}"`
    16    
     16
    1717    # add mrdb quit
    1818    testcase << {:cmd=>"quit"}
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-debugger/tools/mrdb/apibreak.c

    r321 r331  
    55
    66#include <string.h>
    7 #include "mruby.h"
    8 #include "mruby/irep.h"
     7#include <mruby.h>
     8#include <mruby/irep.h>
    99#include "mrdb.h"
    10 #include "mruby/debug.h"
    11 #include "mruby/opcode.h"
    12 #include "mruby/class.h"
    13 #include "mruby/proc.h"
    14 #include "mruby/variable.h"
     10#include <mruby/debug.h>
     11#include <mruby/opcode.h>
     12#include <mruby/class.h>
     13#include <mruby/proc.h>
     14#include <mruby/variable.h>
    1515#include "mrdberror.h"
    1616#include "apibreak.h"
     
    2121
    2222static uint16_t
    23 check_lineno( mrb_irep_debug_info_file *info_file, uint16_t lineno )
     23check_lineno(mrb_irep_debug_info_file *info_file, uint16_t lineno)
    2424{
    2525  uint32_t count = info_file->line_entry_count;
    2626  uint16_t l_idx;
    2727
    28   if( info_file->line_type == mrb_debug_line_ary ) {
     28  if (info_file->line_type == mrb_debug_line_ary) {
    2929    for (l_idx = 0; l_idx < count; ++l_idx) {
    30       if(lineno == info_file->lines.ary[l_idx]) {
     30      if (lineno == info_file->lines.ary[l_idx]) {
    3131        return lineno;
    3232      }
    3333    }
    34   } else {
     34  }
     35  else {
    3536    for (l_idx = 0; l_idx < count; ++l_idx) {
    36       if(lineno == info_file->lines.flat_map[l_idx].line) {
     37      if (lineno == info_file->lines.flat_map[l_idx].line) {
    3738        return lineno;
    3839      }
     
    4445
    4546static int32_t
    46 get_break_index( mrb_debug_context *dbg, int32_t bpno )
     47get_break_index(mrb_debug_context *dbg, uint32_t bpno)
    4748{
    4849  uint32_t i;
     
    5152
    5253  for(i = 0 ; i < dbg->bpnum; i++) {
    53     if(dbg->bp[i].bpno == bpno) {
     54    if (dbg->bp[i].bpno == bpno) {
    5455      hit = TRUE;
    5556      index = i;
     
    5859  }
    5960
    60   if(hit == FALSE) {
     61  if (hit == FALSE) {
    6162    return MRB_DEBUG_BREAK_INVALID_NO;
    6263  }
     
    6667
    6768static void
    68 free_breakpoint( mrb_state *mrb, mrb_debug_breakpoint *bp )
     69free_breakpoint(mrb_state *mrb, mrb_debug_breakpoint *bp)
    6970{
    7071  switch(bp->type) {
     
    7475    case MRB_DEBUG_BPTYPE_METHOD:
    7576      mrb_free(mrb, (void*)bp->point.methodpoint.method_name);
    76       if(bp->point.methodpoint.class_name != NULL) {
     77      if (bp->point.methodpoint.class_name != NULL) {
    7778        mrb_free(mrb, (void*)bp->point.methodpoint.class_name);
    7879      }
     
    8485
    8586static uint16_t
    86 check_file_lineno( struct mrb_irep *irep, const char *file, uint16_t lineno )
     87check_file_lineno(struct mrb_irep *irep, const char *file, uint16_t lineno)
    8788{
    8889  mrb_irep_debug_info_file *info_file;
     
    9495  for (f_idx = 0; f_idx < irep->debug_info->flen; ++f_idx) {
    9596    info_file = irep->debug_info->files[f_idx];
    96     if(!strcmp(info_file->filename, file)) {
     97    if (!strcmp(info_file->filename, file)) {
    9798      result = MRB_DEBUG_BP_FILE_OK;
    9899
    99       fix_lineno = check_lineno( info_file, lineno );
    100       if(fix_lineno != 0) {
     100      fix_lineno = check_lineno(info_file, lineno);
     101      if (fix_lineno != 0) {
    101102        return result | MRB_DEBUG_BP_LINENO_OK;
    102103      }
    103104    }
    104     for ( i=0; i < irep->rlen; ++i ) {
     105    for (i=0; i < irep->rlen; ++i) {
    105106      result  |= check_file_lineno(irep->reps[i], file, lineno);
    106       if(result == (MRB_DEBUG_BP_FILE_OK | MRB_DEBUG_BP_LINENO_OK)) {
     107      if (result == (MRB_DEBUG_BP_FILE_OK | MRB_DEBUG_BP_LINENO_OK)) {
    107108        return result;
    108109      }
     
    113114
    114115static const char*
    115 get_class_name( mrb_state *mrb, struct RClass *class_obj )
     116get_class_name(mrb_state *mrb, struct RClass *class_obj)
    116117{
    117118  struct RClass *outer;
     
    124125
    125126static int32_t
    126 compare_break_method( mrb_state *mrb, mrb_debug_breakpoint *bp, struct RClass *class_obj, mrb_sym method_sym, mrb_bool* isCfunc )
     127compare_break_method(mrb_state *mrb, mrb_debug_breakpoint *bp, struct RClass *class_obj, mrb_sym method_sym, mrb_bool* isCfunc)
    127128{
    128129  const char* class_name;
     
    138139
    139140  method_p = &bp->point.methodpoint;
    140   if(strcmp(method_p->method_name, method_name) == 0) {
     141  if (strcmp(method_p->method_name, method_name) == 0) {
    141142    class_name = get_class_name(mrb, class_obj);
    142     if(class_name == NULL) {
    143       if(method_p->class_name == NULL) {
     143    if (class_name == NULL) {
     144      if (method_p->class_name == NULL) {
    144145        return bp->bpno;
    145146      }
    146147    }
    147     else if(method_p->class_name != NULL) {
     148    else if (method_p->class_name != NULL) {
    148149      m = mrb_method_search_vm(mrb, &class_obj, method_sym);
    149       if(m == NULL) {
     150      if (m == NULL) {
    150151        return MRB_DEBUG_OK;
    151152      }
    152       if(MRB_PROC_CFUNC_P(m)) {
     153      if (MRB_PROC_CFUNC_P(m)) {
    153154        *isCfunc = TRUE;
    154155      }
    155156
    156157      is_defined = mrb_class_defined(mrb, method_p->class_name);
    157       if(is_defined == FALSE) {
     158      if (is_defined == FALSE) {
    158159        return MRB_DEBUG_OK;
    159160      }
     
    162163      ssym = mrb_symbol(mrb_check_intern_cstr(mrb, method_p->method_name));
    163164      m = mrb_method_search_vm(mrb, &sc, ssym);
    164       if(m == NULL) {
     165      if (m == NULL) {
    165166        return MRB_DEBUG_OK;
    166167      }
     
    168169      class_name = get_class_name(mrb, class_obj);
    169170      sn = get_class_name(mrb, sc);
    170       if(strcmp(sn, class_name) == 0) {
     171      if (strcmp(sn, class_name) == 0) {
    171172        return bp->bpno;
    172173      }
     
    177178
    178179int32_t
    179 mrb_debug_set_break_line( mrb_state *mrb, mrb_debug_context *dbg, const char *file, uint16_t lineno)
     180mrb_debug_set_break_line(mrb_state *mrb, mrb_debug_context *dbg, const char *file, uint16_t lineno)
    180181{
    181182  int32_t index;
     
    183184  uint16_t result;
    184185
    185   if((mrb == NULL)||(dbg == NULL)||(file == NULL)) {
    186     return MRB_DEBUG_INVALID_ARGUMENT;
    187   }
    188 
    189   if(dbg->bpnum >= MAX_BREAKPOINT) {
     186  if ((mrb == NULL)||(dbg == NULL)||(file == NULL)) {
     187    return MRB_DEBUG_INVALID_ARGUMENT;
     188  }
     189
     190  if (dbg->bpnum >= MAX_BREAKPOINT) {
    190191    return MRB_DEBUG_BREAK_NUM_OVER;
    191192  }
    192193
    193   if(dbg->next_bpno > MAX_BREAKPOINTNO) {
     194  if (dbg->next_bpno > MAX_BREAKPOINTNO) {
    194195    return MRB_DEBUG_BREAK_NO_OVER;
    195196  }
    196197
    197198  /* file and lineno check (line type mrb_debug_line_ary only.) */
    198   result = check_file_lineno( dbg->root_irep, file, lineno );
    199   if(result == 0) {
     199  result = check_file_lineno(dbg->root_irep, file, lineno);
     200  if (result == 0) {
    200201    return MRB_DEBUG_BREAK_INVALID_FILE;
    201   }else if(result == MRB_DEBUG_BP_FILE_OK) {
     202  }
     203  else if (result == MRB_DEBUG_BP_FILE_OK) {
    202204    return MRB_DEBUG_BREAK_INVALID_LINENO;
    203   } 
     205  }
    204206
    205207  set_file = mrb_malloc(mrb, strlen(file) + 1);
     
    221223
    222224int32_t
    223 mrb_debug_set_break_method( mrb_state *mrb, mrb_debug_context *dbg, const char *class_name, const char *method_name )
     225mrb_debug_set_break_method(mrb_state *mrb, mrb_debug_context *dbg, const char *class_name, const char *method_name)
    224226{
    225227  int32_t index;
     
    227229  char* set_method;
    228230
    229   if((mrb == NULL) || (dbg == NULL) || (method_name == NULL)) {
    230     return MRB_DEBUG_INVALID_ARGUMENT;
    231   }
    232 
    233   if(dbg->bpnum >= MAX_BREAKPOINT) {
     231  if ((mrb == NULL) || (dbg == NULL) || (method_name == NULL)) {
     232    return MRB_DEBUG_INVALID_ARGUMENT;
     233  }
     234
     235  if (dbg->bpnum >= MAX_BREAKPOINT) {
    234236    return MRB_DEBUG_BREAK_NUM_OVER;
    235237  }
    236238
    237   if(dbg->next_bpno > MAX_BREAKPOINTNO) {
     239  if (dbg->next_bpno > MAX_BREAKPOINTNO) {
    238240    return MRB_DEBUG_BREAK_NO_OVER;
    239241  }
    240242
    241   if(class_name != NULL) {
     243  if (class_name != NULL) {
    242244    set_class = mrb_malloc(mrb, strlen(class_name) + 1);
    243245    strncpy(set_class, class_name, strlen(class_name) + 1);
     
    264266
    265267int32_t
    266 mrb_debug_get_breaknum( mrb_state *mrb, mrb_debug_context *dbg )
    267 {
    268   if((mrb == NULL) || (dbg == NULL)) {
     268mrb_debug_get_breaknum(mrb_state *mrb, mrb_debug_context *dbg)
     269{
     270  if ((mrb == NULL) || (dbg == NULL)) {
    269271    return MRB_DEBUG_INVALID_ARGUMENT;
    270272  }
     
    273275}
    274276
    275 int32_t 
    276 mrb_debug_get_break_all( mrb_state *mrb, mrb_debug_context *dbg, uint32_t size, mrb_debug_breakpoint *bp )
     277int32_t
     278mrb_debug_get_break_all(mrb_state *mrb, mrb_debug_context *dbg, uint32_t size, mrb_debug_breakpoint *bp)
    277279{
    278280  uint32_t get_size = 0;
    279281
    280   if((mrb == NULL) || (dbg == NULL) || (bp == NULL)) {
    281     return MRB_DEBUG_INVALID_ARGUMENT;
    282   }
    283 
    284   if(dbg->bpnum >= size) {
     282  if ((mrb == NULL) || (dbg == NULL) || (bp == NULL)) {
     283    return MRB_DEBUG_INVALID_ARGUMENT;
     284  }
     285
     286  if (dbg->bpnum >= size) {
    285287    get_size = size;
    286288  }
     
    295297
    296298int32_t
    297 mrb_debug_get_break( mrb_state *mrb, mrb_debug_context *dbg, uint32_t bpno, mrb_debug_breakpoint *bp )
    298 {
    299   uint32_t index;
    300 
    301   if((mrb == NULL) || (dbg == NULL) || (bp == NULL)) {
     299mrb_debug_get_break(mrb_state *mrb, mrb_debug_context *dbg, uint32_t bpno, mrb_debug_breakpoint *bp)
     300{
     301  int32_t index;
     302
     303  if ((mrb == NULL) || (dbg == NULL) || (bp == NULL)) {
    302304    return MRB_DEBUG_INVALID_ARGUMENT;
    303305  }
    304306
    305307  index = get_break_index(dbg, bpno);
    306   if(index == MRB_DEBUG_BREAK_INVALID_NO) {
     308  if (index == MRB_DEBUG_BREAK_INVALID_NO) {
    307309    return MRB_DEBUG_BREAK_INVALID_NO;
    308310  }
     
    316318}
    317319
    318 int32_t 
    319 mrb_debug_delete_break( mrb_state *mrb, mrb_debug_context *dbg, uint32_t bpno )
     320int32_t
     321mrb_debug_delete_break(mrb_state *mrb, mrb_debug_context *dbg, uint32_t bpno)
    320322{
    321323  uint32_t i;
    322324  int32_t index;
    323325
    324   if((mrb == NULL) ||(dbg == NULL)) {
     326  if ((mrb == NULL) ||(dbg == NULL)) {
    325327    return MRB_DEBUG_INVALID_ARGUMENT;
    326328  }
    327329
    328330  index = get_break_index(dbg, bpno);
    329   if(index == MRB_DEBUG_BREAK_INVALID_NO) {
     331  if (index == MRB_DEBUG_BREAK_INVALID_NO) {
    330332    return MRB_DEBUG_BREAK_INVALID_NO;
    331333  }
     
    334336
    335337  for(i = index ; i < dbg->bpnum; i++) {
    336     if((i + 1) == dbg->bpnum) {
     338    if ((i + 1) == dbg->bpnum) {
    337339      memset(&dbg->bp[i], 0, sizeof(mrb_debug_breakpoint));
    338340    }
     
    347349}
    348350
    349 int32_t 
    350 mrb_debug_delete_break_all( mrb_state *mrb, mrb_debug_context *dbg )
    351 {
    352   uint32_t i;
    353 
    354   if((mrb == NULL) || (dbg == NULL)) {
     351int32_t
     352mrb_debug_delete_break_all(mrb_state *mrb, mrb_debug_context *dbg)
     353{
     354  uint32_t i;
     355
     356  if ((mrb == NULL) || (dbg == NULL)) {
    355357    return MRB_DEBUG_INVALID_ARGUMENT;
    356358  }
     
    365367}
    366368
    367 int32_t 
    368 mrb_debug_enable_break( mrb_state *mrb, mrb_debug_context *dbg, uint32_t bpno )
     369int32_t
     370mrb_debug_enable_break(mrb_state *mrb, mrb_debug_context *dbg, uint32_t bpno)
    369371{
    370372  int32_t index = 0;
    371373
    372   if((mrb == NULL) || (dbg == NULL)) {
     374  if ((mrb == NULL) || (dbg == NULL)) {
    373375    return MRB_DEBUG_INVALID_ARGUMENT;
    374376  }
    375377
    376378  index = get_break_index(dbg, bpno);
    377   if(index == MRB_DEBUG_BREAK_INVALID_NO) {
     379  if (index == MRB_DEBUG_BREAK_INVALID_NO) {
    378380    return MRB_DEBUG_BREAK_INVALID_NO;
    379381  }
     
    385387
    386388int32_t
    387 mrb_debug_enable_break_all( mrb_state *mrb, mrb_debug_context *dbg )
    388 {
    389   uint32_t i;
    390 
    391   if((mrb == NULL) || (dbg == NULL)) {
     389mrb_debug_enable_break_all(mrb_state *mrb, mrb_debug_context *dbg)
     390{
     391  uint32_t i;
     392
     393  if ((mrb == NULL) || (dbg == NULL)) {
    392394    return MRB_DEBUG_INVALID_ARGUMENT;
    393395  }
     
    400402}
    401403
    402 int32_t 
    403 mrb_debug_disable_break( mrb_state *mrb, mrb_debug_context *dbg, uint32_t bpno )
     404int32_t
     405mrb_debug_disable_break(mrb_state *mrb, mrb_debug_context *dbg, uint32_t bpno)
    404406{
    405407  int32_t index = 0;
    406408
    407   if((mrb == NULL) || (dbg == NULL)) {
     409  if ((mrb == NULL) || (dbg == NULL)) {
    408410    return MRB_DEBUG_INVALID_ARGUMENT;
    409411  }
    410412
    411413  index = get_break_index(dbg, bpno);
    412   if(index == MRB_DEBUG_BREAK_INVALID_NO) {
     414  if (index == MRB_DEBUG_BREAK_INVALID_NO) {
    413415    return MRB_DEBUG_BREAK_INVALID_NO;
    414416  }
     
    419421}
    420422
    421 int32_t 
    422 mrb_debug_disable_break_all( mrb_state *mrb, mrb_debug_context *dbg )
    423 {
    424   uint32_t i;
    425 
    426   if((mrb == NULL) || (dbg == NULL)) {
     423int32_t
     424mrb_debug_disable_break_all(mrb_state *mrb, mrb_debug_context *dbg)
     425{
     426  uint32_t i;
     427
     428  if ((mrb == NULL) || (dbg == NULL)) {
    427429    return MRB_DEBUG_INVALID_ARGUMENT;
    428430  }
     
    436438
    437439static mrb_bool
    438 check_start_pc_for_line( mrb_irep *irep, mrb_code *pc, uint16_t line )
    439 {
    440   if( pc > irep->iseq ) {
    441     if( line == mrb_debug_get_line(irep, (uint32_t)(pc - irep->iseq - 1))) {
     440check_start_pc_for_line(mrb_irep *irep, mrb_code *pc, uint16_t line)
     441{
     442  if (pc > irep->iseq) {
     443    if (line == mrb_debug_get_line(irep, (uint32_t)(pc - irep->iseq - 1))) {
    442444      return FALSE;
    443445    }
     
    447449
    448450int32_t
    449 mrb_debug_check_breakpoint_line( mrb_state *mrb, mrb_debug_context *dbg, const char *file, uint16_t line )
     451mrb_debug_check_breakpoint_line(mrb_state *mrb, mrb_debug_context *dbg, const char *file, uint16_t line)
    450452{
    451453  mrb_debug_breakpoint *bp;
    452454  mrb_debug_linepoint *line_p;
    453   int i;
    454 
    455   if((mrb == NULL) || (dbg == NULL) || (file == NULL) || (line <= 0)) {
    456     return MRB_DEBUG_INVALID_ARGUMENT;
    457   }
    458 
    459   if(!check_start_pc_for_line(dbg->irep, dbg->pc, line)) {
     455  uint32_t i;
     456
     457  if ((mrb == NULL) || (dbg == NULL) || (file == NULL) || (line <= 0)) {
     458    return MRB_DEBUG_INVALID_ARGUMENT;
     459  }
     460
     461  if (!check_start_pc_for_line(dbg->irep, dbg->pc, line)) {
    460462    return MRB_DEBUG_OK;
    461463  }
     
    465467    switch (bp->type) {
    466468      case MRB_DEBUG_BPTYPE_LINE:
    467         if(bp->enable == TRUE) {
     469        if (bp->enable == TRUE) {
    468470          line_p = &bp->point.linepoint;
    469           if((strcmp(line_p->file, file) == 0) && (line_p->lineno == line)) {
     471          if ((strcmp(line_p->file, file) == 0) && (line_p->lineno == line)) {
    470472            return bp->bpno;
    471473          }
     
    484486
    485487
    486 int32_t 
    487 mrb_debug_check_breakpoint_method( mrb_state *mrb, mrb_debug_context *dbg, struct RClass *class_obj, mrb_sym method_sym, mrb_bool* isCfunc )
     488int32_t
     489mrb_debug_check_breakpoint_method(mrb_state *mrb, mrb_debug_context *dbg, struct RClass *class_obj, mrb_sym method_sym, mrb_bool* isCfunc)
    488490{
    489491  mrb_debug_breakpoint *bp;
    490492  int32_t bpno;
    491   int i;
    492 
    493   if((mrb == NULL) || (dbg == NULL) || (class_obj == NULL)) {
     493  uint32_t i;
     494
     495  if ((mrb == NULL) || (dbg == NULL) || (class_obj == NULL)) {
    494496    return MRB_DEBUG_INVALID_ARGUMENT;
    495497  }
     
    497499  bp = dbg->bp;
    498500  for(i=0; i<dbg->bpnum; i++) {
    499     if(bp->type == MRB_DEBUG_BPTYPE_METHOD) {
    500       if(bp->enable == TRUE) {
     501    if (bp->type == MRB_DEBUG_BPTYPE_METHOD) {
     502      if (bp->enable == TRUE) {
    501503        bpno = compare_break_method(mrb, bp, class_obj, method_sym, isCfunc);
    502         if(bpno > 0) {
     504        if (bpno > 0) {
    503505          return bpno;
    504506        }
    505507      }
    506508    }
    507     else if(bp->type == MRB_DEBUG_BPTYPE_NONE) {
     509    else if (bp->type == MRB_DEBUG_BPTYPE_NONE) {
    508510      break;
    509511    }
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-debugger/tools/mrdb/apibreak.h

    r321 r331  
    77#define APIBREAK_H_
    88
    9 #include "mruby.h"
     9#include <mruby.h>
    1010#include "mrdb.h"
    1111
    12 int32_t mrb_debug_set_break_line( mrb_state *, mrb_debug_context *, const char *, uint16_t );
    13 int32_t mrb_debug_set_break_method( mrb_state *, mrb_debug_context *, const char *, const char * );
    14 int32_t mrb_debug_get_breaknum( mrb_state *, mrb_debug_context * );
    15 int32_t mrb_debug_get_break_all( mrb_state *, mrb_debug_context *, uint32_t, mrb_debug_breakpoint bp[]);
    16 int32_t mrb_debug_get_break( mrb_state *, mrb_debug_context *, uint32_t, mrb_debug_breakpoint * );
    17 int32_t mrb_debug_delete_break( mrb_state *, mrb_debug_context *, uint32_t );
    18 int32_t mrb_debug_delete_break_all( mrb_state *, mrb_debug_context * );
    19 int32_t mrb_debug_enable_break( mrb_state *, mrb_debug_context *, uint32_t );
    20 int32_t mrb_debug_enable_break_all( mrb_state *, mrb_debug_context * );
    21 int32_t mrb_debug_disable_break( mrb_state *, mrb_debug_context *, uint32_t );
    22 int32_t mrb_debug_disable_break_all( mrb_state *, mrb_debug_context * );
    23 int32_t mrb_debug_check_breakpoint_line( mrb_state *, mrb_debug_context *, const char *, uint16_t );
    24 int32_t mrb_debug_check_breakpoint_method( mrb_state *, mrb_debug_context *, struct RClass *, mrb_sym, mrb_bool* );
     12int32_t mrb_debug_set_break_line(mrb_state *, mrb_debug_context *, const char *, uint16_t);
     13int32_t mrb_debug_set_break_method(mrb_state *, mrb_debug_context *, const char *, const char *);
     14int32_t mrb_debug_get_breaknum(mrb_state *, mrb_debug_context *);
     15int32_t mrb_debug_get_break_all(mrb_state *, mrb_debug_context *, uint32_t, mrb_debug_breakpoint bp[]);
     16int32_t mrb_debug_get_break(mrb_state *, mrb_debug_context *, uint32_t, mrb_debug_breakpoint *);
     17int32_t mrb_debug_delete_break(mrb_state *, mrb_debug_context *, uint32_t);
     18int32_t mrb_debug_delete_break_all(mrb_state *, mrb_debug_context *);
     19int32_t mrb_debug_enable_break(mrb_state *, mrb_debug_context *, uint32_t);
     20int32_t mrb_debug_enable_break_all(mrb_state *, mrb_debug_context *);
     21int32_t mrb_debug_disable_break(mrb_state *, mrb_debug_context *, uint32_t);
     22int32_t mrb_debug_disable_break_all(mrb_state *, mrb_debug_context *);
     23int32_t mrb_debug_check_breakpoint_line(mrb_state *, mrb_debug_context *, const char *, uint16_t);
     24int32_t mrb_debug_check_breakpoint_method(mrb_state *, mrb_debug_context *, struct RClass *, mrb_sym, mrb_bool*);
    2525
    2626#endif /* APIBREAK_H_ */
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-debugger/tools/mrdb/apilist.c

    r321 r331  
    1010#include "mrdberror.h"
    1111#include "apilist.h"
    12 #include "mruby/compile.h"
    13 #include "mruby/irep.h"
    14 #include "mruby/debug.h"
     12#include <mruby/compile.h>
     13#include <mruby/irep.h>
     14#include <mruby/debug.h>
    1515
    1616#define LINE_BUF_SIZE MAX_COMMAND_LINE
     
    7272
    7373  p = strrchr(path, '/');
    74   len = p != NULL ? p - path : strlen(path);
     74  len = p != NULL ? (size_t)(p - path) : strlen(path);
    7575
    7676  dir = mrb_malloc(mrb, len + 1);
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-debugger/tools/mrdb/apilist.h

    r321 r331  
    66#define APILIST_H_
    77
    8 #include "mruby.h"
     8#include <mruby.h>
    99#include "mrdb.h"
    1010
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-debugger/tools/mrdb/apiprint.c

    r321 r331  
    66#include <string.h>
    77#include "mrdb.h"
    8 #include "mruby/value.h"
    9 #include "mruby/class.h"
    10 #include "mruby/compile.h"
    11 #include "mruby/error.h"
    12 #include "mruby/numeric.h"
    13 #include "mruby/string.h"
     8#include <mruby/value.h>
     9#include <mruby/class.h>
     10#include <mruby/compile.h>
     11#include <mruby/error.h>
     12#include <mruby/numeric.h>
     13#include <mruby/string.h>
    1414#include "apiprint.h"
    1515
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-debugger/tools/mrdb/apiprint.h

    r321 r331  
    66#define APIPRINT_H_
    77
    8 #include "mruby.h"
     8#include <mruby.h>
    99#include "mrdb.h"
    1010
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-debugger/tools/mrdb/cmdbreak.c

    r321 r331  
    66#include <ctype.h>
    77#include <string.h>
    8 #include "mruby.h"
    9 #include "mruby/dump.h"
    10 #include "mruby/debug.h"
    11 #include "mruby/string.h"
     8#include <mruby.h>
     9#include <mruby/dump.h>
     10#include <mruby/debug.h>
     11#include <mruby/string.h>
    1212#include "mrdb.h"
    1313#include "mrdberror.h"
     
    7171  uint32_t l;
    7272
    73   if((*ps == '0')||(strlen(ps) >= BPNO_LETTER_NUM)) {
     73  if ((*ps == '0')||(strlen(ps) >= BPNO_LETTER_NUM)) {
    7474    return 0;
    7575  }
    7676
    77   while( !(ISBLANK(*ps)||ISCNTRL(*ps)) ) {
    78     if(!ISDIGIT(*ps)) {
     77  while (!(ISBLANK(*ps)||ISCNTRL(*ps))) {
     78    if (!ISDIGIT(*ps)) {
    7979      return 0;
    8080    }
     
    9191  int32_t ret = MRB_DEBUG_OK;
    9292
    93   if(mrdb->wcnt == 1) {
     93  if (mrdb->wcnt == 1) {
    9494    ret = func(mrb, mrdb->dbg);
    9595    print_api_common_error(ret);
     
    110110    ps = mrdb->words[i];
    111111    bpno = parse_breakpoint_no(ps);
    112     if(bpno == 0) {
     112    if (bpno == 0) {
    113113      printf(BREAK_ERR_MSG_INVALIDBPNO, ps);
    114114      break;
    115115    }
    116116    ret = func(mrb, mrdb->dbg, (uint32_t)bpno);
    117     if(ret == MRB_DEBUG_BREAK_INVALID_NO) {
     117    if (ret == MRB_DEBUG_BREAK_INVALID_NO) {
    118118      printf(BREAK_ERR_MSG_NOBPNO, bpno);
    119119    }
    120     else if(ret != MRB_DEBUG_OK) {
     120    else if (ret != MRB_DEBUG_OK) {
    121121      print_api_common_error(ret);
    122122    }
     
    129129  char* ps = args;
    130130
    131   if(ISBLANK(*ps)||ISCNTRL(*ps)) {
     131  if (ISBLANK(*ps)||ISCNTRL(*ps)) {
    132132    puts(BREAK_ERR_MSG_BLANK);
    133133    return MRB_DEBUG_BPTYPE_NONE;
    134134  }
    135135
    136   if(!ISDIGIT(*ps)) {
     136  if (!ISDIGIT(*ps)) {
    137137    return MRB_DEBUG_BPTYPE_METHOD;
    138138  }
    139139
    140   while( !(ISBLANK(*ps)||ISCNTRL(*ps)) ) {
    141     if(!ISDIGIT(*ps)) {
     140  while (!(ISBLANK(*ps)||ISCNTRL(*ps))) {
     141    if (!ISDIGIT(*ps)) {
    142142      printf(BREAK_ERR_MSG_INVALIDSTR, args);
    143143      return MRB_DEBUG_BPTYPE_NONE;
     
    146146  }
    147147
    148   if((*args == '0')||(strlen(args) >= LINENO_MAX_DIGIT)) {
     148  if ((*args == '0')||(strlen(args) >= LINENO_MAX_DIGIT)) {
    149149    puts(BREAK_ERR_MSG_RANGEOVER);
    150150    return MRB_DEBUG_BPTYPE_NONE;
     
    159159  const char* enable_letter[] = {BREAK_INFO_MSG_DISABLE, BREAK_INFO_MSG_ENABLE};
    160160
    161   if(bp->type == MRB_DEBUG_BPTYPE_LINE) {
     161  if (bp->type == MRB_DEBUG_BPTYPE_LINE) {
    162162    printf(BREAK_INFO_MSG_LINEBREAK,
    163163      bp->bpno, enable_letter[bp->enable], bp->point.linepoint.file, bp->point.linepoint.lineno);
    164164  }
    165165  else {
    166     if(bp->point.methodpoint.class_name == NULL) {
     166    if (bp->point.methodpoint.class_name == NULL) {
    167167      printf(BREAK_INFO_MSG_METHODBREAK_NOCLASS,
    168168        bp->bpno, enable_letter[bp->enable], bp->point.methodpoint.method_name);
     
    184184
    185185  bpnum = mrb_debug_get_breaknum(mrb, mrdb->dbg);
    186   if(bpnum < 0) {
     186  if (bpnum < 0) {
    187187    print_api_common_error(bpnum);
    188188    return;
    189189  }
    190   else if(bpnum == 0) {
     190  else if (bpnum == 0) {
    191191    puts(BREAK_ERR_MSG_NOBPNO_INFOALL);
    192192    return;
     
    195195
    196196  ret = mrb_debug_get_break_all(mrb, mrdb->dbg, (uint32_t)bpnum, bp_list);
    197   if(ret < 0) {
     197  if (ret < 0) {
    198198    print_api_common_error(ret);
    199199    return;
     
    220220    ps = mrdb->words[i];
    221221    bpno = parse_breakpoint_no(ps);
    222     if(bpno == 0) {
     222    if (bpno == 0) {
    223223      puts(BREAK_ERR_MSG_INVALIDBPNO_INFO);
    224224      break;
     
    226226
    227227    ret = mrb_debug_get_break(mrb, mrdb->dbg, bpno, &bp);
    228     if(ret == MRB_DEBUG_BREAK_INVALID_NO) {
     228    if (ret == MRB_DEBUG_BREAK_INVALID_NO) {
    229229      printf(BREAK_ERR_MSG_NOBPNO_INFO, bpno);
    230230      break;
    231231    }
    232     else if(ret != MRB_DEBUG_OK) {
     232    else if (ret != MRB_DEBUG_OK) {
    233233      print_api_common_error(ret);
    234234      break;
    235235    }
    236     else if(isFirst == TRUE) {
     236    else if (isFirst == TRUE) {
    237237      isFirst = FALSE;
    238238      puts(BREAK_INFO_MSG_HEADER);
     
    251251  uint32_t l;
    252252
    253   if(mrdb->wcnt <= 1) {
     253  if (mrdb->wcnt <= 1) {
    254254    puts(BREAK_ERR_MSG_BLANK);
    255255    return MRB_DEBUG_BPTYPE_NONE;
     
    257257
    258258  args = mrdb->words[1];
    259   if((body = strrchr(args, ':')) == NULL) {
     259  if ((body = strrchr(args, ':')) == NULL) {
    260260    body = args;
    261261    type = check_bptype(body);
    262   } else {
    263     if(body == args) {
     262  }
     263  else {
     264    if (body == args) {
    264265      printf(BREAK_ERR_MSG_INVALIDSTR, args);
    265266      return MRB_DEBUG_BPTYPE_NONE;
     
    272273    case MRB_DEBUG_BPTYPE_LINE:
    273274      STRTOUL(l, body);
    274       if( l <= 65535 ) {
     275      if (l <= 65535) {
    275276        *line = l;
    276277        *file = (body == args)? mrb_debug_get_filename(dbg->irep, (uint32_t)(dbg->pc - dbg->irep->iseq)): args;
    277       } else {
     278      }
     279      else {
    278280        puts(BREAK_ERR_MSG_RANGEOVER);
    279281        type = MRB_DEBUG_BPTYPE_NONE;
     
    281283      break;
    282284    case MRB_DEBUG_BPTYPE_METHOD:
    283       if(body == args) {
     285      if (body == args) {
    284286        /* method only */
    285         if( ISUPPER(*body)||ISLOWER(*body)||(*body == '_') ) {
     287        if (ISUPPER(*body)||ISLOWER(*body)||(*body == '_')) {
    286288          *method = body;
    287289          *cname = NULL;
    288         } else {
     290        }
     291        else {
    289292          printf(BREAK_ERR_MSG_INVALIDMETHOD, args);
    290293          type = MRB_DEBUG_BPTYPE_NONE;
    291294        }
    292       } else {
    293         if( ISUPPER(*args) ) {
     295      }
     296      else {
     297        if (ISUPPER(*args)) {
    294298          switch(*body) {
    295299            case '@': case '$': case '?': case '.': case ',': case ':':
     
    303307            break;
    304308          }
    305         } else {
     309        }
     310        else {
    306311          printf(BREAK_ERR_MSG_INVALIDCLASS, args);
    307312          type = MRB_DEBUG_BPTYPE_NONE;
     
    344349    if (type == MRB_DEBUG_BPTYPE_LINE) {
    345350      printf(BREAK_SET_MSG_LINE, ret, file, line);
    346     } else if ((type == MRB_DEBUG_BPTYPE_METHOD)&&(cname == NULL)) {
     351    }
     352    else if ((type == MRB_DEBUG_BPTYPE_METHOD)&&(cname == NULL)) {
    347353      printf(BREAK_SET_MSG_METHOD, ret, method);
    348     } else {
     354    }
     355    else {
    349356      printf(BREAK_SET_MSG_CLASS_METHOD, ret, cname, method);
    350357    }
    351   } else {
     358  }
     359  else {
    352360    switch (ret) {
    353361      case MRB_DEBUG_BREAK_INVALID_LINENO:
     
    380388dbgcmd_info_break(mrb_state *mrb, mrdb_state *mrdb)
    381389{
    382   if(mrdb->wcnt == 2) {
     390  if (mrdb->wcnt == 2) {
    383391    info_break_all(mrb, mrdb);
    384392  }
     
    396404
    397405  ret = exe_set_command_all(mrb, mrdb, mrb_debug_delete_break_all);
    398   if(ret != TRUE) {
     406  if (ret != TRUE) {
    399407    exe_set_command_select(mrb, mrdb, mrb_debug_delete_break);
    400408  }
     
    409417
    410418  ret = exe_set_command_all(mrb, mrdb, mrb_debug_enable_break_all);
    411   if(ret != TRUE) {
     419  if (ret != TRUE) {
    412420    exe_set_command_select(mrb, mrdb, mrb_debug_enable_break);
    413421  }
     
    422430
    423431  ret = exe_set_command_all(mrb, mrdb, mrb_debug_disable_break_all);
    424   if(ret != TRUE) {
     432  if (ret != TRUE) {
    425433    exe_set_command_select(mrb, mrdb, mrb_debug_disable_break);
    426434  }
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-debugger/tools/mrdb/cmdmisc.c

    r321 r331  
    99
    1010#include "apilist.h"
    11 #include "mruby/compile.h"
     11#include <mruby/compile.h>
    1212
    1313typedef struct help_msg {
     
    334334    return FALSE;
    335335  }
    336   if((lbracket = strchr(pattern, '[')) == NULL) {
     336  if ((lbracket = strchr(pattern, '[')) == NULL) {
    337337    return !strcmp(pattern, cmd);
    338338  }
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-debugger/tools/mrdb/cmdprint.c

    r321 r331  
    66#include <string.h>
    77#include "mrdb.h"
    8 #include "mruby/value.h"
    9 #include "mruby/class.h"
    10 #include "mruby/compile.h"
    11 #include "mruby/error.h"
    12 #include "mruby/numeric.h"
    13 #include "mruby/string.h"
     8#include <mruby/value.h>
     9#include <mruby/class.h>
     10#include <mruby/compile.h>
     11#include <mruby/error.h>
     12#include <mruby/numeric.h>
     13#include <mruby/string.h>
    1414#include "apiprint.h"
    1515
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-debugger/tools/mrdb/cmdrun.c

    r321 r331  
    44*/
    55
    6 #include "mruby/opcode.h"
     6#include <mruby/opcode.h>
    77#include "mrdb.h"
    88
     
    1212  mrb_debug_context *dbg = mrdb->dbg;
    1313
    14   if( dbg->xm == DBG_INIT ){
     14  if (dbg->xm == DBG_INIT){
    1515    dbg->xm = DBG_RUN;
    16   } else {
     16  }
     17  else {
    1718    dbg->xm = DBG_QUIT;
    18     if( dbg->xphase == DBG_PHASE_RUNNING ){
     19    if (dbg->xphase == DBG_PHASE_RUNNING){
    1920      struct RClass *exc;
    2021      puts("Start it from the beginning.");
     
    2324    }
    2425  }
    25  
     26
    2627  return DBGST_RESTART;
    2728}
     
    3334  int ccnt = 1;
    3435
    35   if( mrdb->wcnt > 1 ){
     36  if (mrdb->wcnt > 1){
    3637    sscanf(mrdb->words[1], "%d", &ccnt);
    3738  }
    3839  dbg->ccnt = (uint16_t)(ccnt > 0 ? ccnt : 1);  /* count of continue */
    3940
    40   if( dbg->xphase == DBG_PHASE_AFTER_RUN ){
     41  if (dbg->xphase == DBG_PHASE_AFTER_RUN){
    4142    puts("The program is not running.");
    4243    dbg->xm = DBG_QUIT;
    43   } else {
     44  }
     45  else {
    4446    dbg->xm = DBG_RUN;
    4547  }
     
    5355  return DBGST_CONTINUE;
    5456}
     57
     58dbgcmd_state
     59dbgcmd_next(mrb_state *mrb, mrdb_state *mrdb)
     60{
     61  mrdb->dbg->xm = DBG_NEXT;
     62  mrdb->dbg->prvci = mrb->c->ci;
     63  return DBGST_CONTINUE;
     64}
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-debugger/tools/mrdb/mrdb.c

    r321 r331  
    99#include <ctype.h>
    1010
    11 #include "mruby.h"
    12 #include "mruby/dump.h"
    13 #include "mruby/debug.h"
    14 #include "mruby/class.h"
    15 #include "mruby/opcode.h"
    16 #include "mruby/variable.h"
     11#include <mruby.h>
     12#include <mruby/dump.h>
     13#include <mruby/debug.h>
     14#include <mruby/class.h>
     15#include <mruby/opcode.h>
     16#include <mruby/variable.h>
    1717
    1818#include "mrdb.h"
     
    5858  {"run",       NULL,           1, 0, 0, DBGCMD_RUN,            dbgcmd_run},             /* r[un] */
    5959  {"step",      NULL,           1, 0, 1, DBGCMD_STEP,           dbgcmd_step},            /* s[tep] */
     60  {"next",      NULL,           1, 0, 1, DBGCMD_NEXT,           dbgcmd_next},            /* n[ext] */
    6061  {NULL}
    6162};
     
    406407
    407408  ret = mrb_debug_get_break(mrb, mrdb->dbg, mrdb->dbg->stopped_bpno, &bp);
    408   if(ret == 0) {
     409  if (ret == 0) {
    409410    switch(bp.type) {
    410411      case MRB_DEBUG_BPTYPE_LINE:
     
    416417        method_name = bp.point.methodpoint.method_name;
    417418        class_name = bp.point.methodpoint.class_name;
    418         if(class_name == NULL) {
     419        if (class_name == NULL) {
    419420          printf("Breakpoint %d, %s\n", bp.bpno, method_name);
    420421        }
     
    422423          printf("Breakpoint %d, %s:%s\n", bp.bpno, class_name, method_name);
    423424        }
    424         if(mrdb->dbg->isCfunc) {
     425        if (mrdb->dbg->isCfunc) {
    425426          printf("Stopped before calling the C function.\n");
    426427        }
     
    445446  char* file = mrb_debug_get_source(mrb, mrdb, mrdb->srcpath, mrdb->dbg->prvfile);
    446447  uint16_t lineno = mrdb->dbg->prvline;
    447   if(file != NULL) {
     448  if (file != NULL) {
    448449    mrb_debug_list(mrb, mrdb->dbg, file, lineno, lineno);
    449450    mrb_free(mrb, file);
     
    531532      break;
    532533  }
    533   if(sym != 0) {
     534  if (sym != 0) {
    534535    dbg->method_bpno = mrb_debug_check_breakpoint_method(mrb, dbg, c, sym, &isCfunc);
    535     if(isCfunc) {
     536    if (isCfunc) {
    536537      bpno = dbg->method_bpno;
    537538      dbg->method_bpno = 0;
     
    557558  dbg->regs = regs;
    558559
    559   if(dbg->xphase == DBG_PHASE_RESTART) {
     560  if (dbg->xphase == DBG_PHASE_RESTART) {
    560561    dbg->root_irep = irep;
    561562    dbg->prvfile = NULL;
    562563    dbg->prvline = 0;
     564    dbg->prvci = NULL;
    563565    dbg->xm = DBG_RUN;
    564566    dbg->xphase = DBG_PHASE_RUNNING;
     
    570572  switch (dbg->xm) {
    571573  case DBG_STEP:
    572   case DBG_NEXT:  // temporary
    573574    if (!file || (dbg->prvfile == file && dbg->prvline == line)) {
    574575      return;
     
    576577    dbg->method_bpno = 0;
    577578    dbg->bm = BRK_STEP;
     579    break;
     580
     581  case DBG_NEXT:
     582    if (!file || (dbg->prvfile == file && dbg->prvline == line)) {
     583      return;
     584    }
     585    if ((intptr_t)(dbg->prvci) < (intptr_t)(mrb->c->ci)) {
     586      return;
     587    }
     588    dbg->prvci = NULL;
     589    dbg->method_bpno = 0;
     590    dbg->bm = BRK_NEXT;
    578591    break;
    579592
     
    611624  dbg->prvline = line;
    612625
    613   if(dbg->bm == BRK_BREAK && --dbg->ccnt > 0) {
     626  if (dbg->bm == BRK_BREAK && --dbg->ccnt > 0) {
    614627    return;
    615628  }
     
    634647    st = cmd->func(mrb, mrdb);
    635648
    636     if( (st == DBGST_CONTINUE) || (st == DBGST_RESTART) ) break;
     649    if ((st == DBGST_CONTINUE) || (st == DBGST_RESTART)) break;
    637650  }
    638651  return dbg->xm;
     
    671684  mrdb->srcpath = args.srcpath;
    672685
    673   if(mrdb->dbg->xm == DBG_QUIT) {
     686  if (mrdb->dbg->xm == DBG_QUIT) {
    674687    mrdb->dbg->xphase = DBG_PHASE_RESTART;
    675688  }
     
    679692  mrdb->dbg->xm = DBG_INIT;
    680693  mrdb->dbg->ccnt = 1;
    681  
     694
    682695  /* setup hook functions */
    683696  mrb->code_fetch_hook = mrb_code_fetch_hook;
     
    726739    }
    727740  }
    728  
     741
    729742  mrdb->dbg->prvfile = "-";
    730743  mrdb->dbg->prvline = 0;
    731  
     744
    732745  while (1) {
    733746    cmd = get_and_parse_command(mrb, mrdb);
    734747    mrb_assert(cmd);
    735    
     748
    736749    if (cmd->id == DBGCMD_QUIT) {
    737750      break;
    738751    }
    739    
    740     if( cmd->func(mrb, mrdb) == DBGST_RESTART ) goto l_restart;
    741   }
    742  
     752
     753    if ( cmd->func(mrb, mrdb) == DBGST_RESTART ) goto l_restart;
     754  }
     755
    743756  cleanup(mrb, &args);
    744757
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-debugger/tools/mrdb/mrdb.h

    r321 r331  
    77#define MRDB_H
    88
    9 #include "mruby.h"
     9#include <mruby.h>
    1010
    1111#include "mrdbconf.h"
     
    110110  const char *prvfile;
    111111  int32_t prvline;
     112  mrb_callinfo *prvci;
    112113
    113114  mrdb_exemode xm;
     
    147148dbgcmd_state dbgcmd_continue(mrb_state*, mrdb_state*);
    148149dbgcmd_state dbgcmd_step(mrb_state*, mrdb_state*);
     150dbgcmd_state dbgcmd_next(mrb_state*, mrdb_state*);
    149151/* cmdbreak.c */
    150152dbgcmd_state dbgcmd_break(mrb_state*, mrdb_state*);
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-mirb/tools/mirb/mirb.c

    r321 r331  
    1111#include <stdio.h>
    1212#include <ctype.h>
     13
     14#include <signal.h>
     15#include <setjmp.h>
    1316
    1417#ifdef ENABLE_READLINE
     
    3033#endif
    3134
    32 #include "mruby.h"
    33 #include "mruby/array.h"
    34 #include "mruby/proc.h"
    35 #include "mruby/compile.h"
    36 #include "mruby/string.h"
     35#ifndef _WIN32
     36#define MIRB_SIGSETJMP(env) sigsetjmp(env, 1)
     37#define MIRB_SIGLONGJMP(env, val) siglongjmp(env, val)
     38#define SIGJMP_BUF sigjmp_buf
     39#else
     40#define MIRB_SIGSETJMP(env) setjmp(env)
     41#define MIRB_SIGLONGJMP(env, val) longjmp(env, val)
     42#define SIGJMP_BUF jmp_buf
     43#endif
     44
     45#include <mruby.h>
     46#include <mruby/array.h>
     47#include <mruby/proc.h>
     48#include <mruby/compile.h>
     49#include <mruby/string.h>
    3750
    3851#ifdef ENABLE_READLINE
     
    195208
    196209struct _args {
     210  FILE *rfp;
    197211  mrb_bool verbose      : 1;
    198212  int argc;
     
    252266    }
    253267  }
     268
     269  if (args->rfp == NULL) {
     270    if (*argv != NULL) {
     271      args->rfp = fopen(argv[0], "r");
     272      if (args->rfp == NULL) {
     273        printf("Cannot open program file. (%s)\n", *argv);
     274        return EXIT_FAILURE;
     275      }
     276      argc--; argv++;
     277    }
     278  }
     279  args->argv = (char **)mrb_realloc(mrb, args->argv, sizeof(char*) * (argc + 1));
     280  memcpy(args->argv, argv, (argc+1) * sizeof(char*));
     281  args->argc = argc;
     282
    254283  return EXIT_SUCCESS;
    255284}
     
    258287cleanup(mrb_state *mrb, struct _args *args)
    259288{
     289  if (args->rfp)
     290    fclose(args->rfp);
     291  mrb_free(mrb, args->argv);
    260292  mrb_close(mrb);
    261293}
     
    308340}
    309341
     342
     343#ifndef ENABLE_READLINE
     344volatile sig_atomic_t input_canceled = 0;
     345void
     346ctrl_c_handler(int signo)
     347{
     348  input_canceled = 1;
     349}
     350#else
     351SIGJMP_BUF ctrl_c_buf;
     352void
     353ctrl_c_handler(int signo)
     354{
     355  MIRB_SIGLONGJMP(ctrl_c_buf, 1);
     356}
     357#endif
     358
    310359int
    311360main(int argc, char **argv)
    312361{
    313   char ruby_code[1024] = { 0 };
     362  char ruby_code[4096] = { 0 };
    314363  char last_code_line[1024] = { 0 };
    315364#ifndef ENABLE_READLINE
    316365  int last_char;
    317   int char_index;
     366  size_t char_index;
    318367#else
    319368  char *history_path;
     369  char* line;
    320370#endif
    321371  mrbc_context *cxt;
     
    324374  mrb_value result;
    325375  struct _args args;
     376  mrb_value ARGV;
    326377  int n;
     378  int i;
    327379  mrb_bool code_block_open = FALSE;
    328380  int ai;
     
    335387    return EXIT_FAILURE;
    336388  }
    337   mrb_define_global_const(mrb, "ARGV", mrb_ary_new_capa(mrb, 0));
    338389
    339390  n = parse_args(mrb, argc, argv, &args);
     
    343394    return n;
    344395  }
     396
     397  ARGV = mrb_ary_new_capa(mrb, args.argc);
     398  for (i = 0; i < args.argc; i++) {
     399    char* utf8 = mrb_utf8_from_locale(args.argv[i], -1);
     400    if (utf8) {
     401      mrb_ary_push(mrb, ARGV, mrb_str_new_cstr(mrb, utf8));
     402      mrb_utf8_free(utf8);
     403    }
     404  }
     405  mrb_define_global_const(mrb, "ARGV", ARGV);
    345406
    346407#ifdef ENABLE_READLINE
     
    369430    char *utf8;
    370431
     432    if (args.rfp) {
     433      if (fgets(last_code_line, sizeof(last_code_line)-1, args.rfp) != NULL)
     434        goto done;
     435      break;
     436    }
     437
    371438#ifndef ENABLE_READLINE
    372439    print_cmdline(code_block_open);
    373440
     441    signal(SIGINT, ctrl_c_handler);
    374442    char_index = 0;
    375443    while ((last_char = getchar()) != '\n') {
    376444      if (last_char == EOF) break;
    377       if (char_index > sizeof(last_code_line)-2) {
     445      if (char_index >= sizeof(last_code_line)-2) {
    378446        fputs("input string too long\n", stderr);
    379447        continue;
    380448      }
    381449      last_code_line[char_index++] = last_char;
     450    }
     451    signal(SIGINT, SIG_DFL);
     452    if (input_canceled) {
     453      ruby_code[0] = '\0';
     454      last_code_line[0] = '\0';
     455      code_block_open = FALSE;
     456      puts("^C");
     457      input_canceled = 0;
     458      continue;
    382459    }
    383460    if (last_char == EOF) {
     
    389466    last_code_line[char_index] = '\0';
    390467#else
    391     char* line = MIRB_READLINE(code_block_open ? "* " : "> ");
     468    if (MIRB_SIGSETJMP(ctrl_c_buf) == 0) {
     469      ;
     470    }
     471    else {
     472      ruby_code[0] = '\0';
     473      last_code_line[0] = '\0';
     474      code_block_open = FALSE;
     475      puts("^C");
     476    }
     477    signal(SIGINT, ctrl_c_handler);
     478    line = MIRB_READLINE(code_block_open ? "* " : "> ");
     479    signal(SIGINT, SIG_DFL);
     480
    392481    if (line == NULL) {
    393482      printf("\n");
     
    403492    free(line);
    404493#endif
     494
     495done:
    405496
    406497    if (code_block_open) {
     
    454545          mrb_codedump_all(mrb, proc);
    455546        }
    456         /* pass a proc for evaulation */
     547        /* pass a proc for evaluation */
    457548        /* evaluate the bytecode */
    458         result = mrb_context_run(mrb,
     549        result = mrb_vm_run(mrb,
    459550            proc,
    460551            mrb_top_self(mrb),
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-mrbc/tools/mrbc/mrbc.c

    r321 r331  
    22#include <stdlib.h>
    33#include <string.h>
    4 #include "mruby.h"
    5 #include "mruby/compile.h"
    6 #include "mruby/dump.h"
    7 #include "mruby/proc.h"
     4#include <mruby.h>
     5#include <mruby/compile.h>
     6#include <mruby/dump.h>
     7#include <mruby/proc.h>
    88
    99#define RITEBIN_EXT ".mrb"
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-mruby-config/mrbgem.rake

    r321 r331  
    2424    config = Hash[open("#{build_dir}/lib/libmruby.flags.mak").read.split("\n").map {|x| a = x.split(/\s*=\s*/, 2); [a[0], a[1].gsub('\\"', '"') ]}]
    2525    IO.write(t.name, File.open(t.name) {|f|
    26       f.read.gsub (/echo (MRUBY_CFLAGS|MRUBY_LIBS|MRUBY_LDFLAGS_BEFORE_LIBS|MRUBY_LDFLAGS)/) {|x| config[$1].empty? ? '' : "echo #{config[$1]}"}
     26      f.read.gsub (/echo (MRUBY_CFLAGS|MRUBY_LIBS|MRUBY_LDFLAGS_BEFORE_LIBS|MRUBY_LDFLAGS|MRUBY_LIBMRUBY_PATH)/) {|x| config[$1].empty? ? '' : "echo #{config[$1]}"}
    2727    })
    2828    FileUtils.chmod(0755, t.name)
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-mruby-config/mruby-config

    r270 r331  
    77    --ldflags-before-libs) echo MRUBY_LDFLAGS_BEFORE_LIBS;;
    88    --libs) echo MRUBY_LIBS;;
     9    --libmruby-path) echo MRUBY_LIBMRUBY_PATH;;
    910    --help) echo "Usage: mruby-config [switches]"
    1011            echo "  switches:"
    1112            echo "  --cflags                    print flags passed to compiler"
    1213            echo "  --ldflags                   print flags passed to linker"
    13             echo "  --ldflags-before-libs       print flags passwd to linker before linked libraries"
     14            echo "  --ldflags-before-libs       print flags passed to linker before linked libraries"
    1415            echo "  --libs                      print linked libraries"
     16            echo "  --libmruby-path             print libmruby path"
    1517            exit 0;;
    1618  esac
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-mruby-config/mruby-config.bat

    r270 r331  
    88if "%0" equ "--ldflags-before-libs" goto ldflagsbeforelibs
    99if "%0" equ "--libs" goto libs
     10if "%0" equ "--libmruby-path" goto libmrubypath
    1011if "%0" equ "--help" goto showhelp
    1112echo Invalid Option
     
    2829goto top
    2930
     31:libmrubypath
     32echo MRUBY_LIBMRUBY_PATH
     33goto top
     34
    3035:showhelp
    3136echo Usage: mruby-config [switches]
     
    3338echo   --cflags                   print flags passed to compiler
    3439echo   --ldflags                  print flags passed to linker
    35 echo   --ldflags-before-libs      print flags passwd to linker before linked libraries
     40echo   --ldflags-before-libs      print flags passed to linker before linked libraries
    3641echo   --libs                     print linked libraries
     42echo   --libmruby-path            print libmruby path
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-mruby/bintest/mruby.rb

    r321 r331  
    33assert('regression for #1564') do
    44  o = `#{cmd('mruby')} -e #{shellquote('<<')} 2>&1`
    5   assert_equal o, "-e:1:2: syntax error, unexpected tLSHFT\n"
     5  assert_include o, "-e:1:2: syntax error"
    66  o = `#{cmd('mruby')} -e #{shellquote('<<-')} 2>&1`
    7   assert_equal o, "-e:1:3: syntax error, unexpected tLSHFT\n"
     7  assert_include o, "-e:1:3: syntax error"
    88end
    99
     
    4545  assert_equal "\"test\"\n\"fin\"\n", `#{cmd('mruby')} #{script.path}`
    4646end
     47
     48assert('garbage collecting built-in classes') do
     49  script = Tempfile.new('test.rb')
     50
     51  script.write <<RUBY
     52NilClass = nil
     53GC.start
     54Array.dup
     55print nil.class.to_s
     56RUBY
     57  script.flush
     58  assert_equal "NilClass", `#{cmd('mruby')} #{script.path}`
     59  assert_equal 0, $?.exitstatus
     60end
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-mruby/mrbgem.rake

    r321 r331  
    55  spec.bins = %w(mruby)
    66  spec.add_dependency('mruby-compiler', :core => 'mruby-compiler')
     7  spec.add_dependency('mruby-error', :core => 'mruby-error')
     8
     9  if build.cxx_exception_enabled?
     10    @objs << build.compile_as_cxx("#{spec.dir}/tools/mruby/mruby.c", "#{spec.build_dir}/tools/mruby/mruby.cxx")
     11    @objs.delete_if { |v| v == objfile("#{spec.build_dir}/tools/mruby/mruby") }
     12  end
    713end
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-mruby/tools/mruby/mruby.c

    r321 r331  
    22#include <stdlib.h>
    33#include <string.h>
    4 #include "mruby.h"
    5 #include "mruby/array.h"
    6 #include "mruby/compile.h"
    7 #include "mruby/dump.h"
    8 #include "mruby/variable.h"
     4#include <mruby.h>
     5#include <mruby/array.h>
     6#include <mruby/compile.h>
     7#include <mruby/dump.h>
     8#include <mruby/variable.h>
    99
    1010#ifdef MRB_DISABLE_STDIO
     
    189189    return n;
    190190  }
    191 
    192   ARGV = mrb_ary_new_capa(mrb, args.argc);
    193   for (i = 0; i < args.argc; i++) {
    194     char* utf8 = mrb_utf8_from_locale(args.argv[i], -1);
    195     if (utf8) {
    196       mrb_ary_push(mrb, ARGV, mrb_str_new_cstr(mrb, utf8));
     191  else {
     192    int ai = mrb_gc_arena_save(mrb);
     193    ARGV = mrb_ary_new_capa(mrb, args.argc);
     194    for (i = 0; i < args.argc; i++) {
     195      char* utf8 = mrb_utf8_from_locale(args.argv[i], -1);
     196      if (utf8) {
     197        mrb_ary_push(mrb, ARGV, mrb_str_new_cstr(mrb, utf8));
     198        mrb_utf8_free(utf8);
     199      }
     200    }
     201    mrb_define_global_const(mrb, "ARGV", ARGV);
     202
     203    c = mrbc_context_new(mrb);
     204    if (args.verbose)
     205      c->dump_result = TRUE;
     206    if (args.check_syntax)
     207      c->no_exec = TRUE;
     208
     209    /* Set $0 */
     210    zero_sym = mrb_intern_lit(mrb, "$0");
     211    if (args.rfp) {
     212      const char *cmdline;
     213      cmdline = args.cmdline ? args.cmdline : "-";
     214      mrbc_filename(mrb, c, cmdline);
     215      mrb_gv_set(mrb, zero_sym, mrb_str_new_cstr(mrb, cmdline));
     216    }
     217    else {
     218      mrbc_filename(mrb, c, "-e");
     219      mrb_gv_set(mrb, zero_sym, mrb_str_new_lit(mrb, "-e"));
     220    }
     221
     222    /* Load program */
     223    if (args.mrbfile) {
     224      v = mrb_load_irep_file_cxt(mrb, args.rfp, c);
     225    }
     226    else if (args.rfp) {
     227      v = mrb_load_file_cxt(mrb, args.rfp, c);
     228    }
     229    else {
     230      char* utf8 = mrb_utf8_from_locale(args.cmdline, -1);
     231      if (!utf8) abort();
     232      v = mrb_load_string_cxt(mrb, utf8, c);
    197233      mrb_utf8_free(utf8);
    198234    }
    199   }
    200   mrb_define_global_const(mrb, "ARGV", ARGV);
    201 
    202   c = mrbc_context_new(mrb);
    203   if (args.verbose)
    204     c->dump_result = TRUE;
    205   if (args.check_syntax)
    206     c->no_exec = TRUE;
    207 
    208   /* Set $0 */
    209   zero_sym = mrb_intern_lit(mrb, "$0");
    210   if (args.rfp) {
    211     const char *cmdline;
    212     cmdline = args.cmdline ? args.cmdline : "-";
    213     mrbc_filename(mrb, c, cmdline);
    214     mrb_gv_set(mrb, zero_sym, mrb_str_new_cstr(mrb, cmdline));
    215   }
    216   else {
    217     mrbc_filename(mrb, c, "-e");
    218     mrb_gv_set(mrb, zero_sym, mrb_str_new_lit(mrb, "-e"));
    219   }
    220 
    221   /* Load program */
    222   if (args.mrbfile) {
    223     v = mrb_load_irep_file_cxt(mrb, args.rfp, c);
    224   }
    225   else if (args.rfp) {
    226     v = mrb_load_file_cxt(mrb, args.rfp, c);
    227   }
    228   else {
    229     char* utf8 = mrb_utf8_from_locale(args.cmdline, -1);
    230     if (!utf8) abort();
    231     v = mrb_load_string_cxt(mrb, utf8, c);
    232     mrb_utf8_free(utf8);
    233   }
    234 
    235   mrbc_context_free(mrb, c);
    236   if (mrb->exc) {
    237     if (!mrb_undef_p(v)) {
    238       mrb_print_error(mrb);
    239     }
    240     n = -1;
    241   }
    242   else if (args.check_syntax) {
    243     printf("Syntax OK\n");
     235
     236    mrb_gc_arena_restore(mrb, ai);
     237    mrbc_context_free(mrb, c);
     238    if (mrb->exc) {
     239      if (mrb_undef_p(v)) {
     240        mrb_p(mrb, mrb_obj_value(mrb->exc));
     241      }
     242      else {
     243        mrb_print_error(mrb);
     244      }
     245      n = -1;
     246    }
     247    else if (args.check_syntax) {
     248      printf("Syntax OK\n");
     249    }
    244250  }
    245251  cleanup(mrb, &args);
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-bin-strip/tools/mruby-strip/mruby-strip.c

    r321 r331  
    22#include <stdlib.h>
    33#include <string.h>
    4 #include "mruby.h"
    5 #include "mruby/irep.h"
    6 #include "mruby/dump.h"
     4#include <mruby.h>
     5#include <mruby/irep.h>
     6#include <mruby/dump.h>
    77
    88struct strip_args {
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-compiler/bintest/mrbc.rb

    r321 r331  
    1111  assert_equal 0, $?.exitstatus
    1212end
     13
     14assert('parsing function with void argument') do
     15  a, out = Tempfile.new('a.rb'), Tempfile.new('out.mrb')
     16  a.write('f ()')
     17  a.flush
     18  result = `#{cmd('mrbc')} -c -o #{out.path} #{a.path} 2>&1`
     19  assert_equal "#{cmd('mrbc')}:#{a.path}:Syntax OK", result.chomp
     20  assert_equal 0, $?.exitstatus
     21end
     22
     23assert('embedded document with invalid terminator') do
     24  a, out = Tempfile.new('a.rb'), Tempfile.new('out.mrb')
     25  a.write("=begin\n=endx\n")
     26  a.flush
     27  result = `#{cmd('mrbc')} -c -o #{out.path} #{a.path} 2>&1`
     28  assert_equal "#{a.path}:3:0: embedded document meets end of file", result.chomp
     29  assert_equal 1, $?.exitstatus
     30end
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-compiler/core/codegen.c

    r321 r331  
    99#include <stdlib.h>
    1010#include <string.h>
    11 #include "mruby.h"
    12 #include "mruby/compile.h"
    13 #include "mruby/proc.h"
    14 #include "mruby/numeric.h"
    15 #include "mruby/string.h"
    16 #include "mruby/debug.h"
     11#include <mruby.h>
     12#include <mruby/compile.h>
     13#include <mruby/proc.h>
     14#include <mruby/numeric.h>
     15#include <mruby/string.h>
     16#include <mruby/debug.h>
    1717#include "node.h"
    18 #include "mruby/opcode.h"
    19 #include "mruby/re.h"
    20 #include "mruby/throw.h"
     18#include <mruby/opcode.h>
     19#include <mruby/re.h>
     20#include <mruby/throw.h>
     21
     22#ifndef MRB_CODEGEN_LEVEL_MAX
     23#define MRB_CODEGEN_LEVEL_MAX 1024
     24#endif
    2125
    2226typedef mrb_ast_node node;
     
    7478  uint16_t filename_index;
    7579  parser_state* parser;
     80
     81  int rlev;                     /* recursion levels */
    7682} codegen_scope;
    7783
     
    94100  while (s->prev) {
    95101    codegen_scope *tmp = s->prev;
     102    mrb_free(s->mrb, s->iseq);
    96103    mrb_pool_close(s->mpool);
    97104    s = tmp;
    98105  }
    99 #ifndef MBB_DISABLE_STDIO
     106#ifndef MRB_DISABLE_STDIO
    100107  if (s->filename && s->lineno) {
    101108    fprintf(stderr, "codegen error:%s:%d: %s\n", s->filename, s->lineno, message);
     
    340347        }
    341348      }
     349      if (c0 == OP_LOADNIL) {
     350        if (GETARG_B(i) == GETARG_A(i0)) {
     351          s->pc--;
     352          return 0;
     353        }
     354      }
    342355      break;
    343356    case OP_JMPIF:
     
    381394    scope_error(s);
    382395    break;
     396  }
     397  if (diff > MAXARG_sBx) {
     398    codegen_error(s, "too distant jump address");
    383399  }
    384400  s->iseq[pc] = MKOP_AsBx(c, GETARG_A(i), diff);
     
    495511}
    496512
    497 static inline int
     513/* method symbols should be fit in 9 bits */
     514#define MAXMSYMLEN 512
     515/* maximum symbol numbers */
     516#define MAXSYMLEN 65536
     517
     518static int
    498519new_msym(codegen_scope *s, mrb_sym sym)
    499520{
     
    503524
    504525  len = s->irep->slen;
    505   if (len > 256) len = 256;
     526  if (len > MAXMSYMLEN) len = MAXMSYMLEN;
    506527  for (i=0; i<len; i++) {
    507528    if (s->irep->syms[i] == sym) return i;
    508529    if (s->irep->syms[i] == 0) break;
    509530  }
    510   if (i == 256) {
    511     codegen_error(s, "too many symbols (max 256)");
     531  if (i == MAXMSYMLEN) {
     532    codegen_error(s, "too many symbols (max " MRB_STRINGIZE(MAXMSYMLEN) ")");
    512533  }
    513534  s->irep->syms[i] = sym;
     
    516537}
    517538
    518 static inline int
     539static int
    519540new_sym(codegen_scope *s, mrb_sym sym)
    520541{
     
    524545    if (s->irep->syms[i] == sym) return i;
    525546  }
    526   if (s->irep->slen > 125 && s->irep->slen < 256) {
    527     s->irep->syms = (mrb_sym *)codegen_realloc(s, s->irep->syms, sizeof(mrb_sym)*65536);
    528     for (i = 0; i < 256 - s->irep->slen; i++) {
     547  if (s->irep->slen == MAXSYMLEN) {
     548    codegen_error(s, "too many symbols (max " MRB_STRINGIZE(MAXSYMLEN) ")");
     549  }
     550
     551  if (s->irep->slen > MAXMSYMLEN/2 && s->scapa == MAXMSYMLEN) {
     552    s->scapa = MAXSYMLEN;
     553    s->irep->syms = (mrb_sym *)codegen_realloc(s, s->irep->syms, sizeof(mrb_sym)*MAXSYMLEN);
     554    for (i = s->irep->slen; i < MAXMSYMLEN; i++) {
    529555      static const mrb_sym mrb_sym_zero = { 0 };
    530       s->irep->syms[i + s->irep->slen] = mrb_sym_zero;
    531     }
    532     s->irep->slen = 256;
     556      s->irep->syms[i] = mrb_sym_zero;
     557    }
     558    s->irep->slen = MAXMSYMLEN;
    533559  }
    534560  s->irep->syms[s->irep->slen] = sym;
     
    583609  push();                       /* push for a block parameter */
    584610
    585   lp = loop_push(s, LOOP_FOR);
    586   lp->pc1 = new_label(s);
    587 
    588611  /* generate loop variable */
    589612  n2 = tree->car;
     
    595618    gen_vmassignment(s, n2, 1, VAL);
    596619  }
     620  /* construct loop */
     621  lp = loop_push(s, LOOP_FOR);
     622  lp->pc2 = new_label(s);
     623
     624  /* loop body */
    597625  codegen(s, tree->cdr->cdr->car, VAL);
    598626  pop();
     
    645673    ba = tree->car->cdr->cdr->cdr->cdr ? 1 : 0;
    646674
     675    if (ma > 0x1f || oa > 0x1f || pa > 0x1f || ka > 0x1f) {
     676      codegen_error(s, "too many formal arguments");
     677    }
    647678    a = ((mrb_aspec)(ma & 0x1f) << 18)
    648679      | ((mrb_aspec)(oa & 0x1f) << 13)
     
    765796}
    766797
     798#define CALL_MAXARGS 127
     799
    767800static int
    768 gen_values(codegen_scope *s, node *t, int val)
     801gen_values(codegen_scope *s, node *t, int val, int extra)
    769802{
    770803  int n = 0;
     
    773806  while (t) {
    774807    is_splat = (intptr_t)t->car->car == NODE_SPLAT; /* splat mode */
    775     if (n >= 127 || is_splat) {
     808    if (
     809      n+extra >= CALL_MAXARGS - 1 /* need to subtract one because vm.c expects an array if n == CALL_MAXARGS */
     810      || is_splat) {
    776811      if (val) {
    777         pop_n(n);
    778         genop(s, MKOP_ABC(OP_ARRAY, cursp(), cursp(), n));
    779         push();
    780         codegen(s, t->car, VAL);
    781         pop(); pop();
    782         if (is_splat) {
    783           genop(s, MKOP_AB(OP_ARYCAT, cursp(), cursp()+1));
     812        if (is_splat && n == 0 && (intptr_t)t->car->cdr->car == NODE_ARRAY) {
     813          codegen(s, t->car->cdr, VAL);
     814          pop();
    784815        }
    785816        else {
    786           genop(s, MKOP_AB(OP_ARYPUSH, cursp(), cursp()+1));
     817          pop_n(n);
     818          genop(s, MKOP_ABC(OP_ARRAY, cursp(), cursp(), n));
     819          push();
     820          codegen(s, t->car, VAL);
     821          pop(); pop();
     822          if (is_splat) {
     823            genop(s, MKOP_AB(OP_ARYCAT, cursp(), cursp()+1));
     824          }
     825          else {
     826            genop(s, MKOP_AB(OP_ARYPUSH, cursp(), cursp()+1));
     827          }
    787828        }
    788829        t = t->cdr;
     
    801842      }
    802843      else {
    803         codegen(s, t->car->cdr, NOVAL);
    804         t = t->cdr;
    805844        while (t) {
    806845          codegen(s, t->car, NOVAL);
     
    818857}
    819858
    820 #define CALL_MAXARGS 127
    821 
    822859static void
    823 gen_call(codegen_scope *s, node *tree, mrb_sym name, int sp, int val)
     860gen_call(codegen_scope *s, node *tree, mrb_sym name, int sp, int val, int safe)
    824861{
    825862  mrb_sym sym = name ? name : sym(tree->cdr->car);
    826   int idx;
     863  int idx, skip = 0;
    827864  int n = 0, noop = 0, sendv = 0, blk = 0;
    828865
    829866  codegen(s, tree->car, VAL); /* receiver */
     867  if (safe) {
     868    int recv = cursp()-1;
     869    genop(s, MKOP_A(OP_LOADNIL, cursp()));
     870    push();
     871    genop(s, MKOP_AB(OP_MOVE, cursp(), recv));
     872    push(); pop();              /* space for a block */
     873    pop();
     874    idx = new_msym(s, mrb_intern_lit(s->mrb, "=="));
     875    genop(s, MKOP_ABC(OP_EQ, cursp(), idx, 1));
     876    skip = genop(s, MKOP_AsBx(OP_JMPIF, cursp(), 0));
     877  }
    830878  idx = new_msym(s, sym);
    831879  tree = tree->cdr->cdr->car;
    832880  if (tree) {
    833     n = gen_values(s, tree->car, VAL);
     881    n = gen_values(s, tree->car, VAL, sp?1:0);
    834882    if (n < 0) {
    835883      n = noop = sendv = 1;
     
    863911    const char *symname = mrb_sym2name_len(s->mrb, sym, &symlen);
    864912
    865     if (!noop && symlen == 1 && symname[0] == '+')  {
     913    if (!noop && symlen == 1 && symname[0] == '+' && n == 1)  {
    866914      genop_peep(s, MKOP_ABC(OP_ADD, cursp(), idx, n), val);
    867915    }
    868     else if (!noop && symlen == 1 && symname[0] == '-')  {
     916    else if (!noop && symlen == 1 && symname[0] == '-' && n == 1)  {
    869917      genop_peep(s, MKOP_ABC(OP_SUB, cursp(), idx, n), val);
    870918    }
    871     else if (!noop && symlen == 1 && symname[0] == '*')  {
     919    else if (!noop && symlen == 1 && symname[0] == '*' && n == 1)  {
    872920      genop(s, MKOP_ABC(OP_MUL, cursp(), idx, n));
    873921    }
    874     else if (!noop && symlen == 1 && symname[0] == '/')  {
     922    else if (!noop && symlen == 1 && symname[0] == '/' && n == 1)  {
    875923      genop(s, MKOP_ABC(OP_DIV, cursp(), idx, n));
    876924    }
    877     else if (!noop && symlen == 1 && symname[0] == '<')  {
     925    else if (!noop && symlen == 1 && symname[0] == '<' && n == 1)  {
    878926      genop(s, MKOP_ABC(OP_LT, cursp(), idx, n));
    879927    }
    880     else if (!noop && symlen == 2 && symname[0] == '<' && symname[1] == '=')  {
     928    else if (!noop && symlen == 2 && symname[0] == '<' && symname[1] == '=' && n == 1)  {
    881929      genop(s, MKOP_ABC(OP_LE, cursp(), idx, n));
    882930    }
    883     else if (!noop && symlen == 1 && symname[0] == '>')  {
     931    else if (!noop && symlen == 1 && symname[0] == '>' && n == 1)  {
    884932      genop(s, MKOP_ABC(OP_GT, cursp(), idx, n));
    885933    }
    886     else if (!noop && symlen == 2 && symname[0] == '>' && symname[1] == '=')  {
     934    else if (!noop && symlen == 2 && symname[0] == '>' && symname[1] == '=' && n == 1)  {
    887935      genop(s, MKOP_ABC(OP_GE, cursp(), idx, n));
    888936    }
    889     else if (!noop && symlen == 2 && symname[0] == '=' && symname[1] == '=')  {
     937    else if (!noop && symlen == 2 && symname[0] == '=' && symname[1] == '=' && n == 1)  {
    890938      genop(s, MKOP_ABC(OP_EQ, cursp(), idx, n));
    891939    }
     
    900948    }
    901949  }
     950  if (safe) {
     951    dispatch(s, skip);
     952  }
    902953  if (val) {
    903954    push();
     
    912963
    913964  tree = tree->cdr;
    914   switch ((intptr_t)type) {
     965  switch (type) {
    915966  case NODE_GVAR:
    916967    idx = new_sym(s, sym(tree));
     
    9621013
    9631014  case NODE_CALL:
     1015  case NODE_SCALL:
    9641016    push();
    965     gen_call(s, tree, attrsym(s, sym(tree->cdr->car)), sp, NOVAL);
     1017    gen_call(s, tree, attrsym(s, sym(tree->cdr->car)), sp, NOVAL,
     1018             type == NODE_SCALL);
    9661019    pop();
    9671020    if (val) {
     
    9801033  default:
    9811034#ifndef MRB_DISABLE_STDIO
    982     printf("unknown lhs %d\n", type);
     1035    fprintf(stderr, "unknown lhs %d\n", type);
    9831036#endif
    9841037    break;
     
    10331086      }
    10341087    }
    1035     push();
     1088    if (!val) {
     1089      push();
     1090    }
    10361091  }
    10371092}
     
    11761231
    11771232static void
     1233gen_retval(codegen_scope *s, node *tree)
     1234{
     1235  if ((intptr_t)tree->car == NODE_SPLAT) {
     1236    genop(s, MKOP_ABC(OP_ARRAY, cursp(), cursp(), 0));
     1237    push();
     1238    codegen(s, tree, VAL);
     1239    pop(); pop();
     1240    genop(s, MKOP_AB(OP_ARYCAT, cursp(), cursp()+1));
     1241  }
     1242  else {
     1243    codegen(s, tree, VAL);
     1244    pop();
     1245  }
     1246}
     1247
     1248static void
    11781249codegen(codegen_scope *s, node *tree, int val)
    11791250{
    11801251  int nt;
    1181 
    1182   if (!tree) return;
    1183 
     1252  int rlev = s->rlev;
     1253
     1254  if (!tree) {
     1255    if (val) {
     1256      genop(s, MKOP_A(OP_LOADNIL, cursp()));
     1257      push();
     1258    }
     1259    return;
     1260  }
     1261
     1262  s->rlev++;
     1263  if (s->rlev > MRB_CODEGEN_LEVEL_MAX) {
     1264    codegen_error(s, "too complex expression");
     1265  }
    11841266  if (s->irep && s->filename_index != tree->filename_index) {
    11851267    s->irep->filename = mrb_parser_get_filename(s->parser, s->filename_index);
     
    12101292      struct loopinfo *lp;
    12111293
     1294      if (tree->car == NULL) goto exit;
    12121295      onerr = genop(s, MKOP_Bx(OP_ONERR, 0));
    12131296      lp = loop_push(s, LOOP_BEGIN);
    12141297      lp->pc1 = onerr;
    1215       if (tree->car) {
    1216         codegen(s, tree->car, val);
    1217         if (val) pop();
    1218       }
     1298      codegen(s, tree->car, VAL);
     1299      pop();
    12191300      lp->type = LOOP_RESCUE;
    12201301      noexc = genop(s, MKOP_Bx(OP_JMP, 0));
     
    12271308        int exc = cursp();
    12281309
    1229         genop(s, MKOP_A(OP_RESCUE, exc));
     1310        genop(s, MKOP_ABC(OP_RESCUE, exc, 0, 0));
    12301311        push();
    12311312        while (n2) {
     
    12361317          pos2 = 0;
    12371318          do {
    1238             if (n4) {
     1319            if (n4 && n4->car && (intptr_t)n4->car->car == NODE_SPLAT) {
    12391320              codegen(s, n4->car, VAL);
    1240             }
    1241             else {
    1242               genop(s, MKOP_ABx(OP_GETCONST, cursp(), new_msym(s, mrb_intern_lit(s->mrb, "StandardError"))));
    1243               push();
    1244             }
    1245             genop(s, MKOP_AB(OP_MOVE, cursp(), exc));
    1246             pop();
    1247             if (n4 && n4->car && (intptr_t)n4->car->car == NODE_SPLAT) {
     1321              genop(s, MKOP_AB(OP_MOVE, cursp(), exc));
     1322              pop();
    12481323              genop(s, MKOP_ABC(OP_SEND, cursp(), new_msym(s, mrb_intern_lit(s->mrb, "__case_eqq")), 1));
    12491324            }
    12501325            else {
    1251               genop(s, MKOP_ABC(OP_SEND, cursp(), new_msym(s, mrb_intern_lit(s->mrb, "===")), 1));
     1326              if (n4) {
     1327                codegen(s, n4->car, VAL);
     1328              }
     1329              else {
     1330                genop(s, MKOP_ABx(OP_GETCONST, cursp(), new_msym(s, mrb_intern_lit(s->mrb, "StandardError"))));
     1331                push();
     1332              }
     1333              pop();
     1334              genop(s, MKOP_ABC(OP_RESCUE, exc, cursp(), 1));
    12521335            }
    12531336            tmp = genop(s, MKOP_AsBx(OP_JMPIF, cursp(), pos2));
     
    12941377
    12951378  case NODE_ENSURE:
    1296     {
     1379    if (!tree->cdr || !tree->cdr->cdr ||
     1380        ((intptr_t)tree->cdr->cdr->car == NODE_BEGIN &&
     1381         tree->cdr->cdr->cdr)) {
    12971382      int idx;
    12981383      int epush = s->pc;
     
    13061391      genop_peep(s, MKOP_A(OP_EPOP, 1), NOVAL);
    13071392    }
     1393    else {                      /* empty ensure ignored */
     1394      codegen(s, tree->car, val);
     1395    }
    13081396    break;
    13091397
    13101398  case NODE_LAMBDA:
    1311     {
     1399    if (val) {
    13121400      int idx = lambda_body(s, tree, 1);
    13131401
     
    13181406
    13191407  case NODE_BLOCK:
    1320     {
     1408    if (val) {
    13211409      int idx = lambda_body(s, tree, 1);
    13221410
     
    13311419      node *e = tree->cdr->cdr->car;
    13321420
     1421      if (!tree->car) {
     1422        codegen(s, e, val);
     1423        goto exit;
     1424      }
    13331425      switch ((intptr_t)tree->car->car) {
    13341426      case NODE_TRUE:
     
    13361428      case NODE_STR:
    13371429        codegen(s, tree->cdr->car, val);
    1338         return;
     1430        goto exit;
    13391431      case NODE_FALSE:
    13401432      case NODE_NIL:
    13411433        codegen(s, e, val);
    1342         return;
     1434        goto exit;
    13431435      }
    13441436      codegen(s, tree->car, VAL);
     
    13471439
    13481440      codegen(s, tree->cdr->car, val);
    1349       if (val && !(tree->cdr->car)) {
    1350         genop(s, MKOP_A(OP_LOADNIL, cursp()));
    1351         push();
    1352       }
    13531441      if (e) {
    13541442        if (val) pop();
     
    14851573        if (pos3) dispatch_linked(s, pos3);
    14861574        if (head) pop();
    1487         genop(s, MKOP_AB(OP_MOVE, cursp(), pos));
     1575        if (cursp() != pos) {
     1576          genop(s, MKOP_AB(OP_MOVE, cursp(), pos));
     1577        }
    14881578        push();
    14891579      }
     
    15051595  case NODE_FCALL:
    15061596  case NODE_CALL:
    1507     gen_call(s, tree, 0, 0, val);
     1597    gen_call(s, tree, 0, 0, val, 0);
     1598    break;
     1599  case NODE_SCALL:
     1600    gen_call(s, tree, 0, 0, val, 1);
    15081601    break;
    15091602
     
    15531646      int n;
    15541647
    1555       n = gen_values(s, tree, val);
     1648      n = gen_values(s, tree, val, 0);
    15561649      if (n >= 0) {
    15571650        if (val) {
     
    16021695
    16031696  case NODE_SPLAT:
    1604     codegen(s, tree, VAL);
     1697    codegen(s, tree, val);
    16051698    break;
    16061699
     
    16171710      int rhs = cursp();
    16181711
    1619       if ((intptr_t)t->car == NODE_ARRAY && nosplat(t->cdr)) {
     1712      if ((intptr_t)t->car == NODE_ARRAY && t->cdr && nosplat(t->cdr)) {
    16201713        /* fixed rhs */
    16211714        t = t->cdr;
     
    16301723          n = 0;
    16311724          while (t) {
    1632             gen_assignment(s, t->car, rhs+n, NOVAL);
    1633             n++;
     1725            if (n < len) {
     1726              gen_assignment(s, t->car, rhs+n, NOVAL);
     1727              n++;
     1728            }
     1729            else {
     1730              genop(s, MKOP_A(OP_LOADNIL, rhs+n));
     1731              gen_assignment(s, t->car, rhs+n, NOVAL);
     1732            }
    16341733            t = t->cdr;
    16351734          }
     
    16881787      mrb_int len;
    16891788      const char *name = mrb_sym2name_len(s->mrb, sym, &len);
    1690       int idx;
    1691 
    1692       codegen(s, tree->car, VAL);
     1789      int idx, callargs = -1, vsp = -1;
     1790
     1791      if ((len == 2 && name[0] == '|' && name[1] == '|') &&
     1792          ((intptr_t)tree->car->car == NODE_CONST ||
     1793           (intptr_t)tree->car->car == NODE_CVAR)) {
     1794        int onerr, noexc, exc;
     1795        struct loopinfo *lp;
     1796
     1797        onerr = genop(s, MKOP_Bx(OP_ONERR, 0));
     1798        lp = loop_push(s, LOOP_BEGIN);
     1799        lp->pc1 = onerr;
     1800        exc = cursp();
     1801        codegen(s, tree->car, VAL);
     1802        lp->type = LOOP_RESCUE;
     1803        genop(s, MKOP_A(OP_POPERR, 1));
     1804        noexc = genop(s, MKOP_Bx(OP_JMP, 0));
     1805        dispatch(s, onerr);
     1806        genop(s, MKOP_ABC(OP_RESCUE, exc, 0, 0));
     1807        genop(s, MKOP_A(OP_LOADF, exc));
     1808        dispatch(s, noexc);
     1809        loop_pop(s, NOVAL);
     1810      }
     1811      else if ((intptr_t)tree->car->car == NODE_CALL) {
     1812        node *n = tree->car->cdr;
     1813
     1814        if (val) {
     1815          vsp = cursp();
     1816          push();
     1817        }
     1818        codegen(s, n->car, VAL);   /* receiver */
     1819        idx = new_msym(s, sym(n->cdr->car));
     1820        if (n->cdr->cdr->car) {
     1821          int base = cursp()-1;
     1822          int nargs = gen_values(s, n->cdr->cdr->car->car, VAL, 1);
     1823
     1824          /* copy receiver and arguments */
     1825          if (nargs >= 0) {
     1826            int i;
     1827
     1828            genop(s, MKOP_AB(OP_MOVE, cursp(), base));
     1829            for (i=0; i<nargs; i++) {
     1830              genop(s, MKOP_AB(OP_MOVE, cursp()+i+1, base+i+1));
     1831            }
     1832            push_n(nargs+1);
     1833            pop_n(nargs+1);
     1834            callargs = nargs;
     1835          }
     1836          else {
     1837            /* varargs */
     1838            push();
     1839            genop(s, MKOP_AB(OP_MOVE, cursp(), base));
     1840            genop(s, MKOP_AB(OP_MOVE, cursp()+1, base+1));
     1841            callargs = CALL_MAXARGS;
     1842          }
     1843          genop(s, MKOP_ABC(OP_SEND, cursp(), idx, callargs));
     1844        }
     1845        else {
     1846          genop(s, MKOP_AB(OP_MOVE, cursp(), cursp()-1));
     1847          genop(s, MKOP_ABC(OP_SEND, cursp(), idx, 0));
     1848          callargs = 0;
     1849        }
     1850        push();
     1851      }
     1852      else {
     1853        codegen(s, tree->car, VAL);
     1854      }
    16931855      if (len == 2 &&
    16941856          ((name[0] == '|' && name[1] == '|') ||
     
    16971859
    16981860        pop();
    1699         pos = genop_peep(s, MKOP_AsBx(name[0] == '|' ? OP_JMPIF : OP_JMPNOT, cursp(), 0), NOVAL);
     1861        if (val) {
     1862          if (vsp >= 0) {
     1863            genop(s, MKOP_AB(OP_MOVE, vsp, cursp()));
     1864          }
     1865          pos = genop(s, MKOP_AsBx(name[0]=='|'?OP_JMPIF:OP_JMPNOT, cursp(), 0));
     1866        }
     1867        else {
     1868          pos = genop_peep(s, MKOP_AsBx(name[0]=='|'?OP_JMPIF:OP_JMPNOT, cursp(), 0), NOVAL);
     1869        }
    17001870        codegen(s, tree->cdr->cdr->car, VAL);
    17011871        pop();
    1702         gen_assignment(s, tree->car, cursp(), val);
     1872        if (val && vsp >= 0) {
     1873          genop(s, MKOP_AB(OP_MOVE, vsp, cursp()));
     1874        }
     1875        if ((intptr_t)tree->car->car == NODE_CALL) {
     1876          mrb_sym m = sym(tree->car->cdr->cdr->car);
     1877          mrb_sym m2 = attrsym(s, m);
     1878
     1879          idx = new_msym(s, m2);
     1880          pop();
     1881          if (callargs == CALL_MAXARGS) {
     1882            genop(s, MKOP_AB(OP_ARYPUSH, cursp(), cursp()+1));
     1883            pop();
     1884            genop(s, MKOP_ABC(OP_SEND, cursp(), idx, callargs));
     1885          }
     1886          else {
     1887            pop_n(callargs);
     1888            genop(s, MKOP_ABC(OP_SEND, cursp(), idx, callargs+1));
     1889          }
     1890        }
     1891        else {
     1892          gen_assignment(s, tree->car, cursp(), val);
     1893        }
    17031894        dispatch(s, pos);
    1704         break;
     1895        goto exit;
    17051896      }
    17061897      codegen(s, tree->cdr->cdr->car, VAL);
     
    17361927        genop(s, MKOP_ABC(OP_SEND, cursp(), idx, 1));
    17371928      }
    1738     }
    1739     gen_assignment(s, tree->car, cursp(), val);
     1929      if (callargs < 0) {
     1930        gen_assignment(s, tree->car, cursp(), val);
     1931      }
     1932      else {
     1933        if (val && vsp >= 0) {
     1934          genop(s, MKOP_AB(OP_MOVE, vsp, cursp()));
     1935        }
     1936        if (callargs == CALL_MAXARGS) {
     1937          pop();
     1938          genop(s, MKOP_AB(OP_ARYPUSH, cursp(), cursp()+1));
     1939        }
     1940        else {
     1941          pop_n(callargs);
     1942          callargs++;
     1943        }
     1944        pop();
     1945        idx = new_msym(s, attrsym(s,sym(tree->car->cdr->cdr->car)));
     1946        genop(s, MKOP_ABC(OP_SEND, cursp(), idx, callargs));
     1947      }
     1948    }
    17401949    break;
    17411950
    17421951  case NODE_SUPER:
    17431952    {
     1953      codegen_scope *s2 = s;
     1954      int lv = 0;
    17441955      int n = 0, noop = 0, sendv = 0;
    17451956
    17461957      push();        /* room for receiver */
     1958      while (!s2->mscope) {
     1959        lv++;
     1960        s2 = s2->prev;
     1961        if (!s2) break;
     1962      }
     1963      genop(s, MKOP_ABx(OP_ARGARY, cursp(), (lv & 0xf)));
     1964      push(); push();         /* ARGARY pushes two values */
     1965      pop(); pop();
    17471966      if (tree) {
    17481967        node *args = tree->car;
    17491968        if (args) {
    1750           n = gen_values(s, args, VAL);
     1969          n = gen_values(s, args, VAL, 0);
    17511970          if (n < 0) {
    17521971            n = noop = sendv = 1;
     
    17962015  case NODE_RETURN:
    17972016    if (tree) {
    1798       codegen(s, tree, VAL);
    1799       pop();
     2017      gen_retval(s, tree);
    18002018    }
    18012019    else {
     
    18232041      }
    18242042      if (s2) ainfo = s2->ainfo;
    1825       genop(s, MKOP_ABx(OP_BLKPUSH, cursp(), (ainfo<<4)|(lv & 0xf)));
    18262043      push();
    18272044      if (tree) {
    1828         n = gen_values(s, tree, VAL);
     2045        n = gen_values(s, tree, VAL, 0);
    18292046        if (n < 0) {
    18302047          n = sendv = 1;
     
    18332050      }
    18342051      pop_n(n+1);
     2052      genop(s, MKOP_ABx(OP_BLKPUSH, cursp(), (ainfo<<4)|(lv & 0xf)));
    18352053      if (sendv) n = CALL_MAXARGS;
    18362054      genop(s, MKOP_ABC(OP_SEND, cursp(), new_msym(s, mrb_intern_lit(s->mrb, "call")), n));
     
    18692087
    18702088  case NODE_REDO:
    1871     if (!s->loop) {
     2089    if (!s->loop || s->loop->type == LOOP_BEGIN || s->loop->type == LOOP_RESCUE) {
    18722090      raise_error(s, "unexpected redo");
    18732091    }
     
    18782096      genop(s, MKOP_sBx(OP_JMP, s->loop->pc2 - s->pc));
    18792097    }
     2098    if (val) push();
    18802099    break;
    18812100
     
    19122131        }
    19132132      }
     2133      if (val) push();
    19142134    }
    19152135    break;
     
    19842204  case NODE_BACK_REF:
    19852205    if (val) {
    1986       char buf[2] = { '$' };
     2206      char buf[3];
     2207      int sym;
     2208
     2209      buf[0] = '$';
     2210      buf[1] = (char)(intptr_t)tree;
     2211      buf[2] = 0;
     2212      sym = new_sym(s, mrb_intern_cstr(s->mrb, buf));
     2213      genop(s, MKOP_ABx(OP_GETGLOBAL, cursp(), sym));
     2214      push();
     2215    }
     2216    break;
     2217
     2218  case NODE_NTH_REF:
     2219    if (val) {
     2220      mrb_state *mrb = s->mrb;
    19872221      mrb_value str;
    19882222      int sym;
    19892223
    1990       buf[1] = (char)(intptr_t)tree;
    1991       str = mrb_str_new(s->mrb, buf, 2);
    1992       sym = new_sym(s, mrb_intern_str(s->mrb, str));
    1993       genop(s, MKOP_ABx(OP_GETGLOBAL, cursp(), sym));
    1994       push();
    1995     }
    1996     break;
    1997 
    1998   case NODE_NTH_REF:
    1999     if (val) {
    2000       int sym;
    2001       mrb_state *mrb = s->mrb;
    2002       mrb_value fix = mrb_fixnum_value((intptr_t)tree);
    2003       mrb_value str = mrb_str_buf_new(mrb, 4);
    2004 
    2005       mrb_str_cat_lit(mrb, str, "$");
    2006       mrb_str_cat_str(mrb, str, mrb_fixnum_to_str(mrb, fix, 10));
     2224      str = mrb_format(mrb, "$%S", mrb_fixnum_value((mrb_int)(intptr_t)tree));
    20072225      sym = new_sym(s, mrb_intern_str(mrb, str));
    20082226      genop(s, MKOP_ABx(OP_GETGLOBAL, cursp(), sym));
     
    20512269    if (val) {
    20522270      char *p = (char*)tree;
    2053       mrb_float f = str_to_mrb_float(p);
     2271      mrb_float f = mrb_float_read(p, NULL);
    20542272      int off = new_lit(s, mrb_float_value(s->mrb, f));
    20552273
     
    20652283      switch (nt) {
    20662284      case NODE_FLOAT:
    2067         {
     2285        if (val) {
    20682286          char *p = (char*)tree;
    2069           mrb_float f = str_to_mrb_float(p);
     2287          mrb_float f = mrb_float_read(p, NULL);
    20702288          int off = new_lit(s, mrb_float_value(s->mrb, -f));
    20712289
     
    20762294
    20772295      case NODE_INT:
    2078         {
     2296        if (val) {
    20792297          char *p = (char*)tree->car;
    20802298          int base = (intptr_t)tree->cdr->car;
     
    21052323
    21062324      default:
    2107         {
     2325        if (val) {
    21082326          int sym = new_msym(s, mrb_intern_lit(s->mrb, "-"));
    21092327
     
    21132331          pop(); pop();
    21142332          genop(s, MKOP_ABC(OP_SUB, cursp(), sym, 2));
     2333        }
     2334        else {
     2335          codegen(s, tree, NOVAL);
    21152336        }
    21162337        break;
     
    21392360      node *n = tree;
    21402361
    2141       if (!n) break;
     2362      if (!n) {
     2363        genop(s, MKOP_A(OP_LOADNIL, cursp()));
     2364        push();
     2365        break;
     2366      }
    21422367      codegen(s, n->car, VAL);
    21432368      n = n->cdr;
     
    21762401      int sym = new_sym(s, mrb_intern_lit(s->mrb, "Kernel"));
    21772402
    2178       if (val == NOVAL) { push(); }
    2179       genop(s, MKOP_A(OP_OCLASS, cursp()));
    2180       genop(s, MKOP_ABx(OP_GETMCNST, cursp(), sym));
     2403      genop(s, MKOP_A(OP_LOADSELF, cursp()));
    21812404      push();
    21822405      codegen(s, tree->car, VAL);
     
    21932416        n = n->cdr;
    21942417      }
    2195       pop();
    2196       pop();
     2418      push();                   /* for block */
     2419      pop_n(3);
    21972420      sym = new_sym(s, mrb_intern_lit(s->mrb, "`"));
    21982421      genop(s, MKOP_ABC(OP_SEND, cursp(), sym, 1));
    2199       if (val == NOVAL) { pop(); }
    2200       else { push(); }
     2422      if (val) push();
    22012423      mrb_gc_arena_restore(s->mrb, ai);
    22022424    }
     
    22082430      size_t len = (intptr_t)tree->cdr;
    22092431      int ai = mrb_gc_arena_save(s->mrb);
    2210       int sym = new_sym(s, mrb_intern_lit(s->mrb, "Kernel"));
    22112432      int off = new_lit(s, mrb_str_new(s->mrb, p, len));
    2212 
    2213       if (val == NOVAL) { push(); }
    2214       genop(s, MKOP_A(OP_OCLASS, cursp()));
    2215       genop(s, MKOP_ABx(OP_GETMCNST, cursp(), sym));
     2433      int sym;
     2434
     2435      genop(s, MKOP_A(OP_LOADSELF, cursp()));
    22162436      push();
    22172437      genop(s, MKOP_ABx(OP_STRING, cursp(), off));
    2218       pop();
     2438      push(); push();
     2439      pop_n(3);
    22192440      sym = new_sym(s, mrb_intern_lit(s->mrb, "`"));
    22202441      genop(s, MKOP_ABC(OP_SEND, cursp(), sym, 1));
    2221       if (val == NOVAL) { pop(); }
    2222       else { push(); }
     2442      if (val) push();
    22232443      mrb_gc_arena_restore(s->mrb, ai);
    22242444    }
     
    22442464          off = new_lit(s, mrb_str_new_cstr(s->mrb, p2));
    22452465          genop(s, MKOP_ABx(OP_STRING, cursp(), off));
    2246         } else {
     2466        }
     2467        else {
    22472468          genop(s, MKOP_A(OP_LOADNIL, cursp()));
    22482469        }
     
    22952516        genop_peep(s, MKOP_AB(OP_STRCAT, cursp(), cursp()+1), VAL);
    22962517      }
    2297       if (n->cdr) {
    2298         char *p2 = (char*)n->cdr;
     2518      if (n->cdr->car) {
     2519        char *p2 = (char*)n->cdr->car;
    22992520
    23002521        push();
     
    23022523        genop(s, MKOP_ABx(OP_STRING, cursp(), off));
    23032524        argc++;
    2304         pop();
    2305       }
    2306       pop();
     2525      }
     2526      if (n->cdr->cdr) {
     2527        char *p2 = (char*)n->cdr->cdr;
     2528
     2529        push();
     2530        off = new_lit(s, mrb_str_new_cstr(s->mrb, p2));
     2531        genop(s, MKOP_ABx(OP_STRING, cursp(), off));
     2532        argc++;
     2533      }
     2534      pop_n(argc);
    23072535      sym = new_sym(s, mrb_intern_lit(s->mrb, "compile"));
    23082536      genop(s, MKOP_ABC(OP_SEND, cursp(), sym, argc));
     
    23792607      push();
    23802608      genop(s, MKOP_A(OP_LOADNIL, cursp()));
    2381       pop_n(3);
     2609      push();
     2610      pop_n(4);
    23822611      genop(s, MKOP_ABC(OP_SEND, cursp(), c, 2));
    23832612      if (val) {
     
    23962625      push();
    23972626      while (t) {
    2398         int symbol = new_msym(s, sym(t->car));
     2627        int symbol;
     2628        if (num >= CALL_MAXARGS - 1) {
     2629          pop_n(num);
     2630          genop(s, MKOP_ABC(OP_ARRAY, cursp(), cursp(), num));
     2631          while (t) {
     2632            symbol = new_msym(s, sym(t->car));
     2633            push();
     2634            genop(s, MKOP_ABx(OP_LOADSYM, cursp(), symbol));
     2635            pop();
     2636            genop(s, MKOP_AB(OP_ARYPUSH, cursp(), cursp()+1));
     2637            t = t->cdr;
     2638          }
     2639          num = CALL_MAXARGS;
     2640          break;
     2641        }
     2642        symbol = new_msym(s, sym(t->car));
    23992643        genop(s, MKOP_ABx(OP_LOADSYM, cursp(), symbol));
    24002644        push();
     
    24022646        num++;
    24032647      }
    2404       pop_n(num + 1);
     2648      pop();
     2649      if (num < CALL_MAXARGS) {
     2650        pop_n(num);
     2651      }
    24052652      genop(s, MKOP_ABC(OP_SEND, cursp(), undef, num));
    24062653      if (val) {
     
    25292776    break;
    25302777  }
     2778 exit:
     2779  s->rlev = rlev;
    25312780}
    25322781
     
    25702819  p->icapa = 1024;
    25712820  p->iseq = (mrb_code*)mrb_malloc(mrb, sizeof(mrb_code)*p->icapa);
    2572   p->irep->iseq = p->iseq;
     2821  p->irep->iseq = NULL;
    25732822
    25742823  p->pcapa = 32;
     
    25762825  p->irep->plen = 0;
    25772826
    2578   p->scapa = 256;
     2827  p->scapa = MAXMSYMLEN;
    25792828  p->irep->syms = (mrb_sym*)mrb_malloc(mrb, sizeof(mrb_sym)*p->scapa);
    25802829  p->irep->slen = 0;
     
    26202869  p->filename_index = prev->filename_index;
    26212870
     2871  p->rlev = prev->rlev+1;
     2872
    26222873  return p;
    26232874}
     
    26462897  irep->reps = (mrb_irep**)codegen_realloc(s, irep->reps, sizeof(mrb_irep*)*irep->rlen);
    26472898  if (s->filename) {
    2648     s->irep->filename = mrb_parser_get_filename(s->parser, s->filename_index);
    2649     mrb_debug_info_append_file(mrb, s->irep, s->debug_start_pos, s->pc);
     2899    irep->filename = mrb_parser_get_filename(s->parser, s->filename_index);
     2900    mrb_debug_info_append_file(mrb, irep, s->debug_start_pos, s->pc);
    26502901
    26512902    fname_len = strlen(s->filename);
     
    26542905    fname[fname_len] = '\0';
    26552906    irep->filename = fname;
     2907    irep->own_filename = TRUE;
    26562908  }
    26572909
     
    26892941
    26902942    if (tree) {
    2691       codegen(s, tree, VAL);
    2692       pop();
     2943      gen_retval(s, tree);
    26932944    }
    26942945
     
    27022953    }
    27032954    if (!loop) {
    2704       codegen_error(s, "unexpected break");
     2955      raise_error(s, "unexpected break");
     2956      return;
    27052957    }
    27062958
     
    27182970    }
    27192971    else {
     2972      if (!tree) {
     2973        genop(s, MKOP_A(OP_LOADNIL, cursp()));
     2974      }
    27202975      genop(s, MKOP_AB(OP_RETURN, cursp(), OP_R_BREAK));
    27212976    }
     
    27262981loop_pop(codegen_scope *s, int val)
    27272982{
     2983  dispatch_linked(s, s->loop->pc3);
    27282984  if (val) {
    27292985    genop(s, MKOP_A(OP_LOADNIL, cursp()));
    27302986  }
    2731   dispatch_linked(s, s->loop->pc3);
    27322987  s->loop = s->loop->prev;
    27332988  if (val) push();
     
    27392994  codegen_scope *scope = scope_new(mrb, 0, 0);
    27402995  struct RProc *proc;
     2996  struct mrb_jmpbuf *prev_jmp = mrb->jmp;
    27412997
    27422998  if (!scope) {
     
    27493005
    27503006  MRB_TRY(&scope->jmp) {
     3007    mrb->jmp = &scope->jmp;
    27513008    /* prepare irep */
    27523009    codegen(scope, p->tree, NOVAL);
     
    27543011    mrb_irep_decref(mrb, scope->irep);
    27553012    mrb_pool_close(scope->mpool);
     3013    proc->c = NULL;
     3014    mrb->jmp = prev_jmp;
    27563015    return proc;
    27573016  }
    27583017  MRB_CATCH(&scope->jmp) {
    2759     if (scope->filename == scope->irep->filename) {
    2760       scope->irep->filename = NULL;
    2761     }
    27623018    mrb_irep_decref(mrb, scope->irep);
    27633019    mrb_pool_close(scope->mpool);
     3020    mrb->jmp = prev_jmp;
    27643021    return NULL;
    27653022  }
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-compiler/core/lex.def

    • Property svn:keywords deleted
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-compiler/core/node.h

    r321 r331  
    55*/
    66
    7 #ifndef NODE_H
    8 #define NODE_H
     7#ifndef MRUBY_COMPILER_NODE_H
     8#define MRUBY_COMPILER_NODE_H
    99
    1010enum node_type {
     
    3939  NODE_OP_ASGN,
    4040  NODE_CALL,
     41  NODE_SCALL,
    4142  NODE_FCALL,
    4243  NODE_VCALL,
     
    115116};
    116117
    117 #endif  /* NODE_H */
     118#endif  /* MRUBY_COMPILER_NODE_H */
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-compiler/core/parse.y

    r270 r331  
    2323#include <stdlib.h>
    2424#include <string.h>
    25 #include "mruby.h"
    26 #include "mruby/compile.h"
    27 #include "mruby/proc.h"
    28 #include "mruby/error.h"
     25#include <mruby.h>
     26#include <mruby/compile.h>
     27#include <mruby/proc.h>
     28#include <mruby/error.h>
     29#include <mruby/throw.h>
    2930#include "node.h"
    30 #include "mruby/throw.h"
    3131
    3232#define YYLEX_PARAM p
     
    4242static void yywarning(parser_state *p, const char *s);
    4343static void backref_error(parser_state *p, node *n);
     44static void void_expr_error(parser_state *p, node *n);
    4445static void tokadd(parser_state *p, int32_t c);
    4546
     
    7374#define sym(x) ((mrb_sym)(intptr_t)(x))
    7475#define nsym(x) ((node*)(intptr_t)(x))
     76#define nint(x) ((node*)(intptr_t)(x))
     77#define intn(x) ((int)(intptr_t)(x))
    7578
    7679static inline mrb_sym
     
    309312}
    310313
     314static node*
     315new_mod_rescue(parser_state *p, node *body, node *resq)
     316{
     317  return new_rescue(p, body, list1(list3(0, 0, resq)), 0);
     318}
     319
    311320/* (:ensure body ensure) */
    312321static node*
     
    348357new_if(parser_state *p, node *a, node *b, node *c)
    349358{
     359  void_expr_error(p, a);
    350360  return list4((node*)NODE_IF, a, b, c);
    351361}
     
    355365new_unless(parser_state *p, node *a, node *b, node *c)
    356366{
     367  void_expr_error(p, a);
    357368  return list4((node*)NODE_IF, a, c, b);
    358369}
     
    362373new_while(parser_state *p, node *a, node *b)
    363374{
     375  void_expr_error(p, a);
    364376  return cons((node*)NODE_WHILE, cons(a, b));
    365377}
     
    369381new_until(parser_state *p, node *a, node *b)
    370382{
     383  void_expr_error(p, a);
    371384  return cons((node*)NODE_UNTIL, cons(a, b));
    372385}
     
    376389new_for(parser_state *p, node *v, node *o, node *b)
    377390{
     391  void_expr_error(p, o);
    378392  return list4((node*)NODE_FOR, v, o, b);
    379393}
     
    386400  node *n2 = n;
    387401
     402  void_expr_error(p, a);
    388403  while (n2->cdr) {
    389404    n2 = n2->cdr;
     
    409424/* (:call a b c) */
    410425static node*
    411 new_call(parser_state *p, node *a, mrb_sym b, node *c)
    412 {
    413   node *n = list4((node*)NODE_CALL, a, nsym(b), c);
     426new_call(parser_state *p, node *a, mrb_sym b, node *c, int pass)
     427{
     428  node *n = list4(nint(pass?NODE_CALL:NODE_SCALL), a, nsym(b), c);
     429  void_expr_error(p, a);
    414430  NODE_LINENO(n, a);
    415431  return n;
     
    507523new_colon2(parser_state *p, node *b, mrb_sym c)
    508524{
     525  void_expr_error(p, b);
    509526  return cons((node*)NODE_COLON2, cons(b, nsym(c)));
    510527}
     
    614631new_class(parser_state *p, node *c, node *s, node *b)
    615632{
     633  void_expr_error(p, s);
    616634  return list4((node*)NODE_CLASS, c, s, cons(locals_node(p), b));
    617635}
     
    621639new_sclass(parser_state *p, node *o, node *b)
    622640{
     641  void_expr_error(p, o);
    623642  return list3((node*)NODE_SCLASS, o, cons(locals_node(p), b));
    624643}
     
    642661new_sdef(parser_state *p, node *o, mrb_sym m, node *a, node *b)
    643662{
     663  void_expr_error(p, o);
    644664  return list6((node*)NODE_SDEF, o, nsym(m), locals_node(p), a, b);
    645665}
     
    694714new_asgn(parser_state *p, node *a, node *b)
    695715{
     716  void_expr_error(p, b);
    696717  return cons((node*)NODE_ASGN, cons(a, b));
    697718}
     
    701722new_masgn(parser_state *p, node *a, node *b)
    702723{
     724  void_expr_error(p, b);
    703725  return cons((node*)NODE_MASGN, cons(a, b));
    704726}
     
    708730new_op_asgn(parser_state *p, node *a, mrb_sym op, node *b)
    709731{
     732  void_expr_error(p, b);
    710733  return list4((node*)NODE_OP_ASGN, a, nsym(op), b);
    711734}
     
    715738new_int(parser_state *p, const char *s, int base)
    716739{
    717   return list3((node*)NODE_INT, (node*)strdup(s), (node*)(intptr_t)base);
     740  return list3((node*)NODE_INT, (node*)strdup(s), nint(base));
    718741}
    719742
     
    729752new_str(parser_state *p, const char *s, int len)
    730753{
    731   return cons((node*)NODE_STR, cons((node*)strndup(s, len), (node*)(intptr_t)len));
     754  return cons((node*)NODE_STR, cons((node*)strndup(s, len), nint(len)));
    732755}
    733756
     
    743766new_xstr(parser_state *p, const char *s, int len)
    744767{
    745   return cons((node*)NODE_XSTR, cons((node*)strndup(s, len), (node*)(intptr_t)len));
     768  return cons((node*)NODE_XSTR, cons((node*)strndup(s, len), nint(len)));
    746769}
    747770
     
    760783}
    761784
    762 /* (:str . (a . a)) */
     785/* (:regx . (s . (opt . enc))) */
    763786static node*
    764787new_regx(parser_state *p, const char *p1, const char* p2, const char* p3)
     
    767790}
    768791
    769 /* (:dregx . a) */
     792/* (:dregx . (a . b)) */
    770793static node*
    771794new_dregx(parser_state *p, node *a, node *b)
     
    778801new_back_ref(parser_state *p, int n)
    779802{
    780   return cons((node*)NODE_BACK_REF, (node*)(intptr_t)n);
     803  return cons((node*)NODE_BACK_REF, nint(n));
    781804}
    782805
     
    785808new_nth_ref(parser_state *p, int n)
    786809{
    787   return cons((node*)NODE_NTH_REF, (node*)(intptr_t)n);
     810  return cons((node*)NODE_NTH_REF, nint(n));
    788811}
    789812
     
    827850call_uni_op(parser_state *p, node *recv, const char *m)
    828851{
    829   return new_call(p, recv, intern_cstr(m), 0);
     852  void_expr_error(p, recv);
     853  return new_call(p, recv, intern_cstr(m), 0, 1);
    830854}
    831855
     
    834858call_bin_op(parser_state *p, node *recv, const char *m, node *arg1)
    835859{
    836   return new_call(p, recv, intern_cstr(m), list1(list1(arg1)));
     860  return new_call(p, recv, intern_cstr(m), list1(list1(arg1)), 1);
    837861}
    838862
     
    853877  node *n;
    854878
    855   if (a->car == (node*)NODE_SUPER ||
    856       a->car == (node*)NODE_ZSUPER) {
     879  switch ((enum node_type)intn(a->car)) {
     880  case NODE_SUPER:
     881  case NODE_ZSUPER:
    857882    if (!a->cdr) a->cdr = cons(0, b);
    858883    else {
    859884      args_with_block(p, a->cdr, b);
    860885    }
    861   }
    862   else {
     886    break;
     887  case NODE_CALL:
     888  case NODE_FCALL:
     889  case NODE_SCALL:
    863890    n = a->cdr->cdr->cdr;
    864891    if (!n->car) n->car = cons(0, b);
     
    866893      args_with_block(p, n->car, b);
    867894    }
     895    break;
     896  default:
     897    break;
    868898  }
    869899}
     
    895925assignable(parser_state *p, node *lhs)
    896926{
    897   if ((int)(intptr_t)lhs->car == NODE_LVAR) {
     927  if (intn(lhs->car) == NODE_LVAR) {
    898928    local_add(p, sym(lhs->cdr));
    899929  }
     
    905935  node *n;
    906936
    907   if ((int)(intptr_t)lhs->car == NODE_LVAR) {
     937  if (intn(lhs->car) == NODE_LVAR) {
    908938    if (!local_var_p(p, sym(lhs->cdr))) {
    909939      n = new_fcall(p, sym(lhs->cdr), 0);
     
    921951new_strterm(parser_state *p, string_type type, int term, int paren)
    922952{
    923   return cons((node*)(intptr_t)type, cons((node*)0, cons((node*)(intptr_t)paren, (node*)(intptr_t)term)));
     953  return cons(nint(type), cons((node*)0, cons(nint(paren), nint(term))));
    924954}
    925955
     
    10021032  else {
    10031033    /* next heredoc */
    1004     p->lex_strterm->car = (node*)(intptr_t)parsing_heredoc_inf(p)->type;
    1005   }
    1006 }
    1007 #define is_strterm_type(p,str_func) ((int)(intptr_t)((p)->lex_strterm->car) & (str_func))
     1034    p->lex_strterm->car = nint(parsing_heredoc_inf(p)->type);
     1035  }
     1036}
     1037#define is_strterm_type(p,str_func) (intn((p)->lex_strterm->car) & (str_func))
    10081038
    10091039/* xxx ----------------------------- */
     
    10771107%token <id>  tIDENTIFIER tFID tGVAR tIVAR tCONSTANT tCVAR tLABEL
    10781108%token <nd>  tINTEGER tFLOAT tCHAR tXSTRING tREGEXP
    1079 %token <nd>  tSTRING tSTRING_PART tSTRING_MID
     1109%token <nd>  tSTRING tSTRING_PART tSTRING_MID tLABEL_END
    10801110%token <nd>  tNTH_REF tBACK_REF
    10811111%token <num> tREGEXP_END
     
    10851115%type <nd> top_compstmt top_stmts top_stmt
    10861116%type <nd> bodystmt compstmt stmts stmt expr arg primary command command_call method_call
    1087 %type <nd> expr_value arg_value primary_value
     1117%type <nd> expr_value arg_rhs primary_value
    10881118%type <nd> if_tail opt_else case_body cases opt_rescue exc_list exc_var opt_ensure
    10891119%type <nd> args call_args opt_call_args
    10901120%type <nd> paren_args opt_paren_args variable
    10911121%type <nd> command_args aref_args opt_block_arg block_arg var_ref var_lhs
    1092 %type <nd> command_asgn mrhs superclass block_call block_command
     1122%type <nd> command_asgn command_rhs mrhs superclass block_call block_command
    10931123%type <nd> f_block_optarg f_block_opt
    10941124%type <nd> f_arglist f_args f_arg f_arg_item f_optarg f_marg f_marg_list f_margs
     
    11011131%type <id> cname fname op f_rest_arg f_block_arg opt_f_block_arg f_norm_arg f_opt_asgn
    11021132%type <nd> heredoc words symbols
     1133%type <num> call_op call_op2     /* 0:'&.', 1:'.', 2:'::' */
    11031134
    11041135%token tUPLUS             /* unary+ */
     
    11291160%token tAMPER             /* & */
    11301161%token tLAMBDA            /* -> */
     1162%token tANDDOT            /* &. */
    11311163%token tSYMBEG tREGEXP_BEG tWORDS_BEG tSYMBOLS_BEG
    11321164%token tSTRING_BEG tXSTRING_BEG tSTRING_DVAR tLAMBEG
     
    12921324                | stmt modifier_rescue stmt
    12931325                    {
    1294                       $$ = new_rescue(p, $1, list1(list3(0, 0, $3)), 0);
     1326                      $$ = new_mod_rescue(p, $1, $3);
    12951327                    }
    12961328                | keyword_END '{' compstmt '}'
    12971329                    {
    1298                       yyerror(p, "END not suported");
     1330                      yyerror(p, "END not supported");
    12991331                      $$ = new_postexe(p, $3);
    13001332                    }
     
    13041336                      $$ = new_masgn(p, $1, $3);
    13051337                    }
    1306                 | var_lhs tOP_ASGN command_call
     1338                | lhs '=' mrhs
     1339                    {
     1340                      $$ = new_asgn(p, $1, new_array(p, $3));
     1341                    }
     1342                | mlhs '=' arg
     1343                    {
     1344                      $$ = new_masgn(p, $1, $3);
     1345                    }
     1346                | mlhs '=' mrhs
     1347                    {
     1348                      $$ = new_masgn(p, $1, new_array(p, $3));
     1349                    }
     1350                | expr
     1351                ;
     1352
     1353command_asgn    : lhs '=' command_rhs
     1354                    {
     1355                      $$ = new_asgn(p, $1, $3);
     1356                    }
     1357                | var_lhs tOP_ASGN command_rhs
    13071358                    {
    13081359                      $$ = new_op_asgn(p, $1, $2, $3);
    13091360                    }
    1310                 | primary_value '[' opt_call_args rbracket tOP_ASGN command_call
    1311                     {
    1312                       $$ = new_op_asgn(p, new_call(p, $1, intern("[]",2), $3), $5, $6);
    1313                     }
    1314                 | primary_value '.' tIDENTIFIER tOP_ASGN command_call
    1315                     {
    1316                       $$ = new_op_asgn(p, new_call(p, $1, $3, 0), $4, $5);
    1317                     }
    1318                 | primary_value '.' tCONSTANT tOP_ASGN command_call
    1319                     {
    1320                       $$ = new_op_asgn(p, new_call(p, $1, $3, 0), $4, $5);
     1361                | primary_value '[' opt_call_args rbracket tOP_ASGN command_rhs
     1362                    {
     1363                      $$ = new_op_asgn(p, new_call(p, $1, intern("[]",2), $3, '.'), $5, $6);
     1364                    }
     1365                | primary_value call_op tIDENTIFIER tOP_ASGN command_rhs
     1366                    {
     1367                      $$ = new_op_asgn(p, new_call(p, $1, $3, 0, $2), $4, $5);
     1368                    }
     1369                | primary_value call_op tCONSTANT tOP_ASGN command_rhs
     1370                    {
     1371                      $$ = new_op_asgn(p, new_call(p, $1, $3, 0, $2), $4, $5);
    13211372                    }
    13221373                | primary_value tCOLON2 tCONSTANT tOP_ASGN command_call
     
    13251376                      $$ = 0;
    13261377                    }
    1327                 | primary_value tCOLON2 tIDENTIFIER tOP_ASGN command_call
    1328                     {
    1329                       $$ = new_op_asgn(p, new_call(p, $1, $3, 0), $4, $5);
    1330                     }
    1331                 | backref tOP_ASGN command_call
     1378                | primary_value tCOLON2 tIDENTIFIER tOP_ASGN command_rhs
     1379                    {
     1380                      $$ = new_op_asgn(p, new_call(p, $1, $3, 0, tCOLON2), $4, $5);
     1381                    }
     1382                | backref tOP_ASGN command_rhs
    13321383                    {
    13331384                      backref_error(p, $1);
    13341385                      $$ = new_begin(p, 0);
    13351386                    }
    1336                 | lhs '=' mrhs
    1337                     {
    1338                       $$ = new_asgn(p, $1, new_array(p, $3));
    1339                     }
    1340                 | mlhs '=' arg_value
    1341                     {
    1342                       $$ = new_masgn(p, $1, $3);
    1343                     }
    1344                 | mlhs '=' mrhs
    1345                     {
    1346                       $$ = new_masgn(p, $1, new_array(p, $3));
    1347                     }
    1348                 | expr
    1349                 ;
    1350 
    1351 command_asgn    : lhs '=' command_call
    1352                     {
    1353                       $$ = new_asgn(p, $1, $3);
    1354                     }
    1355                 | lhs '=' command_asgn
    1356                     {
    1357                       $$ = new_asgn(p, $1, $3);
    1358                     }
     1387                ;
     1388
     1389command_rhs     : command_call   %prec tOP_ASGN
     1390                | command_call modifier_rescue stmt
     1391                    {
     1392                      $$ = new_mod_rescue(p, $1, $3);
     1393                    }
     1394                | command_asgn
    13591395                ;
    13601396
     
    13831419                    {
    13841420                      if (!$1) $$ = new_nil(p);
    1385                       else $$ = $1;
     1421                      else {
     1422                        $$ = $1;
     1423                      }
    13861424                    }
    13871425                ;
     
    13921430
    13931431block_command   : block_call
    1394                 | block_call dot_or_colon operation2 command_args
     1432                | block_call call_op2 operation2 command_args
     1433                    {
     1434                      $$ = new_call(p, $1, $3, $4, $2);
     1435                    }
    13951436                ;
    13961437
     
    14171458                      $$ = new_fcall(p, $1, $2);
    14181459                    }
    1419                 | primary_value '.' operation2 command_args     %prec tLOWEST
    1420                     {
    1421                       $$ = new_call(p, $1, $3, $4);
    1422                     }
    1423                 | primary_value '.' operation2 command_args cmd_brace_block
     1460                | primary_value call_op operation2 command_args     %prec tLOWEST
     1461                    {
     1462                      $$ = new_call(p, $1, $3, $4, $2);
     1463                    }
     1464                | primary_value call_op operation2 command_args cmd_brace_block
    14241465                    {
    14251466                      args_with_block(p, $4, $5);
    1426                       $$ = new_call(p, $1, $3, $4);
     1467                      $$ = new_call(p, $1, $3, $4, $2);
    14271468                   }
    14281469                | primary_value tCOLON2 operation2 command_args %prec tLOWEST
    14291470                    {
    1430                       $$ = new_call(p, $1, $3, $4);
     1471                      $$ = new_call(p, $1, $3, $4, tCOLON2);
    14311472                    }
    14321473                | primary_value tCOLON2 operation2 command_args cmd_brace_block
    14331474                    {
    14341475                      args_with_block(p, $4, $5);
    1435                       $$ = new_call(p, $1, $3, $4);
     1476                      $$ = new_call(p, $1, $3, $4, tCOLON2);
    14361477                    }
    14371478                | keyword_super command_args
     
    15491590                | primary_value '[' opt_call_args rbracket
    15501591                    {
    1551                       $$ = new_call(p, $1, intern("[]",2), $3);
    1552                     }
    1553                 | primary_value '.' tIDENTIFIER
    1554                     {
    1555                       $$ = new_call(p, $1, $3, 0);
     1592                      $$ = new_call(p, $1, intern("[]",2), $3, '.');
     1593                    }
     1594                | primary_value call_op tIDENTIFIER
     1595                    {
     1596                      $$ = new_call(p, $1, $3, 0, $2);
    15561597                    }
    15571598                | primary_value tCOLON2 tIDENTIFIER
    15581599                    {
    1559                       $$ = new_call(p, $1, $3, 0);
    1560                     }
    1561                 | primary_value '.' tCONSTANT
    1562                     {
    1563                       $$ = new_call(p, $1, $3, 0);
     1600                      $$ = new_call(p, $1, $3, 0, tCOLON2);
     1601                    }
     1602                | primary_value call_op tCONSTANT
     1603                    {
     1604                      $$ = new_call(p, $1, $3, 0, $2);
    15641605                    }
    15651606                | primary_value tCOLON2 tCONSTANT
     
    15881629                | primary_value '[' opt_call_args rbracket
    15891630                    {
    1590                       $$ = new_call(p, $1, intern("[]",2), $3);
    1591                     }
    1592                 | primary_value '.' tIDENTIFIER
    1593                     {
    1594                       $$ = new_call(p, $1, $3, 0);
     1631                      $$ = new_call(p, $1, intern("[]",2), $3, '.');
     1632                    }
     1633                | primary_value call_op tIDENTIFIER
     1634                    {
     1635                      $$ = new_call(p, $1, $3, 0, $2);
    15951636                    }
    15961637                | primary_value tCOLON2 tIDENTIFIER
    15971638                    {
    1598                       $$ = new_call(p, $1, $3, 0);
    1599                     }
    1600                 | primary_value '.' tCONSTANT
    1601                     {
    1602                       $$ = new_call(p, $1, $3, 0);
     1639                      $$ = new_call(p, $1, $3, 0, tCOLON2);
     1640                    }
     1641                | primary_value call_op tCONSTANT
     1642                    {
     1643                      $$ = new_call(p, $1, $3, 0, $2);
    16031644                    }
    16041645                | primary_value tCOLON2 tCONSTANT
     
    16381679                | primary_value tCOLON2 cname
    16391680                    {
     1681                      void_expr_error(p, $1);
    16401682                      $$ = cons($1, nsym($3));
    16411683                    }
     
    17161758                ;
    17171759
    1718 arg             : lhs '=' arg
     1760arg             : lhs '=' arg_rhs
    17191761                    {
    17201762                      $$ = new_asgn(p, $1, $3);
    17211763                    }
    1722                 | lhs '=' arg modifier_rescue arg
    1723                     {
    1724                       $$ = new_asgn(p, $1, new_rescue(p, $3, list1(list3(0, 0, $5)), 0));
    1725                     }
    1726                 | var_lhs tOP_ASGN arg
     1764                | var_lhs tOP_ASGN arg_rhs
    17271765                    {
    17281766                      $$ = new_op_asgn(p, $1, $2, $3);
    17291767                    }
    1730                 | var_lhs tOP_ASGN arg modifier_rescue arg
    1731                     {
    1732                       $$ = new_op_asgn(p, $1, $2, new_rescue(p, $3, list1(list3(0, 0, $5)), 0));
    1733                     }
    1734                 | primary_value '[' opt_call_args rbracket tOP_ASGN arg
    1735                     {
    1736                       $$ = new_op_asgn(p, new_call(p, $1, intern("[]",2), $3), $5, $6);
    1737                     }
    1738                 | primary_value '.' tIDENTIFIER tOP_ASGN arg
    1739                     {
    1740                       $$ = new_op_asgn(p, new_call(p, $1, $3, 0), $4, $5);
    1741                     }
    1742                 | primary_value '.' tCONSTANT tOP_ASGN arg
    1743                     {
    1744                       $$ = new_op_asgn(p, new_call(p, $1, $3, 0), $4, $5);
    1745                     }
    1746                 | primary_value tCOLON2 tIDENTIFIER tOP_ASGN arg
    1747                     {
    1748                       $$ = new_op_asgn(p, new_call(p, $1, $3, 0), $4, $5);
    1749                     }
    1750                 | primary_value tCOLON2 tCONSTANT tOP_ASGN arg
     1768                | primary_value '[' opt_call_args rbracket tOP_ASGN arg_rhs
     1769                    {
     1770                      $$ = new_op_asgn(p, new_call(p, $1, intern("[]",2), $3, '.'), $5, $6);
     1771                    }
     1772                | primary_value call_op tIDENTIFIER tOP_ASGN arg_rhs
     1773                    {
     1774                      $$ = new_op_asgn(p, new_call(p, $1, $3, 0, $2), $4, $5);
     1775                    }
     1776                | primary_value call_op tCONSTANT tOP_ASGN arg_rhs
     1777                    {
     1778                      $$ = new_op_asgn(p, new_call(p, $1, $3, 0, $2), $4, $5);
     1779                    }
     1780                | primary_value tCOLON2 tIDENTIFIER tOP_ASGN arg_rhs
     1781                    {
     1782                      $$ = new_op_asgn(p, new_call(p, $1, $3, 0, tCOLON2), $4, $5);
     1783                    }
     1784                | primary_value tCOLON2 tCONSTANT tOP_ASGN arg_rhs
    17511785                    {
    17521786                      yyerror(p, "constant re-assignment");
    17531787                      $$ = new_begin(p, 0);
    17541788                    }
    1755                 | tCOLON3 tCONSTANT tOP_ASGN arg
     1789                | tCOLON3 tCONSTANT tOP_ASGN arg_rhs
    17561790                    {
    17571791                      yyerror(p, "constant re-assignment");
    17581792                      $$ = new_begin(p, 0);
    17591793                    }
    1760                 | backref tOP_ASGN arg
     1794                | backref tOP_ASGN arg_rhs
    17611795                    {
    17621796                      backref_error(p, $1);
     
    18971931                ;
    18981932
    1899 arg_value       : arg
    1900                     {
    1901                       $$ = $1;
    1902                       if (!$$) $$ = new_nil(p);
    1903                     }
    1904                 ;
    1905 
    19061933aref_args       : none
    19071934                | args trailer
     
    19101937                      NODE_LINENO($$, $1);
    19111938                    }
    1912                 | args ',' assocs trailer
     1939                | args comma assocs trailer
    19131940                    {
    19141941                      $$ = push($1, new_hash(p, $3));
     
    19181945                      $$ = cons(new_hash(p, $1), 0);
    19191946                      NODE_LINENO($$, $1);
     1947                    }
     1948                ;
     1949
     1950arg_rhs         : arg %prec tOP_ASGN
     1951                    {
     1952                      $$ = $1;
     1953                    }
     1954                | arg modifier_rescue arg
     1955                    {
     1956                      void_expr_error(p, $1);
     1957                      void_expr_error(p, $3);
     1958                      $$ = new_mod_rescue(p, $1, $3);
    19201959                    }
    19211960                ;
     
    19381977                      NODE_LINENO($$, $1);
    19391978                    }
    1940                 | args ',' assocs ','
     1979                | args comma assocs ','
    19411980                    {
    19421981                      $$ = cons(push($1, new_hash(p, $3)), 0);
     
    19521991call_args       : command
    19531992                    {
     1993                      void_expr_error(p, $1);
    19541994                      $$ = cons(list1($1), 0);
    19551995                      NODE_LINENO($$, $1);
     
    19652005                      NODE_LINENO($$, $1);
    19662006                    }
    1967                 | args ',' assocs opt_block_arg
     2007                | args comma assocs opt_block_arg
    19682008                    {
    19692009                      $$ = cons(push($1, new_hash(p, $3)), $4);
     
    19882028                ;
    19892029
    1990 block_arg       : tAMPER arg_value
     2030block_arg       : tAMPER arg
    19912031                    {
    19922032                      $$ = new_block_arg(p, $2);
     
    19942034                ;
    19952035
    1996 opt_block_arg   : ',' block_arg
     2036opt_block_arg   : comma block_arg
    19972037                    {
    19982038                      $$ = $2;
     
    20042044                ;
    20052045
    2006 args            : arg_value
    2007                     {
     2046comma           : ','
     2047                | ','  heredoc_bodies
     2048                ;
     2049
     2050args            : arg
     2051                    {
     2052                      void_expr_error(p, $1);
    20082053                      $$ = cons($1, 0);
    20092054                      NODE_LINENO($$, $1);
    20102055                    }
    2011                 | tSTAR arg_value
    2012                     {
     2056                | tSTAR arg
     2057                    {
     2058                      void_expr_error(p, $2);
    20132059                      $$ = cons(new_splat(p, $2), 0);
    20142060                      NODE_LINENO($$, $2);
    20152061                    }
    2016                 | args ',' arg_value
    2017                     {
     2062                | args comma arg
     2063                    {
     2064                      void_expr_error(p, $3);
    20182065                      $$ = push($1, $3);
    20192066                    }
    2020                 | args ',' tSTAR arg_value
    2021                     {
     2067                | args comma tSTAR arg
     2068                    {
     2069                      void_expr_error(p, $4);
    20222070                      $$ = push($1, new_splat(p, $4));
    20232071                    }
    2024                 | args ',' heredoc_bodies arg_value
    2025                     {
    2026                       $$ = push($1, $4);
    2027                     }
    2028                 | args ',' heredoc_bodies tSTAR arg_value
    2029                     {
    2030                       $$ = push($1, new_splat(p, $5));
    2031                     }
    2032                 ;
    2033 
    2034 mrhs            : args ',' arg_value
    2035                     {
     2072                ;
     2073
     2074mrhs            : args comma arg
     2075                    {
     2076                      void_expr_error(p, $3);
    20362077                      $$ = push($1, $3);
    20372078                    }
    2038                 | args ',' tSTAR arg_value
    2039                     {
     2079                | args comma tSTAR arg
     2080                    {
     2081                      void_expr_error(p, $4);
    20402082                      $$ = push($1, new_splat(p, $4));
    20412083                    }
    2042                 | tSTAR arg_value
    2043                     {
     2084                | tSTAR arg
     2085                    {
     2086                      void_expr_error(p, $2);
    20442087                      $$ = list1(new_splat(p, $2));
    20452088                    }
     
    20732116                      p->cmdarg_stack = 0;
    20742117                    }
    2075                   expr {p->lstate = EXPR_ENDARG;} rparen
     2118                  stmt {p->lstate = EXPR_ENDARG;} rparen
    20762119                    {
    20772120                      p->cmdarg_stack = $<stack>2;
     
    20802123                | tLPAREN_ARG {p->lstate = EXPR_ENDARG;} rparen
    20812124                    {
    2082                       $$ = 0;
     2125                      $$ = new_nil(p);
    20832126                    }
    20842127                | tLPAREN compstmt ')'
     
    21082151                      $$ = new_return(p, 0);
    21092152                    }
    2110                 | keyword_yield '(' call_args rparen
    2111                     {
    2112                       $$ = new_yield(p, $3);
    2113                     }
    2114                 | keyword_yield '(' rparen
    2115                     {
    2116                       $$ = new_yield(p, 0);
    2117                     }
    2118                 | keyword_yield
    2119                     {
    2120                       $$ = new_yield(p, 0);
     2153                | keyword_yield opt_paren_args
     2154                    {
     2155                      $$ = new_yield(p, $2);
    21212156                    }
    21222157                | keyword_not '(' expr rparen
     
    22292264                  term
    22302265                    {
    2231                       $<nd>$ = cons(local_switch(p), (node*)(intptr_t)p->in_single);
     2266                      $<nd>$ = cons(local_switch(p), nint(p->in_single));
    22322267                      p->in_single = 0;
    22332268                    }
     
    22392274                      local_resume(p, $<nd>6->car);
    22402275                      p->in_def = $<num>4;
    2241                       p->in_single = (int)(intptr_t)$<nd>6->cdr;
     2276                      p->in_single = intn($<nd>6->cdr);
    22422277                    }
    22432278                | keyword_module
     
    24332468                | f_arg ','
    24342469                    {
    2435                       $$ = new_args(p, $1, 0, 1, 0, 0);
     2470                      $$ = new_args(p, $1, 0, 0, 0, 0);
    24362471                    }
    24372472                | f_arg ',' f_rest_arg ',' f_arg opt_f_block_arg
     
    25612596                      $$ = $1;
    25622597                    }
    2563                 | block_call dot_or_colon operation2 opt_paren_args
    2564                     {
    2565                       $$ = new_call(p, $1, $3, $4);
    2566                     }
    2567                 | block_call dot_or_colon operation2 opt_paren_args brace_block
    2568                     {
    2569                       $$ = new_call(p, $1, $3, $4);
     2598                | block_call call_op2 operation2 opt_paren_args
     2599                    {
     2600                      $$ = new_call(p, $1, $3, $4, $2);
     2601                    }
     2602                | block_call call_op2 operation2 opt_paren_args brace_block
     2603                    {
     2604                      $$ = new_call(p, $1, $3, $4, $2);
    25702605                      call_with_block(p, $$, $5);
    25712606                    }
    2572                 | block_call dot_or_colon operation2 command_args do_block
    2573                     {
    2574                       $$ = new_call(p, $1, $3, $4);
     2607                | block_call call_op2 operation2 command_args do_block
     2608                    {
     2609                      $$ = new_call(p, $1, $3, $4, $2);
    25752610                      call_with_block(p, $$, $5);
    25762611                    }
     
    25812616                      $$ = new_fcall(p, $1, $2);
    25822617                    }
    2583                 | primary_value '.' operation2 opt_paren_args
    2584                     {
    2585                       $$ = new_call(p, $1, $3, $4);
     2618                | primary_value call_op operation2 opt_paren_args
     2619                    {
     2620                      $$ = new_call(p, $1, $3, $4, $2);
    25862621                    }
    25872622                | primary_value tCOLON2 operation2 paren_args
    25882623                    {
    2589                       $$ = new_call(p, $1, $3, $4);
     2624                      $$ = new_call(p, $1, $3, $4, tCOLON2);
    25902625                    }
    25912626                | primary_value tCOLON2 operation3
    25922627                    {
    2593                       $$ = new_call(p, $1, $3, 0);
    2594                     }
    2595                 | primary_value '.' paren_args
    2596                     {
    2597                       $$ = new_call(p, $1, intern("call",4), $3);
     2628                      $$ = new_call(p, $1, $3, 0, tCOLON2);
     2629                    }
     2630                | primary_value call_op paren_args
     2631                    {
     2632                      $$ = new_call(p, $1, intern("call",4), $3, $2);
    25982633                    }
    25992634                | primary_value tCOLON2 paren_args
    26002635                    {
    2601                       $$ = new_call(p, $1, intern("call",4), $3);
     2636                      $$ = new_call(p, $1, intern("call",4), $3, tCOLON2);
    26022637                    }
    26032638                | keyword_super paren_args
     
    26112646                | primary_value '[' opt_call_args rbracket
    26122647                    {
    2613                       $$ = new_call(p, $1, intern("[]",2), $3);
     2648                      $$ = new_call(p, $1, intern("[]",2), $3, '.');
    26142649                    }
    26152650                ;
     
    26712706                ;
    26722707
    2673 exc_list        : arg_value
     2708exc_list        : arg
    26742709                    {
    26752710                        $$ = list1($1);
     
    27662801                ;
    27672802
    2768 opt_heredoc_bodies : /* none */
    2769                    | heredoc_bodies
    2770                    ;
    2771 
    27722803heredoc_bodies  : heredoc_body
    27732804                | heredoc_bodies heredoc_body
     
    28252856                      $$ = new_sym(p, $1);
    28262857                    }
    2827                 | tSYMBEG tSTRING_BEG string_interp tSTRING
     2858                | tSYMBEG tSTRING_BEG string_rep tSTRING
    28282859                    {
    28292860                      p->lstate = EXPR_END;
     
    29252956                | keyword__FILE__
    29262957                    {
    2927                       if (!p->filename) {
    2928                         p->filename = "(null)";
     2958                      const char *fn = p->filename;
     2959                      if (!fn) {
     2960                        fn = "(null)";
    29292961                      }
    2930                       $$ = new_str(p, p->filename, strlen(p->filename));
     2962                      $$ = new_str(p, fn, strlen(fn));
    29312963                    }
    29322964                | keyword__LINE__
     
    29552987                    {
    29562988                      $$ = $3;
    2957                     } /* 
     2989                    } /*
    29582990                | error term
    29592991                    {
     
    30983130                ;
    30993131
    3100 f_opt           : f_opt_asgn arg_value
    3101                     {
     3132f_opt           : f_opt_asgn arg
     3133                    {
     3134                      void_expr_error(p, $2);
    31023135                      $$ = cons(nsym($1), $2);
    31033136                    }
     
    31063139f_block_opt     : f_opt_asgn primary_value
    31073140                    {
     3141                      void_expr_error(p, $2);
    31083142                      $$ = cons(nsym($1), $2);
    31093143                    }
     
    31793213                      }
    31803214                      else {
    3181                         switch ((enum node_type)(int)(intptr_t)$3->car) {
     3215                        switch ((enum node_type)intn($3->car)) {
    31823216                        case NODE_STR:
    31833217                        case NODE_DSTR:
     
    32163250                ;
    32173251
    3218 assoc           : arg_value tASSOC arg_value
    3219                     {
     3252assoc           : arg tASSOC arg
     3253                    {
     3254                      void_expr_error(p, $1);
     3255                      void_expr_error(p, $3);
    32203256                      $$ = cons($1, $3);
    32213257                    }
    3222                 | tLABEL arg_value
    3223                     {
     3258                | tLABEL arg
     3259                    {
     3260                      void_expr_error(p, $2);
    32243261                      $$ = cons(new_sym(p, $1), $2);
     3262                    }
     3263                | tLABEL_END arg
     3264                    {
     3265                      void_expr_error(p, $2);
     3266                      $$ = cons(new_sym(p, new_strsym(p, $1)), $2);
     3267                    }
     3268                | tSTRING_BEG tLABEL_END arg
     3269                    {
     3270                      void_expr_error(p, $3);
     3271                      $$ = cons(new_sym(p, new_strsym(p, $2)), $3);
     3272                    }
     3273                | tSTRING_BEG string_rep tLABEL_END arg
     3274                    {
     3275                      void_expr_error(p, $4);
     3276                      $$ = cons(new_dsym(p, push($2, $3)), $4);
    32253277                    }
    32263278                ;
     
    32463298                ;
    32473299
     3300call_op         : '.'
     3301                    {
     3302                      $$ = '.';
     3303                    }
     3304                | tANDDOT
     3305                    {
     3306                      $$ = 0;
     3307                    }
     3308                ;
     3309
     3310call_op2        : call_op
     3311                | tCOLON2
     3312                    {
     3313                      $$ = tCOLON2;
     3314                    }
     3315                ;
     3316
    32483317opt_terms       : /* none */
    32493318                | terms
     
    32623331trailer         : /* none */
    32633332                | nl
    3264                 | ','
     3333                | comma
    32653334                ;
    32663335
    32673336term            : ';' {yyerrok;}
    32683337                | nl
     3338                | heredoc_body
    32693339                ;
    32703340
     
    32743344                      p->column = 0;
    32753345                    }
    3276                   opt_heredoc_bodies
     3346                ;
    32773347
    32783348terms           : term
    3279                 | terms ';' {yyerrok;}
     3349                | terms term
    32803350                ;
    32813351
     
    32863356                ;
    32873357%%
    3288 #define yylval  (*((YYSTYPE*)(p->ylval)))
     3358#define pylval  (*((YYSTYPE*)(p->ylval)))
    32893359
    32903360static void
     
    33743444
    33753445  if (c == NODE_NTH_REF) {
    3376     yyerror_i(p, "can't set variable $%d", (int)(intptr_t)n->cdr);
     3446    yyerror_i(p, "can't set variable $%" MRB_PRId, (mrb_int)(intptr_t)n->cdr);
    33773447  }
    33783448  else if (c == NODE_BACK_REF) {
     
    33813451  else {
    33823452    mrb_bug(p->mrb, "Internal error in backref_error() : n=>car == %S", mrb_fixnum_value(c));
     3453  }
     3454}
     3455
     3456static void
     3457void_expr_error(parser_state *p, node *n)
     3458{
     3459  int c;
     3460
     3461  if (n == NULL) return;
     3462  c = (int)(intptr_t)n->car;
     3463  switch (c) {
     3464  case NODE_BREAK:
     3465  case NODE_RETURN:
     3466  case NODE_NEXT:
     3467  case NODE_REDO:
     3468  case NODE_RETRY:
     3469    yyerror(p, "void value expression");
     3470    break;
     3471  case NODE_AND:
     3472  case NODE_OR:
     3473    void_expr_error(p, n->cdr->car);
     3474    void_expr_error(p, n->cdr->cdr);
     3475    break;
     3476  case NODE_BEGIN:
     3477    if (n->cdr) {
     3478      while (n->cdr) {
     3479        n = n->cdr;
     3480      }
     3481      void_expr_error(p, n->car);
     3482    }
     3483    break;
     3484  default:
     3485    break;
    33833486  }
    33843487}
     
    34693572    c0 = nextc(p);
    34703573    if (c0 == -1) return c0;    /* do not skip partial EOF */
     3574    if (c0 >= 0) --p->column;
    34713575    list = push(list, (node*)(intptr_t)c0);
    34723576  } while(n--);
     
    35173621    for (;;) {
    35183622      c = nextc(p);
    3519       if (c < 0) return c;
     3623      if (c < 0) return FALSE;
    35203624      if (c == '\n') {
    35213625        p->lineno++;
     
    35473651newtok(parser_state *p)
    35483652{
    3549   p->bidx = 0;
     3653  if (p->tokbuf != p->buf) {
     3654    mrb_free(p->mrb, p->tokbuf);
     3655    p->tokbuf = p->buf;
     3656    p->tsiz = MRB_PARSER_TOKBUF_SIZE;
     3657  }
     3658  p->tidx = 0;
    35503659  return p->column - 1;
    35513660}
     
    35553664{
    35563665  char utf8[4];
    3557   unsigned len;
     3666  int i, len;
    35583667
    35593668  /* mrb_assert(-0x10FFFF <= c && c <= 0xFF); */
     
    35893698    }
    35903699  }
    3591   if (p->bidx+len <= MRB_PARSER_BUF_SIZE) {
    3592     unsigned i;
    3593     for (i = 0; i < len; i++) {
    3594       p->buf[p->bidx++] = utf8[i];
    3595     }
     3700  if (p->tidx+len >= p->tsiz) {
     3701    if (p->tsiz >= MRB_PARSER_TOKBUF_MAX) {
     3702      p->tidx += len;
     3703      return;
     3704    }
     3705    p->tsiz *= 2;
     3706    if (p->tokbuf == p->buf) {
     3707      p->tokbuf = (char*)mrb_malloc(p->mrb, p->tsiz);
     3708      memcpy(p->tokbuf, p->buf, MRB_PARSER_TOKBUF_SIZE);
     3709    }
     3710    else {
     3711      p->tokbuf = (char*)mrb_realloc(p->mrb, p->tokbuf, p->tsiz);
     3712    }
     3713  }
     3714  for (i = 0; i < len; i++) {
     3715    p->tokbuf[p->tidx++] = utf8[i];
    35963716  }
    35973717}
     
    36003720toklast(parser_state *p)
    36013721{
    3602   return p->buf[p->bidx-1];
     3722  return p->tokbuf[p->tidx-1];
    36033723}
    36043724
     
    36063726tokfix(parser_state *p)
    36073727{
    3608   int i = p->bidx, imax = MRB_PARSER_BUF_SIZE - 1;
    3609 
    3610   if (i > imax) {
    3611     i = imax;
     3728  if (p->tidx >= MRB_PARSER_TOKBUF_MAX) {
     3729    p->tidx = MRB_PARSER_TOKBUF_MAX-1;
    36123730    yyerror(p, "string too long (truncated)");
    36133731  }
    3614   p->buf[i] = '\0';
     3732  p->tokbuf[p->tidx] = '\0';
    36153733}
    36163734
     
    36183736tok(parser_state *p)
    36193737{
    3620   return p->buf;
     3738  return p->tokbuf;
    36213739}
    36223740
     
    36243742toklen(parser_state *p)
    36253743{
    3626   return p->bidx;
     3744  return p->tidx;
    36273745}
    36283746
     
    36673785
    36683786  return retval;
     3787}
     3788
     3789static int32_t
     3790read_escape_unicode(parser_state *p, int limit)
     3791{
     3792  int32_t c;
     3793  int buf[9];
     3794  int i;
     3795
     3796  /* Look for opening brace */
     3797  i = 0;
     3798  buf[0] = nextc(p);
     3799  if (buf[0] < 0) goto eof;
     3800  if (ISXDIGIT(buf[0])) {
     3801    /* \uxxxx form */
     3802    for (i=1; i<limit; i++) {
     3803      buf[i] = nextc(p);
     3804      if (buf[i] < 0) goto eof;
     3805      if (!ISXDIGIT(buf[i])) {
     3806        pushback(p, buf[i]);
     3807        break;
     3808      }
     3809    }
     3810  }
     3811  else {
     3812    pushback(p, buf[0]);
     3813  }
     3814  c = scan_hex(buf, i, &i);
     3815  if (i == 0) {
     3816  eof:
     3817    yyerror(p, "Invalid escape character syntax");
     3818    return -1;
     3819  }
     3820  if (c < 0 || c > 0x10FFFF || (c & 0xFFFFF800) == 0xD800) {
     3821    yyerror(p, "Invalid Unicode code point");
     3822    return -1;
     3823  }
     3824  return c;
    36693825}
    36703826
     
    37413897
    37423898  case 'u':     /* Unicode */
    3743   {
    3744     int buf[9];
    3745     int i;
    3746 
    3747     /* Look for opening brace */
    3748     i = 0;
    3749     buf[0] = nextc(p);
    3750     if (buf[0] < 0) goto eof;
    3751     if (buf[0] == '{') {
     3899    if (peek(p, '{')) {
    37523900      /* \u{xxxxxxxx} form */
    3753       for (i=0; i<9; i++) {
    3754         buf[i] = nextc(p);
    3755         if (buf[i] < 0) goto eof;
    3756         if (buf[i] == '}') {
    3757           break;
    3758         }
    3759         else if (!ISXDIGIT(buf[i])) {
    3760           yyerror(p, "Invalid escape character syntax");
    3761           pushback(p, buf[i]);
    3762           return 0;
    3763         }
    3764       }
    3765     }
    3766     else if (ISXDIGIT(buf[0])) {
    3767       /* \uxxxx form */
    3768       for (i=1; i<4; i++) {
    3769         buf[i] = nextc(p);
    3770         if (buf[i] < 0) goto eof;
    3771         if (!ISXDIGIT(buf[i])) {
    3772           pushback(p, buf[i]);
    3773           break;
    3774         }
    3775       }
     3901      nextc(p);
     3902      c = read_escape_unicode(p, 8);
     3903      if (c < 0) return 0;
     3904      if (nextc(p) != '}') goto eof;
    37763905    }
    37773906    else {
    3778       pushback(p, buf[0]);
    3779     }
    3780     c = scan_hex(buf, i, &i);
    3781     if (i == 0) {
    3782       yyerror(p, "Invalid escape character syntax");
    3783       return 0;
    3784     }
    3785     if (c < 0 || c > 0x10FFFF || (c & 0xFFFFF800) == 0xD800) {
    3786       yyerror(p, "Invalid Unicode code point");
    3787       return 0;
    3788     }
    3789   }
     3907      c = read_escape_unicode(p, 4);
     3908      if (c < 0) return 0;
     3909    }
    37903910  return -c;
    37913911
     
    38453965  int end = (intptr_t)p->lex_strterm->cdr->cdr->cdr;
    38463966  parser_heredoc_info *hinf = (type & STR_FUNC_HEREDOC) ? parsing_heredoc_inf(p) : NULL;
    3847 
     3967  int cmd_state = p->cmd_start;
     3968
     3969  if (beg == 0) beg = -3;       /* should never happen */
     3970  if (end == 0) end = -3;
    38483971  newtok(p);
    38493972  while ((c = nextc(p)) != end || nest_level != 0) {
     
    38673990        }
    38683991        if ((len-1 == hinf->term_len) && (strncmp(s, hinf->term, len-1) == 0)) {
    3869           return tHEREDOC_END;
     3992          if (c < 0) {
     3993            p->parsing_heredoc = NULL;
     3994          }
     3995          else {
     3996            return tHEREDOC_END;
     3997          }
    38703998        }
    38713999      }
     
    38764004        return 0;
    38774005      }
    3878       yylval.nd = new_str(p, tok(p), toklen(p));
     4006      pylval.nd = new_str(p, tok(p), toklen(p));
    38794007      return tHD_STRING_MID;
    38804008    }
     
    39084036          tokadd(p, c);
    39094037        }
     4038        else if (c == 'u' && peek(p, '{')) {
     4039          /* \u{xxxx xxxx xxxx} form */
     4040          nextc(p);
     4041          while (1) {
     4042            do c = nextc(p); while (ISSPACE(c));
     4043            if (c == '}') break;
     4044            pushback(p, c);
     4045            c = read_escape_unicode(p, 8);
     4046            if (c < 0) break;
     4047            tokadd(p, -c);
     4048          }
     4049          if (hinf)
     4050            hinf->line_head = FALSE;
     4051        }
    39104052        else {
    39114053          pushback(p, c);
     
    39354077        p->lstate = EXPR_BEG;
    39364078        p->cmd_start = TRUE;
    3937         yylval.nd = new_str(p, tok(p), toklen(p));
     4079        pylval.nd = new_str(p, tok(p), toklen(p));
    39384080        if (hinf) {
    39394081          hinf->line_head = FALSE;
     
    39654107        pushback(p, c);
    39664108        tokfix(p);
    3967         yylval.nd = new_str(p, tok(p), toklen(p));
     4109        pylval.nd = new_str(p, tok(p), toklen(p));
    39684110        return tSTRING_MID;
    39694111      }
     4112    }
     4113    if (c == '\n') {
     4114      p->lineno++;
     4115      p->column = 0;
    39704116    }
    39714117    tokadd(p, c);
     
    39774123
    39784124  if (type & STR_FUNC_XQUOTE) {
    3979     yylval.nd = new_xstr(p, tok(p), toklen(p));
     4125    pylval.nd = new_xstr(p, tok(p), toklen(p));
    39804126    return tXSTRING;
    39814127  }
     
    40194165    if (flag > flags) {
    40204166      dup = strndup(flags, (size_t)(flag - flags));
    4021     } else {
     4167    }
     4168    else {
    40224169      dup = NULL;
    40234170    }
    40244171    if (enc) {
    40254172      encp = strndup(&enc, 1);
    4026     } else {
     4173    }
     4174    else {
    40274175      encp = NULL;
    40284176    }
    4029     yylval.nd = new_regx(p, s, dup, encp);
     4177    pylval.nd = new_regx(p, s, dup, encp);
    40304178
    40314179    return tREGEXP;
    40324180  }
    4033 
    4034   yylval.nd = new_str(p, tok(p), toklen(p));
     4181  pylval.nd = new_str(p, tok(p), toklen(p));
     4182  if (IS_LABEL_POSSIBLE()) {
     4183    if (IS_LABEL_SUFFIX(0)) {
     4184      p->lstate = EXPR_BEG;
     4185      nextc(p);
     4186      return tLABEL_END;
     4187    }
     4188  }
     4189
    40354190  return tSTRING;
    40364191}
     
    41024257  p->lstate = EXPR_END;
    41034258
    4104   yylval.nd = newnode;
     4259  pylval.nd = newnode;
    41054260  return tHEREDOC_BEG;
    41064261}
     
    42064361    if ((c = nextc(p)) == '*') {
    42074362      if ((c = nextc(p)) == '=') {
    4208         yylval.id = intern("**",2);
     4363        pylval.id = intern("**",2);
    42094364        p->lstate = EXPR_BEG;
    42104365        return tOP_ASGN;
     
    42154370    else {
    42164371      if (c == '=') {
    4217         yylval.id = intern_c('*');
     4372        pylval.id = intern_c('*');
    42184373        p->lstate = EXPR_BEG;
    42194374        return tOP_ASGN;
     
    43314486    if (c == '<') {
    43324487      if ((c = nextc(p)) == '=') {
    4333         yylval.id = intern("<<",2);
     4488        pylval.id = intern("<<",2);
    43344489        p->lstate = EXPR_BEG;
    43354490        return tOP_ASGN;
     
    43534508    if (c == '>') {
    43544509      if ((c = nextc(p)) == '=') {
    4355         yylval.id = intern(">>",2);
     4510        pylval.id = intern(">>",2);
    43564511        p->lstate = EXPR_BEG;
    43574512        return tOP_ASGN;
     
    44504605    }
    44514606    tokfix(p);
    4452     yylval.nd = new_str(p, tok(p), toklen(p));
     4607    pylval.nd = new_str(p, tok(p), toklen(p));
    44534608    p->lstate = EXPR_END;
    44544609    return tCHAR;
     
    44584613      p->lstate = EXPR_BEG;
    44594614      if ((c = nextc(p)) == '=') {
    4460         yylval.id = intern("&&",2);
     4615        pylval.id = intern("&&",2);
    44614616        p->lstate = EXPR_BEG;
    44624617        return tOP_ASGN;
     
    44654620      return tANDOP;
    44664621    }
     4622    else if (c == '.') {
     4623      p->lstate = EXPR_DOT;
     4624      return tANDDOT;
     4625    }
    44674626    else if (c == '=') {
    4468       yylval.id = intern_c('&');
     4627      pylval.id = intern_c('&');
    44694628      p->lstate = EXPR_BEG;
    44704629      return tOP_ASGN;
     
    44934652      p->lstate = EXPR_BEG;
    44944653      if ((c = nextc(p)) == '=') {
    4495         yylval.id = intern("||",2);
     4654        pylval.id = intern("||",2);
    44964655        p->lstate = EXPR_BEG;
    44974656        return tOP_ASGN;
     
    45014660    }
    45024661    if (c == '=') {
    4503       yylval.id = intern_c('|');
     4662      pylval.id = intern_c('|');
    45044663      p->lstate = EXPR_BEG;
    45054664      return tOP_ASGN;
     
    45254684    }
    45264685    if (c == '=') {
    4527       yylval.id = intern_c('+');
     4686      pylval.id = intern_c('+');
    45284687      p->lstate = EXPR_BEG;
    45294688      return tOP_ASGN;
     
    45534712    }
    45544713    if (c == '=') {
    4555       yylval.id = intern_c('-');
     4714      pylval.id = intern_c('-');
    45564715      p->lstate = EXPR_BEG;
    45574716      return tOP_ASGN;
     
    46274786        }
    46284787        else if (nondigit) goto trailing_uc;
    4629         yylval.nd = new_int(p, tok(p), 16);
     4788        pylval.nd = new_int(p, tok(p), 16);
    46304789        return tINTEGER;
    46314790      }
     
    46514810        }
    46524811        else if (nondigit) goto trailing_uc;
    4653         yylval.nd = new_int(p, tok(p), 2);
     4812        pylval.nd = new_int(p, tok(p), 2);
    46544813        return tINTEGER;
    46554814      }
     
    46754834        }
    46764835        else if (nondigit) goto trailing_uc;
    4677         yylval.nd = new_int(p, tok(p), 10);
     4836        pylval.nd = new_int(p, tok(p), 10);
    46784837        return tINTEGER;
    46794838      }
     
    47084867          tokfix(p);
    47094868          if (nondigit) goto trailing_uc;
    4710           yylval.nd = new_int(p, tok(p), 8);
     4869          pylval.nd = new_int(p, tok(p), 8);
    47114870          return tINTEGER;
    47124871        }
     
    47254884      else {
    47264885        pushback(p, c);
    4727         yylval.nd = new_int(p, "0", 10);
     4886        pylval.nd = new_int(p, "0", 10);
    47284887        return tINTEGER;
    47294888      }
     
    48014960
    48024961      errno = 0;
    4803       d = strtod(tok(p), &endp);
     4962      d = mrb_float_read(tok(p), &endp);
    48044963      if (d == 0 && endp == tok(p)) {
    48054964        yywarning_s(p, "corrupted float value %s", tok(p));
     
    48094968        errno = 0;
    48104969      }
    4811       yylval.nd = new_float(p, tok(p));
     4970      pylval.nd = new_float(p, tok(p));
    48124971      return tFLOAT;
    48134972    }
    4814     yylval.nd = new_int(p, tok(p), 10);
     4973    pylval.nd = new_int(p, tok(p), 10);
    48154974    return tINTEGER;
    48164975  }
     
    48545013    }
    48555014    if ((c = nextc(p)) == '=') {
    4856       yylval.id = intern_c('/');
     5015      pylval.id = intern_c('/');
    48575016      p->lstate = EXPR_BEG;
    48585017      return tOP_ASGN;
     
    48735032  case '^':
    48745033    if ((c = nextc(p)) == '=') {
    4875       yylval.id = intern_c('^');
     5034      pylval.id = intern_c('^');
    48765035      p->lstate = EXPR_BEG;
    48775036      return tOP_ASGN;
     
    50475206    }
    50485207    if ((c = nextc(p)) == '=') {
    5049       yylval.id = intern_c('%');
     5208      pylval.id = intern_c('%');
    50505209      p->lstate = EXPR_BEG;
    50515210      return tOP_ASGN;
     
    51015260      tokadd(p, c);
    51025261      tokfix(p);
    5103       yylval.id = intern_cstr(tok(p));
     5262      pylval.id = intern_cstr(tok(p));
    51045263      return tGVAR;
    51055264
     
    51115270      gvar:
    51125271      tokfix(p);
    5113       yylval.id = intern_cstr(tok(p));
     5272      pylval.id = intern_cstr(tok(p));
    51145273      return tGVAR;
    51155274
     
    51235282        goto gvar;
    51245283      }
    5125       yylval.nd = new_back_ref(p, c);
     5284      pylval.nd = new_back_ref(p, c);
    51265285      return tBACK_REF;
    51275286
     
    51425301          return 0;
    51435302        }
    5144         yylval.nd = new_nth_ref(p, (int)n);
     5303        pylval.nd = new_nth_ref(p, (int)n);
    51455304      }
    51465305      return tNTH_REF;
     
    51665325      }
    51675326      if (c < 0) {
    5168         if (p->bidx == 1) {
     5327        if (p->tidx == 1) {
    51695328          yyerror(p, "incomplete instance variable syntax");
    51705329        }
     
    51755334      }
    51765335      else if (isdigit(c)) {
    5177         if (p->bidx == 1) {
     5336        if (p->tidx == 1) {
    51785337          yyerror_i(p, "'@%c' is not allowed as an instance variable name", c);
    51795338        }
     
    52705429          nextc(p);
    52715430          tokfix(p);
    5272           yylval.id = intern_cstr(tok(p));
     5431          pylval.id = intern_cstr(tok(p));
    52735432          return tLABEL;
    52745433        }
     
    52815440        if (kw) {
    52825441          enum mrb_lex_state_enum state = p->lstate;
    5283           yylval.num = p->lineno;
     5442          pylval.num = p->lineno;
    52845443          p->lstate = kw->state;
    52855444          if (state == EXPR_FNAME) {
    5286             yylval.id = intern_cstr(kw->name);
     5445            pylval.id = intern_cstr(kw->name);
    52875446            return kw->id[0];
    52885447          }
     
    53315490      mrb_sym ident = intern_cstr(tok(p));
    53325491
    5333       yylval.id = ident;
     5492      pylval.id = ident;
    53345493#if 0
    53355494      if (last_state != EXPR_DOT && islower(tok(p)[0]) && lvar_defined(ident)) {
     
    53965555mrb_parser_parse(parser_state *p, mrbc_context *c)
    53975556{
    5398   struct mrb_jmpbuf buf;
    5399   p->jmp = &buf;
     5557  struct mrb_jmpbuf buf1;
     5558  p->jmp = &buf1;
    54005559
    54015560  MRB_TRY(p->jmp) {
     5561    int n;
    54025562
    54035563    p->cmd_start = TRUE;
     
    54075567
    54085568    parser_init_cxt(p, c);
    5409     yyparse(p);
     5569
     5570    if (p->mrb->jmp) {
     5571      n = yyparse(p);
     5572    }
     5573    else {
     5574      struct mrb_jmpbuf buf2;
     5575
     5576      p->mrb->jmp = &buf2;
     5577      MRB_TRY(p->mrb->jmp) {
     5578        n = yyparse(p);
     5579      }
     5580      MRB_CATCH(p->mrb->jmp) {
     5581        p->nerr++;
     5582      }
     5583      MRB_END_EXC(p->mrb->jmp);
     5584      p->mrb->jmp = 0;
     5585    }
     5586    if (n != 0 || p->nerr > 0) {
     5587      p->tree = 0;
     5588      return;
     5589    }
    54105590    if (!p->tree) {
    54115591      p->tree = new_nil(p);
     
    54155595      mrb_parser_dump(p->mrb, p->tree, 0);
    54165596    }
    5417 
    54185597  }
    54195598  MRB_CATCH(p->jmp) {
     
    54435622
    54445623  p->s = p->send = NULL;
    5445 #ifndef MRB_DISBLE_STDIO
     5624#ifndef MRB_DISABLE_STDIO
    54465625  p->f = NULL;
    54475626#endif
     
    54565635  yydebug = 1;
    54575636#endif
     5637  p->tsiz = MRB_PARSER_TOKBUF_SIZE;
     5638  p->tokbuf = p->buf;
    54585639
    54595640  p->lex_strterm = NULL;
     
    54705651MRB_API void
    54715652mrb_parser_free(parser_state *p) {
     5653  if (p->tokbuf != p->buf) {
     5654    mrb_free(p->mrb, p->tokbuf);
     5655  }
    54725656  mrb_pool_close(p->pool);
    54735657}
     
    54825666mrbc_context_free(mrb_state *mrb, mrbc_context *cxt)
    54835667{
     5668  mrb_free(mrb, cxt->filename);
    54845669  mrb_free(mrb, cxt->syms);
    54855670  mrb_free(mrb, cxt);
     
    54915676  if (s) {
    54925677    int len = strlen(s);
    5493     char *p = (char *)mrb_alloca(mrb, len + 1);
     5678    char *p = (char *)mrb_malloc(mrb, len + 1);
    54945679
    54955680    memcpy(p, s, len + 1);
     5681    if (c->filename) {
     5682      mrb_free(mrb, c->filename);
     5683    }
    54965684    c->filename = p;
    54975685  }
     
    55785766}
    55795767
    5580 static mrb_value
    5581 load_exec(mrb_state *mrb, parser_state *p, mrbc_context *c)
     5768MRB_API mrb_value
     5769mrb_load_exec(mrb_state *mrb, struct mrb_parser_state *p, mrbc_context *c)
    55825770{
    55835771  struct RClass *target = mrb->object_class;
     
    56015789    }
    56025790    else {
    5603       mrb->exc = mrb_obj_ptr(mrb_exc_new_str_lit(mrb, E_SYNTAX_ERROR, "syntax error"));
     5791      if (mrb->exc == NULL) {
     5792        mrb->exc = mrb_obj_ptr(mrb_exc_new_str_lit(mrb, E_SYNTAX_ERROR, "syntax error"));
     5793      }
    56045794      mrb_parser_free(p);
    56055795      return mrb_undef_value();
     
    56095799  mrb_parser_free(p);
    56105800  if (proc == NULL) {
    5611     mrb->exc = mrb_obj_ptr(mrb_exc_new_str_lit(mrb, E_SCRIPT_ERROR, "codegen error"));
     5801    if (mrb->exc == NULL) {
     5802      mrb->exc = mrb_obj_ptr(mrb_exc_new_str_lit(mrb, E_SCRIPT_ERROR, "codegen error"));
     5803    }
    56125804    return mrb_undef_value();
    56135805  }
     
    56295821    mrb->c->ci->target_class = target;
    56305822  }
    5631   v = mrb_toplevel_run_keep(mrb, proc, keep);
     5823  v = mrb_top_run(mrb, proc, mrb_top_self(mrb), keep);
    56325824  if (mrb->exc) return mrb_nil_value();
    56335825  return v;
     
    56385830mrb_load_file_cxt(mrb_state *mrb, FILE *f, mrbc_context *c)
    56395831{
    5640   return load_exec(mrb, mrb_parse_file(mrb, f, c), c);
     5832  return mrb_load_exec(mrb, mrb_parse_file(mrb, f, c), c);
    56415833}
    56425834
     
    56515843mrb_load_nstring_cxt(mrb_state *mrb, const char *s, int len, mrbc_context *c)
    56525844{
    5653   return load_exec(mrb, mrb_parse_nstring(mrb, s, len, c), c);
     5845  return mrb_load_exec(mrb, mrb_parse_nstring(mrb, s, len, c), c);
    56545846}
    56555847
     
    58055997        dump_recur(mrb, n->car, offset+2);
    58065998      }
    5807       n = n->cdr;
    5808       if (n) {
     5999      if (n->cdr) {
    58096000        dump_prefix(n, offset+1);
    5810         printf("blk=&%s\n", mrb_sym2name(mrb, sym(n)));
     6001        printf("blk=&%s\n", mrb_sym2name(mrb, sym(n->cdr)));
    58116002      }
    58126003    }
     
    59466137  case NODE_FCALL:
    59476138  case NODE_CALL:
    5948     printf("NODE_CALL:\n");
     6139  case NODE_SCALL:
     6140    switch (nodetype) {
     6141    case NODE_FCALL:
     6142      printf("NODE_FCALL:\n"); break;
     6143    case NODE_CALL:
     6144      printf("NODE_CALL(.):\n"); break;
     6145    case NODE_SCALL:
     6146      printf("NODE_SCALL(&.):\n"); break;
     6147    default:
     6148      break;
     6149    }
    59496150    mrb_parser_dump(mrb, tree->car, offset+1);
    59506151    dump_prefix(tree, offset+1);
     
    61546355
    61556356  case NODE_NTH_REF:
    6156     printf("NODE_NTH_REF: $%d\n", (int)(intptr_t)tree);
     6357    printf("NODE_NTH_REF: $%" MRB_PRId "\n", (mrb_int)(intptr_t)tree);
    61576358    break;
    61586359
     
    62066407    dump_prefix(tree, offset);
    62076408    printf("tail: %s\n", (char*)tree->cdr->cdr->car);
    6208     dump_prefix(tree, offset);
    6209     printf("opt: %s\n", (char*)tree->cdr->cdr->cdr);
     6409    if (tree->cdr->cdr->cdr->car) {
     6410      dump_prefix(tree, offset);
     6411      printf("opt: %s\n", (char*)tree->cdr->cdr->cdr->car);
     6412    }
     6413    if (tree->cdr->cdr->cdr->cdr) {
     6414      dump_prefix(tree, offset);
     6415      printf("enc: %s\n", (char*)tree->cdr->cdr->cdr->cdr);
     6416    }
    62106417    break;
    62116418
    62126419  case NODE_SYM:
    6213     printf("NODE_SYM :%s\n", mrb_sym2name(mrb, sym(tree)));
     6420    printf("NODE_SYM :%s (%d)\n", mrb_sym2name(mrb, sym(tree)),
     6421           (int)(intptr_t)tree);
    62146422    break;
    62156423
     
    64256633
    64266634  case NODE_HEREDOC:
    6427     printf("NODE_HEREDOC:\n");
    6428     mrb_parser_dump(mrb, ((parser_heredoc_info*)tree)->doc, offset+1);
     6635    printf("NODE_HEREDOC (<<%s):\n", ((parser_heredoc_info*)tree)->term);
     6636    dump_recur(mrb, ((parser_heredoc_info*)tree)->doc, offset+1);
    64296637    break;
    64306638
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-compiler/mrbgem.rake

    r321 r331  
    99  lex_def = "#{current_dir}/core/lex.def"
    1010  core_objs = Dir.glob("#{current_dir}/core/*.c").map { |f|
    11     next nil if build.cxx_abi_enabled? and f =~ /(codegen).c$/
     11    next nil if build.cxx_exception_enabled? and f =~ /(codegen).c$/
    1212    objfile(f.pathmap("#{current_build_dir}/core/%n"))
    1313  }.compact
    1414
    15   if build.cxx_abi_enabled?
     15  if build.cxx_exception_enabled?
    1616    core_objs <<
    1717      build.compile_as_cxx("#{current_build_dir}/core/y.tab.c", "#{current_build_dir}/core/y.tab.cxx",
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-enum-ext/mrblib/enum.rb

    r321 r331  
    5959  def take(n)
    6060    raise TypeError, "no implicit conversion of #{n.class} into Integer" unless n.respond_to?(:to_int)
    61     raise ArgumentError, "attempt to take negative size" if n < 0
    62 
    63     n = n.to_int
    64     ary = []
    65     self.each do |*val|
    66       break if ary.size >= n
     61    i = n.to_int
     62    raise ArgumentError, "attempt to take negative size" if i < 0
     63    ary = []
     64    return ary if i == 0
     65    self.each do |*val|
    6766      ary << val.__svalue
     67      i -= 1
     68      break if i == 0
    6869    end
    6970    ary
     
    124125      block.call(ary.dup) if ary.size == n
    125126    end
     127    nil
    126128  end
    127129
     
    154156    end
    155157    block.call(ary) unless ary.empty?
     158    nil
    156159  end
    157160
     
    215218  # If the enumerable is empty, the first form returns <code>nil</code>, and the
    216219  # second form returns an empty array.
    217   def first(n=NONE)
    218     if n == NONE
     220  def first(*args)
     221    case args.length
     222    when 0
    219223      self.each do |*val|
    220224        return val.__svalue
    221225      end
    222226      return nil
     227    when 1
     228      n = args[0]
     229      raise TypeError, "no implicit conversion of #{n.class} into Integer" unless n.respond_to?(:to_int)
     230      i = n.to_int
     231      raise ArgumentError, "attempt to take negative size" if i < 0
     232      ary = []
     233      return ary if i == 0
     234      self.each do |*val|
     235        ary << val.__svalue
     236        i -= 1
     237        break if i == 0
     238      end
     239      ary
    223240    else
    224       a = []
    225       i = 0
    226       self.each do |*val|
    227         break if n<=i
    228         a.push val.__svalue
    229         i += 1
    230       end
    231       a
     241      raise ArgumentError, "wrong number of arguments (given #{args.length}, expected 0..1)"
    232242    end
    233243  end
     
    385395        first = false
    386396      else
     397        val = val.__svalue
    387398        if block
    388           max = val.__svalue if block.call(*val, max) > 0
    389           min = val.__svalue if block.call(*val, min) < 0
     399          max = val if block.call(val, max) > 0
     400          min = val if block.call(val, min) < 0
    390401        else
    391           val = val.__svalue
    392402          max = val if (val <=> max) > 0
    393403          min = val if (val <=> min) < 0
     
    574584  #
    575585
    576   def cycle(n=nil, &block)
    577     return to_enum(:cycle, n) if !block && n.nil?
    578 
    579     ary = []
    580     if n.nil?
    581       self.each do|*val|
    582         ary.push val
    583         block.call(*val)
    584       end
    585       loop do
    586         ary.each do|e|
    587           block.call(*e)
    588         end
    589       end
     586  def cycle(nv = nil, &block)
     587    return to_enum(:cycle, nv) unless block
     588
     589    n = nil
     590
     591    if nv.nil?
     592      n = -1
    590593    else
    591       raise TypeError, "no implicit conversion of #{n.class} into Integer" unless n.respond_to?(:to_int)
    592 
    593       n = n.to_int
    594       self.each do|*val|
    595         ary.push val
    596       end
    597       count = 0
    598       while count < n
    599         ary.each do|e|
    600           block.call(*e)
    601         end
    602         count += 1
    603       end
    604     end
     594      unless nv.respond_to?(:to_int)
     595        raise TypeError, "no implicit conversion of #{nv.class} into Integer"
     596      end
     597      n = nv.to_int
     598      unless n.kind_of?(Integer)
     599        raise TypeError, "no implicit conversion of #{nv.class} into Integer"
     600      end
     601      return nil if n <= 0
     602    end
     603
     604    ary = []
     605    each do |*i|
     606      ary.push(i)
     607      yield(*i)
     608    end
     609    return nil if ary.empty?
     610
     611    while n < 0 || 0 < (n -= 1)
     612      ary.each do |i|
     613        yield(*i)
     614      end
     615    end
     616
     617    nil
    605618  end
    606619
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-enum-ext/test/enum.rb

    r321 r331  
    2626assert("Enumerable#each_cons") do
    2727  a = []
    28   (1..5).each_cons(3){|e| a << e}
     28  b = (1..5).each_cons(3){|e| a << e}
    2929  assert_equal [[1, 2, 3], [2, 3, 4], [3, 4, 5]], a
     30  assert_equal nil, b
    3031end
    3132
    3233assert("Enumerable#each_slice") do
    3334  a = []
    34   (1..10).each_slice(3){|e| a << e}
     35  b = (1..10).each_slice(3){|e| a << e}
    3536  assert_equal [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]], a
     37  assert_equal nil, b
    3638end
    3739
     
    129131  assert_equal ["a", "b", "c", "a", "b", "c"], a
    130132  assert_raise(TypeError) { ["a", "b", "c"].cycle("a") { |v| a << v } }
     133
     134  empty = Class.new do
     135    include Enumerable
     136    def each
     137    end
     138  end
     139  assert_nil empty.new.cycle { break :nope }
    131140end
    132141
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-enum-lazy/mrbgem.rake

    r321 r331  
    22  spec.license = 'MIT'
    33  spec.author  = 'mruby developers'
    4   spec.summary = 'Enumerable::Lazy class'
     4  spec.summary = 'Enumerator::Lazy class'
    55  spec.add_dependency('mruby-enumerator', :core => 'mruby-enumerator')
    66  spec.add_dependency('mruby-enum-ext', :core => 'mruby-enum-ext')
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-enum-lazy/mrblib/lazy.rb

    r321 r331  
    33  # = Enumerable#lazy implementation
    44  #
    5   # Enumerable#lazy returns an instance of Enumerable::Lazy.
     5  # Enumerable#lazy returns an instance of Enumerator::Lazy.
    66  # You can use it just like as normal Enumerable object,
    77  # except these methods act as 'lazy':
     
    1717  #   - zip
    1818  def lazy
    19     Lazy.new(self)
     19    Enumerator::Lazy.new(self)
    2020  end
     21end
    2122
     23class Enumerator
    2224  # == Acknowledgements
    2325  #
     
    4042      }
    4143    end
     44
     45    def to_enum(meth=:each, *args, &block)
     46      lz = Lazy.new(self, &block)
     47      lz.obj = self
     48      lz.meth = meth
     49      lz.args = args
     50      lz
     51    end
     52    alias enum_for to_enum
    4253
    4354    def map(&block)
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-enum-lazy/test/lazy.rb

    r321 r331  
    1 assert("Enumerable::Lazy") do
     1assert("Enumerator::Lazy") do
    22  a = [1, 2]
    3   assert_equal Enumerable::Lazy, a.lazy.class
     3  assert_equal Enumerator::Lazy, a.lazy.class
    44end
    55
    6 assert("Enumerable::Lazy laziness") do
     6assert("Enumerator::Lazy laziness") do
    77  a = Object.new
    88  def a.each
     
    4141end
    4242
    43 assert("Enumerable::Lazy#zip with cycle") do
     43assert("Enumrator::Lazy#to_enum") do
     44  lazy_enum = (0..Float::INFINITY).lazy.to_enum(:each_slice, 2)
     45  assert_kind_of Enumerator::Lazy, lazy_enum
     46  assert_equal [0*1, 2*3, 4*5, 6*7], lazy_enum.map { |a| a.first * a.last }.first(4)
     47end
     48
     49assert("Enumerator::Lazy#zip with cycle") do
    4450  e1 = [1, 2, 3].cycle
    4551  e2 = [:a, :b].cycle
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-enumerator/mrblib/enumerator.rb

    r321 r331  
    154154  def with_index(offset=0)
    155155    return to_enum :with_index, offset unless block_given?
    156     raise TypeError, "no implicit conversion of #{offset.class} into Integer" unless offset.respond_to?(:to_int)
    157 
    158     n = offset.to_int - 1
    159     enumerator_block_call do |i|
     156    offset = if offset.nil?
     157      0
     158    elsif offset.respond_to?(:to_int)
     159      offset.to_int
     160    else
     161      raise TypeError, "no implicit conversion of #{offset.class} into Integer"
     162    end
     163
     164    n = offset - 1
     165    enumerator_block_call do |*i|
    160166      n += 1
    161       yield [i,n]
     167      yield i.__svalue, n
    162168    end
    163169  end
     
    172178  # If no block is given, a new Enumerator is returned that includes the index.
    173179  #
    174   def each_with_index
    175     with_index
     180  def each_with_index(&block)
     181    with_index(0, &block)
    176182  end
    177183
     
    517523  # just for internal
    518524  class Generator
     525    include Enumerable
    519526    def initialize(&block)
    520527      raise TypeError, "wrong argument type #{self.class} (expected Proc)" unless block.kind_of? Proc
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-enumerator/test/enumerator.rb

    r321 r331  
    5151  assert_equal([[1,0],[2,1],[3,2]], @obj.to_enum(:foo, 1, 2, 3).with_index.to_a)
    5252  assert_equal([[1,5],[2,6],[3,7]], @obj.to_enum(:foo, 1, 2, 3).with_index(5).to_a)
     53  a = []
     54  @obj.to_enum(:foo, 1, 2, 3).with_index(10).with_index(20) { |*i| a << i }
     55  assert_equal [[[1, 10], 20], [[2, 11], 21], [[3, 12], 22]], a
    5356end
    5457
     
    6164assert 'Enumerator#with_index string offset' do
    6265  assert_raise(TypeError){ @obj.to_enum(:foo, 1, 2, 3).with_index('1').to_a }
     66end
     67
     68assert 'Enumerator#each_with_index' do
     69  assert_equal([[1,0],[2,1],[3,2]], @obj.to_enum(:foo, 1, 2, 3).each_with_index.to_a)
     70  a = []
     71  @obj.to_enum(:foo, 1, 2, 3).each_with_index {|*i| a << i}
     72  assert_equal([[1, 0], [2, 1], [3, 2]], a)
    6373end
    6474
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-error/mrbgem.rake

    r321 r331  
    44  spec.summary = 'extensional error handling'
    55
    6   if build.cxx_abi_enabled?
     6  if build.cxx_exception_enabled?
    77    @objs << build.compile_as_cxx("#{spec.dir}/src/exception.c", "#{spec.build_dir}/src/exception.cxx")
    88    @objs.delete_if { |v| v == objfile("#{spec.build_dir}/src/exception") }
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-error/src/exception.c

    r321 r331  
    1 #include "mruby.h"
    2 #include "mruby/throw.h"
    3 #include "mruby/error.h"
     1#include <mruby.h>
     2#include <mruby/throw.h>
     3#include <mruby/error.h>
    44
    55MRB_API mrb_value
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-error/test/exception.c

    r321 r331  
    1 #include "mruby.h"
    2 #include "mruby/error.h"
    3 #include "mruby/array.h"
     1#include <mruby.h>
     2#include <mruby/error.h>
     3#include <mruby/array.h>
    44
    55static mrb_value
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-error/test/exception.rb

    r321 r331  
    66  # failure in protect returns [exception, true]
    77  result = ExceptionTest.mrb_protect { raise 'test' }
    8   assert_kind_of RuntimeError, result[0]   
     8  assert_kind_of RuntimeError, result[0]
    99  assert_true result[1]
    1010end
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-eval/src/eval.c

    r321 r331  
    1 #include "mruby.h"
    2 #include "mruby/class.h"
    3 #include "mruby/compile.h"
    4 #include "mruby/irep.h"
    5 #include "mruby/proc.h"
    6 #include "mruby/opcode.h"
     1#include <mruby.h>
     2#include <mruby/class.h>
     3#include <mruby/compile.h>
     4#include <mruby/irep.h>
     5#include <mruby/proc.h>
     6#include <mruby/opcode.h>
     7#include <mruby/error.h>
     8
     9mrb_value mrb_exec_irep(mrb_state *mrb, mrb_value self, struct RProc *p);
     10mrb_value mrb_obj_instance_eval(mrb_state *mrb, mrb_value self);
    711
    812static struct mrb_irep *
     
    2731
    2832  if (!e) return NULL;
     33  if (!MRB_ENV_STACK_SHARED_P(e)) return NULL;
     34  c = e->cxt.c;
    2935  proc = c->cibase[e->cioff].proc;
    3036
     
    127133      }
    128134      break;
    129     }
    130   }
    131 }
     135
     136    case OP_STOP:
     137      if (mrb->c->ci->acc >= 0) {
     138        irep->iseq[i] = MKOP_AB(OP_RETURN, irep->nlocals, OP_R_NORMAL);
     139      }
     140      break;
     141    }
     142  }
     143}
     144
     145void mrb_codedump_all(mrb_state*, struct RProc*);
    132146
    133147static struct RProc*
    134 create_proc_from_string(mrb_state *mrb, char *s, int len, mrb_value binding, char *file, mrb_int line)
     148create_proc_from_string(mrb_state *mrb, char *s, int len, mrb_value binding, const char *file, mrb_int line)
    135149{
    136150  mrbc_context *cxt;
     
    146160  cxt = mrbc_context_new(mrb);
    147161  cxt->lineno = line;
    148   if (file) {
    149     mrbc_filename(mrb, cxt, file);
    150   }
     162
     163  mrbc_filename(mrb, cxt, file ? file : "(eval)");
    151164  cxt->capture_errors = TRUE;
    152165  cxt->no_optimize = TRUE;
     
    161174  if (0 < p->nerr) {
    162175    /* parse error */
    163     char buf[256];
    164     int n;
    165     n = snprintf(buf, sizeof(buf), "line %d: %s\n", p->error_buffer[0].lineno, p->error_buffer[0].message);
     176    mrb_value str;
     177
     178    if (file) {
     179      str = mrb_format(mrb, " file %S line %S: %S",
     180                       mrb_str_new_cstr(mrb, file),
     181                       mrb_fixnum_value(p->error_buffer[0].lineno),
     182                       mrb_str_new_cstr(mrb, p->error_buffer[0].message));
     183    }
     184    else {
     185      str = mrb_format(mrb, " line %S: %S",
     186                       mrb_fixnum_value(p->error_buffer[0].lineno),
     187                       mrb_str_new_cstr(mrb, p->error_buffer[0].message));
     188    }
    166189    mrb_parser_free(p);
    167190    mrbc_context_free(mrb, cxt);
    168     mrb_exc_raise(mrb, mrb_exc_new(mrb, E_SYNTAX_ERROR, buf, n));
     191    mrb_exc_raise(mrb, mrb_exc_new_str(mrb, E_SYNTAX_ERROR, str));
    169192  }
    170193
     
    182205  if (!e) e = c->ci[-1].env;
    183206  e = (struct REnv*)mrb_obj_alloc(mrb, MRB_TT_ENV, (struct RClass*)e);
    184   e->mid = c->ci[-1].mid;
    185   e->cioff = c->ci - c->cibase - 1;
     207  e->cxt.c = c;
     208  e->cioff = c->ci - c->cibase;
    186209  e->stack = c->ci->stackent;
    187   MRB_SET_ENV_STACK_LEN(e, c->ci[-1].proc->body.irep->nlocals);
    188   c->ci->env = e;
     210  MRB_SET_ENV_STACK_LEN(e, c->ci->proc->body.irep->nlocals);
     211  c->ci->target_class = proc->target_class;
     212  c->ci->env = 0;
    189213  proc->env = e;
    190214  patch_irep(mrb, proc->body.irep, 0);
     
    194218
    195219  return proc;
     220}
     221
     222static mrb_value
     223exec_irep(mrb_state *mrb, mrb_value self, struct RProc *proc)
     224{
     225  if (mrb->c->ci->acc < 0) {
     226    mrb_value ret = mrb_top_run(mrb, proc, mrb->c->stack[0], 0);
     227    if (mrb->exc) {
     228      mrb_exc_raise(mrb, mrb_obj_value(mrb->exc));
     229    }
     230    return ret;
     231  }
     232  return mrb_exec_irep(mrb, self, proc);
    196233}
    197234
     
    204241  char *file = NULL;
    205242  mrb_int line = 1;
    206   mrb_value ret;
    207243  struct RProc *proc;
    208244
     
    210246
    211247  proc = create_proc_from_string(mrb, s, len, binding, file, line);
    212   ret = mrb_toplevel_run(mrb, proc);
    213   if (mrb->exc) {
    214     mrb_exc_raise(mrb, mrb_obj_value(mrb->exc));
    215   }
    216 
    217   return ret;
    218 }
    219 
    220 mrb_value mrb_obj_instance_eval(mrb_state *mrb, mrb_value self);
    221 
    222 #define CI_ACC_SKIP    -1
     248  mrb_assert(!MRB_PROC_CFUNC_P(proc));
     249  return exec_irep(mrb, self, proc);
     250}
    223251
    224252static mrb_value
    225253f_instance_eval(mrb_state *mrb, mrb_value self)
    226254{
    227   struct mrb_context *c = mrb->c;
    228255  mrb_value b;
    229256  mrb_int argc; mrb_value *argv;
     
    237264    mrb_int line = 1;
    238265    mrb_value cv;
     266    struct RProc *proc;
    239267
    240268    mrb_get_args(mrb, "s|zi", &s, &len, &file, &line);
    241     c->ci->acc = CI_ACC_SKIP;
    242269    cv = mrb_singleton_class(mrb, self);
    243     c->ci->target_class = mrb_class_ptr(cv);
    244     return mrb_run(mrb, create_proc_from_string(mrb, s, len, mrb_nil_value(), file, line), self);
     270    proc = create_proc_from_string(mrb, s, len, mrb_nil_value(), file, line);
     271    proc->target_class = mrb_class_ptr(cv);
     272    mrb->c->ci->env = NULL;
     273    mrb_assert(!MRB_PROC_CFUNC_P(proc));
     274    return exec_irep(mrb, self, proc);
    245275  }
    246276  else {
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-eval/test/eval.rb

    r321 r331  
    6565  assert_equal('test') { obj.instance_eval('@test') }
    6666  assert_equal('test') { obj.instance_eval { @test } }
     67  o = Object.new
     68  assert_equal ['', o, o], o.instance_eval("[''].each { |s| break [s, o, self] }")
    6769end
    6870
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-exit/src/mruby-exit.c

    r321 r331  
    11#include <stdlib.h>
    2 #include "mruby.h"
     2#include <mruby.h>
    33
    44static mrb_value
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-fiber/src/fiber.c

    r321 r331  
    1 #include "mruby.h"
    2 #include "mruby/array.h"
    3 #include "mruby/class.h"
    4 #include "mruby/proc.h"
     1#include <mruby.h>
     2#include <mruby/array.h>
     3#include <mruby/class.h>
     4#include <mruby/proc.h>
    55
    66#define fiber_ptr(o) ((struct RFiber*)mrb_ptr(o))
     
    88#define FIBER_STACK_INIT_SIZE 64
    99#define FIBER_CI_INIT_SIZE 8
     10#define CI_ACC_RESUMED -3
    1011
    1112/*
     
    7475  mrb_get_args(mrb, "&", &blk);
    7576
     77  if (f->cxt) {
     78    mrb_raise(mrb, E_RUNTIME_ERROR, "cannot initialize twice");
     79  }
    7680  if (mrb_nil_p(blk)) {
    7781    mrb_raise(mrb, E_ARGUMENT_ERROR, "tried to create Fiber object without a block");
     
    8286  }
    8387
    84   f->cxt = (struct mrb_context*)mrb_malloc(mrb, sizeof(struct mrb_context));
    85   *f->cxt = mrb_context_zero;
    86   c = f->cxt;
     88  c = (struct mrb_context*)mrb_malloc(mrb, sizeof(struct mrb_context));
     89  *c = mrb_context_zero;
     90  f->cxt = c;
    8791
    8892  /* initialize VM stack */
     
    156160#define MARK_CONTEXT_MODIFY(c) (c)->ci->target_class = NULL
    157161
    158 static mrb_value
    159 fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mrb_bool resume)
    160 {
    161   struct mrb_context *c = fiber_check(mrb, self);
     162static void
     163fiber_check_cfunc(mrb_state *mrb, struct mrb_context *c)
     164{
    162165  mrb_callinfo *ci;
    163166
     
    167170    }
    168171  }
     172}
     173
     174static void
     175fiber_switch_context(mrb_state *mrb, struct mrb_context *c)
     176{
     177  if (mrb->c->fib) {
     178    mrb_write_barrier(mrb, (struct RBasic*)mrb->c->fib);
     179  }
     180  c->status = MRB_FIBER_RUNNING;
     181  mrb->c = c;
     182}
     183
     184static mrb_value
     185fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mrb_bool resume, mrb_bool vmexec)
     186{
     187  struct mrb_context *c = fiber_check(mrb, self);
     188  struct mrb_context *old_c = mrb->c;
     189  mrb_value value;
     190
     191  fiber_check_cfunc(mrb, c);
    169192  if (resume && c->status == MRB_FIBER_TRANSFERRED) {
    170193    mrb_raise(mrb, E_FIBER_ERROR, "resuming transferred fiber");
    171194  }
    172   if (c->status == MRB_FIBER_RUNNING || c->status == MRB_FIBER_RESUMING) {
    173     mrb_raise(mrb, E_FIBER_ERROR, "double resume");
     195  if (c->status == MRB_FIBER_RUNNING || c->status == MRB_FIBER_RESUMED) {
     196    mrb_raise(mrb, E_FIBER_ERROR, "double resume (fib)");
    174197  }
    175198  if (c->status == MRB_FIBER_TERMINATED) {
    176199    mrb_raise(mrb, E_FIBER_ERROR, "resuming dead fiber");
    177200  }
    178   mrb->c->status = resume ? MRB_FIBER_RESUMING : MRB_FIBER_TRANSFERRED;
     201  mrb->c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED;
    179202  c->prev = resume ? mrb->c : (c->prev ? c->prev : mrb->root_c);
    180203  if (c->status == MRB_FIBER_CREATED) {
    181     mrb_value *b = c->stack+1;
    182     mrb_value *e = b + len;
    183 
     204    mrb_value *b, *e;
     205
     206    if (len >= c->stend - c->stack) {
     207      mrb_raise(mrb, E_FIBER_ERROR, "too many arguments to fiber");
     208    }
     209    b = c->stack+1;
     210    e = b + len;
    184211    while (b<e) {
    185212      *b++ = *a++;
    186213    }
    187214    c->cibase->argc = len;
    188     if (c->prev->fib)
    189       mrb_field_write_barrier(mrb, (struct RBasic*)c->fib, (struct RBasic*)c->prev->fib);
    190     mrb_write_barrier(mrb, (struct RBasic*)c->fib);
    191     c->status = MRB_FIBER_RUNNING;
    192     mrb->c = c;
    193 
     215    value = c->stack[0] = c->ci->proc->env->stack[0];
     216  }
     217  else {
     218    value = fiber_result(mrb, a, len);
     219  }
     220  fiber_switch_context(mrb, c);
     221
     222  if (vmexec) {
     223    c->vmexec = TRUE;
     224    value = mrb_vm_exec(mrb, c->ci[-1].proc, c->ci->pc);
     225    mrb->c = old_c;
     226  }
     227  else {
    194228    MARK_CONTEXT_MODIFY(c);
    195     return c->ci->proc->env->stack[0];
    196   }
    197   MARK_CONTEXT_MODIFY(c);
    198   if (c->prev->fib)
    199     mrb_field_write_barrier(mrb, (struct RBasic*)c->fib, (struct RBasic*)c->prev->fib);
    200   mrb_write_barrier(mrb, (struct RBasic*)c->fib);
    201   c->status = MRB_FIBER_RUNNING;
    202   mrb->c = c;
    203   return fiber_result(mrb, a, len);
     229  }
     230  return value;
    204231}
    205232
     
    224251  mrb_value *a;
    225252  mrb_int len;
     253  mrb_bool vmexec = FALSE;
    226254
    227255  mrb_get_args(mrb, "*", &a, &len);
    228   return fiber_switch(mrb, self, len, a, TRUE);
     256  if (mrb->c->ci->acc < 0) {
     257    vmexec = TRUE;
     258  }
     259  return fiber_switch(mrb, self, len, a, TRUE, vmexec);
    229260}
    230261
     
    233264mrb_fiber_resume(mrb_state *mrb, mrb_value fib, mrb_int len, const mrb_value *a)
    234265{
    235   return fiber_switch(mrb, fib, len, a, TRUE);
     266  return fiber_switch(mrb, fib, len, a, TRUE, TRUE);
    236267}
    237268
     
    281312  mrb_int len;
    282313
     314  fiber_check_cfunc(mrb, mrb->c);
    283315  mrb_get_args(mrb, "*", &a, &len);
    284316
    285317  if (c == mrb->root_c) {
    286318    mrb->c->status = MRB_FIBER_TRANSFERRED;
    287     mrb->c = c;
    288     c->status = MRB_FIBER_RUNNING;
     319    fiber_switch_context(mrb, c);
    289320    MARK_CONTEXT_MODIFY(c);
    290     mrb_write_barrier(mrb, (struct RBasic*)c->fib);
    291321    return fiber_result(mrb, a, len);
    292322  }
     
    296326  }
    297327
    298   return fiber_switch(mrb, self, len, a, FALSE);
     328  return fiber_switch(mrb, self, len, a, FALSE, FALSE);
    299329}
    300330
     
    305335{
    306336  struct mrb_context *c = mrb->c;
    307   mrb_callinfo *ci;
    308 
    309   for (ci = c->ci; ci >= c->cibase; ci--) {
    310     if (ci->acc < 0) {
    311       mrb_raise(mrb, E_FIBER_ERROR, "can't cross C function boundary");
    312     }
    313   }
     337
    314338  if (!c->prev) {
    315339    mrb_raise(mrb, E_FIBER_ERROR, "can't yield from root fiber");
    316340  }
    317341
     342  fiber_check_cfunc(mrb, c);
    318343  c->prev->status = MRB_FIBER_RUNNING;
    319344  c->status = MRB_FIBER_SUSPENDED;
    320   mrb->c = c->prev;
     345  fiber_switch_context(mrb, c->prev);
    321346  c->prev = NULL;
     347  if (c->vmexec) {
     348    c->vmexec = FALSE;
     349    mrb->c->ci->acc = CI_ACC_RESUMED;
     350  }
    322351  MARK_CONTEXT_MODIFY(mrb->c);
    323   mrb_write_barrier(mrb, (struct RBasic*)c->fib);
    324352  return fiber_result(mrb, a, len);
    325353}
     
    333361 *  processing at this point when <code>resume</code> is called next.
    334362 *  Any arguments passed to the next <code>resume</code> will be the
    335  *  value that this <code>Fiber.yield</code> expression evaluates to.
     363 *
     364 *  mruby limitation: Fiber resume/yield cannot cross C function boundary.
     365 *  thus you cannot yield from #initialize which is called by mrb_funcall().
    336366 */
    337367static mrb_value
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-hash-ext/mrblib/hash.rb

    r321 r331  
    2929      o = object[0]
    3030      if o.respond_to?(:to_hash)
    31         h = Hash.new
     31        h = self.new
    3232        object[0].to_hash.each { |k, v| h[k] = v }
    3333        return h
    3434      elsif o.respond_to?(:to_a)
    35         h = Hash.new
     35        h = self.new
    3636        o.to_a.each do |i|
    3737          raise ArgumentError, "wrong element type #{i.class} (expected array)" unless i.respond_to?(:to_a)
     
    5454      raise ArgumentError, 'odd number of arguments for Hash'
    5555    end
    56     h = Hash.new
     56    h = self.new
    5757    0.step(length - 2, 2) do |i|
    5858      h[object[i]] = object[i + 1]
    5959    end
    6060    h
     61  end
     62
     63  ##
     64  # call-seq:
     65  #     Hash.try_convert(obj) -> hash or nil
     66  #
     67  # Try to convert <i>obj</i> into a hash, using to_hash method.
     68  # Returns converted hash or nil if <i>obj</i> cannot be converted
     69  # for any reason.
     70  #
     71  #     Hash.try_convert({1=>2})   # => {1=>2}
     72  #     Hash.try_convert("1=>2")   # => nil
     73  #
     74  def self.try_convert(obj)
     75    if obj.respond_to?(:to_hash)
     76      obj.to_hash
     77    else
     78      nil
     79    end
    6180  end
    6281
     
    193212
    194213  def invert
    195     h = Hash.new
     214    h = self.class.new
    196215    self.each {|k, v| h[v] = k }
    197216    h
     
    347366    }
    348367  end
     368
     369  ##
     370  # call-seq:
     371  #   hsh.dig(key,...)                 -> object
     372  #
     373  # Extracts the nested value specified by the sequence of <i>key</i>
     374  # objects by calling +dig+ at each step, returning +nil+ if any
     375  # intermediate step is +nil+.
     376  #
     377  def dig(idx,*args)
     378    n = self[idx]
     379    if args.size > 0
     380      n&.dig(*args)
     381    else
     382      n
     383    end
     384  end
    349385end
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-hash-ext/src/hash-ext.c

    r321 r331  
    55*/
    66
    7 #include "mruby.h"
    8 #include "mruby/array.h"
    9 #include "mruby/hash.h"
     7#include <mruby.h>
     8#include <mruby/array.h>
     9#include <mruby/hash.h>
    1010
    1111/*
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-hash-ext/test/hash.rb

    r321 r331  
    3838    Hash['d_key']
    3939  end
     40end
     41
     42assert('Hash.[] for sub class') do
     43  sub_hash_class = Class.new(Hash)
     44  sub_hash = sub_hash_class[]
     45  assert_equal(sub_hash_class, sub_hash.class)
     46end
     47
     48assert('Hash.try_convert') do
     49  assert_nil Hash.try_convert(nil)
     50  assert_nil Hash.try_convert("{1=>2}")
     51  assert_equal({1=>2}, Hash.try_convert({1=>2}))
    4052end
    4153
     
    138150end
    139151
     152assert("Hash#invert with sub class") do
     153  sub_hash_class = Class.new(Hash)
     154  sub_hash = sub_hash_class.new
     155  assert_equal(sub_hash_class, sub_hash.invert.class)
     156end
     157
    140158assert("Hash#keep_if") do
    141159  h = { 1 => 2, 3 => 4, 5 => 6 }
     
    231249  assert_false(h2 > h2)
    232250end
     251
     252assert("Hash#dig") do
     253  h = {a:{b:{c:1}}}
     254  assert_equal(1, h.dig(:a, :b, :c))
     255  assert_nil(h.dig(:d))
     256end
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-kernel-ext/src/kernel.c

    r321 r331  
    1 #include "mruby.h"
    2 #include "mruby/error.h"
    3 #include "mruby/array.h"
    4 #include "mruby/hash.h"
     1#include <mruby.h>
     2#include <mruby/error.h>
     3#include <mruby/array.h>
     4#include <mruby/hash.h>
     5#include <mruby/range.h>
     6
     7static mrb_value
     8mrb_f_caller(mrb_state *mrb, mrb_value self)
     9{
     10  mrb_value bt, v, length;
     11  mrb_int bt_len, argc, lev, n;
     12
     13  bt = mrb_get_backtrace(mrb);
     14  bt_len = RARRAY_LEN(bt);
     15  argc = mrb_get_args(mrb, "|oo", &v, &length);
     16
     17  switch (argc) {
     18    case 0:
     19      lev = 1;
     20      n = bt_len - lev;
     21      break;
     22    case 1:
     23      if (mrb_type(v) == MRB_TT_RANGE) {
     24        mrb_int beg, len;
     25        if (mrb_range_beg_len(mrb, v, &beg, &len, bt_len, TRUE) == 1) {
     26          lev = beg;
     27          n = len;
     28        }
     29        else {
     30          return mrb_nil_value();
     31        }
     32      }
     33      else {
     34        v = mrb_to_int(mrb, v);
     35        lev = mrb_fixnum(v);
     36        if (lev < 0) {
     37          mrb_raisef(mrb, E_ARGUMENT_ERROR, "negative level (%S)", v);
     38        }
     39        n = bt_len - lev;
     40      }
     41      break;
     42    case 2:
     43      lev = mrb_fixnum(mrb_to_int(mrb, v));
     44      n = mrb_fixnum(mrb_to_int(mrb, length));
     45      if (lev < 0) {
     46        mrb_raisef(mrb, E_ARGUMENT_ERROR, "negative level (%S)", v);
     47      }
     48      if (n < 0) {
     49        mrb_raisef(mrb, E_ARGUMENT_ERROR, "negative size (%S)", length);
     50      }
     51      break;
     52    default:
     53      lev = n = 0;
     54      break;
     55  }
     56
     57  if (n == 0) {
     58    return mrb_ary_new(mrb);
     59  }
     60
     61  return mrb_funcall(mrb, bt, "[]", 2, mrb_fixnum_value(lev), mrb_fixnum_value(n));
     62}
    563
    664/*
     
    62120 *
    63121 *  Returns <i>arg</i> converted to a float. Numeric types are converted
    64  *  directly, the rest are converted using <i>arg</i>.to_f. 
     122 *  directly, the rest are converted using <i>arg</i>.to_f.
    65123 *
    66124 *     Float(1)           #=> 1.0
     
    171229
    172230  mrb_define_module_function(mrb, krn, "fail", mrb_f_raise, MRB_ARGS_OPT(2));
     231  mrb_define_module_function(mrb, krn, "caller", mrb_f_caller, MRB_ARGS_OPT(2));
    173232  mrb_define_method(mrb, krn, "__method__", mrb_f_method, MRB_ARGS_NONE());
    174233  mrb_define_module_function(mrb, krn, "Integer", mrb_f_integer, MRB_ARGS_ANY());
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-kernel-ext/test/kernel.rb

    r321 r331  
    22  assert_raise(RuntimeError) { fail }
    33  assert_raise(RuntimeError) { Kernel.fail }
     4end
     5
     6assert('Kernel.caller, Kernel#caller') do
     7  skip "backtrace isn't available" if caller(0).empty?
     8
     9  caller_lineno = __LINE__ + 3
     10  c = Class.new do
     11    def foo(*args)
     12      caller(*args)
     13    end
     14
     15    def bar(*args)
     16      foo(*args)
     17    end
     18
     19    def baz(*args)
     20      bar(*args)
     21    end
     22  end
     23  assert_equal "kernel.rb:#{caller_lineno}:in foo", c.new.baz(0)[0][-19..-1]
     24  assert_equal "bar", c.new.baz[0][-3..-1]
     25  assert_equal "foo", c.new.baz(0)[0][-3..-1]
     26  assert_equal "bar", c.new.baz(1)[0][-3..-1]
     27  assert_equal "baz", c.new.baz(2)[0][-3..-1]
     28  assert_equal ["foo", "bar"], c.new.baz(0, 2).map { |i| i[-3..-1] }
     29  assert_equal ["bar", "baz"], c.new.baz(1..2).map { |i| i[-3..-1] }
     30  assert_nil c.new.baz(10..20)
     31  assert_raise(ArgumentError) { c.new.baz(-1) }
     32  assert_raise(ArgumentError) { c.new.baz(-1, 1) }
     33  assert_raise(ArgumentError) { c.new.baz(1, -1) }
     34  assert_raise(TypeError) { c.new.baz(nil) }
    435end
    536
     
    2354  assert_equal(930, Integer("0930", 10))
    2455  assert_equal(7, Integer("111", 2))
     56  assert_equal(0, Integer("0"))
     57  assert_equal(0, Integer("00000"))
    2558  assert_raise(TypeError) { Integer(nil) }
    2659end
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-math/src/math.c

    r321 r331  
    55*/
    66
    7 #include "mruby.h"
    8 #include "mruby/array.h"
     7#include <mruby.h>
     8#include <mruby/array.h>
    99
    1010#include <math.h>
     
    2020
    2121/* math functions not provided by Microsoft Visual C++ 2012 or older */
    22 #if defined _MSC_VER && _MSC_VER < 1800
     22#if defined _MSC_VER && _MSC_VER <= 1700
    2323
    2424#include <float.h>
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-numeric-ext/mrblib/numeric_ext.rb

    r321 r331  
    33    self.divmod(other)[0]
    44  end
     5
     6  def zero?
     7    self == 0
     8  end
     9
     10  def nonzero?
     11    if self == 0
     12      nil
     13    else
     14      self
     15    end
     16  end
    517end
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-numeric-ext/src/numeric_ext.c

    r321 r331  
    11#include <limits.h>
    2 #include "mruby.h"
     2#include <mruby.h>
    33
    44static mrb_value
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-numeric-ext/test/numeric.rb

    r321 r331  
    1717  assert_float 52, 365.2425.div(7)
    1818end
     19
     20assert('Integer#zero?') do
     21  assert_equal true, 0.zero?
     22  assert_equal false, 1.zero?
     23end
     24
     25assert('Integer#nonzero?') do
     26  assert_equal nil, 0.nonzero?
     27  assert_equal 1000, 1000.nonzero?
     28end
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-object-ext/src/object.c

    r321 r331  
    1 #include "mruby.h"
    2 #include "mruby/array.h"
    3 #include "mruby/class.h"
     1#include <mruby.h>
     2#include <mruby/array.h>
     3#include <mruby/class.h>
     4#include <mruby/proc.h>
    45
    56/*
     
    6364mrb_obj_instance_exec(mrb_state *mrb, mrb_value self)
    6465{
    65   mrb_value *argv;
     66  const mrb_value *argv;
    6667  mrb_int argc;
    6768  mrb_value blk;
    6869  struct RClass *c;
     70  mrb_value args;
    6971
    7072  mrb_get_args(mrb, "*&", &argv, &argc, &blk);
     
    8486    break;
    8587  }
    86 
    87   return mrb_yield_with_class(mrb, blk, argc, argv, self, c);
     88  args = mrb_ary_new_from_values(mrb, argc, argv);
     89  argv = RARRAY_PTR(args);
     90  mrb->c->ci->target_class = c;
     91  return mrb_yield_cont(mrb, blk, self, argc, argv);
    8892}
    8993
     
    97101  mrb_define_method(mrb, n, "to_i", nil_to_i,       MRB_ARGS_NONE());
    98102
    99   mrb_define_method(mrb, mrb->object_class, "instance_exec", mrb_obj_instance_exec, MRB_ARGS_ANY() | MRB_ARGS_BLOCK());
     103  mrb_define_method(mrb, mrb->kernel_module, "instance_exec", mrb_obj_instance_exec, MRB_ARGS_ANY() | MRB_ARGS_BLOCK());
    100104}
    101105
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-object-ext/test/object.rb

    r321 r331  
    2424  assert_equal(:tap_ok, Class.new {def m; tap{return :tap_ok}; end}.new.m)
    2525end
     26
     27assert('instance_exec on primitives with class and module definition') do
     28  begin
     29    class A
     30      1.instance_exec do
     31        class B
     32        end
     33      end
     34    end
     35
     36    assert_kind_of Class, A::B
     37  ensure
     38    Object.remove_const :A
     39  end
     40
     41  begin
     42    class A
     43      1.instance_exec do
     44        module B
     45        end
     46      end
     47    end
     48
     49    assert_kind_of Module, A::B
     50  ensure
     51    Object.remove_const :A
     52  end
     53end
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-objectspace/src/mruby_objectspace.c

    r321 r331  
    1 #include "mruby.h"
    2 #include "mruby/gc.h"
    3 #include "mruby/hash.h"
    4 #include "mruby/class.h"
     1#include <mruby.h>
     2#include <mruby/gc.h>
     3#include <mruby/hash.h>
     4#include <mruby/class.h>
    55
    66struct os_count_struct {
     
    1010};
    1111
    12 static void
     12static int
    1313os_count_object_type(mrb_state *mrb, struct RBasic *obj, void *data)
    1414{
     
    2424    obj_count->counts[obj->tt]++;
    2525  }
     26  return MRB_EACH_OBJ_OK;
    2627}
    2728
     
    5051{
    5152  struct os_count_struct obj_count = { 0 };
    52   enum mrb_vtype i;
     53  mrb_int i;
    5354  mrb_value hash;
    5455
     
    110111};
    111112
    112 static void
     113static int
    113114os_each_object_cb(mrb_state *mrb, struct RBasic *obj, void *ud)
    114115{
     
    117118  /* filter dead objects */
    118119  if (mrb_object_dead_p(mrb, obj)) {
    119     return;
     120    return MRB_EACH_OBJ_OK;
    120121  }
    121122
     
    124125  case MRB_TT_ENV:
    125126  case MRB_TT_ICLASS:
    126     return;
     127    return MRB_EACH_OBJ_OK;
    127128  default:
    128129    break;
     
    130131
    131132  /* filter half baked (or internal) objects */
    132   if (!obj->c) return;
     133  if (!obj->c) return MRB_EACH_OBJ_OK;
    133134
    134135  /* filter class kind if target module defined */
    135136  if (d->target_module && !mrb_obj_is_kind_of(mrb, mrb_obj_value(obj), d->target_module)) {
    136     return;
     137    return MRB_EACH_OBJ_OK;
    137138  }
    138139
    139140  mrb_yield(mrb, d->block, mrb_obj_value(obj));
    140141  ++d->count;
     142  return MRB_EACH_OBJ_OK;
    141143}
    142144
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-print/src/print.c

    r321 r331  
    1 #include "mruby.h"
    2 #include "mruby/string.h"
     1#include <mruby.h>
     2#include <mruby/string.h>
    33#include <stdio.h>
    44#include <string.h>
    55#include <stdlib.h>
    6 #if defined(__MINGW32__) || defined(__MINGW64__)
     6#if defined(_WIN32)
    77# include <windows.h>
    88# include <io.h>
     9#ifdef _MSC_VER
     10# define isatty(x) _isatty(x)
     11# define fileno(x) _fileno(x)
     12#endif
    913#endif
    1014
     
    1317{
    1418  if (mrb_string_p(obj)) {
    15 #if defined(__MINGW32__) || defined(__MINGW64__)
     19#if defined(_WIN32)
    1620    if (isatty(fileno(stdout))) {
    1721      DWORD written;
     
    1923      char* utf8 = RSTRING_PTR(obj);
    2024      int wlen = MultiByteToWideChar(CP_UTF8, 0, utf8, mlen, NULL, 0);
    21       wchar_t* utf16 = mrb_malloc(mrb, (wlen+1) * sizeof(wchar_t));
     25      wchar_t* utf16 = (wchar_t*)mrb_malloc(mrb, (wlen+1) * sizeof(wchar_t));
    2226      if (utf16 == NULL) return;
    2327      if (MultiByteToWideChar(CP_UTF8, 0, utf8, mlen, utf16, wlen) > 0) {
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-proc-ext/src/proc.c

    r321 r331  
    1 #include "mruby.h"
    2 #include "mruby/proc.h"
    3 #include "mruby/opcode.h"
    4 #include "mruby/array.h"
    5 #include "mruby/string.h"
    6 #include "mruby/debug.h"
     1#include <mruby.h>
     2#include <mruby/proc.h>
     3#include <mruby/opcode.h>
     4#include <mruby/array.h>
     5#include <mruby/string.h>
     6#include <mruby/debug.h>
    77
    88static mrb_value
     
    5353    line = mrb_debug_get_line(irep, 0);
    5454    if (line != -1) {
    55       mrb_str_append(mrb, str, mrb_fixnum_value(line));
     55      str = mrb_format(mrb, "%S:%S", str, mrb_fixnum_value(line));
    5656    }
    5757    else {
     
    108108  const struct mrb_irep *irep = proc->body.irep;
    109109  mrb_aspec aspec;
    110   mrb_value parameters;
     110  mrb_value sname, parameters;
    111111  int i, j;
    112112
    113113  if (MRB_PROC_CFUNC_P(proc)) {
    114114    // TODO cfunc aspec is not implemented yet
     115    return mrb_ary_new(mrb);
     116  }
     117  if (!irep) {
    115118    return mrb_ary_new(mrb);
    116119  }
     
    135138
    136139  parameters = mrb_ary_new_capa(mrb, irep->nlocals-1);
     140
    137141  for (i = 0, p = parameters_list; p->name; p++) {
    138     mrb_value sname = mrb_symbol_value(mrb_intern_cstr(mrb, p->name));
     142    if (p->size <= 0) continue;
     143    sname = mrb_symbol_value(mrb_intern_cstr(mrb, p->name));
    139144    for (j = 0; j < p->size; i++, j++) {
    140       mrb_assert(i < (irep->nlocals-1));
    141       mrb_ary_push(mrb, parameters, mrb_assoc_new(mrb,
    142         sname,
    143         mrb_symbol_value(irep->lv[i].name)
    144       ));
     145      mrb_value a = mrb_ary_new(mrb);
     146      mrb_ary_push(mrb, a, sname);
     147      if (irep->lv[i].name) {
     148        mrb_ary_push(mrb, a, mrb_symbol_value(irep->lv[i].name));
     149      }
     150      mrb_ary_push(mrb, parameters, a);
    145151    }
    146152  }
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-proc-ext/test/proc.c

    r321 r331  
    1 #include "mruby.h"
    2 #include "mruby/proc.h"
    3 #include "mruby/class.h"
     1#include <mruby.h>
     2#include <mruby/proc.h>
     3#include <mruby/class.h>
    44
    55static mrb_value
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-proc-ext/test/proc.rb

    r321 r331  
    5454  assert_equal([[:opt, :a]], lambda {|a=nil|}.parameters)
    5555  assert_equal([[:req, :a]], ->(a){}.parameters)
     56  assert_equal([[:rest]], lambda { |*| }.parameters)
    5657  assert_equal([[:rest, :a]], Proc.new {|*a|}.parameters)
    5758  assert_equal([[:opt, :a], [:opt, :b], [:opt, :c], [:opt, :d], [:rest, :e], [:opt, :f], [:opt, :g], [:block, :h]], Proc.new {|a,b,c=:c,d=:d,*e,f,g,&h|}.parameters)
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-random/src/mt19937ar.c

    r321 r331  
    22** mt19937ar.c - MT Random functions
    33**
    4 ** See Copyright Notice in mruby.h
     4** Copyright (C) 1997 - 2016, Makoto Matsumoto and Takuji Nishimura,
     5** All rights reserved.
     6**
     7** Permission is hereby granted, free of charge, to any person obtaining
     8** a copy of this software and associated documentation files (the
     9** "Software"), to deal in the Software without restriction, including
     10** without limitation the rights to use, copy, modify, merge, publish,
     11** distribute, sublicense, and/or sell copies of the Software, and to
     12** permit persons to whom the Software is furnished to do so, subject to
     13** the following conditions:
     14**
     15** The above copyright notice and this permission notice shall be
     16** included in all copies or substantial portions of the Software.
     17**
     18** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
     19** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
     20** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
     21** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
     22** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
     23** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
     24** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
     25**
     26** [ MIT license: http://www.opensource.org/licenses/mit-license.php ]
     27**
     28** Any feedback is very welcome.
     29** http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
     30** email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
     31**
     32** This version is modified by mruby developers. If you see any problem,
     33** contact us first at https://github.com/mruby/mruby/issues
    534*/
    635
    7 #include "mruby.h"
     36#include <mruby.h>
    837#include "mt19937ar.h"
    938
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-random/src/mt19937ar.h

    r321 r331  
    22** mt19937ar.h - MT Random functions
    33**
    4 ** See Copyright Notice in mruby.h
     4** Copyright (C) 1997 - 2016, Makoto Matsumoto and Takuji Nishimura,
     5** All rights reserved.
     6**
     7** Permission is hereby granted, free of charge, to any person obtaining
     8** a copy of this software and associated documentation files (the
     9** "Software"), to deal in the Software without restriction, including
     10** without limitation the rights to use, copy, modify, merge, publish,
     11** distribute, sublicense, and/or sell copies of the Software, and to
     12** permit persons to whom the Software is furnished to do so, subject to
     13** the following conditions:
     14**
     15** The above copyright notice and this permission notice shall be
     16** included in all copies or substantial portions of the Software.
     17**
     18** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
     19** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
     20** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
     21** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
     22** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
     23** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
     24** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
     25**
     26** [ MIT license: http://www.opensource.org/licenses/mit-license.php ]
     27**
     28** Any feedback is very welcome.
     29** http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
     30** email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
     31**
     32** This version is modified by mruby developers. If you see any problem,
     33** contact us first at https://github.com/mruby/mruby/issues
    534*/
    635
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-random/src/random.c

    r321 r331  
    55*/
    66
    7 #include "mruby.h"
    8 #include "mruby/variable.h"
    9 #include "mruby/class.h"
    10 #include "mruby/data.h"
    11 #include "mruby/array.h"
     7#include <mruby.h>
     8#include <mruby/variable.h>
     9#include <mruby/class.h>
     10#include <mruby/data.h>
     11#include <mruby/array.h>
    1212#include "mt19937ar.h"
    1313
     
    8080
    8181  if (!mrb_nil_p(arg)) {
    82     if (!mrb_fixnum_p(arg)) {
     82    arg = mrb_check_convert_type(mrb, arg, MRB_TT_FIXNUM, "Fixnum", "to_int");
     83    if (mrb_nil_p(arg)) {
    8384      mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid argument type");
    8485    }
    85     arg = mrb_check_convert_type(mrb, arg, MRB_TT_FIXNUM, "Fixnum", "to_int");
    8686    if (mrb_fixnum(arg) < 0) {
    8787      arg = mrb_fixnum_value(0 - mrb_fixnum(arg));
     
    125125  mt_state *t;
    126126
     127  seed = get_opt(mrb);
     128
    127129  /* avoid memory leaks */
    128130  t = (mt_state*)DATA_PTR(self);
     
    135137  t->mti = N + 1;
    136138
    137   seed = get_opt(mrb);
    138139  seed = mrb_random_mt_srand(mrb, t, seed);
    139140  if (mrb_nil_p(seed)) {
     
    267268  mrb_bool given;
    268269  mt_state *random = NULL;
    269   mrb_int len = RARRAY_LEN(ary);
     270  mrb_int len;
    270271
    271272  mrb_get_args(mrb, "|i?d", &n, &given, &random, &mt_state_type);
     
    275276  mrb_random_rand_seed(mrb, random);
    276277  mt_rand(random);
     278  len = RARRAY_LEN(ary);
    277279  if (!given) {                 /* pick one element */
    278280    switch (len) {
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-random/src/random.h

    r321 r331  
    55*/
    66
    7 #ifndef RANDOM_H
    8 #define RANDOM_H
     7#ifndef MRUBY_RANDOM_H
     8#define MRUBY_RANDOM_H
    99
    1010void mrb_mruby_random_gem_init(mrb_state *mrb);
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-random/test/random.rb

    r321 r331  
    7575  ary1 != [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and 10.times { |x| ary1.include? x } and ary1 == ary2
    7676end
     77
     78assert('Array#sample checks input length after reading arguments') do
     79  $ary = [1, 2, 3]
     80  class ArrayChange
     81    def to_i
     82      $ary << 4
     83      4
     84    end
     85  end
     86
     87  assert_equal [1, 2, 3, 4], $ary.sample(ArrayChange.new).sort
     88end
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-range-ext/src/range.c

    r321 r331  
    1 #include "mruby.h"
    2 #include "mruby/range.h"
     1#include <mruby.h>
     2#include <mruby/range.h>
    33#include <math.h>
     4#include <float.h>
    45
    56static mrb_bool
     
    4445{
    4546  mrb_value val;
    46   struct RRange *r = mrb_range_ptr(range);
     47  struct RRange *r = mrb_range_ptr(mrb, range);
    4748  mrb_value beg, end;
    4849
     
    6869/*
    6970 *  call-seq:
    70  *     rng.first    -> obj
    71  *     rng.first(n) -> an_array
    72  *
    73  *  Returns the first object in the range, or an array of the first +n+
    74  *  elements.
    75  *
    76  *    (10..20).first     #=> 10
    77  *    (10..20).first(3)  #=> [10, 11, 12]
    78  */
    79 static mrb_value
    80 mrb_range_first(mrb_state *mrb, mrb_value range)
    81 {
    82   mrb_int num;
    83   mrb_value array;
    84   struct RRange *r = mrb_range_ptr(range);
    85 
    86   if (mrb_get_args(mrb, "|i", &num) == 0) {
    87     return r->edges->beg;
    88   }
    89 
    90   array = mrb_funcall(mrb, range, "to_a", 0);
    91   return mrb_funcall(mrb, array, "first", 1, mrb_fixnum_value(num));
    92 }
    93 
    94 /*
    95  *  call-seq:
    9671 *     rng.last    -> obj
    9772 *     rng.last(n) -> an_array
     
    11388  mrb_value num;
    11489  mrb_value array;
    115   struct RRange *r = mrb_range_ptr(range);
     90  struct RRange *r = mrb_range_ptr(mrb, range);
    11691
    11792  if (mrb_get_args(mrb, "|o", &num) == 0) {
     
    137112mrb_range_size(mrb_state *mrb, mrb_value range)
    138113{
    139   struct RRange *r = mrb_range_ptr(range);
     114  struct RRange *r = mrb_range_ptr(mrb, range);
    140115  mrb_value beg, end;
    141   double beg_f, end_f;
     116  mrb_float beg_f, end_f;
    142117  mrb_bool num_p = TRUE;
     118  mrb_bool excl;
    143119
    144120  beg = r->edges->beg;
    145121  end = r->edges->end;
     122  excl = r->excl;
    146123  if (mrb_fixnum_p(beg)) {
    147     beg_f = (double)mrb_fixnum(beg);
     124    beg_f = (mrb_float)mrb_fixnum(beg);
    148125  }
    149126  else if (mrb_float_p(beg)) {
     
    154131  }
    155132  if (mrb_fixnum_p(end)) {
    156     end_f = (double)mrb_fixnum(end);
     133    end_f = (mrb_float)mrb_fixnum(end);
    157134  }
    158135  else if (mrb_float_p(end)) {
     
    163140  }
    164141  if (num_p) {
    165     double f;
     142    mrb_float n = end_f - beg_f;
     143    mrb_float err = (fabs(beg_f) + fabs(end_f) + fabs(end_f-beg_f)) * MRB_FLOAT_EPSILON;
    166144
    167     if (beg_f > end_f) return mrb_fixnum_value(0);
    168     f = end_f - beg_f;
    169     if (!r->excl) {
    170       return mrb_fixnum_value((mrb_int)ceil(f + 1));
     145    if (err>0.5) err=0.5;
     146    if (excl) {
     147      if (n<=0) return mrb_fixnum_value(0);
     148      if (n<1)
     149        n = 0;
     150      else
     151        n = floor(n - err);
    171152    }
    172     return mrb_fixnum_value((mrb_int)ceil(f));
     153    else {
     154      if (n<0) return mrb_fixnum_value(0);
     155      n = floor(n + err);
     156    }
     157    if (isinf(n+1))
     158      return mrb_float_value(mrb, INFINITY);
     159    return mrb_fixnum_value((mrb_int)n+1);
    173160  }
    174161  return mrb_nil_value();
     
    181168
    182169  mrb_define_method(mrb, s, "cover?", mrb_range_cover, MRB_ARGS_REQ(1));
    183   mrb_define_method(mrb, s, "first",  mrb_range_first, MRB_ARGS_OPT(1));
    184170  mrb_define_method(mrb, s, "last",   mrb_range_last,  MRB_ARGS_OPT(1));
    185171  mrb_define_method(mrb, s, "size",   mrb_range_size,  MRB_ARGS_NONE());
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-range-ext/test/range.rb

    r321 r331  
    1111  assert_equal 10, (10..20).first
    1212  assert_equal [10, 11, 12], (10..20).first(3)
     13  assert_equal [0, 1, 2], (0..Float::INFINITY).first(3)
    1314end
    1415
     
    2627  assert_equal 5, (1...6.0).size
    2728  assert_equal 5, (1.1...6).size
     29  assert_equal 15, (1.0..15.9).size
     30  assert_equal Float::INFINITY, (0..Float::INFINITY).size
    2831  assert_nil ('a'..'z').size
    2932end
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-sprintf/src/kernel.c

    r321 r331  
    55*/
    66
    7 #include "mruby.h"
     7#include <mruby.h>
    88
    99mrb_value mrb_f_sprintf(mrb_state *mrb, mrb_value obj); /* in sprintf.c */
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-sprintf/src/sprintf.c

    r321 r331  
    55*/
    66
    7 #include "mruby.h"
     7#include <mruby.h>
    88
    99#include <limits.h>
    1010#include <stdio.h>
    1111#include <string.h>
    12 #include "mruby/string.h"
    13 #include "mruby/hash.h"
    14 #include "mruby/numeric.h"
     12#include <mruby/string.h>
     13#include <mruby/hash.h>
     14#include <mruby/numeric.h>
    1515#include <math.h>
    1616#include <ctype.h>
     
    1818#define BIT_DIGITS(N)   (((N)*146)/485 + 1)  /* log2(10) =~ 146/485 */
    1919#define BITSPERDIG MRB_INT_BIT
    20 #define EXTENDSIGN(n, l) (((~0 << (n)) >> (((n)*(l)) % BITSPERDIG)) & ~(~0 << (n)))
     20#define EXTENDSIGN(n, l) (((~0U << (n)) >> (((n)*(l)) % BITSPERDIG)) & ~(~0U << (n)))
    2121
    2222mrb_value mrb_str_format(mrb_state *, int, const mrb_value *, mrb_value);
     
    7272mrb_fix2binstr(mrb_state *mrb, mrb_value x, int base)
    7373{
    74   char buf[64], *b = buf + sizeof buf;
     74  char buf[66], *b = buf + sizeof buf;
    7575  mrb_int num = mrb_fixnum(x);
    7676  uint64_t val = (uint64_t)num;
     
    8080    mrb_raisef(mrb, E_ARGUMENT_ERROR, "invalid radix %S", mrb_fixnum_value(base));
    8181  }
    82 
    83   if (val >= (1 << 10))
    84     val &= 0x3ff;
    85 
    8682  if (val == 0) {
    8783    return mrb_str_new_lit(mrb, "0");
     
    121117#define CHECK(l) do {\
    122118/*  int cr = ENC_CODERANGE(result);*/\
    123   while (blen + (l) >= bsiz) {\
     119  while ((l) >= bsiz - blen) {\
    124120    bsiz*=2;\
     121    if (bsiz < 0) mrb_raise(mrb, E_ARGUMENT_ERROR, "too big specifier"); \
    125122  }\
    126123  mrb_str_resize(mrb, result, bsiz);\
     
    141138} while (0)
    142139
    143 #define GETARG() (!mrb_undef_p(nextvalue) ? nextvalue : \
    144   posarg == -1 ? \
    145   (mrb_raisef(mrb, E_ARGUMENT_ERROR, "unnumbered(%S) mixed with numbered", mrb_fixnum_value(nextarg)), mrb_undef_value()) : \
    146   posarg == -2 ? \
    147   (mrb_raisef(mrb, E_ARGUMENT_ERROR, "unnumbered(%S) mixed with named", mrb_fixnum_value(nextarg)), mrb_undef_value()) : \
     140static void
     141check_next_arg(mrb_state *mrb, int posarg, int nextarg)
     142{
     143  switch (posarg) {
     144  case -1:
     145    mrb_raisef(mrb, E_ARGUMENT_ERROR, "unnumbered(%S) mixed with numbered", mrb_fixnum_value(nextarg));
     146    break;
     147  case -2:
     148    mrb_raisef(mrb, E_ARGUMENT_ERROR, "unnumbered(%S) mixed with named", mrb_fixnum_value(nextarg));
     149    break;
     150  default:
     151    break;
     152  }
     153}
     154
     155static void
     156check_pos_arg(mrb_state *mrb, int posarg, int n)
     157{
     158  if (posarg > 0) {
     159    mrb_raisef(mrb, E_ARGUMENT_ERROR, "numbered(%S) after unnumbered(%S)",
     160               mrb_fixnum_value(n), mrb_fixnum_value(posarg));
     161  }
     162  if (posarg == -2) {
     163    mrb_raisef(mrb, E_ARGUMENT_ERROR, "numbered(%S) after named", mrb_fixnum_value(n));
     164  }
     165  if (n < 1) {
     166    mrb_raisef(mrb, E_ARGUMENT_ERROR, "invalid index - %S$", mrb_fixnum_value(n));
     167  }
     168}
     169
     170static void
     171check_name_arg(mrb_state *mrb, int posarg, const char *name, int len)
     172{
     173  if (posarg > 0) {
     174    mrb_raisef(mrb, E_ARGUMENT_ERROR, "named%S after unnumbered(%S)",
     175               mrb_str_new(mrb, (name), (len)), mrb_fixnum_value(posarg));
     176  }
     177  if (posarg == -1) {
     178    mrb_raisef(mrb, E_ARGUMENT_ERROR, "named%S after numbered", mrb_str_new(mrb, (name), (len)));
     179  }
     180}
     181
     182#define GETNEXTARG() (\
     183  check_next_arg(mrb, posarg, nextarg),\
    148184  (posarg = nextarg++, GETNTHARG(posarg)))
    149185
    150 #define GETPOSARG(n) (posarg > 0 ? \
    151   (mrb_raisef(mrb, E_ARGUMENT_ERROR, "numbered(%S) after unnumbered(%S)", mrb_fixnum_value(n), mrb_fixnum_value(posarg)), mrb_undef_value()) : \
    152   posarg == -2 ? \
    153   (mrb_raisef(mrb, E_ARGUMENT_ERROR, "numbered(%S) after named", mrb_fixnum_value(n)), mrb_undef_value()) : \
    154   ((n < 1) ? \
    155   (mrb_raisef(mrb, E_ARGUMENT_ERROR, "invalid index - %S$", mrb_fixnum_value(n)), mrb_undef_value()) : \
    156   (posarg = -1, GETNTHARG(n))))
     186#define GETARG() (!mrb_undef_p(nextvalue) ? nextvalue : GETNEXTARG())
     187
     188#define GETPOSARG(n) (\
     189  check_pos_arg(mrb, posarg, n),\
     190  (posarg = -1, GETNTHARG(n)))
    157191
    158192#define GETNTHARG(nth) \
    159193  ((nth >= argc) ? (mrb_raise(mrb, E_ARGUMENT_ERROR, "too few arguments"), mrb_undef_value()) : argv[nth])
    160194
    161 #define GETNAMEARG(id, name, len) ( \
    162   posarg > 0 ? \
    163   (mrb_raisef(mrb, E_ARGUMENT_ERROR, "named%S after unnumbered(%S)", mrb_str_new(mrb, (name), (len)), mrb_fixnum_value(posarg)), mrb_undef_value()) : \
    164   posarg == -1 ? \
    165   (mrb_raisef(mrb, E_ARGUMENT_ERROR, "named%S after numbered", mrb_str_new(mrb, (name), (len))), mrb_undef_value()) :    \
     195#define GETNAMEARG(id, name, len) (\
     196  check_name_arg(mrb, posarg, name, len),\
    166197  (posarg = -2, mrb_hash_fetch(mrb, get_hash(mrb, &hash, argc, argv), id, mrb_undef_value())))
    167198
     
    187218  } \
    188219  else { \
    189     tmp_v = GETARG(); \
     220    tmp_v = GETNEXTARG(); \
    190221    p = t; \
    191222  } \
    192   num = mrb_fixnum(tmp_v); \
     223  num = mrb_int(mrb, tmp_v); \
    193224} while (0)
    194225
     
    536567
    537568    for (t = p; t < end && *t != '%'; t++) ;
     569    if (t + 1 == end) ++t;
    538570    PUSH(p, t - p);
    539571    if (t >= end)
     
    680712          mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid character");
    681713        }
     714        mrb_check_type(mrb, tmp, MRB_TT_STRING);
    682715        c = RSTRING_PTR(tmp);
    683716        n = RSTRING_LEN(tmp);
    684717        if (!(flags & FWIDTH)) {
    685           CHECK(n);
    686           memcpy(buf+blen, c, n);
    687           blen += n;
     718          PUSH(c, n);
    688719        }
    689720        else if ((flags & FMINUS)) {
    690           CHECK(n);
    691           memcpy(buf+blen, c, n);
    692           blen += n;
    693           FILL(' ', width-1);
     721          PUSH(c, n);
     722          if (width>0) FILL(' ', width-1);
    694723        }
    695724        else {
    696           FILL(' ', width-1);
    697           CHECK(n);
    698           memcpy(buf+blen, c, n);
    699           blen += n;
     725          if (width>0) FILL(' ', width-1);
     726          PUSH(c, n);
    700727        }
    701728      }
     
    717744          RSTRING(result)->flags &= ~MRB_STR_EMBED_LEN_MASK;
    718745          RSTRING(result)->flags |= tmp_n << MRB_STR_EMBED_LEN_SHIFT;
    719         } else {
     746        }
     747        else {
    720748          RSTRING(result)->as.heap.len = blen;
    721749        }
     
    734762            width -= (int)slen;
    735763            if (!(flags&FMINUS)) {
    736               CHECK(width);
    737               while (width--) {
    738                 buf[blen++] = ' ';
    739               }
     764              FILL(' ', width);
    740765            }
    741             CHECK(len);
    742             memcpy(&buf[blen], RSTRING_PTR(str), len);
    743             blen += len;
     766            PUSH(RSTRING_PTR(str), len);
    744767            if (flags&FMINUS) {
    745               CHECK(width);
    746               while (width--) {
    747                 buf[blen++] = ' ';
    748               }
     768              FILL(' ', width);
    749769            }
    750770            break;
     
    764784      case 'u': {
    765785        mrb_value val = GETARG();
    766         char fbuf[32], nbuf[64], *s;
     786        char nbuf[68], *s;
    767787        const char *prefix = NULL;
    768788        int sign = 0, dots = 0;
    769789        char sc = 0;
    770         mrb_int v = 0, org_v = 0;
     790        mrb_int v = 0;
    771791        int base;
    772792        mrb_int len;
     
    775795          case 'd':
    776796          case 'i':
    777           case 'u':
    778797            sign = 1; break;
    779           case 'o':
    780           case 'x':
    781           case 'X':
    782           case 'b':
    783           case 'B':
    784             if (flags&(FPLUS|FSPACE)) sign = 1;
    785             break;
    786798          default:
    787799            break;
     
    801813        switch (mrb_type(val)) {
    802814          case MRB_TT_FLOAT:
    803             if (FIXABLE(mrb_float(val))) {
    804               val = mrb_fixnum_value((mrb_int)mrb_float(val));
    805               goto bin_retry;
    806             }
    807815            val = mrb_flo_to_fixnum(mrb, val);
    808816            if (mrb_fixnum_p(val)) goto bin_retry;
     
    836844
    837845        if (base == 2) {
    838           org_v = v;
    839846          if (v < 0 && !sign) {
    840847            val = mrb_fix2binstr(mrb, mrb_fixnum_value(v), base);
     
    844851            val = mrb_fixnum_to_str(mrb, mrb_fixnum_value(v), base);
    845852          }
    846           v = mrb_fixnum(mrb_str_to_inum(mrb, val, 10, FALSE));
    847853        }
    848854        if (sign) {
    849           char c = *p;
    850           if (c == 'i') c = 'd'; /* %d and %i are identical */
    851           if (base == 2) c = 'd';
    852           if (v < 0) {
    853             v = -v;
    854             sc = '-';
    855             width--;
    856           }
    857           else if (flags & FPLUS) {
    858             sc = '+';
    859             width--;
    860           }
    861           else if (flags & FSPACE) {
    862             sc = ' ';
    863             width--;
    864           }
    865           snprintf(fbuf, sizeof(fbuf), "%%l%c", c);
    866           snprintf(nbuf, sizeof(nbuf), fbuf, v);
     855          if (v > 0) {
     856            if (flags & FPLUS) {
     857              sc = '+';
     858              width--;
     859            }
     860            else if (flags & FSPACE) {
     861              sc = ' ';
     862              width--;
     863            }
     864          }
     865          switch (base) {
     866          case 2:
     867            strncpy(nbuf, RSTRING_PTR(val), sizeof(nbuf));
     868            break;
     869          case 8:
     870            snprintf(nbuf, sizeof(nbuf), "%" MRB_PRIo, v);
     871            break;
     872          case 10:
     873            snprintf(nbuf, sizeof(nbuf), "%" MRB_PRId, v);
     874            break;
     875          case 16:
     876            snprintf(nbuf, sizeof(nbuf), "%" MRB_PRIx, v);
     877            break;
     878          }
    867879          s = nbuf;
    868880        }
    869881        else {
    870           char c = *p;
    871           if (c == 'X') c = 'x';
    872           if (base == 2) c = 'd';
    873882          s = nbuf;
    874           if (v < 0) {
     883          if (base != 10 && v < 0) {
    875884            dots = 1;
    876885          }
    877           snprintf(fbuf, sizeof(fbuf), "%%l%c", c);
    878           snprintf(++s, sizeof(nbuf) - 1, fbuf, v);
     886          switch (base) {
     887          case 2:
     888            strncpy(++s, RSTRING_PTR(val), sizeof(nbuf)-1);
     889            break;
     890          case 8:
     891            snprintf(++s, sizeof(nbuf)-1, "%" MRB_PRIo, v);
     892            break;
     893          case 10:
     894            snprintf(++s, sizeof(nbuf)-1, "%" MRB_PRId, v);
     895            break;
     896          case 16:
     897            snprintf(++s, sizeof(nbuf)-1, "%" MRB_PRIx, v);
     898            break;
     899          }
    879900          if (v < 0) {
    880901            char d;
     
    950971        }
    951972
    952         if (!(flags&FMINUS)) {
    953           CHECK(width);
    954           while (width-- > 0) {
    955             buf[blen++] = ' ';
    956           }
     973        if (!(flags&FMINUS) && width > 0) {
     974          FILL(' ', width);
    957975        }
    958976
     
    963981          PUSH(prefix, plen);
    964982        }
    965         CHECK(prec - len);
    966983        if (dots) PUSH("..", 2);
    967984
    968         if (v < 0 || (base == 2 && org_v < 0)) {
    969           char c = sign_bits(base, p);
    970           while (len < prec--) {
    971             buf[blen++] = c;
    972           }
    973         }
    974         else if ((flags & (FMINUS|FPREC)) != FMINUS) {
    975           char c = '0';
    976           while (len < prec--) {
    977             buf[blen++] = c;
    978           }
    979         }
    980 
     985        if (prec > len) {
     986          CHECK(prec - len);
     987          if (v < 0) {
     988            char c = sign_bits(base, p);
     989            FILL(c, prec - len);
     990          }
     991          else if ((flags & (FMINUS|FPREC)) != FMINUS) {
     992            char c = '0';
     993            FILL(c, prec - len);
     994          }
     995        }
    981996        PUSH(s, len);
    982         CHECK(width);
    983         while (width-- > 0) {
    984           buf[blen++] = ' ';
     997        if (width > 0) {
     998          FILL(' ', width);
    985999        }
    9861000      }
     
    10031017          const char *expr;
    10041018          const int elen = 3;
     1019          char sign = '\0';
    10051020
    10061021          if (isnan(fval)) {
     
    10111026          }
    10121027          need = elen;
    1013           if ((!isnan(fval) && fval < 0.0) || (flags & FPLUS))
    1014             need++;
     1028          if (!isnan(fval) && fval < 0.0)
     1029            sign = '-';
     1030          else if (flags & (FPLUS|FSPACE))
     1031            sign = (flags & FPLUS) ? '+' : ' ';
     1032          if (sign)
     1033            ++need;
    10151034          if ((flags & FWIDTH) && need < width)
    10161035            need = width;
    10171036
    1018           CHECK(need + 1);
    1019           snprintf(&buf[blen], need + 1, "%*s", need, "");
     1037          if (need < 0) {
     1038            mrb_raise(mrb, E_ARGUMENT_ERROR, "width too big");
     1039          }
     1040          FILL(' ', need);
    10201041          if (flags & FMINUS) {
    1021             if (!isnan(fval) && fval < 0.0)
    1022               buf[blen++] = '-';
    1023             else if (flags & FPLUS)
    1024               buf[blen++] = '+';
    1025             else if (flags & FSPACE)
    1026               blen++;
    1027             memcpy(&buf[blen], expr, elen);
     1042            if (sign)
     1043              buf[blen - need--] = sign;
     1044            memcpy(&buf[blen - need], expr, elen);
    10281045          }
    10291046          else {
    1030             if (!isnan(fval) && fval < 0.0)
    1031               buf[blen + need - elen - 1] = '-';
    1032             else if (flags & FPLUS)
    1033               buf[blen + need - elen - 1] = '+';
    1034             else if ((flags & FSPACE) && need > width)
    1035               blen++;
    1036             memcpy(&buf[blen + need - elen], expr, elen);
    1037           }
    1038           blen += strlen(&buf[blen]);
     1047            if (sign)
     1048              buf[blen - elen - 1] = sign;
     1049            memcpy(&buf[blen - elen], expr, elen);
     1050          }
    10391051          break;
    10401052        }
     
    10521064          need = width;
    10531065        need += 20;
     1066        if (need <= 0) {
     1067          mrb_raise(mrb, E_ARGUMENT_ERROR,
     1068                    (width > prec ? "width too big" : "prec too big"));
     1069        }
    10541070
    10551071        CHECK(need);
    10561072        n = snprintf(&buf[blen], need, fbuf, fval);
     1073        if (n < 0) {
     1074          mrb_raise(mrb, E_RUNTIME_ERROR, "formatting error");
     1075        }
    10571076        blen += n;
    10581077      }
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-sprintf/test/sprintf.rb

    r321 r331  
    66  assert_equal "1 one 1.0", "%d %s %3.1f" % [ 1, "one", 1.01 ]
    77  assert_equal "123 < 456", "%{num} < %<str>s" % { num: 123, str: "456" }
     8  assert_equal 15, ("%b" % (1<<14)).size
    89end
     10
     11assert('String#% with inf') do
     12  inf = Float::INFINITY
     13
     14  assert_equal "Inf", "%f" % inf
     15  assert_equal "Inf", "%2f" % inf
     16  assert_equal "Inf", "%3f" % inf
     17  assert_equal " Inf", "%4f" % inf
     18  assert_equal "  Inf", "%5f" % inf
     19
     20  assert_equal "+Inf", "%+f" % inf
     21  assert_equal "+Inf", "%+2f" % inf
     22  assert_equal "+Inf", "%+3f" % inf
     23  assert_equal "+Inf", "%+4f" % inf
     24  assert_equal " +Inf", "%+5f" % inf
     25
     26  assert_equal "Inf", "%-f" % inf
     27  assert_equal "Inf", "%-2f" % inf
     28  assert_equal "Inf", "%-3f" % inf
     29  assert_equal "Inf ", "%-4f" % inf
     30  assert_equal "Inf  ", "%-5f" % inf
     31
     32  assert_equal " Inf", "% f" % inf
     33  assert_equal " Inf", "% 2f" % inf
     34  assert_equal " Inf", "% 3f" % inf
     35  assert_equal " Inf", "% 4f" % inf
     36  assert_equal "  Inf", "% 5f" % inf
     37end
     38
     39assert('String#% with nan') do
     40  nan = Float::NAN
     41
     42  assert_equal "NaN", "%f" % nan
     43  assert_equal "NaN", "%2f" % nan
     44  assert_equal "NaN", "%3f" % nan
     45  assert_equal " NaN", "%4f" % nan
     46  assert_equal "  NaN", "%5f" % nan
     47
     48  assert_equal "+NaN", "%+f" % nan
     49  assert_equal "+NaN", "%+2f" % nan
     50  assert_equal "+NaN", "%+3f" % nan
     51  assert_equal "+NaN", "%+4f" % nan
     52  assert_equal " +NaN", "%+5f" % nan
     53
     54  assert_equal "NaN", "%-f" % nan
     55  assert_equal "NaN", "%-2f" % nan
     56  assert_equal "NaN", "%-3f" % nan
     57  assert_equal "NaN ", "%-4f" % nan
     58  assert_equal "NaN  ", "%-5f" % nan
     59
     60  assert_equal " NaN", "% f" % nan
     61  assert_equal " NaN", "% 2f" % nan
     62  assert_equal " NaN", "% 3f" % nan
     63  assert_equal " NaN", "% 4f" % nan
     64  assert_equal "  NaN", "% 5f" % nan
     65end
     66
     67assert("String#% with invalid chr") do
     68  begin
     69    class Fixnum
     70      alias_method :chr_, :chr if method_defined?(:chr)
     71
     72      def chr
     73        nil
     74      end
     75    end
     76
     77    assert_raise TypeError do
     78      "%c" % 0
     79    end
     80  ensure
     81    class Fixnum
     82      if method_defined?(:chr_)
     83        alias_method :chr, :chr_
     84        remove_method :chr_
     85      end
     86    end
     87  end
     88end
     89
     90assert("String#% %b") do
     91  assert_equal("..10115", "%0b5" % -5)
     92end
     93
     94assert("String#% invalid format") do
     95  assert_raise ArgumentError do
     96    "%?" % ""
     97  end
     98end
     99
     100assert("String#% invalid format shared substring") do
     101  fmt = ("x"*30+"%!")[0...-1]
     102  assert_equal fmt, sprintf(fmt, "")
     103end
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-string-ext/mrbgem.rake

    r321 r331  
    33  spec.author  = 'mruby developers'
    44  spec.summary = 'String class extension'
     5  spec.add_test_dependency 'mruby-enumerator', core: 'mruby-enumerator'
    56end
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-string-ext/mrblib/string.rb

    r321 r331  
    11class String
     2
     3  ##
     4  #  call-seq:
     5  #     String.try_convert(obj) -> string or nil
     6  #
     7  # Try to convert <i>obj</i> into a String, using to_str method.
     8  # Returns converted string or nil if <i>obj</i> cannot be converted
     9  # for any reason.
     10  #
     11  #     String.try_convert("str")     #=> "str"
     12  #     String.try_convert(/re/)      #=> nil
     13  #
     14  def self.try_convert(obj)
     15    if obj.respond_to?(:to_str)
     16      obj.to_str
     17    else
     18      nil
     19    end
     20  end
    221
    322  ##
     
    2746    a = 0
    2847    z = self.size - 1
    29     a += 1 while " \f\n\r\t\v".include?(self[a]) and a <= z
     48    a += 1 while a <= z and " \f\n\r\t\v".include?(self[a])
    3049    (z >= 0) ? self[a..z] : ""
    3150  end
     
    4463    a = 0
    4564    z = self.size - 1
    46     z -= 1 while " \f\n\r\t\v\0".include?(self[z]) and a <= z
     65    z -= 1 while a <= z and " \f\n\r\t\v\0".include?(self[z])
    4766    (z >= 0) ? self[a..z] : ""
    4867  end
     
    6079    a = 0
    6180    z = self.size - 1
    62     a += 1 while " \f\n\r\t\v".include?(self[a]) and a <= z
    63     z -= 1 while " \f\n\r\t\v\0".include?(self[z]) and a <= z
     81    a += 1 while a <= z and " \f\n\r\t\v".include?(self[a])
     82    z -= 1 while a <= z and " \f\n\r\t\v\0".include?(self[z])
    6483    (z >= 0) ? self[a..z] : ""
    6584  end
     
    7796  #
    7897  def lstrip!
     98    raise RuntimeError, "can't modify frozen String" if frozen?
    7999    s = self.lstrip
    80100    (s == self) ? nil : self.replace(s)
     
    93113  #
    94114  def rstrip!
     115    raise RuntimeError, "can't modify frozen String" if frozen?
    95116    s = self.rstrip
    96117    (s == self) ? nil : self.replace(s)
     
    105126  #
    106127  def strip!
     128    raise RuntimeError, "can't modify frozen String" if frozen?
    107129    s = self.strip
    108130    (s == self) ? nil : self.replace(s)
     
    165187  #
    166188  def slice!(arg1, arg2=nil)
     189    raise RuntimeError, "can't modify frozen String" if frozen?
    167190    raise "wrong number of arguments (for 1..2)" if arg1.nil? && arg2.nil?
    168191
     
    189212        idx = arg1
    190213        idx += self.size if arg1 < 0
    191         validated = true if idx >=0 && arg1 < self.size   
     214        validated = true if idx >=0 && arg1 < self.size
    192215      end
    193216      if validated
     
    236259  #
    237260  def insert(idx, str)
    238     pos = idx.to_i
    239     pos += self.size + 1 if pos < 0
    240 
    241     raise IndexError, "index #{idx.to_i} out of string" if pos < 0 || pos > self.size
    242 
    243     return self + str if pos == -1
    244     return str + self if pos == 0
    245     return self[0..pos - 1] + str + self[pos..-1]
     261    if idx == -1
     262      return self << str
     263    elsif idx < 0
     264      idx += 1
     265    end
     266    self[idx, 0] = str
     267    self
    246268  end
    247269
     
    258280  #     "hello".ljust(20, '1234')   #=> "hello123412341234123"
    259281  def ljust(idx, padstr = ' ')
    260     if idx <= self.size
    261       return self
    262     end
    263     newstr = self.dup
    264     newstr << padstr
    265     while newstr.size <= idx
    266       newstr << padstr
    267     end
    268     return newstr.slice(0,idx)
    269   end
    270 
    271   #     str.upto(other_str, exclusive=false) {|s| block }   -> str
    272   #     str.upto(other_str, exclusive=false)                -> an_enumerator
    273   #
    274   #  Iterates through successive values, starting at <i>str</i> and
    275   #  ending at <i>other_str</i> inclusive, passing each value in turn to
    276   #  the block. The <code>String#succ</code> method is used to generate
    277   #  each value.  If optional second argument exclusive is omitted or is false,
    278   #  the last value will be included; otherwise it will be excluded.
    279   #
    280   #  If no block is given, an enumerator is returned instead.
    281   #
    282   #     "a8".upto("b6") {|s| print s, ' ' }
    283   #     for s in "a8".."b6"
    284   #       print s, ' '
    285   #     end
    286   #
    287   #  <em>produces:</em>
    288   #
    289   #     a8 a9 b0 b1 b2 b3 b4 b5 b6
    290   #     a8 a9 b0 b1 b2 b3 b4 b5 b6
    291   #
    292   #  If <i>str</i> and <i>other_str</i> contains only ascii numeric characters,
    293   #  both are recognized as decimal numbers. In addition, the width of
    294   #  string (e.g. leading zeros) is handled appropriately.
    295   #
    296   #     "9".upto("11").to_a   #=> ["9", "10", "11"]
    297   #     "25".upto("5").to_a   #=> []
    298   #     "07".upto("11").to_a  #=> ["07", "08", "09", "10", "11"]
    299   #
    300   def upto(other_str, excl=false, &block)
    301     return to_enum :upto, other_str, excl unless block
    302 
    303     str = self
    304     n = self.<=>other_str
    305     return self if n > 0 || (self == other_str && excl)
    306     while true
    307       block.call(str)
    308       return self if !excl && str == other_str
    309       str = str.succ
    310       return self if excl && str == other_str
    311     end
     282    raise ArgumentError, 'zero width padding' if padstr == ''
     283    return self if idx <= self.size
     284    pad_repetitions = (idx / padstr.length).ceil
     285    padding = (padstr * pad_repetitions)[0...(idx - self.length)]
     286    self + padding
     287  end
     288
     289  ##
     290  #  call-seq:
     291  #     str.rjust(integer, padstr=' ')   -> new_str
     292  #
     293  #  If <i>integer</i> is greater than the length of <i>str</i>, returns a new
     294  #  <code>String</code> of length <i>integer</i> with <i>str</i> right justified
     295  #  and padded with <i>padstr</i>; otherwise, returns <i>str</i>.
     296  #
     297  #     "hello".rjust(4)            #=> "hello"
     298  #     "hello".rjust(20)           #=> "               hello"
     299  #     "hello".rjust(20, '1234')   #=> "123412341234123hello"
     300  def rjust(idx, padstr = ' ')
     301    raise ArgumentError, 'zero width padding' if padstr == ''
     302    return self if idx <= self.size
     303    pad_repetitions = (idx / padstr.length).ceil
     304    padding = (padstr * pad_repetitions)[0...(idx - self.length)]
     305    padding + self
    312306  end
    313307
    314308  def chars(&block)
    315309    if block_given?
    316       self.split('').map do |i|
     310      self.split('').each do |i|
    317311        block.call(i)
    318312      end
     
    322316    end
    323317  end
    324   alias each_char chars
     318
     319  def each_char(&block)
     320    return to_enum :each_char unless block
     321
     322    split('').each do |i|
     323      block.call(i)
     324    end
     325    self
     326  end
    325327
    326328  def codepoints(&block)
     
    328330
    329331    if block_given?
    330       self.split('').map do|x|
     332      self.split('').each do|x|
    331333        block.call(x.ord)
    332334      end
     
    337339  end
    338340  alias each_codepoint codepoints
     341
     342  ##
     343  # call-seq:
     344  #    str.prepend(other_str)  -> str
     345  #
     346  # Prepend---Prepend the given string to <i>str</i>.
     347  #
     348  #    a = "world"
     349  #    a.prepend("hello ") #=> "hello world"
     350  #    a                   #=> "hello world"
     351  def prepend(arg)
     352    self[0, 0] = arg
     353    self
     354  end
    339355end
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-string-ext/src/string.c

    r321 r331  
    11#include <string.h>
    2 #include "mruby.h"
    3 #include "mruby/array.h"
    4 #include "mruby/class.h"
    5 #include "mruby/string.h"
    6 #include "mruby/range.h"
     2#include <mruby.h>
     3#include <mruby/array.h>
     4#include <mruby/class.h>
     5#include <mruby/string.h>
     6#include <mruby/range.h>
    77
    88static mrb_value
     
    2424{
    2525  mrb_int pos, byte;
    26   long len = RSTRING_LEN(str);
     26  long len;
    2727
    2828  mrb_get_args(mrb, "ii", &pos, &byte);
    2929
     30  len = RSTRING_LEN(str);
    3031  if (pos < -len || len <= pos)
    3132    mrb_raisef(mrb, E_INDEX_ERROR, "index %S is out of array", mrb_fixnum_value(pos));
     
    5657
    5758      len = RSTRING_LEN(str);
    58       if (mrb_range_beg_len(mrb, a1, &beg, &len, len)) {
     59      switch (mrb_range_beg_len(mrb, a1, &beg, &len, len, TRUE)) {
     60      case 0:                   /* not range */
     61        break;
     62      case 1:                   /* range */
    5963        return mrb_str_substr(mrb, str, beg, len);
     64      case 2:                   /* out of range */
     65        mrb_raisef(mrb, E_RANGE_ERROR, "%S out of range", a1);
     66        break;
    6067      }
    6168      return mrb_nil_value();
     
    128135}
    129136
     137static mrb_value mrb_fixnum_chr(mrb_state *mrb, mrb_value num);
     138
    130139/*
    131140 *  call-seq:
     
    147156{
    148157  mrb_value str;
    149   mrb_get_args(mrb, "S", &str);
     158
     159  mrb_get_args(mrb, "o", &str);
     160  if (mrb_fixnum_p(str))
     161    str = mrb_fixnum_chr(mrb, str);
     162  else
     163    str = mrb_string_type(mrb, str);
    150164  mrb_str_concat(mrb, self, str);
    151165  return self;
     
    308322  mrb_int len;
    309323  mrb_value arg;
    310   char *p = RSTRING_PTR(self), *t;
    311   char *e = p + RSTRING_LEN(self);
     324  char *b = RSTRING_PTR(self);
     325  char *p = b, *t;
     326  char *e = b + RSTRING_LEN(self);
    312327
    313328  mrb_get_args(mrb, "&", &blk);
    314329
    315330  result = mrb_ary_new(mrb);
    316 
     331  ai = mrb_gc_arena_save(mrb);
    317332  if (!mrb_nil_p(blk)) {
    318333    while (p < e) {
     
    323338      arg = mrb_str_new(mrb, t, len);
    324339      mrb_yield_argv(mrb, blk, 1, &arg);
     340      mrb_gc_arena_restore(mrb, ai);
     341      if (b != RSTRING_PTR(self)) {
     342        ptrdiff_t diff = p - b;
     343        b = RSTRING_PTR(self);
     344        p = b + diff;
     345      }
     346      e = b + RSTRING_LEN(self);
    325347    }
    326348    return self;
    327349  }
    328350  while (p < e) {
    329     ai = mrb_gc_arena_save(mrb);
    330351    t = p;
    331352    while (p < e && *p != '\n') p++;
     
    354375  const char *prepend;
    355376  struct RString *s = mrb_str_ptr(self);
    356   size_t l;
     377  mrb_int l;
    357378
    358379  if (RSTRING_LEN(self) == 0)
     
    374395    e = p + l - 1;
    375396    result = mrb_str_new_lit(mrb, "");
    376   } else {
     397  }
     398  else {
    377399    // find leading letter of the ascii/number
    378400    b = e;
     
    392414        mrb_str_cat_lit(mrb, result, "\x01");
    393415        (*e) = 0;
    394       } else
     416      }
     417      else
    395418        (*e)++;
    396419      break;
     
    400423      if (e == b) prepend = "1";
    401424      *e = '0';
    402     } else if (*e == 'z') {
     425    }
     426    else if (*e == 'z') {
    403427      if (e == b) prepend = "a";
    404428      *e = 'a';
    405     } else if (*e == 'Z') {
     429    }
     430    else if (*e == 'Z') {
    406431      if (e == b) prepend = "A";
    407432      *e = 'A';
    408     } else {
     433    }
     434    else {
    409435      (*e)++;
    410436      break;
     
    428454  mrb_str_succ_bang(mrb, str);
    429455  return str;
    430 }
    431 
    432 /*
    433  *  call-seq:
    434  *     str.prepend(other_str)  -> str
    435  *
    436  *  Prepend---Prepend the given string to <i>str</i>.
    437  *
    438  *     a = "world"
    439  *     a.prepend("hello ") #=> "hello world"
    440  *     a                   #=> "hello world"
    441  */
    442 static mrb_value
    443 mrb_str_prepend(mrb_state *mrb, mrb_value self)
    444 {
    445   struct RString *s1 = mrb_str_ptr(self), *s2, *temp_s;
    446   mrb_int len;
    447   mrb_value other, temp_str;
    448 
    449   mrb_get_args(mrb, "S", &other);
    450 
    451   mrb_str_modify(mrb, s1);
    452   if (!mrb_string_p(other)) {
    453     other = mrb_str_to_str(mrb, other);
    454   }
    455   s2 = mrb_str_ptr(other);
    456   len = RSTR_LEN(s1) + RSTR_LEN(s2);
    457   temp_str = mrb_str_new(mrb, NULL, RSTR_LEN(s1));
    458   temp_s = mrb_str_ptr(temp_str);
    459   memcpy(RSTR_PTR(temp_s), RSTR_PTR(s1), RSTR_LEN(s1));
    460   if (RSTRING_CAPA(self) < len) {
    461     mrb_str_resize(mrb, self, len);
    462   }
    463   memcpy(RSTR_PTR(s1), RSTR_PTR(s2), RSTR_LEN(s2));
    464   memcpy(RSTR_PTR(s1) + RSTR_LEN(s2), RSTR_PTR(temp_s), RSTR_LEN(temp_s));
    465   RSTR_SET_LEN(s1, len);
    466   RSTR_PTR(s1)[len] = '\0';
    467   return self;
    468456}
    469457
     
    530518  if (RSTRING_LEN(str) == 0)
    531519    mrb_raise(mrb, E_ARGUMENT_ERROR, "empty string");
    532   return mrb_fixnum_value(RSTRING_PTR(str)[0]);
     520  return mrb_fixnum_value((unsigned char)RSTRING_PTR(str)[0]);
    533521}
    534522#endif
     523
     524static mrb_bool
     525all_digits_p(const char *s, mrb_int len)
     526{
     527  while (len-- > 0) {
     528    if (!ISDIGIT(*s)) return FALSE;
     529    s++;
     530  }
     531  return TRUE;
     532}
     533
     534/*
     535 *  call-seq:
     536 *     str.upto(other_str, exclusive=false) {|s| block }   -> str
     537 *     str.upto(other_str, exclusive=false)                -> an_enumerator
     538 *
     539 *  Iterates through successive values, starting at <i>str</i> and
     540 *  ending at <i>other_str</i> inclusive, passing each value in turn to
     541 *  the block. The <code>String#succ</code> method is used to generate
     542 *  each value.  If optional second argument exclusive is omitted or is false,
     543 *  the last value will be included; otherwise it will be excluded.
     544 *
     545 *  If no block is given, an enumerator is returned instead.
     546 *
     547 *     "a8".upto("b6") {|s| print s, ' ' }
     548 *     for s in "a8".."b6"
     549 *       print s, ' '
     550 *     end
     551 *
     552 *  <em>produces:</em>
     553 *
     554 *     a8 a9 b0 b1 b2 b3 b4 b5 b6
     555 *     a8 a9 b0 b1 b2 b3 b4 b5 b6
     556 *
     557 *  If <i>str</i> and <i>other_str</i> contains only ascii numeric characters,
     558 *  both are recognized as decimal numbers. In addition, the width of
     559 *  string (e.g. leading zeros) is handled appropriately.
     560 *
     561 *     "9".upto("11").to_a   #=> ["9", "10", "11"]
     562 *     "25".upto("5").to_a   #=> []
     563 *     "07".upto("11").to_a  #=> ["07", "08", "09", "10", "11"]
     564 */
     565static mrb_value
     566mrb_str_upto(mrb_state *mrb, mrb_value beg)
     567{
     568  mrb_value end;
     569  mrb_value exclusive = mrb_false_value();
     570  mrb_value block = mrb_nil_value();
     571  mrb_value current, after_end;
     572  mrb_int n;
     573  mrb_bool excl;
     574
     575  mrb_get_args(mrb, "o|o&", &end, &exclusive, &block);
     576
     577  if (mrb_nil_p(block)) {
     578    return mrb_funcall(mrb, beg, "to_enum", 3, mrb_symbol_value(mrb_intern_lit(mrb, "upto")), end, exclusive);
     579  }
     580  end = mrb_string_type(mrb, end);
     581  excl = mrb_test(exclusive);
     582
     583  /* single character */
     584  if (RSTRING_LEN(beg) == 1 && RSTRING_LEN(end) == 1 &&
     585  ISASCII(RSTRING_PTR(beg)[0]) && ISASCII(RSTRING_PTR(end)[0])) {
     586    char c = RSTRING_PTR(beg)[0];
     587    char e = RSTRING_PTR(end)[0];
     588    int ai = mrb_gc_arena_save(mrb);
     589
     590    if (c > e || (excl && c == e)) return beg;
     591    for (;;) {
     592      mrb_yield(mrb, block, mrb_str_new(mrb, &c, 1));
     593      mrb_gc_arena_restore(mrb, ai);
     594      if (!excl && c == e) break;
     595      c++;
     596      if (excl && c == e) break;
     597    }
     598    return beg;
     599  }
     600  /* both edges are all digits */
     601  if (ISDIGIT(RSTRING_PTR(beg)[0]) && ISDIGIT(RSTRING_PTR(end)[0]) &&
     602      all_digits_p(RSTRING_PTR(beg), RSTRING_LEN(beg)) &&
     603      all_digits_p(RSTRING_PTR(end), RSTRING_LEN(end))) {
     604    int ai = mrb_gc_arena_save(mrb);
     605    mrb_int min_width = RSTRING_LEN(beg);
     606    mrb_int max_width = RSTRING_LEN(end);
     607    mrb_int bi = mrb_int(mrb, mrb_str_to_inum(mrb, beg, 10, FALSE));
     608    mrb_int ei = mrb_int(mrb, mrb_str_to_inum(mrb, end, 10, FALSE));
     609    mrb_value str = mrb_str_new(mrb, NULL, max_width);
     610    char *buf = RSTRING_PTR(str);
     611
     612    while (bi <= ei) {
     613      if (excl && bi == ei) break;
     614      snprintf(buf, max_width+1, "%.*" MRB_PRId, (int)min_width, bi);
     615      mrb_yield(mrb, block, mrb_str_new(mrb, buf, strlen(buf)));
     616      mrb_gc_arena_restore(mrb, ai);
     617      bi++;
     618    }
     619
     620    return beg;
     621  }
     622  /* normal case */
     623  n = mrb_int(mrb, mrb_funcall(mrb, beg, "<=>", 1, end));
     624  if (n > 0 || (excl && n == 0)) return beg;
     625
     626  after_end = mrb_funcall(mrb, end, "succ", 0);
     627  current = mrb_str_dup(mrb, beg);
     628  while (!mrb_str_equal(mrb, current, after_end)) {
     629    int ai = mrb_gc_arena_save(mrb);
     630    mrb_value next = mrb_nil_value();
     631    if (excl || !mrb_str_equal(mrb, current, end))
     632      next = mrb_funcall(mrb, current, "succ", 0);
     633    mrb_yield(mrb, block, current);
     634    if (mrb_nil_p(next)) break;
     635    current = mrb_str_to_str(mrb, next);
     636    if (excl && mrb_str_equal(mrb, current, end)) break;
     637    if (RSTRING_LEN(current) > RSTRING_LEN(end) || RSTRING_LEN(current) == 0)
     638      break;
     639    mrb_gc_arena_restore(mrb, ai);
     640  }
     641
     642  return beg;
     643}
    535644
    536645void
     
    555664  mrb_define_method(mrb, s, "succ",            mrb_str_succ,            MRB_ARGS_NONE());
    556665  mrb_define_method(mrb, s, "succ!",           mrb_str_succ_bang,       MRB_ARGS_NONE());
    557   mrb_define_method(mrb, s, "prepend",         mrb_str_prepend,         MRB_ARGS_REQ(1));
    558666  mrb_alias_method(mrb, s, mrb_intern_lit(mrb, "next"), mrb_intern_lit(mrb, "succ"));
    559667  mrb_alias_method(mrb, s, mrb_intern_lit(mrb, "next!"), mrb_intern_lit(mrb, "succ!"));
    560668  mrb_define_method(mrb, s, "ord", mrb_str_ord, MRB_ARGS_NONE());
     669  mrb_define_method(mrb, s, "upto", mrb_str_upto, MRB_ARGS_ANY());
    561670
    562671  mrb_define_method(mrb, mrb->fixnum_class, "chr", mrb_fixnum_chr, MRB_ARGS_NONE());
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-string-ext/test/string.rb

    r321 r331  
    33
    44UTF8STRING = ("\343\201\202".size == 1)
     5
     6assert('String.try_convert') do
     7  assert_nil String.try_convert(nil)
     8  assert_nil String.try_convert(:foo)
     9  assert_equal "", String.try_convert("")
     10  assert_equal "1,2,3", String.try_convert("1,2,3")
     11end
    512
    613assert('String#getbyte') do
     
    2229  assert_equal(h, str1.getbyte(0))
    2330  assert_equal("Hello", str1)
     31end
     32
     33assert("String#setbyte raises IndexError if arg conversion resizes String") do
     34  $s = "01234\n"
     35  class Tmp
     36      def to_i
     37          $s.chomp! ''
     38          95
     39      end
     40  end
     41  tmp = Tmp.new
     42  assert_raise(IndexError) { $s.setbyte(5, tmp) }
    2443end
    2544
     
    104123
    105124assert('String#concat') do
    106   s = "Hello "
    107   s.concat "World!"
    108   t = "Hello "
    109   t << "World!"
    110   assert_equal "Hello World!", t
    111   assert_equal "Hello World!", s
     125  assert_equal "Hello World!", "Hello " << "World" << 33
     126  assert_equal "Hello World!", "Hello ".concat("World").concat(33)
     127
     128  o = Object.new
     129  def o.to_str
     130    "to_str"
     131  end
     132  assert_equal "hi to_str", "hi " << o
     133
     134  assert_raise(TypeError) { "".concat(Object.new) }
    112135end
    113136
     
    400423  assert_raise(IndexError) { "abcd".insert(5, 'X') }
    401424  assert_raise(IndexError) { "abcd".insert(-6, 'X') }
     425
     426  a = "abcd"
     427  a.insert(0, 'X')
     428  assert_equal "Xabcd", a
    402429end
    403430
     
    411438  assert_equal "hello", "hello".ljust(4)
    412439  assert_equal "hello               ", "hello".ljust(20)
     440  assert_equal 20, "hello".ljust(20).length
    413441  assert_equal "hello123412341234123", "hello".ljust(20, '1234')
    414442  assert_equal "hello", "hello".ljust(-3)
    415443end
    416444
     445assert('String#rjust') do
     446  assert_equal "hello", "hello".rjust(4)
     447  assert_equal "               hello", "hello".rjust(20)
     448  assert_equal 20, "hello".rjust(20).length
     449  assert_equal "123412341234123hello", "hello".rjust(20, '1234')
     450  assert_equal "hello", "hello".rjust(-3)
     451end
     452
     453if UTF8STRING
     454  assert('String#ljust with UTF8') do
     455    assert_equal "helloん              ", "helloん".ljust(20)
     456    assert_equal "helloó                            ", "helloó".ljust(34)
     457    assert_equal 34, "helloó".ljust(34).length
     458    assert_equal "helloんんんんんんんんんんんんんん", "hello".ljust(19, 'ん')
     459    assert_equal "helloんんんんんんんんんんんんんんん", "hello".ljust(20, 'ん')
     460  end
     461
     462  assert('String#rjust with UTF8') do
     463    assert_equal "              helloん", "helloん".rjust(20)
     464    assert_equal "                            helloó", "helloó".rjust(34)
     465    # assert_equal 34, "helloó".rjust(34).length
     466    assert_equal "んんんんんんんんんんんんんんhello", "hello".rjust(19, 'ん')
     467    assert_equal "んんんんんんんんんんんんんんんhello", "hello".rjust(20, 'ん')
     468  end
     469
     470  assert('UTF8 byte counting') do
     471    ret = '                                  '
     472    ret[-6..-1] = "helloó"
     473    assert_equal 34, ret.length
     474  end
     475end
     476
     477assert('String#ljust should not change string') do
     478  a = "hello"
     479  a.ljust(20)
     480  assert_equal "hello", a
     481end
     482
     483assert('String#rjust should not change string') do
     484  a = "hello"
     485  a.rjust(20)
     486  assert_equal "hello", a
     487end
     488
     489assert('String#ljust should raise on zero width padding') do
     490  assert_raise(ArgumentError) { "foo".ljust(10, '') }
     491end
     492
     493assert('String#rjust should raise on zero width padding') do
     494  assert_raise(ArgumentError) { "foo".rjust(10, '') }
     495end
     496
    417497assert('String#upto') do
     498  assert_equal %w(a8 a9 b0 b1 b2 b3 b4 b5 b6), "a8".upto("b6").to_a
     499  assert_equal ["9", "10", "11"], "9".upto("11").to_a
     500  assert_equal [], "25".upto("5").to_a
     501  assert_equal ["07", "08", "09", "10", "11"], "07".upto("11").to_a
     502
     503if UTF8STRING
     504  assert_equal ["あ", "ぃ", "い", "ぅ", "う", "ぇ", "え", "ぉ", "お"], "あ".upto("お").to_a
     505end
     506
     507  assert_equal ["9", ":", ";", "<", "=", ">", "?", "@", "A"], "9".upto("A").to_a
     508
    418509  a     = "aa"
    419510  start = "aa"
     
    475566  })
    476567  assert_equal(2, count)
     568
     569  assert_raise(TypeError) { "a".upto(:c) {} }
    477570end
    478571
     
    480573  got = "hello!".split('').map {|x| x.ord}
    481574  expect = [104, 101, 108, 108, 111, 33]
     575  unless UTF8STRING
     576    got << "\xff".ord
     577    expect << 0xff
     578  end
    482579  assert_equal expect, got
    483580end
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-struct/mrblib/struct.rb

    r321 r331  
    8383    alias to_s inspect
    8484  end
     85
     86  ##
     87  # call-seq:
     88  #   hsh.dig(key,...)                 -> object
     89  #
     90  # Extracts the nested value specified by the sequence of <i>key</i>
     91  # objects by calling +dig+ at each step, returning +nil+ if any
     92  # intermediate step is +nil+.
     93  #
     94  def dig(idx,*args)
     95    n = self[idx]
     96    if args.size > 0
     97      n&.dig(*args)
     98    else
     99      n
     100    end
     101  end
    85102end
    86103
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-struct/src/struct.c

    r321 r331  
    66
    77#include <string.h>
    8 #include "mruby.h"
    9 #include "mruby/array.h"
    10 #include "mruby/string.h"
    11 #include "mruby/class.h"
    12 #include "mruby/variable.h"
    13 #include "mruby/hash.h"
    14 #include "mruby/range.h"
     8#include <mruby.h>
     9#include <mruby/array.h>
     10#include <mruby/string.h>
     11#include <mruby/class.h>
     12#include <mruby/variable.h>
     13#include <mruby/hash.h>
     14#include <mruby/range.h>
    1515
    1616#define RSTRUCT_LEN(st) mrb_ary_ptr(st)->len
     
    6262  }
    6363  if (RSTRUCT_LEN(s) != RARRAY_LEN(members)) {
    64     mrb_raisef(mrb, E_TYPE_ERROR,
    65                "struct size differs (%S required %S given)",
    66                mrb_fixnum_value(RARRAY_LEN(members)), mrb_fixnum_value(RSTRUCT_LEN(s)));
     64    if (RSTRUCT_LEN(s) == 0) {  /* probably uninitialized */
     65      mrb_ary_resize(mrb, s, RARRAY_LEN(members));
     66    }
     67    else {
     68      mrb_raisef(mrb, E_TYPE_ERROR,
     69                 "struct size differs (%S required %S given)",
     70                 mrb_fixnum_value(RARRAY_LEN(members)), mrb_fixnum_value(RSTRUCT_LEN(s)));
     71    }
    6772  }
    6873  return members;
     
    8085}
    8186
     87static void
     88mrb_struct_modify(mrb_state *mrb, mrb_value strct)
     89{
     90  if (MRB_FROZEN_P(mrb_basic_ptr(strct))) {
     91    mrb_raise(mrb, E_RUNTIME_ERROR, "can't modify frozen struct");
     92  }
     93
     94  mrb_write_barrier(mrb, mrb_basic_ptr(strct));
     95}
     96
    8297/* 15.2.18.4.6  */
    8398/*
     
    99114}
    100115
    101 static mrb_value
    102 mrb_struct_getmember(mrb_state *mrb, mrb_value obj, mrb_sym id)
    103 {
    104   mrb_value members, slot, *ptr;
    105   const mrb_value *ptr_members;
    106   mrb_int i, len;
    107 
    108   ptr = RSTRUCT_PTR(obj);
    109   members = struct_members(mrb, obj);
    110   ptr_members = RARRAY_PTR(members);
    111   slot = mrb_symbol_value(id);
    112   len = RARRAY_LEN(members);
    113   for (i=0; i<len; i++) {
    114     if (mrb_obj_equal(mrb, ptr_members[i], slot)) {
    115       return ptr[i];
    116     }
    117   }
    118   mrb_raisef(mrb, E_INDEX_ERROR, "'%S' is not a struct member", mrb_sym2str(mrb, id));
    119   return mrb_nil_value();       /* not reached */
    120 }
     116static mrb_value struct_aref_sym(mrb_state *mrb, mrb_value obj, mrb_sym id);
    121117
    122118static mrb_value
    123119mrb_struct_ref(mrb_state *mrb, mrb_value obj)
    124120{
    125   return mrb_struct_getmember(mrb, obj, mrb->c->ci->mid);
    126 }
    127 
    128 static mrb_value mrb_struct_ref0(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[0];}
    129 static mrb_value mrb_struct_ref1(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[1];}
    130 static mrb_value mrb_struct_ref2(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[2];}
    131 static mrb_value mrb_struct_ref3(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[3];}
    132 static mrb_value mrb_struct_ref4(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[4];}
    133 static mrb_value mrb_struct_ref5(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[5];}
    134 static mrb_value mrb_struct_ref6(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[6];}
    135 static mrb_value mrb_struct_ref7(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[7];}
    136 static mrb_value mrb_struct_ref8(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[8];}
    137 static mrb_value mrb_struct_ref9(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[9];}
    138 
    139 #define numberof(array) (int)(sizeof(array) / sizeof((array)[0]))
    140 #define N_REF_FUNC numberof(ref_func)
    141 
    142 static const mrb_func_t ref_func[] = {
    143   mrb_struct_ref0,
    144   mrb_struct_ref1,
    145   mrb_struct_ref2,
    146   mrb_struct_ref3,
    147   mrb_struct_ref4,
    148   mrb_struct_ref5,
    149   mrb_struct_ref6,
    150   mrb_struct_ref7,
    151   mrb_struct_ref8,
    152   mrb_struct_ref9,
    153 };
     121  return struct_aref_sym(mrb, obj, mrb->c->ci->mid);
     122}
    154123
    155124static mrb_sym
     
    172141}
    173142
    174 static mrb_value
    175 mrb_struct_set(mrb_state *mrb, mrb_value obj, mrb_value val)
    176 {
     143static mrb_value mrb_struct_aset_sym(mrb_state *mrb, mrb_value s, mrb_sym id, mrb_value val);
     144
     145static mrb_value
     146mrb_struct_set_m(mrb_state *mrb, mrb_value obj)
     147{
     148  mrb_value val;
     149
    177150  const char *name;
    178   mrb_int i, len, slen;
     151  mrb_int slen;
    179152  mrb_sym mid;
    180   mrb_value members, slot, *ptr;
    181   const mrb_value *ptr_members;
     153
     154  mrb_get_args(mrb, "o", &val);
    182155
    183156  /* get base id */
     
    185158  mid = mrb_intern(mrb, name, slen-1); /* omit last "=" */
    186159
    187   members = struct_members(mrb, obj);
    188   ptr_members = RARRAY_PTR(members);
    189   len = RARRAY_LEN(members);
    190   ptr = RSTRUCT_PTR(obj);
    191   for (i=0; i<len; i++) {
    192     slot = ptr_members[i];
    193     if (mrb_symbol(slot) == mid) {
    194       return ptr[i] = val;
    195     }
    196   }
    197   mrb_raisef(mrb, E_INDEX_ERROR, "'%S' is not a struct member", mrb_sym2str(mrb, mid));
    198   return mrb_nil_value();       /* not reached */
    199 }
    200 
    201 static mrb_value
    202 mrb_struct_set_m(mrb_state *mrb, mrb_value obj)
    203 {
    204   mrb_value val;
    205 
    206   mrb_get_args(mrb, "o", &val);
    207   return mrb_struct_set(mrb, obj, val);
     160  return mrb_struct_aset_sym(mrb, obj, mid, val);
    208161}
    209162
     
    235188
    236189    if (is_local_id(mrb, name) || is_const_id(mrb, name)) {
    237       if (i < N_REF_FUNC) {
    238         mrb_define_method_id(mrb, c, id, ref_func[i], MRB_ARGS_NONE());
    239       }
    240       else {
    241         mrb_define_method_id(mrb, c, id, mrb_struct_ref, MRB_ARGS_NONE());
    242       }
     190      mrb_define_method_id(mrb, c, id, mrb_struct_ref, MRB_ARGS_NONE());
    243191      mrb_define_method_id(mrb, c, mrb_id_attrset(mrb, id), mrb_struct_set_m, MRB_ARGS_REQ(1));
    244192      mrb_gc_arena_restore(mrb, ai);
     
    266214    if (mrb_const_defined_at(mrb, mrb_obj_value(klass), id)) {
    267215      mrb_warn(mrb, "redefining constant Struct::%S", name);
    268       /* ?rb_mod_remove_const(klass, mrb_sym2name(mrb, id)); */
     216      mrb_const_remove(mrb, mrb_obj_value(klass), id);
    269217    }
    270218    c = mrb_define_class_under(mrb, klass, RSTRING_PTR(name), klass);
     
    336284  else {
    337285    if (argc > 0) name = argv[0];
    338     if (argc > 1) rest = argv[1];
    339     if (mrb_array_p(rest)) {
    340       if (!mrb_nil_p(name) && mrb_symbol_p(name)) {
    341         /* 1stArgument:symbol -> name=nil rest=argv[0]-[n] */
    342         mrb_ary_unshift(mrb, rest, name);
    343         name = mrb_nil_value();
    344       }
    345     }
    346     else {
    347       pargv = &argv[1];
    348       argcnt = argc-1;
    349       if (!mrb_nil_p(name) && mrb_symbol_p(name)) {
    350         /* 1stArgument:symbol -> name=nil rest=argv[0]-[n] */
    351         name = mrb_nil_value();
    352         pargv = &argv[0];
    353         argcnt++;
    354       }
    355       rest = mrb_ary_new_from_values(mrb, argcnt, pargv);
    356     }
     286    pargv = &argv[1];
     287    argcnt = argc-1;
     288    if (!mrb_nil_p(name) && mrb_symbol_p(name)) {
     289      /* 1stArgument:symbol -> name=nil rest=argv[0]-[n] */
     290      name = mrb_nil_value();
     291      pargv = &argv[0];
     292      argcnt++;
     293    }
     294    rest = mrb_ary_new_from_values(mrb, argcnt, pargv);
    357295    for (i=0; i<RARRAY_LEN(rest); i++) {
    358296      id = mrb_obj_to_sym(mrb, RARRAY_PTR(rest)[i]);
     
    360298    }
    361299  }
    362   st = make_struct(mrb, name, rest, struct_class(mrb));
     300  st = make_struct(mrb, name, rest, mrb_class_ptr(klass));
    363301  if (!mrb_nil_p(b)) {
    364     mrb_yield_with_class(mrb, b, 1, &st, st, mrb_class_ptr(klass));
     302    mrb_yield_with_class(mrb, b, 1, &st, st, mrb_class_ptr(st));
    365303  }
    366304
     
    419357{
    420358  mrb_value s;
    421   mrb_int i, len;
    422359
    423360  mrb_get_args(mrb, "o", &s);
     
    430367    mrb_raise(mrb, E_TYPE_ERROR, "corrupted struct");
    431368  }
    432   if (RSTRUCT_LEN(copy) != RSTRUCT_LEN(s)) {
    433     mrb_raise(mrb, E_TYPE_ERROR, "struct size mismatch");
    434   }
    435   len = RSTRUCT_LEN(copy);
    436   for (i = 0; i < len; i++) {
    437     mrb_ary_set(mrb, copy, i, RSTRUCT_PTR(s)[i]);
    438   }
     369  mrb_ary_replace(mrb, copy, s);
    439370  return copy;
    440371}
    441372
    442373static mrb_value
    443 struct_aref_sym(mrb_state *mrb, mrb_value s, mrb_sym id)
    444 {
    445   mrb_value *ptr, members;
     374struct_aref_sym(mrb_state *mrb, mrb_value obj, mrb_sym id)
     375{
     376  mrb_value members, *ptr;
    446377  const mrb_value *ptr_members;
    447378  mrb_int i, len;
    448379
    449   ptr = RSTRUCT_PTR(s);
    450   members = struct_members(mrb, s);
     380  members = struct_members(mrb, obj);
    451381  ptr_members = RARRAY_PTR(members);
    452382  len = RARRAY_LEN(members);
     383  ptr = RSTRUCT_PTR(obj);
    453384  for (i=0; i<len; i++) {
    454     if (mrb_symbol(ptr_members[i]) == id) {
     385    mrb_value slot = ptr_members[i];
     386    if (mrb_symbol_p(slot) && mrb_symbol(slot) == id) {
    455387      return ptr[i];
    456388    }
    457389  }
    458   mrb_raisef(mrb, E_INDEX_ERROR, "no member '%S' in struct", mrb_sym2str(mrb, id));
     390  mrb_raisef(mrb, E_INDEX_ERROR, "'%S' is not a struct member", mrb_sym2str(mrb, id));
    459391  return mrb_nil_value();       /* not reached */
    460392}
     
    504436
    505437    if (mrb_nil_p(sym)) {
    506       mrb_raisef(mrb, E_INDEX_ERROR, "no member '%S' in struct", idx);
     438      mrb_name_error(mrb, mrb_intern_str(mrb, idx), "no member '%S' in struct", idx);
    507439    }
    508440    idx = sym;
     
    523455  members = struct_members(mrb, s);
    524456  len = RARRAY_LEN(members);
    525   if (RSTRUCT_LEN(s) != len) {
    526     mrb_raisef(mrb, E_TYPE_ERROR,
    527                "struct size differs (%S required %S given)",
    528                mrb_fixnum_value(len), mrb_fixnum_value(RSTRUCT_LEN(s)));
    529   }
    530457  ptr = RSTRUCT_PTR(s);
    531458  ptr_members = RARRAY_PTR(members);
    532459  for (i=0; i<len; i++) {
    533460    if (mrb_symbol(ptr_members[i]) == id) {
     461      mrb_struct_modify(mrb, s);
    534462      ptr[i] = val;
    535463      return val;
    536464    }
    537465  }
    538   mrb_raisef(mrb, E_INDEX_ERROR, "no member '%S' in struct", mrb_sym2str(mrb, id));
     466  mrb_name_error(mrb, id, "no member '%S' in struct", mrb_sym2str(mrb, id));
    539467  return val;                   /* not reach */
    540468}
     
    575503
    576504    if (mrb_nil_p(sym)) {
    577       mrb_raisef(mrb, E_INDEX_ERROR, "no member '%S' in struct", idx);
     505      mrb_name_error(mrb, mrb_intern_str(mrb, idx), "no member '%S' in struct", idx);
    578506    }
    579507    idx = sym;
     
    595523               mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s)));
    596524  }
     525  mrb_struct_modify(mrb, s);
    597526  return RSTRUCT_PTR(s)[i] = val;
    598527}
     
    720649  mrb_int i;
    721650
    722   members = struct_s_members(mrb, mrb_class(mrb, self));
     651  members = struct_members(mrb, self);
    723652  ret = mrb_hash_new_capa(mrb, RARRAY_LEN(members));
    724653
     
    761690  struct RClass *st;
    762691  st = mrb_define_class(mrb, "Struct",  mrb->object_class);
     692  MRB_SET_INSTANCE_TT(st, MRB_TT_ARRAY);
    763693
    764694  mrb_define_class_method(mrb, st, "new",             mrb_struct_s_def,       MRB_ARGS_ANY());  /* 15.2.18.3.1  */
     
    777707  mrb_define_method(mrb, st,        "values",         mrb_struct_to_a,        MRB_ARGS_NONE());
    778708  mrb_define_method(mrb, st,        "to_h",           mrb_struct_to_h,        MRB_ARGS_NONE());
    779   mrb_define_method(mrb, st,        "values_at",      mrb_struct_values_at,   MRB_ARGS_NONE());
     709  mrb_define_method(mrb, st,        "values_at",      mrb_struct_values_at,   MRB_ARGS_ANY());
    780710}
    781711
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-struct/test/struct.rb

    r321 r331  
    33
    44assert('Struct', '15.2.18') do
    5   Struct.class == Class
     5  assert_equal Class, Struct.class
    66end
    77
    88assert('Struct.new', '15.2.18.3.1') do
    99  c = Struct.new(:m1, :m2)
    10   c.superclass == Struct and
    11     c.members == [:m1,:m2]
     10  assert_equal Struct, c.superclass
     11  assert_equal [:m1, :m2], c.members
    1212end
    1313
     
    1515assert('Struct.new', '15.2.18.3.1') do
    1616  c = Struct.new()
    17   c.superclass == Struct and c.members == []
     17  assert_equal Struct, c.superclass
     18  assert_equal [], c.members
    1819end
    1920
     
    2223  cc1 = c.new(1,2)
    2324  cc2 = c.new(1,2)
    24   cc1 == cc2
     25  assert_true cc1 == cc2
     26
     27  Struct.new(:m1, :m2) { def foo; end }
     28  assert_raise(NoMethodError) { Struct.new(:m1).new.foo }
    2529end
    2630
     
    2832  c = Struct.new(:m1, :m2)
    2933  cc = c.new(1,2)
    30   cc[:m1] == 1 and cc["m2"] == 2
     34  assert_equal 1, cc[:m1]
     35  assert_equal 2, cc["m2"]
     36  assert_equal 1, cc[0]
     37  assert_equal 2, cc[-1]
     38  assert_raise(TypeError) { cc[[]] }
     39  assert_raise(IndexError) { cc[2] }
     40  assert_raise(NameError) { cc['tama'] }
    3141end
    3242
     
    3545  cc = c.new(1,2)
    3646  cc[:m1] = 3
    37   cc[:m1] == 3
     47  assert_equal 3, cc[:m1]
    3848  cc["m2"] = 3
    3949  assert_equal 3, cc["m2"]
     50  cc[0] = 4
     51  assert_equal 4, cc[0]
     52  cc[-1] = 5
     53  assert_equal 5, cc[-1]
    4054  assert_raise(TypeError) { cc[[]] = 3 }
     55  assert_raise(IndexError) { cc[2] = 7 }
     56  assert_raise(NameError) { cc['pochi'] = 8 }
    4157end
    4258
     
    4864    a << x
    4965  }
    50   a[0] == 1 and a[1] == 2
     66  assert_equal [1, 2], a
    5167end
    5268
     
    5874    a << [k,v]
    5975  }
    60   a[0] == [:m1, 1] and a[1] == [:m2, 2]
     76  assert_equal [[:m1, 1], [:m2, 2]], a
    6177end
    6278
    6379assert('Struct#members', '15.2.18.4.6') do
    6480  c = Struct.new(:m1, :m2)
    65   cc = c.new(1,2)
    66   cc.members == [:m1,:m2]
     81  assert_equal [:m1, :m2], c.new(1,2).members
    6782end
    6883
    6984assert('Struct#select', '15.2.18.4.7') do
    7085  c = Struct.new(:m1, :m2)
    71   cc = c.new(1,2)
    72   cc.select{|v| v % 2 == 0} == [2]
     86  assert_equal([2]) { c.new(1,2).select{|v| v % 2 == 0} }
    7387end
    7488
     
    101115end
    102116
     117assert('struct dup') do
     118  c = Struct.new(:m1, :m2, :m3, :m4, :m5)
     119  cc = c.new(1,2,3,4,5)
     120  assert_nothing_raised {
     121    assert_equal(cc, cc.dup)
     122  }
     123end
     124
    103125assert('struct inspect') do
    104126  c = Struct.new(:m1, :m2, :m3, :m4, :m5)
     
    130152  assert_raise(IndexError) { a.values_at 2 }
    131153end
     154
     155assert("Struct#dig") do
     156  a = Struct.new(:blue, :purple).new('aki', Struct.new(:red).new(1))
     157  assert_equal 'aki', a.dig(:blue)
     158  assert_equal 1, a.dig(:purple, :red)
     159  assert_equal 1, a.dig(1, 0)
     160end
     161
     162assert("Struct.new removes existing constant") do
     163  skip "redefining Struct with same name cause warnings"
     164  begin
     165    assert_not_equal Struct.new("Test", :a), Struct.new("Test", :a, :b)
     166  ensure
     167    Struct.remove_const :Test
     168  end
     169end
     170
     171assert("Struct#initialize_copy requires struct to be the same type") do
     172  begin
     173    Struct.new("Test", :a)
     174    a = Struct::Test.new("a")
     175    Struct.remove_const :Test
     176    Struct.new("Test", :a, :b)
     177    assert_raise(TypeError) do
     178      a.initialize_copy(Struct::Test.new("a", "b"))
     179    end
     180  ensure
     181    Struct.remove_const :Test
     182  end
     183end
     184
     185assert("Struct.new does not allow array") do
     186  assert_raise(TypeError) do
     187    Struct.new("Test", [:a])
     188  end
     189end
     190
     191assert("Struct.new generates subclass of Struct") do
     192  begin
     193    original_struct = Struct
     194    Struct = String
     195    assert_equal original_struct, original_struct.new.superclass
     196  ensure
     197    Struct = original_struct
     198  end
     199end
     200
     201assert 'Struct#freeze' do
     202  c = Struct.new :m
     203
     204  o = c.new
     205  o.m = :test
     206  assert_equal :test, o.m
     207
     208  o.freeze
     209  assert_raise(RuntimeError) { o.m = :modify }
     210  assert_raise(RuntimeError) { o[:m] = :modify }
     211  assert_equal :test, o.m
     212end
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-symbol-ext/src/symbol.c

    r321 r331  
    1 #include "mruby.h"
    2 #include "mruby/khash.h"
    3 #include "mruby/array.h"
     1#include <mruby.h>
     2#include <mruby/khash.h>
     3#include <mruby/array.h>
    44
    55typedef struct symbol_name {
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-test/driver.c

    r321 r331  
    1111#include <string.h>
    1212
    13 #include "mruby.h"
    14 #include "mruby/proc.h"
    15 #include "mruby/data.h"
    16 #include "mruby/compile.h"
    17 #include "mruby/string.h"
    18 #include "mruby/variable.h"
    19 #include "mruby/array.h"
     13#include <mruby.h>
     14#include <mruby/proc.h>
     15#include <mruby/data.h>
     16#include <mruby/compile.h>
     17#include <mruby/string.h>
     18#include <mruby/variable.h>
     19#include <mruby/array.h>
    2020
    2121void
     
    9595  mrb_define_const(mrb, mrbtest, "FIXNUM_BIT", mrb_fixnum_value(MRB_INT_BIT));
    9696
     97#ifdef MRB_USE_FLOAT
     98  mrb_define_const(mrb, mrbtest, "FLOAT_TOLERANCE", mrb_float_value(mrb, 1e-6));
     99#else
     100  mrb_define_const(mrb, mrbtest, "FLOAT_TOLERANCE", mrb_float_value(mrb, 1e-12));
     101#endif
     102
    97103  if (verbose) {
    98104    mrb_gv_set(mrb, mrb_intern_lit(mrb, "$mrbtest_verbose"), mrb_true_value());
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-test/init_mrbtest.c

    r321 r331  
    11#include <stdlib.h>
    2 #include "mruby.h"
    3 #include "mruby/irep.h"
    4 #include "mruby/variable.h"
     2#include <mruby.h>
     3#include <mruby/irep.h>
     4#include <mruby/variable.h>
    55
    66extern const uint8_t mrbtest_assert_irep[];
    7 extern const uint8_t mrbtest_irep[];
    87
    98void mrbgemtest_init(mrb_state* mrb);
     
    2524  mrb_init_test_driver(core_test, mrb_test(mrb_gv_get(mrb, mrb_intern_lit(mrb, "$mrbtest_verbose"))));
    2625  mrb_load_irep(core_test, mrbtest_assert_irep);
    27   mrb_load_irep(core_test, mrbtest_irep);
    2826  mrb_t_pass_result(mrb, core_test);
    2927
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-test/mrbgem.rake

    r321 r331  
    77  spec.add_dependency('mruby-compiler', :core => 'mruby-compiler')
    88
     9  spec.test_rbfiles = Dir.glob("#{MRUBY_ROOT}/test/t/*.rb")
     10
    911  clib = "#{build_dir}/mrbtest.c"
    1012  mlib = clib.ext(exts.object)
    11   mrbs = Dir.glob("#{MRUBY_ROOT}/test/t/*.rb")
    1213  exec = exefile("#{build.build_dir}/bin/mrbtest")
    1314
     
    2728
    2829  file assert_lib => assert_c
    29   file assert_c => [build.mrbcfile, assert_rb] do |t|
     30  file assert_c => assert_rb do |t|
    3031    open(t.name, 'w') do |f|
    3132      mrbc.run f, assert_rb, 'mrbtest_assert_irep'
     
    4142
    4243    file test_rbobj => g.test_rbireps
    43     file g.test_rbireps => [g.test_rbfiles].flatten + [File.join(g.dir, 'mrbgem.rake'), g.build.mrbcfile, "#{MRUBY_ROOT}/tasks/mrbgem_spec.rake"] do |t|
     44    file g.test_rbireps => [g.test_rbfiles].flatten do |t|
    4445      FileUtils.mkdir_p File.dirname(t.name)
    4546      open(t.name, 'w') do |f|
     
    146147
    147148  init = "#{spec.dir}/init_mrbtest.c"
     149
     150  # store the last gem selection and make the re-build
     151  # of the test gem depending on a change to the gem
     152  # selection
     153  active_gems = "#{build_dir}/active_gems.lst"
     154  FileUtils.mkdir_p File.dirname(active_gems)
     155  open(active_gems, 'w+') do |f|
     156    build.gems.each do |g|
     157      f.puts g.name
     158    end
     159  end
     160  file clib => active_gems
     161
    148162  file mlib => clib
    149   file clib => [build.mrbcfile, init] + mrbs do |t|
     163  file clib => init do |t|
    150164    _pp "GEN", "*.rb", "#{clib.relative_path}"
    151165    FileUtils.mkdir_p File.dirname(clib)
     
    161175      f.puts %Q[]
    162176      f.puts IO.read(init)
    163       mrbc.run f, mrbs, 'mrbtest_irep'
    164177      build.gems.each do |g|
    165178        f.puts %Q[void GENERATED_TMP_mrb_#{g.funcname}_gem_test(mrb_state *mrb);]
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-time/src/time.c

    r321 r331  
    66
    77#include <math.h>
     8#include <time.h>
     9#include <mruby.h>
     10#include <mruby/class.h>
     11#include <mruby/data.h>
     12
     13#ifndef DISABLE_STDIO
    814#include <stdio.h>
    9 #include <time.h>
    10 #include "mruby.h"
    11 #include "mruby/class.h"
    12 #include "mruby/data.h"
     15#else
     16#include <string.h>
     17#endif
     18
     19#define NDIV(x,y) (-(-((x)+1)/(y))-1)
     20
     21#if _MSC_VER < 1800
     22double round(double x) {
     23  if (x >= 0.0) {
     24    return (double)((int)(x + 0.5));
     25  }
     26  else {
     27    return (double)((int)(x - 0.5));
     28  }
     29}
     30#endif
    1331
    1432#if !defined(__MINGW64__) && defined(_WIN32)
     
    4260#endif
    4361#endif
     62
     63/* asctime(3) */
     64/* mruby usually use its own implementation of struct tm to string conversion */
     65/* except when DISABLE_STDIO is set. In that case, it uses asctime() or asctime_r(). */
     66/* By default mruby tries to use asctime_r() which is reentrant. */
     67/* Undef following macro on platforms that does not have asctime_r(). */
     68/* #define NO_ASCTIME_R */
    4469
    4570/* timegm(3) */
     
    154179};
    155180
     181#ifndef DISABLE_STDIO
    156182static const char mon_names[12][4] = {
    157183  "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
     
    161187  "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
    162188};
     189#endif
    163190
    164191struct mrb_time {
     
    174201seconds setting. Returns self on success, NULL of failure. */
    175202static struct mrb_time*
    176 mrb_time_update_datetime(struct mrb_time *self)
     203time_update_datetime(mrb_state *mrb, struct mrb_time *self)
    177204{
    178205  struct tm *aid;
     
    184211    aid = localtime_r(&self->sec, &self->datetime);
    185212  }
    186   if (!aid) return NULL;
     213  if (!aid) {
     214    mrb_raisef(mrb, E_ARGUMENT_ERROR, "%S out of Time range", mrb_float_value(mrb, (mrb_float)self->sec));
     215    /* not reached */
     216    return NULL;
     217  }
    187218#ifdef NO_GMTIME_R
    188219  self->datetime = *aid; /* copy data */
     
    198229}
    199230
     231void mrb_check_num_exact(mrb_state *mrb, mrb_float num);
    200232
    201233/* Allocates a mrb_time object and initializes it. */
     
    204236{
    205237  struct mrb_time *tm;
    206 
    207   tm = (struct mrb_time *)mrb_malloc(mrb, sizeof(struct mrb_time));
     238  time_t tsec = 0;
     239
     240  mrb_check_num_exact(mrb, (mrb_float)sec);
     241  mrb_check_num_exact(mrb, (mrb_float)usec);
     242
    208243  if (sizeof(time_t) == 4 && (sec > (double)INT32_MAX || (double)INT32_MIN > sec)) {
    209244    goto out_of_range;
     
    212247    goto out_of_range;
    213248  }
    214   tm->sec  = (time_t)sec;
    215   if ((sec > 0 && tm->sec < 0) || (sec < 0 && (double)tm->sec > sec)) {
     249  tsec  = (time_t)sec;
     250  if ((sec > 0 && tsec < 0) || (sec < 0 && (double)tsec > sec)) {
    216251  out_of_range:
    217252    mrb_raisef(mrb, E_ARGUMENT_ERROR, "%S out of Time range", mrb_float_value(mrb, sec));
    218253  }
     254  tm = (struct mrb_time *)mrb_malloc(mrb, sizeof(struct mrb_time));
     255  tm->sec  = tsec;
    219256  tm->usec = (time_t)llround((sec - tm->sec) * 1.0e6 + usec);
    220   while (tm->usec < 0) {
    221     tm->sec--;
    222     tm->usec += 1000000;
    223   }
    224   while (tm->usec >= 1000000) {
    225     tm->sec++;
    226     tm->usec -= 1000000;
     257  if (tm->usec < 0) {
     258    long sec2 = (long)NDIV(usec,1000000); /* negative div */
     259    tm->usec -= sec2 * 1000000;
     260    tm->sec += sec2;
     261  }
     262  else if (tm->usec >= 1000000) {
     263    long sec2 = (long)(usec / 1000000);
     264    tm->usec -= sec2 * 1000000;
     265    tm->sec += sec2;
    227266  }
    228267  tm->timezone = timezone;
    229   mrb_time_update_datetime(tm);
     268  time_update_datetime(mrb, tm);
    230269
    231270  return tm;
     
    279318#endif
    280319  tm->timezone = MRB_TIMEZONE_LOCAL;
    281   mrb_time_update_datetime(tm);
     320  time_update_datetime(mrb, tm);
    282321
    283322  return tm;
     
    317356  nowtime.tm_sec   = (int)asec;
    318357  nowtime.tm_isdst = -1;
     358
     359  if (nowtime.tm_mon  < 0 || nowtime.tm_mon  > 11
     360      || nowtime.tm_mday < 1 || nowtime.tm_mday > 31
     361      || nowtime.tm_hour < 0 || nowtime.tm_hour > 24
     362      || (nowtime.tm_hour == 24 && (nowtime.tm_min > 0 || nowtime.tm_sec > 0))
     363      || nowtime.tm_min  < 0 || nowtime.tm_min  > 59
     364      || nowtime.tm_sec  < 0 || nowtime.tm_sec  > 60)
     365    mrb_raise(mrb, E_RUNTIME_ERROR, "argument out of range");
     366
    319367  if (timezone == MRB_TIMEZONE_UTC) {
    320368    nowsecs = timegm(&nowtime);
     
    357405}
    358406
     407static struct mrb_time*
     408time_get_ptr(mrb_state *mrb, mrb_value time)
     409{
     410  struct mrb_time *tm;
     411
     412  tm = DATA_GET_PTR(mrb, time, &mrb_time_type, struct mrb_time);
     413  if (!tm) {
     414    mrb_raise(mrb, E_ARGUMENT_ERROR, "uninitialized time");
     415  }
     416  return tm;
     417}
    359418
    360419static mrb_value
     
    366425
    367426  mrb_get_args(mrb, "o", &other);
    368   tm1 = DATA_CHECK_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
     427  tm1 = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
    369428  tm2 = DATA_CHECK_GET_PTR(mrb, other, &mrb_time_type, struct mrb_time);
    370429  eq_p = tm1 && tm2 && tm1->sec == tm2->sec && tm1->usec == tm2->usec;
     
    380439
    381440  mrb_get_args(mrb, "o", &other);
    382   tm1 = DATA_CHECK_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
     441  tm1 = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
    383442  tm2 = DATA_CHECK_GET_PTR(mrb, other, &mrb_time_type, struct mrb_time);
    384443  if (!tm1 || !tm2) return mrb_nil_value();
     
    406465
    407466  mrb_get_args(mrb, "f", &f);
    408   tm = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
     467  tm = time_get_ptr(mrb, self);
    409468  return mrb_time_make(mrb, mrb_obj_class(mrb, self), (double)tm->sec+f, (double)tm->usec, tm->timezone);
    410469}
     
    418477
    419478  mrb_get_args(mrb, "o", &other);
    420   tm = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
    421 
     479  tm = time_get_ptr(mrb, self);
    422480  tm2 = DATA_CHECK_GET_PTR(mrb, other, &mrb_time_type, struct mrb_time);
    423481  if (tm2) {
     
    439497  struct mrb_time *tm;
    440498
    441   tm = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
     499  tm = time_get_ptr(mrb, self);
    442500  return mrb_fixnum_value(tm->datetime.tm_wday);
    443501}
     
    450508  struct mrb_time *tm;
    451509
    452   tm = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
     510  tm = time_get_ptr(mrb, self);
    453511  return mrb_fixnum_value(tm->datetime.tm_yday + 1);
    454512}
     
    461519  struct mrb_time *tm;
    462520
    463   tm = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
     521  tm = time_get_ptr(mrb, self);
    464522  return mrb_fixnum_value(tm->datetime.tm_year + 1900);
    465523}
     
    472530  struct mrb_time *tm;
    473531
    474   tm = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
     532  tm = time_get_ptr(mrb, self);
    475533  if (tm->timezone <= MRB_TIMEZONE_NONE) return mrb_nil_value();
    476534  if (tm->timezone >= MRB_TIMEZONE_LAST) return mrb_nil_value();
     
    485543mrb_time_asctime(mrb_state *mrb, mrb_value self)
    486544{
    487   struct mrb_time *tm;
    488   struct tm *d;
     545  struct mrb_time *tm = time_get_ptr(mrb, self);
     546  struct tm *d = &tm->datetime;
     547  int len;
     548
     549#if defined(DISABLE_STDIO)
     550  char *s;
     551# ifdef NO_ASCTIME_R
     552  s = asctime(d);
     553# else
     554  char buf[32];
     555  s = asctime_r(d, buf);
     556# endif
     557  len = strlen(s)-1;            /* truncate the last newline */
     558#else
    489559  char buf[256];
    490   int len;
    491 
    492   tm = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
    493   d = &tm->datetime;
     560
    494561  len = snprintf(buf, sizeof(buf), "%s %s %02d %02d:%02d:%02d %s%d",
    495562    wday_names[d->tm_wday], mon_names[d->tm_mon], d->tm_mday,
     
    497564    tm->timezone == MRB_TIMEZONE_UTC ? "UTC " : "",
    498565    d->tm_year + 1900);
     566#endif
    499567  return mrb_str_new(mrb, buf, len);
    500568}
     
    507575  struct mrb_time *tm;
    508576
    509   tm = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
    510   if (!tm) return mrb_nil_value();
     577  tm = time_get_ptr(mrb, self);
    511578  return mrb_fixnum_value(tm->datetime.tm_mday);
    512579}
     
    520587  struct mrb_time *tm;
    521588
    522   tm = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
     589  tm = time_get_ptr(mrb, self);
    523590  return mrb_bool_value(tm->datetime.tm_isdst);
    524591}
     
    532599  struct mrb_time *tm, *tm2;
    533600
    534   tm = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
     601  tm = time_get_ptr(mrb, self);
    535602  tm2 = (struct mrb_time *)mrb_malloc(mrb, sizeof(*tm));
    536603  *tm2 = *tm;
    537604  tm2->timezone = MRB_TIMEZONE_UTC;
    538   mrb_time_update_datetime(tm2);
     605  time_update_datetime(mrb, tm2);
    539606  return mrb_time_wrap(mrb, mrb_obj_class(mrb, self), tm2);
    540607}
     
    547614  struct mrb_time *tm, *tm2;
    548615
    549   tm = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
     616  tm = time_get_ptr(mrb, self);
    550617  tm2 = (struct mrb_time *)mrb_malloc(mrb, sizeof(*tm));
    551618  *tm2 = *tm;
    552619  tm2->timezone = MRB_TIMEZONE_LOCAL;
    553   mrb_time_update_datetime(tm2);
     620  time_update_datetime(mrb, tm2);
    554621  return mrb_time_wrap(mrb, mrb_obj_class(mrb, self), tm2);
    555622}
     
    562629  struct mrb_time *tm;
    563630
    564   tm = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
     631  tm = time_get_ptr(mrb, self);
    565632  return mrb_fixnum_value(tm->datetime.tm_hour);
    566633}
     
    576643  struct mrb_time *tm;
    577644
     645  n = mrb_get_args(mrb, "|iiiiiii",
     646       &ayear, &amonth, &aday, &ahour, &amin, &asec, &ausec);
    578647  tm = (struct mrb_time*)DATA_PTR(self);
    579648  if (tm) {
     
    582651  mrb_data_init(self, NULL, &mrb_time_type);
    583652
    584   n = mrb_get_args(mrb, "|iiiiiii",
    585        &ayear, &amonth, &aday, &ahour, &amin, &asec, &ausec);
    586653  if (n == 0) {
    587654    tm = current_mrb_time(mrb);
     
    600667{
    601668  mrb_value src;
     669  struct mrb_time *t1, *t2;
    602670
    603671  mrb_get_args(mrb, "o", &src);
     
    606674    mrb_raise(mrb, E_TYPE_ERROR, "wrong argument class");
    607675  }
    608   if (!DATA_PTR(copy)) {
    609     mrb_data_init(copy, mrb_malloc(mrb, sizeof(struct mrb_time)), &mrb_time_type);
    610   }
    611   *(struct mrb_time *)DATA_PTR(copy) = *(struct mrb_time *)DATA_PTR(src);
     676  t1 = (struct mrb_time *)DATA_PTR(copy);
     677  t2 = (struct mrb_time *)DATA_PTR(src);
     678  if (!t2) {
     679    mrb_raise(mrb, E_ARGUMENT_ERROR, "uninitialized time");
     680  }
     681  if (!t1) {
     682    t1 = (struct mrb_time *)mrb_malloc(mrb, sizeof(struct mrb_time));
     683    mrb_data_init(copy, t1, &mrb_time_type);
     684  }
     685  *t1 = *t2;
    612686  return copy;
    613687}
     
    620694  struct mrb_time *tm;
    621695
    622   tm = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
     696  tm = time_get_ptr(mrb, self);
    623697  tm->timezone = MRB_TIMEZONE_LOCAL;
    624   mrb_time_update_datetime(tm);
     698  time_update_datetime(mrb, tm);
    625699  return self;
    626700}
     
    633707  struct mrb_time *tm;
    634708
    635   tm = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
     709  tm = time_get_ptr(mrb, self);
    636710  return mrb_fixnum_value(tm->datetime.tm_mday);
    637711}
     
    644718  struct mrb_time *tm;
    645719
    646   tm = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
     720  tm = time_get_ptr(mrb, self);
    647721  return mrb_fixnum_value(tm->datetime.tm_min);
    648722}
     
    655729  struct mrb_time *tm;
    656730
    657   tm = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
     731  tm = time_get_ptr(mrb, self);
    658732  return mrb_fixnum_value(tm->datetime.tm_mon + 1);
    659733}
     
    666740  struct mrb_time *tm;
    667741
    668   tm = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
     742  tm = time_get_ptr(mrb, self);
    669743  return mrb_fixnum_value(tm->datetime.tm_sec);
    670744}
     
    678752  struct mrb_time *tm;
    679753
    680   tm = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
     754  tm = time_get_ptr(mrb, self);
    681755  return mrb_float_value(mrb, (mrb_float)tm->sec + (mrb_float)tm->usec/1.0e6);
    682756}
     
    689763  struct mrb_time *tm;
    690764
    691   tm = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
     765  tm = time_get_ptr(mrb, self);
    692766  if (tm->sec > MRB_INT_MAX || tm->sec < MRB_INT_MIN) {
    693767    return mrb_float_value(mrb, (mrb_float)tm->sec);
     
    703777  struct mrb_time *tm;
    704778
    705   tm = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
     779  tm = time_get_ptr(mrb, self);
    706780  if (tm->usec > MRB_INT_MAX || tm->usec < MRB_INT_MIN) {
    707781    return mrb_float_value(mrb, (mrb_float)tm->usec);
     
    717791  struct mrb_time *tm;
    718792
    719   tm = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
     793  tm = time_get_ptr(mrb, self);
    720794  tm->timezone = MRB_TIMEZONE_UTC;
    721   mrb_time_update_datetime(tm);
     795  time_update_datetime(mrb, tm);
    722796  return self;
    723797}
     
    730804  struct mrb_time *tm;
    731805
    732   tm = DATA_GET_PTR(mrb, self, &mrb_time_type, struct mrb_time);
     806  tm = time_get_ptr(mrb, self);
    733807  return mrb_bool_value(tm->timezone == MRB_TIMEZONE_UTC);
    734808}
  • EcnlProtoTool/trunk/mruby-1.3.0/mrbgems/mruby-time/test/time.rb

    r321 r331  
    1111
    1212assert('Time.at', '15.2.19.6.1') do
    13   Time.at(1300000000.0)
     13  assert_kind_of(Time, Time.at(1300000000.0))
     14
     15  assert_raise(FloatDomainError) { Time.at(Float::NAN) }
     16  assert_raise(FloatDomainError) { Time.at(Float::INFINITY) }
     17  assert_raise(FloatDomainError) { Time.at(-Float::INFINITY) }
     18  assert_raise(FloatDomainError) { Time.at(0, Float::NAN) }
     19  assert_raise(FloatDomainError) { Time.at(0, Float::INFINITY) }
     20  assert_raise(FloatDomainError) { Time.at(0, -Float::INFINITY) }
    1421end
    1522
     
    3845  t2 = t1.+(60)
    3946
    40   t2.utc.asctime == "Sun Mar 13 07:07:40 UTC 2011"
     47  assert_equal(t2.utc.asctime, "Sun Mar 13 07:07:40 UTC 2011")
     48
     49  assert_raise(FloatDomainError) { Time.at(0) + Float::NAN }
     50  assert_raise(FloatDomainError) { Time.at(0) + Float::INFINITY }
     51  assert_raise(FloatDomainError) { Time.at(0) + -Float::INFINITY }
    4152end
    4253
     
    4556  t2 = t1.-(60)
    4657
    47   t2.utc.asctime == "Sun Mar 13 07:05:40 UTC 2011"
     58  assert_equal(t2.utc.asctime, "Sun Mar 13 07:05:40 UTC 2011")
     59
     60  assert_raise(FloatDomainError) { Time.at(0) - Float::NAN }
     61  assert_raise(FloatDomainError) { Time.at(0) - Float::INFINITY }
     62  assert_raise(FloatDomainError) { Time.at(0) - -Float::INFINITY }
    4863end
    4964
Note: See TracChangeset for help on using the changeset viewer.