From 5b21e94bebed90180d8ff63dad03b8b948361089 Mon Sep 17 00:00:00 2001 From: Takashi Kokubun Date: Thu, 21 Jul 2022 09:23:58 -0700 Subject: [PATCH] Expand tabs [ci skip] [Misc #18891] --- array.c | 1858 ++--- bignum.c | 1106 +-- class.c | 528 +- compar.c | 14 +- compile.c | 6342 ++++++++--------- complex.c | 648 +- debug.c | 118 +- debug_counter.c | 10 +- dir.c | 1694 ++--- dln.c | 150 +- dln_find.c | 234 +- dmyenc.c | 2 +- encoding.c | 356 +- enum.c | 604 +- enumerator.c | 438 +- error.c | 678 +- eval.c | 684 +- eval_error.c | 354 +- eval_intern.h | 6 +- eval_jump.c | 36 +- ext/-test-/debug/inspector.c | 14 +- ext/-test-/debug/profile_frames.c | 24 +- ext/-test-/file/fs.c | 14 +- ext/-test-/funcall/funcall.c | 12 +- .../gvl/call_without_gvl/call_without_gvl.c | 2 +- ext/-test-/memory_status/memory_status.c | 12 +- ext/-test-/printf/printf.c | 64 +- ext/-test-/proc/super.c | 2 +- ext/-test-/st/foreach/foreach.c | 96 +- ext/-test-/st/numhash/numhash.c | 16 +- ext/-test-/st/update/update.c | 12 +- ext/-test-/string/coderange.c | 8 +- ext/-test-/string/cstr.c | 16 +- ext/-test-/string/qsort.c | 14 +- ext/-test-/struct/member.c | 2 +- ext/-test-/symbol/type.c | 6 +- ext/-test-/tracepoint/gc_hook.c | 26 +- ext/-test-/tracepoint/tracepoint.c | 54 +- ext/-test-/typeddata/typeddata.c | 2 +- ext/-test-/vm/at_exit.c | 12 +- ext/-test-/win32/console/attribute.c | 18 +- ext/-test-/win32/fd_setsize/fd_setsize.c | 10 +- ext/cgi/escape/escape.c | 290 +- ext/coverage/coverage.c | 158 +- ext/digest/bubblebabble/bubblebabble.c | 2 +- ext/digest/digest.c | 12 +- ext/digest/digest.h | 2 +- ext/digest/md5/md5.c | 118 +- ext/digest/md5/md5.h | 4 +- ext/digest/rmd160/rmd160.c | 480 +- ext/digest/rmd160/rmd160.h | 8 +- ext/digest/sha1/sha1.c | 26 +- ext/digest/sha1/sha1.h | 6 +- ext/digest/sha2/sha2.c | 1274 ++-- ext/digest/sha2/sha2.h | 12 +- ext/digest/sha2/sha2init.c | 2 +- ext/io/nonblock/nonblock.c | 28 +- ext/io/wait/wait.c | 46 +- ext/nkf/nkf.c | 78 +- ext/objspace/object_tracing.c | 156 +- ext/objspace/objspace.c | 340 +- ext/objspace/objspace_dump.c | 56 +- ext/pathname/pathname.c | 2 +- ext/pty/pty.c | 134 +- ext/readline/readline.c | 4 +- ext/socket/addrinfo.h | 36 +- ext/socket/ancdata.c | 258 +- ext/socket/basicsocket.c | 74 +- ext/socket/constants.c | 6 +- ext/socket/getaddrinfo.c | 840 +-- ext/socket/getnameinfo.c | 212 +- ext/socket/ifaddr.c | 8 +- ext/socket/init.c | 148 +- ext/socket/ipsocket.c | 184 +- ext/socket/option.c | 86 +- ext/socket/raddrinfo.c | 230 +- ext/socket/rubysocket.h | 12 +- ext/socket/socket.c | 446 +- ext/socket/sockssocket.c | 4 +- ext/socket/tcpserver.c | 2 +- ext/socket/tcpsocket.c | 18 +- ext/socket/udpsocket.c | 28 +- ext/socket/unixserver.c | 4 +- ext/socket/unixsocket.c | 140 +- ext/syslog/syslog.c | 22 +- ext/win32/resolv/resolv.c | 18 +- ext/win32ole/win32ole.c | 168 +- ext/win32ole/win32ole_event.c | 18 +- ext/win32ole/win32ole_typelib.c | 16 +- file.c | 2110 +++--- gc.c | 3314 ++++----- gc.h | 16 +- goruby.c | 32 +- hash.c | 540 +- id_table.c | 134 +- include/ruby/ruby.h | 38 +- include/ruby/thread.h | 4 +- include/ruby/util.h | 2 +- include/ruby/win32.h | 8 +- insns.def | 106 +- io.c | 3592 +++++----- iseq.c | 1482 ++-- iseq.h | 38 +- load.c | 598 +- localeinit.c | 10 +- marshal.c | 1572 ++-- math.c | 68 +- memory_view.c | 12 +- mjit_instruction.rb | 1034 +++ node.c | 1412 ++-- node.h | 30 +- numeric.c | 1586 ++--- object.c | 686 +- pack.c | 2066 +++--- probes_helper.h | 14 +- proc.c | 722 +- process.c | 1476 ++-- ractor.c | 4 +- random.c | 480 +- range.c | 554 +- rational.c | 726 +- re.c | 1264 ++-- ruby-runner.c | 56 +- ruby.c | 1770 ++--- rubystub.c | 28 +- signal.c | 494 +- siphash.c | 84 +- sprintf.c | 1244 ++-- st.c | 630 +- string.c | 5630 +++++++-------- struct.c | 356 +- symbol.c | 332 +- symbol.h | 20 +- template/prelude.c.tmpl | 38 +- thread.c | 1024 +-- thread_pthread.c | 350 +- thread_sync.c | 72 +- thread_win32.c | 202 +- time.c | 528 +- tool/ruby_vm/views/optinsn.inc.erb | 4 +- transcode.c | 512 +- transcode_data.h | 32 +- util.c | 166 +- variable.c | 676 +- vm.c | 1112 +-- vm_args.c | 516 +- vm_backtrace.c | 380 +- vm_core.h | 238 +- vm_dump.c | 952 +-- vm_eval.c | 626 +- vm_exec.c | 22 +- vm_insnhelper.c | 1854 ++--- vm_insnhelper.h | 4 +- vm_method.c | 818 +-- vm_trace.c | 414 +- win32/file.c | 542 +- win32/file.h | 32 +- win32/win32.c | 5536 +++++++------- 158 files changed, 38285 insertions(+), 37251 deletions(-) create mode 100644 mjit_instruction.rb diff --git a/array.c b/array.c index 0891e3ba00..54d928a992 100644 --- a/array.c +++ b/array.c @@ -93,7 +93,7 @@ should_be_T_ARRAY(VALUE ary) #define ARY_EMBED_LEN(a) \ (assert(ARY_EMBED_P(a)), \ (long)((RBASIC(a)->flags >> RARRAY_EMBED_LEN_SHIFT) & \ - (RARRAY_EMBED_LEN_MASK >> RARRAY_EMBED_LEN_SHIFT))) + (RARRAY_EMBED_LEN_MASK >> RARRAY_EMBED_LEN_SHIFT))) #define ARY_HEAP_SIZE(a) (assert(!ARY_EMBED_P(a)), assert(ARY_OWNS_HEAP_P(a)), ARY_CAPA(a) * sizeof(VALUE)) #define ARY_OWNS_HEAP_P(a) (assert(should_be_T_ARRAY((VALUE)(a))), \ @@ -322,7 +322,7 @@ void rb_mem_clear(VALUE *mem, long size) { while (size--) { - *mem++ = Qnil; + *mem++ = Qnil; } } @@ -330,7 +330,7 @@ static void ary_mem_clear(VALUE ary, long beg, long size) { RARRAY_PTR_USE_TRANSIENT(ary, ptr, { - rb_mem_clear(ptr + beg, size); + rb_mem_clear(ptr + beg, size); }); } @@ -338,7 +338,7 @@ static inline void memfill(register VALUE *mem, register long size, register VALUE val) { while (size--) { - *mem++ = val; + *mem++ = val; } } @@ -346,8 +346,8 @@ static void ary_memfill(VALUE ary, long beg, long size, VALUE val) { RARRAY_PTR_USE_TRANSIENT(ary, ptr, { - memfill(ptr + beg, size, val); - RB_OBJ_WRITTEN(ary, Qundef, val); + memfill(ptr + beg, size, val); + RB_OBJ_WRITTEN(ary, Qundef, val); }); } @@ -577,10 +577,10 @@ ary_double_capa(VALUE ary, long min) long new_capa = ARY_CAPA(ary) / 2; if (new_capa < ARY_DEFAULT_SIZE) { - new_capa = ARY_DEFAULT_SIZE; + new_capa = ARY_DEFAULT_SIZE; } if (new_capa >= ARY_MAX_SIZE - min) { - new_capa = (ARY_MAX_SIZE - min) / 2; + new_capa = (ARY_MAX_SIZE - min) / 2; } new_capa += min; ary_resize_capa(ary, new_capa); @@ -702,40 +702,40 @@ ary_ensure_room_for_push(VALUE ary, long add_len) long capa; if (old_len > ARY_MAX_SIZE - add_len) { - rb_raise(rb_eIndexError, "index %ld too big", new_len); + rb_raise(rb_eIndexError, "index %ld too big", new_len); } if (ARY_SHARED_P(ary)) { - if (new_len > ary_embed_capa(ary)) { + if (new_len > ary_embed_capa(ary)) { VALUE shared_root = ARY_SHARED_ROOT(ary); if (ARY_SHARED_ROOT_OCCUPIED(shared_root)) { if (ARY_HEAP_PTR(ary) - RARRAY_CONST_PTR_TRANSIENT(shared_root) + new_len <= RARRAY_LEN(shared_root)) { - rb_ary_modify_check(ary); + rb_ary_modify_check(ary); ary_verify(ary); ary_verify(shared_root); return shared_root; - } - else { - /* if array is shared, then it is likely it participate in push/shift pattern */ - rb_ary_modify(ary); - capa = ARY_CAPA(ary); - if (new_len > capa - (capa >> 6)) { - ary_double_capa(ary, new_len); - } + } + else { + /* if array is shared, then it is likely it participate in push/shift pattern */ + rb_ary_modify(ary); + capa = ARY_CAPA(ary); + if (new_len > capa - (capa >> 6)) { + ary_double_capa(ary, new_len); + } ary_verify(ary); - return ary; - } - } - } + return ary; + } + } + } ary_verify(ary); rb_ary_modify(ary); } else { - rb_ary_modify_check(ary); + rb_ary_modify_check(ary); } capa = ARY_CAPA(ary); if (new_len > capa) { - ary_double_capa(ary, new_len); + ary_double_capa(ary, new_len); } ary_verify(ary); @@ -821,10 +821,10 @@ ary_new(VALUE klass, long capa) VALUE ary,*ptr; if (capa < 0) { - rb_raise(rb_eArgError, "negative array size (or size too big)"); + rb_raise(rb_eArgError, "negative array size (or size too big)"); } if (capa > ARY_MAX_SIZE) { - rb_raise(rb_eArgError, "array size too big"); + rb_raise(rb_eArgError, "array size too big"); } RUBY_DTRACE_CREATE_HOOK(ARRAY, capa); @@ -868,7 +868,7 @@ VALUE va_start(ar, n); for (i=0; i 0 && elts) { - ary_memcpy(ary, 0, n, elts); - ARY_SET_LEN(ary, n); + ary_memcpy(ary, 0, n, elts); + ARY_SET_LEN(ary, n); } return ary; @@ -929,10 +929,10 @@ ec_ary_new(rb_execution_context_t *ec, VALUE klass, long capa) VALUE ary,*ptr; if (capa < 0) { - rb_raise(rb_eArgError, "negative array size (or size too big)"); + rb_raise(rb_eArgError, "negative array size (or size too big)"); } if (capa > ARY_MAX_SIZE) { - rb_raise(rb_eArgError, "array size too big"); + rb_raise(rb_eArgError, "array size too big"); } RUBY_DTRACE_CREATE_HOOK(ARRAY, capa); @@ -960,8 +960,8 @@ rb_ec_ary_new_from_values(rb_execution_context_t *ec, long n, const VALUE *elts) ary = ec_ary_new(ec, rb_cArray, n); if (n > 0 && elts) { - ary_memcpy(ary, 0, n, elts); - ARY_SET_LEN(ary, n); + ary_memcpy(ary, 0, n, elts); + ARY_SET_LEN(ary, n); } return ary; @@ -1028,10 +1028,10 @@ RUBY_FUNC_EXPORTED size_t rb_ary_memsize(VALUE ary) { if (ARY_OWNS_HEAP_P(ary)) { - return ARY_CAPA(ary) * sizeof(VALUE); + return ARY_CAPA(ary) * sizeof(VALUE); } else { - return 0; + return 0; } } @@ -1054,17 +1054,17 @@ ary_make_shared(VALUE ary) return ARY_SHARED_ROOT(ary); } else if (ARY_SHARED_ROOT_P(ary)) { - return ary; + return ary; } else if (OBJ_FROZEN(ary)) { rb_ary_transient_heap_evacuate(ary, TRUE); ary_shrink_capa(ary); FL_SET_SHARED_ROOT(ary); ARY_SET_SHARED_ROOT_REFCNT(ary, 1); - return ary; + return ary; } else { - long capa = ARY_CAPA(ary), len = RARRAY_LEN(ary); + long capa = ARY_CAPA(ary), len = RARRAY_LEN(ary); const VALUE *ptr; VALUE shared = ary_alloc_heap(0); @@ -1241,45 +1241,45 @@ rb_ary_initialize(int argc, VALUE *argv, VALUE ary) rb_ary_reset(ary); assert(ARY_EMBED_P(ary)); assert(ARY_EMBED_LEN(ary) == 0); - if (rb_block_given_p()) { - rb_warning("given block not used"); - } - return ary; + if (rb_block_given_p()) { + rb_warning("given block not used"); + } + return ary; } rb_scan_args(argc, argv, "02", &size, &val); if (argc == 1 && !FIXNUM_P(size)) { - val = rb_check_array_type(size); - if (!NIL_P(val)) { - rb_ary_replace(ary, val); - return ary; - } + val = rb_check_array_type(size); + if (!NIL_P(val)) { + rb_ary_replace(ary, val); + return ary; + } } len = NUM2LONG(size); /* NUM2LONG() may call size.to_int, ary can be frozen, modified, etc */ if (len < 0) { - rb_raise(rb_eArgError, "negative array size"); + rb_raise(rb_eArgError, "negative array size"); } if (len > ARY_MAX_SIZE) { - rb_raise(rb_eArgError, "array size too big"); + rb_raise(rb_eArgError, "array size too big"); } /* recheck after argument conversion */ rb_ary_modify(ary); ary_resize_capa(ary, len); if (rb_block_given_p()) { - long i; + long i; - if (argc == 2) { - rb_warn("block supersedes default value argument"); - } - for (i=0; i= ARY_MAX_SIZE) { - rb_raise(rb_eIndexError, "index %ld too big", idx); + rb_raise(rb_eIndexError, "index %ld too big", idx); } rb_ary_modify(ary); if (idx >= ARY_CAPA(ary)) { - ary_double_capa(ary, idx); + ary_double_capa(ary, idx); } if (idx > len) { - ary_mem_clear(ary, len, idx - len + 1); + ary_mem_clear(ary, len, idx - len + 1); } if (idx >= len) { - ARY_SET_LEN(ary, idx + 1); + ARY_SET_LEN(ary, idx + 1); } ARY_SET(ary, idx, val); } @@ -1441,13 +1441,13 @@ ary_take_first_or_last(int argc, const VALUE *argv, VALUE ary, enum ary_take_pos n = NUM2LONG(argv[0]); len = RARRAY_LEN(ary); if (n > len) { - n = len; + n = len; } else if (n < 0) { - rb_raise(rb_eArgError, "negative array size"); + rb_raise(rb_eArgError, "negative array size"); } if (last) { - offset = len - n; + offset = len - n; } return ary_make_partial(ary, rb_cArray, offset, n); } @@ -1475,7 +1475,7 @@ rb_ary_push(VALUE ary, VALUE item) long idx = RARRAY_LEN((ary_verify(ary), ary)); VALUE target_ary = ary_ensure_room_for_push(ary, 1); RARRAY_PTR_USE_TRANSIENT(ary, ptr, { - RB_OBJ_WRITE(target_ary, &ptr[idx], item); + RB_OBJ_WRITE(target_ary, &ptr[idx], item); }); ARY_SET_LEN(ary, idx + 1); ary_verify(ary); @@ -1528,10 +1528,10 @@ rb_ary_pop(VALUE ary) n = RARRAY_LEN(ary); if (n == 0) return Qnil; if (ARY_OWNS_HEAP_P(ary) && - n * 3 < ARY_CAPA(ary) && - ARY_CAPA(ary) > ARY_DEFAULT_SIZE) + n * 3 < ARY_CAPA(ary) && + ARY_CAPA(ary) > ARY_DEFAULT_SIZE) { - ary_resize_capa(ary, n * 2); + ary_resize_capa(ary, n * 2); } --n; ARY_SET_LEN(ary, n); @@ -1576,7 +1576,7 @@ rb_ary_pop_m(int argc, VALUE *argv, VALUE ary) VALUE result; if (argc == 0) { - return rb_ary_pop(ary); + return rb_ary_pop(ary); } rb_ary_modify_check(ary); @@ -1644,7 +1644,7 @@ rb_ary_shift_m(int argc, VALUE *argv, VALUE ary) long n; if (argc == 0) { - return rb_ary_shift(ary); + return rb_ary_shift(ary); } rb_ary_modify_check(ary); @@ -1716,7 +1716,7 @@ ary_modify_for_unshift(VALUE ary, int argc) rb_ary_modify(ary); capa = ARY_CAPA(ary); if (capa - (capa >> 6) <= new_len) { - ary_double_capa(ary, new_len); + ary_double_capa(ary, new_len); } /* use shared array for big "queues" */ @@ -1724,20 +1724,20 @@ ary_modify_for_unshift(VALUE ary, int argc) ary_verify(ary); /* make a room for unshifted items */ - capa = ARY_CAPA(ary); - ary_make_shared(ary); + capa = ARY_CAPA(ary); + ary_make_shared(ary); head = sharedp = RARRAY_CONST_PTR_TRANSIENT(ary); return make_room_for_unshift(ary, head, (void *)sharedp, argc, capa, len); } else { - /* sliding items */ + /* sliding items */ RARRAY_PTR_USE_TRANSIENT(ary, ptr, { - MEMMOVE(ptr + argc, ptr, VALUE, len); - }); + MEMMOVE(ptr + argc, ptr, VALUE, len); + }); ary_verify(ary); - return ary; + return ary; } } @@ -1794,8 +1794,8 @@ rb_ary_unshift_m(int argc, VALUE *argv, VALUE ary) VALUE target_ary; if (argc == 0) { - rb_ary_modify_check(ary); - return ary; + rb_ary_modify_check(ary); + return ary; } target_ary = ary_ensure_room_for_unshift(ary, argc); @@ -1817,7 +1817,7 @@ rb_ary_elt(VALUE ary, long offset) long len = RARRAY_LEN(ary); if (len == 0) return Qnil; if (offset < 0 || len <= offset) { - return Qnil; + return Qnil; } return RARRAY_AREF(ary, offset); } @@ -1838,7 +1838,7 @@ rb_ary_subseq_step(VALUE ary, long beg, long len, long step) if (beg < 0 || len < 0) return Qnil; if (alen < len || alen < beg + len) { - len = alen - beg; + len = alen - beg; } klass = rb_cArray; if (len == 0) return ary_new(klass, 0); @@ -1968,7 +1968,7 @@ rb_ary_aref(int argc, const VALUE *argv, VALUE ary) { rb_check_arity(argc, 1, 2); if (argc == 2) { - return rb_ary_aref2(ary, argv[0], argv[1]); + return rb_ary_aref2(ary, argv[0], argv[1]); } return rb_ary_aref1(ary, argv[0]); } @@ -1979,7 +1979,7 @@ rb_ary_aref2(VALUE ary, VALUE b, VALUE e) long beg = NUM2LONG(b); long len = NUM2LONG(e); if (beg < 0) { - beg += RARRAY_LEN(ary); + beg += RARRAY_LEN(ary); } return rb_ary_subseq(ary, beg, len); } @@ -1991,7 +1991,7 @@ rb_ary_aref1(VALUE ary, VALUE arg) /* special case - speeding up */ if (FIXNUM_P(arg)) { - return rb_ary_entry(ary, FIX2LONG(arg)); + return rb_ary_entry(ary, FIX2LONG(arg)); } /* check if idx is Range or ArithmeticSequence */ switch (rb_arithmetic_sequence_beg_len_step(arg, &beg, &len, &step, RARRAY_LEN(ary), 0)) { @@ -2060,11 +2060,11 @@ static VALUE rb_ary_first(int argc, VALUE *argv, VALUE ary) { if (argc == 0) { - if (RARRAY_LEN(ary) == 0) return Qnil; - return RARRAY_AREF(ary, 0); + if (RARRAY_LEN(ary) == 0) return Qnil; + return RARRAY_AREF(ary, 0); } else { - return ary_take_first_or_last(argc, argv, ary, ARY_TAKE_FIRST); + return ary_take_first_or_last(argc, argv, ary, ARY_TAKE_FIRST); } } @@ -2106,12 +2106,12 @@ VALUE rb_ary_last(int argc, const VALUE *argv, VALUE ary) { if (argc == 0) { - long len = RARRAY_LEN(ary); - if (len == 0) return Qnil; - return RARRAY_AREF(ary, len-1); + long len = RARRAY_LEN(ary); + if (len == 0) return Qnil; + return RARRAY_AREF(ary, len-1); } else { - return ary_take_first_or_last(argc, argv, ary, ARY_TAKE_LAST); + return ary_take_first_or_last(argc, argv, ary, ARY_TAKE_LAST); } } @@ -2162,20 +2162,20 @@ rb_ary_fetch(int argc, VALUE *argv, VALUE ary) rb_scan_args(argc, argv, "11", &pos, &ifnone); block_given = rb_block_given_p(); if (block_given && argc == 2) { - rb_warn("block supersedes default value argument"); + rb_warn("block supersedes default value argument"); } idx = NUM2LONG(pos); if (idx < 0) { - idx += RARRAY_LEN(ary); + idx += RARRAY_LEN(ary); } if (idx < 0 || RARRAY_LEN(ary) <= idx) { - if (block_given) return rb_yield(pos); - if (argc == 1) { - rb_raise(rb_eIndexError, "index %ld outside of array bounds: %ld...%ld", - idx - (idx < 0 ? RARRAY_LEN(ary) : 0), -RARRAY_LEN(ary), RARRAY_LEN(ary)); - } - return ifnone; + if (block_given) return rb_yield(pos); + if (argc == 1) { + rb_raise(rb_eIndexError, "index %ld outside of array bounds: %ld...%ld", + idx - (idx < 0 ? RARRAY_LEN(ary) : 0), -RARRAY_LEN(ary), RARRAY_LEN(ary)); + } + return ifnone; } return RARRAY_AREF(ary, idx); } @@ -2225,23 +2225,23 @@ rb_ary_index(int argc, VALUE *argv, VALUE ary) long i; if (argc == 0) { - RETURN_ENUMERATOR(ary, 0, 0); - for (i=0; i (len = RARRAY_LEN(ary))) { - i = len; - } - } - return Qnil; + RETURN_ENUMERATOR(ary, 0, 0); + while (i--) { + if (RTEST(rb_yield(RARRAY_AREF(ary, i)))) + return LONG2NUM(i); + if (i > (len = RARRAY_LEN(ary))) { + i = len; + } + } + return Qnil; } rb_check_arity(argc, 0, 1); val = argv[0]; if (rb_block_given_p()) - rb_warn("given block not used"); + rb_warn("given block not used"); while (i--) { - VALUE e = RARRAY_AREF(ary, i); - if (rb_equal(e, val)) { - return LONG2NUM(i); - } + VALUE e = RARRAY_AREF(ary, i); + if (rb_equal(e, val)) { + return LONG2NUM(i); + } if (i > RARRAY_LEN(ary)) { break; } @@ -2330,54 +2330,54 @@ rb_ary_splice(VALUE ary, long beg, long len, const VALUE *rptr, long rlen) if (len < 0) rb_raise(rb_eIndexError, "negative length (%ld)", len); olen = RARRAY_LEN(ary); if (beg < 0) { - beg += olen; - if (beg < 0) { - rb_raise(rb_eIndexError, "index %ld too small for array; minimum: %ld", - beg - olen, -olen); - } + beg += olen; + if (beg < 0) { + rb_raise(rb_eIndexError, "index %ld too small for array; minimum: %ld", + beg - olen, -olen); + } } if (olen < len || olen < beg + len) { - len = olen - beg; + len = olen - beg; } { const VALUE *optr = RARRAY_CONST_PTR_TRANSIENT(ary); - rofs = (rptr >= optr && rptr < optr + olen) ? rptr - optr : -1; + rofs = (rptr >= optr && rptr < optr + olen) ? rptr - optr : -1; } if (beg >= olen) { - VALUE target_ary; - if (beg > ARY_MAX_SIZE - rlen) { - rb_raise(rb_eIndexError, "index %ld too big", beg); - } - target_ary = ary_ensure_room_for_push(ary, rlen-len); /* len is 0 or negative */ - len = beg + rlen; - ary_mem_clear(ary, olen, beg - olen); - if (rlen > 0) { + VALUE target_ary; + if (beg > ARY_MAX_SIZE - rlen) { + rb_raise(rb_eIndexError, "index %ld too big", beg); + } + target_ary = ary_ensure_room_for_push(ary, rlen-len); /* len is 0 or negative */ + len = beg + rlen; + ary_mem_clear(ary, olen, beg - olen); + if (rlen > 0) { if (rofs != -1) rptr = RARRAY_CONST_PTR_TRANSIENT(ary) + rofs; - ary_memcpy0(ary, beg, rlen, rptr, target_ary); - } - ARY_SET_LEN(ary, len); + ary_memcpy0(ary, beg, rlen, rptr, target_ary); + } + ARY_SET_LEN(ary, len); } else { - long alen; + long alen; - if (olen - len > ARY_MAX_SIZE - rlen) { - rb_raise(rb_eIndexError, "index %ld too big", olen + rlen - len); - } - rb_ary_modify(ary); - alen = olen + rlen - len; - if (alen >= ARY_CAPA(ary)) { - ary_double_capa(ary, alen); - } + if (olen - len > ARY_MAX_SIZE - rlen) { + rb_raise(rb_eIndexError, "index %ld too big", olen + rlen - len); + } + rb_ary_modify(ary); + alen = olen + rlen - len; + if (alen >= ARY_CAPA(ary)) { + ary_double_capa(ary, alen); + } - if (len != rlen) { + if (len != rlen) { RARRAY_PTR_USE_TRANSIENT(ary, ptr, MEMMOVE(ptr + beg + rlen, ptr + beg + len, VALUE, olen - (beg + len))); - ARY_SET_LEN(ary, alen); - } - if (rlen > 0) { + ARY_SET_LEN(ary, alen); + } + if (rlen > 0) { if (rofs != -1) rptr = RARRAY_CONST_PTR_TRANSIENT(ary) + rofs; /* give up wb-protected ary */ RB_OBJ_WB_UNPROTECT_FOR(ARRAY, ary); @@ -2387,7 +2387,7 @@ rb_ary_splice(VALUE ary, long beg, long len, const VALUE *rptr, long rlen) */ RARRAY_PTR_USE_TRANSIENT(ary, ptr, MEMMOVE(ptr + beg, rptr, VALUE, rlen)); - } + } } } @@ -2398,10 +2398,10 @@ rb_ary_set_len(VALUE ary, long len) rb_ary_modify_check(ary); if (ARY_SHARED_P(ary)) { - rb_raise(rb_eRuntimeError, "can't set length of shared "); + rb_raise(rb_eRuntimeError, "can't set length of shared "); } if (len > (capa = (long)ARY_CAPA(ary))) { - rb_bug("probable buffer overflow: %ld for %ld", len, capa); + rb_bug("probable buffer overflow: %ld for %ld", len, capa); } ARY_SET_LEN(ary, len); } @@ -2415,14 +2415,14 @@ rb_ary_resize(VALUE ary, long len) olen = RARRAY_LEN(ary); if (len == olen) return ary; if (len > ARY_MAX_SIZE) { - rb_raise(rb_eIndexError, "index %ld too big", len); + rb_raise(rb_eIndexError, "index %ld too big", len); } if (len > olen) { - if (len >= ARY_CAPA(ary)) { - ary_double_capa(ary, len); - } - ary_mem_clear(ary, olen, len - olen); - ARY_SET_LEN(ary, len); + if (len >= ARY_CAPA(ary)) { + ary_double_capa(ary, len); + } + ary_mem_clear(ary, olen, len - olen); + ARY_SET_LEN(ary, len); } else if (ARY_EMBED_P(ary)) { ARY_SET_EMBED_LEN(ary, len); @@ -2441,11 +2441,11 @@ rb_ary_resize(VALUE ary, long len) if (is_malloc_ptr) ruby_sized_xfree((void *)ptr, ptr_capa); } else { - if (olen > len + ARY_DEFAULT_SIZE) { + if (olen > len + ARY_DEFAULT_SIZE) { size_t new_capa = ary_heap_realloc(ary, len); ARY_SET_CAPA(ary, new_capa); - } - ARY_SET_HEAP_LEN(ary, len); + } + ARY_SET_HEAP_LEN(ary, len); } ary_verify(ary); return ary; @@ -2589,16 +2589,16 @@ rb_ary_aset(int argc, VALUE *argv, VALUE ary) rb_check_arity(argc, 2, 3); rb_ary_modify_check(ary); if (argc == 3) { - beg = NUM2LONG(argv[0]); - len = NUM2LONG(argv[1]); + beg = NUM2LONG(argv[0]); + len = NUM2LONG(argv[1]); return ary_aset_by_rb_ary_splice(ary, beg, len, argv[2]); } if (FIXNUM_P(argv[0])) { - offset = FIX2LONG(argv[0]); + offset = FIX2LONG(argv[0]); return ary_aset_by_rb_ary_store(ary, offset, argv[1]); } if (rb_range_beg_len(argv[0], &beg, &len, RARRAY_LEN(ary), 1)) { - /* check if idx is Range */ + /* check if idx is Range */ return ary_aset_by_rb_ary_splice(ary, beg, len, argv[1]); } @@ -2652,15 +2652,15 @@ rb_ary_insert(int argc, VALUE *argv, VALUE ary) pos = NUM2LONG(argv[0]); if (argc == 1) return ary; if (pos == -1) { - pos = RARRAY_LEN(ary); + pos = RARRAY_LEN(ary); } else if (pos < 0) { - long minpos = -RARRAY_LEN(ary) - 1; - if (pos < minpos) { - rb_raise(rb_eIndexError, "index %ld too small for array; minimum: %ld", - pos, minpos); - } - pos++; + long minpos = -RARRAY_LEN(ary) - 1; + if (pos < minpos) { + rb_raise(rb_eIndexError, "index %ld too small for array; minimum: %ld", + pos, minpos); + } + pos++; } rb_ary_splice(ary, pos, 0, argv + 1, argc - 1); return ary; @@ -2727,7 +2727,7 @@ rb_ary_each(VALUE ary) ary_verify(ary); RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length); for (i=0; i 0) rb_enc_copy(result, RARRAY_AREF(ary, 0)); for (i=0; i 0 && !NIL_P(sep)) - rb_str_buf_append(result, sep); - rb_str_buf_append(result, val); + if (i > 0 && !NIL_P(sep)) + rb_str_buf_append(result, sep); + rb_str_buf_append(result, val); } return i; } @@ -2972,16 +2972,16 @@ ary_join_1(VALUE obj, VALUE ary, VALUE sep, long i, VALUE result, int *first) VALUE val, tmp; for (; i 0 && !NIL_P(sep)) - rb_str_buf_append(result, sep); + if (i > 0 && !NIL_P(sep)) + rb_str_buf_append(result, sep); - val = RARRAY_AREF(ary, i); - if (RB_TYPE_P(val, T_STRING)) { + val = RARRAY_AREF(ary, i); + if (RB_TYPE_P(val, T_STRING)) { ary_join_1_str(result, val, first); - } - else if (RB_TYPE_P(val, T_ARRAY)) { + } + else if (RB_TYPE_P(val, T_ARRAY)) { ary_join_1_ary(val, ary, sep, result, val, first); - } + } else if (!NIL_P(tmp = rb_check_string_type(val))) { ary_join_1_str(result, tmp, first); } @@ -2990,7 +2990,7 @@ ary_join_1(VALUE obj, VALUE ary, VALUE sep, long i, VALUE result, int *first) } else { ary_join_1_str(result, rb_obj_as_string(val), first); - } + } } } @@ -3003,26 +3003,26 @@ rb_ary_join(VALUE ary, VALUE sep) if (RARRAY_LEN(ary) == 0) return rb_usascii_str_new(0, 0); if (!NIL_P(sep)) { - StringValue(sep); - len += RSTRING_LEN(sep) * (RARRAY_LEN(ary) - 1); + StringValue(sep); + len += RSTRING_LEN(sep) * (RARRAY_LEN(ary) - 1); } for (i=0; i n) i = n; result = rb_str_buf_new(len + (n-i)*10); - rb_enc_associate(result, rb_usascii_encoding()); + rb_enc_associate(result, rb_usascii_encoding()); i = ary_join_0(ary, sep, i, result); - first = i == 0; - ary_join_1(ary, ary, sep, i, result, &first); - return result; - } + first = i == 0; + ary_join_1(ary, ary, sep, i, result, &first); + return result; + } - len += RSTRING_LEN(tmp); + len += RSTRING_LEN(tmp); } result = rb_str_new(0, len); @@ -3085,10 +3085,10 @@ inspect_ary(VALUE ary, VALUE dummy, int recur) if (recur) return rb_usascii_str_new_cstr("[...]"); str = rb_str_buf_new2("["); for (i=0; i 0) rb_str_buf_cat2(str, ", "); - else rb_enc_copy(str, s); - rb_str_buf_append(str, s); + s = rb_inspect(RARRAY_AREF(ary, i)); + if (i > 0) rb_str_buf_cat2(str, ", "); + else rb_enc_copy(str, s); + rb_str_buf_append(str, s); } rb_str_buf_cat2(str, "]"); return str; @@ -3145,9 +3145,9 @@ static VALUE rb_ary_to_a(VALUE ary) { if (rb_obj_class(ary) != rb_cArray) { - VALUE dup = rb_ary_new2(RARRAY_LEN(ary)); - rb_ary_replace(dup, ary); - return dup; + VALUE dup = rb_ary_new2(RARRAY_LEN(ary)); + rb_ary_replace(dup, ary); + return dup; } return ary; } @@ -3185,18 +3185,18 @@ rb_ary_to_h(VALUE ary) int block_given = rb_block_given_p(); for (i=0; i 0) { const VALUE *p1 = RARRAY_CONST_PTR_TRANSIENT(ary); VALUE *p2 = (VALUE *)RARRAY_CONST_PTR_TRANSIENT(dup) + len - 1; - do *p2-- = *p1++; while (--len > 0); + do *p2-- = *p1++; while (--len > 0); } ARY_SET_LEN(dup, RARRAY_LEN(ary)); return dup; @@ -3440,11 +3440,11 @@ rb_ary_rotate_m(int argc, VALUE *argv, VALUE ary) len = RARRAY_LEN(ary); rotated = rb_ary_new2(len); if (len > 0) { - cnt = rotate_count(cnt, len); + cnt = rotate_count(cnt, len); ptr = RARRAY_CONST_PTR_TRANSIENT(ary); - len -= cnt; - ary_memcpy(rotated, 0, len, ptr + cnt); - ary_memcpy(rotated, len, cnt, ptr); + len -= cnt; + ary_memcpy(rotated, 0, len, ptr + cnt); + ary_memcpy(rotated, len, cnt, ptr); } ARY_SET_LEN(rotated, RARRAY_LEN(ary)); return rotated; @@ -3460,7 +3460,7 @@ static VALUE sort_reentered(VALUE ary) { if (RBASIC(ary)->klass) { - rb_raise(rb_eRuntimeError, "sort reentered"); + rb_raise(rb_eRuntimeError, "sort reentered"); } return Qnil; } @@ -3500,15 +3500,15 @@ sort_2(const void *ap, const void *bp, void *dummy) int n; if (FIXNUM_P(a) && FIXNUM_P(b) && CMP_OPTIMIZABLE(data->cmp_opt, Integer)) { - if ((long)a > (long)b) return 1; - if ((long)a < (long)b) return -1; - return 0; + if ((long)a > (long)b) return 1; + if ((long)a < (long)b) return -1; + return 0; } if (STRING_P(a) && STRING_P(b) && CMP_OPTIMIZABLE(data->cmp_opt, String)) { - return rb_str_cmp(a, b); + return rb_str_cmp(a, b); } if (RB_FLOAT_TYPE_P(a) && CMP_OPTIMIZABLE(data->cmp_opt, Float)) { - return rb_float_cmp(a, b); + return rb_float_cmp(a, b); } retval = rb_funcallv(a, id_cmp, 1, &b); @@ -3565,25 +3565,25 @@ rb_ary_sort_bang(VALUE ary) rb_ary_modify(ary); assert(!ARY_SHARED_P(ary)); if (RARRAY_LEN(ary) > 1) { - VALUE tmp = ary_make_substitution(ary); /* only ary refers tmp */ - struct ary_sort_data data; - long len = RARRAY_LEN(ary); - RBASIC_CLEAR_CLASS(tmp); - data.ary = tmp; + VALUE tmp = ary_make_substitution(ary); /* only ary refers tmp */ + struct ary_sort_data data; + long len = RARRAY_LEN(ary); + RBASIC_CLEAR_CLASS(tmp); + data.ary = tmp; data.receiver = ary; - data.cmp_opt.opt_methods = 0; - data.cmp_opt.opt_inited = 0; - RARRAY_PTR_USE(tmp, ptr, { + data.cmp_opt.opt_methods = 0; + data.cmp_opt.opt_inited = 0; + RARRAY_PTR_USE(tmp, ptr, { ruby_qsort(ptr, len, sizeof(VALUE), rb_block_given_p()?sort_1:sort_2, &data); - }); /* WB: no new reference */ - rb_ary_modify(ary); + }); /* WB: no new reference */ + rb_ary_modify(ary); if (ARY_EMBED_P(tmp)) { if (ARY_SHARED_P(ary)) { /* ary might be destructively operated in the given block */ rb_ary_unshare(ary); - FL_SET_EMBED(ary); + FL_SET_EMBED(ary); } - ary_memcpy(ary, 0, ARY_EMBED_LEN(tmp), ARY_EMBED_PTR(tmp)); + ary_memcpy(ary, 0, ARY_EMBED_LEN(tmp), ARY_EMBED_PTR(tmp)); ARY_SET_LEN(ary, ARY_EMBED_LEN(tmp)); } else { @@ -3688,7 +3688,7 @@ rb_ary_bsearch(VALUE ary) VALUE index_result = rb_ary_bsearch_index(ary); if (FIXNUM_P(index_result)) { - return rb_ary_entry(ary, FIX2LONG(index_result)); + return rb_ary_entry(ary, FIX2LONG(index_result)); } return index_result; } @@ -3711,39 +3711,39 @@ rb_ary_bsearch_index(VALUE ary) RETURN_ENUMERATOR(ary, 0, 0); while (low < high) { - mid = low + ((high - low) / 2); - val = rb_ary_entry(ary, mid); - v = rb_yield(val); - if (FIXNUM_P(v)) { - if (v == INT2FIX(0)) return INT2FIX(mid); - smaller = (SIGNED_VALUE)v < 0; /* Fixnum preserves its sign-bit */ - } - else if (v == Qtrue) { - satisfied = 1; - smaller = 1; - } - else if (!RTEST(v)) { - smaller = 0; - } - else if (rb_obj_is_kind_of(v, rb_cNumeric)) { - const VALUE zero = INT2FIX(0); - switch (rb_cmpint(rb_funcallv(v, id_cmp, 1, &zero), v, zero)) { - case 0: return INT2FIX(mid); - case 1: smaller = 1; break; - case -1: smaller = 0; - } - } - else { - rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE - " (must be numeric, true, false or nil)", - rb_obj_class(v)); - } - if (smaller) { - high = mid; - } - else { - low = mid + 1; - } + mid = low + ((high - low) / 2); + val = rb_ary_entry(ary, mid); + v = rb_yield(val); + if (FIXNUM_P(v)) { + if (v == INT2FIX(0)) return INT2FIX(mid); + smaller = (SIGNED_VALUE)v < 0; /* Fixnum preserves its sign-bit */ + } + else if (v == Qtrue) { + satisfied = 1; + smaller = 1; + } + else if (!RTEST(v)) { + smaller = 0; + } + else if (rb_obj_is_kind_of(v, rb_cNumeric)) { + const VALUE zero = INT2FIX(0); + switch (rb_cmpint(rb_funcallv(v, id_cmp, 1, &zero), v, zero)) { + case 0: return INT2FIX(mid); + case 1: smaller = 1; break; + case -1: smaller = 0; + } + } + else { + rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE + " (must be numeric, true, false or nil)", + rb_obj_class(v)); + } + if (smaller) { + high = mid; + } + else { + low = mid + 1; + } } if (!satisfied) return Qnil; return INT2FIX(low); @@ -3858,7 +3858,7 @@ rb_ary_collect_bang(VALUE ary) RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length); rb_ary_modify(ary); for (i = 0; i < RARRAY_LEN(ary); i++) { - rb_ary_store(ary, i, rb_yield(RARRAY_AREF(ary, i))); + rb_ary_store(ary, i, rb_yield(RARRAY_AREF(ary, i))); } return ary; } @@ -3870,21 +3870,21 @@ rb_get_values_at(VALUE obj, long olen, int argc, const VALUE *argv, VALUE (*func long beg, len, i, j; for (i=0; i j) - rb_ary_resize(result, RARRAY_LEN(result) + (beg + len) - j); - continue; - } - rb_ary_push(result, (*func)(obj, NUM2LONG(argv[i]))); + if (FIXNUM_P(argv[i])) { + rb_ary_push(result, (*func)(obj, FIX2LONG(argv[i]))); + continue; + } + /* check if idx is Range */ + if (rb_range_beg_len(argv[i], &beg, &len, olen, 1)) { + long end = olen < beg+len ? olen : beg+len; + for (j = beg; j < end; j++) { + rb_ary_push(result, (*func)(obj, j)); + } + if (beg + len > j) + rb_ary_resize(result, RARRAY_LEN(result) + (beg + len) - j); + continue; + } + rb_ary_push(result, (*func)(obj, NUM2LONG(argv[i]))); } return result; } @@ -3894,25 +3894,25 @@ append_values_at_single(VALUE result, VALUE ary, long olen, VALUE idx) { long beg, len; if (FIXNUM_P(idx)) { - beg = FIX2LONG(idx); + beg = FIX2LONG(idx); } /* check if idx is Range */ else if (rb_range_beg_len(idx, &beg, &len, olen, 1)) { - if (len > 0) { + if (len > 0) { const VALUE *const src = RARRAY_CONST_PTR_TRANSIENT(ary); - const long end = beg + len; - const long prevlen = RARRAY_LEN(result); - if (beg < olen) { - rb_ary_cat(result, src + beg, end > olen ? olen-beg : len); - } - if (end > olen) { - rb_ary_store(result, prevlen + len - 1, Qnil); - } - } - return result; + const long end = beg + len; + const long prevlen = RARRAY_LEN(result); + if (beg < olen) { + rb_ary_cat(result, src + beg, end > olen ? olen-beg : len); + } + if (end > olen) { + rb_ary_store(result, prevlen + len - 1, Qnil); + } + } + return result; } else { - beg = NUM2LONG(idx); + beg = NUM2LONG(idx); } return rb_ary_push(result, rb_ary_entry(ary, beg)); } @@ -3966,7 +3966,7 @@ rb_ary_values_at(int argc, VALUE *argv, VALUE ary) long i, olen = RARRAY_LEN(ary); VALUE result = rb_ary_new_capa(argc); for (i = 0; i < argc; ++i) { - append_values_at_single(result, ary, olen, argv[i]); + append_values_at_single(result, ary, olen, argv[i]); } RB_GC_GUARD(ary); return result; @@ -4003,9 +4003,9 @@ rb_ary_select(VALUE ary) RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length); result = rb_ary_new2(RARRAY_LEN(ary)); for (i = 0; i < RARRAY_LEN(ary); i++) { - if (RTEST(rb_yield(RARRAY_AREF(ary, i)))) { - rb_ary_push(result, rb_ary_elt(ary, i)); - } + if (RTEST(rb_yield(RARRAY_AREF(ary, i)))) { + rb_ary_push(result, rb_ary_elt(ary, i)); + } } return result; } @@ -4023,12 +4023,12 @@ select_bang_i(VALUE a) long i1, i2; for (i1 = i2 = 0; i1 < RARRAY_LEN(ary); arg->len[0] = ++i1) { - VALUE v = RARRAY_AREF(ary, i1); - if (!RTEST(rb_yield(v))) continue; - if (i1 != i2) { - rb_ary_store(ary, i2, v); - } - arg->len[1] = ++i2; + VALUE v = RARRAY_AREF(ary, i1); + if (!RTEST(rb_yield(v))) continue; + if (i1 != i2) { + rb_ary_store(ary, i2, v); + } + arg->len[1] = ++i2; } return (i1 == i2) ? Qnil : ary; } @@ -4042,15 +4042,15 @@ select_bang_ensure(VALUE a) long i1 = arg->len[0], i2 = arg->len[1]; if (i2 < len && i2 < i1) { - long tail = 0; + long tail = 0; rb_ary_modify(ary); - if (i1 < len) { - tail = len - i1; + if (i1 < len) { + tail = len - i1; RARRAY_PTR_USE_TRANSIENT(ary, ptr, { - MEMMOVE(ptr + i2, ptr + i1, VALUE, tail); - }); - } - ARY_SET_LEN(ary, i2 + tail); + MEMMOVE(ptr + i2, ptr + i1, VALUE, tail); + }); + } + ARY_SET_LEN(ary, i2 + tail); } return ary; } @@ -4122,11 +4122,11 @@ ary_resize_smaller(VALUE ary, long len) { rb_ary_modify(ary); if (RARRAY_LEN(ary) > len) { - ARY_SET_LEN(ary, len); - if (len * 2 < ARY_CAPA(ary) && - ARY_CAPA(ary) > ARY_DEFAULT_SIZE) { - ary_resize_capa(ary, len * 2); - } + ARY_SET_LEN(ary, len); + if (len * 2 < ARY_CAPA(ary) && + ARY_CAPA(ary) > ARY_DEFAULT_SIZE) { + ary_resize_capa(ary, len * 2); + } } } @@ -4173,22 +4173,22 @@ rb_ary_delete(VALUE ary, VALUE item) long i1, i2; for (i1 = i2 = 0; i1 < RARRAY_LEN(ary); i1++) { - VALUE e = RARRAY_AREF(ary, i1); + VALUE e = RARRAY_AREF(ary, i1); - if (rb_equal(e, item)) { - v = e; - continue; - } - if (i1 != i2) { - rb_ary_store(ary, i2, e); - } - i2++; + if (rb_equal(e, item)) { + v = e; + continue; + } + if (i1 != i2) { + rb_ary_store(ary, i2, e); + } + i2++; } if (RARRAY_LEN(ary) == i2) { - if (rb_block_given_p()) { - return rb_yield(item); - } - return Qnil; + if (rb_block_given_p()) { + return rb_yield(item); + } + return Qnil; } ary_resize_smaller(ary, i2); @@ -4203,18 +4203,18 @@ rb_ary_delete_same(VALUE ary, VALUE item) long i1, i2; for (i1 = i2 = 0; i1 < RARRAY_LEN(ary); i1++) { - VALUE e = RARRAY_AREF(ary, i1); + VALUE e = RARRAY_AREF(ary, i1); - if (e == item) { - continue; - } - if (i1 != i2) { - rb_ary_store(ary, i2, e); - } - i2++; + if (e == item) { + continue; + } + if (i1 != i2) { + rb_ary_store(ary, i2, e); + } + i2++; } if (RARRAY_LEN(ary) == i2) { - return; + return; } ary_resize_smaller(ary, i2); @@ -4228,8 +4228,8 @@ rb_ary_delete_at(VALUE ary, long pos) if (pos >= len) return Qnil; if (pos < 0) { - pos += len; - if (pos < 0) return Qnil; + pos += len; + if (pos < 0) return Qnil; } rb_ary_modify(ary); @@ -4381,23 +4381,23 @@ rb_ary_slice_bang(int argc, VALUE *argv, VALUE ary) arg1 = argv[0]; if (argc == 2) { - pos = NUM2LONG(argv[0]); - len = NUM2LONG(argv[1]); + pos = NUM2LONG(argv[0]); + len = NUM2LONG(argv[1]); return ary_slice_bang_by_rb_ary_splice(ary, pos, len); } if (!FIXNUM_P(arg1)) { - switch (rb_range_beg_len(arg1, &pos, &len, RARRAY_LEN(ary), 0)) { - case Qtrue: - /* valid range */ + switch (rb_range_beg_len(arg1, &pos, &len, RARRAY_LEN(ary), 0)) { + case Qtrue: + /* valid range */ return ary_slice_bang_by_rb_ary_splice(ary, pos, len); - case Qnil: - /* invalid range */ - return Qnil; - default: - /* not a range */ - break; - } + case Qnil: + /* invalid range */ + return Qnil; + default: + /* not a range */ + break; + } } return rb_ary_delete_at(ary, NUM2LONG(arg1)); @@ -4409,11 +4409,11 @@ ary_reject(VALUE orig, VALUE result) long i; for (i = 0; i < RARRAY_LEN(orig); i++) { - VALUE v = RARRAY_AREF(orig, i); + VALUE v = RARRAY_AREF(orig, i); if (!RTEST(rb_yield(v))) { - rb_ary_push(result, v); - } + rb_ary_push(result, v); + } } return result; } @@ -4426,12 +4426,12 @@ reject_bang_i(VALUE a) long i1, i2; for (i1 = i2 = 0; i1 < RARRAY_LEN(ary); arg->len[0] = ++i1) { - VALUE v = RARRAY_AREF(ary, i1); - if (RTEST(rb_yield(v))) continue; - if (i1 != i2) { - rb_ary_store(ary, i2, v); - } - arg->len[1] = ++i2; + VALUE v = RARRAY_AREF(ary, i1); + if (RTEST(rb_yield(v))) continue; + if (i1 != i2) { + rb_ary_store(ary, i2, v); + } + arg->len[1] = ++i2; } return (i1 == i2) ? Qnil : ary; } @@ -4553,8 +4553,8 @@ take_items(VALUE obj, long n) result = rb_ary_new2(n); args[0] = result; args[1] = (VALUE)n; if (rb_check_block_call(obj, idEach, 0, 0, take_i, (VALUE)args) == Qundef) - rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (must respond to :each)", - rb_obj_class(obj)); + rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (must respond to :each)", + rb_obj_class(obj)); return result; } @@ -4623,51 +4623,51 @@ rb_ary_zip(int argc, VALUE *argv, VALUE ary) VALUE result = Qnil; for (i=0; i 1) { - VALUE work, *tmp; + if (arity > 1) { + VALUE work, *tmp; - tmp = ALLOCV_N(VALUE, work, argc+1); + tmp = ALLOCV_N(VALUE, work, argc+1); - for (i=0; i= ARY_MAX_SIZE || len > ARY_MAX_SIZE - beg) { - rb_raise(rb_eArgError, "argument too big"); + rb_raise(rb_eArgError, "argument too big"); } end = beg + len; if (RARRAY_LEN(ary) < end) { - if (end >= ARY_CAPA(ary)) { - ary_resize_capa(ary, end); - } - ary_mem_clear(ary, RARRAY_LEN(ary), end - RARRAY_LEN(ary)); - ARY_SET_LEN(ary, end); + if (end >= ARY_CAPA(ary)) { + ary_resize_capa(ary, end); + } + ary_mem_clear(ary, RARRAY_LEN(ary), end - RARRAY_LEN(ary)); + ARY_SET_LEN(ary, end); } if (item == Qundef) { - VALUE v; - long i; + VALUE v; + long i; - for (i=beg; i=RARRAY_LEN(ary)) break; - ARY_SET(ary, i, v); - } + for (i=beg; i=RARRAY_LEN(ary)) break; + ARY_SET(ary, i, v); + } } else { - ary_memfill(ary, beg, len, item); + ary_memfill(ary, beg, len, item); } return ary; } @@ -5119,15 +5119,15 @@ rb_ary_concat_multi(int argc, VALUE *argv, VALUE ary) rb_ary_modify_check(ary); if (argc == 1) { - rb_ary_concat(ary, argv[0]); + rb_ary_concat(ary, argv[0]); } else if (argc > 1) { - int i; - VALUE args = rb_ary_tmp_new(argc); - for (i = 0; i < argc; i++) { - rb_ary_concat(args, argv[i]); - } - ary_append(ary, args); + int i; + VALUE args = rb_ary_tmp_new(argc); + for (i = 0; i < argc; i++) { + rb_ary_concat(args, argv[i]); + } + ary_append(ary, args); } ary_verify(ary); @@ -5167,19 +5167,19 @@ rb_ary_times(VALUE ary, VALUE times) tmp = rb_check_string_type(times); if (!NIL_P(tmp)) { - return rb_ary_join(ary, tmp); + return rb_ary_join(ary, tmp); } len = NUM2LONG(times); if (len == 0) { ary2 = ary_new(rb_cArray, 0); - goto out; + goto out; } if (len < 0) { - rb_raise(rb_eArgError, "negative argument"); + rb_raise(rb_eArgError, "negative argument"); } if (ARY_MAX_SIZE/len < RARRAY_LEN(ary)) { - rb_raise(rb_eArgError, "argument too big"); + rb_raise(rb_eArgError, "argument too big"); } len *= RARRAY_LEN(ary); @@ -5189,8 +5189,8 @@ rb_ary_times(VALUE ary, VALUE times) ptr = RARRAY_CONST_PTR_TRANSIENT(ary); t = RARRAY_LEN(ary); if (0 < t) { - ary_memcpy(ary2, 0, t, ptr); - while (t <= len/2) { + ary_memcpy(ary2, 0, t, ptr); + while (t <= len/2) { ary_memcpy(ary2, t, t, RARRAY_CONST_PTR_TRANSIENT(ary2)); t *= 2; } @@ -5224,10 +5224,10 @@ rb_ary_assoc(VALUE ary, VALUE key) VALUE v; for (i = 0; i < RARRAY_LEN(ary); ++i) { - v = rb_check_array_type(RARRAY_AREF(ary, i)); - if (!NIL_P(v) && RARRAY_LEN(v) > 0 && - rb_equal(RARRAY_AREF(v, 0), key)) - return v; + v = rb_check_array_type(RARRAY_AREF(ary, i)); + if (!NIL_P(v) && RARRAY_LEN(v) > 0 && + rb_equal(RARRAY_AREF(v, 0), key)) + return v; } return Qnil; } @@ -5254,11 +5254,11 @@ rb_ary_rassoc(VALUE ary, VALUE value) VALUE v; for (i = 0; i < RARRAY_LEN(ary); ++i) { - v = RARRAY_AREF(ary, i); - if (RB_TYPE_P(v, T_ARRAY) && - RARRAY_LEN(v) > 1 && - rb_equal(RARRAY_AREF(v, 1), value)) - return v; + v = RARRAY_AREF(ary, i); + if (RB_TYPE_P(v, T_ARRAY) && + RARRAY_LEN(v) > 1 && + rb_equal(RARRAY_AREF(v, 1), value)) + return v; } return Qnil; } @@ -5277,22 +5277,22 @@ recursive_equal(VALUE ary1, VALUE ary2, int recur) len1 = RARRAY_LEN(ary1); for (i = 0; i < len1; i++) { - if (*p1 != *p2) { - if (rb_equal(*p1, *p2)) { - len1 = RARRAY_LEN(ary1); - if (len1 != RARRAY_LEN(ary2)) - return Qfalse; - if (len1 < i) - return Qtrue; + if (*p1 != *p2) { + if (rb_equal(*p1, *p2)) { + len1 = RARRAY_LEN(ary1); + if (len1 != RARRAY_LEN(ary2)) + return Qfalse; + if (len1 < i) + return Qtrue; p1 = RARRAY_CONST_PTR(ary1) + i; p2 = RARRAY_CONST_PTR(ary2) + i; - } - else { - return Qfalse; - } - } - p1++; - p2++; + } + else { + return Qfalse; + } + } + p1++; + p2++; } return Qtrue; } @@ -5320,10 +5320,10 @@ rb_ary_equal(VALUE ary1, VALUE ary2) { if (ary1 == ary2) return Qtrue; if (!RB_TYPE_P(ary2, T_ARRAY)) { - if (!rb_respond_to(ary2, idTo_ary)) { - return Qfalse; - } - return rb_equal(ary2, ary1); + if (!rb_respond_to(ary2, idTo_ary)) { + return Qfalse; + } + return rb_equal(ary2, ary1); } if (RARRAY_LEN(ary1) != RARRAY_LEN(ary2)) return Qfalse; if (RARRAY_CONST_PTR_TRANSIENT(ary1) == RARRAY_CONST_PTR_TRANSIENT(ary2)) return Qtrue; @@ -5337,8 +5337,8 @@ recursive_eql(VALUE ary1, VALUE ary2, int recur) if (recur) return Qtrue; /* Subtle! */ for (i=0; i RARRAY_LEN(ary2)) { - len = RARRAY_LEN(ary2); + len = RARRAY_LEN(ary2); } for (i=0; i 0) { - result = v; - } - } + for (i = 0; i < RARRAY_LEN(ary); i++) { + v = RARRAY_AREF(ary, i); + if (result == Qundef || rb_cmpint(rb_yield_values(2, v, result), v, result) > 0) { + result = v; + } + } } else if (n > 0) { result = RARRAY_AREF(ary, 0); @@ -6232,12 +6232,12 @@ rb_ary_min(int argc, VALUE *argv, VALUE ary) const long n = RARRAY_LEN(ary); if (rb_block_given_p()) { - for (i = 0; i < RARRAY_LEN(ary); i++) { - v = RARRAY_AREF(ary, i); - if (result == Qundef || rb_cmpint(rb_yield_values(2, v, result), v, result) < 0) { - result = v; - } - } + for (i = 0; i < RARRAY_LEN(ary); i++) { + v = RARRAY_AREF(ary, i); + if (result == Qundef || rb_cmpint(rb_yield_values(2, v, result), v, result) < 0) { + result = v; + } + } } else if (n > 0) { result = RARRAY_AREF(ary, 0); @@ -6338,19 +6338,19 @@ rb_ary_uniq_bang(VALUE ary) if (RARRAY_LEN(ary) <= 1) return Qnil; if (rb_block_given_p()) - hash = ary_make_hash_by(ary); + hash = ary_make_hash_by(ary); else - hash = ary_make_hash(ary); + hash = ary_make_hash(ary); hash_size = RHASH_SIZE(hash); if (RARRAY_LEN(ary) == hash_size) { - return Qnil; + return Qnil; } rb_ary_modify_check(ary); ARY_SET_LEN(ary, 0); if (ARY_SHARED_P(ary) && !ARY_EMBED_P(ary)) { - rb_ary_unshare(ary); - FL_SET_EMBED(ary); + rb_ary_unshare(ary); + FL_SET_EMBED(ary); } ary_resize_capa(ary, hash_size); rb_hash_foreach(hash, push_value, ary); @@ -6392,12 +6392,12 @@ rb_ary_uniq(VALUE ary) uniq = rb_ary_dup(ary); } else if (rb_block_given_p()) { - hash = ary_make_hash_by(ary); - uniq = rb_hash_values(hash); + hash = ary_make_hash_by(ary); + uniq = rb_hash_values(hash); } else { - hash = ary_make_hash(ary); - uniq = rb_hash_values(hash); + hash = ary_make_hash(ary); + uniq = rb_hash_values(hash); } if (hash) { ary_recycle_hash(hash); @@ -6426,12 +6426,12 @@ rb_ary_compact_bang(VALUE ary) end = p + RARRAY_LEN(ary); while (t < end) { - if (NIL_P(*t)) t++; - else *p++ = *t++; + if (NIL_P(*t)) t++; + else *p++ = *t++; } n = p - RARRAY_CONST_PTR_TRANSIENT(ary); if (RARRAY_LEN(ary) == n) { - return Qnil; + return Qnil; } ary_resize_smaller(ary, n); @@ -6489,25 +6489,25 @@ rb_ary_count(int argc, VALUE *argv, VALUE ary) long i, n = 0; if (rb_check_arity(argc, 0, 1) == 0) { - VALUE v; + VALUE v; - if (!rb_block_given_p()) - return LONG2NUM(RARRAY_LEN(ary)); + if (!rb_block_given_p()) + return LONG2NUM(RARRAY_LEN(ary)); - for (i = 0; i < RARRAY_LEN(ary); i++) { - v = RARRAY_AREF(ary, i); - if (RTEST(rb_yield(v))) n++; - } + for (i = 0; i < RARRAY_LEN(ary); i++) { + v = RARRAY_AREF(ary, i); + if (RTEST(rb_yield(v))) n++; + } } else { VALUE obj = argv[0]; - if (rb_block_given_p()) { - rb_warn("given block not used"); - } - for (i = 0; i < RARRAY_LEN(ary); i++) { - if (rb_equal(RARRAY_AREF(ary, i), obj)) n++; - } + if (rb_block_given_p()) { + rb_warn("given block not used"); + } + for (i = 0; i < RARRAY_LEN(ary); i++) { + if (rb_equal(RARRAY_AREF(ary, i), obj)) n++; + } } return LONG2NUM(n); @@ -6541,64 +6541,64 @@ flatten(VALUE ary, int level) rb_ary_push(stack, LONG2NUM(i + 1)); if (level < 0) { - vmemo = rb_hash_new(); - RBASIC_CLEAR_CLASS(vmemo); - memo = st_init_numtable(); - rb_hash_st_table_set(vmemo, memo); - st_insert(memo, (st_data_t)ary, (st_data_t)Qtrue); - st_insert(memo, (st_data_t)tmp, (st_data_t)Qtrue); + vmemo = rb_hash_new(); + RBASIC_CLEAR_CLASS(vmemo); + memo = st_init_numtable(); + rb_hash_st_table_set(vmemo, memo); + st_insert(memo, (st_data_t)ary, (st_data_t)Qtrue); + st_insert(memo, (st_data_t)tmp, (st_data_t)Qtrue); } ary = tmp; i = 0; while (1) { - while (i < RARRAY_LEN(ary)) { - elt = RARRAY_AREF(ary, i++); - if (level >= 0 && RARRAY_LEN(stack) / 2 >= level) { - rb_ary_push(result, elt); - continue; - } - tmp = rb_check_array_type(elt); - if (RBASIC(result)->klass) { - if (memo) { - RB_GC_GUARD(vmemo); - st_clear(memo); - } - rb_raise(rb_eRuntimeError, "flatten reentered"); - } - if (NIL_P(tmp)) { - rb_ary_push(result, elt); - } - else { - if (memo) { - id = (st_data_t)tmp; - if (st_is_member(memo, id)) { - st_clear(memo); - rb_raise(rb_eArgError, "tried to flatten recursive array"); - } - st_insert(memo, id, (st_data_t)Qtrue); - } - rb_ary_push(stack, ary); - rb_ary_push(stack, LONG2NUM(i)); - ary = tmp; - i = 0; - } - } - if (RARRAY_LEN(stack) == 0) { - break; - } - if (memo) { - id = (st_data_t)ary; - st_delete(memo, &id, 0); - } - tmp = rb_ary_pop(stack); - i = NUM2LONG(tmp); - ary = rb_ary_pop(stack); + while (i < RARRAY_LEN(ary)) { + elt = RARRAY_AREF(ary, i++); + if (level >= 0 && RARRAY_LEN(stack) / 2 >= level) { + rb_ary_push(result, elt); + continue; + } + tmp = rb_check_array_type(elt); + if (RBASIC(result)->klass) { + if (memo) { + RB_GC_GUARD(vmemo); + st_clear(memo); + } + rb_raise(rb_eRuntimeError, "flatten reentered"); + } + if (NIL_P(tmp)) { + rb_ary_push(result, elt); + } + else { + if (memo) { + id = (st_data_t)tmp; + if (st_is_member(memo, id)) { + st_clear(memo); + rb_raise(rb_eArgError, "tried to flatten recursive array"); + } + st_insert(memo, id, (st_data_t)Qtrue); + } + rb_ary_push(stack, ary); + rb_ary_push(stack, LONG2NUM(i)); + ary = tmp; + i = 0; + } + } + if (RARRAY_LEN(stack) == 0) { + break; + } + if (memo) { + id = (st_data_t)ary; + st_delete(memo, &id, 0); + } + tmp = rb_ary_pop(stack); + i = NUM2LONG(tmp); + ary = rb_ary_pop(stack); } if (memo) { - st_clear(memo); + st_clear(memo); } RBASIC_SET_CLASS(result, rb_cArray); @@ -6649,7 +6649,7 @@ rb_ary_flatten_bang(int argc, VALUE *argv, VALUE ary) result = flatten(ary, level); if (result == ary) { - return Qnil; + return Qnil; } if (!(mod = ARY_EMBED_P(result))) rb_obj_freeze(result); rb_ary_replace(ary, result); @@ -6720,16 +6720,16 @@ rb_ary_shuffle_bang(rb_execution_context_t *ec, VALUE ary, VALUE randgen) rb_ary_modify(ary); i = len = RARRAY_LEN(ary); RARRAY_PTR_USE(ary, ptr, { - while (i) { - long j = RAND_UPTO(i); - VALUE tmp; + while (i) { + long j = RAND_UPTO(i); + VALUE tmp; if (len != RARRAY_LEN(ary) || ptr != RARRAY_CONST_PTR_TRANSIENT(ary)) { rb_raise(rb_eRuntimeError, "modified during shuffle"); - } - tmp = ptr[--i]; - ptr[i] = ptr[j]; - ptr[j] = tmp; - } + } + tmp = ptr[--i]; + ptr[i] = ptr[j]; + ptr[j] = tmp; + } }); /* WB: no new reference */ return ary; } @@ -6752,120 +6752,120 @@ ary_sample(rb_execution_context_t *ec, VALUE ary, VALUE randgen, VALUE nv, VALUE len = RARRAY_LEN(ary); if (!to_array) { - if (len < 2) - i = 0; - else - i = RAND_UPTO(len); + if (len < 2) + i = 0; + else + i = RAND_UPTO(len); - return rb_ary_elt(ary, i); + return rb_ary_elt(ary, i); } n = NUM2LONG(nv); if (n < 0) rb_raise(rb_eArgError, "negative sample number"); if (n > len) n = len; if (n <= numberof(idx)) { - for (i = 0; i < n; ++i) { - rnds[i] = RAND_UPTO(len - i); - } + for (i = 0; i < n; ++i) { + rnds[i] = RAND_UPTO(len - i); + } } k = len; len = RARRAY_LEN(ary); if (len < k && n <= numberof(idx)) { - for (i = 0; i < n; ++i) { - if (rnds[i] >= len) return rb_ary_new_capa(0); - } + for (i = 0; i < n; ++i) { + if (rnds[i] >= len) return rb_ary_new_capa(0); + } } if (n > len) n = len; switch (n) { case 0: - return rb_ary_new_capa(0); + return rb_ary_new_capa(0); case 1: - i = rnds[0]; - return rb_ary_new_from_args(1, RARRAY_AREF(ary, i)); + i = rnds[0]; + return rb_ary_new_from_args(1, RARRAY_AREF(ary, i)); case 2: - i = rnds[0]; - j = rnds[1]; - if (j >= i) j++; - return rb_ary_new_from_args(2, RARRAY_AREF(ary, i), RARRAY_AREF(ary, j)); + i = rnds[0]; + j = rnds[1]; + if (j >= i) j++; + return rb_ary_new_from_args(2, RARRAY_AREF(ary, i), RARRAY_AREF(ary, j)); case 3: - i = rnds[0]; - j = rnds[1]; - k = rnds[2]; - { - long l = j, g = i; - if (j >= i) l = i, g = ++j; - if (k >= l && (++k >= g)) ++k; - } - return rb_ary_new_from_args(3, RARRAY_AREF(ary, i), RARRAY_AREF(ary, j), RARRAY_AREF(ary, k)); + i = rnds[0]; + j = rnds[1]; + k = rnds[2]; + { + long l = j, g = i; + if (j >= i) l = i, g = ++j; + if (k >= l && (++k >= g)) ++k; + } + return rb_ary_new_from_args(3, RARRAY_AREF(ary, i), RARRAY_AREF(ary, j), RARRAY_AREF(ary, k)); } memo_threshold = - len < 2560 ? len / 128 : - len < 5120 ? len / 64 : - len < 10240 ? len / 32 : - len / 16; + len < 2560 ? len / 128 : + len < 5120 ? len / 64 : + len < 10240 ? len / 32 : + len / 16; if (n <= numberof(idx)) { - long sorted[numberof(idx)]; - sorted[0] = idx[0] = rnds[0]; - for (i=1; i max_idx) max_idx = r; - } - len = RARRAY_LEN(ary); - if (len <= max_idx) n = 0; - else if (n > len) n = len; + VALUE vmemo = Data_Wrap_Struct(0, 0, st_free_table, 0); + st_table *memo = st_init_numtable_with_size(n); + DATA_PTR(vmemo) = memo; + result = rb_ary_new_capa(n); + RARRAY_PTR_USE(result, ptr_result, { + for (i=0; i max_idx) max_idx = r; + } + len = RARRAY_LEN(ary); + if (len <= max_idx) n = 0; + else if (n > len) n = len; RARRAY_PTR_USE_TRANSIENT(ary, ptr_ary, { - for (i=0; i 0)) { - n = RARRAY_AREF(args, 0); + n = RARRAY_AREF(args, 0); } if (RARRAY_LEN(self) == 0) return INT2FIX(0); if (NIL_P(n)) return DBL2NUM(HUGE_VAL); @@ -6989,32 +6989,32 @@ permute0(const long n, const long r, long *const p, char *const used, const VALU long i = 0, index = 0; for (;;) { - const char *const unused = memchr(&used[i], 0, n-i); - if (!unused) { - if (!index) break; - i = p[--index]; /* pop index */ - used[i++] = 0; /* index unused */ - } - else { - i = unused - used; - p[index] = i; - used[i] = 1; /* mark index used */ - ++index; - if (index < r-1) { /* if not done yet */ - p[index] = i = 0; - continue; - } - for (i = 0; i < n; ++i) { - if (used[i]) continue; - p[index] = i; - if (!yield_indexed_values(values, r, p)) { - rb_raise(rb_eRuntimeError, "permute reentered"); - } - } - i = p[--index]; /* pop index */ - used[i] = 0; /* index unused */ - p[index] = ++i; - } + const char *const unused = memchr(&used[i], 0, n-i); + if (!unused) { + if (!index) break; + i = p[--index]; /* pop index */ + used[i++] = 0; /* index unused */ + } + else { + i = unused - used; + p[index] = i; + used[i] = 1; /* mark index used */ + ++index; + if (index < r-1) { /* if not done yet */ + p[index] = i = 0; + continue; + } + for (i = 0; i < n; ++i) { + if (used[i]) continue; + p[index] = i; + if (!yield_indexed_values(values, r, p)) { + rb_raise(rb_eRuntimeError, "permute reentered"); + } + } + i = p[--index]; /* pop index */ + used[i] = 0; /* index unused */ + p[index] = ++i; + } } } @@ -7027,14 +7027,14 @@ descending_factorial(long from, long how_many) { VALUE cnt; if (how_many > 0) { - cnt = LONG2FIX(from); - while (--how_many > 0) { - long v = --from; - cnt = rb_int_mul(cnt, LONG2FIX(v)); - } + cnt = LONG2FIX(from); + while (--how_many > 0) { + long v = --from; + cnt = rb_int_mul(cnt, LONG2FIX(v)); + } } else { - cnt = LONG2FIX(how_many == 0); + cnt = LONG2FIX(how_many == 0); } return cnt; } @@ -7045,18 +7045,18 @@ binomial_coefficient(long comb, long size) VALUE r; long i; if (comb > size-comb) { - comb = size-comb; + comb = size-comb; } if (comb < 0) { - return LONG2FIX(0); + return LONG2FIX(0); } else if (comb == 0) { - return LONG2FIX(1); + return LONG2FIX(1); } r = LONG2FIX(size); for (i = 1; i < comb; ++i) { - r = rb_int_mul(r, LONG2FIX(size - i)); - r = rb_int_idiv(r, LONG2FIX(i + 1)); + r = rb_int_mul(r, LONG2FIX(size - i)); + r = rb_int_idiv(r, LONG2FIX(i + 1)); } return r; } @@ -7162,28 +7162,28 @@ rb_ary_permutation(int argc, VALUE *argv, VALUE ary) r = NUM2LONG(argv[0]); /* Permutation size from argument */ if (r < 0 || n < r) { - /* no permutations: yield nothing */ + /* no permutations: yield nothing */ } else if (r == 0) { /* exactly one permutation: the zero-length array */ - rb_yield(rb_ary_new2(0)); + rb_yield(rb_ary_new2(0)); } else if (r == 1) { /* this is a special, easy case */ - for (i = 0; i < RARRAY_LEN(ary); i++) { - rb_yield(rb_ary_new3(1, RARRAY_AREF(ary, i))); - } + for (i = 0; i < RARRAY_LEN(ary); i++) { + rb_yield(rb_ary_new3(1, RARRAY_AREF(ary, i))); + } } else { /* this is the general case */ - volatile VALUE t0; - long *p = ALLOCV_N(long, t0, r+roomof(n, sizeof(long))); - char *used = (char*)(p + r); - VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */ - RBASIC_CLEAR_CLASS(ary0); + volatile VALUE t0; + long *p = ALLOCV_N(long, t0, r+roomof(n, sizeof(long))); + char *used = (char*)(p + r); + VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */ + RBASIC_CLEAR_CLASS(ary0); - MEMZERO(used, char, n); /* initialize array */ + MEMZERO(used, char, n); /* initialize array */ - permute0(n, r, p, used, ary0); /* compute and yield permutations */ - ALLOCV_END(t0); - RBASIC_SET_CLASS_RAW(ary0, rb_cArray); + permute0(n, r, p, used, ary0); /* compute and yield permutations */ + ALLOCV_END(t0); + RBASIC_SET_CLASS_RAW(ary0, rb_cArray); } return ary; } @@ -7196,16 +7196,16 @@ combinate0(const long len, const long n, long *const stack, const VALUE values) MEMZERO(stack+1, long, n); stack[0] = -1; for (;;) { - for (lev++; lev < n; lev++) { - stack[lev+1] = stack[lev]+1; - } - if (!yield_indexed_values(values, n, stack+1)) { - rb_raise(rb_eRuntimeError, "combination reentered"); - } - do { - if (lev == 0) return; - stack[lev--]++; - } while (stack[lev+1]+n == len+lev+1); + for (lev++; lev < n; lev++) { + stack[lev+1] = stack[lev]+1; + } + if (!yield_indexed_values(values, n, stack+1)) { + rb_raise(rb_eRuntimeError, "combination reentered"); + } + do { + if (lev == 0) return; + stack[lev--]++; + } while (stack[lev+1]+n == len+lev+1); } } @@ -7281,25 +7281,25 @@ rb_ary_combination(VALUE ary, VALUE num) RETURN_SIZED_ENUMERATOR(ary, 1, &num, rb_ary_combination_size); len = RARRAY_LEN(ary); if (n < 0 || len < n) { - /* yield nothing */ + /* yield nothing */ } else if (n == 0) { - rb_yield(rb_ary_new2(0)); + rb_yield(rb_ary_new2(0)); } else if (n == 1) { - for (i = 0; i < RARRAY_LEN(ary); i++) { - rb_yield(rb_ary_new3(1, RARRAY_AREF(ary, i))); - } + for (i = 0; i < RARRAY_LEN(ary); i++) { + rb_yield(rb_ary_new3(1, RARRAY_AREF(ary, i))); + } } else { - VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */ - volatile VALUE t0; - long *stack = ALLOCV_N(long, t0, n+1); + VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */ + volatile VALUE t0; + long *stack = ALLOCV_N(long, t0, n+1); - RBASIC_CLEAR_CLASS(ary0); - combinate0(len, n, stack, ary0); - ALLOCV_END(t0); - RBASIC_SET_CLASS_RAW(ary0, rb_cArray); + RBASIC_CLEAR_CLASS(ary0); + combinate0(len, n, stack, ary0); + ALLOCV_END(t0); + RBASIC_SET_CLASS_RAW(ary0, rb_cArray); } return ary; } @@ -7323,19 +7323,19 @@ rpermute0(const long n, const long r, long *const p, const VALUE values) p[index] = i; for (;;) { - if (++index < r-1) { - p[index] = i = 0; - continue; - } - for (i = 0; i < n; ++i) { - p[index] = i; - if (!yield_indexed_values(values, r, p)) { - rb_raise(rb_eRuntimeError, "repeated permute reentered"); - } - } - do { - if (index <= 0) return; - } while ((i = ++p[--index]) >= n); + if (++index < r-1) { + p[index] = i = 0; + continue; + } + for (i = 0; i < n; ++i) { + p[index] = i; + if (!yield_indexed_values(values, r, p)) { + rb_raise(rb_eRuntimeError, "repeated permute reentered"); + } + } + do { + if (index <= 0) return; + } while ((i = ++p[--index]) >= n); } } @@ -7346,10 +7346,10 @@ rb_ary_repeated_permutation_size(VALUE ary, VALUE args, VALUE eobj) long k = NUM2LONG(RARRAY_AREF(args, 0)); if (k < 0) { - return LONG2FIX(0); + return LONG2FIX(0); } if (n <= 0) { - return LONG2FIX(!k); + return LONG2FIX(!k); } return rb_int_positive_pow(n, (unsigned long)k); } @@ -7429,25 +7429,25 @@ rb_ary_repeated_permutation(VALUE ary, VALUE num) r = NUM2LONG(num); /* Permutation size from argument */ if (r < 0) { - /* no permutations: yield nothing */ + /* no permutations: yield nothing */ } else if (r == 0) { /* exactly one permutation: the zero-length array */ - rb_yield(rb_ary_new2(0)); + rb_yield(rb_ary_new2(0)); } else if (r == 1) { /* this is a special, easy case */ - for (i = 0; i < RARRAY_LEN(ary); i++) { - rb_yield(rb_ary_new3(1, RARRAY_AREF(ary, i))); - } + for (i = 0; i < RARRAY_LEN(ary); i++) { + rb_yield(rb_ary_new3(1, RARRAY_AREF(ary, i))); + } } else { /* this is the general case */ - volatile VALUE t0; - long *p = ALLOCV_N(long, t0, r); - VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */ - RBASIC_CLEAR_CLASS(ary0); + volatile VALUE t0; + long *p = ALLOCV_N(long, t0, r); + VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */ + RBASIC_CLEAR_CLASS(ary0); - rpermute0(n, r, p, ary0); /* compute and yield repeated permutations */ - ALLOCV_END(t0); - RBASIC_SET_CLASS_RAW(ary0, rb_cArray); + rpermute0(n, r, p, ary0); /* compute and yield repeated permutations */ + ALLOCV_END(t0); + RBASIC_SET_CLASS_RAW(ary0, rb_cArray); } return ary; } @@ -7459,19 +7459,19 @@ rcombinate0(const long n, const long r, long *const p, const long rest, const VA p[index] = i; for (;;) { - if (++index < r-1) { - p[index] = i; - continue; - } - for (; i < n; ++i) { - p[index] = i; - if (!yield_indexed_values(values, r, p)) { - rb_raise(rb_eRuntimeError, "repeated combination reentered"); - } - } - do { - if (index <= 0) return; - } while ((i = ++p[--index]) >= n); + if (++index < r-1) { + p[index] = i; + continue; + } + for (; i < n; ++i) { + p[index] = i; + if (!yield_indexed_values(values, r, p)) { + rb_raise(rb_eRuntimeError, "repeated combination reentered"); + } + } + do { + if (index <= 0) return; + } while ((i = ++p[--index]) >= n); } } @@ -7481,7 +7481,7 @@ rb_ary_repeated_combination_size(VALUE ary, VALUE args, VALUE eobj) long n = RARRAY_LEN(ary); long k = NUM2LONG(RARRAY_AREF(args, 0)); if (k == 0) { - return LONG2FIX(1); + return LONG2FIX(1); } return binomial_coefficient(k, n + k - 1); } @@ -7558,28 +7558,28 @@ rb_ary_repeated_combination(VALUE ary, VALUE num) RETURN_SIZED_ENUMERATOR(ary, 1, &num, rb_ary_repeated_combination_size); /* Return enumerator if no block */ len = RARRAY_LEN(ary); if (n < 0) { - /* yield nothing */ + /* yield nothing */ } else if (n == 0) { - rb_yield(rb_ary_new2(0)); + rb_yield(rb_ary_new2(0)); } else if (n == 1) { - for (i = 0; i < RARRAY_LEN(ary); i++) { - rb_yield(rb_ary_new3(1, RARRAY_AREF(ary, i))); - } + for (i = 0; i < RARRAY_LEN(ary); i++) { + rb_yield(rb_ary_new3(1, RARRAY_AREF(ary, i))); + } } else if (len == 0) { - /* yield nothing */ + /* yield nothing */ } else { - volatile VALUE t0; - long *p = ALLOCV_N(long, t0, n); - VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */ - RBASIC_CLEAR_CLASS(ary0); + volatile VALUE t0; + long *p = ALLOCV_N(long, t0, n); + VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */ + RBASIC_CLEAR_CLASS(ary0); - rcombinate0(len, n, p, n, ary0); /* compute and yield repeated combinations */ - ALLOCV_END(t0); - RBASIC_SET_CLASS_RAW(ary0, rb_cArray); + rcombinate0(len, n, p, n, ary0); /* compute and yield repeated combinations */ + ALLOCV_END(t0); + RBASIC_SET_CLASS_RAW(ary0, rb_cArray); } return ary; } @@ -7669,61 +7669,61 @@ rb_ary_product(int argc, VALUE *argv, VALUE ary) /* Otherwise, allocate and fill in an array of results */ if (rb_block_given_p()) { - /* Make defensive copies of arrays; exit if any is empty */ - for (i = 0; i < n; i++) { - if (RARRAY_LEN(arrays[i]) == 0) goto done; - arrays[i] = ary_make_shared_copy(arrays[i]); - } + /* Make defensive copies of arrays; exit if any is empty */ + for (i = 0; i < n; i++) { + if (RARRAY_LEN(arrays[i]) == 0) goto done; + arrays[i] = ary_make_shared_copy(arrays[i]); + } } else { - /* Compute the length of the result array; return [] if any is empty */ - for (i = 0; i < n; i++) { - long k = RARRAY_LEN(arrays[i]); - if (k == 0) { - result = rb_ary_new2(0); - goto done; - } + /* Compute the length of the result array; return [] if any is empty */ + for (i = 0; i < n; i++) { + long k = RARRAY_LEN(arrays[i]); + if (k == 0) { + result = rb_ary_new2(0); + goto done; + } if (MUL_OVERFLOW_LONG_P(resultlen, k)) - rb_raise(rb_eRangeError, "too big to product"); - resultlen *= k; - } - result = rb_ary_new2(resultlen); + rb_raise(rb_eRangeError, "too big to product"); + resultlen *= k; + } + result = rb_ary_new2(resultlen); } for (;;) { - int m; - /* fill in one subarray */ - VALUE subarray = rb_ary_new2(n); - for (j = 0; j < n; j++) { - rb_ary_push(subarray, rb_ary_entry(arrays[j], counters[j])); - } + int m; + /* fill in one subarray */ + VALUE subarray = rb_ary_new2(n); + for (j = 0; j < n; j++) { + rb_ary_push(subarray, rb_ary_entry(arrays[j], counters[j])); + } - /* put it on the result array */ - if (NIL_P(result)) { + /* put it on the result array */ + if (NIL_P(result)) { FL_SET(t0, RARRAY_SHARED_ROOT_FLAG); - rb_yield(subarray); + rb_yield(subarray); if (!FL_TEST(t0, RARRAY_SHARED_ROOT_FLAG)) { - rb_raise(rb_eRuntimeError, "product reentered"); - } - else { + rb_raise(rb_eRuntimeError, "product reentered"); + } + else { FL_UNSET(t0, RARRAY_SHARED_ROOT_FLAG); - } - } - else { - rb_ary_push(result, subarray); - } + } + } + else { + rb_ary_push(result, subarray); + } - /* - * Increment the last counter. If it overflows, reset to 0 - * and increment the one before it. - */ - m = n-1; - counters[m]++; - while (counters[m] == RARRAY_LEN(arrays[m])) { - counters[m] = 0; - /* If the first counter overflows, we are done */ - if (--m < 0) goto done; - counters[m]++; - } + /* + * Increment the last counter. If it overflows, reset to 0 + * and increment the one before it. + */ + m = n-1; + counters[m]++; + while (counters[m] == RARRAY_LEN(arrays[m])) { + counters[m] = 0; + /* If the first counter overflows, we are done */ + if (--m < 0) goto done; + counters[m]++; + } } done: tmpary_discard(t0); @@ -7755,7 +7755,7 @@ rb_ary_take(VALUE obj, VALUE n) { long len = NUM2LONG(n); if (len < 0) { - rb_raise(rb_eArgError, "attempt to take negative size"); + rb_raise(rb_eArgError, "attempt to take negative size"); } return rb_ary_subseq(obj, 0, len); } @@ -7790,7 +7790,7 @@ rb_ary_take_while(VALUE ary) RETURN_ENUMERATOR(ary, 0, 0); for (i = 0; i < RARRAY_LEN(ary); i++) { - if (!RTEST(rb_yield(RARRAY_AREF(ary, i)))) break; + if (!RTEST(rb_yield(RARRAY_AREF(ary, i)))) break; } return rb_ary_take(ary, LONG2FIX(i)); } @@ -7818,7 +7818,7 @@ rb_ary_drop(VALUE ary, VALUE n) VALUE result; long pos = NUM2LONG(n); if (pos < 0) { - rb_raise(rb_eArgError, "attempt to drop negative size"); + rb_raise(rb_eArgError, "attempt to drop negative size"); } result = rb_ary_subseq(ary, pos, RARRAY_LEN(ary)); @@ -7854,7 +7854,7 @@ rb_ary_drop_while(VALUE ary) RETURN_ENUMERATOR(ary, 0, 0); for (i = 0; i < RARRAY_LEN(ary); i++) { - if (!RTEST(rb_yield(RARRAY_AREF(ary, i)))) break; + if (!RTEST(rb_yield(RARRAY_AREF(ary, i)))) break; } return rb_ary_drop(ary, LONG2FIX(i)); } @@ -7903,9 +7903,9 @@ rb_ary_any_p(int argc, VALUE *argv, VALUE ary) if (rb_block_given_p()) { rb_warn("given block not used"); } - for (i = 0; i < RARRAY_LEN(ary); ++i) { - if (RTEST(rb_funcall(argv[0], idEqq, 1, RARRAY_AREF(ary, i)))) return Qtrue; - } + for (i = 0; i < RARRAY_LEN(ary); ++i) { + if (RTEST(rb_funcall(argv[0], idEqq, 1, RARRAY_AREF(ary, i)))) return Qtrue; + } } else if (!rb_block_given_p()) { for (i = 0; i < len; ++i) { @@ -7913,9 +7913,9 @@ rb_ary_any_p(int argc, VALUE *argv, VALUE ary) } } else { - for (i = 0; i < RARRAY_LEN(ary); ++i) { - if (RTEST(rb_yield(RARRAY_AREF(ary, i)))) return Qtrue; - } + for (i = 0; i < RARRAY_LEN(ary); ++i) { + if (RTEST(rb_yield(RARRAY_AREF(ary, i)))) return Qtrue; + } } return Qfalse; } diff --git a/bignum.c b/bignum.c index 75651f9524..9901a807b1 100644 --- a/bignum.c +++ b/bignum.c @@ -105,8 +105,8 @@ STATIC_ASSERT(sizeof_long_and_sizeof_bdigit, SIZEOF_BDIGIT % SIZEOF_LONG == 0); #endif #define BIGZEROP(x) (BIGNUM_LEN(x) == 0 || \ - (BDIGITS(x)[0] == 0 && \ - (BIGNUM_LEN(x) == 1 || bigzero_p(x)))) + (BDIGITS(x)[0] == 0 && \ + (BIGNUM_LEN(x) == 1 || bigzero_p(x)))) #define BIGSIZE(x) (BIGNUM_LEN(x) == 0 ? (size_t)0 : \ BDIGITS(x)[BIGNUM_LEN(x)-1] ? \ (size_t)(BIGNUM_LEN(x)*SIZEOF_BDIGIT - nlz(BDIGITS(x)[BIGNUM_LEN(x)-1])/CHAR_BIT) : \ @@ -419,9 +419,9 @@ bary_small_lshift(BDIGIT *zds, const BDIGIT *xds, size_t n, int shift) assert(0 <= shift && shift < BITSPERDIG); for (i=0; i> shift; + num = (num | x) >> shift; zds[n - i - 1] = BIGLO(num); - num = BIGUP(x); + num = BIGUP(x); } } @@ -449,7 +449,7 @@ bary_zero_p(const BDIGIT *xds, size_t xn) if (xn == 0) return 1; do { - if (xds[--xn]) return 0; + if (xds[--xn]) return 0; } while (xn); return 1; } @@ -1350,9 +1350,9 @@ bary_subb(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn, const BDIGIT *yd num = borrow ? -1 : 0; for (i = 0; i < sn; i++) { - num += (BDIGIT_DBL_SIGNED)xds[i] - yds[i]; - zds[i] = BIGLO(num); - num = BIGDN(num); + num += (BDIGIT_DBL_SIGNED)xds[i] - yds[i]; + zds[i] = BIGLO(num); + num = BIGDN(num); } if (yn <= xn) { for (; i < xn; i++) { @@ -1371,7 +1371,7 @@ bary_subb(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn, const BDIGIT *yd } if (num == 0) goto num_is_zero; for (; i < zn; i++) { - zds[i] = BDIGMAX; + zds[i] = BDIGMAX; } return 1; @@ -1379,10 +1379,10 @@ bary_subb(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn, const BDIGIT *yd if (xds == zds && xn == zn) return 0; for (; i < xn; i++) { - zds[i] = xds[i]; + zds[i] = xds[i]; } for (; i < zn; i++) { - zds[i] = 0; + zds[i] = 0; } return 0; } @@ -1409,27 +1409,27 @@ bary_addc(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn, const BDIGIT *yd assert(yn <= zn); if (xn > yn) { - const BDIGIT *tds; - tds = xds; xds = yds; yds = tds; - i = xn; xn = yn; yn = i; + const BDIGIT *tds; + tds = xds; xds = yds; yds = tds; + i = xn; xn = yn; yn = i; } num = carry ? 1 : 0; for (i = 0; i < xn; i++) { - num += (BDIGIT_DBL)xds[i] + yds[i]; - zds[i] = BIGLO(num); - num = BIGDN(num); + num += (BDIGIT_DBL)xds[i] + yds[i]; + zds[i] = BIGLO(num); + num = BIGDN(num); } for (; i < yn; i++) { if (num == 0) goto num_is_zero; - num += yds[i]; - zds[i] = BIGLO(num); - num = BIGDN(num); + num += yds[i]; + zds[i] = BIGLO(num); + num = BIGDN(num); } for (; i < zn; i++) { if (num == 0) goto num_is_zero; - zds[i] = BIGLO(num); - num = BIGDN(num); + zds[i] = BIGLO(num); + num = BIGDN(num); } return num != 0; @@ -1437,10 +1437,10 @@ bary_addc(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn, const BDIGIT *yd if (yds == zds && yn == zn) return 0; for (; i < yn; i++) { - zds[i] = yds[i]; + zds[i] = yds[i]; } for (; i < zn; i++) { - zds[i] = 0; + zds[i] = 0; } return 0; } @@ -1597,30 +1597,30 @@ bary_sq_fast(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn) return; for (i = 0; i < xn-1; i++) { - v = (BDIGIT_DBL)xds[i]; - if (!v) + v = (BDIGIT_DBL)xds[i]; + if (!v) continue; - c = (BDIGIT_DBL)zds[i + i] + v * v; - zds[i + i] = BIGLO(c); - c = BIGDN(c); - v *= 2; + c = (BDIGIT_DBL)zds[i + i] + v * v; + zds[i + i] = BIGLO(c); + c = BIGDN(c); + v *= 2; vl = BIGLO(v); vh = (int)BIGDN(v); - for (j = i + 1; j < xn; j++) { - w = (BDIGIT_DBL)xds[j]; - c += (BDIGIT_DBL)zds[i + j] + vl * w; - zds[i + j] = BIGLO(c); - c = BIGDN(c); - if (vh) + for (j = i + 1; j < xn; j++) { + w = (BDIGIT_DBL)xds[j]; + c += (BDIGIT_DBL)zds[i + j] + vl * w; + zds[i + j] = BIGLO(c); + c = BIGDN(c); + if (vh) c += w; - } - if (c) { - c += (BDIGIT_DBL)zds[i + xn]; - zds[i + xn] = BIGLO(c); - c = BIGDN(c); + } + if (c) { + c += (BDIGIT_DBL)zds[i + xn]; + zds[i + xn] = BIGLO(c); + c = BIGDN(c); if (c) zds[i + xn + 1] += (BDIGIT)c; - } + } } /* i == xn-1 */ @@ -1710,7 +1710,7 @@ bary_mul_balance_with_mulfunc(BDIGIT *const zds, const size_t zn, zds + n, tn, wds, xn); } - n += r; + n += r; } BDIGITS_ZERO(zds+xn+yn, zn - (xn+yn)); @@ -2102,21 +2102,21 @@ bary_mul_toom3(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn, const BDIGI v3n = u3n; v3ds = u3ds; v3p = u3p; } else { - /* v1 <- y0 + y2 */ + /* v1 <- y0 + y2 */ bary_add(v1ds, v1n, y0ds, y0n, y2ds, y2n); v1p = 1; - /* y(-1) : v2 <- v1 - y1 = y0 - y1 + y2 */ + /* y(-1) : v2 <- v1 - y1 = y0 - y1 + y2 */ v2p = 1; if (bary_sub(v2ds, v2n, v1ds, v1n, y1ds, y1n)) { bary_2comp(v2ds, v2n); v2p = 0; } - /* y(1) : v1 <- v1 + y1 = y0 + y1 + y2 */ + /* y(1) : v1 <- v1 + y1 = y0 + y1 + y2 */ bary_add(v1ds, v1n, v1ds, v1n, y1ds, y1n); - /* y(-2) : v3 <- 2 * (v2 + y2) - y0 = y0 - 2 * (y1 - 2 * y2) */ + /* y(-2) : v3 <- 2 * (v2 + y2) - y0 = y0 - 2 * (y1 - 2 * y2) */ v3p = 1; if (v2p) { bary_add(v3ds, v3n, v2ds, v2n, y2ds, y2n); @@ -2447,8 +2447,8 @@ bary_mul_precheck(BDIGIT **zdsp, size_t *znp, const BDIGIT **xdsp, size_t *xnp, if (xn > yn) { const BDIGIT *tds; size_t tn; - tds = xds; xds = yds; yds = tds; - tn = xn; xn = yn; yn = tn; + tds = xds; xds = yds; yds = tds; + tn = xn; xn = yn; yn = tn; } assert(xn <= yn); @@ -2598,26 +2598,26 @@ bigdivrem1(void *ptr) BDIGIT q; do { - if (bds->stop) { - bds->zn = zn; - return 0; + if (bds->stop) { + bds->zn = zn; + return 0; } - if (zds[zn-1] == yds[yn-1]) q = BDIGMAX; - else q = (BDIGIT)((BIGUP(zds[zn-1]) + zds[zn-2])/yds[yn-1]); - if (q) { + if (zds[zn-1] == yds[yn-1]) q = BDIGMAX; + else q = (BDIGIT)((BIGUP(zds[zn-1]) + zds[zn-2])/yds[yn-1]); + if (q) { num = bigdivrem_mulsub(zds+zn-(yn+1), yn+1, q, yds, yn); - while (num) { /* "add back" required */ - q--; + while (num) { /* "add back" required */ + q--; num = bary_add(zds+zn-(yn+1), yn, zds+zn-(yn+1), yn, yds, yn); num--; - } - } + } + } zn--; - zds[zn] = q; + zds[zn] = q; } while (zn > yn); return 0; } @@ -2686,16 +2686,16 @@ bigdivrem_restoring(BDIGIT *zds, size_t zn, BDIGIT *yds, size_t yn) bds.zn = zn - ynzero; if (bds.zn > 10000 || bds.yn > 10000) { retry: - bds.stop = Qfalse; + bds.stop = Qfalse; rb_nogvl(bigdivrem1, &bds, rb_big_stop, &bds, RB_NOGVL_UBF_ASYNC_SAFE); - if (bds.stop == Qtrue) { - /* execute trap handler, but exception was not raised. */ - goto retry; - } + if (bds.stop == Qtrue) { + /* execute trap handler, but exception was not raised. */ + goto retry; + } } else { - bigdivrem1(&bds); + bigdivrem1(&bds); } } @@ -2953,7 +2953,7 @@ int rb_cmpint(VALUE val, VALUE a, VALUE b) { if (NIL_P(val)) { - rb_cmperr(a, b); + rb_cmperr(a, b); } if (FIXNUM_P(val)) { long l = FIX2LONG(val); @@ -2962,9 +2962,9 @@ rb_cmpint(VALUE val, VALUE a, VALUE b) return 0; } if (RB_BIGNUM_TYPE_P(val)) { - if (BIGZEROP(val)) return 0; - if (BIGNUM_SIGN(val)) return 1; - return -1; + if (BIGZEROP(val)) return 0; + if (BIGNUM_SIGN(val)) return 1; + return -1; } if (RTEST(rb_funcall(val, '>', 1, INT2FIX(0)))) return 1; if (RTEST(rb_funcall(val, '<', 1, INT2FIX(0)))) return -1; @@ -2974,8 +2974,8 @@ rb_cmpint(VALUE val, VALUE a, VALUE b) #define BIGNUM_SET_LEN(b,l) \ (BIGNUM_EMBED_P(b) ? \ (void)(RBASIC(b)->flags = \ - (RBASIC(b)->flags & ~BIGNUM_EMBED_LEN_MASK) | \ - ((l) << BIGNUM_EMBED_LEN_SHIFT)) : \ + (RBASIC(b)->flags & ~BIGNUM_EMBED_LEN_MASK) | \ + ((l) << BIGNUM_EMBED_LEN_SHIFT)) : \ (void)(RBIGNUM(b)->as.heap.len = (l))) static void @@ -2983,33 +2983,33 @@ rb_big_realloc(VALUE big, size_t len) { BDIGIT *ds; if (BIGNUM_EMBED_P(big)) { - if (BIGNUM_EMBED_LEN_MAX < len) { - ds = ALLOC_N(BDIGIT, len); - MEMCPY(ds, RBIGNUM(big)->as.ary, BDIGIT, BIGNUM_EMBED_LEN_MAX); - RBIGNUM(big)->as.heap.len = BIGNUM_LEN(big); - RBIGNUM(big)->as.heap.digits = ds; + if (BIGNUM_EMBED_LEN_MAX < len) { + ds = ALLOC_N(BDIGIT, len); + MEMCPY(ds, RBIGNUM(big)->as.ary, BDIGIT, BIGNUM_EMBED_LEN_MAX); + RBIGNUM(big)->as.heap.len = BIGNUM_LEN(big); + RBIGNUM(big)->as.heap.digits = ds; FL_UNSET_RAW(big, BIGNUM_EMBED_FLAG); - } + } } else { - if (len <= BIGNUM_EMBED_LEN_MAX) { - ds = RBIGNUM(big)->as.heap.digits; + if (len <= BIGNUM_EMBED_LEN_MAX) { + ds = RBIGNUM(big)->as.heap.digits; FL_SET_RAW(big, BIGNUM_EMBED_FLAG); - BIGNUM_SET_LEN(big, len); + BIGNUM_SET_LEN(big, len); (void)VALGRIND_MAKE_MEM_UNDEFINED((void*)RBIGNUM(big)->as.ary, sizeof(RBIGNUM(big)->as.ary)); - if (ds) { - MEMCPY(RBIGNUM(big)->as.ary, ds, BDIGIT, len); - xfree(ds); - } - } - else { - if (BIGNUM_LEN(big) == 0) { - RBIGNUM(big)->as.heap.digits = ALLOC_N(BDIGIT, len); - } - else { - REALLOC_N(RBIGNUM(big)->as.heap.digits, BDIGIT, len); - } - } + if (ds) { + MEMCPY(RBIGNUM(big)->as.ary, ds, BDIGIT, len); + xfree(ds); + } + } + else { + if (BIGNUM_LEN(big) == 0) { + RBIGNUM(big)->as.heap.digits = ALLOC_N(BDIGIT, len); + } + else { + REALLOC_N(RBIGNUM(big)->as.heap.digits, BDIGIT, len); + } + } } } @@ -3095,7 +3095,7 @@ abs2twocomp(VALUE *xp, long *n_ret) MEMCPY(BDIGITS(z), ds, BDIGIT, n); bary_2comp(BDIGITS(z), n); hibits = BDIGMAX; - *xp = z; + *xp = z; } *n_ret = n; return hibits; @@ -3119,7 +3119,7 @@ bigtrunc(VALUE x) if (len == 0) return x; while (--len && !ds[len]); if (BIGNUM_LEN(x) > len+1) { - rb_big_resize(x, len+1); + rb_big_resize(x, len+1); } return x; } @@ -3172,7 +3172,7 @@ static VALUE bignorm(VALUE x) { if (RB_BIGNUM_TYPE_P(x)) { - x = bigfixize(x); + x = bigfixize(x); } return x; } @@ -3194,8 +3194,8 @@ rb_uint2big(uintptr_t n) digits[0] = n; #else for (i = 0; i < bdigit_roomof(SIZEOF_VALUE); i++) { - digits[i] = BIGLO(n); - n = BIGDN(n); + digits[i] = BIGLO(n); + n = BIGDN(n); } #endif @@ -3214,14 +3214,14 @@ rb_int2big(intptr_t n) if (n < 0) { u = 1 + (VALUE)(-(n + 1)); /* u = -n avoiding overflow */ - neg = 1; + neg = 1; } else { u = n; } big = rb_uint2big(u); if (neg) { - BIGNUM_SET_NEGATIVE_SIGN(big); + BIGNUM_SET_NEGATIVE_SIGN(big); } return big; } @@ -3380,7 +3380,7 @@ absint_numwords_generic(size_t numbytes, int nlz_bits_in_msbyte, size_t word_num if (sign == 2) { #if defined __GNUC__ && (__GNUC__ == 4 && __GNUC_MINOR__ == 4) - *nlz_bits_ret = 0; + *nlz_bits_ret = 0; #endif return (size_t)-1; } @@ -3700,7 +3700,7 @@ rb_integer_unpack(const void *words, size_t numwords, size_t wordsize, size_t na } else if (num_bdigits == numberof(fixbuf)) { val = bignew((long)num_bdigits+1, 0); - MEMCPY(BDIGITS(val), fixbuf, BDIGIT, num_bdigits); + MEMCPY(BDIGITS(val), fixbuf, BDIGIT, num_bdigits); BDIGITS(val)[num_bdigits++] = 1; } else { @@ -3712,9 +3712,9 @@ rb_integer_unpack(const void *words, size_t numwords, size_t wordsize, size_t na BDIGIT_DBL u = fixbuf[0] + BIGUP(fixbuf[1]); if (u == 0) return LONG2FIX(0); - if (0 < sign && POSFIXABLE(u)) + if (0 < sign && POSFIXABLE(u)) return LONG2FIX((long)u); - if (sign < 0 && BDIGIT_MSB(fixbuf[1]) == 0 && + if (sign < 0 && BDIGIT_MSB(fixbuf[1]) == 0 && NEGFIXABLE(-(BDIGIT_DBL_SIGNED)u)) return LONG2FIX((long)-(BDIGIT_DBL_SIGNED)u); val = bignew((long)num_bdigits, 0 <= sign); @@ -3766,41 +3766,41 @@ str2big_scan_digits(const char *s, const char *str, int base, int badcheck, size int c; if (!len) { - *num_digits_p = 0; - *len_p = 0; - return TRUE; + *num_digits_p = 0; + *len_p = 0; + return TRUE; } if (badcheck && *str == '_') return FALSE; while ((c = *str++) != 0) { - if (c == '_') { - if (nondigit) { + if (c == '_') { + if (nondigit) { if (badcheck) return FALSE; - break; - } - nondigit = (char) c; - } - else if ((c = conv_digit(c)) < 0 || c >= base) { - break; - } - else { - nondigit = 0; - num_digits++; - digits_end = str; - } - if (len > 0 && !--len) break; + break; + } + nondigit = (char) c; + } + else if ((c = conv_digit(c)) < 0 || c >= base) { + break; + } + else { + nondigit = 0; + num_digits++; + digits_end = str; + } + if (len > 0 && !--len) break; } if (badcheck && nondigit) return FALSE; if (badcheck && len) { - str--; - while (*str && ISSPACE(*str)) { - str++; - if (len > 0 && !--len) break; - } - if (len && *str) { - return FALSE; - } + str--; + while (*str && ISSPACE(*str)) { + str++; + if (len > 0 && !--len) break; + } + if (len && *str) { + return FALSE; + } } *num_digits_p = num_digits; *len_p = digits_end - digits_start; @@ -4042,8 +4042,8 @@ rb_cstr_to_inum(const char *str, int base, int badcheck) char *end; VALUE ret = rb_cstr_parse_inum(str, -1, (badcheck ? NULL : &end), base); if (NIL_P(ret)) { - if (badcheck) rb_invalid_str(str, "Integer()"); - ret = INT2FIX(0); + if (badcheck) rb_invalid_str(str, "Integer()"); + ret = INT2FIX(0); } return ret; } @@ -4067,7 +4067,7 @@ rb_cstr_to_inum(const char *str, int base, int badcheck) VALUE rb_int_parse_cstr(const char *str, ssize_t len, char **endp, size_t *ndigits, - int base, int flags) + int base, int flags) { const char *const s = str; char sign = 1; @@ -4084,82 +4084,82 @@ rb_int_parse_cstr(const char *str, ssize_t len, char **endp, size_t *ndigits, const int badcheck = !endp; #define ADV(n) do {\ - if (len > 0 && len <= (n)) goto bad; \ - str += (n); \ - len -= (n); \ + if (len > 0 && len <= (n)) goto bad; \ + str += (n); \ + len -= (n); \ } while (0) #define ASSERT_LEN() do {\ - assert(len != 0); \ - if (len0 >= 0) assert(s + len0 == str + len); \ + assert(len != 0); \ + if (len0 >= 0) assert(s + len0 == str + len); \ } while (0) if (!str) { goto bad; } if (len && (flags & RB_INT_PARSE_SIGN)) { - while (ISSPACE(*str)) ADV(1); + while (ISSPACE(*str)) ADV(1); - if (str[0] == '+') { - ADV(1); - } - else if (str[0] == '-') { - ADV(1); - sign = 0; - } - ASSERT_LEN(); + if (str[0] == '+') { + ADV(1); + } + else if (str[0] == '-') { + ADV(1); + sign = 0; + } + ASSERT_LEN(); } if (base <= 0) { - if (str[0] == '0' && len > 1) { - switch (str[1]) { - case 'x': case 'X': - base = 16; - ADV(2); - break; - case 'b': case 'B': - base = 2; - ADV(2); - break; - case 'o': case 'O': - base = 8; - ADV(2); - break; - case 'd': case 'D': - base = 10; - ADV(2); - break; - default: - base = 8; - } - } - else if (base < -1) { - base = -base; - } - else { - base = 10; - } + if (str[0] == '0' && len > 1) { + switch (str[1]) { + case 'x': case 'X': + base = 16; + ADV(2); + break; + case 'b': case 'B': + base = 2; + ADV(2); + break; + case 'o': case 'O': + base = 8; + ADV(2); + break; + case 'd': case 'D': + base = 10; + ADV(2); + break; + default: + base = 8; + } + } + else if (base < -1) { + base = -base; + } + else { + base = 10; + } } else if (len == 1 || !(flags & RB_INT_PARSE_PREFIX)) { - /* no prefix */ + /* no prefix */ } else if (base == 2) { - if (str[0] == '0' && (str[1] == 'b'||str[1] == 'B')) { - ADV(2); - } + if (str[0] == '0' && (str[1] == 'b'||str[1] == 'B')) { + ADV(2); + } } else if (base == 8) { - if (str[0] == '0' && (str[1] == 'o'||str[1] == 'O')) { - ADV(2); - } + if (str[0] == '0' && (str[1] == 'o'||str[1] == 'O')) { + ADV(2); + } } else if (base == 10) { - if (str[0] == '0' && (str[1] == 'd'||str[1] == 'D')) { - ADV(2); - } + if (str[0] == '0' && (str[1] == 'd'||str[1] == 'D')) { + ADV(2); + } } else if (base == 16) { - if (str[0] == '0' && (str[1] == 'x'||str[1] == 'X')) { - ADV(2); - } + if (str[0] == '0' && (str[1] == 'x'||str[1] == 'X')) { + ADV(2); + } } if (!valid_radix_p(base)) { invalid_radix(base); @@ -4167,73 +4167,73 @@ rb_int_parse_cstr(const char *str, ssize_t len, char **endp, size_t *ndigits, if (!len) goto bad; num_digits = str - s; if (*str == '0' && len != 1) { /* squeeze preceding 0s */ - int us = 0; - const char *end = len < 0 ? NULL : str + len; - ++num_digits; - while ((c = *++str) == '0' || - ((flags & RB_INT_PARSE_UNDERSCORE) && c == '_')) { - if (c == '_') { - if (++us >= 2) - break; - } - else { - ++num_digits; - us = 0; - } - if (str == end) break; - } - if (!c || ISSPACE(c)) --str; - if (end) len = end - str; - ASSERT_LEN(); + int us = 0; + const char *end = len < 0 ? NULL : str + len; + ++num_digits; + while ((c = *++str) == '0' || + ((flags & RB_INT_PARSE_UNDERSCORE) && c == '_')) { + if (c == '_') { + if (++us >= 2) + break; + } + else { + ++num_digits; + us = 0; + } + if (str == end) break; + } + if (!c || ISSPACE(c)) --str; + if (end) len = end - str; + ASSERT_LEN(); } c = *str; c = conv_digit(c); if (c < 0 || c >= base) { - if (!badcheck && num_digits) z = INT2FIX(0); - goto bad; + if (!badcheck && num_digits) z = INT2FIX(0); + goto bad; } if (ndigits) *ndigits = num_digits; val = ruby_scan_digits(str, len, base, &num_digits, &ov); if (!ov) { - const char *end = &str[num_digits]; - if (num_digits > 0 && *end == '_' && (flags & RB_INT_PARSE_UNDERSCORE)) - goto bigparse; - if (endp) *endp = (char *)end; - if (ndigits) *ndigits += num_digits; - if (badcheck) { - if (num_digits == 0) return Qnil; /* no number */ - while (len < 0 ? *end : end < str + len) { - if (!ISSPACE(*end)) return Qnil; /* trailing garbage */ - end++; - } - } + const char *end = &str[num_digits]; + if (num_digits > 0 && *end == '_' && (flags & RB_INT_PARSE_UNDERSCORE)) + goto bigparse; + if (endp) *endp = (char *)end; + if (ndigits) *ndigits += num_digits; + if (badcheck) { + if (num_digits == 0) return Qnil; /* no number */ + while (len < 0 ? *end : end < str + len) { + if (!ISSPACE(*end)) return Qnil; /* trailing garbage */ + end++; + } + } - if (POSFIXABLE(val)) { - if (sign) return LONG2FIX(val); - else { - long result = -(long)val; - return LONG2FIX(result); - } - } - else { - VALUE big = rb_uint2big(val); - BIGNUM_SET_SIGN(big, sign); - return bignorm(big); - } + if (POSFIXABLE(val)) { + if (sign) return LONG2FIX(val); + else { + long result = -(long)val; + return LONG2FIX(result); + } + } + else { + VALUE big = rb_uint2big(val); + BIGNUM_SET_SIGN(big, sign); + return bignorm(big); + } } bigparse: digits_start = str; if (!str2big_scan_digits(s, str, base, badcheck, &num_digits, &len)) - goto bad; + goto bad; if (endp) *endp = (char *)(str + len); if (ndigits) *ndigits += num_digits; digits_end = digits_start + len; if (POW2_P(base)) { z = str2big_poweroftwo(sign, digits_start, digits_end, num_digits, - bit_length(base-1)); + bit_length(base-1)); } else { int digits_per_bdigits_dbl; @@ -4269,7 +4269,7 @@ static VALUE rb_cstr_parse_inum(const char *str, ssize_t len, char **endp, int base) { return rb_int_parse_cstr(str, len, endp, NULL, base, - RB_INT_PARSE_DEFAULT); + RB_INT_PARSE_DEFAULT); } VALUE @@ -4318,14 +4318,14 @@ rb_str2big_poweroftwo(VALUE arg, int base, int badcheck) s = str = StringValueCStr(arg); len = RSTRING_LEN(arg); if (*str == '-') { - len--; + len--; str++; positive_p = 0; } digits_start = str; if (!str2big_scan_digits(s, str, base, badcheck, &num_digits, &len)) - invalid_integer(arg); + invalid_integer(arg); digits_end = digits_start + len; z = str2big_poweroftwo(positive_p, digits_start, digits_end, num_digits, @@ -4357,14 +4357,14 @@ rb_str2big_normal(VALUE arg, int base, int badcheck) s = str = StringValuePtr(arg); len = RSTRING_LEN(arg); if (len > 0 && *str == '-') { - len--; + len--; str++; positive_p = 0; } digits_start = str; if (!str2big_scan_digits(s, str, base, badcheck, &num_digits, &len)) - invalid_integer(arg); + invalid_integer(arg); digits_end = digits_start + len; maxpow_in_bdigit_dbl(base, &digits_per_bdigits_dbl); @@ -4399,14 +4399,14 @@ rb_str2big_karatsuba(VALUE arg, int base, int badcheck) s = str = StringValuePtr(arg); len = RSTRING_LEN(arg); if (len > 0 && *str == '-') { - len--; + len--; str++; positive_p = 0; } digits_start = str; if (!str2big_scan_digits(s, str, base, badcheck, &num_digits, &len)) - invalid_integer(arg); + invalid_integer(arg); digits_end = digits_start + len; maxpow_in_bdigit_dbl(base, &digits_per_bdigits_dbl); @@ -4442,14 +4442,14 @@ rb_str2big_gmp(VALUE arg, int base, int badcheck) s = str = StringValuePtr(arg); len = RSTRING_LEN(arg); if (len > 0 && *str == '-') { - len--; + len--; str++; positive_p = 0; } digits_start = str; if (!str2big_scan_digits(s, str, base, badcheck, &num_digits, &len)) - invalid_integer(arg); + invalid_integer(arg); digits_end = digits_start + len; maxpow_in_bdigit_dbl(base, &digits_per_bdigits_dbl); @@ -4476,8 +4476,8 @@ rb_ull2big(unsigned LONG_LONG n) digits[0] = n; #else for (i = 0; i < bdigit_roomof(SIZEOF_LONG_LONG); i++) { - digits[i] = BIGLO(n); - n = BIGDN(n); + digits[i] = BIGLO(n); + n = BIGDN(n); } #endif @@ -4496,14 +4496,14 @@ rb_ll2big(LONG_LONG n) if (n < 0) { u = 1 + (unsigned LONG_LONG)(-(n + 1)); /* u = -n avoiding overflow */ - neg = 1; + neg = 1; } else { u = n; } big = rb_ull2big(u); if (neg) { - BIGNUM_SET_NEGATIVE_SIGN(big); + BIGNUM_SET_NEGATIVE_SIGN(big); } return big; } @@ -4533,7 +4533,7 @@ rb_uint128t2big(uint128_t n) BDIGIT *digits = BDIGITS(big); for (i = 0; i < bdigit_roomof(SIZEOF_INT128_T); i++) { - digits[i] = BIGLO(RSHIFT(n ,BITSPERDIG*i)); + digits[i] = BIGLO(RSHIFT(n ,BITSPERDIG*i)); } i = bdigit_roomof(SIZEOF_INT128_T); @@ -4551,14 +4551,14 @@ rb_int128t2big(int128_t n) if (n < 0) { u = 1 + (uint128_t)(-(n + 1)); /* u = -n avoiding overflow */ - neg = 1; + neg = 1; } else { u = n; } big = rb_uint128t2big(u); if (neg) { - BIGNUM_SET_NEGATIVE_SIGN(big); + BIGNUM_SET_NEGATIVE_SIGN(big); } return big; } @@ -4721,7 +4721,7 @@ power_cache_get_power(int base, int power_level, size_t *numdigits_ret) rb_obj_hide(power); base36_power_cache[base - 2][power_level] = power; base36_numdigits_cache[base - 2][power_level] = numdigits; - rb_gc_register_mark_object(power); + rb_gc_register_mark_object(power); } if (numdigits_ret) *numdigits_ret = base36_numdigits_cache[base - 2][power_level]; @@ -4772,7 +4772,7 @@ big2str_2bdigits(struct big2str_struct *b2s, BDIGIT *xds, size_t xn, size_t tail } while (num); len = sizeof(buf) - j; big2str_alloc(b2s, len + taillen); - MEMCPY(b2s->ptr, buf + j, char, len); + MEMCPY(b2s->ptr, buf + j, char, len); } else { p = b2s->ptr; @@ -4789,7 +4789,7 @@ big2str_2bdigits(struct big2str_struct *b2s, BDIGIT *xds, size_t xn, size_t tail static void big2str_karatsuba(struct big2str_struct *b2s, BDIGIT *xds, size_t xn, size_t wn, - int power_level, size_t taillen) + int power_level, size_t taillen) { VALUE b; size_t half_numdigits, lower_numdigits; @@ -4819,17 +4819,17 @@ big2str_karatsuba(struct big2str_struct *b2s, BDIGIT *xds, size_t xn, size_t wn, */ if (xn == 0 || bary_zero_p(xds, xn)) { - if (b2s->ptr) { + if (b2s->ptr) { /* When x is zero, power_cache_get_power(base, power_level) should be cached already. */ power_cache_get_power(b2s->base, power_level, &len); - memset(b2s->ptr, '0', len); + memset(b2s->ptr, '0', len); b2s->ptr += len; - } + } return; } if (power_level == 0) { - big2str_2bdigits(b2s, xds, xn, taillen); + big2str_2bdigits(b2s, xds, xn, taillen); return; } @@ -4857,7 +4857,7 @@ big2str_karatsuba(struct big2str_struct *b2s, BDIGIT *xds, size_t xn, size_t wn, memset(b2s->ptr, '0', len); b2s->ptr += len; } - big2str_2bdigits(b2s, xds, xn, taillen); + big2str_2bdigits(b2s, xds, xn, taillen); } else { BDIGIT *qds, *rds; @@ -4961,11 +4961,11 @@ big2str_generic(VALUE x, int base) BARY_TRUNC(xds, xn); if (xn == 0) { - return rb_usascii_str_new2("0"); + return rb_usascii_str_new2("0"); } if (!valid_radix_p(base)) - invalid_radix(base); + invalid_radix(base); if (xn >= LONG_MAX/BITSPERDIG) { rb_raise(rb_eRangeError, "bignum too big to convert into `string'"); @@ -5002,7 +5002,7 @@ big2str_generic(VALUE x, int base) b2s_data.ptr = NULL; if (power_level == 0) { - big2str_2bdigits(&b2s_data, xds, xn, 0); + big2str_2bdigits(&b2s_data, xds, xn, 0); } else { VALUE tmpw = 0; @@ -5011,7 +5011,7 @@ big2str_generic(VALUE x, int base) wn = power_level * BIGDIVREM_EXTRA_WORDS + BIGNUM_LEN(power); wds = ALLOCV_N(BDIGIT, tmpw, xn + wn); MEMCPY(wds, xds, BDIGIT, xn); - big2str_karatsuba(&b2s_data, wds, xn, wn, power_level, 0); + big2str_karatsuba(&b2s_data, wds, xn, wn, power_level, 0); if (tmpw) ALLOCV_END(tmpw); } @@ -5077,7 +5077,7 @@ rb_big2str1(VALUE x, int base) size_t xn; if (FIXNUM_P(x)) { - return rb_fix2str(x, base); + return rb_fix2str(x, base); } bigtrunc(x); @@ -5086,11 +5086,11 @@ rb_big2str1(VALUE x, int base) BARY_TRUNC(xds, xn); if (xn == 0) { - return rb_usascii_str_new2("0"); + return rb_usascii_str_new2("0"); } if (!valid_radix_p(base)) - invalid_radix(base); + invalid_radix(base); if (xn >= LONG_MAX/BITSPERDIG) { rb_raise(rb_eRangeError, "bignum too big to convert into `string'"); @@ -5137,7 +5137,7 @@ big2ulong(VALUE x, const char *type) #else num = 0; for (i = 0; i < len; i++) { - num <<= BITSPERDIG; + num <<= BITSPERDIG; num += (unsigned long)ds[len - i - 1]; /* overflow is already checked */ } #endif @@ -5190,13 +5190,13 @@ big2ull(VALUE x, const char *type) if (len == 0) return 0; if (BIGSIZE(x) > SIZEOF_LONG_LONG) - rb_raise(rb_eRangeError, "bignum too big to convert into `%s'", type); + rb_raise(rb_eRangeError, "bignum too big to convert into `%s'", type); #if SIZEOF_LONG_LONG <= SIZEOF_BDIGIT num = (unsigned LONG_LONG)ds[0]; #else num = 0; for (i = 0; i < len; i++) { - num = BIGUP(num); + num = BIGUP(num); num += ds[len - i - 1]; } #endif @@ -5246,23 +5246,23 @@ dbl2big(double d) double u = (d < 0)?-d:d; if (isinf(d)) { - rb_raise(rb_eFloatDomainError, d < 0 ? "-Infinity" : "Infinity"); + rb_raise(rb_eFloatDomainError, d < 0 ? "-Infinity" : "Infinity"); } if (isnan(d)) { - rb_raise(rb_eFloatDomainError, "NaN"); + rb_raise(rb_eFloatDomainError, "NaN"); } while (1.0 <= u) { - u /= (double)(BIGRAD); - i++; + u /= (double)(BIGRAD); + i++; } z = bignew(i, d>=0); digits = BDIGITS(z); while (i--) { - u *= BIGRAD; - c = (BDIGIT)u; - u -= c; - digits[i] = c; + u *= BIGRAD; + c = (BDIGIT)u; + u -= c; + digits[i] = c; } return z; @@ -5282,28 +5282,28 @@ big2dbl(VALUE x) BDIGIT *ds = BDIGITS(x), dl; if (i) { - bits = i * BITSPERDIG - nlz(ds[i-1]); - if (bits > DBL_MANT_DIG+DBL_MAX_EXP) { - d = HUGE_VAL; - } - else { - if (bits > DBL_MANT_DIG+1) - lo = (bits -= DBL_MANT_DIG+1) / BITSPERDIG; - else - bits = 0; - while (--i > lo) { - d = ds[i] + BIGRAD*d; - } - dl = ds[i]; - if (bits && (dl & ((BDIGIT)1 << (bits %= BITSPERDIG)))) { - int carry = (dl & ~(BDIGMAX << bits)) != 0; - if (!carry) { - while (i-- > 0) { - carry = ds[i] != 0; - if (carry) break; - } - } - if (carry) { + bits = i * BITSPERDIG - nlz(ds[i-1]); + if (bits > DBL_MANT_DIG+DBL_MAX_EXP) { + d = HUGE_VAL; + } + else { + if (bits > DBL_MANT_DIG+1) + lo = (bits -= DBL_MANT_DIG+1) / BITSPERDIG; + else + bits = 0; + while (--i > lo) { + d = ds[i] + BIGRAD*d; + } + dl = ds[i]; + if (bits && (dl & ((BDIGIT)1 << (bits %= BITSPERDIG)))) { + int carry = (dl & ~(BDIGMAX << bits)) != 0; + if (!carry) { + while (i-- > 0) { + carry = ds[i] != 0; + if (carry) break; + } + } + if (carry) { BDIGIT mask = BDIGMAX; BDIGIT bit = 1; mask <<= bits; @@ -5311,19 +5311,19 @@ big2dbl(VALUE x) dl &= mask; dl += bit; dl = BIGLO(dl); - if (!dl) d += 1; - } - } - d = dl + BIGRAD*d; - if (lo) { - if (lo > INT_MAX / BITSPERDIG) - d = HUGE_VAL; - else if (lo < INT_MIN / BITSPERDIG) - d = 0.0; - else - d = ldexp(d, (int)(lo * BITSPERDIG)); - } - } + if (!dl) d += 1; + } + } + d = dl + BIGRAD*d; + if (lo) { + if (lo > INT_MAX / BITSPERDIG) + d = HUGE_VAL; + else if (lo < INT_MIN / BITSPERDIG) + d = 0.0; + else + d = ldexp(d, (int)(lo * BITSPERDIG)); + } + } } if (BIGNUM_NEGATIVE_P(x)) d = -d; return d; @@ -5335,11 +5335,11 @@ rb_big2dbl(VALUE x) double d = big2dbl(x); if (isinf(d)) { - rb_warning("Integer out of Float range"); - if (d < 0.0) - d = -HUGE_VAL; - else - d = HUGE_VAL; + rb_warning("Integer out of Float range"); + if (d < 0.0) + d = -HUGE_VAL; + else + d = HUGE_VAL; } return d; } @@ -5436,26 +5436,26 @@ VALUE rb_big_cmp(VALUE x, VALUE y) { if (FIXNUM_P(y)) { - x = bigfixize(x); + x = bigfixize(x); if (FIXNUM_P(x)) { - /* SIGNED_VALUE and Fixnum have same sign-bits, same - * order */ - SIGNED_VALUE sx = (SIGNED_VALUE)x, sy = (SIGNED_VALUE)y; - if (sx < sy) return INT2FIX(-1); - return INT2FIX(sx > sy); + /* SIGNED_VALUE and Fixnum have same sign-bits, same + * order */ + SIGNED_VALUE sx = (SIGNED_VALUE)x, sy = (SIGNED_VALUE)y; + if (sx < sy) return INT2FIX(-1); + return INT2FIX(sx > sy); } } else if (RB_BIGNUM_TYPE_P(y)) { - if (BIGNUM_SIGN(x) == BIGNUM_SIGN(y)) { - int cmp = bary_cmp(BDIGITS(x), BIGNUM_LEN(x), BDIGITS(y), BIGNUM_LEN(y)); - return INT2FIX(BIGNUM_SIGN(x) ? cmp : -cmp); - } + if (BIGNUM_SIGN(x) == BIGNUM_SIGN(y)) { + int cmp = bary_cmp(BDIGITS(x), BIGNUM_LEN(x), BDIGITS(y), BIGNUM_LEN(y)); + return INT2FIX(BIGNUM_SIGN(x) ? cmp : -cmp); + } } else if (RB_FLOAT_TYPE_P(y)) { return rb_integer_float_cmp(x, y); } else { - return rb_num_coerce_cmp(x, y, idCmp); + return rb_num_coerce_cmp(x, y, idCmp); } return INT2FIX(BIGNUM_SIGN(x) ? 1 : -1); } @@ -5474,30 +5474,30 @@ big_op(VALUE x, VALUE y, enum big_op_t op) int n; if (RB_INTEGER_TYPE_P(y)) { - rel = rb_big_cmp(x, y); + rel = rb_big_cmp(x, y); } else if (RB_FLOAT_TYPE_P(y)) { rel = rb_integer_float_cmp(x, y); } else { - ID id = 0; - switch (op) { - case big_op_gt: id = '>'; break; - case big_op_ge: id = idGE; break; - case big_op_lt: id = '<'; break; - case big_op_le: id = idLE; break; - } - return rb_num_coerce_relop(x, y, id); + ID id = 0; + switch (op) { + case big_op_gt: id = '>'; break; + case big_op_ge: id = idGE; break; + case big_op_lt: id = '<'; break; + case big_op_le: id = idLE; break; + } + return rb_num_coerce_relop(x, y, id); } if (NIL_P(rel)) return Qfalse; n = FIX2INT(rel); switch (op) { - case big_op_gt: return RBOOL(n > 0); - case big_op_ge: return RBOOL(n >= 0); - case big_op_lt: return RBOOL(n < 0); - case big_op_le: return RBOOL(n <= 0); + case big_op_gt: return RBOOL(n > 0); + case big_op_ge: return RBOOL(n >= 0); + case big_op_lt: return RBOOL(n < 0); + case big_op_le: return RBOOL(n <= 0); } return Qundef; } @@ -5541,7 +5541,7 @@ VALUE rb_big_eq(VALUE x, VALUE y) { if (FIXNUM_P(y)) { - return RBOOL(bignorm(x) == y); + return RBOOL(bignorm(x) == y); } else if (RB_BIGNUM_TYPE_P(y)) { } @@ -5549,7 +5549,7 @@ rb_big_eq(VALUE x, VALUE y) return rb_integer_float_eq(x, y); } else { - return rb_equal(y, x); + return rb_equal(y, x); } if (BIGNUM_SIGN(x) != BIGNUM_SIGN(y)) return Qfalse; if (BIGNUM_LEN(x) != BIGNUM_LEN(y)) return Qfalse; @@ -5656,10 +5656,10 @@ bigsub_int(VALUE x, long y0) assert(xn == zn); num = (BDIGIT_DBL_SIGNED)xds[0] - y; if (xn == 1 && num < 0) { - BIGNUM_NEGATE(z); - zds[0] = (BDIGIT)-num; - RB_GC_GUARD(x); - return bignorm(z); + BIGNUM_NEGATE(z); + zds[0] = (BDIGIT)-num; + RB_GC_GUARD(x); + return bignorm(z); } zds[0] = BIGLO(num); num = BIGDN(num); @@ -5671,10 +5671,10 @@ bigsub_int(VALUE x, long y0) num = 0; for (i=0; i < xn; i++) { if (y == 0) goto y_is_zero_x; - num += (BDIGIT_DBL_SIGNED)xds[i] - BIGLO(y); - zds[i] = BIGLO(num); - num = BIGDN(num); - y = BIGDN(y); + num += (BDIGIT_DBL_SIGNED)xds[i] - BIGLO(y); + zds[i] = BIGLO(num); + num = BIGDN(num); + y = BIGDN(y); } for (; i < zn; i++) { if (y == 0) goto y_is_zero_z; @@ -5689,9 +5689,9 @@ bigsub_int(VALUE x, long y0) for (; i < xn; i++) { y_is_zero_x: if (num == 0) goto num_is_zero_x; - num += xds[i]; - zds[i] = BIGLO(num); - num = BIGDN(num); + num += xds[i]; + zds[i] = BIGLO(num); + num = BIGDN(num); } #if SIZEOF_BDIGIT < SIZEOF_LONG for (; i < zn; i++) { @@ -5705,7 +5705,7 @@ bigsub_int(VALUE x, long y0) for (; i < xn; i++) { num_is_zero_x: - zds[i] = xds[i]; + zds[i] = xds[i]; } #if SIZEOF_BDIGIT < SIZEOF_LONG for (; i < zn; i++) { @@ -5719,7 +5719,7 @@ bigsub_int(VALUE x, long y0) assert(num == 0 || num == -1); if (num < 0) { get2comp(z); - BIGNUM_NEGATE(z); + BIGNUM_NEGATE(z); } RB_GC_GUARD(x); return bignorm(z); @@ -5762,17 +5762,17 @@ bigadd_int(VALUE x, long y) num = 0; for (i=0; i < xn; i++) { if (y == 0) goto y_is_zero_x; - num += (BDIGIT_DBL)xds[i] + BIGLO(y); - zds[i] = BIGLO(num); - num = BIGDN(num); - y = BIGDN(y); + num += (BDIGIT_DBL)xds[i] + BIGLO(y); + zds[i] = BIGLO(num); + num = BIGDN(num); + y = BIGDN(y); } for (; i < zn; i++) { if (y == 0) goto y_is_zero_z; - num += BIGLO(y); - zds[i] = BIGLO(num); - num = BIGDN(num); - y = BIGDN(y); + num += BIGLO(y); + zds[i] = BIGLO(num); + num = BIGDN(num); + y = BIGDN(y); } goto finish; @@ -5781,25 +5781,25 @@ bigadd_int(VALUE x, long y) for (;i < xn; i++) { y_is_zero_x: if (num == 0) goto num_is_zero_x; - num += (BDIGIT_DBL)xds[i]; - zds[i] = BIGLO(num); - num = BIGDN(num); + num += (BDIGIT_DBL)xds[i]; + zds[i] = BIGLO(num); + num = BIGDN(num); } for (; i < zn; i++) { y_is_zero_z: if (num == 0) goto num_is_zero_z; - zds[i] = BIGLO(num); - num = BIGDN(num); + zds[i] = BIGLO(num); + num = BIGDN(num); } goto finish; for (;i < xn; i++) { num_is_zero_x: - zds[i] = xds[i]; + zds[i] = xds[i]; } for (; i < zn; i++) { num_is_zero_z: - zds[i] = 0; + zds[i] = 0; } goto finish; @@ -5816,15 +5816,15 @@ bigadd(VALUE x, VALUE y, int sign) sign = (sign == BIGNUM_SIGN(y)); if (BIGNUM_SIGN(x) != sign) { - if (sign) return bigsub(y, x); - return bigsub(x, y); + if (sign) return bigsub(y, x); + return bigsub(x, y); } if (BIGNUM_LEN(x) > BIGNUM_LEN(y)) { - len = BIGNUM_LEN(x) + 1; + len = BIGNUM_LEN(x) + 1; } else { - len = BIGNUM_LEN(y) + 1; + len = BIGNUM_LEN(y) + 1; } z = bignew(len, sign); @@ -5841,26 +5841,26 @@ rb_big_plus(VALUE x, VALUE y) long n; if (FIXNUM_P(y)) { - n = FIX2LONG(y); - if ((n > 0) != BIGNUM_SIGN(x)) { - if (n < 0) { - n = -n; - } - return bigsub_int(x, n); - } - if (n < 0) { - n = -n; - } - return bigadd_int(x, n); + n = FIX2LONG(y); + if ((n > 0) != BIGNUM_SIGN(x)) { + if (n < 0) { + n = -n; + } + return bigsub_int(x, n); + } + if (n < 0) { + n = -n; + } + return bigadd_int(x, n); } else if (RB_BIGNUM_TYPE_P(y)) { - return bignorm(bigadd(x, y, 1)); + return bignorm(bigadd(x, y, 1)); } else if (RB_FLOAT_TYPE_P(y)) { - return DBL2NUM(rb_big2dbl(x) + RFLOAT_VALUE(y)); + return DBL2NUM(rb_big2dbl(x) + RFLOAT_VALUE(y)); } else { - return rb_num_coerce_bin(x, y, '+'); + return rb_num_coerce_bin(x, y, '+'); } } @@ -5870,26 +5870,26 @@ rb_big_minus(VALUE x, VALUE y) long n; if (FIXNUM_P(y)) { - n = FIX2LONG(y); - if ((n > 0) != BIGNUM_SIGN(x)) { - if (n < 0) { - n = -n; - } - return bigadd_int(x, n); - } - if (n < 0) { - n = -n; - } - return bigsub_int(x, n); + n = FIX2LONG(y); + if ((n > 0) != BIGNUM_SIGN(x)) { + if (n < 0) { + n = -n; + } + return bigadd_int(x, n); + } + if (n < 0) { + n = -n; + } + return bigsub_int(x, n); } else if (RB_BIGNUM_TYPE_P(y)) { - return bignorm(bigadd(x, y, 0)); + return bignorm(bigadd(x, y, 0)); } else if (RB_FLOAT_TYPE_P(y)) { - return DBL2NUM(rb_big2dbl(x) - RFLOAT_VALUE(y)); + return DBL2NUM(rb_big2dbl(x) - RFLOAT_VALUE(y)); } else { - return rb_num_coerce_bin(x, y, '-'); + return rb_num_coerce_bin(x, y, '-'); } } @@ -5948,15 +5948,15 @@ VALUE rb_big_mul(VALUE x, VALUE y) { if (FIXNUM_P(y)) { - y = rb_int2big(FIX2LONG(y)); + y = rb_int2big(FIX2LONG(y)); } else if (RB_BIGNUM_TYPE_P(y)) { } else if (RB_FLOAT_TYPE_P(y)) { - return DBL2NUM(rb_big2dbl(x) * RFLOAT_VALUE(y)); + return DBL2NUM(rb_big2dbl(x) * RFLOAT_VALUE(y)); } else { - return rb_num_coerce_bin(x, y, '*'); + return rb_num_coerce_bin(x, y, '*'); } return bignorm(bigmul0(x, y)); @@ -5983,21 +5983,21 @@ bigdivrem(VALUE x, VALUE y, volatile VALUE *divp, volatile VALUE *modp) BARY_TRUNC(xds, xn); if (xn < yn || (xn == yn && xds[xn - 1] < yds[yn - 1])) { - if (divp) *divp = rb_int2big(0); - if (modp) *modp = x; - return Qnil; + if (divp) *divp = rb_int2big(0); + if (modp) *modp = x; + return Qnil; } if (yn == 1) { - dd = yds[0]; - z = bignew(xn, BIGNUM_SIGN(x)==BIGNUM_SIGN(y)); - zds = BDIGITS(z); + dd = yds[0]; + z = bignew(xn, BIGNUM_SIGN(x)==BIGNUM_SIGN(y)); + zds = BDIGITS(z); dd = bigdivrem_single(zds, xds, xn, dd); - if (modp) { - *modp = rb_uint2big((uintptr_t)dd); - BIGNUM_SET_SIGN(*modp, BIGNUM_SIGN(x)); - } - if (divp) *divp = z; - return Qnil; + if (modp) { + *modp = rb_uint2big((uintptr_t)dd); + BIGNUM_SET_SIGN(*modp, BIGNUM_SIGN(x)); + } + if (divp) *divp = z; + return Qnil; } if (xn == 2 && yn == 2) { BDIGIT_DBL x0 = bary2bdigitdbl(xds, 2); @@ -6062,11 +6062,11 @@ bigdivmod(VALUE x, VALUE y, volatile VALUE *divp, volatile VALUE *modp) bigdivrem(x, y, divp, &mod); if (BIGNUM_SIGN(x) != BIGNUM_SIGN(y) && !BIGZEROP(mod)) { - if (divp) *divp = bigadd(*divp, rb_int2big(1), 0); - if (modp) *modp = bigadd(mod, y, 1); + if (divp) *divp = bigadd(*divp, rb_int2big(1), 0); + if (modp) *modp = bigadd(mod, y, 1); } else if (modp) { - *modp = mod; + *modp = mod; } } @@ -6077,25 +6077,25 @@ rb_big_divide(VALUE x, VALUE y, ID op) VALUE z; if (FIXNUM_P(y)) { - y = rb_int2big(FIX2LONG(y)); + y = rb_int2big(FIX2LONG(y)); } else if (RB_BIGNUM_TYPE_P(y)) { } else if (RB_FLOAT_TYPE_P(y)) { - if (op == '/') { + if (op == '/') { double dx = rb_big2dbl(x); return rb_flo_div_flo(DBL2NUM(dx), y); - } - else { + } + else { VALUE v; - double dy = RFLOAT_VALUE(y); - if (dy == 0.0) rb_num_zerodiv(); + double dy = RFLOAT_VALUE(y); + if (dy == 0.0) rb_num_zerodiv(); v = rb_big_divide(x, y, '/'); return rb_dbl2big(RFLOAT_VALUE(v)); - } + } } else { - return rb_num_coerce_bin(x, y, op); + return rb_num_coerce_bin(x, y, op); } bigdivmod(x, y, &z, 0); @@ -6120,10 +6120,10 @@ rb_big_modulo(VALUE x, VALUE y) VALUE z; if (FIXNUM_P(y)) { - y = rb_int2big(FIX2LONG(y)); + y = rb_int2big(FIX2LONG(y)); } else if (!RB_BIGNUM_TYPE_P(y)) { - return rb_num_coerce_bin(x, y, '%'); + return rb_num_coerce_bin(x, y, '%'); } bigdivmod(x, y, 0, &z); @@ -6136,10 +6136,10 @@ rb_big_remainder(VALUE x, VALUE y) VALUE z; if (FIXNUM_P(y)) { - y = rb_int2big(FIX2LONG(y)); + y = rb_int2big(FIX2LONG(y)); } else if (!RB_BIGNUM_TYPE_P(y)) { - return rb_num_coerce_bin(x, y, rb_intern("remainder")); + return rb_num_coerce_bin(x, y, rb_intern("remainder")); } bigdivrem(x, y, 0, &z); @@ -6152,7 +6152,7 @@ rb_big_divmod(VALUE x, VALUE y) VALUE div, mod; if (FIXNUM_P(y)) { - y = rb_int2big(FIX2LONG(y)); + y = rb_int2big(FIX2LONG(y)); } else if (!RB_BIGNUM_TYPE_P(y)) { return rb_num_coerce_bin(x, y, idDivmod); @@ -6166,9 +6166,9 @@ static VALUE big_shift(VALUE x, long n) { if (n < 0) - return big_lshift(x, 1+(unsigned long)(-(n+1))); + return big_lshift(x, 1+(unsigned long)(-(n+1))); else if (n > 0) - return big_rshift(x, (unsigned long)n); + return big_rshift(x, (unsigned long)n); return x; } @@ -6192,9 +6192,9 @@ big_fdiv(VALUE x, VALUE y, long ey) l = ex - ey; #if SIZEOF_LONG > SIZEOF_INT { - /* Visual C++ can't be here */ - if (l > INT_MAX) return HUGE_VAL; - if (l < INT_MIN) return 0.0; + /* Visual C++ can't be here */ + if (l > INT_MAX) return HUGE_VAL; + if (l < INT_MIN) return 0.0; } #endif return ldexp(big2dbl(z), (int)l); @@ -6228,19 +6228,19 @@ rb_big_fdiv_double(VALUE x, VALUE y) dx = big2dbl(x); if (FIXNUM_P(y)) { - dy = (double)FIX2LONG(y); - if (isinf(dx)) - return big_fdiv_int(x, rb_int2big(FIX2LONG(y))); + dy = (double)FIX2LONG(y); + if (isinf(dx)) + return big_fdiv_int(x, rb_int2big(FIX2LONG(y))); } else if (RB_BIGNUM_TYPE_P(y)) { - return big_fdiv_int(x, y); + return big_fdiv_int(x, y); } else if (RB_FLOAT_TYPE_P(y)) { - dy = RFLOAT_VALUE(y); - if (isnan(dy)) - return dy; - if (isinf(dx)) - return big_fdiv_float(x, y); + dy = RFLOAT_VALUE(y); + if (isnan(dy)) + return dy; + if (isinf(dx)) + return big_fdiv_float(x, y); } else { return NUM2DBL(rb_num_coerce_bin(x, y, idFdiv)); @@ -6265,20 +6265,20 @@ rb_big_pow(VALUE x, VALUE y) if (y == INT2FIX(0)) return INT2FIX(1); if (y == INT2FIX(1)) return x; if (RB_FLOAT_TYPE_P(y)) { - d = RFLOAT_VALUE(y); - if ((BIGNUM_NEGATIVE_P(x) && !BIGZEROP(x))) { + d = RFLOAT_VALUE(y); + if ((BIGNUM_NEGATIVE_P(x) && !BIGZEROP(x))) { return rb_dbl_complex_new_polar_pi(pow(-rb_big2dbl(x), d), d); - } + } } else if (RB_BIGNUM_TYPE_P(y)) { - y = bignorm(y); - if (FIXNUM_P(y)) - goto again; - rb_warn("in a**b, b may be too big"); - d = rb_big2dbl(y); + y = bignorm(y); + if (FIXNUM_P(y)) + goto again; + rb_warn("in a**b, b may be too big"); + d = rb_big2dbl(y); } else if (FIXNUM_P(y)) { - yy = FIX2LONG(y); + yy = FIX2LONG(y); if (yy < 0) { x = rb_big_pow(x, LONG2NUM(-yy)); @@ -6287,31 +6287,31 @@ rb_big_pow(VALUE x, VALUE y) else return DBL2NUM(1.0 / NUM2DBL(x)); } - else { - VALUE z = 0; - SIGNED_VALUE mask; + else { + VALUE z = 0; + SIGNED_VALUE mask; const size_t xbits = rb_absint_numwords(x, 1, NULL); - const size_t BIGLEN_LIMIT = 32*1024*1024; + const size_t BIGLEN_LIMIT = 32*1024*1024; - if (xbits == (size_t)-1 || + if (xbits == (size_t)-1 || (xbits > BIGLEN_LIMIT) || (xbits * yy > BIGLEN_LIMIT)) { - rb_warn("in a**b, b may be too big"); - d = (double)yy; - } - else { - for (mask = FIXNUM_MAX + 1; mask; mask >>= 1) { - if (z) z = bigsq(z); - if (yy & mask) { - z = z ? bigtrunc(bigmul0(z, x)) : x; - } - } - return bignorm(z); - } - } + rb_warn("in a**b, b may be too big"); + d = (double)yy; + } + else { + for (mask = FIXNUM_MAX + 1; mask; mask >>= 1) { + if (z) z = bigsq(z); + if (yy & mask) { + z = z ? bigtrunc(bigmul0(z, x)) : x; + } + } + return bignorm(z); + } + } } else { - return rb_num_coerce_bin(x, y, idPow); + return rb_num_coerce_bin(x, y, idPow); } return DBL2NUM(pow(rb_big2dbl(x), d)); } @@ -6331,8 +6331,8 @@ bigand_int(VALUE x, long xn, BDIGIT hibitsx, long y) xds = BDIGITS(x); #if SIZEOF_BDIGIT >= SIZEOF_LONG if (!hibitsy) { - y &= xds[0]; - return LONG2NUM(y); + y &= xds[0]; + return LONG2NUM(y); } #endif @@ -6361,10 +6361,10 @@ bigand_int(VALUE x, long xn, BDIGIT hibitsx, long y) } #endif for (;i < xn; i++) { - zds[i] = xds[i] & hibitsy; + zds[i] = xds[i] & hibitsy; } for (;i < zn; i++) { - zds[i] = hibitsx & hibitsy; + zds[i] = hibitsx & hibitsy; } twocomp2abs_bang(z, hibitsx && hibitsy); RB_GC_GUARD(x); @@ -6384,12 +6384,12 @@ rb_big_and(VALUE x, VALUE y) long tmpn; if (!RB_INTEGER_TYPE_P(y)) { - return rb_num_coerce_bit(x, y, '&'); + return rb_num_coerce_bit(x, y, '&'); } hibitsx = abs2twocomp(&x, &xn); if (FIXNUM_P(y)) { - return bigand_int(x, xn, hibitsx, FIX2LONG(y)); + return bigand_int(x, xn, hibitsx, FIX2LONG(y)); } hibitsy = abs2twocomp(&y, &yn); if (xn > yn) { @@ -6411,10 +6411,10 @@ rb_big_and(VALUE x, VALUE y) zds = BDIGITS(z); for (i=0; i yn) { @@ -6530,10 +6530,10 @@ rb_big_or(VALUE x, VALUE y) zds = BDIGITS(z); for (i=0; i yn) { @@ -6621,10 +6621,10 @@ rb_big_xor(VALUE x, VALUE y) zds = BDIGITS(z); for (i=0; i> bit_length(BITSPERDIG-1); return bignorm(big_shift3(x, lshift_p, shift_numdigits, shift_numbits)); - } - else if (RB_BIGNUM_TYPE_P(y)) { + } + else if (RB_BIGNUM_TYPE_P(y)) { return bignorm(big_shift2(x, 1, y)); - } - y = rb_to_int(y); + } + y = rb_to_int(y); } } @@ -6670,8 +6670,8 @@ rb_big_rshift(VALUE x, VALUE y) int shift_numbits; for (;;) { - if (FIXNUM_P(y)) { - long l = FIX2LONG(y); + if (FIXNUM_P(y)) { + long l = FIX2LONG(y); unsigned long shift; if (0 <= l) { lshift_p = 0; @@ -6679,16 +6679,16 @@ rb_big_rshift(VALUE x, VALUE y) } else { lshift_p = 1; - shift = 1+(unsigned long)(-(l+1)); - } + shift = 1+(unsigned long)(-(l+1)); + } shift_numbits = (int)(shift & (BITSPERDIG-1)); shift_numdigits = shift >> bit_length(BITSPERDIG-1); return bignorm(big_shift3(x, lshift_p, shift_numdigits, shift_numbits)); - } - else if (RB_BIGNUM_TYPE_P(y)) { + } + else if (RB_BIGNUM_TYPE_P(y)) { return bignorm(big_shift2(x, 0, y)); - } - y = rb_to_int(y); + } + y = rb_to_int(y); } } @@ -6702,22 +6702,22 @@ rb_big_aref(VALUE x, VALUE y) BDIGIT bit; if (RB_BIGNUM_TYPE_P(y)) { - if (BIGNUM_NEGATIVE_P(y)) - return INT2FIX(0); - bigtrunc(y); - if (BIGSIZE(y) > sizeof(size_t)) { - return BIGNUM_SIGN(x) ? INT2FIX(0) : INT2FIX(1); - } + if (BIGNUM_NEGATIVE_P(y)) + return INT2FIX(0); + bigtrunc(y); + if (BIGSIZE(y) > sizeof(size_t)) { + return BIGNUM_SIGN(x) ? INT2FIX(0) : INT2FIX(1); + } #if SIZEOF_SIZE_T <= SIZEOF_LONG - shift = big2ulong(y, "long"); + shift = big2ulong(y, "long"); #else - shift = big2ull(y, "long long"); + shift = big2ull(y, "long long"); #endif } else { - l = NUM2LONG(y); - if (l < 0) return INT2FIX(0); - shift = (size_t)l; + l = NUM2LONG(y); + if (l < 0) return INT2FIX(0); + shift = (size_t)l; } s1 = shift/BITSPERDIG; s2 = shift%BITSPERDIG; @@ -6778,8 +6778,8 @@ VALUE rb_big_abs(VALUE x) { if (BIGNUM_NEGATIVE_P(x)) { - x = rb_big_clone(x); - BIGNUM_SET_POSITIVE_SIGN(x); + x = rb_big_clone(x); + BIGNUM_SET_POSITIVE_SIGN(x); } return x; } @@ -6853,7 +6853,7 @@ VALUE rb_big_even_p(VALUE num) { if (BIGNUM_LEN(num) != 0 && BDIGITS(num)[0] & 1) { - return Qfalse; + return Qfalse; } return Qtrue; } @@ -6884,21 +6884,21 @@ estimate_initial_sqrt(VALUE *xp, const size_t xn, const BDIGIT *nds, size_t len) double f; if (rshift > 0) { - lowbits = (BDIGIT)d & ~(~(BDIGIT)1U << rshift); - d >>= rshift; + lowbits = (BDIGIT)d & ~(~(BDIGIT)1U << rshift); + d >>= rshift; } else if (rshift < 0) { - d <<= -rshift; - d |= nds[len-dbl_per_bdig-1] >> (BITSPERDIG+rshift); + d <<= -rshift; + d |= nds[len-dbl_per_bdig-1] >> (BITSPERDIG+rshift); } f = sqrt(BDIGIT_DBL_TO_DOUBLE(d)); d = (BDIGIT_DBL)ceil(f); if (BDIGIT_DBL_TO_DOUBLE(d) == f) { - if (lowbits || (lowbits = !bary_zero_p(nds, len-dbl_per_bdig))) - ++d; + if (lowbits || (lowbits = !bary_zero_p(nds, len-dbl_per_bdig))) + ++d; } else { - lowbits = 1; + lowbits = 1; } rshift /= 2; rshift += (2-(len&1))*BITSPERDIG/2; @@ -6930,29 +6930,29 @@ rb_big_isqrt(VALUE n) BDIGIT *xds; if (len <= 2) { - BDIGIT sq = rb_bdigit_dbl_isqrt(bary2bdigitdbl(nds, len)); + BDIGIT sq = rb_bdigit_dbl_isqrt(bary2bdigitdbl(nds, len)); #if SIZEOF_BDIGIT > SIZEOF_LONG - return ULL2NUM(sq); + return ULL2NUM(sq); #else - return ULONG2NUM(sq); + return ULONG2NUM(sq); #endif } else if ((xds = estimate_initial_sqrt(&x, xn, nds, len)) != 0) { - size_t tn = xn + BIGDIVREM_EXTRA_WORDS; - VALUE t = bignew_1(0, tn, 1); - BDIGIT *tds = BDIGITS(t); - tn = BIGNUM_LEN(t); + size_t tn = xn + BIGDIVREM_EXTRA_WORDS; + VALUE t = bignew_1(0, tn, 1); + BDIGIT *tds = BDIGITS(t); + tn = BIGNUM_LEN(t); - /* t = n/x */ - while (bary_divmod_branch(tds, tn, NULL, 0, nds, len, xds, xn), - bary_cmp(tds, tn, xds, xn) < 0) { - int carry; - BARY_TRUNC(tds, tn); - /* x = (x+t)/2 */ - carry = bary_add(xds, xn, xds, xn, tds, tn); - bary_small_rshift(xds, xds, xn, 1, carry); - tn = BIGNUM_LEN(t); - } + /* t = n/x */ + while (bary_divmod_branch(tds, tn, NULL, 0, nds, len, xds, xn), + bary_cmp(tds, tn, xds, xn) < 0) { + int carry; + BARY_TRUNC(tds, tn); + /* x = (x+t)/2 */ + carry = bary_add(xds, xn, xds, xn, tds, tn); + bary_small_rshift(xds, xds, xn, 1, carry); + tn = BIGNUM_LEN(t); + } } RBASIC_SET_CLASS_RAW(x, rb_cInteger); return x; @@ -7160,7 +7160,7 @@ rb_int_powm(int const argc, VALUE * const argv, VALUE const num) } else { if (rb_bigzero_p(m)) rb_num_zerodiv(); - if (bignorm(m) == INT2FIX(1)) return INT2FIX(0); + if (bignorm(m) == INT2FIX(1)) return INT2FIX(0); return int_pow_tmp3(rb_int_modulo(a, m), b, m, nega_flg); } } diff --git a/class.c b/class.c index 6db373edc1..4306b7c0f3 100644 --- a/class.c +++ b/class.c @@ -106,7 +106,7 @@ rb_class_remove_from_super_subclasses(VALUE klass) next->prev = prev; } - xfree(entry); + xfree(entry); } RCLASS_SUBCLASS_ENTRY(klass) = NULL; @@ -123,11 +123,11 @@ rb_class_remove_from_module_subclasses(VALUE klass) if (prev) { prev->next = next; } - if (next) { + if (next) { next->prev = prev; - } + } - xfree(entry); + xfree(entry); } RCLASS_MODULE_SUBCLASS_ENTRY(klass) = NULL; @@ -148,11 +148,11 @@ rb_class_foreach_subclass(VALUE klass, void (*f)(VALUE, VALUE), VALUE arg) /* do not be tempted to simplify this loop into a for loop, the order of operations is important here if `f` modifies the linked list */ while (cur) { - VALUE curklass = cur->klass; - cur = cur->next; + VALUE curklass = cur->klass; + cur = cur->next; // do not trigger GC during f, otherwise the cur will become // a dangling pointer if the subclass is collected - f(curklass, arg); + f(curklass, arg); } } @@ -316,13 +316,13 @@ rb_check_inheritable(VALUE super) { if (!RB_TYPE_P(super, T_CLASS)) { rb_raise(rb_eTypeError, "superclass must be an instance of Class (given an instance of %"PRIsVALUE")", - rb_obj_class(super)); + rb_obj_class(super)); } if (RBASIC(super)->flags & FL_SINGLETON) { - rb_raise(rb_eTypeError, "can't make subclass of singleton class"); + rb_raise(rb_eTypeError, "can't make subclass of singleton class"); } if (super == rb_cClass) { - rb_raise(rb_eTypeError, "can't make subclass of Class"); + rb_raise(rb_eTypeError, "can't make subclass of Class"); } } @@ -344,12 +344,12 @@ static void clone_method(VALUE old_klass, VALUE new_klass, ID mid, const rb_method_entry_t *me) { if (me->def->type == VM_METHOD_TYPE_ISEQ) { - rb_cref_t *new_cref; - rb_vm_rewrite_cref(me->def->body.iseq.cref, old_klass, new_klass, &new_cref); - rb_add_method_iseq(new_klass, mid, me->def->body.iseq.iseqptr, new_cref, METHOD_ENTRY_VISI(me)); + rb_cref_t *new_cref; + rb_vm_rewrite_cref(me->def->body.iseq.cref, old_klass, new_klass, &new_cref); + rb_add_method_iseq(new_klass, mid, me->def->body.iseq.iseqptr, new_cref, METHOD_ENTRY_VISI(me)); } else { - rb_method_entry_set(new_klass, mid, me, METHOD_ENTRY_VISI(me)); + rb_method_entry_set(new_klass, mid, me, METHOD_ENTRY_VISI(me)); } } @@ -393,13 +393,13 @@ static void class_init_copy_check(VALUE clone, VALUE orig) { if (orig == rb_cBasicObject) { - rb_raise(rb_eTypeError, "can't copy the root class"); + rb_raise(rb_eTypeError, "can't copy the root class"); } if (RCLASS_SUPER(clone) != 0 || clone == rb_cBasicObject) { - rb_raise(rb_eTypeError, "already initialized class"); + rb_raise(rb_eTypeError, "already initialized class"); } if (FL_TEST(orig, FL_SINGLETON)) { - rb_raise(rb_eTypeError, "can't copy singleton class"); + rb_raise(rb_eTypeError, "can't copy singleton class"); } } @@ -407,31 +407,31 @@ static void copy_tables(VALUE clone, VALUE orig) { if (RCLASS_IV_TBL(clone)) { - st_free_table(RCLASS_IV_TBL(clone)); - RCLASS_IV_TBL(clone) = 0; + st_free_table(RCLASS_IV_TBL(clone)); + RCLASS_IV_TBL(clone) = 0; } if (RCLASS_CONST_TBL(clone)) { - rb_free_const_table(RCLASS_CONST_TBL(clone)); - RCLASS_CONST_TBL(clone) = 0; + rb_free_const_table(RCLASS_CONST_TBL(clone)); + RCLASS_CONST_TBL(clone) = 0; } RCLASS_M_TBL(clone) = 0; if (RCLASS_IV_TBL(orig)) { - st_data_t id; + st_data_t id; - rb_iv_tbl_copy(clone, orig); - CONST_ID(id, "__tmp_classpath__"); - st_delete(RCLASS_IV_TBL(clone), &id, 0); - CONST_ID(id, "__classpath__"); - st_delete(RCLASS_IV_TBL(clone), &id, 0); - CONST_ID(id, "__classid__"); - st_delete(RCLASS_IV_TBL(clone), &id, 0); + rb_iv_tbl_copy(clone, orig); + CONST_ID(id, "__tmp_classpath__"); + st_delete(RCLASS_IV_TBL(clone), &id, 0); + CONST_ID(id, "__classpath__"); + st_delete(RCLASS_IV_TBL(clone), &id, 0); + CONST_ID(id, "__classid__"); + st_delete(RCLASS_IV_TBL(clone), &id, 0); } if (RCLASS_CONST_TBL(orig)) { - struct clone_const_arg arg; + struct clone_const_arg arg; - arg.tbl = RCLASS_CONST_TBL(clone) = rb_id_table_create(0); - arg.klass = clone; - rb_id_table_foreach(RCLASS_CONST_TBL(orig), clone_const_i, &arg); + arg.tbl = RCLASS_CONST_TBL(clone) = rb_id_table_create(0); + arg.klass = clone; + rb_id_table_foreach(RCLASS_CONST_TBL(orig), clone_const_i, &arg); } } @@ -493,11 +493,11 @@ rb_mod_init_copy(VALUE clone, VALUE orig) RCLASS_ALLOCATOR(clone) = RCLASS_ALLOCATOR(orig); copy_tables(clone, orig); if (RCLASS_M_TBL(orig)) { - struct clone_method_arg arg; - arg.old_klass = orig; - arg.new_klass = clone; - RCLASS_M_TBL_INIT(clone); - rb_id_table_foreach(RCLASS_M_TBL(orig), clone_method_i, &arg); + struct clone_method_arg arg; + arg.old_klass = orig; + arg.new_klass = clone; + RCLASS_M_TBL_INIT(clone); + rb_id_table_foreach(RCLASS_M_TBL(orig), clone_method_i, &arg); } if (RCLASS_ORIGIN(orig) == orig) { @@ -595,49 +595,49 @@ rb_singleton_class_clone_and_attach(VALUE obj, VALUE attach) return klass; } else { - /* copy singleton(unnamed) class */ + /* copy singleton(unnamed) class */ bool klass_of_clone_is_new; - VALUE clone = class_alloc(RBASIC(klass)->flags, 0); + VALUE clone = class_alloc(RBASIC(klass)->flags, 0); - if (BUILTIN_TYPE(obj) == T_CLASS) { + if (BUILTIN_TYPE(obj) == T_CLASS) { klass_of_clone_is_new = true; - RBASIC_SET_CLASS(clone, clone); - } - else { + RBASIC_SET_CLASS(clone, clone); + } + else { VALUE klass_metaclass_clone = rb_singleton_class_clone(klass); // When `METACLASS_OF(klass) == klass_metaclass_clone`, it means the // recursive call did not clone `METACLASS_OF(klass)`. klass_of_clone_is_new = (METACLASS_OF(klass) != klass_metaclass_clone); RBASIC_SET_CLASS(clone, klass_metaclass_clone); - } + } - RCLASS_SET_SUPER(clone, RCLASS_SUPER(klass)); - RCLASS_ALLOCATOR(clone) = RCLASS_ALLOCATOR(klass); - if (RCLASS_IV_TBL(klass)) { - rb_iv_tbl_copy(clone, klass); - } - if (RCLASS_CONST_TBL(klass)) { - struct clone_const_arg arg; - arg.tbl = RCLASS_CONST_TBL(clone) = rb_id_table_create(0); - arg.klass = clone; - rb_id_table_foreach(RCLASS_CONST_TBL(klass), clone_const_i, &arg); - } - if (attach != Qundef) { - rb_singleton_class_attached(clone, attach); - } - RCLASS_M_TBL_INIT(clone); - { - struct clone_method_arg arg; - arg.old_klass = klass; - arg.new_klass = clone; - rb_id_table_foreach(RCLASS_M_TBL(klass), clone_method_i, &arg); - } + RCLASS_SET_SUPER(clone, RCLASS_SUPER(klass)); + RCLASS_ALLOCATOR(clone) = RCLASS_ALLOCATOR(klass); + if (RCLASS_IV_TBL(klass)) { + rb_iv_tbl_copy(clone, klass); + } + if (RCLASS_CONST_TBL(klass)) { + struct clone_const_arg arg; + arg.tbl = RCLASS_CONST_TBL(clone) = rb_id_table_create(0); + arg.klass = clone; + rb_id_table_foreach(RCLASS_CONST_TBL(klass), clone_const_i, &arg); + } + if (attach != Qundef) { + rb_singleton_class_attached(clone, attach); + } + RCLASS_M_TBL_INIT(clone); + { + struct clone_method_arg arg; + arg.old_klass = klass; + arg.new_klass = clone; + rb_id_table_foreach(RCLASS_M_TBL(klass), clone_method_i, &arg); + } if (klass_of_clone_is_new) { rb_singleton_class_attached(METACLASS_OF(clone), clone); } - FL_SET(clone, FL_SINGLETON); + FL_SET(clone, FL_SINGLETON); - return clone; + return clone; } } @@ -645,7 +645,7 @@ void rb_singleton_class_attached(VALUE klass, VALUE obj) { if (FL_TEST(klass, FL_SINGLETON)) { - rb_class_ivar_set(klass, id_attached, obj); + rb_class_ivar_set(klass, id_attached, obj); } } @@ -666,7 +666,7 @@ int rb_singleton_class_internal_p(VALUE sklass) { return (RB_TYPE_P(rb_attr_get(sklass, id_attached), T_CLASS) && - !rb_singleton_class_has_metaclass_p(sklass)); + !rb_singleton_class_has_metaclass_p(sklass)); } /*! @@ -708,13 +708,13 @@ make_metaclass(VALUE klass) rb_singleton_class_attached(metaclass, klass); if (META_CLASS_OF_CLASS_CLASS_P(klass)) { - SET_METACLASS_OF(klass, metaclass); - SET_METACLASS_OF(metaclass, metaclass); + SET_METACLASS_OF(klass, metaclass); + SET_METACLASS_OF(metaclass, metaclass); } else { - VALUE tmp = METACLASS_OF(klass); /* for a meta^(n)-class klass, tmp is meta^(n)-class of Class class */ - SET_METACLASS_OF(klass, metaclass); - SET_METACLASS_OF(metaclass, ENSURE_EIGENCLASS(tmp)); + VALUE tmp = METACLASS_OF(klass); /* for a meta^(n)-class klass, tmp is meta^(n)-class of Class class */ + SET_METACLASS_OF(klass, metaclass); + SET_METACLASS_OF(metaclass, ENSURE_EIGENCLASS(tmp)); } super = RCLASS_SUPER(klass); @@ -855,10 +855,10 @@ VALUE rb_make_metaclass(VALUE obj, VALUE unused) { if (BUILTIN_TYPE(obj) == T_CLASS) { - return make_metaclass(obj); + return make_metaclass(obj); } else { - return make_singleton_class(obj); + return make_singleton_class(obj); } } @@ -900,21 +900,21 @@ rb_define_class(const char *name, VALUE super) id = rb_intern(name); if (rb_const_defined(rb_cObject, id)) { - klass = rb_const_get(rb_cObject, id); - if (!RB_TYPE_P(klass, T_CLASS)) { - rb_raise(rb_eTypeError, "%s is not a class (%"PRIsVALUE")", - name, rb_obj_class(klass)); - } - if (rb_class_real(RCLASS_SUPER(klass)) != super) { - rb_raise(rb_eTypeError, "superclass mismatch for class %s", name); - } + klass = rb_const_get(rb_cObject, id); + if (!RB_TYPE_P(klass, T_CLASS)) { + rb_raise(rb_eTypeError, "%s is not a class (%"PRIsVALUE")", + name, rb_obj_class(klass)); + } + if (rb_class_real(RCLASS_SUPER(klass)) != super) { + rb_raise(rb_eTypeError, "superclass mismatch for class %s", name); + } /* Class may have been defined in Ruby and not pin-rooted */ rb_vm_add_root_module(klass); - return klass; + return klass; } if (!super) { - rb_raise(rb_eArgError, "no super class for `%s'", name); + rb_raise(rb_eArgError, "no super class for `%s'", name); } klass = rb_define_class_id(id, super); rb_vm_add_root_module(klass); @@ -936,26 +936,26 @@ rb_define_class_id_under(VALUE outer, ID id, VALUE super) VALUE klass; if (rb_const_defined_at(outer, id)) { - klass = rb_const_get_at(outer, id); - if (!RB_TYPE_P(klass, T_CLASS)) { - rb_raise(rb_eTypeError, "%"PRIsVALUE"::%"PRIsVALUE" is not a class" - " (%"PRIsVALUE")", - outer, rb_id2str(id), rb_obj_class(klass)); - } - if (rb_class_real(RCLASS_SUPER(klass)) != super) { - rb_raise(rb_eTypeError, "superclass mismatch for class " - "%"PRIsVALUE"::%"PRIsVALUE"" - " (%"PRIsVALUE" is given but was %"PRIsVALUE")", - outer, rb_id2str(id), RCLASS_SUPER(klass), super); - } + klass = rb_const_get_at(outer, id); + if (!RB_TYPE_P(klass, T_CLASS)) { + rb_raise(rb_eTypeError, "%"PRIsVALUE"::%"PRIsVALUE" is not a class" + " (%"PRIsVALUE")", + outer, rb_id2str(id), rb_obj_class(klass)); + } + if (rb_class_real(RCLASS_SUPER(klass)) != super) { + rb_raise(rb_eTypeError, "superclass mismatch for class " + "%"PRIsVALUE"::%"PRIsVALUE"" + " (%"PRIsVALUE" is given but was %"PRIsVALUE")", + outer, rb_id2str(id), RCLASS_SUPER(klass), super); + } /* Class may have been defined in Ruby and not pin-rooted */ rb_vm_add_root_module(klass); - return klass; + return klass; } if (!super) { - rb_raise(rb_eArgError, "no super class for `%"PRIsVALUE"::%"PRIsVALUE"'", - rb_class_path(outer), rb_id2str(id)); + rb_raise(rb_eArgError, "no super class for `%"PRIsVALUE"::%"PRIsVALUE"'", + rb_class_path(outer), rb_id2str(id)); } klass = rb_define_class_id(id, super); rb_set_class_path_string(klass, outer, rb_id2str(id)); @@ -1010,14 +1010,14 @@ rb_define_module(const char *name) id = rb_intern(name); if (rb_const_defined(rb_cObject, id)) { - module = rb_const_get(rb_cObject, id); - if (!RB_TYPE_P(module, T_MODULE)) { - rb_raise(rb_eTypeError, "%s is not a module (%"PRIsVALUE")", - name, rb_obj_class(module)); - } + module = rb_const_get(rb_cObject, id); + if (!RB_TYPE_P(module, T_MODULE)) { + rb_raise(rb_eTypeError, "%s is not a module (%"PRIsVALUE")", + name, rb_obj_class(module)); + } /* Module may have been defined in Ruby and not pin-rooted */ rb_vm_add_root_module(module); - return module; + return module; } module = rb_module_new(); rb_vm_add_root_module(module); @@ -1038,15 +1038,15 @@ rb_define_module_id_under(VALUE outer, ID id) VALUE module; if (rb_const_defined_at(outer, id)) { - module = rb_const_get_at(outer, id); - if (!RB_TYPE_P(module, T_MODULE)) { - rb_raise(rb_eTypeError, "%"PRIsVALUE"::%"PRIsVALUE" is not a module" - " (%"PRIsVALUE")", - outer, rb_id2str(id), rb_obj_class(module)); - } + module = rb_const_get_at(outer, id); + if (!RB_TYPE_P(module, T_MODULE)) { + rb_raise(rb_eTypeError, "%"PRIsVALUE"::%"PRIsVALUE" is not a module" + " (%"PRIsVALUE")", + outer, rb_id2str(id), rb_obj_class(module)); + } /* Module may have been defined in Ruby and not pin-rooted */ rb_gc_register_mark_object(module); - return module; + return module; } module = rb_module_new(); rb_const_set(outer, id, module); @@ -1065,14 +1065,14 @@ rb_include_class_new(VALUE module, VALUE super) RCLASS_SET_ORIGIN(klass, klass); if (BUILTIN_TYPE(module) == T_ICLASS) { - module = METACLASS_OF(module); + module = METACLASS_OF(module); } RUBY_ASSERT(!RB_TYPE_P(module, T_ICLASS)); if (!RCLASS_IV_TBL(module)) { - RCLASS_IV_TBL(module) = st_init_numtable(); + RCLASS_IV_TBL(module) = st_init_numtable(); } if (!RCLASS_CONST_TBL(module)) { - RCLASS_CONST_TBL(module) = rb_id_table_create(0); + RCLASS_CONST_TBL(module) = rb_id_table_create(0); } RCLASS_IV_TBL(klass) = RCLASS_IV_TBL(module); RCLASS_CVC_TBL(klass) = RCLASS_CVC_TBL(module); @@ -1093,7 +1093,7 @@ ensure_includable(VALUE klass, VALUE module) Check_Type(module, T_MODULE); rb_module_set_initialized(module); if (!NIL_P(rb_refinement_module_get_refined_class(module))) { - rb_raise(rb_eArgError, "refinement module is not allowed"); + rb_raise(rb_eArgError, "refinement module is not allowed"); } } @@ -1106,7 +1106,7 @@ rb_include_module(VALUE klass, VALUE module) changed = include_modules_at(klass, RCLASS_ORIGIN(klass), module, TRUE); if (changed < 0) - rb_raise(rb_eArgError, "cyclic include detected"); + rb_raise(rb_eArgError, "cyclic include detected"); if (RB_TYPE_P(klass, T_MODULE)) { rb_subclass_entry_t *iclass = RCLASS_SUBCLASSES(klass); @@ -1194,8 +1194,8 @@ do_include_modules_at(const VALUE klass, VALUE c, VALUE module, int search_super while (module) { int c_seen = FALSE; - int superclass_seen = FALSE; - struct rb_id_table *tbl; + int superclass_seen = FALSE; + struct rb_id_table *tbl; if (klass == c) { c_seen = TRUE; @@ -1245,8 +1245,8 @@ do_include_modules_at(const VALUE klass, VALUE c, VALUE module, int search_super } // setup T_ICLASS for the include/prepend module - iclass = rb_include_class_new(module, super_class); - c = RCLASS_SET_SUPER(c, iclass); + iclass = rb_include_class_new(module, super_class); + c = RCLASS_SET_SUPER(c, iclass); RCLASS_SET_INCLUDER(iclass, klass); add_subclass = TRUE; if (module != RCLASS_ORIGIN(module)) { @@ -1262,25 +1262,25 @@ do_include_modules_at(const VALUE klass, VALUE c, VALUE module, int search_super add_subclass = FALSE; } - if (add_subclass) { - VALUE m = module; + if (add_subclass) { + VALUE m = module; if (BUILTIN_TYPE(m) == T_ICLASS) m = METACLASS_OF(m); rb_module_add_to_subclasses_list(m, iclass); - } + } - if (BUILTIN_TYPE(klass) == T_MODULE && FL_TEST(klass, RMODULE_IS_REFINEMENT)) { - VALUE refined_class = - rb_refinement_module_get_refined_class(klass); + if (BUILTIN_TYPE(klass) == T_MODULE && FL_TEST(klass, RMODULE_IS_REFINEMENT)) { + VALUE refined_class = + rb_refinement_module_get_refined_class(klass); rb_id_table_foreach(RCLASS_M_TBL(module), add_refined_method_entry_i, (void *)refined_class); RUBY_ASSERT(BUILTIN_TYPE(c) == T_MODULE); - } + } tbl = RCLASS_CONST_TBL(module); - if (tbl && rb_id_table_size(tbl)) - rb_id_table_foreach(tbl, clear_constant_cache_i, NULL); + if (tbl && rb_id_table_size(tbl)) + rb_id_table_foreach(tbl, clear_constant_cache_i, NULL); skip: - module = RCLASS_SUPER(module); + module = RCLASS_SUPER(module); } return method_changed; @@ -1302,20 +1302,20 @@ move_refined_method(ID key, VALUE value, void *data) struct rb_id_table *tbl = RCLASS_M_TBL(klass); if (me->def->body.refined.orig_me) { - const rb_method_entry_t *orig_me = me->def->body.refined.orig_me, *new_me; - RB_OBJ_WRITE(me, &me->def->body.refined.orig_me, NULL); - new_me = rb_method_entry_clone(me); + const rb_method_entry_t *orig_me = me->def->body.refined.orig_me, *new_me; + RB_OBJ_WRITE(me, &me->def->body.refined.orig_me, NULL); + new_me = rb_method_entry_clone(me); rb_method_table_insert(klass, tbl, key, new_me); - rb_method_entry_copy(me, orig_me); - return ID_TABLE_CONTINUE; - } - else { + rb_method_entry_copy(me, orig_me); + return ID_TABLE_CONTINUE; + } + else { rb_method_table_insert(klass, tbl, key, me); - return ID_TABLE_DELETE; - } + return ID_TABLE_DELETE; + } } else { - return ID_TABLE_CONTINUE; + return ID_TABLE_CONTINUE; } } @@ -1339,14 +1339,14 @@ ensure_origin(VALUE klass) { VALUE origin = RCLASS_ORIGIN(klass); if (origin == klass) { - origin = class_alloc(T_ICLASS, klass); - RCLASS_SET_SUPER(origin, RCLASS_SUPER(klass)); - RCLASS_SET_SUPER(klass, origin); - RCLASS_SET_ORIGIN(klass, origin); - RCLASS_M_TBL(origin) = RCLASS_M_TBL(klass); - RCLASS_M_TBL_INIT(klass); + origin = class_alloc(T_ICLASS, klass); + RCLASS_SET_SUPER(origin, RCLASS_SUPER(klass)); + RCLASS_SET_SUPER(klass, origin); + RCLASS_SET_ORIGIN(klass, origin); + RCLASS_M_TBL(origin) = RCLASS_M_TBL(klass); + RCLASS_M_TBL_INIT(klass); rb_id_table_foreach(RCLASS_M_TBL(origin), cache_clear_refined_method, (void *)klass); - rb_id_table_foreach(RCLASS_M_TBL(origin), move_refined_method, (void *)klass); + rb_id_table_foreach(RCLASS_M_TBL(origin), move_refined_method, (void *)klass); return true; } return false; @@ -1366,7 +1366,7 @@ rb_prepend_module(VALUE klass, VALUE module) changed = do_include_modules_at(klass, klass, module, FALSE, false); RUBY_ASSERT(changed >= 0); // already checked for cyclic prepend above if (changed) { - rb_vm_check_redefinition_by_prepend(klass); + rb_vm_check_redefinition_by_prepend(klass); } if (RB_TYPE_P(klass, T_MODULE)) { rb_subclass_entry_t *iclass = RCLASS_SUBCLASSES(klass); @@ -1433,10 +1433,10 @@ rb_mod_included_modules(VALUE mod) for (p = RCLASS_SUPER(mod); p; p = RCLASS_SUPER(p)) { if (p != origin && RCLASS_ORIGIN(p) == p && BUILTIN_TYPE(p) == T_ICLASS) { - VALUE m = METACLASS_OF(p); - if (RB_TYPE_P(m, T_MODULE)) - rb_ary_push(ary, m); - } + VALUE m = METACLASS_OF(p); + if (RB_TYPE_P(m, T_MODULE)) + rb_ary_push(ary, m); + } } return ary; } @@ -1468,8 +1468,8 @@ rb_mod_include_p(VALUE mod, VALUE mod2) Check_Type(mod2, T_MODULE); for (p = RCLASS_SUPER(mod); p; p = RCLASS_SUPER(p)) { if (BUILTIN_TYPE(p) == T_ICLASS && !FL_TEST(p, RICLASS_IS_ORIGIN)) { - if (METACLASS_OF(p) == mod2) return Qtrue; - } + if (METACLASS_OF(p) == mod2) return Qtrue; + } } return Qfalse; } @@ -1504,12 +1504,12 @@ rb_mod_ancestors(VALUE mod) for (p = mod; p; p = RCLASS_SUPER(p)) { if (p == refined_class) break; if (p != RCLASS_ORIGIN(p)) continue; - if (BUILTIN_TYPE(p) == T_ICLASS) { - rb_ary_push(ary, METACLASS_OF(p)); - } + if (BUILTIN_TYPE(p) == T_ICLASS) { + rb_ary_push(ary, METACLASS_OF(p)); + } else { - rb_ary_push(ary, p); - } + rb_ary_push(ary, p); + } } return ary; } @@ -1603,10 +1603,10 @@ ins_methods_i(st_data_t name, st_data_t type, st_data_t ary) switch ((rb_method_visibility_t)type) { case METHOD_VISI_UNDEF: case METHOD_VISI_PRIVATE: - break; + break; default: /* everything but private */ - ins_methods_push(name, ary); - break; + ins_methods_push(name, ary); + break; } return ST_CONTINUE; } @@ -1615,7 +1615,7 @@ static int ins_methods_type_i(st_data_t name, st_data_t type, st_data_t ary, rb_method_visibility_t visi) { if ((rb_method_visibility_t)type == visi) { - ins_methods_push(name, ary); + ins_methods_push(name, ary); } return ST_CONTINUE; } @@ -1642,7 +1642,7 @@ static int ins_methods_undef_i(st_data_t name, st_data_t type, st_data_t ary) { if ((rb_method_visibility_t)type == METHOD_VISI_UNDEF) { - ins_methods_push(name, ary); + ins_methods_push(name, ary); } return ST_CONTINUE; } @@ -1660,20 +1660,20 @@ method_entry_i(ID key, VALUE value, void *data) rb_method_visibility_t type; if (me->def->type == VM_METHOD_TYPE_REFINED) { - VALUE owner = me->owner; - me = rb_resolve_refined_method(Qnil, me); - if (!me) return ID_TABLE_CONTINUE; - if (!arg->recur && me->owner != owner) return ID_TABLE_CONTINUE; + VALUE owner = me->owner; + me = rb_resolve_refined_method(Qnil, me); + if (!me) return ID_TABLE_CONTINUE; + if (!arg->recur && me->owner != owner) return ID_TABLE_CONTINUE; } if (!st_is_member(arg->list, key)) { - if (UNDEFINED_METHOD_ENTRY_P(me)) { - type = METHOD_VISI_UNDEF; /* none */ - } - else { - type = METHOD_ENTRY_VISI(me); - RUBY_ASSERT(type != METHOD_VISI_UNDEF); - } - st_add_direct(arg->list, key, (st_data_t)type); + if (UNDEFINED_METHOD_ENTRY_P(me)) { + type = METHOD_VISI_UNDEF; /* none */ + } + else { + type = METHOD_ENTRY_VISI(me); + RUBY_ASSERT(type != METHOD_VISI_UNDEF); + } + st_add_direct(arg->list, key, (st_data_t)type); } return ID_TABLE_CONTINUE; } @@ -1714,14 +1714,14 @@ class_instance_method_list(int argc, const VALUE *argv, VALUE mod, int obj, int } if (!recur && RCLASS_ORIGIN(mod) != mod) { - mod = RCLASS_ORIGIN(mod); - prepended = 1; + mod = RCLASS_ORIGIN(mod); + prepended = 1; } for (; mod; mod = RCLASS_SUPER(mod)) { add_instance_method_list(mod, &me_arg); - if (BUILTIN_TYPE(mod) == T_ICLASS && !prepended) continue; - if (!recur) break; + if (BUILTIN_TYPE(mod) == T_ICLASS && !prepended) continue; + if (!recur) break; } ary = rb_ary_new2(me_arg.list->num_entries); st_foreach(me_arg.list, func, ary); @@ -1866,7 +1866,7 @@ rb_obj_methods(int argc, const VALUE *argv, VALUE obj) { rb_check_arity(argc, 0, 1); if (argc > 0 && !RTEST(argv[0])) { - return rb_obj_singleton_methods(argc, argv, obj); + return rb_obj_singleton_methods(argc, argv, obj); } return class_instance_method_list(argc, argv, CLASS_OF(obj), 1, ins_methods_i); } @@ -1966,14 +1966,14 @@ rb_obj_singleton_methods(int argc, const VALUE *argv, VALUE obj) me_arg.list = st_init_numtable(); me_arg.recur = recur; if (klass && FL_TEST(klass, FL_SINGLETON)) { - if ((mtbl = RCLASS_M_TBL(origin)) != 0) rb_id_table_foreach(mtbl, method_entry_i, &me_arg); - klass = RCLASS_SUPER(klass); + if ((mtbl = RCLASS_M_TBL(origin)) != 0) rb_id_table_foreach(mtbl, method_entry_i, &me_arg); + klass = RCLASS_SUPER(klass); } if (recur) { - while (klass && (FL_TEST(klass, FL_SINGLETON) || RB_TYPE_P(klass, T_ICLASS))) { - if (klass != origin && (mtbl = RCLASS_M_TBL(klass)) != 0) rb_id_table_foreach(mtbl, method_entry_i, &me_arg); - klass = RCLASS_SUPER(klass); - } + while (klass && (FL_TEST(klass, FL_SINGLETON) || RB_TYPE_P(klass, T_ICLASS))) { + if (klass != origin && (mtbl = RCLASS_M_TBL(klass)) != 0) rb_id_table_foreach(mtbl, method_entry_i, &me_arg); + klass = RCLASS_SUPER(klass); + } } ary = rb_ary_new2(me_arg.list->num_entries); st_foreach(me_arg.list, ins_methods_i, ary); @@ -2045,7 +2045,7 @@ rb_undef_methods_from(VALUE klass, VALUE super) { struct rb_id_table *mtbl = RCLASS_M_TBL(super); if (mtbl) { - rb_id_table_foreach(mtbl, undef_method_i, (void *)klass); + rb_id_table_foreach(mtbl, undef_method_i, (void *)klass); } } @@ -2093,15 +2093,15 @@ singleton_class_of(VALUE obj) case T_BIGNUM: case T_FLOAT: case T_SYMBOL: - rb_raise(rb_eTypeError, "can't define singleton"); + rb_raise(rb_eTypeError, "can't define singleton"); case T_FALSE: case T_TRUE: case T_NIL: - klass = special_singleton_class_of(obj); - if (NIL_P(klass)) - rb_bug("unknown immediate %p", (void *)obj); - return klass; + klass = special_singleton_class_of(obj); + if (NIL_P(klass)) + rb_bug("unknown immediate %p", (void *)obj); + return klass; case T_STRING: if (FL_TEST_RAW(obj, RSTRING_FSTR)) { @@ -2112,9 +2112,9 @@ singleton_class_of(VALUE obj) klass = METACLASS_OF(obj); if (!(FL_TEST(klass, FL_SINGLETON) && rb_attr_get(klass, id_attached) == obj)) { - rb_serial_t serial = RCLASS_SERIAL(klass); - klass = rb_make_metaclass(obj, klass); - RCLASS_SERIAL(klass) = serial; + rb_serial_t serial = RCLASS_SERIAL(klass); + klass = rb_make_metaclass(obj, klass); + RCLASS_SERIAL(klass) = serial; } RB_FL_SET_RAW(klass, RB_OBJ_FROZEN_RAW(obj)); @@ -2127,11 +2127,11 @@ rb_freeze_singleton_class(VALUE x) { /* should not propagate to meta-meta-class, and so on */ if (!(RBASIC(x)->flags & FL_SINGLETON)) { - VALUE klass = RBASIC_CLASS(x); - if (klass && (klass = RCLASS_ORIGIN(klass)) != 0 && - FL_TEST(klass, (FL_SINGLETON|FL_FREEZE)) == FL_SINGLETON) { - OBJ_FREEZE_RAW(klass); - } + VALUE klass = RBASIC_CLASS(x); + if (klass && (klass = RCLASS_ORIGIN(klass)) != 0 && + FL_TEST(klass, (FL_SINGLETON|FL_FREEZE)) == FL_SINGLETON) { + OBJ_FREEZE_RAW(klass); + } } } @@ -2148,7 +2148,7 @@ rb_singleton_class_get(VALUE obj) VALUE klass; if (SPECIAL_CONST_P(obj)) { - return rb_special_singleton_class(obj); + return rb_special_singleton_class(obj); } klass = METACLASS_OF(obj); if (!FL_TEST(klass, FL_SINGLETON)) return Qnil; @@ -2223,13 +2223,13 @@ rb_keyword_error_new(const char *error, VALUE keys) VALUE error_message = rb_sprintf("%s keyword%.*s", error, len > 1, "s"); if (len > 0) { - rb_str_cat_cstr(error_message, ": "); - while (1) { + rb_str_cat_cstr(error_message, ": "); + while (1) { const VALUE k = RARRAY_AREF(keys, i); - rb_str_append(error_message, rb_inspect(k)); - if (++i >= len) break; - rb_str_cat_cstr(error_message, ", "); - } + rb_str_append(error_message, rb_inspect(k)); + if (++i >= len) break; + rb_str_cat_cstr(error_message, ", "); + } } return rb_exc_new_str(rb_eArgError, error_message); @@ -2248,7 +2248,7 @@ unknown_keyword_error(VALUE hash, const ID *table, int keywords) { int i; for (i = 0; i < keywords; i++) { - st_data_t key = ID2SYM(table[i]); + st_data_t key = ID2SYM(table[i]); rb_hash_stlike_delete(hash, &key, NULL); } rb_keyword_error("unknown", rb_hash_keys(hash)); @@ -2272,8 +2272,8 @@ rb_extract_keywords(VALUE *orighash) VALUE hash = *orighash; if (RHASH_EMPTY_P(hash)) { - *orighash = 0; - return hash; + *orighash = 0; + return hash; } rb_hash_foreach(hash, separate_symbol, (st_data_t)&parthash); *orighash = parthash[1]; @@ -2299,36 +2299,36 @@ rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, V if (NIL_P(keyword_hash)) keyword_hash = 0; if (optional < 0) { - rest = 1; - optional = -1-optional; + rest = 1; + optional = -1-optional; } if (required) { - for (; i < required; i++) { - VALUE keyword = ID2SYM(table[i]); - if (keyword_hash) { + for (; i < required; i++) { + VALUE keyword = ID2SYM(table[i]); + if (keyword_hash) { if (extract_kwarg(keyword, values[i])) { - continue; - } - } - if (NIL_P(missing)) missing = rb_ary_tmp_new(1); - rb_ary_push(missing, keyword); - } - if (!NIL_P(missing)) { - rb_keyword_error("missing", missing); - } + continue; + } + } + if (NIL_P(missing)) missing = rb_ary_tmp_new(1); + rb_ary_push(missing, keyword); + } + if (!NIL_P(missing)) { + rb_keyword_error("missing", missing); + } } j = i; if (optional && keyword_hash) { - for (i = 0; i < optional; i++) { + for (i = 0; i < optional; i++) { if (extract_kwarg(ID2SYM(table[required+i]), values[required+i])) { - j++; - } - } + j++; + } + } } if (!rest && keyword_hash) { - if (RHASH_SIZE(keyword_hash) > (unsigned int)(values ? 0 : j)) { - unknown_keyword_error(keyword_hash, table, required+optional); - } + if (RHASH_SIZE(keyword_hash) > (unsigned int)(values ? 0 : j)) { + unknown_keyword_error(keyword_hash, table, required+optional); + } } if (values && !keyword_hash) { for (i = 0; i < required + optional; i++) { @@ -2359,30 +2359,30 @@ rb_scan_args_parse(int kw_flag, const char *fmt, struct rb_scan_args_t *arg) if (ISDIGIT(*p)) { arg->n_lead = *p - '0'; - p++; - if (ISDIGIT(*p)) { + p++; + if (ISDIGIT(*p)) { arg->n_opt = *p - '0'; - p++; - } + p++; + } } if (*p == '*') { arg->f_var = 1; - p++; + p++; } if (ISDIGIT(*p)) { arg->n_trail = *p - '0'; - p++; + p++; } if (*p == ':') { arg->f_hash = 1; - p++; + p++; } if (*p == '&') { arg->f_block = 1; - p++; + p++; } if (*p != '\0') { - rb_fatal("bad scan arg format: %s", fmt); + rb_fatal("bad scan arg format: %s", fmt); } } @@ -2418,37 +2418,37 @@ rb_scan_args_assign(const struct rb_scan_args_t *arg, int argc, const VALUE *con for (i = 0; i < n_lead; i++) { var = rb_scan_args_next_param(); if (var) *var = argv[argi]; - argi++; + argi++; } /* capture optional arguments */ for (i = 0; i < n_opt; i++) { var = rb_scan_args_next_param(); if (argi < argc - n_trail) { if (var) *var = argv[argi]; - argi++; - } - else { - if (var) *var = Qnil; - } + argi++; + } + else { + if (var) *var = Qnil; + } } /* capture variable length arguments */ if (f_var) { int n_var = argc - argi - n_trail; var = rb_scan_args_next_param(); - if (0 < n_var) { + if (0 < n_var) { if (var) *var = rb_ary_new_from_values(n_var, &argv[argi]); - argi += n_var; - } - else { - if (var) *var = rb_ary_new(); - } + argi += n_var; + } + else { + if (var) *var = rb_ary_new(); + } } /* capture trailing mandatory arguments */ for (i = 0; i < n_trail; i++) { var = rb_scan_args_next_param(); if (var) *var = argv[argi]; - argi++; + argi++; } /* capture an option hash - phase 2: assignment */ if (f_hash) { @@ -2458,12 +2458,12 @@ rb_scan_args_assign(const struct rb_scan_args_t *arg, int argc, const VALUE *con /* capture iterator block */ if (f_block) { var = rb_scan_args_next_param(); - if (rb_block_given_p()) { - *var = rb_block_proc(); - } - else { - *var = Qnil; - } + if (rb_block_given_p()) { + *var = rb_block_proc(); + } + else { + *var = Qnil; + } } if (argi == argc) { diff --git a/compar.c b/compar.c index bf8db53af7..00e79b5767 100644 --- a/compar.c +++ b/compar.c @@ -30,13 +30,13 @@ rb_cmperr(VALUE x, VALUE y) VALUE classname; if (SPECIAL_CONST_P(y) || BUILTIN_TYPE(y) == T_FLOAT) { - classname = rb_inspect(y); + classname = rb_inspect(y); } else { - classname = rb_obj_class(y); + classname = rb_obj_class(y); } rb_raise(rb_eArgError, "comparison of %"PRIsVALUE" with %"PRIsVALUE" failed", - rb_obj_class(x), classname); + rb_obj_class(x), classname); } static VALUE @@ -51,11 +51,11 @@ rb_invcmp(VALUE x, VALUE y) { VALUE invcmp = rb_exec_recursive(invcmp_recursive, x, y); if (invcmp == Qundef || NIL_P(invcmp)) { - return Qnil; + return Qnil; } else { - int result = -rb_cmpint(invcmp, x, y); - return INT2FIX(result); + int result = -rb_cmpint(invcmp, x, y); + return INT2FIX(result); } } @@ -229,7 +229,7 @@ cmp_clamp(int argc, VALUE *argv, VALUE x) } } if (!NIL_P(min) && !NIL_P(max) && cmpint(min, max) > 0) { - rb_raise(rb_eArgError, "min argument must be smaller than max argument"); + rb_raise(rb_eArgError, "min argument must be smaller than max argument"); } if (!NIL_P(min)) { diff --git a/compile.c b/compile.c index 8c975782d7..fc3aa8aaab 100644 --- a/compile.c +++ b/compile.c @@ -52,10 +52,10 @@ typedef struct iseq_link_element { enum { - ISEQ_ELEMENT_ANCHOR, - ISEQ_ELEMENT_LABEL, - ISEQ_ELEMENT_INSN, - ISEQ_ELEMENT_ADJUST, + ISEQ_ELEMENT_ANCHOR, + ISEQ_ELEMENT_LABEL, + ISEQ_ELEMENT_INSN, + ISEQ_ELEMENT_ADJUST, ISEQ_ELEMENT_TRACE, } type; struct iseq_link_element *next; @@ -93,9 +93,9 @@ typedef struct iseq_insn_data { int sc_state; VALUE *operands; struct { - int line_no; + int line_no; int node_id; - rb_event_flag_t events; + rb_event_flag_t events; } insn_info; } INSN; @@ -307,8 +307,8 @@ static void iseq_add_setlocal(rb_iseq_t *iseq, LINK_ANCHOR *const seq, const NOD ((label) ? (LABEL_REF(label), (label)->unremovable=1) : 0) #define ADD_CATCH_ENTRY(type, ls, le, iseqv, lc) do { \ VALUE _e = rb_ary_new3(5, (type), \ - (VALUE)(ls) | 1, (VALUE)(le) | 1, \ - (VALUE)(iseqv), (VALUE)(lc) | 1); \ + (VALUE)(ls) | 1, (VALUE)(le) | 1, \ + (VALUE)(iseqv), (VALUE)(lc) | 1); \ LABEL_UNREMOVABLE(ls); \ LABEL_REF(le); \ LABEL_REF(lc); \ @@ -368,11 +368,11 @@ append_compile_error(const rb_iseq_t *iseq, int line, const char *fmt, ...) err = rb_syntax_error_append(err, file, line, -1, NULL, fmt, args); va_end(args); if (NIL_P(err_info)) { - RB_OBJ_WRITE(iseq, &ISEQ_COMPILE_DATA(iseq)->err_info, err); - rb_set_errinfo(err); + RB_OBJ_WRITE(iseq, &ISEQ_COMPILE_DATA(iseq)->err_info, err); + rb_set_errinfo(err); } else if (!err_info) { - RB_OBJ_WRITE(iseq, &ISEQ_COMPILE_DATA(iseq)->err_info, Qtrue); + RB_OBJ_WRITE(iseq, &ISEQ_COMPILE_DATA(iseq)->err_info, Qtrue); } if (compile_debug) { if (SPECIAL_CONST_P(err)) err = rb_eSyntaxError; @@ -402,17 +402,17 @@ do { \ const NODE *error_node = (node); \ enum node_type error_type = nd_type(error_node); \ if (error_type != (ndtype)) { \ - COMPILE_ERROR(ERROR_ARGS_AT(error_node) \ - prefix ": " #ndtype " is expected, but %s", \ - ruby_node_name(error_type)); \ - return errval; \ + COMPILE_ERROR(ERROR_ARGS_AT(error_node) \ + prefix ": " #ndtype " is expected, but %s", \ + ruby_node_name(error_type)); \ + return errval; \ } \ } while (0) #define EXPECT_NODE_NONULL(prefix, parent, ndtype, errval) \ do { \ COMPILE_ERROR(ERROR_ARGS_AT(parent) \ - prefix ": must be " #ndtype ", but 0"); \ + prefix ": must be " #ndtype ", but 0"); \ return errval; \ } while (0) @@ -420,7 +420,7 @@ do { \ do { \ const NODE *error_node = (node); \ COMPILE_ERROR(ERROR_ARGS_AT(error_node) prefix ": unknown node (%s)", \ - ruby_node_name(nd_type(error_node))); \ + ruby_node_name(nd_type(error_node))); \ return errval; \ } while (0) @@ -510,19 +510,19 @@ verify_list(ISEQ_ARG_DECLARE const char *info, LINK_ANCHOR *const anchor) list = anchor->anchor.next; plist = &anchor->anchor; while (list) { - if (plist != list->prev) { - flag += 1; - } - plist = list; - list = list->next; + if (plist != list->prev) { + flag += 1; + } + plist = list; + list = list->next; } if (anchor->last != plist && anchor->last != 0) { - flag |= 0x70000; + flag |= 0x70000; } if (flag != 0) { - rb_bug("list verify error: %08x (%s)", flag, info); + rb_bug("list verify error: %08x (%s)", flag, info); } #endif } @@ -705,11 +705,11 @@ validate_label(st_data_t name, st_data_t label, st_data_t arg) rb_iseq_t *iseq = (rb_iseq_t *)arg; LABEL *lobj = (LABEL *)label; if (!lobj->link.next) { - do { - COMPILE_ERROR(iseq, lobj->position, - "%"PRIsVALUE": undefined label", - rb_sym2str((VALUE)name)); - } while (0); + do { + COMPILE_ERROR(iseq, lobj->position, + "%"PRIsVALUE": undefined label", + rb_sym2str((VALUE)name)); + } while (0); } return ST_CONTINUE; } @@ -748,108 +748,108 @@ rb_iseq_compile_node(rb_iseq_t *iseq, const NODE *node) if (node == 0) { NO_CHECK(COMPILE(ret, "nil", node)); - iseq_set_local_table(iseq, 0); + iseq_set_local_table(iseq, 0); } /* assume node is T_NODE */ else if (nd_type_p(node, NODE_SCOPE)) { - /* iseq type of top, method, class, block */ - iseq_set_local_table(iseq, node->nd_tbl); - iseq_set_arguments(iseq, ret, node->nd_args); + /* iseq type of top, method, class, block */ + iseq_set_local_table(iseq, node->nd_tbl); + iseq_set_arguments(iseq, ret, node->nd_args); switch (ISEQ_BODY(iseq)->type) { - case ISEQ_TYPE_BLOCK: - { - LABEL *start = ISEQ_COMPILE_DATA(iseq)->start_label = NEW_LABEL(0); - LABEL *end = ISEQ_COMPILE_DATA(iseq)->end_label = NEW_LABEL(0); + case ISEQ_TYPE_BLOCK: + { + LABEL *start = ISEQ_COMPILE_DATA(iseq)->start_label = NEW_LABEL(0); + LABEL *end = ISEQ_COMPILE_DATA(iseq)->end_label = NEW_LABEL(0); - start->rescued = LABEL_RESCUE_BEG; - end->rescued = LABEL_RESCUE_END; + start->rescued = LABEL_RESCUE_BEG; + end->rescued = LABEL_RESCUE_END; - ADD_TRACE(ret, RUBY_EVENT_B_CALL); + ADD_TRACE(ret, RUBY_EVENT_B_CALL); NODE dummy_line_node = generate_dummy_line_node(FIX2INT(ISEQ_BODY(iseq)->location.first_lineno), -1); - ADD_INSN (ret, &dummy_line_node, nop); - ADD_LABEL(ret, start); - CHECK(COMPILE(ret, "block body", node->nd_body)); - ADD_LABEL(ret, end); - ADD_TRACE(ret, RUBY_EVENT_B_RETURN); + ADD_INSN (ret, &dummy_line_node, nop); + ADD_LABEL(ret, start); + CHECK(COMPILE(ret, "block body", node->nd_body)); + ADD_LABEL(ret, end); + ADD_TRACE(ret, RUBY_EVENT_B_RETURN); ISEQ_COMPILE_DATA(iseq)->last_line = ISEQ_BODY(iseq)->location.code_location.end_pos.lineno; - /* wide range catch handler must put at last */ - ADD_CATCH_ENTRY(CATCH_TYPE_REDO, start, end, NULL, start); - ADD_CATCH_ENTRY(CATCH_TYPE_NEXT, start, end, NULL, end); - break; - } - case ISEQ_TYPE_CLASS: - { - ADD_TRACE(ret, RUBY_EVENT_CLASS); - CHECK(COMPILE(ret, "scoped node", node->nd_body)); - ADD_TRACE(ret, RUBY_EVENT_END); - ISEQ_COMPILE_DATA(iseq)->last_line = nd_line(node); - break; - } - case ISEQ_TYPE_METHOD: - { + /* wide range catch handler must put at last */ + ADD_CATCH_ENTRY(CATCH_TYPE_REDO, start, end, NULL, start); + ADD_CATCH_ENTRY(CATCH_TYPE_NEXT, start, end, NULL, end); + break; + } + case ISEQ_TYPE_CLASS: + { + ADD_TRACE(ret, RUBY_EVENT_CLASS); + CHECK(COMPILE(ret, "scoped node", node->nd_body)); + ADD_TRACE(ret, RUBY_EVENT_END); + ISEQ_COMPILE_DATA(iseq)->last_line = nd_line(node); + break; + } + case ISEQ_TYPE_METHOD: + { ISEQ_COMPILE_DATA(iseq)->root_node = node->nd_body; - ADD_TRACE(ret, RUBY_EVENT_CALL); - CHECK(COMPILE(ret, "scoped node", node->nd_body)); + ADD_TRACE(ret, RUBY_EVENT_CALL); + CHECK(COMPILE(ret, "scoped node", node->nd_body)); ISEQ_COMPILE_DATA(iseq)->root_node = node->nd_body; - ADD_TRACE(ret, RUBY_EVENT_RETURN); - ISEQ_COMPILE_DATA(iseq)->last_line = nd_line(node); - break; - } - default: { - CHECK(COMPILE(ret, "scoped node", node->nd_body)); - break; - } - } + ADD_TRACE(ret, RUBY_EVENT_RETURN); + ISEQ_COMPILE_DATA(iseq)->last_line = nd_line(node); + break; + } + default: { + CHECK(COMPILE(ret, "scoped node", node->nd_body)); + break; + } + } } else { - const char *m; + const char *m; #define INVALID_ISEQ_TYPE(type) \ - ISEQ_TYPE_##type: m = #type; goto invalid_iseq_type + ISEQ_TYPE_##type: m = #type; goto invalid_iseq_type switch (ISEQ_BODY(iseq)->type) { - case INVALID_ISEQ_TYPE(METHOD); - case INVALID_ISEQ_TYPE(CLASS); - case INVALID_ISEQ_TYPE(BLOCK); - case INVALID_ISEQ_TYPE(EVAL); - case INVALID_ISEQ_TYPE(MAIN); - case INVALID_ISEQ_TYPE(TOP); + case INVALID_ISEQ_TYPE(METHOD); + case INVALID_ISEQ_TYPE(CLASS); + case INVALID_ISEQ_TYPE(BLOCK); + case INVALID_ISEQ_TYPE(EVAL); + case INVALID_ISEQ_TYPE(MAIN); + case INVALID_ISEQ_TYPE(TOP); #undef INVALID_ISEQ_TYPE /* invalid iseq types end */ - case ISEQ_TYPE_RESCUE: - iseq_set_exception_local_table(iseq); - CHECK(COMPILE(ret, "rescue", node)); - break; - case ISEQ_TYPE_ENSURE: - iseq_set_exception_local_table(iseq); - CHECK(COMPILE_POPPED(ret, "ensure", node)); - break; - case ISEQ_TYPE_PLAIN: - CHECK(COMPILE(ret, "ensure", node)); - break; - default: + case ISEQ_TYPE_RESCUE: + iseq_set_exception_local_table(iseq); + CHECK(COMPILE(ret, "rescue", node)); + break; + case ISEQ_TYPE_ENSURE: + iseq_set_exception_local_table(iseq); + CHECK(COMPILE_POPPED(ret, "ensure", node)); + break; + case ISEQ_TYPE_PLAIN: + CHECK(COMPILE(ret, "ensure", node)); + break; + default: COMPILE_ERROR(ERROR_ARGS "unknown scope: %d", ISEQ_BODY(iseq)->type); - return COMPILE_NG; - invalid_iseq_type: - COMPILE_ERROR(ERROR_ARGS "compile/ISEQ_TYPE_%s should not be reached", m); - return COMPILE_NG; - } + return COMPILE_NG; + invalid_iseq_type: + COMPILE_ERROR(ERROR_ARGS "compile/ISEQ_TYPE_%s should not be reached", m); + return COMPILE_NG; + } } if (ISEQ_BODY(iseq)->type == ISEQ_TYPE_RESCUE || ISEQ_BODY(iseq)->type == ISEQ_TYPE_ENSURE) { NODE dummy_line_node = generate_dummy_line_node(0, -1); - ADD_GETLOCAL(ret, &dummy_line_node, LVAR_ERRINFO, 0); - ADD_INSN1(ret, &dummy_line_node, throw, INT2FIX(0) /* continue throw */ ); + ADD_GETLOCAL(ret, &dummy_line_node, LVAR_ERRINFO, 0); + ADD_INSN1(ret, &dummy_line_node, throw, INT2FIX(0) /* continue throw */ ); } else { NODE dummy_line_node = generate_dummy_line_node(ISEQ_COMPILE_DATA(iseq)->last_line, -1); - ADD_INSN(ret, &dummy_line_node, leave); + ADD_INSN(ret, &dummy_line_node, leave); } #if OPT_SUPPORT_JOKE if (ISEQ_COMPILE_DATA(iseq)->labels_table) { - st_table *labels_table = ISEQ_COMPILE_DATA(iseq)->labels_table; - ISEQ_COMPILE_DATA(iseq)->labels_table = 0; - validate_labels(iseq, labels_table); + st_table *labels_table = ISEQ_COMPILE_DATA(iseq)->labels_table; + ISEQ_COMPILE_DATA(iseq)->labels_table = 0; + validate_labels(iseq, labels_table); } #endif CHECK(iseq_setup_insn(iseq, ret)); @@ -866,9 +866,9 @@ rb_iseq_translate_threaded_code(rb_iseq_t *iseq) for (i = 0; i < ISEQ_BODY(iseq)->iseq_size; /* */ ) { int insn = (int)ISEQ_BODY(iseq)->iseq_encoded[i]; - int len = insn_len(insn); - encoded[i] = (VALUE)table[insn]; - i += len; + int len = insn_len(insn); + encoded[i] = (VALUE)table[insn]; + i += len; } FL_SET((VALUE)iseq, ISEQ_TRANSLATED); #endif @@ -886,15 +886,15 @@ rb_iseq_original_iseq(const rb_iseq_t *iseq) /* cold path */ #if OPT_DIRECT_THREADED_CODE || OPT_CALL_THREADED_CODE { - unsigned int i; + unsigned int i; for (i = 0; i < ISEQ_BODY(iseq)->iseq_size; /* */ ) { - const void *addr = (const void *)original_code[i]; - const int insn = rb_vm_insn_addr2insn(addr); + const void *addr = (const void *)original_code[i]; + const int insn = rb_vm_insn_addr2insn(addr); - original_code[i] = insn; - i += insn_len(insn); - } + original_code[i] = insn; + i += insn_len(insn); + } } #endif return original_code; @@ -976,18 +976,18 @@ compile_data_alloc_with_arena(struct iseq_compile_data_storage **arena, size_t s if (size >= INT_MAX - padding) rb_memerror(); if (storage->pos + size + padding > storage->size) { - unsigned int alloc_size = storage->size; + unsigned int alloc_size = storage->size; - while (alloc_size < size + PADDING_SIZE_MAX) { - if (alloc_size >= INT_MAX / 2) rb_memerror(); - alloc_size *= 2; - } - storage->next = (void *)ALLOC_N(char, alloc_size + - offsetof(struct iseq_compile_data_storage, buff)); - storage = *arena = storage->next; - storage->next = 0; - storage->pos = 0; - storage->size = alloc_size; + while (alloc_size < size + PADDING_SIZE_MAX) { + if (alloc_size >= INT_MAX / 2) rb_memerror(); + alloc_size *= 2; + } + storage->next = (void *)ALLOC_N(char, alloc_size + + offsetof(struct iseq_compile_data_storage, buff)); + storage = *arena = storage->next; + storage->next = 0; + storage->pos = 0; + storage->size = alloc_size; #ifdef STRICT_ALIGNMENT padding = calc_padding((void *)&storage->buff[storage->pos], size); #endif /* STRICT_ALIGNMENT */ @@ -1060,7 +1060,7 @@ ELEM_INSERT_NEXT(LINK_ELEMENT *elem1, LINK_ELEMENT *elem2) elem2->prev = elem1; elem1->next = elem2; if (elem2->next) { - elem2->next->prev = elem2; + elem2->next->prev = elem2; } } @@ -1074,7 +1074,7 @@ ELEM_INSERT_PREV(LINK_ELEMENT *elem1, LINK_ELEMENT *elem2) elem2->next = elem1; elem1->prev = elem2; if (elem2->prev) { - elem2->prev->next = elem2; + elem2->prev->next = elem2; } } @@ -1087,10 +1087,10 @@ ELEM_REPLACE(LINK_ELEMENT *elem1, LINK_ELEMENT *elem2) elem2->prev = elem1->prev; elem2->next = elem1->next; if (elem1->prev) { - elem1->prev->next = elem2; + elem1->prev->next = elem2; } if (elem1->next) { - elem1->next->prev = elem2; + elem1->next->prev = elem2; } } @@ -1099,7 +1099,7 @@ ELEM_REMOVE(LINK_ELEMENT *elem) { elem->prev->next = elem->next; if (elem->next) { - elem->next->prev = elem->prev; + elem->next->prev = elem->prev; } } @@ -1119,13 +1119,13 @@ static LINK_ELEMENT * ELEM_FIRST_INSN(LINK_ELEMENT *elem) { while (elem) { - switch (elem->type) { - case ISEQ_ELEMENT_INSN: - case ISEQ_ELEMENT_ADJUST: - return elem; - default: - elem = elem->next; - } + switch (elem->type) { + case ISEQ_ELEMENT_INSN: + case ISEQ_ELEMENT_ADJUST: + return elem; + default: + elem = elem->next; + } } return NULL; } @@ -1135,11 +1135,11 @@ LIST_INSN_SIZE_ONE(const LINK_ANCHOR *const anchor) { LINK_ELEMENT *first_insn = ELEM_FIRST_INSN(FIRST_ELEMENT(anchor)); if (first_insn != NULL && - ELEM_FIRST_INSN(first_insn->next) == NULL) { - return TRUE; + ELEM_FIRST_INSN(first_insn->next) == NULL) { + return TRUE; } else { - return FALSE; + return FALSE; } } @@ -1147,10 +1147,10 @@ static int LIST_INSN_SIZE_ZERO(const LINK_ANCHOR *const anchor) { if (ELEM_FIRST_INSN(FIRST_ELEMENT(anchor)) == NULL) { - return TRUE; + return TRUE; } else { - return FALSE; + return FALSE; } } @@ -1165,9 +1165,9 @@ static void APPEND_LIST(ISEQ_ARG_DECLARE LINK_ANCHOR *const anc1, LINK_ANCHOR *const anc2) { if (anc2->anchor.next) { - anc1->last->next = anc2->anchor.next; - anc2->anchor.next->prev = anc1->last; - anc1->last = anc2->last; + anc1->last->next = anc2->anchor.next; + anc2->anchor.next->prev = anc1->last; + anc1->last = anc2->last; } verify_list("append", anc1); } @@ -1182,11 +1182,11 @@ debug_list(ISEQ_ARG_DECLARE LINK_ANCHOR *const anchor, LINK_ELEMENT *cur) LINK_ELEMENT *list = FIRST_ELEMENT(anchor); printf("----\n"); printf("anch: %p, frst: %p, last: %p\n", (void *)&anchor->anchor, - (void *)anchor->anchor.next, (void *)anchor->last); + (void *)anchor->anchor.next, (void *)anchor->last); while (list) { - printf("curr: %p, next: %p, prev: %p, type: %d\n", (void *)list, (void *)list->next, - (void *)list->prev, (int)list->type); - list = list->next; + printf("curr: %p, next: %p, prev: %p, type: %d\n", (void *)list, (void *)list->next, + (void *)list->prev, (int)list->type); + list = list->next; } printf("----\n"); @@ -1245,7 +1245,7 @@ new_adjust_body(rb_iseq_t *iseq, LABEL *label, int line) static INSN * new_insn_core(rb_iseq_t *iseq, const NODE *line_node, - int insn_id, int argc, VALUE *argv) + int insn_id, int argc, VALUE *argv) { INSN *iobj = compile_data_alloc_insn(iseq); @@ -1269,14 +1269,14 @@ new_insn_body(rb_iseq_t *iseq, const NODE *const line_node, enum ruby_vminsn_typ VALUE *operands = 0; va_list argv; if (argc > 0) { - int i; + int i; va_start(argv, argc); operands = compile_data_alloc2(iseq, sizeof(VALUE), argc); - for (i = 0; i < argc; i++) { - VALUE v = va_arg(argv, VALUE); - operands[i] = v; - } - va_end(argv); + for (i = 0; i < argc; i++) { + VALUE v = va_arg(argv, VALUE); + operands[i] = v; + } + va_end(argv); } return new_insn_core(iseq, line_node, insn_id, argc, operands); } @@ -1320,7 +1320,7 @@ new_insn_send(rb_iseq_t *iseq, const NODE *const line_node, ID id, VALUE argc, c static rb_iseq_t * new_child_iseq(rb_iseq_t *iseq, const NODE *const node, - VALUE name, const rb_iseq_t *parent, enum iseq_type type, int line_no) + VALUE name, const rb_iseq_t *parent, enum iseq_type type, int line_no) { rb_iseq_t *ret_iseq; rb_ast_body_t ast; @@ -1332,7 +1332,7 @@ new_child_iseq(rb_iseq_t *iseq, const NODE *const node, debugs("[new_child_iseq]> ---------------------------------------\n"); int isolated_depth = ISEQ_COMPILE_DATA(iseq)->isolated_depth; ret_iseq = rb_iseq_new_with_opt(&ast, name, - rb_iseq_path(iseq), rb_iseq_realpath(iseq), + rb_iseq_path(iseq), rb_iseq_realpath(iseq), INT2FIX(line_no), parent, isolated_depth ? isolated_depth + 1 : 0, type, ISEQ_COMPILE_DATA(iseq)->option); @@ -1342,14 +1342,14 @@ new_child_iseq(rb_iseq_t *iseq, const NODE *const node, static rb_iseq_t * new_child_iseq_with_callback(rb_iseq_t *iseq, const struct rb_iseq_new_with_callback_callback_func *ifunc, - VALUE name, const rb_iseq_t *parent, enum iseq_type type, int line_no) + VALUE name, const rb_iseq_t *parent, enum iseq_type type, int line_no) { rb_iseq_t *ret_iseq; debugs("[new_child_iseq_with_callback]> ---------------------------------------\n"); ret_iseq = rb_iseq_new_with_callback(ifunc, name, - rb_iseq_path(iseq), rb_iseq_realpath(iseq), - INT2FIX(line_no), parent, type, ISEQ_COMPILE_DATA(iseq)->option); + rb_iseq_path(iseq), rb_iseq_realpath(iseq), + INT2FIX(line_no), parent, type, ISEQ_COMPILE_DATA(iseq)->option); debugs("[new_child_iseq_with_callback]< ---------------------------------------\n"); return ret_iseq; } @@ -1440,31 +1440,31 @@ static int iseq_setup_insn(rb_iseq_t *iseq, LINK_ANCHOR *const anchor) { if (RTEST(ISEQ_COMPILE_DATA(iseq)->err_info)) - return COMPILE_NG; + return COMPILE_NG; /* debugs("[compile step 2] (iseq_array_to_linkedlist)\n"); */ if (compile_debug > 5) - dump_disasm_list(FIRST_ELEMENT(anchor)); + dump_disasm_list(FIRST_ELEMENT(anchor)); debugs("[compile step 3.1 (iseq_optimize)]\n"); iseq_optimize(iseq, anchor); if (compile_debug > 5) - dump_disasm_list(FIRST_ELEMENT(anchor)); + dump_disasm_list(FIRST_ELEMENT(anchor)); if (ISEQ_COMPILE_DATA(iseq)->option->instructions_unification) { - debugs("[compile step 3.2 (iseq_insns_unification)]\n"); - iseq_insns_unification(iseq, anchor); - if (compile_debug > 5) - dump_disasm_list(FIRST_ELEMENT(anchor)); + debugs("[compile step 3.2 (iseq_insns_unification)]\n"); + iseq_insns_unification(iseq, anchor); + if (compile_debug > 5) + dump_disasm_list(FIRST_ELEMENT(anchor)); } if (ISEQ_COMPILE_DATA(iseq)->option->stack_caching) { - debugs("[compile step 3.3 (iseq_set_sequence_stackcaching)]\n"); - iseq_set_sequence_stackcaching(iseq, anchor); - if (compile_debug > 5) - dump_disasm_list(FIRST_ELEMENT(anchor)); + debugs("[compile step 3.3 (iseq_set_sequence_stackcaching)]\n"); + iseq_set_sequence_stackcaching(iseq, anchor); + if (compile_debug > 5) + dump_disasm_list(FIRST_ELEMENT(anchor)); } debugs("[compile step 3.4 (iseq_insert_nop_between_end_and_cont)]\n"); @@ -1484,7 +1484,7 @@ iseq_setup(rb_iseq_t *iseq, LINK_ANCHOR *const anchor) debugs("[compile step 4.1 (iseq_set_sequence)]\n"); if (!iseq_set_sequence(iseq, anchor)) return COMPILE_NG; if (compile_debug > 5) - dump_disasm_list(FIRST_ELEMENT(anchor)); + dump_disasm_list(FIRST_ELEMENT(anchor)); debugs("[compile step 4.2 (iseq_set_exception_table)]\n"); if (!iseq_set_exception_table(iseq)) return COMPILE_NG; @@ -1512,8 +1512,8 @@ iseq_setup(rb_iseq_t *iseq, LINK_ANCHOR *const anchor) #endif if (compile_debug > 1) { - VALUE str = rb_iseq_disasm(iseq); - printf("%s\n", StringValueCStr(str)); + VALUE str = rb_iseq_disasm(iseq); + printf("%s\n", StringValueCStr(str)); } verify_call_cache(iseq); debugs("[compile step: finish]\n"); @@ -1534,7 +1534,7 @@ get_lvar_level(const rb_iseq_t *iseq) { int lev = 0; while (iseq != ISEQ_BODY(iseq)->local_iseq) { - lev++; + lev++; iseq = ISEQ_BODY(iseq)->parent_iseq; } return lev; @@ -1547,8 +1547,8 @@ get_dyna_var_idx_at_raw(const rb_iseq_t *iseq, ID id) for (i = 0; i < ISEQ_BODY(iseq)->local_table_size; i++) { if (ISEQ_BODY(iseq)->local_table[i] == id) { - return (int)i; - } + return (int)i; + } } return -1; } @@ -1573,12 +1573,12 @@ get_dyna_var_idx(const rb_iseq_t *iseq, ID id, int *level, int *ls) const rb_iseq_t *const topmost_iseq = iseq; while (iseq) { - idx = get_dyna_var_idx_at_raw(iseq, id); - if (idx >= 0) { - break; - } + idx = get_dyna_var_idx_at_raw(iseq, id); + if (idx >= 0) { + break; + } iseq = ISEQ_BODY(iseq)->parent_iseq; - lv++; + lv++; } if (idx < 0) { @@ -1597,16 +1597,16 @@ iseq_local_block_param_p(const rb_iseq_t *iseq, unsigned int idx, unsigned int l const struct rb_iseq_constant_body *body; while (level > 0) { iseq = ISEQ_BODY(iseq)->parent_iseq; - level--; + level--; } body = ISEQ_BODY(iseq); if (body->local_iseq == iseq && /* local variables */ - body->param.flags.has_block && - body->local_table_size - body->param.block_start == idx) { - return TRUE; + body->param.flags.has_block && + body->local_table_size - body->param.block_start == idx) { + return TRUE; } else { - return FALSE; + return FALSE; } } @@ -1616,12 +1616,12 @@ iseq_block_param_id_p(const rb_iseq_t *iseq, ID id, int *pidx, int *plevel) int level, ls; int idx = get_dyna_var_idx(iseq, id, &level, &ls); if (iseq_local_block_param_p(iseq, ls - idx, level)) { - *pidx = ls - idx; - *plevel = level; - return TRUE; + *pidx = ls - idx; + *plevel = level; + return TRUE; } else { - return FALSE; + return FALSE; } } @@ -1676,10 +1676,10 @@ static void iseq_add_getlocal(rb_iseq_t *iseq, LINK_ANCHOR *const seq, const NODE *const line_node, int idx, int level) { if (iseq_local_block_param_p(iseq, idx, level)) { - ADD_INSN2(seq, line_node, getblockparam, INT2FIX((idx) + VM_ENV_DATA_SIZE - 1), INT2FIX(level)); + ADD_INSN2(seq, line_node, getblockparam, INT2FIX((idx) + VM_ENV_DATA_SIZE - 1), INT2FIX(level)); } else { - ADD_INSN2(seq, line_node, getlocal, INT2FIX((idx) + VM_ENV_DATA_SIZE - 1), INT2FIX(level)); + ADD_INSN2(seq, line_node, getlocal, INT2FIX((idx) + VM_ENV_DATA_SIZE - 1), INT2FIX(level)); } if (level > 0) access_outer_variables(iseq, level, iseq_lvar_id(iseq, idx, level), Qfalse); } @@ -1688,10 +1688,10 @@ static void iseq_add_setlocal(rb_iseq_t *iseq, LINK_ANCHOR *const seq, const NODE *const line_node, int idx, int level) { if (iseq_local_block_param_p(iseq, idx, level)) { - ADD_INSN2(seq, line_node, setblockparam, INT2FIX((idx) + VM_ENV_DATA_SIZE - 1), INT2FIX(level)); + ADD_INSN2(seq, line_node, setblockparam, INT2FIX((idx) + VM_ENV_DATA_SIZE - 1), INT2FIX(level)); } else { - ADD_INSN2(seq, line_node, setlocal, INT2FIX((idx) + VM_ENV_DATA_SIZE - 1), INT2FIX(level)); + ADD_INSN2(seq, line_node, setlocal, INT2FIX((idx) + VM_ENV_DATA_SIZE - 1), INT2FIX(level)); } if (level > 0) access_outer_variables(iseq, level, iseq_lvar_id(iseq, idx, level), Qtrue); } @@ -1703,42 +1703,42 @@ iseq_calc_param_size(rb_iseq_t *iseq) { struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq); if (body->param.flags.has_opt || - body->param.flags.has_post || - body->param.flags.has_rest || - body->param.flags.has_block || - body->param.flags.has_kw || - body->param.flags.has_kwrest) { + body->param.flags.has_post || + body->param.flags.has_rest || + body->param.flags.has_block || + body->param.flags.has_kw || + body->param.flags.has_kwrest) { - if (body->param.flags.has_block) { - body->param.size = body->param.block_start + 1; - } - else if (body->param.flags.has_kwrest) { - body->param.size = body->param.keyword->rest_start + 1; - } - else if (body->param.flags.has_kw) { - body->param.size = body->param.keyword->bits_start + 1; - } - else if (body->param.flags.has_post) { - body->param.size = body->param.post_start + body->param.post_num; - } - else if (body->param.flags.has_rest) { - body->param.size = body->param.rest_start + 1; - } - else if (body->param.flags.has_opt) { - body->param.size = body->param.lead_num + body->param.opt_num; - } - else { + if (body->param.flags.has_block) { + body->param.size = body->param.block_start + 1; + } + else if (body->param.flags.has_kwrest) { + body->param.size = body->param.keyword->rest_start + 1; + } + else if (body->param.flags.has_kw) { + body->param.size = body->param.keyword->bits_start + 1; + } + else if (body->param.flags.has_post) { + body->param.size = body->param.post_start + body->param.post_num; + } + else if (body->param.flags.has_rest) { + body->param.size = body->param.rest_start + 1; + } + else if (body->param.flags.has_opt) { + body->param.size = body->param.lead_num + body->param.opt_num; + } + else { UNREACHABLE; - } + } } else { - body->param.size = body->param.lead_num; + body->param.size = body->param.lead_num; } } static int iseq_set_arguments_keywords(rb_iseq_t *iseq, LINK_ANCHOR *const optargs, - const struct rb_args_info *args, int arg_size) + const struct rb_args_info *args, int arg_size) { const NODE *node = args->kw_args; struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq); @@ -1751,68 +1751,68 @@ iseq_set_arguments_keywords(rb_iseq_t *iseq, LINK_ANCHOR *const optargs, body->param.keyword = keyword = ZALLOC_N(struct rb_iseq_param_keyword, 1); while (node) { - kw++; - node = node->nd_next; + kw++; + node = node->nd_next; } arg_size += kw; keyword->bits_start = arg_size++; node = args->kw_args; while (node) { - const NODE *val_node = node->nd_body->nd_value; - VALUE dv; + const NODE *val_node = node->nd_body->nd_value; + VALUE dv; if (val_node == NODE_SPECIAL_REQUIRED_KEYWORD) { - ++rkw; - } - else { - switch (nd_type(val_node)) { - case NODE_LIT: - dv = val_node->nd_lit; - break; - case NODE_NIL: - dv = Qnil; - break; - case NODE_TRUE: - dv = Qtrue; - break; - case NODE_FALSE: - dv = Qfalse; - break; - default: + ++rkw; + } + else { + switch (nd_type(val_node)) { + case NODE_LIT: + dv = val_node->nd_lit; + break; + case NODE_NIL: + dv = Qnil; + break; + case NODE_TRUE: + dv = Qtrue; + break; + case NODE_FALSE: + dv = Qfalse; + break; + default: NO_CHECK(COMPILE_POPPED(optargs, "kwarg", node)); /* nd_type_p(node, NODE_KW_ARG) */ - dv = complex_mark; - } + dv = complex_mark; + } - keyword->num = ++di; - rb_ary_push(default_values, dv); - } + keyword->num = ++di; + rb_ary_push(default_values, dv); + } - node = node->nd_next; + node = node->nd_next; } keyword->num = kw; if (args->kw_rest_arg->nd_vid != 0) { - keyword->rest_start = arg_size++; - body->param.flags.has_kwrest = TRUE; + keyword->rest_start = arg_size++; + body->param.flags.has_kwrest = TRUE; } keyword->required_num = rkw; keyword->table = &body->local_table[keyword->bits_start - keyword->num]; { - VALUE *dvs = ALLOC_N(VALUE, RARRAY_LEN(default_values)); + VALUE *dvs = ALLOC_N(VALUE, RARRAY_LEN(default_values)); - for (i = 0; i < RARRAY_LEN(default_values); i++) { - VALUE dv = RARRAY_AREF(default_values, i); - if (dv == complex_mark) dv = Qundef; - if (!SPECIAL_CONST_P(dv)) { - RB_OBJ_WRITTEN(iseq, Qundef, dv); - } - dvs[i] = dv; - } + for (i = 0; i < RARRAY_LEN(default_values); i++) { + VALUE dv = RARRAY_AREF(default_values, i); + if (dv == complex_mark) dv = Qundef; + if (!SPECIAL_CONST_P(dv)) { + RB_OBJ_WRITTEN(iseq, Qundef, dv); + } + dvs[i] = dv; + } - keyword->default_values = dvs; + keyword->default_values = dvs; } return arg_size; } @@ -1824,119 +1824,119 @@ iseq_set_arguments(rb_iseq_t *iseq, LINK_ANCHOR *const optargs, const NODE *cons if (node_args) { struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq); - struct rb_args_info *args = node_args->nd_ainfo; - ID rest_id = 0; - int last_comma = 0; - ID block_id = 0; - int arg_size; + struct rb_args_info *args = node_args->nd_ainfo; + ID rest_id = 0; + int last_comma = 0; + ID block_id = 0; + int arg_size; - EXPECT_NODE("iseq_set_arguments", node_args, NODE_ARGS, COMPILE_NG); + EXPECT_NODE("iseq_set_arguments", node_args, NODE_ARGS, COMPILE_NG); body->param.flags.ruby2_keywords = args->ruby2_keywords; - body->param.lead_num = arg_size = (int)args->pre_args_num; - if (body->param.lead_num > 0) body->param.flags.has_lead = TRUE; - debugs(" - argc: %d\n", body->param.lead_num); + body->param.lead_num = arg_size = (int)args->pre_args_num; + if (body->param.lead_num > 0) body->param.flags.has_lead = TRUE; + debugs(" - argc: %d\n", body->param.lead_num); - rest_id = args->rest_arg; + rest_id = args->rest_arg; if (rest_id == NODE_SPECIAL_EXCESSIVE_COMMA) { - last_comma = 1; - rest_id = 0; - } - block_id = args->block_arg; + last_comma = 1; + rest_id = 0; + } + block_id = args->block_arg; - if (args->opt_args) { - const NODE *node = args->opt_args; - LABEL *label; - VALUE labels = rb_ary_tmp_new(1); - VALUE *opt_table; - int i = 0, j; + if (args->opt_args) { + const NODE *node = args->opt_args; + LABEL *label; + VALUE labels = rb_ary_tmp_new(1); + VALUE *opt_table; + int i = 0, j; - while (node) { - label = NEW_LABEL(nd_line(node)); - rb_ary_push(labels, (VALUE)label | 1); - ADD_LABEL(optargs, label); + while (node) { + label = NEW_LABEL(nd_line(node)); + rb_ary_push(labels, (VALUE)label | 1); + ADD_LABEL(optargs, label); NO_CHECK(COMPILE_POPPED(optargs, "optarg", node->nd_body)); - node = node->nd_next; - i += 1; - } + node = node->nd_next; + i += 1; + } - /* last label */ - label = NEW_LABEL(nd_line(node_args)); - rb_ary_push(labels, (VALUE)label | 1); - ADD_LABEL(optargs, label); + /* last label */ + label = NEW_LABEL(nd_line(node_args)); + rb_ary_push(labels, (VALUE)label | 1); + ADD_LABEL(optargs, label); - opt_table = ALLOC_N(VALUE, i+1); + opt_table = ALLOC_N(VALUE, i+1); MEMCPY(opt_table, RARRAY_CONST_PTR_TRANSIENT(labels), VALUE, i+1); - for (j = 0; j < i+1; j++) { - opt_table[j] &= ~1; - } - rb_ary_clear(labels); + for (j = 0; j < i+1; j++) { + opt_table[j] &= ~1; + } + rb_ary_clear(labels); - body->param.flags.has_opt = TRUE; - body->param.opt_num = i; - body->param.opt_table = opt_table; - arg_size += i; - } + body->param.flags.has_opt = TRUE; + body->param.opt_num = i; + body->param.opt_table = opt_table; + arg_size += i; + } - if (rest_id) { - body->param.rest_start = arg_size++; - body->param.flags.has_rest = TRUE; - assert(body->param.rest_start != -1); - } + if (rest_id) { + body->param.rest_start = arg_size++; + body->param.flags.has_rest = TRUE; + assert(body->param.rest_start != -1); + } - if (args->first_post_arg) { - body->param.post_start = arg_size; - body->param.post_num = args->post_args_num; - body->param.flags.has_post = TRUE; - arg_size += args->post_args_num; + if (args->first_post_arg) { + body->param.post_start = arg_size; + body->param.post_num = args->post_args_num; + body->param.flags.has_post = TRUE; + arg_size += args->post_args_num; - if (body->param.flags.has_rest) { /* TODO: why that? */ - body->param.post_start = body->param.rest_start + 1; - } - } + if (body->param.flags.has_rest) { /* TODO: why that? */ + body->param.post_start = body->param.rest_start + 1; + } + } - if (args->kw_args) { - arg_size = iseq_set_arguments_keywords(iseq, optargs, args, arg_size); - } - else if (args->kw_rest_arg) { - struct rb_iseq_param_keyword *keyword = ZALLOC_N(struct rb_iseq_param_keyword, 1); - keyword->rest_start = arg_size++; - body->param.keyword = keyword; - body->param.flags.has_kwrest = TRUE; - } - else if (args->no_kwarg) { - body->param.flags.accepts_no_kwarg = TRUE; - } + if (args->kw_args) { + arg_size = iseq_set_arguments_keywords(iseq, optargs, args, arg_size); + } + else if (args->kw_rest_arg) { + struct rb_iseq_param_keyword *keyword = ZALLOC_N(struct rb_iseq_param_keyword, 1); + keyword->rest_start = arg_size++; + body->param.keyword = keyword; + body->param.flags.has_kwrest = TRUE; + } + else if (args->no_kwarg) { + body->param.flags.accepts_no_kwarg = TRUE; + } - if (block_id) { - body->param.block_start = arg_size++; - body->param.flags.has_block = TRUE; - } + if (block_id) { + body->param.block_start = arg_size++; + body->param.flags.has_block = TRUE; + } - iseq_calc_param_size(iseq); - body->param.size = arg_size; + iseq_calc_param_size(iseq); + body->param.size = arg_size; - if (args->pre_init) { /* m_init */ + if (args->pre_init) { /* m_init */ NO_CHECK(COMPILE_POPPED(optargs, "init arguments (m)", args->pre_init)); - } - if (args->post_init) { /* p_init */ + } + if (args->post_init) { /* p_init */ NO_CHECK(COMPILE_POPPED(optargs, "init arguments (p)", args->post_init)); - } + } - if (body->type == ISEQ_TYPE_BLOCK) { - if (body->param.flags.has_opt == FALSE && - body->param.flags.has_post == FALSE && - body->param.flags.has_rest == FALSE && - body->param.flags.has_kw == FALSE && - body->param.flags.has_kwrest == FALSE) { + if (body->type == ISEQ_TYPE_BLOCK) { + if (body->param.flags.has_opt == FALSE && + body->param.flags.has_post == FALSE && + body->param.flags.has_rest == FALSE && + body->param.flags.has_kw == FALSE && + body->param.flags.has_kwrest == FALSE) { - if (body->param.lead_num == 1 && last_comma == 0) { - /* {|a|} */ - body->param.flags.ambiguous_param0 = TRUE; - } - } - } + if (body->param.lead_num == 1 && last_comma == 0) { + /* {|a|} */ + body->param.flags.ambiguous_param0 = TRUE; + } + } + } } return COMPILE_OK; @@ -1948,8 +1948,8 @@ iseq_set_local_table(rb_iseq_t *iseq, const rb_ast_id_table_t *tbl) unsigned int size = tbl ? tbl->size : 0; if (size > 0) { - ID *ids = (ID *)ALLOC_N(ID, size); - MEMCPY(ids, tbl->ids, ID, size); + ID *ids = (ID *)ALLOC_N(ID, size); + MEMCPY(ids, tbl->ids, ID, size); ISEQ_BODY(iseq)->local_table = ids; } ISEQ_BODY(iseq)->local_table_size = size; @@ -2061,13 +2061,13 @@ get_ivar_ic_value(rb_iseq_t *iseq,ID id) VALUE val; struct rb_id_table *tbl = ISEQ_COMPILE_DATA(iseq)->ivar_cache_table; if (tbl) { - if (rb_id_table_lookup(tbl,id,&val)) { - return val; - } + if (rb_id_table_lookup(tbl,id,&val)) { + return val; + } } else { - tbl = rb_id_table_create(1); - ISEQ_COMPILE_DATA(iseq)->ivar_cache_table = tbl; + tbl = rb_id_table_create(1); + ISEQ_COMPILE_DATA(iseq)->ivar_cache_table = tbl; } val = INT2FIX(ISEQ_BODY(iseq)->ivc_size++); rb_id_table_insert(tbl,id,val); @@ -2080,13 +2080,13 @@ get_cvar_ic_value(rb_iseq_t *iseq,ID id) VALUE val; struct rb_id_table *tbl = ISEQ_COMPILE_DATA(iseq)->ivar_cache_table; if (tbl) { - if (rb_id_table_lookup(tbl,id,&val)) { - return val; - } + if (rb_id_table_lookup(tbl,id,&val)) { + return val; + } } else { - tbl = rb_id_table_create(1); - ISEQ_COMPILE_DATA(iseq)->ivar_cache_table = tbl; + tbl = rb_id_table_create(1); + ISEQ_COMPILE_DATA(iseq)->ivar_cache_table = tbl; } val = INT2FIX(ISEQ_BODY(iseq)->icvarc_size++); rb_id_table_insert(tbl,id,val); @@ -2109,113 +2109,113 @@ fix_sp_depth(rb_iseq_t *iseq, LINK_ANCHOR *const anchor) LINK_ELEMENT *list; for (list = FIRST_ELEMENT(anchor); list; list = list->next) { - if (IS_LABEL(list)) { - LABEL *lobj = (LABEL *)list; - lobj->set = TRUE; - } + if (IS_LABEL(list)) { + LABEL *lobj = (LABEL *)list; + lobj->set = TRUE; + } } for (list = FIRST_ELEMENT(anchor); list; list = list->next) { - switch (list->type) { - case ISEQ_ELEMENT_INSN: - { - int j, len, insn; - const char *types; - VALUE *operands; - INSN *iobj = (INSN *)list; + switch (list->type) { + case ISEQ_ELEMENT_INSN: + { + int j, len, insn; + const char *types; + VALUE *operands; + INSN *iobj = (INSN *)list; - /* update sp */ - sp = calc_sp_depth(sp, iobj); - if (sp < 0) { - BADINSN_DUMP(anchor, list, NULL); - COMPILE_ERROR(iseq, iobj->insn_info.line_no, - "argument stack underflow (%d)", sp); - return -1; - } - if (sp > stack_max) { - stack_max = sp; - } + /* update sp */ + sp = calc_sp_depth(sp, iobj); + if (sp < 0) { + BADINSN_DUMP(anchor, list, NULL); + COMPILE_ERROR(iseq, iobj->insn_info.line_no, + "argument stack underflow (%d)", sp); + return -1; + } + if (sp > stack_max) { + stack_max = sp; + } - line = iobj->insn_info.line_no; - /* fprintf(stderr, "insn: %-16s, sp: %d\n", insn_name(iobj->insn_id), sp); */ - operands = iobj->operands; - insn = iobj->insn_id; - types = insn_op_types(insn); - len = insn_len(insn); + line = iobj->insn_info.line_no; + /* fprintf(stderr, "insn: %-16s, sp: %d\n", insn_name(iobj->insn_id), sp); */ + operands = iobj->operands; + insn = iobj->insn_id; + types = insn_op_types(insn); + len = insn_len(insn); - /* operand check */ - if (iobj->operand_size != len - 1) { - /* printf("operand size miss! (%d, %d)\n", iobj->operand_size, len); */ - BADINSN_DUMP(anchor, list, NULL); - COMPILE_ERROR(iseq, iobj->insn_info.line_no, - "operand size miss! (%d for %d)", - iobj->operand_size, len - 1); - return -1; - } + /* operand check */ + if (iobj->operand_size != len - 1) { + /* printf("operand size miss! (%d, %d)\n", iobj->operand_size, len); */ + BADINSN_DUMP(anchor, list, NULL); + COMPILE_ERROR(iseq, iobj->insn_info.line_no, + "operand size miss! (%d for %d)", + iobj->operand_size, len - 1); + return -1; + } - for (j = 0; types[j]; j++) { - if (types[j] == TS_OFFSET) { - /* label(destination position) */ - LABEL *lobj = (LABEL *)operands[j]; - if (!lobj->set) { - BADINSN_DUMP(anchor, list, NULL); - COMPILE_ERROR(iseq, iobj->insn_info.line_no, - "unknown label: "LABEL_FORMAT, lobj->label_no); - return -1; - } - if (lobj->sp == -1) { - lobj->sp = sp; + for (j = 0; types[j]; j++) { + if (types[j] == TS_OFFSET) { + /* label(destination position) */ + LABEL *lobj = (LABEL *)operands[j]; + if (!lobj->set) { + BADINSN_DUMP(anchor, list, NULL); + COMPILE_ERROR(iseq, iobj->insn_info.line_no, + "unknown label: "LABEL_FORMAT, lobj->label_no); + return -1; + } + if (lobj->sp == -1) { + lobj->sp = sp; } else if (lobj->sp != sp) { debugs("%s:%d: sp inconsistency found but ignored (" LABEL_FORMAT " sp: %d, calculated sp: %d)\n", RSTRING_PTR(rb_iseq_path(iseq)), line, lobj->label_no, lobj->sp, sp); } - } - } - break; - } - case ISEQ_ELEMENT_LABEL: - { - LABEL *lobj = (LABEL *)list; - if (lobj->sp == -1) { - lobj->sp = sp; - } - else { + } + } + break; + } + case ISEQ_ELEMENT_LABEL: + { + LABEL *lobj = (LABEL *)list; + if (lobj->sp == -1) { + lobj->sp = sp; + } + else { if (lobj->sp != sp) { debugs("%s:%d: sp inconsistency found but ignored (" LABEL_FORMAT " sp: %d, calculated sp: %d)\n", RSTRING_PTR(rb_iseq_path(iseq)), line, lobj->label_no, lobj->sp, sp); } - sp = lobj->sp; - } - break; - } - case ISEQ_ELEMENT_TRACE: - { - /* ignore */ - break; - } - case ISEQ_ELEMENT_ADJUST: - { - ADJUST *adjust = (ADJUST *)list; - int orig_sp = sp; + sp = lobj->sp; + } + break; + } + case ISEQ_ELEMENT_TRACE: + { + /* ignore */ + break; + } + case ISEQ_ELEMENT_ADJUST: + { + ADJUST *adjust = (ADJUST *)list; + int orig_sp = sp; - sp = adjust->label ? adjust->label->sp : 0; - if (adjust->line_no != -1 && orig_sp - sp < 0) { - BADINSN_DUMP(anchor, list, NULL); - COMPILE_ERROR(iseq, adjust->line_no, - "iseq_set_sequence: adjust bug %d < %d", - orig_sp, sp); - return -1; - } - break; - } - default: - BADINSN_DUMP(anchor, list, NULL); - COMPILE_ERROR(iseq, line, "unknown list type: %d", list->type); - return -1; - } + sp = adjust->label ? adjust->label->sp : 0; + if (adjust->line_no != -1 && orig_sp - sp < 0) { + BADINSN_DUMP(anchor, list, NULL); + COMPILE_ERROR(iseq, adjust->line_no, + "iseq_set_sequence: adjust bug %d < %d", + orig_sp, sp); + return -1; + } + break; + } + default: + BADINSN_DUMP(anchor, list, NULL); + COMPILE_ERROR(iseq, line, "unknown list type: %d", list->type); + return -1; + } } return stack_max; } @@ -2273,13 +2273,13 @@ iseq_set_sequence(rb_iseq_t *iseq, LINK_ANCHOR *const anchor) /* fix label position */ insn_num = code_index = 0; for (list = FIRST_ELEMENT(anchor); list; list = list->next) { - switch (list->type) { - case ISEQ_ELEMENT_INSN: - { - INSN *iobj = (INSN *)list; - /* update sp */ - sp = calc_sp_depth(sp, iobj); - insn_num++; + switch (list->type) { + case ISEQ_ELEMENT_INSN: + { + INSN *iobj = (INSN *)list; + /* update sp */ + sp = calc_sp_depth(sp, iobj); + insn_num++; events = iobj->insn_info.events |= events; if (ISEQ_COVERAGE(iseq)) { if (ISEQ_LINE_COVERAGE(iseq) && (events & RUBY_EVENT_COVERAGE_LINE) && @@ -2295,47 +2295,47 @@ iseq_set_sequence(rb_iseq_t *iseq, LINK_ANCHOR *const anchor) } RARRAY_ASET(ISEQ_PC2BRANCHINDEX(iseq), code_index, INT2FIX(data)); } - } + } code_index += insn_data_length(iobj); - events = 0; + events = 0; data = 0; - break; - } - case ISEQ_ELEMENT_LABEL: - { - LABEL *lobj = (LABEL *)list; - lobj->position = code_index; + break; + } + case ISEQ_ELEMENT_LABEL: + { + LABEL *lobj = (LABEL *)list; + lobj->position = code_index; if (lobj->sp != sp) { debugs("%s: sp inconsistency found but ignored (" LABEL_FORMAT " sp: %d, calculated sp: %d)\n", RSTRING_PTR(rb_iseq_path(iseq)), lobj->label_no, lobj->sp, sp); } - sp = lobj->sp; - break; - } - case ISEQ_ELEMENT_TRACE: - { - TRACE *trace = (TRACE *)list; - events |= trace->event; + sp = lobj->sp; + break; + } + case ISEQ_ELEMENT_TRACE: + { + TRACE *trace = (TRACE *)list; + events |= trace->event; if (trace->event & RUBY_EVENT_COVERAGE_BRANCH) data = trace->data; - break; - } - case ISEQ_ELEMENT_ADJUST: - { - ADJUST *adjust = (ADJUST *)list; - if (adjust->line_no != -1) { - int orig_sp = sp; - sp = adjust->label ? adjust->label->sp : 0; - if (orig_sp - sp > 0) { - if (orig_sp - sp > 1) code_index++; /* 1 operand */ - code_index++; /* insn */ - insn_num++; - } - } - break; - } - default: break; - } + break; + } + case ISEQ_ELEMENT_ADJUST: + { + ADJUST *adjust = (ADJUST *)list; + if (adjust->line_no != -1) { + int orig_sp = sp; + sp = adjust->label ? adjust->label->sp : 0; + if (orig_sp - sp > 0) { + if (orig_sp - sp > 1) code_index++; /* 1 operand */ + code_index++; /* insn */ + insn_num++; + } + } + break; + } + default: break; + } } /* make instruction sequence */ @@ -2368,92 +2368,92 @@ iseq_set_sequence(rb_iseq_t *iseq, LINK_ANCHOR *const anchor) insns_info_index = code_index = sp = 0; while (list) { - switch (list->type) { - case ISEQ_ELEMENT_INSN: - { - int j, len, insn; - const char *types; - VALUE *operands; - INSN *iobj = (INSN *)list; + switch (list->type) { + case ISEQ_ELEMENT_INSN: + { + int j, len, insn; + const char *types; + VALUE *operands; + INSN *iobj = (INSN *)list; - /* update sp */ - sp = calc_sp_depth(sp, iobj); - /* fprintf(stderr, "insn: %-16s, sp: %d\n", insn_name(iobj->insn_id), sp); */ - operands = iobj->operands; - insn = iobj->insn_id; - generated_iseq[code_index] = insn; - types = insn_op_types(insn); - len = insn_len(insn); + /* update sp */ + sp = calc_sp_depth(sp, iobj); + /* fprintf(stderr, "insn: %-16s, sp: %d\n", insn_name(iobj->insn_id), sp); */ + operands = iobj->operands; + insn = iobj->insn_id; + generated_iseq[code_index] = insn; + types = insn_op_types(insn); + len = insn_len(insn); - for (j = 0; types[j]; j++) { - char type = types[j]; + for (j = 0; types[j]; j++) { + char type = types[j]; - /* printf("--> [%c - (%d-%d)]\n", type, k, j); */ - switch (type) { - case TS_OFFSET: - { - /* label(destination position) */ - LABEL *lobj = (LABEL *)operands[j]; - generated_iseq[code_index + 1 + j] = lobj->position - (code_index + len); - break; - } - case TS_CDHASH: - { - VALUE map = operands[j]; - struct cdhash_set_label_struct data; + /* printf("--> [%c - (%d-%d)]\n", type, k, j); */ + switch (type) { + case TS_OFFSET: + { + /* label(destination position) */ + LABEL *lobj = (LABEL *)operands[j]; + generated_iseq[code_index + 1 + j] = lobj->position - (code_index + len); + break; + } + case TS_CDHASH: + { + VALUE map = operands[j]; + struct cdhash_set_label_struct data; data.hash = map; data.pos = code_index; data.len = len; - rb_hash_foreach(map, cdhash_set_label_i, (VALUE)&data); + rb_hash_foreach(map, cdhash_set_label_i, (VALUE)&data); - rb_hash_rehash(map); - freeze_hide_obj(map); - generated_iseq[code_index + 1 + j] = map; + rb_hash_rehash(map); + freeze_hide_obj(map); + generated_iseq[code_index + 1 + j] = map; ISEQ_MBITS_SET(mark_offset_bits, code_index + 1 + j); - RB_OBJ_WRITTEN(iseq, Qundef, map); + RB_OBJ_WRITTEN(iseq, Qundef, map); needs_bitmap = true; - break; - } - case TS_LINDEX: - case TS_NUM: /* ulong */ - generated_iseq[code_index + 1 + j] = FIX2INT(operands[j]); - break; - case TS_ISEQ: /* iseq */ - case TS_VALUE: /* VALUE */ - { - VALUE v = operands[j]; - generated_iseq[code_index + 1 + j] = v; - /* to mark ruby object */ - if (!SPECIAL_CONST_P(v)) { - RB_OBJ_WRITTEN(iseq, Qundef, v); + break; + } + case TS_LINDEX: + case TS_NUM: /* ulong */ + generated_iseq[code_index + 1 + j] = FIX2INT(operands[j]); + break; + case TS_ISEQ: /* iseq */ + case TS_VALUE: /* VALUE */ + { + VALUE v = operands[j]; + generated_iseq[code_index + 1 + j] = v; + /* to mark ruby object */ + if (!SPECIAL_CONST_P(v)) { + RB_OBJ_WRITTEN(iseq, Qundef, v); ISEQ_MBITS_SET(mark_offset_bits, code_index + 1 + j); needs_bitmap = true; - } - break; - } + } + break; + } /* [ TS_IVC | TS_ICVARC | TS_ISE | TS_IC ] */ case TS_IC: /* inline cache: constants */ case TS_ISE: /* inline storage entry: `once` insn */ case TS_ICVARC: /* inline cvar cache */ - case TS_IVC: /* inline ivar cache */ - { - unsigned int ic_index = FIX2UINT(operands[j]); + case TS_IVC: /* inline ivar cache */ + { + unsigned int ic_index = FIX2UINT(operands[j]); IC ic = &ISEQ_IS_ENTRY_START(body, type)[ic_index].ic_cache; - if (UNLIKELY(ic_index >= ISEQ_IS_SIZE(body))) { + if (UNLIKELY(ic_index >= ISEQ_IS_SIZE(body))) { BADINSN_DUMP(anchor, &iobj->link, 0); COMPILE_ERROR(iseq, iobj->insn_info.line_no, "iseq_set_sequence: ic_index overflow: index: %d, size: %d", ic_index, ISEQ_IS_SIZE(body)); - } - generated_iseq[code_index + 1 + j] = (VALUE)ic; + } + generated_iseq[code_index + 1 + j] = (VALUE)ic; if (insn == BIN(opt_getinlinecache) && type == TS_IC) { // Store the instruction index for opt_getinlinecache on the IC for // YJIT to invalidate code when opt_setinlinecache runs. ic->get_insn_idx = (unsigned int)code_index; } - break; - } + break; + } case TS_CALLDATA: { const struct rb_callinfo *source_ci = (const struct rb_callinfo *)operands[j]; @@ -2464,86 +2464,86 @@ iseq_set_sequence(rb_iseq_t *iseq, LINK_ANCHOR *const anchor) generated_iseq[code_index + 1 + j] = (VALUE)cd; break; } - case TS_ID: /* ID */ - generated_iseq[code_index + 1 + j] = SYM2ID(operands[j]); - break; - case TS_FUNCPTR: - generated_iseq[code_index + 1 + j] = operands[j]; - break; + case TS_ID: /* ID */ + generated_iseq[code_index + 1 + j] = SYM2ID(operands[j]); + break; + case TS_FUNCPTR: + generated_iseq[code_index + 1 + j] = operands[j]; + break; case TS_BUILTIN: generated_iseq[code_index + 1 + j] = operands[j]; break; - default: - BADINSN_ERROR(iseq, iobj->insn_info.line_no, - "unknown operand type: %c", type); - return COMPILE_NG; - } - } - if (add_insn_info(insns_info, positions, insns_info_index, code_index, iobj)) insns_info_index++; - code_index += len; - break; - } - case ISEQ_ELEMENT_LABEL: - { - LABEL *lobj = (LABEL *)list; + default: + BADINSN_ERROR(iseq, iobj->insn_info.line_no, + "unknown operand type: %c", type); + return COMPILE_NG; + } + } + if (add_insn_info(insns_info, positions, insns_info_index, code_index, iobj)) insns_info_index++; + code_index += len; + break; + } + case ISEQ_ELEMENT_LABEL: + { + LABEL *lobj = (LABEL *)list; if (lobj->sp != sp) { debugs("%s: sp inconsistency found but ignored (" LABEL_FORMAT " sp: %d, calculated sp: %d)\n", RSTRING_PTR(rb_iseq_path(iseq)), lobj->label_no, lobj->sp, sp); } - sp = lobj->sp; - break; - } - case ISEQ_ELEMENT_ADJUST: - { - ADJUST *adjust = (ADJUST *)list; - int orig_sp = sp; + sp = lobj->sp; + break; + } + case ISEQ_ELEMENT_ADJUST: + { + ADJUST *adjust = (ADJUST *)list; + int orig_sp = sp; - if (adjust->label) { - sp = adjust->label->sp; - } - else { - sp = 0; - } + if (adjust->label) { + sp = adjust->label->sp; + } + else { + sp = 0; + } - if (adjust->line_no != -1) { - const int diff = orig_sp - sp; - if (diff > 0) { + if (adjust->line_no != -1) { + const int diff = orig_sp - sp; + if (diff > 0) { if (insns_info_index == 0) { COMPILE_ERROR(iseq, adjust->line_no, "iseq_set_sequence: adjust bug (ISEQ_ELEMENT_ADJUST must not be the first in iseq)"); } - if (add_adjust_info(insns_info, positions, insns_info_index, code_index, adjust)) insns_info_index++; - } - if (diff > 1) { - generated_iseq[code_index++] = BIN(adjuststack); - generated_iseq[code_index++] = orig_sp - sp; - } - else if (diff == 1) { - generated_iseq[code_index++] = BIN(pop); - } - else if (diff < 0) { - int label_no = adjust->label ? adjust->label->label_no : -1; - xfree(generated_iseq); - xfree(insns_info); - xfree(positions); + if (add_adjust_info(insns_info, positions, insns_info_index, code_index, adjust)) insns_info_index++; + } + if (diff > 1) { + generated_iseq[code_index++] = BIN(adjuststack); + generated_iseq[code_index++] = orig_sp - sp; + } + else if (diff == 1) { + generated_iseq[code_index++] = BIN(pop); + } + else if (diff < 0) { + int label_no = adjust->label ? adjust->label->label_no : -1; + xfree(generated_iseq); + xfree(insns_info); + xfree(positions); if (ISEQ_MBITS_BUFLEN(code_size) > 1) { xfree(mark_offset_bits); } - debug_list(anchor, list); - COMPILE_ERROR(iseq, adjust->line_no, - "iseq_set_sequence: adjust bug to %d %d < %d", - label_no, orig_sp, sp); - return COMPILE_NG; - } - } - break; - } - default: - /* ignore */ - break; - } - list = list->next; + debug_list(anchor, list); + COMPILE_ERROR(iseq, adjust->line_no, + "iseq_set_sequence: adjust bug to %d %d < %d", + label_no, orig_sp, sp); + return COMPILE_NG; + } + } + break; + } + default: + /* ignore */ + break; + } + list = list->next; } body->iseq_encoded = (void *)generated_iseq; @@ -2601,37 +2601,37 @@ iseq_set_exception_table(rb_iseq_t *iseq) tptr = RARRAY_CONST_PTR_TRANSIENT(ISEQ_COMPILE_DATA(iseq)->catch_table_ary); if (tlen > 0) { - struct iseq_catch_table *table = xmalloc(iseq_catch_table_bytes(tlen)); - table->size = tlen; + struct iseq_catch_table *table = xmalloc(iseq_catch_table_bytes(tlen)); + table->size = tlen; - for (i = 0; i < table->size; i++) { + for (i = 0; i < table->size; i++) { ptr = RARRAY_CONST_PTR_TRANSIENT(tptr[i]); - entry = UNALIGNED_MEMBER_PTR(table, entries[i]); - entry->type = (enum catch_type)(ptr[0] & 0xffff); - entry->start = label_get_position((LABEL *)(ptr[1] & ~1)); - entry->end = label_get_position((LABEL *)(ptr[2] & ~1)); - entry->iseq = (rb_iseq_t *)ptr[3]; - RB_OBJ_WRITTEN(iseq, Qundef, entry->iseq); + entry = UNALIGNED_MEMBER_PTR(table, entries[i]); + entry->type = (enum catch_type)(ptr[0] & 0xffff); + entry->start = label_get_position((LABEL *)(ptr[1] & ~1)); + entry->end = label_get_position((LABEL *)(ptr[2] & ~1)); + entry->iseq = (rb_iseq_t *)ptr[3]; + RB_OBJ_WRITTEN(iseq, Qundef, entry->iseq); - /* stack depth */ - if (ptr[4]) { - LABEL *lobj = (LABEL *)(ptr[4] & ~1); - entry->cont = label_get_position(lobj); - entry->sp = label_get_sp(lobj); + /* stack depth */ + if (ptr[4]) { + LABEL *lobj = (LABEL *)(ptr[4] & ~1); + entry->cont = label_get_position(lobj); + entry->sp = label_get_sp(lobj); - /* TODO: Dirty Hack! Fix me */ - if (entry->type == CATCH_TYPE_RESCUE || - entry->type == CATCH_TYPE_BREAK || - entry->type == CATCH_TYPE_NEXT) { - entry->sp--; - } - } - else { - entry->cont = 0; - } - } + /* TODO: Dirty Hack! Fix me */ + if (entry->type == CATCH_TYPE_RESCUE || + entry->type == CATCH_TYPE_BREAK || + entry->type == CATCH_TYPE_NEXT) { + entry->sp--; + } + } + else { + entry->cont = 0; + } + } ISEQ_BODY(iseq)->catch_table = table; - RB_OBJ_WRITE(iseq, &ISEQ_COMPILE_DATA(iseq)->catch_table_ary, 0); /* free */ + RB_OBJ_WRITE(iseq, &ISEQ_COMPILE_DATA(iseq)->catch_table_ary, 0); /* free */ } return COMPILE_OK; @@ -2654,8 +2654,8 @@ iseq_set_optargs_table(rb_iseq_t *iseq) if (ISEQ_BODY(iseq)->param.flags.has_opt) { for (i = 0; i < ISEQ_BODY(iseq)->param.opt_num + 1; i++) { - opt_table[i] = label_get_position((LABEL *)opt_table[i]); - } + opt_table[i] = label_get_position((LABEL *)opt_table[i]); + } } return COMPILE_OK; } @@ -2669,27 +2669,27 @@ get_destination_insn(INSN *iobj) list = lobj->link.next; while (list) { - switch (list->type) { - case ISEQ_ELEMENT_INSN: - case ISEQ_ELEMENT_ADJUST: - goto found; - case ISEQ_ELEMENT_LABEL: - /* ignore */ - break; - case ISEQ_ELEMENT_TRACE: - { - TRACE *trace = (TRACE *)list; - events |= trace->event; - } - break; - default: break; - } - list = list->next; + switch (list->type) { + case ISEQ_ELEMENT_INSN: + case ISEQ_ELEMENT_ADJUST: + goto found; + case ISEQ_ELEMENT_LABEL: + /* ignore */ + break; + case ISEQ_ELEMENT_TRACE: + { + TRACE *trace = (TRACE *)list; + events |= trace->event; + } + break; + default: break; + } + list = list->next; } found: if (list && IS_INSN(list)) { - INSN *iobj = (INSN *)list; - iobj->insn_info.events |= events; + INSN *iobj = (INSN *)list; + iobj->insn_info.events |= events; } return list; } @@ -2700,10 +2700,10 @@ get_next_insn(INSN *iobj) LINK_ELEMENT *list = iobj->link.next; while (list) { - if (IS_INSN(list) || IS_ADJUST(list)) { - return list; - } - list = list->next; + if (IS_INSN(list) || IS_ADJUST(list)) { + return list; + } + list = list->next; } return 0; } @@ -2714,10 +2714,10 @@ get_prev_insn(INSN *iobj) LINK_ELEMENT *list = iobj->link.prev; while (list) { - if (IS_INSN(list) || IS_ADJUST(list)) { - return list; - } - list = list->prev; + if (IS_INSN(list) || IS_ADJUST(list)) { + return list; + } + list = list->prev; } return 0; } @@ -2747,9 +2747,9 @@ find_destination(INSN *i) { int pos, len = insn_len(i->insn_id); for (pos = 0; pos < len; ++pos) { - if (insn_op_types(i->insn_id)[pos] == TS_OFFSET) { - return (LABEL *)OPERAND_AT(i, pos); - } + if (insn_op_types(i->insn_id)[pos] == TS_OFFSET) { + return (LABEL *)OPERAND_AT(i, pos); + } } return 0; } @@ -2765,53 +2765,53 @@ remove_unreachable_chunk(rb_iseq_t *iseq, LINK_ELEMENT *i) MEMZERO(unref_counts, int, nlabels); end = i; do { - LABEL *lab; - if (IS_INSN(i)) { - if (IS_INSN_ID(i, leave)) { - end = i; - break; - } - else if ((lab = find_destination((INSN *)i)) != 0) { - if (lab->unremovable) break; - unref_counts[lab->label_no]++; - } - } - else if (IS_LABEL(i)) { - lab = (LABEL *)i; - if (lab->unremovable) return 0; - if (lab->refcnt > unref_counts[lab->label_no]) { - if (i == first) return 0; - break; - } - continue; - } - else if (IS_TRACE(i)) { - /* do nothing */ - } - else if (IS_ADJUST(i)) { - LABEL *dest = ((ADJUST *)i)->label; - if (dest && dest->unremovable) return 0; - } - end = i; + LABEL *lab; + if (IS_INSN(i)) { + if (IS_INSN_ID(i, leave)) { + end = i; + break; + } + else if ((lab = find_destination((INSN *)i)) != 0) { + if (lab->unremovable) break; + unref_counts[lab->label_no]++; + } + } + else if (IS_LABEL(i)) { + lab = (LABEL *)i; + if (lab->unremovable) return 0; + if (lab->refcnt > unref_counts[lab->label_no]) { + if (i == first) return 0; + break; + } + continue; + } + else if (IS_TRACE(i)) { + /* do nothing */ + } + else if (IS_ADJUST(i)) { + LABEL *dest = ((ADJUST *)i)->label; + if (dest && dest->unremovable) return 0; + } + end = i; } while ((i = i->next) != 0); i = first; do { - if (IS_INSN(i)) { + if (IS_INSN(i)) { struct rb_iseq_constant_body *body = ISEQ_BODY(iseq); - VALUE insn = INSN_OF(i); - int pos, len = insn_len(insn); - for (pos = 0; pos < len; ++pos) { - switch (insn_op_types(insn)[pos]) { - case TS_OFFSET: - unref_destination((INSN *)i, pos); - break; + VALUE insn = INSN_OF(i); + int pos, len = insn_len(insn); + for (pos = 0; pos < len; ++pos) { + switch (insn_op_types(insn)[pos]) { + case TS_OFFSET: + unref_destination((INSN *)i, pos); + break; case TS_CALLDATA: --(body->ci_size); - break; - } - } - } - ELEM_REMOVE(i); + break; + } + } + } + ELEM_REMOVE(i); } while ((i != end) && (i = i->next) != 0); return 1; } @@ -2821,14 +2821,14 @@ iseq_pop_newarray(rb_iseq_t *iseq, INSN *iobj) { switch (OPERAND_AT(iobj, 0)) { case INT2FIX(0): /* empty array */ - ELEM_REMOVE(&iobj->link); - return TRUE; + ELEM_REMOVE(&iobj->link); + return TRUE; case INT2FIX(1): /* single element array */ - ELEM_REMOVE(&iobj->link); - return FALSE; + ELEM_REMOVE(&iobj->link); + return FALSE; default: - iobj->insn_id = BIN(adjuststack); - return TRUE; + iobj->insn_id = BIN(adjuststack); + return TRUE; } } @@ -2877,41 +2877,41 @@ optimize_checktype(rb_iseq_t *iseq, INSN *iobj) switch (INSN_OF(iobj)) { case BIN(putstring): - type = INT2FIX(T_STRING); - break; + type = INT2FIX(T_STRING); + break; case BIN(putnil): - type = INT2FIX(T_NIL); - break; + type = INT2FIX(T_NIL); + break; case BIN(putobject): - type = INT2FIX(TYPE(OPERAND_AT(iobj, 0))); - break; + type = INT2FIX(TYPE(OPERAND_AT(iobj, 0))); + break; default: return FALSE; } ciobj = (INSN *)get_next_insn(iobj); if (IS_INSN_ID(ciobj, jump)) { - ciobj = (INSN *)get_next_insn((INSN*)OPERAND_AT(ciobj, 0)); + ciobj = (INSN *)get_next_insn((INSN*)OPERAND_AT(ciobj, 0)); } if (IS_INSN_ID(ciobj, dup)) { - ciobj = (INSN *)get_next_insn(dup = ciobj); + ciobj = (INSN *)get_next_insn(dup = ciobj); } if (!ciobj || !IS_INSN_ID(ciobj, checktype)) return FALSE; niobj = (INSN *)get_next_insn(ciobj); if (!niobj) { - /* TODO: putobject true/false */ - return FALSE; + /* TODO: putobject true/false */ + return FALSE; } switch (INSN_OF(niobj)) { case BIN(branchif): - if (OPERAND_AT(ciobj, 0) == type) { - dest = (LABEL *)OPERAND_AT(niobj, 0); - } - break; + if (OPERAND_AT(ciobj, 0) == type) { + dest = (LABEL *)OPERAND_AT(niobj, 0); + } + break; case BIN(branchunless): - if (OPERAND_AT(ciobj, 0) != type) { - dest = (LABEL *)OPERAND_AT(niobj, 0); - } - break; + if (OPERAND_AT(ciobj, 0) != type) { + dest = (LABEL *)OPERAND_AT(niobj, 0); + } + break; default: return FALSE; } @@ -2919,13 +2919,13 @@ optimize_checktype(rb_iseq_t *iseq, INSN *iobj) node_id = ciobj->insn_info.node_id; NODE dummy_line_node = generate_dummy_line_node(line, node_id); if (!dest) { - if (niobj->link.next && IS_LABEL(niobj->link.next)) { - dest = (LABEL *)niobj->link.next; /* reuse label */ - } - else { - dest = NEW_LABEL(line); - ELEM_INSERT_NEXT(&niobj->link, &dest->link); - } + if (niobj->link.next && IS_LABEL(niobj->link.next)) { + dest = (LABEL *)niobj->link.next; /* reuse label */ + } + else { + dest = NEW_LABEL(line); + ELEM_INSERT_NEXT(&niobj->link, &dest->link); + } } INSERT_AFTER_INSN1(iobj, &dummy_line_node, jump, dest); LABEL_REF(dest); @@ -2965,112 +2965,112 @@ iseq_peephole_optimize(rb_iseq_t *iseq, LINK_ELEMENT *list, const int do_tailcal if (IS_INSN_ID(iobj, jump)) { INSN *niobj, *diobj, *piobj; - diobj = (INSN *)get_destination_insn(iobj); - niobj = (INSN *)get_next_insn(iobj); + diobj = (INSN *)get_destination_insn(iobj); + niobj = (INSN *)get_next_insn(iobj); - if (diobj == niobj) { - /* - * jump LABEL - * LABEL: - * => - * LABEL: - */ - unref_destination(iobj, 0); - ELEM_REMOVE(&iobj->link); - return COMPILE_OK; - } + if (diobj == niobj) { + /* + * jump LABEL + * LABEL: + * => + * LABEL: + */ + unref_destination(iobj, 0); + ELEM_REMOVE(&iobj->link); + return COMPILE_OK; + } else if (iobj != diobj && IS_INSN(&diobj->link) && IS_INSN_ID(diobj, jump) && - OPERAND_AT(iobj, 0) != OPERAND_AT(diobj, 0) && + OPERAND_AT(iobj, 0) != OPERAND_AT(diobj, 0) && diobj->insn_info.events == 0) { - /* - * useless jump elimination: - * jump LABEL1 - * ... - * LABEL1: - * jump LABEL2 - * - * => in this case, first jump instruction should jump to - * LABEL2 directly - */ - replace_destination(iobj, diobj); - remove_unreachable_chunk(iseq, iobj->link.next); - goto again; - } + /* + * useless jump elimination: + * jump LABEL1 + * ... + * LABEL1: + * jump LABEL2 + * + * => in this case, first jump instruction should jump to + * LABEL2 directly + */ + replace_destination(iobj, diobj); + remove_unreachable_chunk(iseq, iobj->link.next); + goto again; + } else if (IS_INSN_ID(diobj, leave)) { - /* - * jump LABEL - * ... - * LABEL: - * leave - * => - * leave - * ... - * LABEL: - * leave - */ - /* replace */ - unref_destination(iobj, 0); + /* + * jump LABEL + * ... + * LABEL: + * leave + * => + * leave + * ... + * LABEL: + * leave + */ + /* replace */ + unref_destination(iobj, 0); iobj->insn_id = BIN(leave); - iobj->operand_size = 0; - iobj->insn_info = diobj->insn_info; - goto again; - } + iobj->operand_size = 0; + iobj->insn_info = diobj->insn_info; + goto again; + } else if (IS_INSN(iobj->link.prev) && (piobj = (INSN *)iobj->link.prev) && - (IS_INSN_ID(piobj, branchif) || - IS_INSN_ID(piobj, branchunless))) { - INSN *pdiobj = (INSN *)get_destination_insn(piobj); - if (niobj == pdiobj) { - int refcnt = IS_LABEL(piobj->link.next) ? - ((LABEL *)piobj->link.next)->refcnt : 0; - /* - * useless jump elimination (if/unless destination): - * if L1 - * jump L2 - * L1: - * ... - * L2: - * - * ==> - * unless L2 - * L1: - * ... - * L2: - */ - piobj->insn_id = (IS_INSN_ID(piobj, branchif)) - ? BIN(branchunless) : BIN(branchif); - replace_destination(piobj, iobj); - if (refcnt <= 1) { - ELEM_REMOVE(&iobj->link); - } - else { - /* TODO: replace other branch destinations too */ - } - return COMPILE_OK; - } - else if (diobj == pdiobj) { - /* - * useless jump elimination (if/unless before jump): - * L1: - * ... - * if L1 - * jump L1 - * - * ==> - * L1: - * ... - * pop - * jump L1 - */ + (IS_INSN_ID(piobj, branchif) || + IS_INSN_ID(piobj, branchunless))) { + INSN *pdiobj = (INSN *)get_destination_insn(piobj); + if (niobj == pdiobj) { + int refcnt = IS_LABEL(piobj->link.next) ? + ((LABEL *)piobj->link.next)->refcnt : 0; + /* + * useless jump elimination (if/unless destination): + * if L1 + * jump L2 + * L1: + * ... + * L2: + * + * ==> + * unless L2 + * L1: + * ... + * L2: + */ + piobj->insn_id = (IS_INSN_ID(piobj, branchif)) + ? BIN(branchunless) : BIN(branchif); + replace_destination(piobj, iobj); + if (refcnt <= 1) { + ELEM_REMOVE(&iobj->link); + } + else { + /* TODO: replace other branch destinations too */ + } + return COMPILE_OK; + } + else if (diobj == pdiobj) { + /* + * useless jump elimination (if/unless before jump): + * L1: + * ... + * if L1 + * jump L1 + * + * ==> + * L1: + * ... + * pop + * jump L1 + */ NODE dummy_line_node = generate_dummy_line_node(iobj->insn_info.line_no, iobj->insn_info.node_id); - INSN *popiobj = new_insn_core(iseq, &dummy_line_node, BIN(pop), 0, 0); - ELEM_REPLACE(&piobj->link, &popiobj->link); - } - } - if (remove_unreachable_chunk(iseq, iobj->link.next)) { - goto again; - } + INSN *popiobj = new_insn_core(iseq, &dummy_line_node, BIN(pop), 0, 0); + ELEM_REPLACE(&piobj->link, &popiobj->link); + } + } + if (remove_unreachable_chunk(iseq, iobj->link.next)) { + goto again; + } } /* @@ -3091,19 +3091,19 @@ iseq_peephole_optimize(rb_iseq_t *iseq, LINK_ELEMENT *list, const int do_tailcal is_frozen_putstring(end, &str_end) && (beg = (INSN *)get_prev_insn(end)) != 0 && is_frozen_putstring(beg, &str_beg)) { - int excl = FIX2INT(OPERAND_AT(range, 0)); - VALUE lit_range = rb_range_new(str_beg, str_end, excl); + int excl = FIX2INT(OPERAND_AT(range, 0)); + VALUE lit_range = rb_range_new(str_beg, str_end, excl); - ELEM_REMOVE(&beg->link); - ELEM_REMOVE(&end->link); - range->insn_id = BIN(putobject); - OPERAND_AT(range, 0) = lit_range; - RB_OBJ_WRITTEN(iseq, Qundef, lit_range); - } + ELEM_REMOVE(&beg->link); + ELEM_REMOVE(&end->link); + range->insn_id = BIN(putobject); + OPERAND_AT(range, 0) = lit_range; + RB_OBJ_WRITTEN(iseq, Qundef, lit_range); + } } if (IS_INSN_ID(iobj, leave)) { - remove_unreachable_chunk(iseq, iobj->link.next); + remove_unreachable_chunk(iseq, iobj->link.next); } /* @@ -3123,17 +3123,17 @@ iseq_peephole_optimize(rb_iseq_t *iseq, LINK_ELEMENT *list, const int do_tailcal } if (IS_INSN_ID(iobj, branchif) || - IS_INSN_ID(iobj, branchnil) || - IS_INSN_ID(iobj, branchunless)) { - /* - * if L1 - * ... - * L1: - * jump L2 - * => - * if L2 - */ - INSN *nobj = (INSN *)get_destination_insn(iobj); + IS_INSN_ID(iobj, branchnil) || + IS_INSN_ID(iobj, branchunless)) { + /* + * if L1 + * ... + * L1: + * jump L2 + * => + * if L2 + */ + INSN *nobj = (INSN *)get_destination_insn(iobj); /* This is super nasty hack!!! * @@ -3156,10 +3156,10 @@ iseq_peephole_optimize(rb_iseq_t *iseq, LINK_ELEMENT *list, const int do_tailcal * This should be fixed in future. */ int stop_optimization = - ISEQ_COVERAGE(iseq) && ISEQ_LINE_COVERAGE(iseq) && + ISEQ_COVERAGE(iseq) && ISEQ_LINE_COVERAGE(iseq) && nobj->link.type == ISEQ_ELEMENT_INSN && nobj->insn_info.events; - if (!stop_optimization) { + if (!stop_optimization) { INSN *pobj = (INSN *)iobj->link.prev; int prev_dup = 0; if (pobj) { @@ -3269,229 +3269,229 @@ iseq_peephole_optimize(rb_iseq_t *iseq, LINK_ELEMENT *list, const int do_tailcal } if (IS_INSN_ID(iobj, pop)) { - /* - * putself / putnil / putobject obj / putstring "..." - * pop - * => - * # do nothing - */ - LINK_ELEMENT *prev = iobj->link.prev; - if (IS_INSN(prev)) { - enum ruby_vminsn_type previ = ((INSN *)prev)->insn_id; - if (previ == BIN(putobject) || previ == BIN(putnil) || - previ == BIN(putself) || previ == BIN(putstring) || - previ == BIN(dup) || - previ == BIN(getlocal) || - previ == BIN(getblockparam) || - previ == BIN(getblockparamproxy) || - /* getinstancevariable may issue a warning */ - previ == BIN(duparray)) { - /* just push operand or static value and pop soon, no - * side effects */ - ELEM_REMOVE(prev); - ELEM_REMOVE(&iobj->link); - } - else if (previ == BIN(newarray) && iseq_pop_newarray(iseq, (INSN*)prev)) { - ELEM_REMOVE(&iobj->link); - } - else if (previ == BIN(concatarray)) { - INSN *piobj = (INSN *)prev; + /* + * putself / putnil / putobject obj / putstring "..." + * pop + * => + * # do nothing + */ + LINK_ELEMENT *prev = iobj->link.prev; + if (IS_INSN(prev)) { + enum ruby_vminsn_type previ = ((INSN *)prev)->insn_id; + if (previ == BIN(putobject) || previ == BIN(putnil) || + previ == BIN(putself) || previ == BIN(putstring) || + previ == BIN(dup) || + previ == BIN(getlocal) || + previ == BIN(getblockparam) || + previ == BIN(getblockparamproxy) || + /* getinstancevariable may issue a warning */ + previ == BIN(duparray)) { + /* just push operand or static value and pop soon, no + * side effects */ + ELEM_REMOVE(prev); + ELEM_REMOVE(&iobj->link); + } + else if (previ == BIN(newarray) && iseq_pop_newarray(iseq, (INSN*)prev)) { + ELEM_REMOVE(&iobj->link); + } + else if (previ == BIN(concatarray)) { + INSN *piobj = (INSN *)prev; NODE dummy_line_node = generate_dummy_line_node(piobj->insn_info.line_no, piobj->insn_info.node_id); - INSERT_BEFORE_INSN1(piobj, &dummy_line_node, splatarray, Qfalse); - INSN_OF(piobj) = BIN(pop); - } - else if (previ == BIN(concatstrings)) { - if (OPERAND_AT(prev, 0) == INT2FIX(1)) { - ELEM_REMOVE(prev); - } - else { - ELEM_REMOVE(&iobj->link); - INSN_OF(prev) = BIN(adjuststack); - } - } - } + INSERT_BEFORE_INSN1(piobj, &dummy_line_node, splatarray, Qfalse); + INSN_OF(piobj) = BIN(pop); + } + else if (previ == BIN(concatstrings)) { + if (OPERAND_AT(prev, 0) == INT2FIX(1)) { + ELEM_REMOVE(prev); + } + else { + ELEM_REMOVE(&iobj->link); + INSN_OF(prev) = BIN(adjuststack); + } + } + } } if (IS_INSN_ID(iobj, newarray) || - IS_INSN_ID(iobj, duparray) || - IS_INSN_ID(iobj, expandarray) || - IS_INSN_ID(iobj, concatarray) || - IS_INSN_ID(iobj, splatarray) || - 0) { - /* - * newarray N - * splatarray - * => - * newarray N - * newarray always puts an array - */ - LINK_ELEMENT *next = iobj->link.next; - if (IS_INSN(next) && IS_INSN_ID(next, splatarray)) { - /* remove splatarray following always-array insn */ - ELEM_REMOVE(next); - } + IS_INSN_ID(iobj, duparray) || + IS_INSN_ID(iobj, expandarray) || + IS_INSN_ID(iobj, concatarray) || + IS_INSN_ID(iobj, splatarray) || + 0) { + /* + * newarray N + * splatarray + * => + * newarray N + * newarray always puts an array + */ + LINK_ELEMENT *next = iobj->link.next; + if (IS_INSN(next) && IS_INSN_ID(next, splatarray)) { + /* remove splatarray following always-array insn */ + ELEM_REMOVE(next); + } } if (IS_INSN_ID(iobj, anytostring)) { - LINK_ELEMENT *next = iobj->link.next; - /* + LINK_ELEMENT *next = iobj->link.next; + /* * anytostring - * concatstrings 1 - * => + * concatstrings 1 + * => * anytostring - */ - if (IS_INSN(next) && IS_INSN_ID(next, concatstrings) && - OPERAND_AT(next, 0) == INT2FIX(1)) { - ELEM_REMOVE(next); - } + */ + if (IS_INSN(next) && IS_INSN_ID(next, concatstrings) && + OPERAND_AT(next, 0) == INT2FIX(1)) { + ELEM_REMOVE(next); + } } if (IS_INSN_ID(iobj, putstring) || - (IS_INSN_ID(iobj, putobject) && RB_TYPE_P(OPERAND_AT(iobj, 0), T_STRING))) { - /* - * putstring "" - * concatstrings N - * => - * concatstrings N-1 - */ - if (IS_NEXT_INSN_ID(&iobj->link, concatstrings) && - RSTRING_LEN(OPERAND_AT(iobj, 0)) == 0) { - INSN *next = (INSN *)iobj->link.next; - if ((OPERAND_AT(next, 0) = FIXNUM_INC(OPERAND_AT(next, 0), -1)) == INT2FIX(1)) { - ELEM_REMOVE(&next->link); - } - ELEM_REMOVE(&iobj->link); - } + (IS_INSN_ID(iobj, putobject) && RB_TYPE_P(OPERAND_AT(iobj, 0), T_STRING))) { + /* + * putstring "" + * concatstrings N + * => + * concatstrings N-1 + */ + if (IS_NEXT_INSN_ID(&iobj->link, concatstrings) && + RSTRING_LEN(OPERAND_AT(iobj, 0)) == 0) { + INSN *next = (INSN *)iobj->link.next; + if ((OPERAND_AT(next, 0) = FIXNUM_INC(OPERAND_AT(next, 0), -1)) == INT2FIX(1)) { + ELEM_REMOVE(&next->link); + } + ELEM_REMOVE(&iobj->link); + } } if (IS_INSN_ID(iobj, concatstrings)) { - /* - * concatstrings N - * concatstrings M - * => - * concatstrings N+M-1 - */ - LINK_ELEMENT *next = iobj->link.next; - INSN *jump = 0; - if (IS_INSN(next) && IS_INSN_ID(next, jump)) - next = get_destination_insn(jump = (INSN *)next); - if (IS_INSN(next) && IS_INSN_ID(next, concatstrings)) { - int n = FIX2INT(OPERAND_AT(iobj, 0)) + FIX2INT(OPERAND_AT(next, 0)) - 1; - OPERAND_AT(iobj, 0) = INT2FIX(n); - if (jump) { - LABEL *label = ((LABEL *)OPERAND_AT(jump, 0)); - if (!--label->refcnt) { - ELEM_REMOVE(&label->link); - } - else { - label = NEW_LABEL(0); - OPERAND_AT(jump, 0) = (VALUE)label; - } - label->refcnt++; - ELEM_INSERT_NEXT(next, &label->link); - CHECK(iseq_peephole_optimize(iseq, get_next_insn(jump), do_tailcallopt)); - } - else { - ELEM_REMOVE(next); - } - } + /* + * concatstrings N + * concatstrings M + * => + * concatstrings N+M-1 + */ + LINK_ELEMENT *next = iobj->link.next; + INSN *jump = 0; + if (IS_INSN(next) && IS_INSN_ID(next, jump)) + next = get_destination_insn(jump = (INSN *)next); + if (IS_INSN(next) && IS_INSN_ID(next, concatstrings)) { + int n = FIX2INT(OPERAND_AT(iobj, 0)) + FIX2INT(OPERAND_AT(next, 0)) - 1; + OPERAND_AT(iobj, 0) = INT2FIX(n); + if (jump) { + LABEL *label = ((LABEL *)OPERAND_AT(jump, 0)); + if (!--label->refcnt) { + ELEM_REMOVE(&label->link); + } + else { + label = NEW_LABEL(0); + OPERAND_AT(jump, 0) = (VALUE)label; + } + label->refcnt++; + ELEM_INSERT_NEXT(next, &label->link); + CHECK(iseq_peephole_optimize(iseq, get_next_insn(jump), do_tailcallopt)); + } + else { + ELEM_REMOVE(next); + } + } } if (do_tailcallopt && - (IS_INSN_ID(iobj, send) || - IS_INSN_ID(iobj, opt_aref_with) || - IS_INSN_ID(iobj, opt_aset_with) || - IS_INSN_ID(iobj, invokesuper))) { - /* - * send ... - * leave - * => - * send ..., ... | VM_CALL_TAILCALL, ... - * leave # unreachable - */ - INSN *piobj = NULL; - if (iobj->link.next) { - LINK_ELEMENT *next = iobj->link.next; - do { - if (!IS_INSN(next)) { - next = next->next; - continue; - } - switch (INSN_OF(next)) { - case BIN(nop): - next = next->next; - break; - case BIN(jump): - /* if cond - * return tailcall - * end - */ - next = get_destination_insn((INSN *)next); - break; - case BIN(leave): - piobj = iobj; + (IS_INSN_ID(iobj, send) || + IS_INSN_ID(iobj, opt_aref_with) || + IS_INSN_ID(iobj, opt_aset_with) || + IS_INSN_ID(iobj, invokesuper))) { + /* + * send ... + * leave + * => + * send ..., ... | VM_CALL_TAILCALL, ... + * leave # unreachable + */ + INSN *piobj = NULL; + if (iobj->link.next) { + LINK_ELEMENT *next = iobj->link.next; + do { + if (!IS_INSN(next)) { + next = next->next; + continue; + } + switch (INSN_OF(next)) { + case BIN(nop): + next = next->next; + break; + case BIN(jump): + /* if cond + * return tailcall + * end + */ + next = get_destination_insn((INSN *)next); + break; + case BIN(leave): + piobj = iobj; /* fall through */ - default: - next = NULL; - break; - } - } while (next); - } + default: + next = NULL; + break; + } + } while (next); + } - if (piobj) { + if (piobj) { const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT(piobj, 0); - if (IS_INSN_ID(piobj, send) || + if (IS_INSN_ID(piobj, send) || IS_INSN_ID(piobj, invokesuper)) { if (OPERAND_AT(piobj, 1) == 0) { /* no blockiseq */ ci = ci_flag_set(iseq, ci, VM_CALL_TAILCALL); OPERAND_AT(piobj, 0) = (VALUE)ci; RB_OBJ_WRITTEN(iseq, Qundef, ci); - } - } - else { + } + } + else { ci = ci_flag_set(iseq, ci, VM_CALL_TAILCALL); OPERAND_AT(piobj, 0) = (VALUE)ci; RB_OBJ_WRITTEN(iseq, Qundef, ci); - } - } + } + } } if (IS_INSN_ID(iobj, dup)) { - if (IS_NEXT_INSN_ID(&iobj->link, setlocal)) { - LINK_ELEMENT *set1 = iobj->link.next, *set2 = NULL; - if (IS_NEXT_INSN_ID(set1, setlocal)) { - set2 = set1->next; - if (OPERAND_AT(set1, 0) == OPERAND_AT(set2, 0) && - OPERAND_AT(set1, 1) == OPERAND_AT(set2, 1)) { - ELEM_REMOVE(set1); - ELEM_REMOVE(&iobj->link); - } - } - else if (IS_NEXT_INSN_ID(set1, dup) && - IS_NEXT_INSN_ID(set1->next, setlocal)) { - set2 = set1->next->next; - if (OPERAND_AT(set1, 0) == OPERAND_AT(set2, 0) && - OPERAND_AT(set1, 1) == OPERAND_AT(set2, 1)) { - ELEM_REMOVE(set1->next); - ELEM_REMOVE(set2); - } - } - } + if (IS_NEXT_INSN_ID(&iobj->link, setlocal)) { + LINK_ELEMENT *set1 = iobj->link.next, *set2 = NULL; + if (IS_NEXT_INSN_ID(set1, setlocal)) { + set2 = set1->next; + if (OPERAND_AT(set1, 0) == OPERAND_AT(set2, 0) && + OPERAND_AT(set1, 1) == OPERAND_AT(set2, 1)) { + ELEM_REMOVE(set1); + ELEM_REMOVE(&iobj->link); + } + } + else if (IS_NEXT_INSN_ID(set1, dup) && + IS_NEXT_INSN_ID(set1->next, setlocal)) { + set2 = set1->next->next; + if (OPERAND_AT(set1, 0) == OPERAND_AT(set2, 0) && + OPERAND_AT(set1, 1) == OPERAND_AT(set2, 1)) { + ELEM_REMOVE(set1->next); + ELEM_REMOVE(set2); + } + } + } } if (IS_INSN_ID(iobj, getlocal)) { - LINK_ELEMENT *niobj = &iobj->link; - if (IS_NEXT_INSN_ID(niobj, dup)) { - niobj = niobj->next; - } - if (IS_NEXT_INSN_ID(niobj, setlocal)) { - LINK_ELEMENT *set1 = niobj->next; - if (OPERAND_AT(iobj, 0) == OPERAND_AT(set1, 0) && - OPERAND_AT(iobj, 1) == OPERAND_AT(set1, 1)) { - ELEM_REMOVE(set1); - ELEM_REMOVE(niobj); - } - } + LINK_ELEMENT *niobj = &iobj->link; + if (IS_NEXT_INSN_ID(niobj, dup)) { + niobj = niobj->next; + } + if (IS_NEXT_INSN_ID(niobj, setlocal)) { + LINK_ELEMENT *set1 = niobj->next; + if (OPERAND_AT(iobj, 0) == OPERAND_AT(set1, 0) && + OPERAND_AT(iobj, 1) == OPERAND_AT(set1, 1)) { + ELEM_REMOVE(set1); + ELEM_REMOVE(niobj); + } + } } if (IS_INSN_ID(iobj, opt_invokebuiltin_delegate)) { @@ -3527,26 +3527,26 @@ static int iseq_specialized_instruction(rb_iseq_t *iseq, INSN *iobj) { if (IS_INSN_ID(iobj, newarray) && iobj->link.next && - IS_INSN(iobj->link.next)) { - /* - * [a, b, ...].max/min -> a, b, c, opt_newarray_max/min - */ - INSN *niobj = (INSN *)iobj->link.next; - if (IS_INSN_ID(niobj, send)) { + IS_INSN(iobj->link.next)) { + /* + * [a, b, ...].max/min -> a, b, c, opt_newarray_max/min + */ + INSN *niobj = (INSN *)iobj->link.next; + if (IS_INSN_ID(niobj, send)) { const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT(niobj, 0); if ((vm_ci_flag(ci) & VM_CALL_ARGS_SIMPLE) && vm_ci_argc(ci) == 0) { - switch (vm_ci_mid(ci)) { - case idMax: - iobj->insn_id = BIN(opt_newarray_max); - ELEM_REMOVE(&niobj->link); - return COMPILE_OK; - case idMin: - iobj->insn_id = BIN(opt_newarray_min); - ELEM_REMOVE(&niobj->link); - return COMPILE_OK; - } - } - } + switch (vm_ci_mid(ci)) { + case idMax: + iobj->insn_id = BIN(opt_newarray_max); + ELEM_REMOVE(&niobj->link); + return COMPILE_OK; + case idMin: + iobj->insn_id = BIN(opt_newarray_min); + ELEM_REMOVE(&niobj->link); + return COMPILE_OK; + } + } + } } if (IS_INSN_ID(iobj, send)) { @@ -3554,50 +3554,50 @@ iseq_specialized_instruction(rb_iseq_t *iseq, INSN *iobj) const rb_iseq_t *blockiseq = (rb_iseq_t *)OPERAND_AT(iobj, 1); #define SP_INSN(opt) insn_set_specialized_instruction(iseq, iobj, BIN(opt_##opt)) - if (vm_ci_flag(ci) & VM_CALL_ARGS_SIMPLE) { - switch (vm_ci_argc(ci)) { - case 0: - switch (vm_ci_mid(ci)) { - case idLength: SP_INSN(length); return COMPILE_OK; - case idSize: SP_INSN(size); return COMPILE_OK; - case idEmptyP: SP_INSN(empty_p);return COMPILE_OK; + if (vm_ci_flag(ci) & VM_CALL_ARGS_SIMPLE) { + switch (vm_ci_argc(ci)) { + case 0: + switch (vm_ci_mid(ci)) { + case idLength: SP_INSN(length); return COMPILE_OK; + case idSize: SP_INSN(size); return COMPILE_OK; + case idEmptyP: SP_INSN(empty_p);return COMPILE_OK; case idNilP: SP_INSN(nil_p); return COMPILE_OK; - case idSucc: SP_INSN(succ); return COMPILE_OK; - case idNot: SP_INSN(not); return COMPILE_OK; - } - break; - case 1: - switch (vm_ci_mid(ci)) { - case idPLUS: SP_INSN(plus); return COMPILE_OK; - case idMINUS: SP_INSN(minus); return COMPILE_OK; - case idMULT: SP_INSN(mult); return COMPILE_OK; - case idDIV: SP_INSN(div); return COMPILE_OK; - case idMOD: SP_INSN(mod); return COMPILE_OK; - case idEq: SP_INSN(eq); return COMPILE_OK; - case idNeq: SP_INSN(neq); return COMPILE_OK; - case idEqTilde:SP_INSN(regexpmatch2);return COMPILE_OK; - case idLT: SP_INSN(lt); return COMPILE_OK; - case idLE: SP_INSN(le); return COMPILE_OK; - case idGT: SP_INSN(gt); return COMPILE_OK; - case idGE: SP_INSN(ge); return COMPILE_OK; - case idLTLT: SP_INSN(ltlt); return COMPILE_OK; - case idAREF: SP_INSN(aref); return COMPILE_OK; + case idSucc: SP_INSN(succ); return COMPILE_OK; + case idNot: SP_INSN(not); return COMPILE_OK; + } + break; + case 1: + switch (vm_ci_mid(ci)) { + case idPLUS: SP_INSN(plus); return COMPILE_OK; + case idMINUS: SP_INSN(minus); return COMPILE_OK; + case idMULT: SP_INSN(mult); return COMPILE_OK; + case idDIV: SP_INSN(div); return COMPILE_OK; + case idMOD: SP_INSN(mod); return COMPILE_OK; + case idEq: SP_INSN(eq); return COMPILE_OK; + case idNeq: SP_INSN(neq); return COMPILE_OK; + case idEqTilde:SP_INSN(regexpmatch2);return COMPILE_OK; + case idLT: SP_INSN(lt); return COMPILE_OK; + case idLE: SP_INSN(le); return COMPILE_OK; + case idGT: SP_INSN(gt); return COMPILE_OK; + case idGE: SP_INSN(ge); return COMPILE_OK; + case idLTLT: SP_INSN(ltlt); return COMPILE_OK; + case idAREF: SP_INSN(aref); return COMPILE_OK; case idAnd: SP_INSN(and); return COMPILE_OK; case idOr: SP_INSN(or); return COMPILE_OK; - } - break; - case 2: - switch (vm_ci_mid(ci)) { - case idASET: SP_INSN(aset); return COMPILE_OK; - } - break; - } - } + } + break; + case 2: + switch (vm_ci_mid(ci)) { + case idASET: SP_INSN(aset); return COMPILE_OK; + } + break; + } + } - if ((vm_ci_flag(ci) & VM_CALL_ARGS_BLOCKARG) == 0 && blockiseq == NULL) { - iobj->insn_id = BIN(opt_send_without_block); - iobj->operand_size = insn_len(iobj->insn_id) - 1; - } + if ((vm_ci_flag(ci) & VM_CALL_ARGS_BLOCKARG) == 0 && blockiseq == NULL) { + iobj->insn_id = BIN(opt_send_without_block); + iobj->operand_size = insn_len(iobj->insn_id) - 1; + } } #undef SP_INSN @@ -3611,13 +3611,13 @@ tailcallable_p(rb_iseq_t *iseq) case ISEQ_TYPE_TOP: case ISEQ_TYPE_EVAL: case ISEQ_TYPE_MAIN: - /* not tail callable because cfp will be over popped */ + /* not tail callable because cfp will be over popped */ case ISEQ_TYPE_RESCUE: case ISEQ_TYPE_ENSURE: - /* rescue block can't tail call because of errinfo */ - return FALSE; + /* rescue block can't tail call because of errinfo */ + return FALSE; default: - return TRUE; + return TRUE; } } @@ -3627,7 +3627,7 @@ iseq_optimize(rb_iseq_t *iseq, LINK_ANCHOR *const anchor) LINK_ELEMENT *list; const int do_peepholeopt = ISEQ_COMPILE_DATA(iseq)->option->peephole_optimization; const int do_tailcallopt = tailcallable_p(iseq) && - ISEQ_COMPILE_DATA(iseq)->option->tailcall_optimization; + ISEQ_COMPILE_DATA(iseq)->option->tailcall_optimization; const int do_si = ISEQ_COMPILE_DATA(iseq)->option->specialized_instruction; const int do_ou = ISEQ_COMPILE_DATA(iseq)->option->operands_unification; int rescue_level = 0; @@ -3642,16 +3642,16 @@ iseq_optimize(rb_iseq_t *iseq, LINK_ANCHOR *const anchor) } while (list) { - if (IS_INSN(list)) { - if (do_peepholeopt) { - iseq_peephole_optimize(iseq, list, tailcallopt); - } - if (do_si) { - iseq_specialized_instruction(iseq, (INSN *)list); - } - if (do_ou) { - insn_operands_unification((INSN *)list); - } + if (IS_INSN(list)) { + if (do_peepholeopt) { + iseq_peephole_optimize(iseq, list, tailcallopt); + } + if (do_si) { + iseq_specialized_instruction(iseq, (INSN *)list); + } + if (do_ou) { + insn_operands_unification((INSN *)list); + } if (do_block_optimization) { INSN * item = (INSN *)list; @@ -3659,19 +3659,19 @@ iseq_optimize(rb_iseq_t *iseq, LINK_ANCHOR *const anchor) do_block_optimization = 0; } } - } - if (IS_LABEL(list)) { - switch (((LABEL *)list)->rescued) { - case LABEL_RESCUE_BEG: - rescue_level++; - tailcallopt = FALSE; - break; - case LABEL_RESCUE_END: - if (!--rescue_level) tailcallopt = do_tailcallopt; - break; - } - } - list = list->next; + } + if (IS_LABEL(list)) { + switch (((LABEL *)list)->rescued) { + case LABEL_RESCUE_BEG: + rescue_level++; + tailcallopt = FALSE; + break; + case LABEL_RESCUE_END: + if (!--rescue_level) tailcallopt = do_tailcallopt; + break; + } + } + list = list->next; } if (do_block_optimization) { @@ -3686,7 +3686,7 @@ iseq_optimize(rb_iseq_t *iseq, LINK_ANCHOR *const anchor) #if OPT_INSTRUCTIONS_UNIFICATION static INSN * new_unified_insn(rb_iseq_t *iseq, - int insn_id, int size, LINK_ELEMENT *seq_list) + int insn_id, int size, LINK_ELEMENT *seq_list) { INSN *iobj = 0; LINK_ELEMENT *list = seq_list; @@ -3696,22 +3696,22 @@ new_unified_insn(rb_iseq_t *iseq, /* count argc */ for (i = 0; i < size; i++) { - iobj = (INSN *)list; - argc += iobj->operand_size; - list = list->next; + iobj = (INSN *)list; + argc += iobj->operand_size; + list = list->next; } if (argc > 0) { - ptr = operands = compile_data_alloc2(iseq, sizeof(VALUE), argc); + ptr = operands = compile_data_alloc2(iseq, sizeof(VALUE), argc); } /* copy operands */ list = seq_list; for (i = 0; i < size; i++) { - iobj = (INSN *)list; - MEMCPY(ptr, iobj->operands, VALUE, iobj->operand_size); - ptr += iobj->operand_size; - list = list->next; + iobj = (INSN *)list; + MEMCPY(ptr, iobj->operands, VALUE, iobj->operand_size); + ptr += iobj->operand_size; + list = list->next; } NODE dummy_line_node = generate_dummy_line_node(iobj->insn_info.line_no, iobj->insn_info.node_id); @@ -3735,41 +3735,41 @@ iseq_insns_unification(rb_iseq_t *iseq, LINK_ANCHOR *const anchor) list = FIRST_ELEMENT(anchor); while (list) { - if (IS_INSN(list)) { - iobj = (INSN *)list; - id = iobj->insn_id; - if (unified_insns_data[id] != 0) { - const int *const *entry = unified_insns_data[id]; - for (j = 1; j < (intptr_t)entry[0]; j++) { - const int *unified = entry[j]; - LINK_ELEMENT *li = list->next; - for (k = 2; k < unified[1]; k++) { - if (!IS_INSN(li) || - ((INSN *)li)->insn_id != unified[k]) { - goto miss; - } - li = li->next; - } - /* matched */ - niobj = - new_unified_insn(iseq, unified[0], unified[1] - 1, - list); + if (IS_INSN(list)) { + iobj = (INSN *)list; + id = iobj->insn_id; + if (unified_insns_data[id] != 0) { + const int *const *entry = unified_insns_data[id]; + for (j = 1; j < (intptr_t)entry[0]; j++) { + const int *unified = entry[j]; + LINK_ELEMENT *li = list->next; + for (k = 2; k < unified[1]; k++) { + if (!IS_INSN(li) || + ((INSN *)li)->insn_id != unified[k]) { + goto miss; + } + li = li->next; + } + /* matched */ + niobj = + new_unified_insn(iseq, unified[0], unified[1] - 1, + list); - /* insert to list */ - niobj->link.prev = (LINK_ELEMENT *)iobj->link.prev; - niobj->link.next = li; - if (li) { - li->prev = (LINK_ELEMENT *)niobj; - } + /* insert to list */ + niobj->link.prev = (LINK_ELEMENT *)iobj->link.prev; + niobj->link.next = li; + if (li) { + li->prev = (LINK_ELEMENT *)niobj; + } - list->prev->next = (LINK_ELEMENT *)niobj; - list = (LINK_ELEMENT *)niobj; - break; - miss:; - } - } - } - list = list->next; + list->prev->next = (LINK_ELEMENT *)niobj; + list = (LINK_ELEMENT *)niobj; + break; + miss:; + } + } + } + list = list->next; } #endif return COMPILE_OK; @@ -3793,28 +3793,28 @@ insn_set_sc_state(rb_iseq_t *iseq, const LINK_ELEMENT *anchor, INSN *iobj, int s nstate = SC_NEXT(iobj->insn_id); if (insn_id == BIN(jump) || - insn_id == BIN(branchif) || insn_id == BIN(branchunless)) { - LABEL *lobj = (LABEL *)OPERAND_AT(iobj, 0); + insn_id == BIN(branchif) || insn_id == BIN(branchunless)) { + LABEL *lobj = (LABEL *)OPERAND_AT(iobj, 0); - if (lobj->sc_state != 0) { - if (lobj->sc_state != nstate) { - BADINSN_DUMP(anchor, iobj, lobj); - COMPILE_ERROR(iseq, iobj->insn_info.line_no, - "insn_set_sc_state error: %d at "LABEL_FORMAT - ", %d expected\n", - lobj->sc_state, lobj->label_no, nstate); - return COMPILE_NG; - } - } - else { - lobj->sc_state = nstate; - } - if (insn_id == BIN(jump)) { - nstate = SCS_XX; - } + if (lobj->sc_state != 0) { + if (lobj->sc_state != nstate) { + BADINSN_DUMP(anchor, iobj, lobj); + COMPILE_ERROR(iseq, iobj->insn_info.line_no, + "insn_set_sc_state error: %d at "LABEL_FORMAT + ", %d expected\n", + lobj->sc_state, lobj->label_no, nstate); + return COMPILE_NG; + } + } + else { + lobj->sc_state = nstate; + } + if (insn_id == BIN(jump)) { + nstate = SCS_XX; + } } else if (insn_id == BIN(leave)) { - nstate = SCS_XX; + nstate = SCS_XX; } return nstate; @@ -3824,12 +3824,12 @@ static int label_set_sc_state(LABEL *lobj, int state) { if (lobj->sc_state != 0) { - if (lobj->sc_state != state) { - state = lobj->sc_state; - } + if (lobj->sc_state != state) { + state = lobj->sc_state; + } } else { - lobj->sc_state = state; + lobj->sc_state = state; } return state; @@ -3853,84 +3853,84 @@ iseq_set_sequence_stackcaching(rb_iseq_t *iseq, LINK_ANCHOR *const anchor) /* for each list element */ while (list) { redo_point: - switch (list->type) { - case ISEQ_ELEMENT_INSN: - { - INSN *iobj = (INSN *)list; - insn_id = iobj->insn_id; + switch (list->type) { + case ISEQ_ELEMENT_INSN: + { + INSN *iobj = (INSN *)list; + insn_id = iobj->insn_id; - /* dump_disasm_list(list); */ + /* dump_disasm_list(list); */ - switch (insn_id) { - case BIN(nop): - { - /* exception merge point */ - if (state != SCS_AX) { + switch (insn_id) { + case BIN(nop): + { + /* exception merge point */ + if (state != SCS_AX) { NODE dummy_line_node = generate_dummy_line_node(0, -1); - INSN *rpobj = - new_insn_body(iseq, &dummy_line_node, BIN(reput), 0); + INSN *rpobj = + new_insn_body(iseq, &dummy_line_node, BIN(reput), 0); - /* replace this insn */ - ELEM_REPLACE(list, (LINK_ELEMENT *)rpobj); - list = (LINK_ELEMENT *)rpobj; - goto redo_point; - } - break; - } - case BIN(swap): - { - if (state == SCS_AB || state == SCS_BA) { - state = (state == SCS_AB ? SCS_BA : SCS_AB); + /* replace this insn */ + ELEM_REPLACE(list, (LINK_ELEMENT *)rpobj); + list = (LINK_ELEMENT *)rpobj; + goto redo_point; + } + break; + } + case BIN(swap): + { + if (state == SCS_AB || state == SCS_BA) { + state = (state == SCS_AB ? SCS_BA : SCS_AB); - ELEM_REMOVE(list); - list = list->next; - goto redo_point; - } - break; - } - case BIN(pop): - { - switch (state) { - case SCS_AX: - case SCS_BX: - state = SCS_XX; - break; - case SCS_AB: - state = SCS_AX; - break; - case SCS_BA: - state = SCS_BX; - break; - case SCS_XX: - goto normal_insn; - default: - COMPILE_ERROR(iseq, iobj->insn_info.line_no, - "unreachable"); - return COMPILE_NG; - } - /* remove useless pop */ - ELEM_REMOVE(list); - list = list->next; - goto redo_point; - } - default:; - /* none */ - } /* end of switch */ - normal_insn: - state = insn_set_sc_state(iseq, anchor, iobj, state); - break; - } - case ISEQ_ELEMENT_LABEL: - { - LABEL *lobj; - lobj = (LABEL *)list; + ELEM_REMOVE(list); + list = list->next; + goto redo_point; + } + break; + } + case BIN(pop): + { + switch (state) { + case SCS_AX: + case SCS_BX: + state = SCS_XX; + break; + case SCS_AB: + state = SCS_AX; + break; + case SCS_BA: + state = SCS_BX; + break; + case SCS_XX: + goto normal_insn; + default: + COMPILE_ERROR(iseq, iobj->insn_info.line_no, + "unreachable"); + return COMPILE_NG; + } + /* remove useless pop */ + ELEM_REMOVE(list); + list = list->next; + goto redo_point; + } + default:; + /* none */ + } /* end of switch */ + normal_insn: + state = insn_set_sc_state(iseq, anchor, iobj, state); + break; + } + case ISEQ_ELEMENT_LABEL: + { + LABEL *lobj; + lobj = (LABEL *)list; - state = label_set_sc_state(lobj, state); - } - default: - break; - } - list = list->next; + state = label_set_sc_state(lobj, state); + } + default: + break; + } + list = list->next; } #endif return COMPILE_OK; @@ -3942,20 +3942,20 @@ all_string_result_p(const NODE *node) if (!node) return FALSE; switch (nd_type(node)) { case NODE_STR: case NODE_DSTR: - return TRUE; + return TRUE; case NODE_IF: case NODE_UNLESS: - if (!node->nd_body || !node->nd_else) return FALSE; - if (all_string_result_p(node->nd_body)) - return all_string_result_p(node->nd_else); - return FALSE; + if (!node->nd_body || !node->nd_else) return FALSE; + if (all_string_result_p(node->nd_body)) + return all_string_result_p(node->nd_else); + return FALSE; case NODE_AND: case NODE_OR: - if (!node->nd_2nd) - return all_string_result_p(node->nd_1st); - if (!all_string_result_p(node->nd_1st)) - return FALSE; - return all_string_result_p(node->nd_2nd); + if (!node->nd_2nd) + return all_string_result_p(node->nd_1st); + if (!all_string_result_p(node->nd_1st)) + return FALSE; + return all_string_result_p(node->nd_2nd); default: - return FALSE; + return FALSE; } } @@ -3969,35 +3969,35 @@ compile_dstr_fragments(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *cons debugp_param("nd_lit", lit); if (!NIL_P(lit)) { - cnt++; - if (!RB_TYPE_P(lit, T_STRING)) { - COMPILE_ERROR(ERROR_ARGS "dstr: must be string: %s", - rb_builtin_type_name(TYPE(lit))); - return COMPILE_NG; - } - lit = rb_fstring(lit); - ADD_INSN1(ret, node, putobject, lit); + cnt++; + if (!RB_TYPE_P(lit, T_STRING)) { + COMPILE_ERROR(ERROR_ARGS "dstr: must be string: %s", + rb_builtin_type_name(TYPE(lit))); + return COMPILE_NG; + } + lit = rb_fstring(lit); + ADD_INSN1(ret, node, putobject, lit); RB_OBJ_WRITTEN(iseq, Qundef, lit); - if (RSTRING_LEN(lit) == 0) first_lit = LAST_ELEMENT(ret); + if (RSTRING_LEN(lit) == 0) first_lit = LAST_ELEMENT(ret); } while (list) { - const NODE *const head = list->nd_head; - if (nd_type_p(head, NODE_STR)) { - lit = rb_fstring(head->nd_lit); - ADD_INSN1(ret, head, putobject, lit); + const NODE *const head = list->nd_head; + if (nd_type_p(head, NODE_STR)) { + lit = rb_fstring(head->nd_lit); + ADD_INSN1(ret, head, putobject, lit); RB_OBJ_WRITTEN(iseq, Qundef, lit); - lit = Qnil; - } - else { - CHECK(COMPILE(ret, "each string", head)); - } - cnt++; - list = list->nd_next; + lit = Qnil; + } + else { + CHECK(COMPILE(ret, "each string", head)); + } + cnt++; + list = list->nd_next; } if (NIL_P(lit) && first_lit) { - ELEM_REMOVE(first_lit); - --cnt; + ELEM_REMOVE(first_lit); + --cnt; } *cntp = cnt; @@ -4045,12 +4045,12 @@ compile_dregx(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node) static int compile_flip_flop(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int again, - LABEL *then_label, LABEL *else_label) + LABEL *then_label, LABEL *else_label) { const int line = nd_line(node); LABEL *lend = NEW_LABEL(line); rb_num_t cnt = ISEQ_FLIP_CNT_INCREMENT(ISEQ_BODY(iseq)->local_iseq) - + VM_SVAR_FLIPFLOP_START; + + VM_SVAR_FLIPFLOP_START; VALUE key = INT2FIX(cnt); ADD_INSN2(ret, node, getspecial, key, INT2FIX(0)); @@ -4062,7 +4062,7 @@ compile_flip_flop(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const nod ADD_INSN1(ret, node, putobject, Qtrue); ADD_INSN1(ret, node, setspecial, key); if (!again) { - ADD_INSNL(ret, node, jump, then_label); + ADD_INSNL(ret, node, jump, then_label); } /* *flip == 1 */ @@ -4078,67 +4078,67 @@ compile_flip_flop(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const nod static int compile_branch_condition(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *cond, - LABEL *then_label, LABEL *else_label) + LABEL *then_label, LABEL *else_label) { again: switch (nd_type(cond)) { case NODE_AND: - { - LABEL *label = NEW_LABEL(nd_line(cond)); - CHECK(compile_branch_condition(iseq, ret, cond->nd_1st, label, - else_label)); + { + LABEL *label = NEW_LABEL(nd_line(cond)); + CHECK(compile_branch_condition(iseq, ret, cond->nd_1st, label, + else_label)); if (!label->refcnt) { ADD_INSN(ret, cond, putnil); break; } - ADD_LABEL(ret, label); - cond = cond->nd_2nd; - goto again; - } + ADD_LABEL(ret, label); + cond = cond->nd_2nd; + goto again; + } case NODE_OR: - { - LABEL *label = NEW_LABEL(nd_line(cond)); - CHECK(compile_branch_condition(iseq, ret, cond->nd_1st, then_label, - label)); + { + LABEL *label = NEW_LABEL(nd_line(cond)); + CHECK(compile_branch_condition(iseq, ret, cond->nd_1st, then_label, + label)); if (!label->refcnt) { ADD_INSN(ret, cond, putnil); break; } - ADD_LABEL(ret, label); - cond = cond->nd_2nd; - goto again; - } + ADD_LABEL(ret, label); + cond = cond->nd_2nd; + goto again; + } case NODE_LIT: /* NODE_LIT is always true */ case NODE_TRUE: case NODE_STR: case NODE_ZLIST: case NODE_LAMBDA: - /* printf("useless condition eliminate (%s)\n", ruby_node_name(nd_type(cond))); */ - ADD_INSNL(ret, cond, jump, then_label); + /* printf("useless condition eliminate (%s)\n", ruby_node_name(nd_type(cond))); */ + ADD_INSNL(ret, cond, jump, then_label); return COMPILE_OK; case NODE_FALSE: case NODE_NIL: - /* printf("useless condition eliminate (%s)\n", ruby_node_name(nd_type(cond))); */ - ADD_INSNL(ret, cond, jump, else_label); + /* printf("useless condition eliminate (%s)\n", ruby_node_name(nd_type(cond))); */ + ADD_INSNL(ret, cond, jump, else_label); return COMPILE_OK; case NODE_LIST: case NODE_ARGSCAT: case NODE_DREGX: case NODE_DSTR: - CHECK(COMPILE_POPPED(ret, "branch condition", cond)); - ADD_INSNL(ret, cond, jump, then_label); + CHECK(COMPILE_POPPED(ret, "branch condition", cond)); + ADD_INSNL(ret, cond, jump, then_label); return COMPILE_OK; case NODE_FLIP2: - CHECK(compile_flip_flop(iseq, ret, cond, TRUE, then_label, else_label)); + CHECK(compile_flip_flop(iseq, ret, cond, TRUE, then_label, else_label)); return COMPILE_OK; case NODE_FLIP3: - CHECK(compile_flip_flop(iseq, ret, cond, FALSE, then_label, else_label)); + CHECK(compile_flip_flop(iseq, ret, cond, FALSE, then_label, else_label)); return COMPILE_OK; case NODE_DEFINED: - CHECK(compile_defined_expr(iseq, ret, cond, Qfalse)); + CHECK(compile_defined_expr(iseq, ret, cond, Qfalse)); break; default: - CHECK(COMPILE(ret, "branch condition", cond)); + CHECK(COMPILE(ret, "branch condition", cond)); break; } @@ -4157,25 +4157,25 @@ keyword_node_p(const NODE *const node) static int compile_keyword_arg(rb_iseq_t *iseq, LINK_ANCHOR *const ret, - const NODE *const root_node, - struct rb_callinfo_kwarg **const kw_arg_ptr, - unsigned int *flag) + const NODE *const root_node, + struct rb_callinfo_kwarg **const kw_arg_ptr, + unsigned int *flag) { if (kw_arg_ptr == NULL) return FALSE; if (root_node->nd_head && nd_type_p(root_node->nd_head, NODE_LIST)) { - const NODE *node = root_node->nd_head; + const NODE *node = root_node->nd_head; int seen_nodes = 0; - while (node) { - const NODE *key_node = node->nd_head; + while (node) { + const NODE *key_node = node->nd_head; seen_nodes++; - assert(nd_type_p(node, NODE_LIST)); + assert(nd_type_p(node, NODE_LIST)); if (key_node && nd_type_p(key_node, NODE_LIT) && SYMBOL_P(key_node->nd_lit)) { - /* can be keywords */ - } - else { + /* can be keywords */ + } + else { if (flag) { *flag |= VM_CALL_KW_SPLAT; if (seen_nodes > 1 || node->nd_next->nd_next) { @@ -4186,33 +4186,33 @@ compile_keyword_arg(rb_iseq_t *iseq, LINK_ANCHOR *const ret, *flag |= VM_CALL_KW_SPLAT_MUT; } } - return FALSE; - } - node = node->nd_next; /* skip value node */ - node = node->nd_next; - } + return FALSE; + } + node = node->nd_next; /* skip value node */ + node = node->nd_next; + } - /* may be keywords */ - node = root_node->nd_head; - { - int len = (int)node->nd_alen / 2; + /* may be keywords */ + node = root_node->nd_head; + { + int len = (int)node->nd_alen / 2; struct rb_callinfo_kwarg *kw_arg = rb_xmalloc_mul_add(len, sizeof(VALUE), sizeof(struct rb_callinfo_kwarg)); - VALUE *keywords = kw_arg->keywords; - int i = 0; - kw_arg->keyword_len = len; + VALUE *keywords = kw_arg->keywords; + int i = 0; + kw_arg->keyword_len = len; - *kw_arg_ptr = kw_arg; + *kw_arg_ptr = kw_arg; - for (i=0; node != NULL; i++, node = node->nd_next->nd_next) { - const NODE *key_node = node->nd_head; - const NODE *val_node = node->nd_next->nd_head; - keywords[i] = key_node->nd_lit; + for (i=0; node != NULL; i++, node = node->nd_next->nd_next) { + const NODE *key_node = node->nd_head; + const NODE *val_node = node->nd_next->nd_head; + keywords[i] = key_node->nd_lit; NO_CHECK(COMPILE(ret, "keyword values", val_node)); - } - assert(i == len); - return TRUE; - } + } + assert(i == len); + return TRUE; + } } return FALSE; } @@ -4252,11 +4252,11 @@ static_literal_node_p(const NODE *node, const rb_iseq_t *iseq) case NODE_NIL: case NODE_TRUE: case NODE_FALSE: - return TRUE; + return TRUE; case NODE_STR: return ISEQ_COMPILE_DATA(iseq)->option->frozen_string_literal; default: - return FALSE; + return FALSE; } } @@ -4265,11 +4265,11 @@ static_literal_value(const NODE *node, rb_iseq_t *iseq) { switch (nd_type(node)) { case NODE_NIL: - return Qnil; + return Qnil; case NODE_TRUE: - return Qtrue; + return Qtrue; case NODE_FALSE: - return Qfalse; + return Qfalse; case NODE_STR: if (ISEQ_COMPILE_DATA(iseq)->option->debug_frozen_string_literal || RTEST(ruby_debug)) { VALUE lit; @@ -4282,7 +4282,7 @@ static_literal_value(const NODE *node, rb_iseq_t *iseq) return rb_fstring(node->nd_lit); } default: - return node->nd_lit; + return node->nd_lit; } } @@ -4292,9 +4292,9 @@ compile_array(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *node, int pop const NODE *line_node = node; if (nd_type_p(node, NODE_ZLIST)) { - if (!popped) { - ADD_INSN1(ret, line_node, newarray, INT2FIX(0)); - } + if (!popped) { + ADD_INSN1(ret, line_node, newarray, INT2FIX(0)); + } return 0; } @@ -4448,9 +4448,9 @@ compile_hash(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *node, int meth node = node->nd_head; if (!node || nd_type_p(node, NODE_ZLIST)) { - if (!popped) { - ADD_INSN1(ret, line_node, newhash, INT2FIX(0)); - } + if (!popped) { + ADD_INSN1(ret, line_node, newhash, INT2FIX(0)); + } return 0; } @@ -4635,62 +4635,62 @@ rb_node_case_when_optimizable_literal(const NODE *const node) { switch (nd_type(node)) { case NODE_LIT: { - VALUE v = node->nd_lit; - double ival; - if (RB_FLOAT_TYPE_P(v) && - modf(RFLOAT_VALUE(v), &ival) == 0.0) { - return FIXABLE(ival) ? LONG2FIX((long)ival) : rb_dbl2big(ival); - } + VALUE v = node->nd_lit; + double ival; + if (RB_FLOAT_TYPE_P(v) && + modf(RFLOAT_VALUE(v), &ival) == 0.0) { + return FIXABLE(ival) ? LONG2FIX((long)ival) : rb_dbl2big(ival); + } if (RB_TYPE_P(v, T_RATIONAL) || RB_TYPE_P(v, T_COMPLEX)) { return Qundef; } - if (SYMBOL_P(v) || rb_obj_is_kind_of(v, rb_cNumeric)) { - return v; - } - break; + if (SYMBOL_P(v) || rb_obj_is_kind_of(v, rb_cNumeric)) { + return v; + } + break; } case NODE_NIL: - return Qnil; + return Qnil; case NODE_TRUE: - return Qtrue; + return Qtrue; case NODE_FALSE: - return Qfalse; + return Qfalse; case NODE_STR: - return rb_fstring(node->nd_lit); + return rb_fstring(node->nd_lit); } return Qundef; } static int when_vals(rb_iseq_t *iseq, LINK_ANCHOR *const cond_seq, const NODE *vals, - LABEL *l1, int only_special_literals, VALUE literals) + LABEL *l1, int only_special_literals, VALUE literals) { while (vals) { - const NODE *val = vals->nd_head; + const NODE *val = vals->nd_head; VALUE lit = rb_node_case_when_optimizable_literal(val); - if (lit == Qundef) { - only_special_literals = 0; - } + if (lit == Qundef) { + only_special_literals = 0; + } else if (NIL_P(rb_hash_lookup(literals, lit))) { rb_hash_aset(literals, lit, (VALUE)(l1) | 1); - } + } - if (nd_type_p(val, NODE_STR)) { - debugp_param("nd_lit", val->nd_lit); - lit = rb_fstring(val->nd_lit); - ADD_INSN1(cond_seq, val, putobject, lit); + if (nd_type_p(val, NODE_STR)) { + debugp_param("nd_lit", val->nd_lit); + lit = rb_fstring(val->nd_lit); + ADD_INSN1(cond_seq, val, putobject, lit); RB_OBJ_WRITTEN(iseq, Qundef, lit); - } - else { - if (!COMPILE(cond_seq, "when cond", val)) return -1; - } + } + else { + if (!COMPILE(cond_seq, "when cond", val)) return -1; + } // Emit patern === target ADD_INSN1(cond_seq, vals, topn, INT2FIX(1)); ADD_CALL(cond_seq, vals, idEqq, INT2FIX(1)); - ADD_INSNL(cond_seq, val, branchif, l1); - vals = vals->nd_next; + ADD_INSNL(cond_seq, val, branchif, l1); + vals = vals->nd_next; } return only_special_literals; } @@ -4873,14 +4873,14 @@ compile_massign_lhs(rb_iseq_t *iseq, LINK_ANCHOR *const pre, LINK_ANCHOR *const { switch (nd_type(node)) { case NODE_ATTRASGN: { - INSN *iobj; + INSN *iobj; const NODE *line_node = node; CHECK(COMPILE_POPPED(pre, "masgn lhs (NODE_ATTRASGN)", node)); LINK_ELEMENT *insn_element = LAST_ELEMENT(pre); iobj = (INSN *)get_prev_insn((INSN *)insn_element); /* send insn */ - ASSUME(iobj); + ASSUME(iobj); ELEM_REMOVE(LAST_ELEMENT(pre)); ELEM_REMOVE((LINK_ELEMENT *)iobj); pre->last = iobj->link.prev; @@ -4903,14 +4903,14 @@ compile_massign_lhs(rb_iseq_t *iseq, LINK_ANCHOR *const pre, LINK_ANCHOR *const } ADD_ELEM(lhs, (LINK_ELEMENT *)iobj); - if (vm_ci_flag(ci) & VM_CALL_ARGS_SPLAT) { + if (vm_ci_flag(ci) & VM_CALL_ARGS_SPLAT) { int argc = vm_ci_argc(ci); ci = ci_argc_set(iseq, ci, argc - 1); OPERAND_AT(iobj, 0) = (VALUE)ci; RB_OBJ_WRITTEN(iseq, Qundef, iobj); INSERT_BEFORE_INSN1(iobj, line_node, newarray, INT2FIX(1)); - INSERT_BEFORE_INSN(iobj, line_node, concatarray); - } + INSERT_BEFORE_INSN(iobj, line_node, concatarray); + } ADD_INSN(lhs, line_node, pop); if (argc != 1) { ADD_INSN(lhs, line_node, pop); @@ -4918,7 +4918,7 @@ compile_massign_lhs(rb_iseq_t *iseq, LINK_ANCHOR *const pre, LINK_ANCHOR *const for (int i=0; i < argc; i++) { ADD_INSN(post, line_node, pop); } - break; + break; } case NODE_MASGN: { DECL_ANCHOR(nest_rhs); @@ -4936,7 +4936,7 @@ compile_massign_lhs(rb_iseq_t *iseq, LINK_ANCHOR *const pre, LINK_ANCHOR *const ADD_SEQ(lhs, nest_rhs); ADD_SEQ(lhs, nest_lhs); - break; + break; } case NODE_CDECL: if (!node->nd_vid) { @@ -4962,10 +4962,10 @@ compile_massign_lhs(rb_iseq_t *iseq, LINK_ANCHOR *const pre, LINK_ANCHOR *const } /* Fallthrough */ default: { - DECL_ANCHOR(anchor); - INIT_ANCHOR(anchor); - CHECK(COMPILE_POPPED(anchor, "masgn lhs", node)); - ELEM_REMOVE(FIRST_ELEMENT(anchor)); + DECL_ANCHOR(anchor); + INIT_ANCHOR(anchor); + CHECK(COMPILE_POPPED(anchor, "masgn lhs", node)); + ELEM_REMOVE(FIRST_ELEMENT(anchor)); ADD_SEQ(lhs, anchor); } } @@ -4977,7 +4977,7 @@ static int compile_massign_opt_lhs(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *lhsn) { if (lhsn) { - CHECK(compile_massign_opt_lhs(iseq, ret, lhsn->nd_next)); + CHECK(compile_massign_opt_lhs(iseq, ret, lhsn->nd_next)); CHECK(compile_massign_lhs(iseq, ret, ret, ret, ret, lhsn->nd_head, NULL, 0)); } return COMPILE_OK; @@ -4985,7 +4985,7 @@ compile_massign_opt_lhs(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *lhs static int compile_massign_opt(rb_iseq_t *iseq, LINK_ANCHOR *const ret, - const NODE *rhsn, const NODE *orig_lhsn) + const NODE *rhsn, const NODE *orig_lhsn) { VALUE mem[64]; const int memsize = numberof(mem); @@ -4998,48 +4998,48 @@ compile_massign_opt(rb_iseq_t *iseq, LINK_ANCHOR *const ret, int i; \ if (memindex == memsize) return 0; \ for (i=0; ind_head; - switch (nd_type(ln)) { - case NODE_LASGN: - MEMORY(ln->nd_vid); - break; - case NODE_DASGN: - case NODE_IASGN: - case NODE_CVASGN: - MEMORY(ln->nd_vid); - break; - default: - return 0; - } - lhsn = lhsn->nd_next; - llen++; + const NODE *ln = lhsn->nd_head; + switch (nd_type(ln)) { + case NODE_LASGN: + MEMORY(ln->nd_vid); + break; + case NODE_DASGN: + case NODE_IASGN: + case NODE_CVASGN: + MEMORY(ln->nd_vid); + break; + default: + return 0; + } + lhsn = lhsn->nd_next; + llen++; } while (rhsn) { - if (llen <= rlen) { + if (llen <= rlen) { NO_CHECK(COMPILE_POPPED(ret, "masgn val (popped)", rhsn->nd_head)); - } - else { + } + else { NO_CHECK(COMPILE(ret, "masgn val", rhsn->nd_head)); - } - rhsn = rhsn->nd_next; - rlen++; + } + rhsn = rhsn->nd_next; + rlen++; } if (llen > rlen) { - for (i=0; ind_vid); + debugi("compile_const_prefix - colon", node->nd_vid); ADD_INSN1(body, node, putobject, Qtrue); ADD_INSN1(body, node, getconstant, ID2SYM(node->nd_vid)); - break; + break; case NODE_COLON3: - debugi("compile_const_prefix - colon3", node->nd_mid); - ADD_INSN(body, node, pop); - ADD_INSN1(body, node, putobject, rb_cObject); + debugi("compile_const_prefix - colon3", node->nd_mid); + ADD_INSN(body, node, pop); + ADD_INSN1(body, node, putobject, rb_cObject); ADD_INSN1(body, node, putobject, Qtrue); ADD_INSN1(body, node, getconstant, ID2SYM(node->nd_mid)); - break; + break; case NODE_COLON2: - CHECK(compile_const_prefix(iseq, node->nd_head, pref, body)); - debugi("compile_const_prefix - colon2", node->nd_mid); + CHECK(compile_const_prefix(iseq, node->nd_head, pref, body)); + debugi("compile_const_prefix - colon2", node->nd_mid); ADD_INSN1(body, node, putobject, Qfalse); ADD_INSN1(body, node, getconstant, ID2SYM(node->nd_mid)); - break; + break; default: - CHECK(COMPILE(pref, "const colon2 prefix", node)); - break; + CHECK(COMPILE(pref, "const colon2 prefix", node)); + break; } return COMPILE_OK; } @@ -5188,20 +5188,20 @@ static int compile_cpath(LINK_ANCHOR *const ret, rb_iseq_t *iseq, const NODE *cpath) { if (nd_type_p(cpath, NODE_COLON3)) { - /* toplevel class ::Foo */ - ADD_INSN1(ret, cpath, putobject, rb_cObject); - return VM_DEFINECLASS_FLAG_SCOPED; + /* toplevel class ::Foo */ + ADD_INSN1(ret, cpath, putobject, rb_cObject); + return VM_DEFINECLASS_FLAG_SCOPED; } else if (cpath->nd_head) { - /* Bar::Foo */ + /* Bar::Foo */ NO_CHECK(COMPILE(ret, "nd_else->nd_head", cpath->nd_head)); - return VM_DEFINECLASS_FLAG_SCOPED; + return VM_DEFINECLASS_FLAG_SCOPED; } else { - /* class at cbase Foo */ - ADD_INSN1(ret, cpath, putspecialobject, - INT2FIX(VM_SPECIAL_OBJECT_CONST_BASE)); - return 0; + /* class at cbase Foo */ + ADD_INSN1(ret, cpath, putspecialobject, + INT2FIX(VM_SPECIAL_OBJECT_CONST_BASE)); + return 0; } } @@ -5217,7 +5217,7 @@ private_recv_p(const NODE *node) static void defined_expr(rb_iseq_t *iseq, LINK_ANCHOR *const ret, - const NODE *const node, LABEL **lfinish, VALUE needstr); + const NODE *const node, LABEL **lfinish, VALUE needstr); static int compile_call(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, const enum node_type type, const NODE *const line_node, int popped, bool assume_receiver); @@ -5234,31 +5234,31 @@ defined_expr0(rb_iseq_t *iseq, LINK_ANCHOR *const ret, switch (type = nd_type(node)) { - /* easy literals */ + /* easy literals */ case NODE_NIL: - expr_type = DEFINED_NIL; - break; + expr_type = DEFINED_NIL; + break; case NODE_SELF: - expr_type = DEFINED_SELF; - break; + expr_type = DEFINED_SELF; + break; case NODE_TRUE: - expr_type = DEFINED_TRUE; - break; + expr_type = DEFINED_TRUE; + break; case NODE_FALSE: - expr_type = DEFINED_FALSE; - break; + expr_type = DEFINED_FALSE; + break; case NODE_LIST:{ - const NODE *vals = node; + const NODE *vals = node; - do { + do { defined_expr0(iseq, ret, vals->nd_head, lfinish, Qfalse, false); - if (!lfinish[1]) { + if (!lfinish[1]) { lfinish[1] = NEW_LABEL(line); - } + } ADD_INSNL(ret, line_node, branchunless, lfinish[1]); - } while ((vals = vals->nd_next) != NULL); + } while ((vals = vals->nd_next) != NULL); } /* fall through */ case NODE_STR: @@ -5267,43 +5267,43 @@ defined_expr0(rb_iseq_t *iseq, LINK_ANCHOR *const ret, case NODE_AND: case NODE_OR: default: - expr_type = DEFINED_EXPR; - break; + expr_type = DEFINED_EXPR; + break; - /* variables */ + /* variables */ case NODE_LVAR: case NODE_DVAR: - expr_type = DEFINED_LVAR; - break; + expr_type = DEFINED_LVAR; + break; #define PUSH_VAL(type) (needstr == Qfalse ? Qtrue : rb_iseq_defined_string(type)) case NODE_IVAR: ADD_INSN(ret, line_node, putnil); ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_IVAR), - ID2SYM(node->nd_vid), PUSH_VAL(DEFINED_IVAR)); + ID2SYM(node->nd_vid), PUSH_VAL(DEFINED_IVAR)); return; case NODE_GVAR: ADD_INSN(ret, line_node, putnil); ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_GVAR), - ID2SYM(node->nd_entry), PUSH_VAL(DEFINED_GVAR)); + ID2SYM(node->nd_entry), PUSH_VAL(DEFINED_GVAR)); return; case NODE_CVAR: ADD_INSN(ret, line_node, putnil); ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_CVAR), - ID2SYM(node->nd_vid), PUSH_VAL(DEFINED_CVAR)); + ID2SYM(node->nd_vid), PUSH_VAL(DEFINED_CVAR)); return; case NODE_CONST: ADD_INSN(ret, line_node, putnil); ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_CONST), - ID2SYM(node->nd_vid), PUSH_VAL(DEFINED_CONST)); + ID2SYM(node->nd_vid), PUSH_VAL(DEFINED_CONST)); return; case NODE_COLON2: - if (!lfinish[1]) { + if (!lfinish[1]) { lfinish[1] = NEW_LABEL(line); - } + } defined_expr0(iseq, ret, node->nd_head, lfinish, Qfalse, false); ADD_INSNL(ret, line_node, branchunless, lfinish[1]); NO_CHECK(COMPILE(ret, "defined/colon2#nd_head", node->nd_head)); @@ -5320,18 +5320,18 @@ defined_expr0(rb_iseq_t *iseq, LINK_ANCHOR *const ret, case NODE_COLON3: ADD_INSN1(ret, line_node, putobject, rb_cObject); ADD_INSN3(ret, line_node, defined, - INT2FIX(DEFINED_CONST_FROM), ID2SYM(node->nd_mid), PUSH_VAL(DEFINED_CONST)); + INT2FIX(DEFINED_CONST_FROM), ID2SYM(node->nd_mid), PUSH_VAL(DEFINED_CONST)); return; - /* method dispatch */ + /* method dispatch */ case NODE_CALL: case NODE_OPCALL: case NODE_VCALL: case NODE_FCALL: case NODE_ATTRASGN:{ - const int explicit_receiver = - (type == NODE_CALL || type == NODE_OPCALL || - (type == NODE_ATTRASGN && !private_recv_p(node))); + const int explicit_receiver = + (type == NODE_CALL || type == NODE_OPCALL || + (type == NODE_ATTRASGN && !private_recv_p(node))); if (node->nd_args || explicit_receiver) { if (!lfinish[1]) { @@ -5341,11 +5341,11 @@ defined_expr0(rb_iseq_t *iseq, LINK_ANCHOR *const ret, lfinish[2] = NEW_LABEL(line); } } - if (node->nd_args) { + if (node->nd_args) { defined_expr0(iseq, ret, node->nd_args, lfinish, Qfalse, false); ADD_INSNL(ret, line_node, branchunless, lfinish[1]); - } - if (explicit_receiver) { + } + if (explicit_receiver) { defined_expr0(iseq, ret, node->nd_recv, lfinish, Qfalse, true); switch (nd_type(node->nd_recv)) { case NODE_CALL: @@ -5365,38 +5365,38 @@ defined_expr0(rb_iseq_t *iseq, LINK_ANCHOR *const ret, ADD_INSN(ret, line_node, dup); } ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_METHOD), - ID2SYM(node->nd_mid), PUSH_VAL(DEFINED_METHOD)); - } - else { + ID2SYM(node->nd_mid), PUSH_VAL(DEFINED_METHOD)); + } + else { ADD_INSN(ret, line_node, putself); if (keep_result) { ADD_INSN(ret, line_node, dup); } ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_FUNC), - ID2SYM(node->nd_mid), PUSH_VAL(DEFINED_METHOD)); - } + ID2SYM(node->nd_mid), PUSH_VAL(DEFINED_METHOD)); + } return; } case NODE_YIELD: ADD_INSN(ret, line_node, putnil); ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_YIELD), 0, - PUSH_VAL(DEFINED_YIELD)); + PUSH_VAL(DEFINED_YIELD)); return; case NODE_BACK_REF: case NODE_NTH_REF: ADD_INSN(ret, line_node, putnil); ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_REF), - INT2FIX((node->nd_nth << 1) | (type == NODE_BACK_REF)), - PUSH_VAL(DEFINED_GVAR)); + INT2FIX((node->nd_nth << 1) | (type == NODE_BACK_REF)), + PUSH_VAL(DEFINED_GVAR)); return; case NODE_SUPER: case NODE_ZSUPER: ADD_INSN(ret, line_node, putnil); ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_ZSUPER), 0, - PUSH_VAL(DEFINED_ZSUPER)); + PUSH_VAL(DEFINED_ZSUPER)); return; #undef PUSH_VAL @@ -5411,8 +5411,8 @@ defined_expr0(rb_iseq_t *iseq, LINK_ANCHOR *const ret, case NODE_IASGN: case NODE_CDECL: case NODE_CVASGN: - expr_type = DEFINED_ASGN; - break; + expr_type = DEFINED_ASGN; + break; } assert(expr_type != DEFINED_NOT_DEFINED); @@ -5436,26 +5436,26 @@ build_defined_rescue_iseq(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const void *u static void defined_expr(rb_iseq_t *iseq, LINK_ANCHOR *const ret, - const NODE *const node, LABEL **lfinish, VALUE needstr) + const NODE *const node, LABEL **lfinish, VALUE needstr) { LINK_ELEMENT *lcur = ret->last; defined_expr0(iseq, ret, node, lfinish, needstr, false); if (lfinish[1]) { - int line = nd_line(node); - LABEL *lstart = NEW_LABEL(line); - LABEL *lend = NEW_LABEL(line); - const rb_iseq_t *rescue; + int line = nd_line(node); + LABEL *lstart = NEW_LABEL(line); + LABEL *lend = NEW_LABEL(line); + const rb_iseq_t *rescue; struct rb_iseq_new_with_callback_callback_func *ifunc = rb_iseq_new_with_callback_new_callback(build_defined_rescue_iseq, NULL); rescue = new_child_iseq_with_callback(iseq, ifunc, rb_str_concat(rb_str_new2("defined guard in "), ISEQ_BODY(iseq)->location.label), iseq, ISEQ_TYPE_RESCUE, 0); - lstart->rescued = LABEL_RESCUE_BEG; - lend->rescued = LABEL_RESCUE_END; - APPEND_LABEL(ret, lcur, lstart); - ADD_LABEL(ret, lend); - ADD_CATCH_ENTRY(CATCH_TYPE_RESCUE, lstart, lend, rescue, lfinish[1]); + lstart->rescued = LABEL_RESCUE_BEG; + lend->rescued = LABEL_RESCUE_END; + APPEND_LABEL(ret, lcur, lstart); + ADD_LABEL(ret, lend); + ADD_CATCH_ENTRY(CATCH_TYPE_RESCUE, lstart, lend, rescue, lfinish[1]); } } @@ -5465,26 +5465,26 @@ compile_defined_expr(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const const int line = nd_line(node); const NODE *line_node = node; if (!node->nd_head) { - VALUE str = rb_iseq_defined_string(DEFINED_NIL); - ADD_INSN1(ret, line_node, putobject, str); + VALUE str = rb_iseq_defined_string(DEFINED_NIL); + ADD_INSN1(ret, line_node, putobject, str); } else { LABEL *lfinish[3]; - LINK_ELEMENT *last = ret->last; - lfinish[0] = NEW_LABEL(line); - lfinish[1] = 0; + LINK_ELEMENT *last = ret->last; + lfinish[0] = NEW_LABEL(line); + lfinish[1] = 0; lfinish[2] = 0; - defined_expr(iseq, ret, node->nd_head, lfinish, needstr); - if (lfinish[1]) { - ELEM_INSERT_NEXT(last, &new_insn_body(iseq, line_node, BIN(putnil), 0)->link); - ADD_INSN(ret, line_node, swap); + defined_expr(iseq, ret, node->nd_head, lfinish, needstr); + if (lfinish[1]) { + ELEM_INSERT_NEXT(last, &new_insn_body(iseq, line_node, BIN(putnil), 0)->link); + ADD_INSN(ret, line_node, swap); if (lfinish[2]) { ADD_LABEL(ret, lfinish[2]); } - ADD_INSN(ret, line_node, pop); - ADD_LABEL(ret, lfinish[1]); - } - ADD_LABEL(ret, lfinish[0]); + ADD_INSN(ret, line_node, pop); + ADD_LABEL(ret, lfinish[1]); + } + ADD_LABEL(ret, lfinish[0]); } return COMPILE_OK; } @@ -5498,10 +5498,10 @@ make_name_for_block(const rb_iseq_t *orig_iseq) if (ISEQ_BODY(orig_iseq)->parent_iseq != 0) { while (ISEQ_BODY(orig_iseq)->local_iseq != iseq) { if (ISEQ_BODY(iseq)->type == ISEQ_TYPE_BLOCK) { - level++; - } + level++; + } iseq = ISEQ_BODY(iseq)->parent_iseq; - } + } } if (level == 1) { @@ -5514,8 +5514,8 @@ make_name_for_block(const rb_iseq_t *orig_iseq) static void push_ensure_entry(rb_iseq_t *iseq, - struct iseq_compile_data_ensure_node_stack *enl, - struct ensure_range *er, const NODE *const node) + struct iseq_compile_data_ensure_node_stack *enl, + struct ensure_range *er, const NODE *const node) { enl->ensure_node = node; enl->prev = ISEQ_COMPILE_DATA(iseq)->ensure_node_stack; /* prev */ @@ -5525,13 +5525,13 @@ push_ensure_entry(rb_iseq_t *iseq, static void add_ensure_range(rb_iseq_t *iseq, struct ensure_range *erange, - LABEL *lstart, LABEL *lend) + LABEL *lstart, LABEL *lend) { struct ensure_range *ne = - compile_data_alloc(iseq, sizeof(struct ensure_range)); + compile_data_alloc(iseq, sizeof(struct ensure_range)); while (erange->next != 0) { - erange = erange->next; + erange = erange->next; } ne->next = 0; ne->begin = lend; @@ -5560,32 +5560,32 @@ add_ensure_iseq(LINK_ANCHOR *const ret, rb_iseq_t *iseq, int is_return) assert(can_add_ensure_iseq(iseq)); struct iseq_compile_data_ensure_node_stack *enlp = - ISEQ_COMPILE_DATA(iseq)->ensure_node_stack; + ISEQ_COMPILE_DATA(iseq)->ensure_node_stack; struct iseq_compile_data_ensure_node_stack *prev_enlp = enlp; DECL_ANCHOR(ensure); INIT_ANCHOR(ensure); while (enlp) { - if (enlp->erange != NULL) { - DECL_ANCHOR(ensure_part); - LABEL *lstart = NEW_LABEL(0); - LABEL *lend = NEW_LABEL(0); - INIT_ANCHOR(ensure_part); + if (enlp->erange != NULL) { + DECL_ANCHOR(ensure_part); + LABEL *lstart = NEW_LABEL(0); + LABEL *lend = NEW_LABEL(0); + INIT_ANCHOR(ensure_part); - add_ensure_range(iseq, enlp->erange, lstart, lend); + add_ensure_range(iseq, enlp->erange, lstart, lend); - ISEQ_COMPILE_DATA(iseq)->ensure_node_stack = enlp->prev; - ADD_LABEL(ensure_part, lstart); + ISEQ_COMPILE_DATA(iseq)->ensure_node_stack = enlp->prev; + ADD_LABEL(ensure_part, lstart); NO_CHECK(COMPILE_POPPED(ensure_part, "ensure part", enlp->ensure_node)); - ADD_LABEL(ensure_part, lend); - ADD_SEQ(ensure, ensure_part); - } - else { - if (!is_return) { - break; - } - } - enlp = enlp->prev; + ADD_LABEL(ensure_part, lend); + ADD_SEQ(ensure, ensure_part); + } + else { + if (!is_return) { + break; + } + } + enlp = enlp->prev; } ISEQ_COMPILE_DATA(iseq)->ensure_node_stack = prev_enlp; ADD_SEQ(ret, ensure); @@ -5668,7 +5668,7 @@ setup_args_core(rb_iseq_t *iseq, LINK_ANCHOR *const args, const NODE *argn, static VALUE setup_args(rb_iseq_t *iseq, LINK_ANCHOR *const args, const NODE *argn, - unsigned int *flag, struct rb_callinfo_kwarg **keywords) + unsigned int *flag, struct rb_callinfo_kwarg **keywords) { VALUE ret; if (argn && nd_type_p(argn, NODE_BLOCK_PASS)) { @@ -5730,44 +5730,44 @@ compile_named_capture_assign(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE ADD_INSNL(ret, line_node, branchunless, fail_label); for (vars = node; vars; vars = vars->nd_next) { - INSN *cap; - if (vars->nd_next) { - ADD_INSN(ret, line_node, dup); - } - last = ret->last; + INSN *cap; + if (vars->nd_next) { + ADD_INSN(ret, line_node, dup); + } + last = ret->last; NO_CHECK(COMPILE_POPPED(ret, "capture", vars->nd_head)); - last = last->next; /* putobject :var */ - cap = new_insn_send(iseq, line_node, idAREF, INT2FIX(1), - NULL, INT2FIX(0), NULL); - ELEM_INSERT_PREV(last->next, (LINK_ELEMENT *)cap); + last = last->next; /* putobject :var */ + cap = new_insn_send(iseq, line_node, idAREF, INT2FIX(1), + NULL, INT2FIX(0), NULL); + ELEM_INSERT_PREV(last->next, (LINK_ELEMENT *)cap); #if !defined(NAMED_CAPTURE_SINGLE_OPT) || NAMED_CAPTURE_SINGLE_OPT-0 - if (!vars->nd_next && vars == node) { - /* only one name */ - DECL_ANCHOR(nom); + if (!vars->nd_next && vars == node) { + /* only one name */ + DECL_ANCHOR(nom); - INIT_ANCHOR(nom); - ADD_INSNL(nom, line_node, jump, end_label); - ADD_LABEL(nom, fail_label); + INIT_ANCHOR(nom); + ADD_INSNL(nom, line_node, jump, end_label); + ADD_LABEL(nom, fail_label); # if 0 /* $~ must be MatchData or nil */ - ADD_INSN(nom, line_node, pop); - ADD_INSN(nom, line_node, putnil); + ADD_INSN(nom, line_node, pop); + ADD_INSN(nom, line_node, putnil); # endif - ADD_LABEL(nom, end_label); - (nom->last->next = cap->link.next)->prev = nom->last; - (cap->link.next = nom->anchor.next)->prev = &cap->link; - return; - } + ADD_LABEL(nom, end_label); + (nom->last->next = cap->link.next)->prev = nom->last; + (cap->link.next = nom->anchor.next)->prev = &cap->link; + return; + } #endif } ADD_INSNL(ret, line_node, jump, end_label); ADD_LABEL(ret, fail_label); ADD_INSN(ret, line_node, pop); for (vars = node; vars; vars = vars->nd_next) { - last = ret->last; + last = ret->last; NO_CHECK(COMPILE_POPPED(ret, "capture", vars->nd_head)); - last = last->next; /* putobject :var */ - ((INSN*)last)->insn_id = BIN(putnil); - ((INSN*)last)->operand_size = 0; + last = last->next; /* putobject :var */ + ((INSN*)last)->insn_id = BIN(putnil); + ((INSN*)last)->operand_size = 0; } ADD_LABEL(ret, end_label); } @@ -5812,7 +5812,7 @@ compile_if(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int end_label = 0; compile_branch_condition(iseq, cond_seq, node->nd_cond, - then_label, else_label); + then_label, else_label); ci_size = body->ci_size; CHECK(COMPILE_(then_seq, "then", node_body, popped)); @@ -5839,44 +5839,44 @@ compile_if(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int ADD_SEQ(ret, cond_seq); if (then_label->refcnt && else_label->refcnt) { - branches = decl_branch_base(iseq, node, type == NODE_IF ? "if" : "unless"); + branches = decl_branch_base(iseq, node, type == NODE_IF ? "if" : "unless"); } if (then_label->refcnt) { - ADD_LABEL(ret, then_label); - if (else_label->refcnt) { - add_trace_branch_coverage( + ADD_LABEL(ret, then_label); + if (else_label->refcnt) { + add_trace_branch_coverage( iseq, - ret, + ret, node_body ? node_body : node, 0, - type == NODE_IF ? "then" : "else", - branches); - end_label = NEW_LABEL(line); - ADD_INSNL(then_seq, line_node, jump, end_label); + type == NODE_IF ? "then" : "else", + branches); + end_label = NEW_LABEL(line); + ADD_INSNL(then_seq, line_node, jump, end_label); if (!popped) { ADD_INSN(then_seq, line_node, pop); } - } - ADD_SEQ(ret, then_seq); + } + ADD_SEQ(ret, then_seq); } if (else_label->refcnt) { - ADD_LABEL(ret, else_label); - if (then_label->refcnt) { - add_trace_branch_coverage( + ADD_LABEL(ret, else_label); + if (then_label->refcnt) { + add_trace_branch_coverage( iseq, - ret, + ret, node_else ? node_else : node, 1, - type == NODE_IF ? "else" : "then", - branches); - } - ADD_SEQ(ret, else_seq); + type == NODE_IF ? "else" : "then", + branches); + } + ADD_SEQ(ret, else_seq); } if (end_label) { - ADD_LABEL(ret, end_label); + ADD_LABEL(ret, end_label); } return COMPILE_OK; @@ -5921,74 +5921,74 @@ compile_case(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const orig_nod ADD_SEQ(ret, head); /* case VAL */ while (type == NODE_WHEN) { - LABEL *l1; + LABEL *l1; - l1 = NEW_LABEL(line); - ADD_LABEL(body_seq, l1); - ADD_INSN(body_seq, line_node, pop); - add_trace_branch_coverage( + l1 = NEW_LABEL(line); + ADD_LABEL(body_seq, l1); + ADD_INSN(body_seq, line_node, pop); + add_trace_branch_coverage( iseq, - body_seq, + body_seq, node->nd_body ? node->nd_body : node, branch_id++, - "when", - branches); - CHECK(COMPILE_(body_seq, "when body", node->nd_body, popped)); - ADD_INSNL(body_seq, line_node, jump, endlabel); + "when", + branches); + CHECK(COMPILE_(body_seq, "when body", node->nd_body, popped)); + ADD_INSNL(body_seq, line_node, jump, endlabel); - vals = node->nd_head; - if (vals) { - switch (nd_type(vals)) { - case NODE_LIST: - only_special_literals = when_vals(iseq, cond_seq, vals, l1, only_special_literals, literals); - if (only_special_literals < 0) return COMPILE_NG; - break; - case NODE_SPLAT: - case NODE_ARGSCAT: - case NODE_ARGSPUSH: - only_special_literals = 0; - CHECK(when_splat_vals(iseq, cond_seq, vals, l1, only_special_literals, literals)); - break; - default: - UNKNOWN_NODE("NODE_CASE", vals, COMPILE_NG); - } - } - else { - EXPECT_NODE_NONULL("NODE_CASE", node, NODE_LIST, COMPILE_NG); - } + vals = node->nd_head; + if (vals) { + switch (nd_type(vals)) { + case NODE_LIST: + only_special_literals = when_vals(iseq, cond_seq, vals, l1, only_special_literals, literals); + if (only_special_literals < 0) return COMPILE_NG; + break; + case NODE_SPLAT: + case NODE_ARGSCAT: + case NODE_ARGSPUSH: + only_special_literals = 0; + CHECK(when_splat_vals(iseq, cond_seq, vals, l1, only_special_literals, literals)); + break; + default: + UNKNOWN_NODE("NODE_CASE", vals, COMPILE_NG); + } + } + else { + EXPECT_NODE_NONULL("NODE_CASE", node, NODE_LIST, COMPILE_NG); + } - node = node->nd_next; - if (!node) { - break; - } - type = nd_type(node); - line = nd_line(node); + node = node->nd_next; + if (!node) { + break; + } + type = nd_type(node); + line = nd_line(node); line_node = node; } /* else */ if (node) { - ADD_LABEL(cond_seq, elselabel); - ADD_INSN(cond_seq, line_node, pop); - add_trace_branch_coverage(iseq, cond_seq, node, branch_id, "else", branches); - CHECK(COMPILE_(cond_seq, "else", node, popped)); - ADD_INSNL(cond_seq, line_node, jump, endlabel); + ADD_LABEL(cond_seq, elselabel); + ADD_INSN(cond_seq, line_node, pop); + add_trace_branch_coverage(iseq, cond_seq, node, branch_id, "else", branches); + CHECK(COMPILE_(cond_seq, "else", node, popped)); + ADD_INSNL(cond_seq, line_node, jump, endlabel); } else { - debugs("== else (implicit)\n"); - ADD_LABEL(cond_seq, elselabel); - ADD_INSN(cond_seq, orig_node, pop); - add_trace_branch_coverage(iseq, cond_seq, orig_node, branch_id, "else", branches); - if (!popped) { - ADD_INSN(cond_seq, orig_node, putnil); - } - ADD_INSNL(cond_seq, orig_node, jump, endlabel); + debugs("== else (implicit)\n"); + ADD_LABEL(cond_seq, elselabel); + ADD_INSN(cond_seq, orig_node, pop); + add_trace_branch_coverage(iseq, cond_seq, orig_node, branch_id, "else", branches); + if (!popped) { + ADD_INSN(cond_seq, orig_node, putnil); + } + ADD_INSNL(cond_seq, orig_node, jump, endlabel); } if (only_special_literals && ISEQ_COMPILE_DATA(iseq)->option->specialized_instruction) { - ADD_INSN(ret, orig_node, dup); - ADD_INSN2(ret, orig_node, opt_case_dispatch, literals, elselabel); + ADD_INSN(ret, orig_node, dup); + ADD_INSN2(ret, orig_node, opt_case_dispatch, literals, elselabel); RB_OBJ_WRITTEN(iseq, Qundef, literals); - LABEL_REF(elselabel); + LABEL_REF(elselabel); } ADD_SEQ(ret, cond_seq); @@ -6014,56 +6014,56 @@ compile_case2(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const orig_no endlabel = NEW_LABEL(nd_line(node)); while (node && nd_type_p(node, NODE_WHEN)) { - const int line = nd_line(node); - LABEL *l1 = NEW_LABEL(line); - ADD_LABEL(body_seq, l1); - add_trace_branch_coverage( + const int line = nd_line(node); + LABEL *l1 = NEW_LABEL(line); + ADD_LABEL(body_seq, l1); + add_trace_branch_coverage( iseq, - body_seq, - node->nd_body ? node->nd_body : node, + body_seq, + node->nd_body ? node->nd_body : node, branch_id++, - "when", - branches); - CHECK(COMPILE_(body_seq, "when", node->nd_body, popped)); - ADD_INSNL(body_seq, node, jump, endlabel); + "when", + branches); + CHECK(COMPILE_(body_seq, "when", node->nd_body, popped)); + ADD_INSNL(body_seq, node, jump, endlabel); - vals = node->nd_head; - if (!vals) { + vals = node->nd_head; + if (!vals) { EXPECT_NODE_NONULL("NODE_WHEN", node, NODE_LIST, COMPILE_NG); - } - switch (nd_type(vals)) { - case NODE_LIST: - while (vals) { - LABEL *lnext; - val = vals->nd_head; - lnext = NEW_LABEL(nd_line(val)); - debug_compile("== when2\n", (void)0); - CHECK(compile_branch_condition(iseq, ret, val, l1, lnext)); - ADD_LABEL(ret, lnext); - vals = vals->nd_next; - } - break; - case NODE_SPLAT: - case NODE_ARGSCAT: - case NODE_ARGSPUSH: - ADD_INSN(ret, vals, putnil); - CHECK(COMPILE(ret, "when2/cond splat", vals)); - ADD_INSN1(ret, vals, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_WHEN | VM_CHECKMATCH_ARRAY)); - ADD_INSNL(ret, vals, branchif, l1); - break; - default: - UNKNOWN_NODE("NODE_WHEN", vals, COMPILE_NG); - } - node = node->nd_next; + } + switch (nd_type(vals)) { + case NODE_LIST: + while (vals) { + LABEL *lnext; + val = vals->nd_head; + lnext = NEW_LABEL(nd_line(val)); + debug_compile("== when2\n", (void)0); + CHECK(compile_branch_condition(iseq, ret, val, l1, lnext)); + ADD_LABEL(ret, lnext); + vals = vals->nd_next; + } + break; + case NODE_SPLAT: + case NODE_ARGSCAT: + case NODE_ARGSPUSH: + ADD_INSN(ret, vals, putnil); + CHECK(COMPILE(ret, "when2/cond splat", vals)); + ADD_INSN1(ret, vals, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_WHEN | VM_CHECKMATCH_ARRAY)); + ADD_INSNL(ret, vals, branchif, l1); + break; + default: + UNKNOWN_NODE("NODE_WHEN", vals, COMPILE_NG); + } + node = node->nd_next; } /* else */ add_trace_branch_coverage( iseq, - ret, + ret, node ? node : orig_node, branch_id, - "else", - branches); + "else", + branches); CHECK(COMPILE_(ret, "else", node, popped)); ADD_INSNL(ret, orig_node, jump, endlabel); @@ -7181,11 +7181,11 @@ compile_loop(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, in push_ensure_entry(iseq, &enl, NULL, NULL); if (node->nd_state == 1) { - ADD_INSNL(ret, line_node, jump, next_label); + ADD_INSNL(ret, line_node, jump, next_label); } else { - tmp_label = NEW_LABEL(line); - ADD_INSNL(ret, line_node, jump, tmp_label); + tmp_label = NEW_LABEL(line); + ADD_INSNL(ret, line_node, jump, tmp_label); } ADD_LABEL(ret, adjust_label); ADD_INSN(ret, line_node, putnil); @@ -7198,48 +7198,48 @@ compile_loop(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, in branches = decl_branch_base(iseq, node, type == NODE_WHILE ? "while" : "until"); add_trace_branch_coverage( iseq, - ret, + ret, node->nd_body ? node->nd_body : node, 0, - "body", - branches); + "body", + branches); CHECK(COMPILE_POPPED(ret, "while body", node->nd_body)); ADD_LABEL(ret, next_label); /* next */ if (type == NODE_WHILE) { - compile_branch_condition(iseq, ret, node->nd_cond, - redo_label, end_label); + compile_branch_condition(iseq, ret, node->nd_cond, + redo_label, end_label); } else { - /* until */ - compile_branch_condition(iseq, ret, node->nd_cond, - end_label, redo_label); + /* until */ + compile_branch_condition(iseq, ret, node->nd_cond, + end_label, redo_label); } ADD_LABEL(ret, end_label); ADD_ADJUST_RESTORE(ret, adjust_label); if (node->nd_state == Qundef) { - /* ADD_INSN(ret, line_node, putundef); */ - COMPILE_ERROR(ERROR_ARGS "unsupported: putundef"); - return COMPILE_NG; + /* ADD_INSN(ret, line_node, putundef); */ + COMPILE_ERROR(ERROR_ARGS "unsupported: putundef"); + return COMPILE_NG; } else { - ADD_INSN(ret, line_node, putnil); + ADD_INSN(ret, line_node, putnil); } ADD_LABEL(ret, break_label); /* break */ if (popped) { - ADD_INSN(ret, line_node, pop); + ADD_INSN(ret, line_node, pop); } ADD_CATCH_ENTRY(CATCH_TYPE_BREAK, redo_label, break_label, NULL, - break_label); + break_label); ADD_CATCH_ENTRY(CATCH_TYPE_NEXT, redo_label, break_label, NULL, - next_catch_label); + next_catch_label); ADD_CATCH_ENTRY(CATCH_TYPE_REDO, redo_label, break_label, NULL, - ISEQ_COMPILE_DATA(iseq)->redo_label); + ISEQ_COMPILE_DATA(iseq)->redo_label); ISEQ_COMPILE_DATA(iseq)->start_label = prev_start_label; ISEQ_COMPILE_DATA(iseq)->end_label = prev_end_label; @@ -7261,23 +7261,23 @@ compile_iter(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, in ADD_LABEL(ret, retry_label); if (nd_type_p(node, NODE_FOR)) { - CHECK(COMPILE(ret, "iter caller (for)", node->nd_iter)); + CHECK(COMPILE(ret, "iter caller (for)", node->nd_iter)); - ISEQ_COMPILE_DATA(iseq)->current_block = child_iseq = - NEW_CHILD_ISEQ(node->nd_body, make_name_for_block(iseq), - ISEQ_TYPE_BLOCK, line); - ADD_SEND_WITH_BLOCK(ret, line_node, idEach, INT2FIX(0), child_iseq); + ISEQ_COMPILE_DATA(iseq)->current_block = child_iseq = + NEW_CHILD_ISEQ(node->nd_body, make_name_for_block(iseq), + ISEQ_TYPE_BLOCK, line); + ADD_SEND_WITH_BLOCK(ret, line_node, idEach, INT2FIX(0), child_iseq); } else { - ISEQ_COMPILE_DATA(iseq)->current_block = child_iseq = - NEW_CHILD_ISEQ(node->nd_body, make_name_for_block(iseq), - ISEQ_TYPE_BLOCK, line); - CHECK(COMPILE(ret, "iter caller", node->nd_iter)); + ISEQ_COMPILE_DATA(iseq)->current_block = child_iseq = + NEW_CHILD_ISEQ(node->nd_body, make_name_for_block(iseq), + ISEQ_TYPE_BLOCK, line); + CHECK(COMPILE(ret, "iter caller", node->nd_iter)); } ADD_LABEL(ret, retry_end_l); if (popped) { - ADD_INSN(ret, line_node, pop); + ADD_INSN(ret, line_node, pop); } ISEQ_COMPILE_DATA(iseq)->current_block = prevblock; @@ -7324,39 +7324,39 @@ compile_break(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, i unsigned long throw_flag = 0; if (ISEQ_COMPILE_DATA(iseq)->redo_label != 0 && can_add_ensure_iseq(iseq)) { - /* while/until */ - LABEL *splabel = NEW_LABEL(0); - ADD_LABEL(ret, splabel); - ADD_ADJUST(ret, line_node, ISEQ_COMPILE_DATA(iseq)->redo_label); - CHECK(COMPILE_(ret, "break val (while/until)", node->nd_stts, - ISEQ_COMPILE_DATA(iseq)->loopval_popped)); - add_ensure_iseq(ret, iseq, 0); - ADD_INSNL(ret, line_node, jump, ISEQ_COMPILE_DATA(iseq)->end_label); - ADD_ADJUST_RESTORE(ret, splabel); + /* while/until */ + LABEL *splabel = NEW_LABEL(0); + ADD_LABEL(ret, splabel); + ADD_ADJUST(ret, line_node, ISEQ_COMPILE_DATA(iseq)->redo_label); + CHECK(COMPILE_(ret, "break val (while/until)", node->nd_stts, + ISEQ_COMPILE_DATA(iseq)->loopval_popped)); + add_ensure_iseq(ret, iseq, 0); + ADD_INSNL(ret, line_node, jump, ISEQ_COMPILE_DATA(iseq)->end_label); + ADD_ADJUST_RESTORE(ret, splabel); - if (!popped) { - ADD_INSN(ret, line_node, putnil); - } + if (!popped) { + ADD_INSN(ret, line_node, putnil); + } } else { const rb_iseq_t *ip = iseq; - while (ip) { - if (!ISEQ_COMPILE_DATA(ip)) { - ip = 0; - break; - } + while (ip) { + if (!ISEQ_COMPILE_DATA(ip)) { + ip = 0; + break; + } - if (ISEQ_COMPILE_DATA(ip)->redo_label != 0) { + if (ISEQ_COMPILE_DATA(ip)->redo_label != 0) { throw_flag = VM_THROW_NO_ESCAPE_FLAG; - } + } else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_BLOCK) { throw_flag = 0; - } + } else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_EVAL) { COMPILE_ERROR(ERROR_ARGS "Can't escape from eval with break"); return COMPILE_NG; - } + } else { ip = ISEQ_BODY(ip)->parent_iseq; continue; @@ -7369,9 +7369,9 @@ compile_break(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, i ADD_INSN(ret, line_node, pop); } return COMPILE_OK; - } - COMPILE_ERROR(ERROR_ARGS "Invalid break"); - return COMPILE_NG; + } + COMPILE_ERROR(ERROR_ARGS "Invalid break"); + return COMPILE_NG; } return COMPILE_OK; } @@ -7383,69 +7383,69 @@ compile_next(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, in unsigned long throw_flag = 0; if (ISEQ_COMPILE_DATA(iseq)->redo_label != 0 && can_add_ensure_iseq(iseq)) { - LABEL *splabel = NEW_LABEL(0); - debugs("next in while loop\n"); - ADD_LABEL(ret, splabel); - CHECK(COMPILE(ret, "next val/valid syntax?", node->nd_stts)); - add_ensure_iseq(ret, iseq, 0); - ADD_ADJUST(ret, line_node, ISEQ_COMPILE_DATA(iseq)->redo_label); - ADD_INSNL(ret, line_node, jump, ISEQ_COMPILE_DATA(iseq)->start_label); - ADD_ADJUST_RESTORE(ret, splabel); - if (!popped) { - ADD_INSN(ret, line_node, putnil); - } + LABEL *splabel = NEW_LABEL(0); + debugs("next in while loop\n"); + ADD_LABEL(ret, splabel); + CHECK(COMPILE(ret, "next val/valid syntax?", node->nd_stts)); + add_ensure_iseq(ret, iseq, 0); + ADD_ADJUST(ret, line_node, ISEQ_COMPILE_DATA(iseq)->redo_label); + ADD_INSNL(ret, line_node, jump, ISEQ_COMPILE_DATA(iseq)->start_label); + ADD_ADJUST_RESTORE(ret, splabel); + if (!popped) { + ADD_INSN(ret, line_node, putnil); + } } else if (ISEQ_COMPILE_DATA(iseq)->end_label && can_add_ensure_iseq(iseq)) { - LABEL *splabel = NEW_LABEL(0); - debugs("next in block\n"); - ADD_LABEL(ret, splabel); - ADD_ADJUST(ret, line_node, ISEQ_COMPILE_DATA(iseq)->start_label); - CHECK(COMPILE(ret, "next val", node->nd_stts)); - add_ensure_iseq(ret, iseq, 0); - ADD_INSNL(ret, line_node, jump, ISEQ_COMPILE_DATA(iseq)->end_label); - ADD_ADJUST_RESTORE(ret, splabel); - splabel->unremovable = FALSE; + LABEL *splabel = NEW_LABEL(0); + debugs("next in block\n"); + ADD_LABEL(ret, splabel); + ADD_ADJUST(ret, line_node, ISEQ_COMPILE_DATA(iseq)->start_label); + CHECK(COMPILE(ret, "next val", node->nd_stts)); + add_ensure_iseq(ret, iseq, 0); + ADD_INSNL(ret, line_node, jump, ISEQ_COMPILE_DATA(iseq)->end_label); + ADD_ADJUST_RESTORE(ret, splabel); + splabel->unremovable = FALSE; - if (!popped) { - ADD_INSN(ret, line_node, putnil); - } + if (!popped) { + ADD_INSN(ret, line_node, putnil); + } } else { - const rb_iseq_t *ip = iseq; + const rb_iseq_t *ip = iseq; - while (ip) { - if (!ISEQ_COMPILE_DATA(ip)) { - ip = 0; - break; - } + while (ip) { + if (!ISEQ_COMPILE_DATA(ip)) { + ip = 0; + break; + } throw_flag = VM_THROW_NO_ESCAPE_FLAG; - if (ISEQ_COMPILE_DATA(ip)->redo_label != 0) { - /* while loop */ - break; - } + if (ISEQ_COMPILE_DATA(ip)->redo_label != 0) { + /* while loop */ + break; + } else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_BLOCK) { - break; - } + break; + } else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_EVAL) { COMPILE_ERROR(ERROR_ARGS "Can't escape from eval with next"); return COMPILE_NG; - } + } ip = ISEQ_BODY(ip)->parent_iseq; - } - if (ip != 0) { - CHECK(COMPILE(ret, "next val", node->nd_stts)); + } + if (ip != 0) { + CHECK(COMPILE(ret, "next val", node->nd_stts)); ADD_INSN1(ret, line_node, throw, INT2FIX(throw_flag | TAG_NEXT)); - if (popped) { - ADD_INSN(ret, line_node, pop); - } - } - else { - COMPILE_ERROR(ERROR_ARGS "Invalid next"); - return COMPILE_NG; - } + if (popped) { + ADD_INSN(ret, line_node, pop); + } + } + else { + COMPILE_ERROR(ERROR_ARGS "Invalid next"); + return COMPILE_NG; + } } return COMPILE_OK; } @@ -7456,65 +7456,65 @@ compile_redo(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, in const NODE *line_node = node; if (ISEQ_COMPILE_DATA(iseq)->redo_label && can_add_ensure_iseq(iseq)) { - LABEL *splabel = NEW_LABEL(0); - debugs("redo in while"); - ADD_LABEL(ret, splabel); - ADD_ADJUST(ret, line_node, ISEQ_COMPILE_DATA(iseq)->redo_label); - add_ensure_iseq(ret, iseq, 0); - ADD_INSNL(ret, line_node, jump, ISEQ_COMPILE_DATA(iseq)->redo_label); - ADD_ADJUST_RESTORE(ret, splabel); - if (!popped) { - ADD_INSN(ret, line_node, putnil); - } + LABEL *splabel = NEW_LABEL(0); + debugs("redo in while"); + ADD_LABEL(ret, splabel); + ADD_ADJUST(ret, line_node, ISEQ_COMPILE_DATA(iseq)->redo_label); + add_ensure_iseq(ret, iseq, 0); + ADD_INSNL(ret, line_node, jump, ISEQ_COMPILE_DATA(iseq)->redo_label); + ADD_ADJUST_RESTORE(ret, splabel); + if (!popped) { + ADD_INSN(ret, line_node, putnil); + } } else if (ISEQ_BODY(iseq)->type != ISEQ_TYPE_EVAL && ISEQ_COMPILE_DATA(iseq)->start_label && can_add_ensure_iseq(iseq)) { - LABEL *splabel = NEW_LABEL(0); + LABEL *splabel = NEW_LABEL(0); - debugs("redo in block"); - ADD_LABEL(ret, splabel); - add_ensure_iseq(ret, iseq, 0); - ADD_ADJUST(ret, line_node, ISEQ_COMPILE_DATA(iseq)->start_label); - ADD_INSNL(ret, line_node, jump, ISEQ_COMPILE_DATA(iseq)->start_label); - ADD_ADJUST_RESTORE(ret, splabel); + debugs("redo in block"); + ADD_LABEL(ret, splabel); + add_ensure_iseq(ret, iseq, 0); + ADD_ADJUST(ret, line_node, ISEQ_COMPILE_DATA(iseq)->start_label); + ADD_INSNL(ret, line_node, jump, ISEQ_COMPILE_DATA(iseq)->start_label); + ADD_ADJUST_RESTORE(ret, splabel); - if (!popped) { - ADD_INSN(ret, line_node, putnil); - } + if (!popped) { + ADD_INSN(ret, line_node, putnil); + } } else { - const rb_iseq_t *ip = iseq; + const rb_iseq_t *ip = iseq; - while (ip) { - if (!ISEQ_COMPILE_DATA(ip)) { - ip = 0; - break; - } + while (ip) { + if (!ISEQ_COMPILE_DATA(ip)) { + ip = 0; + break; + } - if (ISEQ_COMPILE_DATA(ip)->redo_label != 0) { - break; - } + if (ISEQ_COMPILE_DATA(ip)->redo_label != 0) { + break; + } else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_BLOCK) { - break; - } + break; + } else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_EVAL) { COMPILE_ERROR(ERROR_ARGS "Can't escape from eval with redo"); return COMPILE_NG; - } + } ip = ISEQ_BODY(ip)->parent_iseq; - } - if (ip != 0) { - ADD_INSN(ret, line_node, putnil); + } + if (ip != 0) { + ADD_INSN(ret, line_node, putnil); ADD_INSN1(ret, line_node, throw, INT2FIX(VM_THROW_NO_ESCAPE_FLAG | TAG_REDO)); - if (popped) { - ADD_INSN(ret, line_node, pop); - } - } - else { - COMPILE_ERROR(ERROR_ARGS "Invalid redo"); - return COMPILE_NG; - } + if (popped) { + ADD_INSN(ret, line_node, pop); + } + } + else { + COMPILE_ERROR(ERROR_ARGS "Invalid redo"); + return COMPILE_NG; + } } return COMPILE_OK; } @@ -7525,16 +7525,16 @@ compile_retry(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, i const NODE *line_node = node; if (ISEQ_BODY(iseq)->type == ISEQ_TYPE_RESCUE) { - ADD_INSN(ret, line_node, putnil); - ADD_INSN1(ret, line_node, throw, INT2FIX(TAG_RETRY)); + ADD_INSN(ret, line_node, putnil); + ADD_INSN1(ret, line_node, throw, INT2FIX(TAG_RETRY)); - if (popped) { - ADD_INSN(ret, line_node, pop); - } + if (popped) { + ADD_INSN(ret, line_node, pop); + } } else { - COMPILE_ERROR(ERROR_ARGS "Invalid retry"); - return COMPILE_NG; + COMPILE_ERROR(ERROR_ARGS "Invalid retry"); + return COMPILE_NG; } return COMPILE_OK; } @@ -7565,14 +7565,14 @@ compile_rescue(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, ADD_LABEL(ret, lend); if (node->nd_else) { - ADD_INSN(ret, line_node, pop); - CHECK(COMPILE(ret, "rescue else", node->nd_else)); + ADD_INSN(ret, line_node, pop); + CHECK(COMPILE(ret, "rescue else", node->nd_else)); } ADD_INSN(ret, line_node, nop); ADD_LABEL(ret, lcont); if (popped) { - ADD_INSN(ret, line_node, pop); + ADD_INSN(ret, line_node, pop); } /* register catch entry */ @@ -7591,48 +7591,48 @@ compile_resbody(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, LABEL *label_miss, *label_hit; while (resq) { - label_miss = NEW_LABEL(line); - label_hit = NEW_LABEL(line); + label_miss = NEW_LABEL(line); + label_hit = NEW_LABEL(line); - narg = resq->nd_args; - if (narg) { - switch (nd_type(narg)) { - case NODE_LIST: - while (narg) { - ADD_GETLOCAL(ret, line_node, LVAR_ERRINFO, 0); - CHECK(COMPILE(ret, "rescue arg", narg->nd_head)); - ADD_INSN1(ret, line_node, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_RESCUE)); - ADD_INSNL(ret, line_node, branchif, label_hit); - narg = narg->nd_next; - } - break; - case NODE_SPLAT: - case NODE_ARGSCAT: - case NODE_ARGSPUSH: - ADD_GETLOCAL(ret, line_node, LVAR_ERRINFO, 0); - CHECK(COMPILE(ret, "rescue/cond splat", narg)); - ADD_INSN1(ret, line_node, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_RESCUE | VM_CHECKMATCH_ARRAY)); - ADD_INSNL(ret, line_node, branchif, label_hit); - break; - default: - UNKNOWN_NODE("NODE_RESBODY", narg, COMPILE_NG); - } - } - else { - ADD_GETLOCAL(ret, line_node, LVAR_ERRINFO, 0); - ADD_INSN1(ret, line_node, putobject, rb_eStandardError); - ADD_INSN1(ret, line_node, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_RESCUE)); - ADD_INSNL(ret, line_node, branchif, label_hit); - } - ADD_INSNL(ret, line_node, jump, label_miss); - ADD_LABEL(ret, label_hit); - CHECK(COMPILE(ret, "resbody body", resq->nd_body)); - if (ISEQ_COMPILE_DATA(iseq)->option->tailcall_optimization) { - ADD_INSN(ret, line_node, nop); - } - ADD_INSN(ret, line_node, leave); - ADD_LABEL(ret, label_miss); - resq = resq->nd_head; + narg = resq->nd_args; + if (narg) { + switch (nd_type(narg)) { + case NODE_LIST: + while (narg) { + ADD_GETLOCAL(ret, line_node, LVAR_ERRINFO, 0); + CHECK(COMPILE(ret, "rescue arg", narg->nd_head)); + ADD_INSN1(ret, line_node, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_RESCUE)); + ADD_INSNL(ret, line_node, branchif, label_hit); + narg = narg->nd_next; + } + break; + case NODE_SPLAT: + case NODE_ARGSCAT: + case NODE_ARGSPUSH: + ADD_GETLOCAL(ret, line_node, LVAR_ERRINFO, 0); + CHECK(COMPILE(ret, "rescue/cond splat", narg)); + ADD_INSN1(ret, line_node, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_RESCUE | VM_CHECKMATCH_ARRAY)); + ADD_INSNL(ret, line_node, branchif, label_hit); + break; + default: + UNKNOWN_NODE("NODE_RESBODY", narg, COMPILE_NG); + } + } + else { + ADD_GETLOCAL(ret, line_node, LVAR_ERRINFO, 0); + ADD_INSN1(ret, line_node, putobject, rb_eStandardError); + ADD_INSN1(ret, line_node, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_RESCUE)); + ADD_INSNL(ret, line_node, branchif, label_hit); + } + ADD_INSNL(ret, line_node, jump, label_miss); + ADD_LABEL(ret, label_hit); + CHECK(COMPILE(ret, "resbody body", resq->nd_body)); + if (ISEQ_COMPILE_DATA(iseq)->option->tailcall_optimization) { + ADD_INSN(ret, line_node, nop); + } + ADD_INSN(ret, line_node, leave); + ADD_LABEL(ret, label_miss); + resq = resq->nd_head; } return COMPILE_OK; } @@ -7645,7 +7645,7 @@ compile_ensure(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, DECL_ANCHOR(ensr); const rb_iseq_t *ensure = NEW_CHILD_ISEQ(node->nd_ensr, rb_str_concat(rb_str_new2 ("ensure in "), ISEQ_BODY(iseq)->location.label), - ISEQ_TYPE_ENSURE, line); + ISEQ_TYPE_ENSURE, line); LABEL *lstart = NEW_LABEL(line); LABEL *lend = NEW_LABEL(line); LABEL *lcont = NEW_LABEL(line); @@ -7675,11 +7675,11 @@ compile_ensure(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, erange = ISEQ_COMPILE_DATA(iseq)->ensure_node_stack->erange; if (lstart->link.next != &lend->link) { - while (erange) { - ADD_CATCH_ENTRY(CATCH_TYPE_ENSURE, erange->begin, erange->end, - ensure, lcont); - erange = erange->next; - } + while (erange) { + ADD_CATCH_ENTRY(CATCH_TYPE_ENSURE, erange->begin, erange->end, + ensure, lcont); + erange = erange->next; + } } ISEQ_COMPILE_DATA(iseq)->ensure_node_stack = enl.prev; @@ -7693,54 +7693,54 @@ compile_return(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, if (iseq) { enum iseq_type type = ISEQ_BODY(iseq)->type; - const rb_iseq_t *is = iseq; - enum iseq_type t = type; - const NODE *retval = node->nd_stts; - LABEL *splabel = 0; + const rb_iseq_t *is = iseq; + enum iseq_type t = type; + const NODE *retval = node->nd_stts; + LABEL *splabel = 0; - while (t == ISEQ_TYPE_RESCUE || t == ISEQ_TYPE_ENSURE) { + while (t == ISEQ_TYPE_RESCUE || t == ISEQ_TYPE_ENSURE) { if (!(is = ISEQ_BODY(is)->parent_iseq)) break; t = ISEQ_BODY(is)->type; - } - switch (t) { - case ISEQ_TYPE_TOP: - case ISEQ_TYPE_MAIN: + } + switch (t) { + case ISEQ_TYPE_TOP: + case ISEQ_TYPE_MAIN: if (retval) { rb_warn("argument of top-level return is ignored"); } - if (is == iseq) { - /* plain top-level, leave directly */ - type = ISEQ_TYPE_METHOD; - } - break; - default: - break; - } + if (is == iseq) { + /* plain top-level, leave directly */ + type = ISEQ_TYPE_METHOD; + } + break; + default: + break; + } - if (type == ISEQ_TYPE_METHOD) { - splabel = NEW_LABEL(0); - ADD_LABEL(ret, splabel); - ADD_ADJUST(ret, line_node, 0); - } + if (type == ISEQ_TYPE_METHOD) { + splabel = NEW_LABEL(0); + ADD_LABEL(ret, splabel); + ADD_ADJUST(ret, line_node, 0); + } - CHECK(COMPILE(ret, "return nd_stts (return val)", retval)); + CHECK(COMPILE(ret, "return nd_stts (return val)", retval)); - if (type == ISEQ_TYPE_METHOD && can_add_ensure_iseq(iseq)) { - add_ensure_iseq(ret, iseq, 1); - ADD_TRACE(ret, RUBY_EVENT_RETURN); - ADD_INSN(ret, line_node, leave); - ADD_ADJUST_RESTORE(ret, splabel); + if (type == ISEQ_TYPE_METHOD && can_add_ensure_iseq(iseq)) { + add_ensure_iseq(ret, iseq, 1); + ADD_TRACE(ret, RUBY_EVENT_RETURN); + ADD_INSN(ret, line_node, leave); + ADD_ADJUST_RESTORE(ret, splabel); - if (!popped) { - ADD_INSN(ret, line_node, putnil); - } - } - else { - ADD_INSN1(ret, line_node, throw, INT2FIX(TAG_RETURN)); - if (popped) { - ADD_INSN(ret, line_node, pop); - } - } + if (!popped) { + ADD_INSN(ret, line_node, putnil); + } + } + else { + ADD_INSN1(ret, line_node, throw, INT2FIX(TAG_RETURN)); + if (popped) { + ADD_INSN(ret, line_node, pop); + } + } } return COMPILE_OK; } @@ -7752,7 +7752,7 @@ compile_evstr(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, i if (!popped && !all_string_result_p(node)) { const NODE *line_node = node; - const unsigned int flag = VM_CALL_FCALL; + const unsigned int flag = VM_CALL_FCALL; // Note, this dup could be removed if we are willing to change anytostring. It pops // two VALUEs off the stack when it could work by replacing the top most VALUE. @@ -8340,106 +8340,106 @@ compile_op_asgn1(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node */ if (!popped) { - ADD_INSN(ret, node, putnil); + ADD_INSN(ret, node, putnil); } asgnflag = COMPILE_RECV(ret, "NODE_OP_ASGN1 recv", node); CHECK(asgnflag != -1); switch (nd_type(node->nd_args->nd_head)) { case NODE_ZLIST: - argc = INT2FIX(0); - break; + argc = INT2FIX(0); + break; case NODE_BLOCK_PASS: - boff = 1; - /* fall through */ + boff = 1; + /* fall through */ default: - argc = setup_args(iseq, ret, node->nd_args->nd_head, &flag, NULL); - CHECK(!NIL_P(argc)); + argc = setup_args(iseq, ret, node->nd_args->nd_head, &flag, NULL); + CHECK(!NIL_P(argc)); } ADD_INSN1(ret, node, dupn, FIXNUM_INC(argc, 1 + boff)); flag |= asgnflag; ADD_SEND_WITH_FLAG(ret, node, idAREF, argc, INT2FIX(flag)); if (id == idOROP || id == idANDOP) { - /* a[x] ||= y or a[x] &&= y + /* a[x] ||= y or a[x] &&= y - unless/if a[x] - a[x]= y - else - nil - end - */ - LABEL *label = NEW_LABEL(line); - LABEL *lfin = NEW_LABEL(line); + unless/if a[x] + a[x]= y + else + nil + end + */ + LABEL *label = NEW_LABEL(line); + LABEL *lfin = NEW_LABEL(line); - ADD_INSN(ret, node, dup); - if (id == idOROP) { - ADD_INSNL(ret, node, branchif, label); - } - else { /* idANDOP */ - ADD_INSNL(ret, node, branchunless, label); - } - ADD_INSN(ret, node, pop); + ADD_INSN(ret, node, dup); + if (id == idOROP) { + ADD_INSNL(ret, node, branchif, label); + } + else { /* idANDOP */ + ADD_INSNL(ret, node, branchunless, label); + } + ADD_INSN(ret, node, pop); - CHECK(COMPILE(ret, "NODE_OP_ASGN1 args->body: ", node->nd_args->nd_body)); - if (!popped) { - ADD_INSN1(ret, node, setn, FIXNUM_INC(argc, 2+boff)); - } - if (flag & VM_CALL_ARGS_SPLAT) { - ADD_INSN1(ret, node, newarray, INT2FIX(1)); - if (boff > 0) { - ADD_INSN1(ret, node, dupn, INT2FIX(3)); - ADD_INSN(ret, node, swap); - ADD_INSN(ret, node, pop); - } - ADD_INSN(ret, node, concatarray); - if (boff > 0) { - ADD_INSN1(ret, node, setn, INT2FIX(3)); - ADD_INSN(ret, node, pop); - ADD_INSN(ret, node, pop); - } - ADD_SEND_WITH_FLAG(ret, node, idASET, argc, INT2FIX(flag)); - } - else { - if (boff > 0) - ADD_INSN(ret, node, swap); - ADD_SEND_WITH_FLAG(ret, node, idASET, FIXNUM_INC(argc, 1), INT2FIX(flag)); - } - ADD_INSN(ret, node, pop); - ADD_INSNL(ret, node, jump, lfin); - ADD_LABEL(ret, label); - if (!popped) { - ADD_INSN1(ret, node, setn, FIXNUM_INC(argc, 2+boff)); - } - ADD_INSN1(ret, node, adjuststack, FIXNUM_INC(argc, 2+boff)); - ADD_LABEL(ret, lfin); + CHECK(COMPILE(ret, "NODE_OP_ASGN1 args->body: ", node->nd_args->nd_body)); + if (!popped) { + ADD_INSN1(ret, node, setn, FIXNUM_INC(argc, 2+boff)); + } + if (flag & VM_CALL_ARGS_SPLAT) { + ADD_INSN1(ret, node, newarray, INT2FIX(1)); + if (boff > 0) { + ADD_INSN1(ret, node, dupn, INT2FIX(3)); + ADD_INSN(ret, node, swap); + ADD_INSN(ret, node, pop); + } + ADD_INSN(ret, node, concatarray); + if (boff > 0) { + ADD_INSN1(ret, node, setn, INT2FIX(3)); + ADD_INSN(ret, node, pop); + ADD_INSN(ret, node, pop); + } + ADD_SEND_WITH_FLAG(ret, node, idASET, argc, INT2FIX(flag)); + } + else { + if (boff > 0) + ADD_INSN(ret, node, swap); + ADD_SEND_WITH_FLAG(ret, node, idASET, FIXNUM_INC(argc, 1), INT2FIX(flag)); + } + ADD_INSN(ret, node, pop); + ADD_INSNL(ret, node, jump, lfin); + ADD_LABEL(ret, label); + if (!popped) { + ADD_INSN1(ret, node, setn, FIXNUM_INC(argc, 2+boff)); + } + ADD_INSN1(ret, node, adjuststack, FIXNUM_INC(argc, 2+boff)); + ADD_LABEL(ret, lfin); } else { - CHECK(COMPILE(ret, "NODE_OP_ASGN1 args->body: ", node->nd_args->nd_body)); - ADD_SEND(ret, node, id, INT2FIX(1)); - if (!popped) { - ADD_INSN1(ret, node, setn, FIXNUM_INC(argc, 2+boff)); - } - if (flag & VM_CALL_ARGS_SPLAT) { - ADD_INSN1(ret, node, newarray, INT2FIX(1)); - if (boff > 0) { - ADD_INSN1(ret, node, dupn, INT2FIX(3)); - ADD_INSN(ret, node, swap); - ADD_INSN(ret, node, pop); - } - ADD_INSN(ret, node, concatarray); - if (boff > 0) { - ADD_INSN1(ret, node, setn, INT2FIX(3)); - ADD_INSN(ret, node, pop); - ADD_INSN(ret, node, pop); - } - ADD_SEND_WITH_FLAG(ret, node, idASET, argc, INT2FIX(flag)); - } - else { - if (boff > 0) - ADD_INSN(ret, node, swap); - ADD_SEND_WITH_FLAG(ret, node, idASET, FIXNUM_INC(argc, 1), INT2FIX(flag)); - } - ADD_INSN(ret, node, pop); + CHECK(COMPILE(ret, "NODE_OP_ASGN1 args->body: ", node->nd_args->nd_body)); + ADD_SEND(ret, node, id, INT2FIX(1)); + if (!popped) { + ADD_INSN1(ret, node, setn, FIXNUM_INC(argc, 2+boff)); + } + if (flag & VM_CALL_ARGS_SPLAT) { + ADD_INSN1(ret, node, newarray, INT2FIX(1)); + if (boff > 0) { + ADD_INSN1(ret, node, dupn, INT2FIX(3)); + ADD_INSN(ret, node, swap); + ADD_INSN(ret, node, pop); + } + ADD_INSN(ret, node, concatarray); + if (boff > 0) { + ADD_INSN1(ret, node, setn, INT2FIX(3)); + ADD_INSN(ret, node, pop); + ADD_INSN(ret, node, pop); + } + ADD_SEND_WITH_FLAG(ret, node, idASET, argc, INT2FIX(flag)); + } + else { + if (boff > 0) + ADD_INSN(ret, node, swap); + ADD_SEND_WITH_FLAG(ret, node, idASET, FIXNUM_INC(argc, 1), INT2FIX(flag)); + } + ADD_INSN(ret, node, pop); } return COMPILE_OK; } @@ -8499,56 +8499,56 @@ compile_op_asgn2(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node asgnflag = COMPILE_RECV(ret, "NODE_OP_ASGN2#recv", node); CHECK(asgnflag != -1); if (node->nd_next->nd_aid) { - lskip = NEW_LABEL(line); - ADD_INSN(ret, node, dup); - ADD_INSNL(ret, node, branchnil, lskip); + lskip = NEW_LABEL(line); + ADD_INSN(ret, node, dup); + ADD_INSNL(ret, node, branchnil, lskip); } ADD_INSN(ret, node, dup); ADD_SEND_WITH_FLAG(ret, node, vid, INT2FIX(0), INT2FIX(asgnflag)); if (atype == idOROP || atype == idANDOP) { - ADD_INSN(ret, node, dup); - if (atype == idOROP) { - ADD_INSNL(ret, node, branchif, lcfin); - } - else { /* idANDOP */ - ADD_INSNL(ret, node, branchunless, lcfin); - } - ADD_INSN(ret, node, pop); - CHECK(COMPILE(ret, "NODE_OP_ASGN2 val", node->nd_value)); - ADD_INSN(ret, node, swap); - ADD_INSN1(ret, node, topn, INT2FIX(1)); - ADD_SEND_WITH_FLAG(ret, node, aid, INT2FIX(1), INT2FIX(asgnflag)); - ADD_INSNL(ret, node, jump, lfin); + ADD_INSN(ret, node, dup); + if (atype == idOROP) { + ADD_INSNL(ret, node, branchif, lcfin); + } + else { /* idANDOP */ + ADD_INSNL(ret, node, branchunless, lcfin); + } + ADD_INSN(ret, node, pop); + CHECK(COMPILE(ret, "NODE_OP_ASGN2 val", node->nd_value)); + ADD_INSN(ret, node, swap); + ADD_INSN1(ret, node, topn, INT2FIX(1)); + ADD_SEND_WITH_FLAG(ret, node, aid, INT2FIX(1), INT2FIX(asgnflag)); + ADD_INSNL(ret, node, jump, lfin); - ADD_LABEL(ret, lcfin); - ADD_INSN(ret, node, swap); + ADD_LABEL(ret, lcfin); + ADD_INSN(ret, node, swap); - ADD_LABEL(ret, lfin); - ADD_INSN(ret, node, pop); - if (lskip) { - ADD_LABEL(ret, lskip); - } - if (popped) { - /* we can apply more optimize */ - ADD_INSN(ret, node, pop); - } + ADD_LABEL(ret, lfin); + ADD_INSN(ret, node, pop); + if (lskip) { + ADD_LABEL(ret, lskip); + } + if (popped) { + /* we can apply more optimize */ + ADD_INSN(ret, node, pop); + } } else { - CHECK(COMPILE(ret, "NODE_OP_ASGN2 val", node->nd_value)); - ADD_SEND(ret, node, atype, INT2FIX(1)); - if (!popped) { - ADD_INSN(ret, node, swap); - ADD_INSN1(ret, node, topn, INT2FIX(1)); - } - ADD_SEND_WITH_FLAG(ret, node, aid, INT2FIX(1), INT2FIX(asgnflag)); - if (lskip && popped) { - ADD_LABEL(ret, lskip); - } - ADD_INSN(ret, node, pop); - if (lskip && !popped) { - ADD_LABEL(ret, lskip); - } + CHECK(COMPILE(ret, "NODE_OP_ASGN2 val", node->nd_value)); + ADD_SEND(ret, node, atype, INT2FIX(1)); + if (!popped) { + ADD_INSN(ret, node, swap); + ADD_INSN1(ret, node, topn, INT2FIX(1)); + } + ADD_SEND_WITH_FLAG(ret, node, aid, INT2FIX(1), INT2FIX(asgnflag)); + if (lskip && popped) { + ADD_LABEL(ret, lskip); + } + ADD_INSN(ret, node, pop); + if (lskip && !popped) { + ADD_LABEL(ret, lskip); + } } return COMPILE_OK; } @@ -8563,63 +8563,63 @@ compile_op_cdecl(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node switch (nd_type(node->nd_head)) { case NODE_COLON3: - ADD_INSN1(ret, node, putobject, rb_cObject); - break; + ADD_INSN1(ret, node, putobject, rb_cObject); + break; case NODE_COLON2: - CHECK(COMPILE(ret, "NODE_OP_CDECL/colon2#nd_head", node->nd_head->nd_head)); - break; + CHECK(COMPILE(ret, "NODE_OP_CDECL/colon2#nd_head", node->nd_head->nd_head)); + break; default: - COMPILE_ERROR(ERROR_ARGS "%s: invalid node in NODE_OP_CDECL", - ruby_node_name(nd_type(node->nd_head))); - return COMPILE_NG; + COMPILE_ERROR(ERROR_ARGS "%s: invalid node in NODE_OP_CDECL", + ruby_node_name(nd_type(node->nd_head))); + return COMPILE_NG; } mid = node->nd_head->nd_mid; /* cref */ if (node->nd_aid == idOROP) { - lassign = NEW_LABEL(line); - ADD_INSN(ret, node, dup); /* cref cref */ - ADD_INSN3(ret, node, defined, INT2FIX(DEFINED_CONST_FROM), - ID2SYM(mid), Qtrue); /* cref bool */ - ADD_INSNL(ret, node, branchunless, lassign); /* cref */ + lassign = NEW_LABEL(line); + ADD_INSN(ret, node, dup); /* cref cref */ + ADD_INSN3(ret, node, defined, INT2FIX(DEFINED_CONST_FROM), + ID2SYM(mid), Qtrue); /* cref bool */ + ADD_INSNL(ret, node, branchunless, lassign); /* cref */ } ADD_INSN(ret, node, dup); /* cref cref */ ADD_INSN1(ret, node, putobject, Qtrue); ADD_INSN1(ret, node, getconstant, ID2SYM(mid)); /* cref obj */ if (node->nd_aid == idOROP || node->nd_aid == idANDOP) { - lfin = NEW_LABEL(line); - if (!popped) ADD_INSN(ret, node, dup); /* cref [obj] obj */ - if (node->nd_aid == idOROP) - ADD_INSNL(ret, node, branchif, lfin); - else /* idANDOP */ - ADD_INSNL(ret, node, branchunless, lfin); - /* cref [obj] */ - if (!popped) ADD_INSN(ret, node, pop); /* cref */ - if (lassign) ADD_LABEL(ret, lassign); - CHECK(COMPILE(ret, "NODE_OP_CDECL#nd_value", node->nd_value)); - /* cref value */ - if (popped) - ADD_INSN1(ret, node, topn, INT2FIX(1)); /* cref value cref */ - else { - ADD_INSN1(ret, node, dupn, INT2FIX(2)); /* cref value cref value */ - ADD_INSN(ret, node, swap); /* cref value value cref */ - } - ADD_INSN1(ret, node, setconstant, ID2SYM(mid)); /* cref [value] */ - ADD_LABEL(ret, lfin); /* cref [value] */ - if (!popped) ADD_INSN(ret, node, swap); /* [value] cref */ - ADD_INSN(ret, node, pop); /* [value] */ + lfin = NEW_LABEL(line); + if (!popped) ADD_INSN(ret, node, dup); /* cref [obj] obj */ + if (node->nd_aid == idOROP) + ADD_INSNL(ret, node, branchif, lfin); + else /* idANDOP */ + ADD_INSNL(ret, node, branchunless, lfin); + /* cref [obj] */ + if (!popped) ADD_INSN(ret, node, pop); /* cref */ + if (lassign) ADD_LABEL(ret, lassign); + CHECK(COMPILE(ret, "NODE_OP_CDECL#nd_value", node->nd_value)); + /* cref value */ + if (popped) + ADD_INSN1(ret, node, topn, INT2FIX(1)); /* cref value cref */ + else { + ADD_INSN1(ret, node, dupn, INT2FIX(2)); /* cref value cref value */ + ADD_INSN(ret, node, swap); /* cref value value cref */ + } + ADD_INSN1(ret, node, setconstant, ID2SYM(mid)); /* cref [value] */ + ADD_LABEL(ret, lfin); /* cref [value] */ + if (!popped) ADD_INSN(ret, node, swap); /* [value] cref */ + ADD_INSN(ret, node, pop); /* [value] */ } else { - CHECK(COMPILE(ret, "NODE_OP_CDECL#nd_value", node->nd_value)); - /* cref obj value */ - ADD_CALL(ret, node, node->nd_aid, INT2FIX(1)); - /* cref value */ - ADD_INSN(ret, node, swap); /* value cref */ - if (!popped) { - ADD_INSN1(ret, node, topn, INT2FIX(1)); /* value cref value */ - ADD_INSN(ret, node, swap); /* value value cref */ - } - ADD_INSN1(ret, node, setconstant, ID2SYM(mid)); + CHECK(COMPILE(ret, "NODE_OP_CDECL#nd_value", node->nd_value)); + /* cref obj value */ + ADD_CALL(ret, node, node->nd_aid, INT2FIX(1)); + /* cref value */ + ADD_INSN(ret, node, swap); /* value cref */ + if (!popped) { + ADD_INSN1(ret, node, topn, INT2FIX(1)); /* value cref value */ + ADD_INSN(ret, node, swap); /* value value cref */ + } + ADD_INSN1(ret, node, setconstant, ID2SYM(mid)); } return COMPILE_OK; } @@ -8632,28 +8632,28 @@ compile_op_log(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, LABEL *lassign; if (type == NODE_OP_ASGN_OR && !nd_type_p(node->nd_head, NODE_IVAR)) { - LABEL *lfinish[2]; - lfinish[0] = lfin; - lfinish[1] = 0; - defined_expr(iseq, ret, node->nd_head, lfinish, Qfalse); - lassign = lfinish[1]; - if (!lassign) { - lassign = NEW_LABEL(line); - } - ADD_INSNL(ret, node, branchunless, lassign); + LABEL *lfinish[2]; + lfinish[0] = lfin; + lfinish[1] = 0; + defined_expr(iseq, ret, node->nd_head, lfinish, Qfalse); + lassign = lfinish[1]; + if (!lassign) { + lassign = NEW_LABEL(line); + } + ADD_INSNL(ret, node, branchunless, lassign); } else { - lassign = NEW_LABEL(line); + lassign = NEW_LABEL(line); } CHECK(COMPILE(ret, "NODE_OP_ASGN_AND/OR#nd_head", node->nd_head)); ADD_INSN(ret, node, dup); if (type == NODE_OP_ASGN_AND) { - ADD_INSNL(ret, node, branchunless, lfin); + ADD_INSNL(ret, node, branchunless, lfin); } else { - ADD_INSNL(ret, node, branchif, lfin); + ADD_INSNL(ret, node, branchif, lfin); } ADD_INSN(ret, node, pop); @@ -8662,8 +8662,8 @@ compile_op_log(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, ADD_LABEL(ret, lfin); if (popped) { - /* we can apply more optimize */ - ADD_INSN(ret, node, pop); + /* we can apply more optimize */ + ADD_INSN(ret, node, pop); } return COMPILE_OK; } @@ -8681,115 +8681,115 @@ compile_super(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, i INIT_ANCHOR(args); ISEQ_COMPILE_DATA(iseq)->current_block = NULL; if (type == NODE_SUPER) { - VALUE vargc = setup_args(iseq, args, node->nd_args, &flag, &keywords); - CHECK(!NIL_P(vargc)); - argc = FIX2INT(vargc); + VALUE vargc = setup_args(iseq, args, node->nd_args, &flag, &keywords); + CHECK(!NIL_P(vargc)); + argc = FIX2INT(vargc); } else { - /* NODE_ZSUPER */ - int i; - const rb_iseq_t *liseq = body->local_iseq; + /* NODE_ZSUPER */ + int i; + const rb_iseq_t *liseq = body->local_iseq; const struct rb_iseq_constant_body *const local_body = ISEQ_BODY(liseq); - const struct rb_iseq_param_keyword *const local_kwd = local_body->param.keyword; - int lvar_level = get_lvar_level(iseq); + const struct rb_iseq_param_keyword *const local_kwd = local_body->param.keyword; + int lvar_level = get_lvar_level(iseq); - argc = local_body->param.lead_num; + argc = local_body->param.lead_num; - /* normal arguments */ - for (i = 0; i < local_body->param.lead_num; i++) { - int idx = local_body->local_table_size - i; - ADD_GETLOCAL(args, node, idx, lvar_level); - } + /* normal arguments */ + for (i = 0; i < local_body->param.lead_num; i++) { + int idx = local_body->local_table_size - i; + ADD_GETLOCAL(args, node, idx, lvar_level); + } - if (local_body->param.flags.has_opt) { - /* optional arguments */ - int j; - for (j = 0; j < local_body->param.opt_num; j++) { - int idx = local_body->local_table_size - (i + j); - ADD_GETLOCAL(args, node, idx, lvar_level); - } - i += j; - argc = i; - } - if (local_body->param.flags.has_rest) { - /* rest argument */ - int idx = local_body->local_table_size - local_body->param.rest_start; - ADD_GETLOCAL(args, node, idx, lvar_level); - ADD_INSN1(args, node, splatarray, Qfalse); + if (local_body->param.flags.has_opt) { + /* optional arguments */ + int j; + for (j = 0; j < local_body->param.opt_num; j++) { + int idx = local_body->local_table_size - (i + j); + ADD_GETLOCAL(args, node, idx, lvar_level); + } + i += j; + argc = i; + } + if (local_body->param.flags.has_rest) { + /* rest argument */ + int idx = local_body->local_table_size - local_body->param.rest_start; + ADD_GETLOCAL(args, node, idx, lvar_level); + ADD_INSN1(args, node, splatarray, Qfalse); - argc = local_body->param.rest_start + 1; - flag |= VM_CALL_ARGS_SPLAT; - } - if (local_body->param.flags.has_post) { - /* post arguments */ - int post_len = local_body->param.post_num; - int post_start = local_body->param.post_start; + argc = local_body->param.rest_start + 1; + flag |= VM_CALL_ARGS_SPLAT; + } + if (local_body->param.flags.has_post) { + /* post arguments */ + int post_len = local_body->param.post_num; + int post_start = local_body->param.post_start; - if (local_body->param.flags.has_rest) { - int j; - for (j=0; jlocal_table_size - (post_start + j); - ADD_GETLOCAL(args, node, idx, lvar_level); - } - ADD_INSN1(args, node, newarray, INT2FIX(j)); - ADD_INSN (args, node, concatarray); - /* argc is settled at above */ - } - else { - int j; - for (j=0; jlocal_table_size - (post_start + j); - ADD_GETLOCAL(args, node, idx, lvar_level); - } - argc = post_len + post_start; - } - } + if (local_body->param.flags.has_rest) { + int j; + for (j=0; jlocal_table_size - (post_start + j); + ADD_GETLOCAL(args, node, idx, lvar_level); + } + ADD_INSN1(args, node, newarray, INT2FIX(j)); + ADD_INSN (args, node, concatarray); + /* argc is settled at above */ + } + else { + int j; + for (j=0; jlocal_table_size - (post_start + j); + ADD_GETLOCAL(args, node, idx, lvar_level); + } + argc = post_len + post_start; + } + } - if (local_body->param.flags.has_kw) { /* TODO: support keywords */ - int local_size = local_body->local_table_size; - argc++; + if (local_body->param.flags.has_kw) { /* TODO: support keywords */ + int local_size = local_body->local_table_size; + argc++; - ADD_INSN1(args, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE)); + ADD_INSN1(args, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE)); - if (local_body->param.flags.has_kwrest) { - int idx = local_body->local_table_size - local_kwd->rest_start; - ADD_GETLOCAL(args, node, idx, lvar_level); + if (local_body->param.flags.has_kwrest) { + int idx = local_body->local_table_size - local_kwd->rest_start; + ADD_GETLOCAL(args, node, idx, lvar_level); if (local_kwd->num > 0) { ADD_SEND (args, node, rb_intern("dup"), INT2FIX(0)); flag |= VM_CALL_KW_SPLAT_MUT; } - } - else { - ADD_INSN1(args, node, newhash, INT2FIX(0)); + } + else { + ADD_INSN1(args, node, newhash, INT2FIX(0)); flag |= VM_CALL_KW_SPLAT_MUT; - } - for (i = 0; i < local_kwd->num; ++i) { - ID id = local_kwd->table[i]; - int idx = local_size - get_local_var_idx(liseq, id); - ADD_INSN1(args, node, putobject, ID2SYM(id)); - ADD_GETLOCAL(args, node, idx, lvar_level); - } - ADD_SEND(args, node, id_core_hash_merge_ptr, INT2FIX(i * 2 + 1)); - if (local_body->param.flags.has_rest) { - ADD_INSN1(args, node, newarray, INT2FIX(1)); - ADD_INSN (args, node, concatarray); - --argc; - } + } + for (i = 0; i < local_kwd->num; ++i) { + ID id = local_kwd->table[i]; + int idx = local_size - get_local_var_idx(liseq, id); + ADD_INSN1(args, node, putobject, ID2SYM(id)); + ADD_GETLOCAL(args, node, idx, lvar_level); + } + ADD_SEND(args, node, id_core_hash_merge_ptr, INT2FIX(i * 2 + 1)); + if (local_body->param.flags.has_rest) { + ADD_INSN1(args, node, newarray, INT2FIX(1)); + ADD_INSN (args, node, concatarray); + --argc; + } flag |= VM_CALL_KW_SPLAT; - } - else if (local_body->param.flags.has_kwrest) { - int idx = local_body->local_table_size - local_kwd->rest_start; - ADD_GETLOCAL(args, node, idx, lvar_level); + } + else if (local_body->param.flags.has_kwrest) { + int idx = local_body->local_table_size - local_kwd->rest_start; + ADD_GETLOCAL(args, node, idx, lvar_level); - if (local_body->param.flags.has_rest) { - ADD_INSN1(args, node, newarray, INT2FIX(1)); - ADD_INSN (args, node, concatarray); - } - else { - argc++; - } + if (local_body->param.flags.has_rest) { + ADD_INSN1(args, node, newarray, INT2FIX(1)); + ADD_INSN (args, node, concatarray); + } + else { + argc++; + } flag |= VM_CALL_KW_SPLAT; - } + } } flag |= VM_CALL_SUPER | VM_CALL_FCALL; @@ -8797,11 +8797,11 @@ compile_super(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, i ADD_INSN(ret, node, putself); ADD_SEQ(ret, args); ADD_INSN2(ret, node, invokesuper, - new_callinfo(iseq, 0, argc, flag, keywords, parent_block != NULL), - parent_block); + new_callinfo(iseq, 0, argc, flag, keywords, parent_block != NULL), + parent_block); if (popped) { - ADD_INSN(ret, node, pop); + ADD_INSN(ret, node, pop); } return COMPILE_OK; } @@ -8820,24 +8820,24 @@ compile_yield(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, i case ISEQ_TYPE_TOP: case ISEQ_TYPE_MAIN: case ISEQ_TYPE_CLASS: - COMPILE_ERROR(ERROR_ARGS "Invalid yield"); - return COMPILE_NG; + COMPILE_ERROR(ERROR_ARGS "Invalid yield"); + return COMPILE_NG; default: /* valid */; } if (node->nd_head) { - argc = setup_args(iseq, args, node->nd_head, &flag, &keywords); - CHECK(!NIL_P(argc)); + argc = setup_args(iseq, args, node->nd_head, &flag, &keywords); + CHECK(!NIL_P(argc)); } else { - argc = INT2FIX(0); + argc = INT2FIX(0); } ADD_SEQ(ret, args); ADD_INSN1(ret, node, invokeblock, new_callinfo(iseq, 0, FIX2INT(argc), flag, keywords, FALSE)); if (popped) { - ADD_INSN(ret, node, pop); + ADD_INSN(ret, node, pop); } int level = 0; @@ -8860,18 +8860,18 @@ compile_match(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, i INIT_ANCHOR(val); switch ((int)type) { case NODE_MATCH: - ADD_INSN1(recv, node, putobject, node->nd_lit); - ADD_INSN2(val, node, getspecial, INT2FIX(0), - INT2FIX(0)); - break; + ADD_INSN1(recv, node, putobject, node->nd_lit); + ADD_INSN2(val, node, getspecial, INT2FIX(0), + INT2FIX(0)); + break; case NODE_MATCH2: - CHECK(COMPILE(recv, "receiver", node->nd_recv)); - CHECK(COMPILE(val, "value", node->nd_value)); - break; + CHECK(COMPILE(recv, "receiver", node->nd_recv)); + CHECK(COMPILE(val, "value", node->nd_value)); + break; case NODE_MATCH3: - CHECK(COMPILE(recv, "receiver", node->nd_value)); - CHECK(COMPILE(val, "value", node->nd_recv)); - break; + CHECK(COMPILE(recv, "receiver", node->nd_value)); + CHECK(COMPILE(val, "value", node->nd_recv)); + break; } ADD_SEQ(ret, recv); @@ -8879,11 +8879,11 @@ compile_match(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, i ADD_SEND(ret, node, idEqTilde, INT2FIX(1)); if (node->nd_args) { - compile_named_capture_assign(iseq, ret, node->nd_args); + compile_named_capture_assign(iseq, ret, node->nd_args); } if (popped) { - ADD_INSN(ret, node, pop); + ADD_INSN(ret, node, pop); } return COMPILE_OK; } @@ -8893,44 +8893,44 @@ compile_colon2(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, { const int line = nd_line(node); if (rb_is_const_id(node->nd_mid)) { - /* constant */ - LABEL *lend = NEW_LABEL(line); + /* constant */ + LABEL *lend = NEW_LABEL(line); int ic_index = ISEQ_BODY(iseq)->ic_size++; - DECL_ANCHOR(pref); - DECL_ANCHOR(body); + DECL_ANCHOR(pref); + DECL_ANCHOR(body); - INIT_ANCHOR(pref); - INIT_ANCHOR(body); - CHECK(compile_const_prefix(iseq, node, pref, body)); - if (LIST_INSN_SIZE_ZERO(pref)) { - if (ISEQ_COMPILE_DATA(iseq)->option->inline_const_cache) { - ADD_INSN2(ret, node, opt_getinlinecache, lend, INT2FIX(ic_index)); - } - else { - ADD_INSN(ret, node, putnil); - } + INIT_ANCHOR(pref); + INIT_ANCHOR(body); + CHECK(compile_const_prefix(iseq, node, pref, body)); + if (LIST_INSN_SIZE_ZERO(pref)) { + if (ISEQ_COMPILE_DATA(iseq)->option->inline_const_cache) { + ADD_INSN2(ret, node, opt_getinlinecache, lend, INT2FIX(ic_index)); + } + else { + ADD_INSN(ret, node, putnil); + } - ADD_SEQ(ret, body); + ADD_SEQ(ret, body); - if (ISEQ_COMPILE_DATA(iseq)->option->inline_const_cache) { - ADD_INSN1(ret, node, opt_setinlinecache, INT2FIX(ic_index)); - ADD_LABEL(ret, lend); - } - } - else { - ADD_SEQ(ret, pref); - ADD_SEQ(ret, body); - } + if (ISEQ_COMPILE_DATA(iseq)->option->inline_const_cache) { + ADD_INSN1(ret, node, opt_setinlinecache, INT2FIX(ic_index)); + ADD_LABEL(ret, lend); + } + } + else { + ADD_SEQ(ret, pref); + ADD_SEQ(ret, body); + } } else { - /* function call */ - ADD_CALL_RECEIVER(ret, node); - CHECK(COMPILE(ret, "colon2#nd_head", node->nd_head)); - ADD_CALL(ret, node, node->nd_mid, INT2FIX(1)); + /* function call */ + ADD_CALL_RECEIVER(ret, node); + CHECK(COMPILE(ret, "colon2#nd_head", node->nd_head)); + ADD_CALL(ret, node, node->nd_mid, INT2FIX(1)); } if (popped) { - ADD_INSN(ret, node, pop); + ADD_INSN(ret, node, pop); } return COMPILE_OK; } @@ -8946,8 +8946,8 @@ compile_colon3(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, /* add cache insn */ if (ISEQ_COMPILE_DATA(iseq)->option->inline_const_cache) { - ADD_INSN2(ret, node, opt_getinlinecache, lend, INT2FIX(ic_index)); - ADD_INSN(ret, node, pop); + ADD_INSN2(ret, node, opt_getinlinecache, lend, INT2FIX(ic_index)); + ADD_INSN(ret, node, pop); } ADD_INSN1(ret, node, putobject, rb_cObject); @@ -8955,12 +8955,12 @@ compile_colon3(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, ADD_INSN1(ret, node, getconstant, ID2SYM(node->nd_mid)); if (ISEQ_COMPILE_DATA(iseq)->option->inline_const_cache) { - ADD_INSN1(ret, node, opt_setinlinecache, INT2FIX(ic_index)); - ADD_LABEL(ret, lend); + ADD_INSN1(ret, node, opt_setinlinecache, INT2FIX(ic_index)); + ADD_LABEL(ret, lend); } if (popped) { - ADD_INSN(ret, node, pop); + ADD_INSN(ret, node, pop); } return COMPILE_OK; } @@ -8973,20 +8973,20 @@ compile_dots(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, in const NODE *e = node->nd_end; if (optimizable_range_item_p(b) && optimizable_range_item_p(e)) { - if (!popped) { + if (!popped) { VALUE bv = nd_type_p(b, NODE_LIT) ? b->nd_lit : Qnil; VALUE ev = nd_type_p(e, NODE_LIT) ? e->nd_lit : Qnil; - VALUE val = rb_range_new(bv, ev, excl); - ADD_INSN1(ret, node, putobject, val); - RB_OBJ_WRITTEN(iseq, Qundef, val); - } + VALUE val = rb_range_new(bv, ev, excl); + ADD_INSN1(ret, node, putobject, val); + RB_OBJ_WRITTEN(iseq, Qundef, val); + } } else { - CHECK(COMPILE_(ret, "min", b, popped)); - CHECK(COMPILE_(ret, "max", e, popped)); - if (!popped) { - ADD_INSN1(ret, node, newrange, flag); - } + CHECK(COMPILE_(ret, "min", b, popped)); + CHECK(COMPILE_(ret, "max", e, popped)); + if (!popped) { + ADD_INSN1(ret, node, newrange, flag); + } } return COMPILE_OK; } @@ -8996,25 +8996,25 @@ compile_errinfo(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, { if (!popped) { if (ISEQ_BODY(iseq)->type == ISEQ_TYPE_RESCUE) { - ADD_GETLOCAL(ret, node, LVAR_ERRINFO, 0); - } - else { - const rb_iseq_t *ip = iseq; - int level = 0; - while (ip) { + ADD_GETLOCAL(ret, node, LVAR_ERRINFO, 0); + } + else { + const rb_iseq_t *ip = iseq; + int level = 0; + while (ip) { if (ISEQ_BODY(ip)->type == ISEQ_TYPE_RESCUE) { - break; - } + break; + } ip = ISEQ_BODY(ip)->parent_iseq; - level++; - } - if (ip) { - ADD_GETLOCAL(ret, node, LVAR_ERRINFO, level); - } - else { - ADD_INSN(ret, node, putnil); - } - } + level++; + } + if (ip) { + ADD_GETLOCAL(ret, node, LVAR_ERRINFO, level); + } + else { + ADD_INSN(ret, node, putnil); + } + } } return COMPILE_OK; } @@ -9027,29 +9027,29 @@ compile_kw_arg(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, const NODE *default_value = node->nd_body->nd_value; if (default_value == NODE_SPECIAL_REQUIRED_KEYWORD) { - /* required argument. do nothing */ - COMPILE_ERROR(ERROR_ARGS "unreachable"); - return COMPILE_NG; + /* required argument. do nothing */ + COMPILE_ERROR(ERROR_ARGS "unreachable"); + return COMPILE_NG; } else if (nd_type_p(default_value, NODE_LIT) || - nd_type_p(default_value, NODE_NIL) || - nd_type_p(default_value, NODE_TRUE) || - nd_type_p(default_value, NODE_FALSE)) { - COMPILE_ERROR(ERROR_ARGS "unreachable"); - return COMPILE_NG; + nd_type_p(default_value, NODE_NIL) || + nd_type_p(default_value, NODE_TRUE) || + nd_type_p(default_value, NODE_FALSE)) { + COMPILE_ERROR(ERROR_ARGS "unreachable"); + return COMPILE_NG; } else { - /* if keywordcheck(_kw_bits, nth_keyword) - * kw = default_value - * end - */ - int kw_bits_idx = body->local_table_size - body->param.keyword->bits_start; - int keyword_idx = body->param.keyword->num; + /* if keywordcheck(_kw_bits, nth_keyword) + * kw = default_value + * end + */ + int kw_bits_idx = body->local_table_size - body->param.keyword->bits_start; + int keyword_idx = body->param.keyword->num; - ADD_INSN2(ret, node, checkkeyword, INT2FIX(kw_bits_idx + VM_ENV_DATA_SIZE - 1), INT2FIX(keyword_idx)); - ADD_INSNL(ret, node, branchif, end_label); - CHECK(COMPILE_POPPED(ret, "keyword default argument", node->nd_body)); - ADD_LABEL(ret, end_label); + ADD_INSN2(ret, node, checkkeyword, INT2FIX(kw_bits_idx + VM_ENV_DATA_SIZE - 1), INT2FIX(keyword_idx)); + ADD_INSNL(ret, node, branchif, end_label); + CHECK(COMPILE_POPPED(ret, "keyword default argument", node->nd_body)); + ADD_LABEL(ret, end_label); } return COMPILE_OK; } @@ -9069,24 +9069,24 @@ compile_attrasgn(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node * obj["literal"] = value -> opt_aset_with(obj, "literal", value) */ if (mid == idASET && !private_recv_p(node) && node->nd_args && - nd_type_p(node->nd_args, NODE_LIST) && node->nd_args->nd_alen == 2 && - nd_type_p(node->nd_args->nd_head, NODE_STR) && - ISEQ_COMPILE_DATA(iseq)->current_block == NULL && - !ISEQ_COMPILE_DATA(iseq)->option->frozen_string_literal && - ISEQ_COMPILE_DATA(iseq)->option->specialized_instruction) + nd_type_p(node->nd_args, NODE_LIST) && node->nd_args->nd_alen == 2 && + nd_type_p(node->nd_args->nd_head, NODE_STR) && + ISEQ_COMPILE_DATA(iseq)->current_block == NULL && + !ISEQ_COMPILE_DATA(iseq)->option->frozen_string_literal && + ISEQ_COMPILE_DATA(iseq)->option->specialized_instruction) { - VALUE str = rb_fstring(node->nd_args->nd_head->nd_lit); - CHECK(COMPILE(ret, "recv", node->nd_recv)); - CHECK(COMPILE(ret, "value", node->nd_args->nd_next->nd_head)); - if (!popped) { - ADD_INSN(ret, node, swap); - ADD_INSN1(ret, node, topn, INT2FIX(1)); - } - ADD_INSN2(ret, node, opt_aset_with, str, - new_callinfo(iseq, idASET, 2, 0, NULL, FALSE)); - RB_OBJ_WRITTEN(iseq, Qundef, str); - ADD_INSN(ret, node, pop); - return COMPILE_OK; + VALUE str = rb_fstring(node->nd_args->nd_head->nd_lit); + CHECK(COMPILE(ret, "recv", node->nd_recv)); + CHECK(COMPILE(ret, "value", node->nd_args->nd_next->nd_head)); + if (!popped) { + ADD_INSN(ret, node, swap); + ADD_INSN1(ret, node, topn, INT2FIX(1)); + } + ADD_INSN2(ret, node, opt_aset_with, str, + new_callinfo(iseq, idASET, 2, 0, NULL, FALSE)); + RB_OBJ_WRITTEN(iseq, Qundef, str); + ADD_INSN(ret, node, pop); + return COMPILE_OK; } INIT_ANCHOR(recv); @@ -9102,38 +9102,38 @@ compile_attrasgn(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node debugp_param("nd_mid", ID2SYM(mid)); if (!rb_is_attrset_id(mid)) { - /* safe nav attr */ - mid = rb_id_attrset(mid); - else_label = qcall_branch_start(iseq, recv, &branches, node, node); + /* safe nav attr */ + mid = rb_id_attrset(mid); + else_label = qcall_branch_start(iseq, recv, &branches, node, node); } if (!popped) { - ADD_INSN(ret, node, putnil); - ADD_SEQ(ret, recv); - ADD_SEQ(ret, args); + ADD_INSN(ret, node, putnil); + ADD_SEQ(ret, recv); + ADD_SEQ(ret, args); - if (flag & VM_CALL_ARGS_BLOCKARG) { - ADD_INSN1(ret, node, topn, INT2FIX(1)); - if (flag & VM_CALL_ARGS_SPLAT) { - ADD_INSN1(ret, node, putobject, INT2FIX(-1)); - ADD_SEND_WITH_FLAG(ret, node, idAREF, INT2FIX(1), INT2FIX(asgnflag)); - } - ADD_INSN1(ret, node, setn, FIXNUM_INC(argc, 3)); - ADD_INSN (ret, node, pop); - } - else if (flag & VM_CALL_ARGS_SPLAT) { - ADD_INSN(ret, node, dup); - ADD_INSN1(ret, node, putobject, INT2FIX(-1)); - ADD_SEND_WITH_FLAG(ret, node, idAREF, INT2FIX(1), INT2FIX(asgnflag)); - ADD_INSN1(ret, node, setn, FIXNUM_INC(argc, 2)); - ADD_INSN (ret, node, pop); - } - else { - ADD_INSN1(ret, node, setn, FIXNUM_INC(argc, 1)); - } + if (flag & VM_CALL_ARGS_BLOCKARG) { + ADD_INSN1(ret, node, topn, INT2FIX(1)); + if (flag & VM_CALL_ARGS_SPLAT) { + ADD_INSN1(ret, node, putobject, INT2FIX(-1)); + ADD_SEND_WITH_FLAG(ret, node, idAREF, INT2FIX(1), INT2FIX(asgnflag)); + } + ADD_INSN1(ret, node, setn, FIXNUM_INC(argc, 3)); + ADD_INSN (ret, node, pop); + } + else if (flag & VM_CALL_ARGS_SPLAT) { + ADD_INSN(ret, node, dup); + ADD_INSN1(ret, node, putobject, INT2FIX(-1)); + ADD_SEND_WITH_FLAG(ret, node, idAREF, INT2FIX(1), INT2FIX(asgnflag)); + ADD_INSN1(ret, node, setn, FIXNUM_INC(argc, 2)); + ADD_INSN (ret, node, pop); + } + else { + ADD_INSN1(ret, node, setn, FIXNUM_INC(argc, 1)); + } } else { - ADD_SEQ(ret, recv); - ADD_SEQ(ret, args); + ADD_SEQ(ret, recv); + ADD_SEQ(ret, args); } ADD_SEND_WITH_FLAG(ret, node, mid, argc, INT2FIX(flag)); qcall_branch_end(iseq, ret, else_label, branches, node, node); @@ -9173,17 +9173,17 @@ iseq_compile_each0(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const no struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq); if (ISEQ_COMPILE_DATA(iseq)->last_line == line) { - /* ignore */ + /* ignore */ } else { - if (node->flags & NODE_FL_NEWLINE) { - int event = RUBY_EVENT_LINE; - ISEQ_COMPILE_DATA(iseq)->last_line = line; - if (ISEQ_COVERAGE(iseq) && ISEQ_LINE_COVERAGE(iseq)) { - event |= RUBY_EVENT_COVERAGE_LINE; - } - ADD_TRACE(ret, event); - } + if (node->flags & NODE_FL_NEWLINE) { + int event = RUBY_EVENT_LINE; + ISEQ_COMPILE_DATA(iseq)->last_line = line; + if (ISEQ_COVERAGE(iseq) && ISEQ_LINE_COVERAGE(iseq)) { + event |= RUBY_EVENT_COVERAGE_LINE; + } + ADD_TRACE(ret, event); + } } debug_node_start(node); @@ -9193,134 +9193,134 @@ iseq_compile_each0(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const no switch (type) { case NODE_BLOCK: CHECK(compile_block(iseq, ret, node, popped)); - break; + break; case NODE_IF: case NODE_UNLESS: - CHECK(compile_if(iseq, ret, node, popped, type)); - break; + CHECK(compile_if(iseq, ret, node, popped, type)); + break; case NODE_CASE: - CHECK(compile_case(iseq, ret, node, popped)); - break; + CHECK(compile_case(iseq, ret, node, popped)); + break; case NODE_CASE2: - CHECK(compile_case2(iseq, ret, node, popped)); - break; + CHECK(compile_case2(iseq, ret, node, popped)); + break; case NODE_CASE3: CHECK(compile_case3(iseq, ret, node, popped)); break; case NODE_WHILE: case NODE_UNTIL: - CHECK(compile_loop(iseq, ret, node, popped, type)); - break; + CHECK(compile_loop(iseq, ret, node, popped, type)); + break; case NODE_FOR: case NODE_ITER: - CHECK(compile_iter(iseq, ret, node, popped)); - break; + CHECK(compile_iter(iseq, ret, node, popped)); + break; case NODE_FOR_MASGN: - CHECK(compile_for_masgn(iseq, ret, node, popped)); - break; + CHECK(compile_for_masgn(iseq, ret, node, popped)); + break; case NODE_BREAK: - CHECK(compile_break(iseq, ret, node, popped)); - break; + CHECK(compile_break(iseq, ret, node, popped)); + break; case NODE_NEXT: - CHECK(compile_next(iseq, ret, node, popped)); - break; + CHECK(compile_next(iseq, ret, node, popped)); + break; case NODE_REDO: - CHECK(compile_redo(iseq, ret, node, popped)); - break; + CHECK(compile_redo(iseq, ret, node, popped)); + break; case NODE_RETRY: - CHECK(compile_retry(iseq, ret, node, popped)); - break; + CHECK(compile_retry(iseq, ret, node, popped)); + break; case NODE_BEGIN:{ - CHECK(COMPILE_(ret, "NODE_BEGIN", node->nd_body, popped)); - break; + CHECK(COMPILE_(ret, "NODE_BEGIN", node->nd_body, popped)); + break; } case NODE_RESCUE: - CHECK(compile_rescue(iseq, ret, node, popped)); - break; + CHECK(compile_rescue(iseq, ret, node, popped)); + break; case NODE_RESBODY: - CHECK(compile_resbody(iseq, ret, node, popped)); - break; + CHECK(compile_resbody(iseq, ret, node, popped)); + break; case NODE_ENSURE: - CHECK(compile_ensure(iseq, ret, node, popped)); - break; + CHECK(compile_ensure(iseq, ret, node, popped)); + break; case NODE_AND: case NODE_OR:{ - LABEL *end_label = NEW_LABEL(line); - CHECK(COMPILE(ret, "nd_1st", node->nd_1st)); - if (!popped) { - ADD_INSN(ret, node, dup); - } - if (type == NODE_AND) { - ADD_INSNL(ret, node, branchunless, end_label); - } - else { - ADD_INSNL(ret, node, branchif, end_label); - } - if (!popped) { - ADD_INSN(ret, node, pop); - } - CHECK(COMPILE_(ret, "nd_2nd", node->nd_2nd, popped)); - ADD_LABEL(ret, end_label); - break; + LABEL *end_label = NEW_LABEL(line); + CHECK(COMPILE(ret, "nd_1st", node->nd_1st)); + if (!popped) { + ADD_INSN(ret, node, dup); + } + if (type == NODE_AND) { + ADD_INSNL(ret, node, branchunless, end_label); + } + else { + ADD_INSNL(ret, node, branchif, end_label); + } + if (!popped) { + ADD_INSN(ret, node, pop); + } + CHECK(COMPILE_(ret, "nd_2nd", node->nd_2nd, popped)); + ADD_LABEL(ret, end_label); + break; } case NODE_MASGN:{ - compile_massign(iseq, ret, node, popped); - break; + compile_massign(iseq, ret, node, popped); + break; } case NODE_LASGN:{ - ID id = node->nd_vid; + ID id = node->nd_vid; int idx = ISEQ_BODY(body->local_iseq)->local_table_size - get_local_var_idx(iseq, id); - debugs("lvar: %s idx: %d\n", rb_id2name(id), idx); - CHECK(COMPILE(ret, "rvalue", node->nd_value)); + debugs("lvar: %s idx: %d\n", rb_id2name(id), idx); + CHECK(COMPILE(ret, "rvalue", node->nd_value)); - if (!popped) { - ADD_INSN(ret, node, dup); - } - ADD_SETLOCAL(ret, node, idx, get_lvar_level(iseq)); - break; + if (!popped) { + ADD_INSN(ret, node, dup); + } + ADD_SETLOCAL(ret, node, idx, get_lvar_level(iseq)); + break; } case NODE_DASGN: { - int idx, lv, ls; - ID id = node->nd_vid; - CHECK(COMPILE(ret, "dvalue", node->nd_value)); - debugi("dassn id", rb_id2str(id) ? id : '*'); + int idx, lv, ls; + ID id = node->nd_vid; + CHECK(COMPILE(ret, "dvalue", node->nd_value)); + debugi("dassn id", rb_id2str(id) ? id : '*'); - if (!popped) { - ADD_INSN(ret, node, dup); - } + if (!popped) { + ADD_INSN(ret, node, dup); + } - idx = get_dyna_var_idx(iseq, id, &lv, &ls); + idx = get_dyna_var_idx(iseq, id, &lv, &ls); - if (idx < 0) { - COMPILE_ERROR(ERROR_ARGS "NODE_DASGN: unknown id (%"PRIsVALUE")", - rb_id2str(id)); - goto ng; - } - ADD_SETLOCAL(ret, node, ls - idx, lv); - break; + if (idx < 0) { + COMPILE_ERROR(ERROR_ARGS "NODE_DASGN: unknown id (%"PRIsVALUE")", + rb_id2str(id)); + goto ng; + } + ADD_SETLOCAL(ret, node, ls - idx, lv); + break; } case NODE_GASGN:{ - CHECK(COMPILE(ret, "lvalue", node->nd_value)); + CHECK(COMPILE(ret, "lvalue", node->nd_value)); - if (!popped) { - ADD_INSN(ret, node, dup); - } - ADD_INSN1(ret, node, setglobal, ID2SYM(node->nd_entry)); - break; + if (!popped) { + ADD_INSN(ret, node, dup); + } + ADD_INSN1(ret, node, setglobal, ID2SYM(node->nd_entry)); + break; } case NODE_IASGN:{ - CHECK(COMPILE(ret, "lvalue", node->nd_value)); - if (!popped) { - ADD_INSN(ret, node, dup); - } - ADD_INSN2(ret, node, setinstancevariable, - ID2SYM(node->nd_vid), - get_ivar_ic_value(iseq,node->nd_vid)); - break; + CHECK(COMPILE(ret, "lvalue", node->nd_value)); + if (!popped) { + ADD_INSN(ret, node, dup); + } + ADD_INSN2(ret, node, setinstancevariable, + ID2SYM(node->nd_vid), + get_ivar_ic_value(iseq,node->nd_vid)); + break; } case NODE_CDECL:{ if (node->nd_vid) { @@ -9330,12 +9330,12 @@ iseq_compile_each0(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const no ADD_INSN(ret, node, dup); } - ADD_INSN1(ret, node, putspecialobject, - INT2FIX(VM_SPECIAL_OBJECT_CONST_BASE)); + ADD_INSN1(ret, node, putspecialobject, + INT2FIX(VM_SPECIAL_OBJECT_CONST_BASE)); ADD_INSN1(ret, node, setconstant, ID2SYM(node->nd_vid)); - } - else { - compile_cpath(ret, iseq, node->nd_else); + } + else { + compile_cpath(ret, iseq, node->nd_else); CHECK(COMPILE(ret, "lvalue", node->nd_value)); ADD_INSN(ret, node, swap); @@ -9345,32 +9345,32 @@ iseq_compile_each0(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const no } ADD_INSN1(ret, node, setconstant, ID2SYM(node->nd_else->nd_mid)); - } - break; + } + break; } case NODE_CVASGN:{ - CHECK(COMPILE(ret, "cvasgn val", node->nd_value)); - if (!popped) { - ADD_INSN(ret, node, dup); - } + CHECK(COMPILE(ret, "cvasgn val", node->nd_value)); + if (!popped) { + ADD_INSN(ret, node, dup); + } ADD_INSN2(ret, node, setclassvariable, ID2SYM(node->nd_vid), get_cvar_ic_value(iseq,node->nd_vid)); - break; + break; } case NODE_OP_ASGN1: - CHECK(compile_op_asgn1(iseq, ret, node, popped)); - break; + CHECK(compile_op_asgn1(iseq, ret, node, popped)); + break; case NODE_OP_ASGN2: - CHECK(compile_op_asgn2(iseq, ret, node, popped)); - break; + CHECK(compile_op_asgn2(iseq, ret, node, popped)); + break; case NODE_OP_CDECL: - CHECK(compile_op_cdecl(iseq, ret, node, popped)); - break; + CHECK(compile_op_cdecl(iseq, ret, node, popped)); + break; case NODE_OP_ASGN_AND: case NODE_OP_ASGN_OR: - CHECK(compile_op_log(iseq, ret, node, popped, type)); - break; + CHECK(compile_op_log(iseq, ret, node, popped, type)); + break; case NODE_CALL: /* obj.foo */ case NODE_OPCALL: /* foo[] */ if (compile_call_precheck_freeze(iseq, ret, node, node, popped) == TRUE) { @@ -9385,271 +9385,271 @@ iseq_compile_each0(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const no break; case NODE_SUPER: case NODE_ZSUPER: - CHECK(compile_super(iseq, ret, node, popped, type)); - break; + CHECK(compile_super(iseq, ret, node, popped, type)); + break; case NODE_LIST:{ CHECK(compile_array(iseq, ret, node, popped) >= 0); - break; + break; } case NODE_ZLIST:{ - if (!popped) { - ADD_INSN1(ret, node, newarray, INT2FIX(0)); - } - break; + if (!popped) { + ADD_INSN1(ret, node, newarray, INT2FIX(0)); + } + break; } case NODE_VALUES:{ - const NODE *n = node; - if (popped) { - COMPILE_ERROR(ERROR_ARGS "NODE_VALUES: must not be popped"); - } - while (n) { - CHECK(COMPILE(ret, "values item", n->nd_head)); - n = n->nd_next; - } - ADD_INSN1(ret, node, newarray, INT2FIX(node->nd_alen)); - break; + const NODE *n = node; + if (popped) { + COMPILE_ERROR(ERROR_ARGS "NODE_VALUES: must not be popped"); + } + while (n) { + CHECK(COMPILE(ret, "values item", n->nd_head)); + n = n->nd_next; + } + ADD_INSN1(ret, node, newarray, INT2FIX(node->nd_alen)); + break; } case NODE_HASH: CHECK(compile_hash(iseq, ret, node, FALSE, popped) >= 0); break; case NODE_RETURN: - CHECK(compile_return(iseq, ret, node, popped)); - break; + CHECK(compile_return(iseq, ret, node, popped)); + break; case NODE_YIELD: - CHECK(compile_yield(iseq, ret, node, popped)); - break; + CHECK(compile_yield(iseq, ret, node, popped)); + break; case NODE_LVAR:{ - if (!popped) { - compile_lvar(iseq, ret, node, node->nd_vid); - } - break; + if (!popped) { + compile_lvar(iseq, ret, node, node->nd_vid); + } + break; } case NODE_DVAR:{ - int lv, idx, ls; - debugi("nd_vid", node->nd_vid); - if (!popped) { - idx = get_dyna_var_idx(iseq, node->nd_vid, &lv, &ls); - if (idx < 0) { - COMPILE_ERROR(ERROR_ARGS "unknown dvar (%"PRIsVALUE")", - rb_id2str(node->nd_vid)); - goto ng; - } - ADD_GETLOCAL(ret, node, ls - idx, lv); - } - break; + int lv, idx, ls; + debugi("nd_vid", node->nd_vid); + if (!popped) { + idx = get_dyna_var_idx(iseq, node->nd_vid, &lv, &ls); + if (idx < 0) { + COMPILE_ERROR(ERROR_ARGS "unknown dvar (%"PRIsVALUE")", + rb_id2str(node->nd_vid)); + goto ng; + } + ADD_GETLOCAL(ret, node, ls - idx, lv); + } + break; } case NODE_GVAR:{ - ADD_INSN1(ret, node, getglobal, ID2SYM(node->nd_entry)); - if (popped) { - ADD_INSN(ret, node, pop); - } - break; + ADD_INSN1(ret, node, getglobal, ID2SYM(node->nd_entry)); + if (popped) { + ADD_INSN(ret, node, pop); + } + break; } case NODE_IVAR:{ - debugi("nd_vid", node->nd_vid); - if (!popped) { - ADD_INSN2(ret, node, getinstancevariable, - ID2SYM(node->nd_vid), - get_ivar_ic_value(iseq,node->nd_vid)); - } - break; + debugi("nd_vid", node->nd_vid); + if (!popped) { + ADD_INSN2(ret, node, getinstancevariable, + ID2SYM(node->nd_vid), + get_ivar_ic_value(iseq,node->nd_vid)); + } + break; } case NODE_CONST:{ - debugi("nd_vid", node->nd_vid); + debugi("nd_vid", node->nd_vid); - if (ISEQ_COMPILE_DATA(iseq)->option->inline_const_cache) { - LABEL *lend = NEW_LABEL(line); - int ic_index = body->ic_size++; + if (ISEQ_COMPILE_DATA(iseq)->option->inline_const_cache) { + LABEL *lend = NEW_LABEL(line); + int ic_index = body->ic_size++; ADD_INSN2(ret, node, opt_getinlinecache, lend, INT2FIX(ic_index)); ADD_INSN1(ret, node, putobject, Qtrue); ADD_INSN1(ret, node, getconstant, ID2SYM(node->nd_vid)); ADD_INSN1(ret, node, opt_setinlinecache, INT2FIX(ic_index)); - ADD_LABEL(ret, lend); - } - else { - ADD_INSN(ret, node, putnil); + ADD_LABEL(ret, lend); + } + else { + ADD_INSN(ret, node, putnil); ADD_INSN1(ret, node, putobject, Qtrue); ADD_INSN1(ret, node, getconstant, ID2SYM(node->nd_vid)); - } + } - if (popped) { - ADD_INSN(ret, node, pop); - } - break; + if (popped) { + ADD_INSN(ret, node, pop); + } + break; } case NODE_CVAR:{ - if (!popped) { - ADD_INSN2(ret, node, getclassvariable, - ID2SYM(node->nd_vid), - get_cvar_ic_value(iseq,node->nd_vid)); - } - break; + if (!popped) { + ADD_INSN2(ret, node, getclassvariable, + ID2SYM(node->nd_vid), + get_cvar_ic_value(iseq,node->nd_vid)); + } + break; } case NODE_NTH_REF:{ if (!popped) { - if (!node->nd_nth) { - ADD_INSN(ret, node, putnil); - break; - } - ADD_INSN2(ret, node, getspecial, INT2FIX(1) /* '~' */, - INT2FIX(node->nd_nth << 1)); - } - break; + if (!node->nd_nth) { + ADD_INSN(ret, node, putnil); + break; + } + ADD_INSN2(ret, node, getspecial, INT2FIX(1) /* '~' */, + INT2FIX(node->nd_nth << 1)); + } + break; } case NODE_BACK_REF:{ - if (!popped) { - ADD_INSN2(ret, node, getspecial, INT2FIX(1) /* '~' */, - INT2FIX(0x01 | (node->nd_nth << 1))); - } - break; + if (!popped) { + ADD_INSN2(ret, node, getspecial, INT2FIX(1) /* '~' */, + INT2FIX(0x01 | (node->nd_nth << 1))); + } + break; } case NODE_MATCH: case NODE_MATCH2: case NODE_MATCH3: - CHECK(compile_match(iseq, ret, node, popped, type)); - break; + CHECK(compile_match(iseq, ret, node, popped, type)); + break; case NODE_LIT:{ - debugp_param("lit", node->nd_lit); - if (!popped) { - ADD_INSN1(ret, node, putobject, node->nd_lit); + debugp_param("lit", node->nd_lit); + if (!popped) { + ADD_INSN1(ret, node, putobject, node->nd_lit); RB_OBJ_WRITTEN(iseq, Qundef, node->nd_lit); - } - break; + } + break; } case NODE_STR:{ - debugp_param("nd_lit", node->nd_lit); - if (!popped) { - VALUE lit = node->nd_lit; - if (!ISEQ_COMPILE_DATA(iseq)->option->frozen_string_literal) { - lit = rb_fstring(lit); - ADD_INSN1(ret, node, putstring, lit); + debugp_param("nd_lit", node->nd_lit); + if (!popped) { + VALUE lit = node->nd_lit; + if (!ISEQ_COMPILE_DATA(iseq)->option->frozen_string_literal) { + lit = rb_fstring(lit); + ADD_INSN1(ret, node, putstring, lit); RB_OBJ_WRITTEN(iseq, Qundef, lit); - } - else { - if (ISEQ_COMPILE_DATA(iseq)->option->debug_frozen_string_literal || RTEST(ruby_debug)) { - VALUE debug_info = rb_ary_new_from_args(2, rb_iseq_path(iseq), INT2FIX(line)); - lit = rb_str_dup(lit); - rb_ivar_set(lit, id_debug_created_info, rb_obj_freeze(debug_info)); - lit = rb_str_freeze(lit); - } - else { - lit = rb_fstring(lit); - } - ADD_INSN1(ret, node, putobject, lit); + } + else { + if (ISEQ_COMPILE_DATA(iseq)->option->debug_frozen_string_literal || RTEST(ruby_debug)) { + VALUE debug_info = rb_ary_new_from_args(2, rb_iseq_path(iseq), INT2FIX(line)); + lit = rb_str_dup(lit); + rb_ivar_set(lit, id_debug_created_info, rb_obj_freeze(debug_info)); + lit = rb_str_freeze(lit); + } + else { + lit = rb_fstring(lit); + } + ADD_INSN1(ret, node, putobject, lit); RB_OBJ_WRITTEN(iseq, Qundef, lit); - } - } - break; + } + } + break; } case NODE_DSTR:{ - compile_dstr(iseq, ret, node); + compile_dstr(iseq, ret, node); - if (popped) { - ADD_INSN(ret, node, pop); - } - break; + if (popped) { + ADD_INSN(ret, node, pop); + } + break; } case NODE_XSTR:{ - ADD_CALL_RECEIVER(ret, node); + ADD_CALL_RECEIVER(ret, node); VALUE str = rb_fstring(node->nd_lit); - ADD_INSN1(ret, node, putobject, str); + ADD_INSN1(ret, node, putobject, str); RB_OBJ_WRITTEN(iseq, Qundef, str); - ADD_CALL(ret, node, idBackquote, INT2FIX(1)); + ADD_CALL(ret, node, idBackquote, INT2FIX(1)); - if (popped) { - ADD_INSN(ret, node, pop); - } - break; + if (popped) { + ADD_INSN(ret, node, pop); + } + break; } case NODE_DXSTR:{ - ADD_CALL_RECEIVER(ret, node); - compile_dstr(iseq, ret, node); - ADD_CALL(ret, node, idBackquote, INT2FIX(1)); + ADD_CALL_RECEIVER(ret, node); + compile_dstr(iseq, ret, node); + ADD_CALL(ret, node, idBackquote, INT2FIX(1)); - if (popped) { - ADD_INSN(ret, node, pop); - } - break; + if (popped) { + ADD_INSN(ret, node, pop); + } + break; } case NODE_EVSTR: - CHECK(compile_evstr(iseq, ret, node->nd_body, popped)); - break; + CHECK(compile_evstr(iseq, ret, node->nd_body, popped)); + break; case NODE_DREGX:{ - compile_dregx(iseq, ret, node); + compile_dregx(iseq, ret, node); - if (popped) { - ADD_INSN(ret, node, pop); - } - break; + if (popped) { + ADD_INSN(ret, node, pop); + } + break; } case NODE_ONCE:{ - int ic_index = body->ise_size++; - const rb_iseq_t *block_iseq; - block_iseq = NEW_CHILD_ISEQ(node->nd_body, make_name_for_block(iseq), ISEQ_TYPE_PLAIN, line); + int ic_index = body->ise_size++; + const rb_iseq_t *block_iseq; + block_iseq = NEW_CHILD_ISEQ(node->nd_body, make_name_for_block(iseq), ISEQ_TYPE_PLAIN, line); - ADD_INSN2(ret, node, once, block_iseq, INT2FIX(ic_index)); + ADD_INSN2(ret, node, once, block_iseq, INT2FIX(ic_index)); RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)block_iseq); - if (popped) { - ADD_INSN(ret, node, pop); - } - break; + if (popped) { + ADD_INSN(ret, node, pop); + } + break; } case NODE_ARGSCAT:{ - if (popped) { - CHECK(COMPILE(ret, "argscat head", node->nd_head)); - ADD_INSN1(ret, node, splatarray, Qfalse); - ADD_INSN(ret, node, pop); - CHECK(COMPILE(ret, "argscat body", node->nd_body)); - ADD_INSN1(ret, node, splatarray, Qfalse); - ADD_INSN(ret, node, pop); - } - else { - CHECK(COMPILE(ret, "argscat head", node->nd_head)); - CHECK(COMPILE(ret, "argscat body", node->nd_body)); - ADD_INSN(ret, node, concatarray); - } - break; + if (popped) { + CHECK(COMPILE(ret, "argscat head", node->nd_head)); + ADD_INSN1(ret, node, splatarray, Qfalse); + ADD_INSN(ret, node, pop); + CHECK(COMPILE(ret, "argscat body", node->nd_body)); + ADD_INSN1(ret, node, splatarray, Qfalse); + ADD_INSN(ret, node, pop); + } + else { + CHECK(COMPILE(ret, "argscat head", node->nd_head)); + CHECK(COMPILE(ret, "argscat body", node->nd_body)); + ADD_INSN(ret, node, concatarray); + } + break; } case NODE_ARGSPUSH:{ - if (popped) { - CHECK(COMPILE(ret, "argspush head", node->nd_head)); - ADD_INSN1(ret, node, splatarray, Qfalse); - ADD_INSN(ret, node, pop); - CHECK(COMPILE_(ret, "argspush body", node->nd_body, popped)); - } - else { - CHECK(COMPILE(ret, "argspush head", node->nd_head)); - CHECK(compile_array_1(iseq, ret, node->nd_body)); - ADD_INSN(ret, node, concatarray); - } - break; + if (popped) { + CHECK(COMPILE(ret, "argspush head", node->nd_head)); + ADD_INSN1(ret, node, splatarray, Qfalse); + ADD_INSN(ret, node, pop); + CHECK(COMPILE_(ret, "argspush body", node->nd_body, popped)); + } + else { + CHECK(COMPILE(ret, "argspush head", node->nd_head)); + CHECK(compile_array_1(iseq, ret, node->nd_body)); + ADD_INSN(ret, node, concatarray); + } + break; } case NODE_SPLAT:{ - CHECK(COMPILE(ret, "splat", node->nd_head)); - ADD_INSN1(ret, node, splatarray, Qtrue); + CHECK(COMPILE(ret, "splat", node->nd_head)); + ADD_INSN1(ret, node, splatarray, Qtrue); - if (popped) { - ADD_INSN(ret, node, pop); - } - break; + if (popped) { + ADD_INSN(ret, node, pop); + } + break; } case NODE_DEFN:{ ID mid = node->nd_mid; - const rb_iseq_t *method_iseq = NEW_ISEQ(node->nd_defn, + const rb_iseq_t *method_iseq = NEW_ISEQ(node->nd_defn, rb_id2str(mid), - ISEQ_TYPE_METHOD, line); + ISEQ_TYPE_METHOD, line); - debugp_param("defn/iseq", rb_iseqw_new(method_iseq)); + debugp_param("defn/iseq", rb_iseqw_new(method_iseq)); ADD_INSN2(ret, node, definemethod, ID2SYM(mid), method_iseq); RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)method_iseq); if (!popped) { ADD_INSN1(ret, node, putobject, ID2SYM(mid)); - } + } - break; + break; } case NODE_DEFS:{ ID mid = node->nd_mid; @@ -9665,206 +9665,206 @@ iseq_compile_each0(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const no if (!popped) { ADD_INSN1(ret, node, putobject, ID2SYM(mid)); } - break; + break; } case NODE_ALIAS:{ - ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE)); - ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_CBASE)); - CHECK(COMPILE(ret, "alias arg1", node->nd_1st)); - CHECK(COMPILE(ret, "alias arg2", node->nd_2nd)); - ADD_SEND(ret, node, id_core_set_method_alias, INT2FIX(3)); + ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE)); + ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_CBASE)); + CHECK(COMPILE(ret, "alias arg1", node->nd_1st)); + CHECK(COMPILE(ret, "alias arg2", node->nd_2nd)); + ADD_SEND(ret, node, id_core_set_method_alias, INT2FIX(3)); - if (popped) { - ADD_INSN(ret, node, pop); - } - break; + if (popped) { + ADD_INSN(ret, node, pop); + } + break; } case NODE_VALIAS:{ - ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE)); - ADD_INSN1(ret, node, putobject, ID2SYM(node->nd_alias)); - ADD_INSN1(ret, node, putobject, ID2SYM(node->nd_orig)); - ADD_SEND(ret, node, id_core_set_variable_alias, INT2FIX(2)); + ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE)); + ADD_INSN1(ret, node, putobject, ID2SYM(node->nd_alias)); + ADD_INSN1(ret, node, putobject, ID2SYM(node->nd_orig)); + ADD_SEND(ret, node, id_core_set_variable_alias, INT2FIX(2)); - if (popped) { - ADD_INSN(ret, node, pop); - } - break; + if (popped) { + ADD_INSN(ret, node, pop); + } + break; } case NODE_UNDEF:{ - ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE)); - ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_CBASE)); - CHECK(COMPILE(ret, "undef arg", node->nd_undef)); - ADD_SEND(ret, node, id_core_undef_method, INT2FIX(2)); + ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE)); + ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_CBASE)); + CHECK(COMPILE(ret, "undef arg", node->nd_undef)); + ADD_SEND(ret, node, id_core_undef_method, INT2FIX(2)); - if (popped) { - ADD_INSN(ret, node, pop); - } - break; + if (popped) { + ADD_INSN(ret, node, pop); + } + break; } case NODE_CLASS:{ - const rb_iseq_t *class_iseq = NEW_CHILD_ISEQ(node->nd_body, - rb_str_freeze(rb_sprintf("", rb_id2str(node->nd_cpath->nd_mid))), - ISEQ_TYPE_CLASS, line); - const int flags = VM_DEFINECLASS_TYPE_CLASS | - (node->nd_super ? VM_DEFINECLASS_FLAG_HAS_SUPERCLASS : 0) | - compile_cpath(ret, iseq, node->nd_cpath); + const rb_iseq_t *class_iseq = NEW_CHILD_ISEQ(node->nd_body, + rb_str_freeze(rb_sprintf("", rb_id2str(node->nd_cpath->nd_mid))), + ISEQ_TYPE_CLASS, line); + const int flags = VM_DEFINECLASS_TYPE_CLASS | + (node->nd_super ? VM_DEFINECLASS_FLAG_HAS_SUPERCLASS : 0) | + compile_cpath(ret, iseq, node->nd_cpath); - CHECK(COMPILE(ret, "super", node->nd_super)); - ADD_INSN3(ret, node, defineclass, ID2SYM(node->nd_cpath->nd_mid), class_iseq, INT2FIX(flags)); + CHECK(COMPILE(ret, "super", node->nd_super)); + ADD_INSN3(ret, node, defineclass, ID2SYM(node->nd_cpath->nd_mid), class_iseq, INT2FIX(flags)); RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)class_iseq); - if (popped) { - ADD_INSN(ret, node, pop); - } - break; + if (popped) { + ADD_INSN(ret, node, pop); + } + break; } case NODE_MODULE:{ const rb_iseq_t *module_iseq = NEW_CHILD_ISEQ(node->nd_body, - rb_str_freeze(rb_sprintf("", rb_id2str(node->nd_cpath->nd_mid))), - ISEQ_TYPE_CLASS, line); - const int flags = VM_DEFINECLASS_TYPE_MODULE | - compile_cpath(ret, iseq, node->nd_cpath); + rb_str_freeze(rb_sprintf("", rb_id2str(node->nd_cpath->nd_mid))), + ISEQ_TYPE_CLASS, line); + const int flags = VM_DEFINECLASS_TYPE_MODULE | + compile_cpath(ret, iseq, node->nd_cpath); - ADD_INSN (ret, node, putnil); /* dummy */ - ADD_INSN3(ret, node, defineclass, ID2SYM(node->nd_cpath->nd_mid), module_iseq, INT2FIX(flags)); + ADD_INSN (ret, node, putnil); /* dummy */ + ADD_INSN3(ret, node, defineclass, ID2SYM(node->nd_cpath->nd_mid), module_iseq, INT2FIX(flags)); RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)module_iseq); - if (popped) { - ADD_INSN(ret, node, pop); - } - break; + if (popped) { + ADD_INSN(ret, node, pop); + } + break; } case NODE_SCLASS:{ - ID singletonclass; - const rb_iseq_t *singleton_class = NEW_ISEQ(node->nd_body, rb_fstring_lit("singleton class"), - ISEQ_TYPE_CLASS, line); + ID singletonclass; + const rb_iseq_t *singleton_class = NEW_ISEQ(node->nd_body, rb_fstring_lit("singleton class"), + ISEQ_TYPE_CLASS, line); - CHECK(COMPILE(ret, "sclass#recv", node->nd_recv)); - ADD_INSN (ret, node, putnil); - CONST_ID(singletonclass, "singletonclass"); - ADD_INSN3(ret, node, defineclass, - ID2SYM(singletonclass), singleton_class, - INT2FIX(VM_DEFINECLASS_TYPE_SINGLETON_CLASS)); + CHECK(COMPILE(ret, "sclass#recv", node->nd_recv)); + ADD_INSN (ret, node, putnil); + CONST_ID(singletonclass, "singletonclass"); + ADD_INSN3(ret, node, defineclass, + ID2SYM(singletonclass), singleton_class, + INT2FIX(VM_DEFINECLASS_TYPE_SINGLETON_CLASS)); RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)singleton_class); - if (popped) { - ADD_INSN(ret, node, pop); - } - break; + if (popped) { + ADD_INSN(ret, node, pop); + } + break; } case NODE_COLON2: - CHECK(compile_colon2(iseq, ret, node, popped)); - break; + CHECK(compile_colon2(iseq, ret, node, popped)); + break; case NODE_COLON3: - CHECK(compile_colon3(iseq, ret, node, popped)); - break; + CHECK(compile_colon3(iseq, ret, node, popped)); + break; case NODE_DOT2: - CHECK(compile_dots(iseq, ret, node, popped, FALSE)); - break; + CHECK(compile_dots(iseq, ret, node, popped, FALSE)); + break; case NODE_DOT3: - CHECK(compile_dots(iseq, ret, node, popped, TRUE)); - break; + CHECK(compile_dots(iseq, ret, node, popped, TRUE)); + break; case NODE_FLIP2: case NODE_FLIP3:{ - LABEL *lend = NEW_LABEL(line); - LABEL *ltrue = NEW_LABEL(line); - LABEL *lfalse = NEW_LABEL(line); - CHECK(compile_flip_flop(iseq, ret, node, type == NODE_FLIP2, - ltrue, lfalse)); - ADD_LABEL(ret, ltrue); - ADD_INSN1(ret, node, putobject, Qtrue); - ADD_INSNL(ret, node, jump, lend); - ADD_LABEL(ret, lfalse); - ADD_INSN1(ret, node, putobject, Qfalse); - ADD_LABEL(ret, lend); - break; + LABEL *lend = NEW_LABEL(line); + LABEL *ltrue = NEW_LABEL(line); + LABEL *lfalse = NEW_LABEL(line); + CHECK(compile_flip_flop(iseq, ret, node, type == NODE_FLIP2, + ltrue, lfalse)); + ADD_LABEL(ret, ltrue); + ADD_INSN1(ret, node, putobject, Qtrue); + ADD_INSNL(ret, node, jump, lend); + ADD_LABEL(ret, lfalse); + ADD_INSN1(ret, node, putobject, Qfalse); + ADD_LABEL(ret, lend); + break; } case NODE_SELF:{ - if (!popped) { - ADD_INSN(ret, node, putself); - } - break; + if (!popped) { + ADD_INSN(ret, node, putself); + } + break; } case NODE_NIL:{ - if (!popped) { - ADD_INSN(ret, node, putnil); - } - break; + if (!popped) { + ADD_INSN(ret, node, putnil); + } + break; } case NODE_TRUE:{ - if (!popped) { - ADD_INSN1(ret, node, putobject, Qtrue); - } - break; + if (!popped) { + ADD_INSN1(ret, node, putobject, Qtrue); + } + break; } case NODE_FALSE:{ - if (!popped) { - ADD_INSN1(ret, node, putobject, Qfalse); - } - break; + if (!popped) { + ADD_INSN1(ret, node, putobject, Qfalse); + } + break; } case NODE_ERRINFO: - CHECK(compile_errinfo(iseq, ret, node, popped)); - break; + CHECK(compile_errinfo(iseq, ret, node, popped)); + break; case NODE_DEFINED: - if (!popped) { - CHECK(compile_defined_expr(iseq, ret, node, Qtrue)); - } - break; + if (!popped) { + CHECK(compile_defined_expr(iseq, ret, node, Qtrue)); + } + break; case NODE_POSTEXE:{ - /* compiled to: - * ONCE{ rb_mRubyVMFrozenCore::core#set_postexe{ ... } } - */ - int is_index = body->ise_size++; + /* compiled to: + * ONCE{ rb_mRubyVMFrozenCore::core#set_postexe{ ... } } + */ + int is_index = body->ise_size++; struct rb_iseq_new_with_callback_callback_func *ifunc = rb_iseq_new_with_callback_new_callback(build_postexe_iseq, node->nd_body); - const rb_iseq_t *once_iseq = + const rb_iseq_t *once_iseq = new_child_iseq_with_callback(iseq, ifunc, - rb_fstring(make_name_for_block(iseq)), iseq, ISEQ_TYPE_BLOCK, line); + rb_fstring(make_name_for_block(iseq)), iseq, ISEQ_TYPE_BLOCK, line); - ADD_INSN2(ret, node, once, once_iseq, INT2FIX(is_index)); + ADD_INSN2(ret, node, once, once_iseq, INT2FIX(is_index)); RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)once_iseq); - if (popped) { - ADD_INSN(ret, node, pop); - } - break; + if (popped) { + ADD_INSN(ret, node, pop); + } + break; } case NODE_KW_ARG: - CHECK(compile_kw_arg(iseq, ret, node, popped)); - break; + CHECK(compile_kw_arg(iseq, ret, node, popped)); + break; case NODE_DSYM:{ - compile_dstr(iseq, ret, node); - if (!popped) { - ADD_INSN(ret, node, intern); - } - else { - ADD_INSN(ret, node, pop); - } - break; + compile_dstr(iseq, ret, node); + if (!popped) { + ADD_INSN(ret, node, intern); + } + else { + ADD_INSN(ret, node, pop); + } + break; } case NODE_ATTRASGN: - CHECK(compile_attrasgn(iseq, ret, node, popped)); - break; + CHECK(compile_attrasgn(iseq, ret, node, popped)); + break; case NODE_LAMBDA:{ - /* compile same as lambda{...} */ - const rb_iseq_t *block = NEW_CHILD_ISEQ(node->nd_body, make_name_for_block(iseq), ISEQ_TYPE_BLOCK, line); - VALUE argc = INT2FIX(0); + /* compile same as lambda{...} */ + const rb_iseq_t *block = NEW_CHILD_ISEQ(node->nd_body, make_name_for_block(iseq), ISEQ_TYPE_BLOCK, line); + VALUE argc = INT2FIX(0); - ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE)); - ADD_CALL_WITH_BLOCK(ret, node, idLambda, argc, block); + ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE)); + ADD_CALL_WITH_BLOCK(ret, node, idLambda, argc, block); RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)block); - if (popped) { - ADD_INSN(ret, node, pop); - } - break; + if (popped) { + ADD_INSN(ret, node, pop); + } + break; } default: - UNKNOWN_NODE("iseq_compile_each", node, COMPILE_NG); + UNKNOWN_NODE("iseq_compile_each", node, COMPILE_NG); ng: - debug_node_end(); - return COMPILE_NG; + debug_node_end(); + return COMPILE_NG; } debug_node_end(); @@ -9892,15 +9892,15 @@ opobj_inspect(VALUE obj) { if (!SPECIAL_CONST_P(obj) && !RBASIC_CLASS(obj)) { switch (BUILTIN_TYPE(obj)) { - case T_STRING: - obj = rb_str_new_cstr(RSTRING_PTR(obj)); - break; - case T_ARRAY: - obj = rb_ary_dup(obj); - break; + case T_STRING: + obj = rb_str_new_cstr(RSTRING_PTR(obj)); + break; + case T_ARRAY: + obj = rb_ary_dup(obj); + break; default: break; - } + } } return rb_inspect(obj); } @@ -9913,86 +9913,86 @@ insn_data_to_s_detail(INSN *iobj) VALUE str = rb_sprintf("%-20s ", insn_name(iobj->insn_id)); if (iobj->operands) { - const char *types = insn_op_types(iobj->insn_id); - int j; + const char *types = insn_op_types(iobj->insn_id); + int j; - for (j = 0; types[j]; j++) { - char type = types[j]; + for (j = 0; types[j]; j++) { + char type = types[j]; - switch (type) { - case TS_OFFSET: /* label(destination position) */ - { - LABEL *lobj = (LABEL *)OPERAND_AT(iobj, j); - rb_str_catf(str, LABEL_FORMAT, lobj->label_no); - break; - } - break; - case TS_ISEQ: /* iseq */ - { - rb_iseq_t *iseq = (rb_iseq_t *)OPERAND_AT(iobj, j); - VALUE val = Qnil; - if (0 && iseq) { /* TODO: invalidate now */ - val = (VALUE)iseq; - } - rb_str_concat(str, opobj_inspect(val)); - } - break; - case TS_LINDEX: - case TS_NUM: /* ulong */ - case TS_VALUE: /* VALUE */ - { - VALUE v = OPERAND_AT(iobj, j); + switch (type) { + case TS_OFFSET: /* label(destination position) */ + { + LABEL *lobj = (LABEL *)OPERAND_AT(iobj, j); + rb_str_catf(str, LABEL_FORMAT, lobj->label_no); + break; + } + break; + case TS_ISEQ: /* iseq */ + { + rb_iseq_t *iseq = (rb_iseq_t *)OPERAND_AT(iobj, j); + VALUE val = Qnil; + if (0 && iseq) { /* TODO: invalidate now */ + val = (VALUE)iseq; + } + rb_str_concat(str, opobj_inspect(val)); + } + break; + case TS_LINDEX: + case TS_NUM: /* ulong */ + case TS_VALUE: /* VALUE */ + { + VALUE v = OPERAND_AT(iobj, j); if (!CLASS_OF(v)) rb_str_cat2(str, ""); else { rb_str_concat(str, opobj_inspect(v)); } - break; - } - case TS_ID: /* ID */ - rb_str_concat(str, opobj_inspect(OPERAND_AT(iobj, j))); - break; - case TS_IC: /* inline cache */ - case TS_IVC: /* inline ivar cache */ - case TS_ICVARC: /* inline cvar cache */ - case TS_ISE: /* inline storage entry */ - rb_str_catf(str, "", FIX2INT(OPERAND_AT(iobj, j))); - break; + break; + } + case TS_ID: /* ID */ + rb_str_concat(str, opobj_inspect(OPERAND_AT(iobj, j))); + break; + case TS_IC: /* inline cache */ + case TS_IVC: /* inline ivar cache */ + case TS_ICVARC: /* inline cvar cache */ + case TS_ISE: /* inline storage entry */ + rb_str_catf(str, "", FIX2INT(OPERAND_AT(iobj, j))); + break; case TS_CALLDATA: /* we store these as call infos at compile time */ - { + { const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT(iobj, j); rb_str_cat2(str, "", vm_ci_argc(ci)); - break; - } - case TS_CDHASH: /* case/when condition cache */ - rb_str_cat2(str, ""); - break; - case TS_FUNCPTR: - { - void *func = (void *)OPERAND_AT(iobj, j); + break; + } + case TS_CDHASH: /* case/when condition cache */ + rb_str_cat2(str, ""); + break; + case TS_FUNCPTR: + { + void *func = (void *)OPERAND_AT(iobj, j); #ifdef HAVE_DLADDR - Dl_info info; - if (dladdr(func, &info) && info.dli_sname) { - rb_str_cat2(str, info.dli_sname); - break; - } + Dl_info info; + if (dladdr(func, &info) && info.dli_sname) { + rb_str_cat2(str, info.dli_sname); + break; + } #endif - rb_str_catf(str, "<%p>", func); - } - break; + rb_str_catf(str, "<%p>", func); + } + break; case TS_BUILTIN: rb_str_cat2(str, ""); break; - default:{ - rb_raise(rb_eSyntaxError, "unknown operand type: %c", type); - } - } - if (types[j + 1]) { - rb_str_cat2(str, ", "); - } - } + default:{ + rb_raise(rb_eSyntaxError, "unknown operand type: %c", type); + } + } + if (types[j + 1]) { + rb_str_cat2(str, ", "); + } + } } return str; } @@ -10014,40 +10014,40 @@ dump_disasm_list_with_cursor(const LINK_ELEMENT *link, const LINK_ELEMENT *curr, printf("-- raw disasm--------\n"); while (link) { - if (curr) printf(curr == link ? "*" : " "); - switch (link->type) { - case ISEQ_ELEMENT_INSN: - { - iobj = (INSN *)link; - str = insn_data_to_s_detail(iobj); - printf(" %04d %-65s(%4u)\n", pos, StringValueCStr(str), iobj->insn_info.line_no); - pos += insn_data_length(iobj); - break; - } - case ISEQ_ELEMENT_LABEL: - { - lobj = (LABEL *)link; - printf(LABEL_FORMAT" [sp: %d]%s\n", lobj->label_no, lobj->sp, - dest == lobj ? " <---" : ""); - break; - } - case ISEQ_ELEMENT_TRACE: - { - TRACE *trace = (TRACE *)link; - printf(" trace: %0x\n", trace->event); - break; - } - case ISEQ_ELEMENT_ADJUST: - { - ADJUST *adjust = (ADJUST *)link; - printf(" adjust: [label: %d]\n", adjust->label ? adjust->label->label_no : -1); - break; - } - default: - /* ignore */ - rb_raise(rb_eSyntaxError, "dump_disasm_list error: %ld\n", FIX2LONG(link->type)); - } - link = link->next; + if (curr) printf(curr == link ? "*" : " "); + switch (link->type) { + case ISEQ_ELEMENT_INSN: + { + iobj = (INSN *)link; + str = insn_data_to_s_detail(iobj); + printf(" %04d %-65s(%4u)\n", pos, StringValueCStr(str), iobj->insn_info.line_no); + pos += insn_data_length(iobj); + break; + } + case ISEQ_ELEMENT_LABEL: + { + lobj = (LABEL *)link; + printf(LABEL_FORMAT" [sp: %d]%s\n", lobj->label_no, lobj->sp, + dest == lobj ? " <---" : ""); + break; + } + case ISEQ_ELEMENT_TRACE: + { + TRACE *trace = (TRACE *)link; + printf(" trace: %0x\n", trace->event); + break; + } + case ISEQ_ELEMENT_ADJUST: + { + ADJUST *adjust = (ADJUST *)link; + printf(" adjust: [label: %d]\n", adjust->label ? adjust->label->label_no : -1); + break; + } + default: + /* ignore */ + rb_raise(rb_eSyntaxError, "dump_disasm_list error: %ld\n", FIX2LONG(link->type)); + } + link = link->next; } printf("---------------------\n"); fflush(stdout); @@ -10065,7 +10065,7 @@ rb_insns_name_array(void) VALUE ary = rb_ary_new_capa(VM_INSTRUCTION_SIZE); int i; for (i = 0; i < VM_INSTRUCTION_SIZE; i++) { - rb_ary_push(ary, rb_fstring_cstr(insn_name(i))); + rb_ary_push(ary, rb_fstring_cstr(insn_name(i))); } return rb_obj_freeze(ary); } @@ -10078,11 +10078,11 @@ register_label(rb_iseq_t *iseq, struct st_table *labels_table, VALUE obj) obj = rb_to_symbol_type(obj); if (st_lookup(labels_table, obj, &tmp) == 0) { - label = NEW_LABEL(0); - st_insert(labels_table, obj, (st_data_t)label); + label = NEW_LABEL(0); + st_insert(labels_table, obj, (st_data_t)label); } else { - label = (LABEL *)tmp; + label = (LABEL *)tmp; } LABEL_REF(label); return label; @@ -10095,12 +10095,12 @@ get_exception_sym2type(VALUE sym) static VALUE symBreak, symRedo, symNext; if (symRescue == 0) { - symRescue = ID2SYM(rb_intern_const("rescue")); - symEnsure = ID2SYM(rb_intern_const("ensure")); - symRetry = ID2SYM(rb_intern_const("retry")); - symBreak = ID2SYM(rb_intern_const("break")); - symRedo = ID2SYM(rb_intern_const("redo")); - symNext = ID2SYM(rb_intern_const("next")); + symRescue = ID2SYM(rb_intern_const("rescue")); + symEnsure = ID2SYM(rb_intern_const("ensure")); + symRetry = ID2SYM(rb_intern_const("retry")); + symBreak = ID2SYM(rb_intern_const("break")); + symRedo = ID2SYM(rb_intern_const("redo")); + symNext = ID2SYM(rb_intern_const("next")); } if (sym == symRescue) return CATCH_TYPE_RESCUE; @@ -10115,25 +10115,25 @@ get_exception_sym2type(VALUE sym) static int iseq_build_from_ary_exception(rb_iseq_t *iseq, struct st_table *labels_table, - VALUE exception) + VALUE exception) { int i; for (i=0; isp = sp; + lcont->sp = sp; - ADD_CATCH_ENTRY(type, lstart, lend, eiseq, lcont); + ADD_CATCH_ENTRY(type, lstart, lend, eiseq, lcont); - RB_GC_GUARD(v); + RB_GC_GUARD(v); } return COMPILE_OK; } @@ -10166,7 +10166,7 @@ insn_make_insn_table(void) table = st_init_numtable_with_size(VM_INSTRUCTION_SIZE); for (i=0; ikeyword_len = len; - for (i = 0; i < len; i++) { - VALUE kw = RARRAY_AREF(vkw_arg, i); - SYM2ID(kw); /* make immortal */ - kw_arg->keywords[i] = kw; - } - } + kw_arg = xmalloc(n); + kw_arg->keyword_len = len; + for (i = 0; i < len; i++) { + VALUE kw = RARRAY_AREF(vkw_arg, i); + SYM2ID(kw); /* make immortal */ + kw_arg->keywords[i] = kw; + } + } } const struct rb_callinfo *ci = new_callinfo(iseq, mid, orig_argc, flag, kw_arg, (flag & VM_CALL_ARGS_SIMPLE) == 0); @@ -10234,20 +10234,20 @@ static rb_event_flag_t event_name_to_flag(VALUE sym) { #define CHECK_EVENT(ev) if (sym == ID2SYM(rb_intern_const(#ev))) return ev; - CHECK_EVENT(RUBY_EVENT_LINE); - CHECK_EVENT(RUBY_EVENT_CLASS); - CHECK_EVENT(RUBY_EVENT_END); - CHECK_EVENT(RUBY_EVENT_CALL); - CHECK_EVENT(RUBY_EVENT_RETURN); - CHECK_EVENT(RUBY_EVENT_B_CALL); - CHECK_EVENT(RUBY_EVENT_B_RETURN); + CHECK_EVENT(RUBY_EVENT_LINE); + CHECK_EVENT(RUBY_EVENT_CLASS); + CHECK_EVENT(RUBY_EVENT_END); + CHECK_EVENT(RUBY_EVENT_CALL); + CHECK_EVENT(RUBY_EVENT_RETURN); + CHECK_EVENT(RUBY_EVENT_B_CALL); + CHECK_EVENT(RUBY_EVENT_B_RETURN); #undef CHECK_EVENT return RUBY_EVENT_NONE; } static int iseq_build_from_ary_body(rb_iseq_t *iseq, LINK_ANCHOR *const anchor, - VALUE body, VALUE node_ids, VALUE labels_wrapper) + VALUE body, VALUE node_ids, VALUE labels_wrapper) { /* TODO: body should be frozen */ long i, len = RARRAY_LEN(body); @@ -10262,52 +10262,52 @@ iseq_build_from_ary_body(rb_iseq_t *iseq, LINK_ANCHOR *const anchor, static struct st_table *insn_table; if (insn_table == 0) { - insn_table = insn_make_insn_table(); + insn_table = insn_make_insn_table(); } for (i=0; i 0) { + if (argc > 0) { argv = compile_data_calloc2(iseq, sizeof(VALUE), argc); // add element before operand setup to make GC root @@ -10316,109 +10316,109 @@ iseq_build_from_ary_body(rb_iseq_t *iseq, LINK_ANCHOR *const anchor, (LINK_ELEMENT*)new_insn_core(iseq, &dummy_line_node, (enum ruby_vminsn_type)insn_id, argc, argv)); - for (j=0; j= ISEQ_BODY(iseq)->ise_size) { ISEQ_BODY(iseq)->ise_size = NUM2INT(op) + 1; } break; - case TS_IC: - argv[j] = op; + case TS_IC: + argv[j] = op; if (NUM2UINT(op) >= ISEQ_BODY(iseq)->ic_size) { ISEQ_BODY(iseq)->ic_size = NUM2INT(op) + 1; } break; case TS_IVC: /* inline ivar cache */ - argv[j] = op; + argv[j] = op; if (NUM2UINT(op) >= ISEQ_BODY(iseq)->ivc_size) { ISEQ_BODY(iseq)->ivc_size = NUM2INT(op) + 1; } - break; + break; case TS_ICVARC: /* inline cvar cache */ - argv[j] = op; + argv[j] = op; if (NUM2UINT(op) >= ISEQ_BODY(iseq)->icvarc_size) { ISEQ_BODY(iseq)->icvarc_size = NUM2INT(op) + 1; } - break; + break; case TS_CALLDATA: - argv[j] = iseq_build_callinfo_from_hash(iseq, op); - break; - case TS_ID: - argv[j] = rb_to_symbol_type(op); - break; - case TS_CDHASH: - { - int i; - VALUE map = rb_hash_new_with_size(RARRAY_LEN(op)/2); + argv[j] = iseq_build_callinfo_from_hash(iseq, op); + break; + case TS_ID: + argv[j] = rb_to_symbol_type(op); + break; + case TS_CDHASH: + { + int i; + VALUE map = rb_hash_new_with_size(RARRAY_LEN(op)/2); RHASH_TBL_RAW(map)->type = &cdhash_type; - op = rb_to_array_type(op); - for (i=0; irequired_num++; + if (!SYMBOL_P(val)) { + goto default_values; + } + ids[i] = SYM2ID(val); + keyword->required_num++; } default_values: /* note: we intentionally preserve `i' from previous loop */ default_len = len - i; if (default_len == 0) { - keyword->table = ids; - return keyword; + keyword->table = ids; + return keyword; } else if (default_len < 0) { UNREACHABLE; @@ -10488,23 +10488,23 @@ iseq_build_kw(rb_iseq_t *iseq, VALUE params, VALUE keywords) dvs = ALLOC_N(VALUE, (unsigned int)default_len); for (j = 0; i < len; i++, j++) { - key = RARRAY_AREF(keywords, i); - CHECK_ARRAY(key); + key = RARRAY_AREF(keywords, i); + CHECK_ARRAY(key); - switch (RARRAY_LEN(key)) { - case 1: - sym = RARRAY_AREF(key, 0); - default_val = Qundef; - break; - case 2: - sym = RARRAY_AREF(key, 0); - default_val = RARRAY_AREF(key, 1); - break; - default: - rb_raise(rb_eTypeError, "keyword default has unsupported len %+"PRIsVALUE, key); - } - ids[i] = SYM2ID(sym); - dvs[j] = default_val; + switch (RARRAY_LEN(key)) { + case 1: + sym = RARRAY_AREF(key, 0); + default_val = Qundef; + break; + case 2: + sym = RARRAY_AREF(key, 0); + default_val = RARRAY_AREF(key, 1); + break; + default: + rb_raise(rb_eTypeError, "keyword default has unsupported len %+"PRIsVALUE, key); + } + ids[i] = SYM2ID(sym); + dvs[j] = default_val; } keyword->table = ids; @@ -10569,7 +10569,7 @@ rb_iseq_mark_insn_storage(struct iseq_compile_data_storage *storage) void rb_iseq_build_from_ary(rb_iseq_t *iseq, VALUE misc, VALUE locals, VALUE params, - VALUE exception, VALUE body) + VALUE exception, VALUE body) { #define SYM(s) ID2SYM(rb_intern_const(#s)) int i, len; @@ -10588,14 +10588,14 @@ rb_iseq_build_from_ary(rb_iseq_t *iseq, VALUE misc, VALUE locals, VALUE params, ISEQ_BODY(iseq)->local_table = tbl = len > 0 ? (ID *)ALLOC_N(ID, ISEQ_BODY(iseq)->local_table_size) : NULL; for (i = 0; i < len; i++) { - VALUE lv = RARRAY_AREF(locals, i); + VALUE lv = RARRAY_AREF(locals, i); - if (sym_arg_rest == lv) { - tbl[i] = 0; - } - else { - tbl[i] = FIXNUM_P(lv) ? (ID)FIX2LONG(lv) : SYM2ID(CHECK_SYMBOL(lv)); - } + if (sym_arg_rest == lv) { + tbl[i] = 0; + } + else { + tbl[i] = FIXNUM_P(lv) ? (ID)FIX2LONG(lv) : SYM2ID(CHECK_SYMBOL(lv)); + } } #define INT_PARAM(F) int_param(&ISEQ_BODY(iseq)->param.F, params, SYM(F)) @@ -10609,10 +10609,10 @@ rb_iseq_build_from_ary(rb_iseq_t *iseq, VALUE misc, VALUE locals, VALUE params, #undef INT_PARAM { #define INT_PARAM(F) F = (int_param(&x, misc, SYM(F)) ? (unsigned int)x : 0) - int x; - INT_PARAM(arg_size); - INT_PARAM(local_size); - INT_PARAM(stack_max); + int x; + INT_PARAM(arg_size); + INT_PARAM(local_size); + INT_PARAM(stack_max); #undef INT_PARAM } @@ -10620,38 +10620,38 @@ rb_iseq_build_from_ary(rb_iseq_t *iseq, VALUE misc, VALUE locals, VALUE params, #ifdef USE_ISEQ_NODE_ID node_ids = rb_hash_aref(misc, ID2SYM(rb_intern("node_ids"))); if (!RB_TYPE_P(node_ids, T_ARRAY)) { - rb_raise(rb_eTypeError, "node_ids is not an array"); + rb_raise(rb_eTypeError, "node_ids is not an array"); } #endif if (RB_TYPE_P(arg_opt_labels, T_ARRAY)) { - len = RARRAY_LENINT(arg_opt_labels); + len = RARRAY_LENINT(arg_opt_labels); ISEQ_BODY(iseq)->param.flags.has_opt = !!(len - 1 >= 0); if (ISEQ_BODY(iseq)->param.flags.has_opt) { - VALUE *opt_table = ALLOC_N(VALUE, len); + VALUE *opt_table = ALLOC_N(VALUE, len); - for (i = 0; i < len; i++) { - VALUE ent = RARRAY_AREF(arg_opt_labels, i); - LABEL *label = register_label(iseq, labels_table, ent); - opt_table[i] = (VALUE)label; - } + for (i = 0; i < len; i++) { + VALUE ent = RARRAY_AREF(arg_opt_labels, i); + LABEL *label = register_label(iseq, labels_table, ent); + opt_table[i] = (VALUE)label; + } ISEQ_BODY(iseq)->param.opt_num = len - 1; ISEQ_BODY(iseq)->param.opt_table = opt_table; - } + } } else if (!NIL_P(arg_opt_labels)) { - rb_raise(rb_eTypeError, ":opt param is not an array: %+"PRIsVALUE, - arg_opt_labels); + rb_raise(rb_eTypeError, ":opt param is not an array: %+"PRIsVALUE, + arg_opt_labels); } if (RB_TYPE_P(keywords, T_ARRAY)) { ISEQ_BODY(iseq)->param.keyword = iseq_build_kw(iseq, params, keywords); } else if (!NIL_P(keywords)) { - rb_raise(rb_eTypeError, ":keywords param is not an array: %+"PRIsVALUE, - keywords); + rb_raise(rb_eTypeError, ":keywords param is not an array: %+"PRIsVALUE, + keywords); } if (Qtrue == rb_hash_aref(params, SYM(ambiguous_param0))) { @@ -10660,10 +10660,10 @@ rb_iseq_build_from_ary(rb_iseq_t *iseq, VALUE misc, VALUE locals, VALUE params, if (int_param(&i, params, SYM(kwrest))) { struct rb_iseq_param_keyword *keyword = (struct rb_iseq_param_keyword *)ISEQ_BODY(iseq)->param.keyword; - if (keyword == NULL) { + if (keyword == NULL) { ISEQ_BODY(iseq)->param.keyword = keyword = ZALLOC(struct rb_iseq_param_keyword); - } - keyword->rest_start = i; + } + keyword->rest_start = i; ISEQ_BODY(iseq)->param.flags.has_kwrest = TRUE; } #undef SYM @@ -10687,22 +10687,22 @@ rb_dvar_defined(ID id, const rb_iseq_t *iseq) { if (iseq) { const struct rb_iseq_constant_body *body = ISEQ_BODY(iseq); - while (body->type == ISEQ_TYPE_BLOCK || - body->type == ISEQ_TYPE_RESCUE || - body->type == ISEQ_TYPE_ENSURE || - body->type == ISEQ_TYPE_EVAL || - body->type == ISEQ_TYPE_MAIN - ) { - unsigned int i; + while (body->type == ISEQ_TYPE_BLOCK || + body->type == ISEQ_TYPE_RESCUE || + body->type == ISEQ_TYPE_ENSURE || + body->type == ISEQ_TYPE_EVAL || + body->type == ISEQ_TYPE_MAIN + ) { + unsigned int i; - for (i = 0; i < body->local_table_size; i++) { - if (body->local_table[i] == id) { - return 1; - } - } - iseq = body->parent_iseq; + for (i = 0; i < body->local_table_size; i++) { + if (body->local_table[i] == id) { + return 1; + } + } + iseq = body->parent_iseq; body = ISEQ_BODY(iseq); - } + } } return 0; } @@ -10711,14 +10711,14 @@ int rb_local_defined(ID id, const rb_iseq_t *iseq) { if (iseq) { - unsigned int i; + unsigned int i; const struct rb_iseq_constant_body *const body = ISEQ_BODY(ISEQ_BODY(iseq)->local_iseq); - for (i=0; ilocal_table_size; i++) { - if (body->local_table[i] == id) { - return 1; - } - } + for (i=0; ilocal_table_size; i++) { + if (body->local_table[i] == id) { + return 1; + } + } } return 0; } @@ -11180,7 +11180,7 @@ ibf_dump_code(struct ibf_dump *dump, const rb_iseq_t *iseq) case TS_IVC: case TS_ICVARC: { - union iseq_inline_storage_entry *is = (union iseq_inline_storage_entry *)op; + union iseq_inline_storage_entry *is = (union iseq_inline_storage_entry *)op; wv = is - ISEQ_IS_ENTRY_START(body, types[op_index]); } break; @@ -12166,7 +12166,7 @@ static const void * ibf_load_check_offset(const struct ibf_load *load, size_t offset) { if (offset >= load->current_buffer->size) { - rb_raise(rb_eIndexError, "object offset out of range: %"PRIdSIZE, offset); + rb_raise(rb_eIndexError, "object offset out of range: %"PRIdSIZE, offset); } return load->current_buffer->buff + offset; } @@ -12227,11 +12227,11 @@ ibf_load_object_class(const struct ibf_load *load, const struct ibf_object_heade switch (cindex) { case IBF_OBJECT_CLASS_OBJECT: - return rb_cObject; + return rb_cObject; case IBF_OBJECT_CLASS_ARRAY: - return rb_cArray; + return rb_cArray; case IBF_OBJECT_CLASS_STANDARD_ERROR: - return rb_eStandardError; + return rb_eStandardError; case IBF_OBJECT_CLASS_NO_MATCHING_PATTERN_ERROR: return rb_eNoMatchingPatternError; case IBF_OBJECT_CLASS_TYPE_ERROR: @@ -12461,7 +12461,7 @@ ibf_load_object_bignum(const struct ibf_load *load, const struct ibf_object_head int sign = bignum->slen > 0; ssize_t len = sign > 0 ? bignum->slen : -1 * bignum->slen; VALUE obj = rb_integer_unpack(bignum->digits, len * 2, 2, 0, - INTEGER_PACK_LITTLE_ENDIAN | (sign == 0 ? INTEGER_PACK_NEGATIVE : 0)); + INTEGER_PACK_LITTLE_ENDIAN | (sign == 0 ? INTEGER_PACK_NEGATIVE : 0)); if (header->internal) rb_obj_hide(obj); if (header->frozen) rb_obj_freeze(obj); return obj; @@ -12888,8 +12888,8 @@ rb_ibf_load_iseq_complete(rb_iseq_t *iseq) load->iseq = iseq; #if IBF_ISEQ_DEBUG fprintf(stderr, "rb_ibf_load_iseq_complete: index=%#x offset=%#x size=%#x\n", - iseq->aux.loader.index, offset, - load->header->size); + iseq->aux.loader.index, offset, + load->header->size); #endif ibf_load_iseq_each(load, iseq, offset); ISEQ_COMPILE_DATA_CLEAR(iseq); @@ -12914,37 +12914,37 @@ ibf_load_iseq(const struct ibf_load *load, const rb_iseq_t *index_iseq) #if IBF_ISEQ_DEBUG fprintf(stderr, "ibf_load_iseq: index_iseq=%p iseq_list=%p\n", - (void *)index_iseq, (void *)load->iseq_list); + (void *)index_iseq, (void *)load->iseq_list); #endif if (iseq_index == -1) { - return NULL; + return NULL; } else { - VALUE iseqv = pinned_list_fetch(load->iseq_list, iseq_index); + VALUE iseqv = pinned_list_fetch(load->iseq_list, iseq_index); #if IBF_ISEQ_DEBUG - fprintf(stderr, "ibf_load_iseq: iseqv=%p\n", (void *)iseqv); + fprintf(stderr, "ibf_load_iseq: iseqv=%p\n", (void *)iseqv); #endif - if (iseqv) { - return (rb_iseq_t *)iseqv; - } - else { - rb_iseq_t *iseq = iseq_imemo_alloc(); + if (iseqv) { + return (rb_iseq_t *)iseqv; + } + else { + rb_iseq_t *iseq = iseq_imemo_alloc(); #if IBF_ISEQ_DEBUG - fprintf(stderr, "ibf_load_iseq: new iseq=%p\n", (void *)iseq); + fprintf(stderr, "ibf_load_iseq: new iseq=%p\n", (void *)iseq); #endif - FL_SET((VALUE)iseq, ISEQ_NOT_LOADED_YET); - iseq->aux.loader.obj = load->loader_obj; - iseq->aux.loader.index = iseq_index; + FL_SET((VALUE)iseq, ISEQ_NOT_LOADED_YET); + iseq->aux.loader.obj = load->loader_obj; + iseq->aux.loader.index = iseq_index; #if IBF_ISEQ_DEBUG - fprintf(stderr, "ibf_load_iseq: iseq=%p loader_obj=%p index=%d\n", - (void *)iseq, (void *)load->loader_obj, iseq_index); + fprintf(stderr, "ibf_load_iseq: iseq=%p loader_obj=%p index=%d\n", + (void *)iseq, (void *)load->loader_obj, iseq_index); #endif - pinned_list_store(load->iseq_list, iseq_index, (VALUE)iseq); + pinned_list_store(load->iseq_list, iseq_index, (VALUE)iseq); #if !USE_LAZY_LOAD #if IBF_ISEQ_DEBUG - fprintf(stderr, "ibf_load_iseq: loading iseq=%p\n", (void *)iseq); + fprintf(stderr, "ibf_load_iseq: loading iseq=%p\n", (void *)iseq); #endif rb_ibf_load_iseq_complete(iseq); #else @@ -12954,11 +12954,11 @@ ibf_load_iseq(const struct ibf_load *load, const rb_iseq_t *index_iseq) #endif /* !USE_LAZY_LOAD */ #if IBF_ISEQ_DEBUG - fprintf(stderr, "ibf_load_iseq: iseq=%p loaded %p\n", - (void *)iseq, (void *)load->iseq); + fprintf(stderr, "ibf_load_iseq: iseq=%p loaded %p\n", + (void *)iseq, (void *)load->iseq); #endif - return iseq; - } + return iseq; + } } } @@ -12978,18 +12978,18 @@ ibf_load_setup_bytes(struct ibf_load *load, VALUE loader_obj, const char *bytes, load->current_buffer = &load->global_buffer; if (size < load->header->size) { - rb_raise(rb_eRuntimeError, "broken binary format"); + rb_raise(rb_eRuntimeError, "broken binary format"); } if (strncmp(load->header->magic, "YARB", 4) != 0) { - rb_raise(rb_eRuntimeError, "unknown binary format"); + rb_raise(rb_eRuntimeError, "unknown binary format"); } if (load->header->major_version != IBF_MAJOR_VERSION || - load->header->minor_version != IBF_MINOR_VERSION) { - rb_raise(rb_eRuntimeError, "unmatched version file (%u.%u for %u.%u)", - load->header->major_version, load->header->minor_version, IBF_MAJOR_VERSION, IBF_MINOR_VERSION); + load->header->minor_version != IBF_MINOR_VERSION) { + rb_raise(rb_eRuntimeError, "unmatched version file (%u.%u for %u.%u)", + load->header->major_version, load->header->minor_version, IBF_MAJOR_VERSION, IBF_MINOR_VERSION); } if (strcmp(load->global_buffer.buff + sizeof(struct ibf_header), RUBY_PLATFORM) != 0) { - rb_raise(rb_eRuntimeError, "unmatched platform"); + rb_raise(rb_eRuntimeError, "unmatched platform"); } if (load->header->iseq_list_offset % RUBY_ALIGNOF(ibf_offset_t)) { rb_raise(rb_eArgError, "unaligned iseq list offset: %u", diff --git a/complex.c b/complex.c index 92f4e812d6..d625ced7fa 100644 --- a/complex.c +++ b/complex.c @@ -97,7 +97,7 @@ inline static VALUE f_div(VALUE x, VALUE y) { if (FIXNUM_P(y) && FIX2LONG(y) == 1) - return x; + return x; return rb_funcall(x, '/', 1, y); } @@ -152,7 +152,7 @@ f_sub(VALUE x, VALUE y) { if (FIXNUM_ZERO_P(y) && LIKELY(rb_method_basic_definition_p(CLASS_OF(x), idMINUS))) { - return x; + return x; } return rb_funcall(x, '-', 1, y); } @@ -262,7 +262,7 @@ inline static VALUE f_to_i(VALUE x) { if (RB_TYPE_P(x, T_STRING)) - return rb_str_to_inum(x, 10, 0); + return rb_str_to_inum(x, 10, 0); return rb_funcall(x, id_to_i, 0); } @@ -270,7 +270,7 @@ inline static VALUE f_to_f(VALUE x) { if (RB_TYPE_P(x, T_STRING)) - return DBL2NUM(rb_str_to_dbl(x, 0)); + return DBL2NUM(rb_str_to_dbl(x, 0)); return rb_funcall(x, id_to_f, 0); } @@ -280,9 +280,9 @@ inline static int f_eqeq_p(VALUE x, VALUE y) { if (FIXNUM_P(x) && FIXNUM_P(y)) - return x == y; + return x == y; else if (RB_FLOAT_TYPE_P(x) || RB_FLOAT_TYPE_P(y)) - return NUM2DBL(x) == NUM2DBL(y); + return NUM2DBL(x) == NUM2DBL(y); return (int)rb_equal(x, y); } @@ -349,7 +349,7 @@ f_finite_p(VALUE x) return TRUE; } else if (RB_FLOAT_TYPE_P(x)) { - return isfinite(RFLOAT_VALUE(x)); + return isfinite(RFLOAT_VALUE(x)); } return RTEST(rb_funcallv(x, id_finite_p, 0, 0)); } @@ -361,7 +361,7 @@ f_infinite_p(VALUE x) return FALSE; } else if (RB_FLOAT_TYPE_P(x)) { - return isinf(RFLOAT_VALUE(x)); + return isinf(RFLOAT_VALUE(x)); } return RTEST(rb_funcallv(x, id_infinite_p, 0, 0)); } @@ -425,10 +425,10 @@ inline static void nucomp_real_check(VALUE num) { if (!RB_INTEGER_TYPE_P(num) && - !RB_FLOAT_TYPE_P(num) && - !RB_TYPE_P(num, T_RATIONAL)) { - if (!k_numeric_p(num) || !f_real_p(num)) - rb_raise(rb_eTypeError, "not a real"); + !RB_FLOAT_TYPE_P(num) && + !RB_TYPE_P(num, T_RATIONAL)) { + if (!k_numeric_p(num) || !f_real_p(num)) + rb_raise(rb_eTypeError, "not a real"); } } @@ -439,28 +439,28 @@ nucomp_s_canonicalize_internal(VALUE klass, VALUE real, VALUE imag) complex_r = RB_TYPE_P(real, T_COMPLEX); complex_i = RB_TYPE_P(imag, T_COMPLEX); if (!complex_r && !complex_i) { - return nucomp_s_new_internal(klass, real, imag); + return nucomp_s_new_internal(klass, real, imag); } else if (!complex_r) { - get_dat1(imag); + get_dat1(imag); - return nucomp_s_new_internal(klass, - f_sub(real, dat->imag), - f_add(ZERO, dat->real)); + return nucomp_s_new_internal(klass, + f_sub(real, dat->imag), + f_add(ZERO, dat->real)); } else if (!complex_i) { - get_dat1(real); + get_dat1(real); - return nucomp_s_new_internal(klass, - dat->real, - f_add(dat->imag, imag)); + return nucomp_s_new_internal(klass, + dat->real, + f_add(dat->imag, imag)); } else { - get_dat2(real, imag); + get_dat2(real, imag); - return nucomp_s_new_internal(klass, - f_sub(adat->real, bdat->imag), - f_add(adat->imag, bdat->real)); + return nucomp_s_new_internal(klass, + f_sub(adat->real, bdat->imag), + f_add(adat->imag, bdat->real)); } } @@ -480,13 +480,13 @@ nucomp_s_new(int argc, VALUE *argv, VALUE klass) switch (rb_scan_args(argc, argv, "11", &real, &imag)) { case 1: - nucomp_real_check(real); - imag = ZERO; - break; + nucomp_real_check(real); + imag = ZERO; + break; default: - nucomp_real_check(real); - nucomp_real_check(imag); - break; + nucomp_real_check(real); + nucomp_real_check(imag); + break; } return nucomp_s_canonicalize_internal(klass, real, imag); @@ -580,14 +580,14 @@ static VALUE m_cos(VALUE x) { if (!RB_TYPE_P(x, T_COMPLEX)) - return m_cos_bang(x); + return m_cos_bang(x); { - get_dat1(x); - return f_complex_new2(rb_cComplex, - f_mul(m_cos_bang(dat->real), - m_cosh_bang(dat->imag)), - f_mul(f_negate(m_sin_bang(dat->real)), - m_sinh_bang(dat->imag))); + get_dat1(x); + return f_complex_new2(rb_cComplex, + f_mul(m_cos_bang(dat->real), + m_cosh_bang(dat->imag)), + f_mul(f_negate(m_sin_bang(dat->real)), + m_sinh_bang(dat->imag))); } } @@ -595,14 +595,14 @@ static VALUE m_sin(VALUE x) { if (!RB_TYPE_P(x, T_COMPLEX)) - return m_sin_bang(x); + return m_sin_bang(x); { - get_dat1(x); - return f_complex_new2(rb_cComplex, - f_mul(m_sin_bang(dat->real), - m_cosh_bang(dat->imag)), - f_mul(m_cos_bang(dat->real), - m_sinh_bang(dat->imag))); + get_dat1(x); + return f_complex_new2(rb_cComplex, + f_mul(m_sin_bang(dat->real), + m_cosh_bang(dat->imag)), + f_mul(m_cos_bang(dat->real), + m_sinh_bang(dat->imag))); } } @@ -612,38 +612,38 @@ f_complex_polar(VALUE klass, VALUE x, VALUE y) assert(!RB_TYPE_P(x, T_COMPLEX)); assert(!RB_TYPE_P(y, T_COMPLEX)); if (f_zero_p(x) || f_zero_p(y)) { - return nucomp_s_new_internal(klass, x, RFLOAT_0); + return nucomp_s_new_internal(klass, x, RFLOAT_0); } if (RB_FLOAT_TYPE_P(y)) { - const double arg = RFLOAT_VALUE(y); - if (arg == M_PI) { - x = f_negate(x); - y = RFLOAT_0; - } - else if (arg == M_PI_2) { - y = x; - x = RFLOAT_0; - } - else if (arg == M_PI_2+M_PI) { - y = f_negate(x); - x = RFLOAT_0; - } - else if (RB_FLOAT_TYPE_P(x)) { - const double abs = RFLOAT_VALUE(x); - const double real = abs * cos(arg), imag = abs * sin(arg); - x = DBL2NUM(real); - y = DBL2NUM(imag); - } - else { + const double arg = RFLOAT_VALUE(y); + if (arg == M_PI) { + x = f_negate(x); + y = RFLOAT_0; + } + else if (arg == M_PI_2) { + y = x; + x = RFLOAT_0; + } + else if (arg == M_PI_2+M_PI) { + y = f_negate(x); + x = RFLOAT_0; + } + else if (RB_FLOAT_TYPE_P(x)) { + const double abs = RFLOAT_VALUE(x); + const double real = abs * cos(arg), imag = abs * sin(arg); + x = DBL2NUM(real); + y = DBL2NUM(imag); + } + else { const double ax = sin(arg), ay = cos(arg); y = f_mul(x, DBL2NUM(ax)); x = f_mul(x, DBL2NUM(ay)); - } - return nucomp_s_new_internal(klass, x, y); + } + return nucomp_s_new_internal(klass, x, y); } return nucomp_s_canonicalize_internal(klass, - f_mul(x, m_cos(y)), - f_mul(x, m_sin(y))); + f_mul(x, m_cos(y)), + f_mul(x, m_sin(y))); } #ifdef HAVE___COSPI @@ -665,12 +665,12 @@ rb_dbl_complex_new_polar_pi(double abs, double ang) int pos = fr == +0.5; if (pos || fr == -0.5) { - if ((modf(fi / 2.0, &fi) != fr) ^ pos) abs = -abs; - return rb_complex_new(RFLOAT_0, DBL2NUM(abs)); + if ((modf(fi / 2.0, &fi) != fr) ^ pos) abs = -abs; + return rb_complex_new(RFLOAT_0, DBL2NUM(abs)); } else if (fr == 0.0) { - if (modf(fi / 2.0, &fi) != 0.0) abs = -abs; - return DBL2NUM(abs); + if (modf(fi / 2.0, &fi) != 0.0) abs = -abs; + return DBL2NUM(abs); } else { const double real = abs * cospi(ang), imag = abs * sinpi(ang); @@ -696,12 +696,12 @@ nucomp_s_polar(int argc, VALUE *argv, VALUE klass) switch (rb_scan_args(argc, argv, "11", &abs, &arg)) { case 1: - nucomp_real_check(abs); - return nucomp_s_new_internal(klass, abs, ZERO); + nucomp_real_check(abs); + return nucomp_s_new_internal(klass, abs, ZERO); default: - nucomp_real_check(abs); - nucomp_real_check(arg); - break; + nucomp_real_check(abs); + nucomp_real_check(arg); + break; } if (RB_TYPE_P(abs, T_COMPLEX)) { get_dat1(abs); @@ -760,7 +760,7 @@ rb_complex_uminus(VALUE self) { get_dat1(self); return f_complex_new2(CLASS_OF(self), - f_negate(dat->real), f_negate(dat->imag)); + f_negate(dat->real), f_negate(dat->imag)); } /* @@ -779,20 +779,20 @@ VALUE rb_complex_plus(VALUE self, VALUE other) { if (RB_TYPE_P(other, T_COMPLEX)) { - VALUE real, imag; + VALUE real, imag; - get_dat2(self, other); + get_dat2(self, other); - real = f_add(adat->real, bdat->real); - imag = f_add(adat->imag, bdat->imag); + real = f_add(adat->real, bdat->real); + imag = f_add(adat->imag, bdat->imag); - return f_complex_new2(CLASS_OF(self), real, imag); + return f_complex_new2(CLASS_OF(self), real, imag); } if (k_numeric_p(other) && f_real_p(other)) { - get_dat1(self); + get_dat1(self); - return f_complex_new2(CLASS_OF(self), - f_add(dat->real, other), dat->imag); + return f_complex_new2(CLASS_OF(self), + f_add(dat->real, other), dat->imag); } return rb_num_coerce_bin(self, other, '+'); } @@ -813,20 +813,20 @@ VALUE rb_complex_minus(VALUE self, VALUE other) { if (RB_TYPE_P(other, T_COMPLEX)) { - VALUE real, imag; + VALUE real, imag; - get_dat2(self, other); + get_dat2(self, other); - real = f_sub(adat->real, bdat->real); - imag = f_sub(adat->imag, bdat->imag); + real = f_sub(adat->real, bdat->real); + imag = f_sub(adat->imag, bdat->imag); - return f_complex_new2(CLASS_OF(self), real, imag); + return f_complex_new2(CLASS_OF(self), real, imag); } if (k_numeric_p(other) && f_real_p(other)) { - get_dat1(self); + get_dat1(self); - return f_complex_new2(CLASS_OF(self), - f_sub(dat->real, other), dat->imag); + return f_complex_new2(CLASS_OF(self), + f_sub(dat->real, other), dat->imag); } return rb_num_coerce_bin(self, other, '-'); } @@ -836,10 +836,10 @@ safe_mul(VALUE a, VALUE b, int az, int bz) { double v; if (!az && bz && RB_FLOAT_TYPE_P(a) && (v = RFLOAT_VALUE(a), !isnan(v))) { - a = signbit(v) ? DBL2NUM(-1.0) : DBL2NUM(1.0); + a = signbit(v) ? DBL2NUM(-1.0) : DBL2NUM(1.0); } if (!bz && az && RB_FLOAT_TYPE_P(b) && (v = RFLOAT_VALUE(b), !isnan(v))) { - b = signbit(v) ? DBL2NUM(-1.0) : DBL2NUM(1.0); + b = signbit(v) ? DBL2NUM(-1.0) : DBL2NUM(1.0); } return f_mul(a, b); } @@ -873,47 +873,47 @@ VALUE rb_complex_mul(VALUE self, VALUE other) { if (RB_TYPE_P(other, T_COMPLEX)) { - VALUE real, imag; - get_dat2(self, other); + VALUE real, imag; + get_dat2(self, other); comp_mul(adat->real, adat->imag, bdat->real, bdat->imag, &real, &imag); - return f_complex_new2(CLASS_OF(self), real, imag); + return f_complex_new2(CLASS_OF(self), real, imag); } if (k_numeric_p(other) && f_real_p(other)) { - get_dat1(self); + get_dat1(self); - return f_complex_new2(CLASS_OF(self), - f_mul(dat->real, other), - f_mul(dat->imag, other)); + return f_complex_new2(CLASS_OF(self), + f_mul(dat->real, other), + f_mul(dat->imag, other)); } return rb_num_coerce_bin(self, other, '*'); } inline static VALUE f_divide(VALUE self, VALUE other, - VALUE (*func)(VALUE, VALUE), ID id) + VALUE (*func)(VALUE, VALUE), ID id) { if (RB_TYPE_P(other, T_COMPLEX)) { VALUE r, n, x, y; - int flo; - get_dat2(self, other); + int flo; + get_dat2(self, other); - flo = (RB_FLOAT_TYPE_P(adat->real) || RB_FLOAT_TYPE_P(adat->imag) || - RB_FLOAT_TYPE_P(bdat->real) || RB_FLOAT_TYPE_P(bdat->imag)); + flo = (RB_FLOAT_TYPE_P(adat->real) || RB_FLOAT_TYPE_P(adat->imag) || + RB_FLOAT_TYPE_P(bdat->real) || RB_FLOAT_TYPE_P(bdat->imag)); - if (f_gt_p(f_abs(bdat->real), f_abs(bdat->imag))) { - r = (*func)(bdat->imag, bdat->real); - n = f_mul(bdat->real, f_add(ONE, f_mul(r, r))); + if (f_gt_p(f_abs(bdat->real), f_abs(bdat->imag))) { + r = (*func)(bdat->imag, bdat->real); + n = f_mul(bdat->real, f_add(ONE, f_mul(r, r))); x = (*func)(f_add(adat->real, f_mul(adat->imag, r)), n); y = (*func)(f_sub(adat->imag, f_mul(adat->real, r)), n); - } - else { - r = (*func)(bdat->real, bdat->imag); - n = f_mul(bdat->imag, f_add(ONE, f_mul(r, r))); + } + else { + r = (*func)(bdat->real, bdat->imag); + n = f_mul(bdat->imag, f_add(ONE, f_mul(r, r))); x = (*func)(f_add(f_mul(adat->real, r), adat->imag), n); y = (*func)(f_sub(f_mul(adat->imag, r), adat->real), n); - } + } if (!flo) { x = rb_rational_canonicalize(x); y = rb_rational_canonicalize(y); @@ -922,7 +922,7 @@ f_divide(VALUE self, VALUE other, } if (k_numeric_p(other) && f_real_p(other)) { VALUE x, y; - get_dat1(self); + get_dat1(self); x = rb_rational_canonicalize((*func)(dat->real, other)); y = rb_rational_canonicalize((*func)(dat->imag, other)); return f_complex_new2(CLASS_OF(self), x, y); @@ -986,31 +986,31 @@ VALUE rb_complex_pow(VALUE self, VALUE other) { if (k_numeric_p(other) && k_exact_zero_p(other)) - return f_complex_new_bang1(CLASS_OF(self), ONE); + return f_complex_new_bang1(CLASS_OF(self), ONE); if (RB_TYPE_P(other, T_RATIONAL) && RRATIONAL(other)->den == LONG2FIX(1)) - other = RRATIONAL(other)->num; /* c14n */ + other = RRATIONAL(other)->num; /* c14n */ if (RB_TYPE_P(other, T_COMPLEX)) { - get_dat1(other); + get_dat1(other); - if (k_exact_zero_p(dat->imag)) - other = dat->real; /* c14n */ + if (k_exact_zero_p(dat->imag)) + other = dat->real; /* c14n */ } if (RB_TYPE_P(other, T_COMPLEX)) { - VALUE r, theta, nr, ntheta; + VALUE r, theta, nr, ntheta; - get_dat1(other); + get_dat1(other); - r = f_abs(self); - theta = f_arg(self); + r = f_abs(self); + theta = f_arg(self); - nr = m_exp_bang(f_sub(f_mul(dat->real, m_log_bang(r)), - f_mul(dat->imag, theta))); - ntheta = f_add(f_mul(theta, dat->real), - f_mul(dat->imag, m_log_bang(r))); - return f_complex_polar(CLASS_OF(self), nr, ntheta); + nr = m_exp_bang(f_sub(f_mul(dat->real, m_log_bang(r)), + f_mul(dat->imag, theta))); + ntheta = f_add(f_mul(theta, dat->real), + f_mul(dat->imag, m_log_bang(r))); + return f_complex_polar(CLASS_OF(self), nr, ntheta); } if (FIXNUM_P(other)) { long n = FIX2LONG(other); @@ -1051,19 +1051,19 @@ rb_complex_pow(VALUE self, VALUE other) } } return nucomp_s_new_internal(CLASS_OF(self), zr, zi); - } + } } if (k_numeric_p(other) && f_real_p(other)) { - VALUE r, theta; + VALUE r, theta; - if (RB_BIGNUM_TYPE_P(other)) - rb_warn("in a**b, b may be too big"); + if (RB_BIGNUM_TYPE_P(other)) + rb_warn("in a**b, b may be too big"); - r = f_abs(self); - theta = f_arg(self); + r = f_abs(self); + theta = f_arg(self); - return f_complex_polar(CLASS_OF(self), f_expt(r, other), - f_mul(theta, other)); + return f_complex_polar(CLASS_OF(self), f_expt(r, other), + f_mul(theta, other)); } return rb_num_coerce_bin(self, other, id_expt); } @@ -1084,15 +1084,15 @@ static VALUE nucomp_eqeq_p(VALUE self, VALUE other) { if (RB_TYPE_P(other, T_COMPLEX)) { - get_dat2(self, other); + get_dat2(self, other); - return RBOOL(f_eqeq_p(adat->real, bdat->real) && - f_eqeq_p(adat->imag, bdat->imag)); + return RBOOL(f_eqeq_p(adat->real, bdat->real) && + f_eqeq_p(adat->imag, bdat->imag)); } if (k_numeric_p(other) && f_real_p(other)) { - get_dat1(self); + get_dat1(self); - return RBOOL(f_eqeq_p(dat->real, other) && f_zero_p(dat->imag)); + return RBOOL(f_eqeq_p(dat->real, other) && f_zero_p(dat->imag)); } return RBOOL(f_eqeq_p(other, self)); } @@ -1139,12 +1139,12 @@ static VALUE nucomp_coerce(VALUE self, VALUE other) { if (RB_TYPE_P(other, T_COMPLEX)) - return rb_assoc_new(other, self); + return rb_assoc_new(other, self); if (k_numeric_p(other) && f_real_p(other)) return rb_assoc_new(f_complex_new_bang1(CLASS_OF(self), other), self); rb_raise(rb_eTypeError, "%"PRIsVALUE" can't be coerced into %"PRIsVALUE, - rb_obj_class(other), rb_obj_class(self)); + rb_obj_class(other), rb_obj_class(self)); return Qnil; } @@ -1164,16 +1164,16 @@ rb_complex_abs(VALUE self) get_dat1(self); if (f_zero_p(dat->real)) { - VALUE a = f_abs(dat->imag); - if (RB_FLOAT_TYPE_P(dat->real) && !RB_FLOAT_TYPE_P(dat->imag)) - a = f_to_f(a); - return a; + VALUE a = f_abs(dat->imag); + if (RB_FLOAT_TYPE_P(dat->real) && !RB_FLOAT_TYPE_P(dat->imag)) + a = f_to_f(a); + return a; } if (f_zero_p(dat->imag)) { - VALUE a = f_abs(dat->real); - if (!RB_FLOAT_TYPE_P(dat->real) && RB_FLOAT_TYPE_P(dat->imag)) - a = f_to_f(a); - return a; + VALUE a = f_abs(dat->real); + if (!RB_FLOAT_TYPE_P(dat->real) && RB_FLOAT_TYPE_P(dat->imag)) + a = f_to_f(a); + return a; } return rb_math_hypot(dat->real, dat->imag); } @@ -1192,7 +1192,7 @@ nucomp_abs2(VALUE self) { get_dat1(self); return f_add(f_mul(dat->real, dat->real), - f_mul(dat->imag, dat->imag)); + f_mul(dat->imag, dat->imag)); } /* @@ -1313,10 +1313,10 @@ nucomp_numerator(VALUE self) cd = nucomp_denominator(self); return f_complex_new2(CLASS_OF(self), - f_mul(f_numerator(dat->real), - f_div(cd, f_denominator(dat->real))), - f_mul(f_numerator(dat->imag), - f_div(cd, f_denominator(dat->imag)))); + f_mul(f_numerator(dat->real), + f_div(cd, f_denominator(dat->real))), + f_mul(f_numerator(dat->imag), + f_div(cd, f_denominator(dat->imag)))); } /* :nodoc: */ @@ -1346,11 +1346,11 @@ static VALUE nucomp_eql_p(VALUE self, VALUE other) { if (RB_TYPE_P(other, T_COMPLEX)) { - get_dat2(self, other); + get_dat2(self, other); - return RBOOL((CLASS_OF(adat->real) == CLASS_OF(bdat->real)) && - (CLASS_OF(adat->imag) == CLASS_OF(bdat->imag)) && - f_eqeq_p(self, other)); + return RBOOL((CLASS_OF(adat->real) == CLASS_OF(bdat->real)) && + (CLASS_OF(adat->imag) == CLASS_OF(bdat->imag)) && + f_eqeq_p(self, other)); } return Qfalse; @@ -1360,8 +1360,8 @@ inline static int f_signbit(VALUE x) { if (RB_FLOAT_TYPE_P(x)) { - double f = RFLOAT_VALUE(x); - return !isnan(f) && signbit(f); + double f = RFLOAT_VALUE(x); + return !isnan(f) && signbit(f); } return f_negative_p(x); } @@ -1387,7 +1387,7 @@ f_format(VALUE self, VALUE (*func)(VALUE)) rb_str_concat(s, (*func)(f_abs(dat->imag))); if (!rb_isdigit(RSTRING_PTR(s)[RSTRING_LEN(s) - 1])) - rb_str_cat2(s, "*"); + rb_str_cat2(s, "*"); rb_str_cat2(s, "i"); return s; @@ -1470,7 +1470,7 @@ rb_complex_infinite_p(VALUE self) get_dat1(self); if (!f_infinite_p(dat->real) && !f_infinite_p(dat->imag)) { - return Qnil; + return Qnil; } return ONE; } @@ -1513,7 +1513,7 @@ nucomp_marshal_load(VALUE self, VALUE a) { Check_Type(a, T_ARRAY); if (RARRAY_LEN(a) != 2) - rb_raise(rb_eArgError, "marshaled complex must have an array whose length is 2 but %ld", RARRAY_LEN(a)); + rb_raise(rb_eArgError, "marshaled complex must have an array whose length is 2 but %ld", RARRAY_LEN(a)); rb_ivar_set(self, id_i_real, RARRAY_AREF(a, 0)); rb_ivar_set(self, id_i_imag, RARRAY_AREF(a, 1)); return self; @@ -1575,8 +1575,8 @@ nucomp_to_i(VALUE self) get_dat1(self); if (!k_exact_zero_p(dat->imag)) { - rb_raise(rb_eRangeError, "can't convert %"PRIsVALUE" into Integer", - self); + rb_raise(rb_eRangeError, "can't convert %"PRIsVALUE" into Integer", + self); } return f_to_i(dat->real); } @@ -1598,8 +1598,8 @@ nucomp_to_f(VALUE self) get_dat1(self); if (!k_exact_zero_p(dat->imag)) { - rb_raise(rb_eRangeError, "can't convert %"PRIsVALUE" into Float", - self); + rb_raise(rb_eRangeError, "can't convert %"PRIsVALUE" into Float", + self); } return f_to_f(dat->real); } @@ -1623,8 +1623,8 @@ nucomp_to_r(VALUE self) get_dat1(self); if (!k_exact_zero_p(dat->imag)) { - rb_raise(rb_eRangeError, "can't convert %"PRIsVALUE" into Rational", - self); + rb_raise(rb_eRangeError, "can't convert %"PRIsVALUE" into Rational", + self); } return f_to_r(dat->real); } @@ -1703,14 +1703,14 @@ issign(int c) static int read_sign(const char **s, - char **b) + char **b) { int sign = '?'; if (issign(**s)) { - sign = **b = **s; - (*s)++; - (*b)++; + sign = **b = **s; + (*s)++; + (*b)++; } return sign; } @@ -1723,32 +1723,32 @@ isdecimal(int c) static int read_digits(const char **s, int strict, - char **b) + char **b) { int us = 1; if (!isdecimal(**s)) - return 0; + return 0; while (isdecimal(**s) || **s == '_') { - if (**s == '_') { - if (strict) { - if (us) - return 0; - } - us = 1; - } - else { - **b = **s; - (*b)++; - us = 0; - } - (*s)++; + if (**s == '_') { + if (strict) { + if (us) + return 0; + } + us = 1; + } + else { + **b = **s; + (*b)++; + us = 0; + } + (*s)++; } if (us) - do { - (*s)--; - } while (**s == '_'); + do { + (*s)--; + } while (**s == '_'); return 1; } @@ -1760,70 +1760,70 @@ islettere(int c) static int read_num(const char **s, int strict, - char **b) + char **b) { if (**s != '.') { - if (!read_digits(s, strict, b)) - return 0; + if (!read_digits(s, strict, b)) + return 0; } if (**s == '.') { - **b = **s; - (*s)++; - (*b)++; - if (!read_digits(s, strict, b)) { - (*b)--; - return 0; - } + **b = **s; + (*s)++; + (*b)++; + if (!read_digits(s, strict, b)) { + (*b)--; + return 0; + } } if (islettere(**s)) { - **b = **s; - (*s)++; - (*b)++; - read_sign(s, b); - if (!read_digits(s, strict, b)) { - (*b)--; - return 0; - } + **b = **s; + (*s)++; + (*b)++; + read_sign(s, b); + if (!read_digits(s, strict, b)) { + (*b)--; + return 0; + } } return 1; } inline static int read_den(const char **s, int strict, - char **b) + char **b) { if (!read_digits(s, strict, b)) - return 0; + return 0; return 1; } static int read_rat_nos(const char **s, int strict, - char **b) + char **b) { if (!read_num(s, strict, b)) - return 0; + return 0; if (**s == '/') { - **b = **s; - (*s)++; - (*b)++; - if (!read_den(s, strict, b)) { - (*b)--; - return 0; - } + **b = **s; + (*s)++; + (*b)++; + if (!read_den(s, strict, b)) { + (*b)--; + return 0; + } } return 1; } static int read_rat(const char **s, int strict, - char **b) + char **b) { read_sign(s, b); if (!read_rat_nos(s, strict, b)) - return 0; + return 0; return 1; } @@ -1831,22 +1831,22 @@ inline static int isimagunit(int c) { return (c == 'i' || c == 'I' || - c == 'j' || c == 'J'); + c == 'j' || c == 'J'); } static VALUE str2num(char *s) { if (strchr(s, '/')) - return rb_cstr_to_rat(s, 0); + return rb_cstr_to_rat(s, 0); if (strpbrk(s, ".eE")) - return DBL2NUM(rb_cstr_to_dbl(s, 0)); + return DBL2NUM(rb_cstr_to_dbl(s, 0)); return rb_cstr_to_inum(s, 10, 0); } static int read_comp(const char **s, int strict, - VALUE *ret, char **b) + VALUE *ret, char **b) { char *bb; int sign; @@ -1857,72 +1857,72 @@ read_comp(const char **s, int strict, sign = read_sign(s, b); if (isimagunit(**s)) { - (*s)++; - num = INT2FIX((sign == '-') ? -1 : + 1); - *ret = rb_complex_new2(ZERO, num); - return 1; /* e.g. "i" */ + (*s)++; + num = INT2FIX((sign == '-') ? -1 : + 1); + *ret = rb_complex_new2(ZERO, num); + return 1; /* e.g. "i" */ } if (!read_rat_nos(s, strict, b)) { - **b = '\0'; - num = str2num(bb); - *ret = rb_complex_new2(num, ZERO); - return 0; /* e.g. "-" */ + **b = '\0'; + num = str2num(bb); + *ret = rb_complex_new2(num, ZERO); + return 0; /* e.g. "-" */ } **b = '\0'; num = str2num(bb); if (isimagunit(**s)) { - (*s)++; - *ret = rb_complex_new2(ZERO, num); - return 1; /* e.g. "3i" */ + (*s)++; + *ret = rb_complex_new2(ZERO, num); + return 1; /* e.g. "3i" */ } if (**s == '@') { - int st; + int st; - (*s)++; - bb = *b; - st = read_rat(s, strict, b); - **b = '\0'; - if (strlen(bb) < 1 || - !isdecimal(*(bb + strlen(bb) - 1))) { - *ret = rb_complex_new2(num, ZERO); - return 0; /* e.g. "1@-" */ - } - num2 = str2num(bb); - *ret = rb_complex_new_polar(num, num2); - if (!st) - return 0; /* e.g. "1@2." */ - else - return 1; /* e.g. "1@2" */ + (*s)++; + bb = *b; + st = read_rat(s, strict, b); + **b = '\0'; + if (strlen(bb) < 1 || + !isdecimal(*(bb + strlen(bb) - 1))) { + *ret = rb_complex_new2(num, ZERO); + return 0; /* e.g. "1@-" */ + } + num2 = str2num(bb); + *ret = rb_complex_new_polar(num, num2); + if (!st) + return 0; /* e.g. "1@2." */ + else + return 1; /* e.g. "1@2" */ } if (issign(**s)) { - bb = *b; - sign = read_sign(s, b); - if (isimagunit(**s)) - num2 = INT2FIX((sign == '-') ? -1 : + 1); - else { - if (!read_rat_nos(s, strict, b)) { - *ret = rb_complex_new2(num, ZERO); - return 0; /* e.g. "1+xi" */ - } - **b = '\0'; - num2 = str2num(bb); - } - if (!isimagunit(**s)) { - *ret = rb_complex_new2(num, ZERO); - return 0; /* e.g. "1+3x" */ - } - (*s)++; - *ret = rb_complex_new2(num, num2); - return 1; /* e.g. "1+2i" */ + bb = *b; + sign = read_sign(s, b); + if (isimagunit(**s)) + num2 = INT2FIX((sign == '-') ? -1 : + 1); + else { + if (!read_rat_nos(s, strict, b)) { + *ret = rb_complex_new2(num, ZERO); + return 0; /* e.g. "1+xi" */ + } + **b = '\0'; + num2 = str2num(bb); + } + if (!isimagunit(**s)) { + *ret = rb_complex_new2(num, ZERO); + return 0; /* e.g. "1+3x" */ + } + (*s)++; + *ret = rb_complex_new2(num, num2); + return 1; /* e.g. "1+2i" */ } /* !(@, - or +) */ { - *ret = rb_complex_new2(num, ZERO); - return 1; /* e.g. "3" */ + *ret = rb_complex_new2(num, ZERO); + return 1; /* e.g. "3" */ } } @@ -1930,7 +1930,7 @@ inline static void skip_ws(const char **s) { while (isspace((unsigned char)**s)) - (*s)++; + (*s)++; } static int @@ -1971,22 +1971,22 @@ string_to_c_strict(VALUE self, int raise) if (!s || memchr(s, '\0', RSTRING_LEN(self))) { if (!raise) return Qnil; - rb_raise(rb_eArgError, "string contains null byte"); + rb_raise(rb_eArgError, "string contains null byte"); } if (s && s[RSTRING_LEN(self)]) { - rb_str_modify(self); - s = RSTRING_PTR(self); - s[RSTRING_LEN(self)] = '\0'; + rb_str_modify(self); + s = RSTRING_PTR(self); + s[RSTRING_LEN(self)] = '\0'; } if (!s) - s = (char *)""; + s = (char *)""; if (!parse_comp(s, 1, &num)) { if (!raise) return Qnil; - rb_raise(rb_eArgError, "invalid value for convert(): %+"PRIsVALUE, - self); + rb_raise(rb_eArgError, "invalid value for convert(): %+"PRIsVALUE, + self); } return num; @@ -2026,13 +2026,13 @@ string_to_c(VALUE self) s = RSTRING_PTR(self); if (s && s[RSTRING_LEN(self)]) { - rb_str_modify(self); - s = RSTRING_PTR(self); - s[RSTRING_LEN(self)] = '\0'; + rb_str_modify(self); + s = RSTRING_PTR(self); + s[RSTRING_LEN(self)] = '\0'; } if (!s) - s = (char *)""; + s = (char *)""; (void)parse_comp(s, 0, &num); @@ -2050,64 +2050,64 @@ nucomp_convert(VALUE klass, VALUE a1, VALUE a2, int raise) { if (NIL_P(a1) || NIL_P(a2)) { if (!raise) return Qnil; - rb_raise(rb_eTypeError, "can't convert nil into Complex"); + rb_raise(rb_eTypeError, "can't convert nil into Complex"); } if (RB_TYPE_P(a1, T_STRING)) { - a1 = string_to_c_strict(a1, raise); + a1 = string_to_c_strict(a1, raise); if (NIL_P(a1)) return Qnil; } if (RB_TYPE_P(a2, T_STRING)) { - a2 = string_to_c_strict(a2, raise); + a2 = string_to_c_strict(a2, raise); if (NIL_P(a2)) return Qnil; } if (RB_TYPE_P(a1, T_COMPLEX)) { - { - get_dat1(a1); + { + get_dat1(a1); - if (k_exact_zero_p(dat->imag)) - a1 = dat->real; - } + if (k_exact_zero_p(dat->imag)) + a1 = dat->real; + } } if (RB_TYPE_P(a2, T_COMPLEX)) { - { - get_dat1(a2); + { + get_dat1(a2); - if (k_exact_zero_p(dat->imag)) - a2 = dat->real; - } + if (k_exact_zero_p(dat->imag)) + a2 = dat->real; + } } if (RB_TYPE_P(a1, T_COMPLEX)) { - if (a2 == Qundef || (k_exact_zero_p(a2))) - return a1; + if (a2 == Qundef || (k_exact_zero_p(a2))) + return a1; } if (a2 == Qundef) { - if (k_numeric_p(a1) && !f_real_p(a1)) - return a1; - /* should raise exception for consistency */ - if (!k_numeric_p(a1)) { + if (k_numeric_p(a1) && !f_real_p(a1)) + return a1; + /* should raise exception for consistency */ + if (!k_numeric_p(a1)) { if (!raise) return rb_protect(to_complex, a1, NULL); - return to_complex(a1); + return to_complex(a1); } } else { - if ((k_numeric_p(a1) && k_numeric_p(a2)) && - (!f_real_p(a1) || !f_real_p(a2))) - return f_add(a1, - f_mul(a2, - f_complex_new_bang2(rb_cComplex, ZERO, ONE))); + if ((k_numeric_p(a1) && k_numeric_p(a2)) && + (!f_real_p(a1) || !f_real_p(a2))) + return f_add(a1, + f_mul(a2, + f_complex_new_bang2(rb_cComplex, ZERO, ONE))); } { int argc; - VALUE argv2[2]; - argv2[0] = a1; + VALUE argv2[2]; + argv2[0] = a1; if (a2 == Qundef) { argv2[1] = Qnil; argc = 1; @@ -2118,7 +2118,7 @@ nucomp_convert(VALUE klass, VALUE a1, VALUE a2, int raise) argv2[1] = a2; argc = 2; } - return nucomp_s_new(argc, argv2, klass); + return nucomp_s_new(argc, argv2, klass); } } @@ -2255,9 +2255,9 @@ static VALUE float_arg(VALUE self) { if (isnan(RFLOAT_VALUE(self))) - return self; + return self; if (f_tpositive_p(self)) - return INT2FIX(0); + return INT2FIX(0); return rb_const_get(rb_mMath, id_PI); } @@ -2429,7 +2429,7 @@ Init_Complex(void) * The imaginary unit. */ rb_define_const(rb_cComplex, "I", - f_complex_new_bang2(rb_cComplex, ZERO, ONE)); + f_complex_new_bang2(rb_cComplex, ZERO, ONE)); #if !USE_FLONUM rb_gc_register_mark_object(RFLOAT_0 = DBL2NUM(0.0)); diff --git a/debug.c b/debug.c index d927f72231..81b03c540f 100644 --- a/debug.c +++ b/debug.c @@ -64,23 +64,23 @@ const union { enum ruby_rarray_flags rarray_flags; enum ruby_rarray_consts rarray_consts; enum { - RUBY_FMODE_READABLE = FMODE_READABLE, - RUBY_FMODE_WRITABLE = FMODE_WRITABLE, - RUBY_FMODE_READWRITE = FMODE_READWRITE, - RUBY_FMODE_BINMODE = FMODE_BINMODE, - RUBY_FMODE_SYNC = FMODE_SYNC, - RUBY_FMODE_TTY = FMODE_TTY, - RUBY_FMODE_DUPLEX = FMODE_DUPLEX, - RUBY_FMODE_APPEND = FMODE_APPEND, - RUBY_FMODE_CREATE = FMODE_CREATE, - RUBY_FMODE_NOREVLOOKUP = 0x00000100, - RUBY_FMODE_TRUNC = FMODE_TRUNC, - RUBY_FMODE_TEXTMODE = FMODE_TEXTMODE, - RUBY_FMODE_PREP = 0x00010000, - RUBY_FMODE_SETENC_BY_BOM = FMODE_SETENC_BY_BOM, - RUBY_FMODE_UNIX = 0x00200000, - RUBY_FMODE_INET = 0x00400000, - RUBY_FMODE_INET6 = 0x00800000, + RUBY_FMODE_READABLE = FMODE_READABLE, + RUBY_FMODE_WRITABLE = FMODE_WRITABLE, + RUBY_FMODE_READWRITE = FMODE_READWRITE, + RUBY_FMODE_BINMODE = FMODE_BINMODE, + RUBY_FMODE_SYNC = FMODE_SYNC, + RUBY_FMODE_TTY = FMODE_TTY, + RUBY_FMODE_DUPLEX = FMODE_DUPLEX, + RUBY_FMODE_APPEND = FMODE_APPEND, + RUBY_FMODE_CREATE = FMODE_CREATE, + RUBY_FMODE_NOREVLOOKUP = 0x00000100, + RUBY_FMODE_TRUNC = FMODE_TRUNC, + RUBY_FMODE_TEXTMODE = FMODE_TEXTMODE, + RUBY_FMODE_PREP = 0x00010000, + RUBY_FMODE_SETENC_BY_BOM = FMODE_SETENC_BY_BOM, + RUBY_FMODE_UNIX = 0x00200000, + RUBY_FMODE_INET = 0x00400000, + RUBY_FMODE_INET6 = 0x00800000, RUBY_NODE_TYPESHIFT = NODE_TYPESHIFT, RUBY_NODE_TYPEMASK = NODE_TYPEMASK, @@ -88,9 +88,9 @@ const union { RUBY_NODE_FL_NEWLINE = NODE_FL_NEWLINE } various; union { - enum imemo_type types; - enum {RUBY_IMEMO_MASK = IMEMO_MASK} mask; - struct RIMemo *ptr; + enum imemo_type types; + enum {RUBY_IMEMO_MASK = IMEMO_MASK} mask; + struct RIMemo *ptr; } imemo; struct RSymbol *symbol_ptr; enum vm_call_flag_bits vm_call_flags; @@ -102,9 +102,9 @@ int ruby_debug_print_indent(int level, int debug_level, int indent_level) { if (level < debug_level) { - fprintf(stderr, "%*s", indent_level, ""); - fflush(stderr); - return TRUE; + fprintf(stderr, "%*s", indent_level, ""); + fflush(stderr); + return TRUE; } return FALSE; } @@ -124,11 +124,11 @@ VALUE ruby_debug_print_value(int level, int debug_level, const char *header, VALUE obj) { if (level < debug_level) { - char buff[0x100]; - rb_raw_obj_info(buff, 0x100, obj); + char buff[0x100]; + rb_raw_obj_info(buff, 0x100, obj); - fprintf(stderr, "DBG> %s: %s\n", header, buff); - fflush(stderr); + fprintf(stderr, "DBG> %s: %s\n", header, buff); + fflush(stderr); } return obj; } @@ -143,8 +143,8 @@ ID ruby_debug_print_id(int level, int debug_level, const char *header, ID id) { if (level < debug_level) { - fprintf(stderr, "DBG> %s: %s\n", header, rb_id2name(id)); - fflush(stderr); + fprintf(stderr, "DBG> %s: %s\n", header, rb_id2name(id)); + fflush(stderr); } return id; } @@ -153,8 +153,8 @@ NODE * ruby_debug_print_node(int level, int debug_level, const char *header, const NODE *node) { if (level < debug_level) { - fprintf(stderr, "DBG> %s: %s (%u)\n", header, - ruby_node_name(nd_type(node)), nd_line(node)); + fprintf(stderr, "DBG> %s: %s (%u)\n", header, + ruby_node_name(nd_type(node)), nd_line(node)); } return (NODE *)node; } @@ -184,11 +184,11 @@ ruby_env_debug_option(const char *str, int len, void *arg) size_t retlen; unsigned long n; #define SET_WHEN(name, var, val) do { \ - if (len == sizeof(name) - 1 && \ - strncmp(str, (name), len) == 0) { \ - (var) = (val); \ - return 1; \ - } \ + if (len == sizeof(name) - 1 && \ + strncmp(str, (name), len) == 0) { \ + (var) = (val); \ + return 1; \ + } \ } while (0) #define NAME_MATCH_VALUE(name) \ ((size_t)len >= sizeof(name)-1 && \ @@ -197,24 +197,24 @@ ruby_env_debug_option(const char *str, int len, void *arg) (str[sizeof(name)-1] == '=' && \ (str += sizeof(name), len -= sizeof(name), 1)))) #define SET_UINT(val) do { \ - n = ruby_scan_digits(str, len, 10, &retlen, &ov); \ - if (!ov && retlen) { \ - val = (unsigned int)n; \ - } \ - str += retlen; \ - len -= retlen; \ + n = ruby_scan_digits(str, len, 10, &retlen, &ov); \ + if (!ov && retlen) { \ + val = (unsigned int)n; \ + } \ + str += retlen; \ + len -= retlen; \ } while (0) #define SET_UINT_LIST(name, vals, num) do { \ - int i; \ - for (i = 0; i < (num); ++i) { \ - SET_UINT((vals)[i]); \ - if (!len || *str != ':') break; \ - ++str; \ - --len; \ - } \ - if (len > 0) { \ - fprintf(stderr, "ignored "name" option: `%.*s'\n", len, str); \ - } \ + int i; \ + for (i = 0; i < (num); ++i) { \ + SET_UINT((vals)[i]); \ + if (!len || *str != ':') break; \ + ++str; \ + --len; \ + } \ + if (len > 0) { \ + fprintf(stderr, "ignored "name" option: `%.*s'\n", len, str); \ + } \ } while (0) #define SET_WHEN_UINT(name, vals, num, req) \ if (NAME_MATCH_VALUE(name)) SET_UINT_LIST(name, vals, num); @@ -223,9 +223,9 @@ ruby_env_debug_option(const char *str, int len, void *arg) SET_WHEN("core", ruby_enable_coredump, 1); SET_WHEN("ci", ruby_on_ci, 1); if (NAME_MATCH_VALUE("rgengc")) { - if (!len) ruby_rgengc_debug = 1; - else SET_UINT_LIST("rgengc", &ruby_rgengc_debug, 1); - return 1; + if (!len) ruby_rgengc_debug = 1; + else SET_UINT_LIST("rgengc", &ruby_rgengc_debug, 1); + return 1; } #if defined _WIN32 # if RUBY_MSVCRT_VERSION >= 80 @@ -234,9 +234,9 @@ ruby_env_debug_option(const char *str, int len, void *arg) #endif #if defined _WIN32 || defined __CYGWIN__ if (NAME_MATCH_VALUE("codepage")) { - if (!len) fprintf(stderr, "missing codepage argument"); - else SET_UINT_LIST("codepage", ruby_w32_codepage, numberof(ruby_w32_codepage)); - return 1; + if (!len) fprintf(stderr, "missing codepage argument"); + else SET_UINT_LIST("codepage", ruby_w32_codepage, numberof(ruby_w32_codepage)); + return 1; } #endif return 0; @@ -246,7 +246,7 @@ static void set_debug_option(const char *str, int len, void *arg) { if (!ruby_env_debug_option(str, len, arg)) { - fprintf(stderr, "unexpected debug option: %.*s\n", len, str); + fprintf(stderr, "unexpected debug option: %.*s\n", len, str); } } diff --git a/debug_counter.c b/debug_counter.c index 1569b0e9fb..0fd0e20c6d 100644 --- a/debug_counter.c +++ b/debug_counter.c @@ -103,13 +103,13 @@ rb_debug_counter_show_results(const char *msg) setlocale(LC_NUMERIC, ""); if (env == NULL || strcmp("1", env) != 0) { - int i; + int i; fprintf(stderr, "[RUBY_DEBUG_COUNTER]\t%d %s\n", getpid(), msg); - for (i=0; i 0) { - if (!ISASCII(*ptr)) return 1; - ptr++; - --len; + if (!ISASCII(*ptr)) return 1; + ptr++; + --len; } return 0; } @@ -254,53 +254,53 @@ bracket( if (p >= pend) return NULL; if (*p == '!' || *p == '^') { - not = 1; - p++; + not = 1; + p++; } while (*p != ']') { - const char *t1 = p; - if (escape && *t1 == '\\') - t1++; - if (!*t1) - return NULL; - p = t1 + (r = rb_enc_mbclen(t1, pend, enc)); - if (p >= pend) return NULL; - if (p[0] == '-' && p[1] != ']') { - const char *t2 = p + 1; - int r2; - if (escape && *t2 == '\\') - t2++; - if (!*t2) - return NULL; - p = t2 + (r2 = rb_enc_mbclen(t2, pend, enc)); - if (ok) continue; - if ((r <= (send-s) && memcmp(t1, s, r) == 0) || - (r2 <= (send-s) && memcmp(t2, s, r2) == 0)) { - ok = 1; - continue; - } - c1 = rb_enc_codepoint(s, send, enc); - if (nocase) c1 = rb_enc_toupper(c1, enc); - c2 = rb_enc_codepoint(t1, pend, enc); - if (nocase) c2 = rb_enc_toupper(c2, enc); - if (c1 < c2) continue; - c2 = rb_enc_codepoint(t2, pend, enc); - if (nocase) c2 = rb_enc_toupper(c2, enc); - if (c1 > c2) continue; - } - else { - if (ok) continue; - if (r <= (send-s) && memcmp(t1, s, r) == 0) { - ok = 1; - continue; - } - if (!nocase) continue; - c1 = rb_enc_toupper(rb_enc_codepoint(s, send, enc), enc); - c2 = rb_enc_toupper(rb_enc_codepoint(p, pend, enc), enc); - if (c1 != c2) continue; - } - ok = 1; + const char *t1 = p; + if (escape && *t1 == '\\') + t1++; + if (!*t1) + return NULL; + p = t1 + (r = rb_enc_mbclen(t1, pend, enc)); + if (p >= pend) return NULL; + if (p[0] == '-' && p[1] != ']') { + const char *t2 = p + 1; + int r2; + if (escape && *t2 == '\\') + t2++; + if (!*t2) + return NULL; + p = t2 + (r2 = rb_enc_mbclen(t2, pend, enc)); + if (ok) continue; + if ((r <= (send-s) && memcmp(t1, s, r) == 0) || + (r2 <= (send-s) && memcmp(t2, s, r2) == 0)) { + ok = 1; + continue; + } + c1 = rb_enc_codepoint(s, send, enc); + if (nocase) c1 = rb_enc_toupper(c1, enc); + c2 = rb_enc_codepoint(t1, pend, enc); + if (nocase) c2 = rb_enc_toupper(c2, enc); + if (c1 < c2) continue; + c2 = rb_enc_codepoint(t2, pend, enc); + if (nocase) c2 = rb_enc_toupper(c2, enc); + if (c1 > c2) continue; + } + else { + if (ok) continue; + if (r <= (send-s) && memcmp(t1, s, r) == 0) { + ok = 1; + continue; + } + if (!nocase) continue; + c1 = rb_enc_toupper(rb_enc_codepoint(s, send, enc), enc); + c2 = rb_enc_toupper(rb_enc_codepoint(p, pend, enc), enc); + if (c1 != c2) continue; + } + ok = 1; } return ok == not ? NULL : (char *)p + 1; @@ -338,72 +338,72 @@ fnmatch_helper( int r; if (period && *s == '.' && *UNESCAPE(p) != '.') /* leading period */ - RETURN(FNM_NOMATCH); + RETURN(FNM_NOMATCH); while (1) { - switch (*p) { - case '*': - do { p++; } while (*p == '*'); - if (ISEND(UNESCAPE(p))) { - p = UNESCAPE(p); - RETURN(0); - } - if (ISEND(s)) - RETURN(FNM_NOMATCH); - ptmp = p; - stmp = s; - continue; + switch (*p) { + case '*': + do { p++; } while (*p == '*'); + if (ISEND(UNESCAPE(p))) { + p = UNESCAPE(p); + RETURN(0); + } + if (ISEND(s)) + RETURN(FNM_NOMATCH); + ptmp = p; + stmp = s; + continue; - case '?': - if (ISEND(s)) - RETURN(FNM_NOMATCH); - p++; - Inc(s, send, enc); - continue; + case '?': + if (ISEND(s)) + RETURN(FNM_NOMATCH); + p++; + Inc(s, send, enc); + continue; - case '[': { - const char *t; - if (ISEND(s)) - RETURN(FNM_NOMATCH); - if ((t = bracket(p + 1, pend, s, send, flags, enc)) != 0) { - p = t; - Inc(s, send, enc); - continue; - } - goto failed; - } - } + case '[': { + const char *t; + if (ISEND(s)) + RETURN(FNM_NOMATCH); + if ((t = bracket(p + 1, pend, s, send, flags, enc)) != 0) { + p = t; + Inc(s, send, enc); + continue; + } + goto failed; + } + } - /* ordinary */ - p = UNESCAPE(p); - if (ISEND(s)) - RETURN(ISEND(p) ? 0 : FNM_NOMATCH); - if (ISEND(p)) - goto failed; - r = rb_enc_precise_mbclen(p, pend, enc); - if (!MBCLEN_CHARFOUND_P(r)) - goto failed; - if (r <= (send-s) && memcmp(p, s, r) == 0) { - p += r; - s += r; - continue; - } - if (!nocase) goto failed; - if (rb_enc_toupper(rb_enc_codepoint(p, pend, enc), enc) != - rb_enc_toupper(rb_enc_codepoint(s, send, enc), enc)) - goto failed; - p += r; - Inc(s, send, enc); - continue; + /* ordinary */ + p = UNESCAPE(p); + if (ISEND(s)) + RETURN(ISEND(p) ? 0 : FNM_NOMATCH); + if (ISEND(p)) + goto failed; + r = rb_enc_precise_mbclen(p, pend, enc); + if (!MBCLEN_CHARFOUND_P(r)) + goto failed; + if (r <= (send-s) && memcmp(p, s, r) == 0) { + p += r; + s += r; + continue; + } + if (!nocase) goto failed; + if (rb_enc_toupper(rb_enc_codepoint(p, pend, enc), enc) != + rb_enc_toupper(rb_enc_codepoint(s, send, enc), enc)) + goto failed; + p += r; + Inc(s, send, enc); + continue; failed: /* try next '*' position */ - if (ptmp && stmp) { - p = ptmp; - Inc(stmp, send, enc); /* !ISEND(*stmp) */ - s = stmp; - continue; - } - RETURN(FNM_NOMATCH); + if (ptmp && stmp) { + p = ptmp; + Inc(stmp, send, enc); /* !ISEND(*stmp) */ + s = stmp; + continue; + } + RETURN(FNM_NOMATCH); } } @@ -424,37 +424,37 @@ fnmatch( const char *stmp = 0; if (pathname) { - while (1) { - if (p[0] == '*' && p[1] == '*' && p[2] == '/') { - do { p += 3; } while (p[0] == '*' && p[1] == '*' && p[2] == '/'); - ptmp = p; - stmp = s; - } - if (fnmatch_helper(&p, &s, flags, enc) == 0) { - while (*s && *s != '/') Inc(s, send, enc); - if (*p && *s) { - p++; - s++; - continue; - } - if (!*p && !*s) - return 0; - } - /* failed : try next recursion */ - if (ptmp && stmp && !(period && *stmp == '.')) { - while (*stmp && *stmp != '/') Inc(stmp, send, enc); - if (*stmp) { - p = ptmp; - stmp++; - s = stmp; - continue; - } - } - return FNM_NOMATCH; - } + while (1) { + if (p[0] == '*' && p[1] == '*' && p[2] == '/') { + do { p += 3; } while (p[0] == '*' && p[1] == '*' && p[2] == '/'); + ptmp = p; + stmp = s; + } + if (fnmatch_helper(&p, &s, flags, enc) == 0) { + while (*s && *s != '/') Inc(s, send, enc); + if (*p && *s) { + p++; + s++; + continue; + } + if (!*p && !*s) + return 0; + } + /* failed : try next recursion */ + if (ptmp && stmp && !(period && *stmp == '.')) { + while (*stmp && *stmp != '/') Inc(stmp, send, enc); + if (*stmp) { + p = ptmp; + stmp++; + s = stmp; + continue; + } + } + return FNM_NOMATCH; + } } else - return fnmatch_helper(&p, &s, flags, enc); + return fnmatch_helper(&p, &s, flags, enc); } VALUE rb_cDir; @@ -520,14 +520,14 @@ static DIR * opendir_without_gvl(const char *path) { if (vm_initialized) { - union { const void *in; void *out; } u; + union { const void *in; void *out; } u; - u.in = path; + u.in = path; - return rb_thread_call_without_gvl(nogvl_opendir, u.out, RUBY_UBF_IO, 0); + return rb_thread_call_without_gvl(nogvl_opendir, u.out, RUBY_UBF_IO, 0); } else - return opendir(path); + return opendir(path); } static VALUE @@ -551,23 +551,23 @@ dir_initialize(rb_execution_context_t *ec, VALUE dir, VALUE dirname, VALUE enc) path = RSTRING_PTR(dirname); dp->dir = opendir_without_gvl(path); if (dp->dir == NULL) { - int e = errno; - if (rb_gc_for_fd(e)) { - dp->dir = opendir_without_gvl(path); - } + int e = errno; + if (rb_gc_for_fd(e)) { + dp->dir = opendir_without_gvl(path); + } #ifdef HAVE_GETATTRLIST - else if (e == EIO) { - u_int32_t attrbuf[1]; - struct attrlist al = {ATTR_BIT_MAP_COUNT, 0}; - if (getattrlist(path, &al, attrbuf, sizeof(attrbuf), FSOPT_NOFOLLOW) == 0) { - dp->dir = opendir_without_gvl(path); - } - } + else if (e == EIO) { + u_int32_t attrbuf[1]; + struct attrlist al = {ATTR_BIT_MAP_COUNT, 0}; + if (getattrlist(path, &al, attrbuf, sizeof(attrbuf), FSOPT_NOFOLLOW) == 0) { + dp->dir = opendir_without_gvl(path); + } + } #endif - if (dp->dir == NULL) { - RB_GC_GUARD(dirname); - rb_syserr_fail_path(e, orig); - } + if (dp->dir == NULL) { + RB_GC_GUARD(dirname); + rb_syserr_fail_path(e, orig); + } } RB_OBJ_WRITE(dir, &dp->path, orig); @@ -630,12 +630,12 @@ dir_inspect(VALUE dir) TypedData_Get_Struct(dir, struct dir_data, &dir_data_type, dirp); if (!NIL_P(dirp->path)) { - VALUE str = rb_str_new_cstr("#<"); - rb_str_append(str, rb_class_name(CLASS_OF(dir))); - rb_str_cat2(str, ":"); - rb_str_append(str, dirp->path); - rb_str_cat2(str, ">"); - return str; + VALUE str = rb_str_new_cstr("#<"); + rb_str_append(str, rb_class_name(CLASS_OF(dir))); + rb_str_cat2(str, ":"); + rb_str_append(str, dirp->path); + rb_str_cat2(str, ">"); + return str; } return rb_funcallv(dir, idTo_s, 0, 0); } @@ -677,7 +677,7 @@ dir_fileno(VALUE dir) GetDIR(dir, dirp); fd = dirfd(dirp->dir); if (fd == -1) - rb_sys_fail("dirfd"); + rb_sys_fail("dirfd"); return INT2NUM(fd); } #else @@ -712,9 +712,9 @@ fundamental_encoding_p(rb_encoding *enc) case ENCINDEX_ASCII_8BIT: case ENCINDEX_US_ASCII: case ENCINDEX_UTF_8: - return TRUE; + return TRUE; default: - return FALSE; + return FALSE; } } # define READDIR(dir, enc) rb_w32_readdir((dir), (enc)) @@ -731,11 +731,11 @@ to_be_skipped(const struct dirent *dp) #ifdef HAVE_DIRENT_NAMLEN switch (NAMLEN(dp)) { case 2: - if (name[1] != '.') return FALSE; + if (name[1] != '.') return FALSE; case 1: - return TRUE; + return TRUE; default: - break; + break; } #else if (!name[1]) return TRUE; @@ -766,12 +766,12 @@ dir_read(VALUE dir) GetDIR(dir, dirp); errno = 0; if ((dp = READDIR(dirp->dir, dirp->enc)) != NULL) { - return rb_external_str_new_with_enc(dp->d_name, NAMLEN(dp), dirp->enc); + return rb_external_str_new_with_enc(dp->d_name, NAMLEN(dp), dirp->enc); } else { - int e = errno; - if (e != 0) rb_syserr_fail(e, 0); - return Qnil; /* end of stream */ + int e = errno; + if (e != 0) rb_syserr_fail(e, 0); + return Qnil; /* end of stream */ } } @@ -821,23 +821,23 @@ dir_each_entry(VALUE dir, VALUE (*each)(VALUE, VALUE), VALUE arg, int children_o rewinddir(dirp->dir); IF_NORMALIZE_UTF8PATH(norm_p = need_normalization(dirp->dir, RSTRING_PTR(dirp->path))); while ((dp = READDIR(dirp->dir, dirp->enc)) != NULL) { - const char *name = dp->d_name; - size_t namlen = NAMLEN(dp); - VALUE path; + const char *name = dp->d_name; + size_t namlen = NAMLEN(dp); + VALUE path; - if (children_only && name[0] == '.') { - if (namlen == 1) continue; /* current directory */ - if (namlen == 2 && name[1] == '.') continue; /* parent directory */ - } + if (children_only && name[0] == '.') { + if (namlen == 1) continue; /* current directory */ + if (namlen == 2 && name[1] == '.') continue; /* parent directory */ + } #if NORMALIZE_UTF8PATH - if (norm_p && has_nonascii(name, namlen) && - !NIL_P(path = rb_str_normalize_ospath(name, namlen))) { - path = rb_external_str_with_enc(path, dirp->enc); - } - else + if (norm_p && has_nonascii(name, namlen) && + !NIL_P(path = rb_str_normalize_ospath(name, namlen))) { + path = rb_external_str_with_enc(path, dirp->enc); + } + else #endif - path = rb_external_str_new_with_enc(name, namlen, dirp->enc); - (*each)(arg, path); + path = rb_external_str_new_with_enc(name, namlen, dirp->enc); + (*each)(arg, path); } return dir; } @@ -978,7 +978,7 @@ static void dir_chdir(VALUE path) { if (chdir(RSTRING_PTR(path)) < 0) - rb_sys_fail_path(path); + rb_sys_fail_path(path); } static int chdir_blocking = 0; @@ -997,7 +997,7 @@ chdir_yield(VALUE v) args->done = TRUE; chdir_blocking++; if (NIL_P(chdir_thread)) - chdir_thread = rb_thread_current(); + chdir_thread = rb_thread_current(); return rb_yield(args->new_path); } @@ -1006,10 +1006,10 @@ chdir_restore(VALUE v) { struct chdir_data *args = (void *)v; if (args->done) { - chdir_blocking--; - if (chdir_blocking == 0) - chdir_thread = Qnil; - dir_chdir(args->old_path); + chdir_blocking--; + if (chdir_blocking == 0) + chdir_thread = Qnil; + dir_chdir(args->old_path); } return Qnil; } @@ -1063,35 +1063,35 @@ dir_s_chdir(int argc, VALUE *argv, VALUE obj) path = rb_str_encode_ospath(rb_get_path(argv[0])); } else { - const char *dist = getenv("HOME"); - if (!dist) { - dist = getenv("LOGDIR"); - if (!dist) rb_raise(rb_eArgError, "HOME/LOGDIR not set"); - } - path = rb_str_new2(dist); + const char *dist = getenv("HOME"); + if (!dist) { + dist = getenv("LOGDIR"); + if (!dist) rb_raise(rb_eArgError, "HOME/LOGDIR not set"); + } + path = rb_str_new2(dist); } if (chdir_blocking > 0) { - if (rb_thread_current() != chdir_thread) + if (rb_thread_current() != chdir_thread) rb_raise(rb_eRuntimeError, "conflicting chdir during another chdir block"); if (!rb_block_given_p()) rb_warn("conflicting chdir during another chdir block"); } if (rb_block_given_p()) { - struct chdir_data args; + struct chdir_data args; - args.old_path = rb_str_encode_ospath(rb_dir_getwd()); - args.new_path = path; - args.done = FALSE; - return rb_ensure(chdir_yield, (VALUE)&args, chdir_restore, (VALUE)&args); + args.old_path = rb_str_encode_ospath(rb_dir_getwd()); + args.new_path = path; + args.done = FALSE; + return rb_ensure(chdir_yield, (VALUE)&args, chdir_restore, (VALUE)&args); } else { - char *p = RSTRING_PTR(path); - int r = (int)(VALUE)rb_thread_call_without_gvl(nogvl_chdir, p, - RUBY_UBF_IO, 0); - if (r < 0) - rb_sys_fail_path(path); + char *p = RSTRING_PTR(path); + int r = (int)(VALUE)rb_thread_call_without_gvl(nogvl_chdir, p, + RUBY_UBF_IO, 0); + if (r < 0) + rb_sys_fail_path(path); } return INT2FIX(0); @@ -1131,12 +1131,12 @@ rb_dir_getwd(void) switch (fsenc) { case ENCINDEX_US_ASCII: - fsenc = ENCINDEX_ASCII_8BIT; + fsenc = ENCINDEX_ASCII_8BIT; case ENCINDEX_ASCII_8BIT: - break; + break; #if defined _WIN32 || defined __APPLE__ default: - return rb_str_conv_enc(cwd, NULL, fs); + return rb_str_conv_enc(cwd, NULL, fs); #endif } return rb_enc_associate_index(cwd, fsenc); @@ -1174,8 +1174,8 @@ check_dirname(VALUE dir) pend = path + len; pend = rb_enc_path_end(rb_enc_path_skip_prefix(path, pend, enc), pend, enc); if (pend - path < len) { - d = rb_str_subseq(d, 0, pend - path); - StringValueCStr(d); + d = rb_str_subseq(d, 0, pend - path); + StringValueCStr(d); } return rb_str_encode_ospath(d); } @@ -1195,7 +1195,7 @@ dir_s_chroot(VALUE dir, VALUE path) { path = check_dirname(path); if (chroot(RSTRING_PTR(path)) == -1) - rb_sys_fail_path(path); + rb_sys_fail_path(path); return INT2FIX(0); } @@ -1238,17 +1238,17 @@ dir_s_mkdir(int argc, VALUE *argv, VALUE obj) int r; if (rb_scan_args(argc, argv, "11", &path, &vmode) == 2) { - m.mode = NUM2MODET(vmode); + m.mode = NUM2MODET(vmode); } else { - m.mode = 0777; + m.mode = 0777; } path = check_dirname(path); m.path = RSTRING_PTR(path); r = (int)(VALUE)rb_thread_call_without_gvl(nogvl_mkdir, &m, RUBY_UBF_IO, 0); if (r < 0) - rb_sys_fail_path(path); + rb_sys_fail_path(path); return INT2FIX(0); } @@ -1280,7 +1280,7 @@ dir_s_rmdir(VALUE obj, VALUE dir) p = RSTRING_PTR(dir); r = (int)(VALUE)rb_thread_call_without_gvl(nogvl_rmdir, (void *)p, RUBY_UBF_IO, 0); if (r < 0) - rb_sys_fail_path(dir); + rb_sys_fail_path(dir); return INT2FIX(0); } @@ -1386,8 +1386,8 @@ at_subpath(int fd, size_t baselen, const char *path) { #if USE_OPENDIR_AT if (fd != (int)AT_FDCWD && baselen > 0) { - path += baselen; - if (*path == '/') ++path; + path += baselen; + if (*path == '/') ++path; } #endif return *path ? path : "."; @@ -1403,7 +1403,7 @@ do_stat(int fd, size_t baselen, const char *path, struct stat *pst, int flags, r int ret = STAT(path, pst); #endif if (ret < 0 && !to_be_ignored(errno)) - sys_warning(path, enc); + sys_warning(path, enc); return ret; } @@ -1418,7 +1418,7 @@ do_lstat(int fd, size_t baselen, const char *path, struct stat *pst, int flags, int ret = lstat(path, pst); #endif if (ret < 0 && !to_be_ignored(errno)) - sys_warning(path, enc); + sys_warning(path, enc); return ret; } @@ -1443,9 +1443,9 @@ static int gc_for_fd_with_gvl(int e) { if (vm_initialized) - return (int)(VALUE)rb_thread_call_with_gvl(with_gvl_gc_for_fd, &e); + return (int)(VALUE)rb_thread_call_with_gvl(with_gvl_gc_for_fd, &e); else - return RBOOL(rb_gc_for_fd(e)); + return RBOOL(rb_gc_for_fd(e)); } static void * @@ -1457,32 +1457,32 @@ nogvl_opendir_at(void *ptr) #if USE_OPENDIR_AT const int opendir_flags = (O_RDONLY|O_CLOEXEC| # ifdef O_DIRECTORY - O_DIRECTORY| + O_DIRECTORY| # endif /* O_DIRECTORY */ - 0); + 0); int fd = openat(oaa->basefd, oaa->path, opendir_flags); dirp = fd >= 0 ? fdopendir(fd) : 0; if (!dirp) { - int e = errno; + int e = errno; - switch (gc_for_fd_with_gvl(e)) { - default: - if (fd < 0) fd = openat(oaa->basefd, oaa->path, opendir_flags); - if (fd >= 0) dirp = fdopendir(fd); - if (dirp) return dirp; + switch (gc_for_fd_with_gvl(e)) { + default: + if (fd < 0) fd = openat(oaa->basefd, oaa->path, opendir_flags); + if (fd >= 0) dirp = fdopendir(fd); + if (dirp) return dirp; - e = errno; - /* fallthrough*/ - case 0: - if (fd >= 0) close(fd); - errno = e; - } + e = errno; + /* fallthrough*/ + case 0: + if (fd >= 0) close(fd); + errno = e; + } } #else /* !USE_OPENDIR_AT */ dirp = opendir(oaa->path); if (!dirp && gc_for_fd_with_gvl(errno)) - dirp = opendir(oaa->path); + dirp = opendir(oaa->path); #endif /* !USE_OPENDIR_AT */ return dirp; @@ -1497,37 +1497,37 @@ opendir_at(int basefd, const char *path) oaa.path = path; if (vm_initialized) - return rb_thread_call_without_gvl(nogvl_opendir_at, &oaa, RUBY_UBF_IO, 0); + return rb_thread_call_without_gvl(nogvl_opendir_at, &oaa, RUBY_UBF_IO, 0); else - return nogvl_opendir_at(&oaa); + return nogvl_opendir_at(&oaa); } static DIR * do_opendir(const int basefd, size_t baselen, const char *path, int flags, rb_encoding *enc, - ruby_glob_errfunc *errfunc, VALUE arg, int *status) + ruby_glob_errfunc *errfunc, VALUE arg, int *status) { DIR *dirp; #ifdef _WIN32 VALUE tmp = 0; if (!fundamental_encoding_p(enc)) { - tmp = rb_enc_str_new(path, strlen(path), enc); - tmp = rb_str_encode_ospath(tmp); - path = RSTRING_PTR(tmp); + tmp = rb_enc_str_new(path, strlen(path), enc); + tmp = rb_str_encode_ospath(tmp); + path = RSTRING_PTR(tmp); } #endif dirp = opendir_at(basefd, at_subpath(basefd, baselen, path)); if (!dirp) { - int e = errno; + int e = errno; - *status = 0; - if (!to_be_ignored(e)) { - if (errfunc) { - *status = (*errfunc)(path, arg, enc, e); - } - else { - sys_warning(path, enc); - } - } + *status = 0; + if (!to_be_ignored(e)) { + if (errfunc) { + *status = (*errfunc)(path, arg, enc, e); + } + else { + sys_warning(path, enc); + } + } } #ifdef _WIN32 if (tmp) rb_str_resize(tmp, 0); /* GC guard */ @@ -1550,37 +1550,37 @@ has_magic(const char *p, const char *pend, int flags, rb_encoding *enc) register char c; while (p < pend && (c = *p++) != 0) { - switch (c) { - case '{': - return BRACE; + switch (c) { + case '{': + return BRACE; - case '*': - case '?': - case '[': - hasmagical = 1; - break; + case '*': + case '?': + case '[': + hasmagical = 1; + break; - case '\\': - if (escape && p++ >= pend) - continue; - break; + case '\\': + if (escape && p++ >= pend) + continue; + break; #ifdef _WIN32 - case '.': - break; + case '.': + break; - case '~': - hasalpha = 1; - break; + case '~': + hasalpha = 1; + break; #endif - default: - if (IS_WIN32 || ISALPHA(c)) { - hasalpha = 1; - } - break; - } + default: + if (IS_WIN32 || ISALPHA(c)) { + hasalpha = 1; + } + break; + } - p = Next(p-1, pend, enc); + p = Next(p-1, pend, enc); } return hasmagical ? MAGICAL : hasalpha ? ALPHA : PLAIN; @@ -1596,33 +1596,33 @@ find_dirsep(const char *p, const char *pend, int flags, rb_encoding *enc) int open = 0; while ((c = *p++) != 0) { - switch (c) { - case '[': - open = 1; - continue; - case ']': - open = 0; - continue; + switch (c) { + case '[': + open = 1; + continue; + case ']': + open = 0; + continue; - case '{': - open = 1; - continue; - case '}': - open = 0; - continue; + case '{': + open = 1; + continue; + case '}': + open = 0; + continue; - case '/': - if (!open) - return (char *)p-1; - continue; + case '/': + if (!open) + return (char *)p-1; + continue; - case '\\': - if (escape && !(c = *p++)) - return (char *)p-1; - continue; - } + case '\\': + if (escape && !(c = *p++)) + return (char *)p-1; + continue; + } - p = Next(p-1, pend, enc); + p = Next(p-1, pend, enc); } return (char *)p-1; @@ -1636,20 +1636,20 @@ remove_backslashes(char *p, register const char *pend, rb_encoding *enc) char *s = p; while (*p) { - if (*p == '\\') { - if (t != s) - memmove(t, s, p - s); - t += p - s; - s = ++p; - if (!*p) break; - } - Inc(p, pend, enc); + if (*p == '\\') { + if (t != s) + memmove(t, s, p - s); + t += p - s; + s = ++p; + if (!*p) break; + } + Inc(p, pend, enc); } while (*p++); if (t != s) - memmove(t, s, p - s); /* move '\0' too */ + memmove(t, s, p - s); /* move '\0' too */ return p; } @@ -1670,49 +1670,49 @@ glob_make_pattern(const char *p, const char *e, int flags, rb_encoding *enc) int recursive = 0; while (p < e && *p) { - tmp = GLOB_ALLOC(struct glob_pattern); - if (!tmp) goto error; - if (p + 2 < e && p[0] == '*' && p[1] == '*' && p[2] == '/') { - /* fold continuous RECURSIVEs (needed in glob_helper) */ - do { p += 3; while (*p == '/') p++; } while (p[0] == '*' && p[1] == '*' && p[2] == '/'); - tmp->type = RECURSIVE; - tmp->str = 0; - dirsep = 1; - recursive = 1; - } - else { - const char *m = find_dirsep(p, e, flags, enc); - const enum glob_pattern_type magic = has_magic(p, m, flags, enc); - const enum glob_pattern_type non_magic = (USE_NAME_ON_FS || FNM_SYSCASE) ? PLAIN : ALPHA; - char *buf; + tmp = GLOB_ALLOC(struct glob_pattern); + if (!tmp) goto error; + if (p + 2 < e && p[0] == '*' && p[1] == '*' && p[2] == '/') { + /* fold continuous RECURSIVEs (needed in glob_helper) */ + do { p += 3; while (*p == '/') p++; } while (p[0] == '*' && p[1] == '*' && p[2] == '/'); + tmp->type = RECURSIVE; + tmp->str = 0; + dirsep = 1; + recursive = 1; + } + else { + const char *m = find_dirsep(p, e, flags, enc); + const enum glob_pattern_type magic = has_magic(p, m, flags, enc); + const enum glob_pattern_type non_magic = (USE_NAME_ON_FS || FNM_SYSCASE) ? PLAIN : ALPHA; + char *buf; - if (!(FNM_SYSCASE || magic > non_magic) && !recursive && *m) { - const char *m2; - while (has_magic(m+1, m2 = find_dirsep(m+1, e, flags, enc), flags, enc) <= non_magic && - *m2) { - m = m2; - } - } - buf = GLOB_ALLOC_N(char, m-p+1); - if (!buf) { - GLOB_FREE(tmp); - goto error; - } - memcpy(buf, p, m-p); - buf[m-p] = '\0'; - tmp->type = magic > MAGICAL ? MAGICAL : magic > non_magic ? magic : PLAIN; - tmp->str = buf; - if (*m) { - dirsep = 1; - p = m + 1; - } - else { - dirsep = 0; - p = m; - } - } - *tail = tmp; - tail = &tmp->next; + if (!(FNM_SYSCASE || magic > non_magic) && !recursive && *m) { + const char *m2; + while (has_magic(m+1, m2 = find_dirsep(m+1, e, flags, enc), flags, enc) <= non_magic && + *m2) { + m = m2; + } + } + buf = GLOB_ALLOC_N(char, m-p+1); + if (!buf) { + GLOB_FREE(tmp); + goto error; + } + memcpy(buf, p, m-p); + buf[m-p] = '\0'; + tmp->type = magic > MAGICAL ? MAGICAL : magic > non_magic ? magic : PLAIN; + tmp->str = buf; + if (*m) { + dirsep = 1; + p = m + 1; + } + else { + dirsep = 0; + p = m; + } + } + *tail = tmp; + tail = &tmp->next; } tmp = GLOB_ALLOC(struct glob_pattern); @@ -1736,11 +1736,11 @@ static void glob_free_pattern(struct glob_pattern *list) { while (list) { - struct glob_pattern *tmp = list; - list = list->next; - if (tmp->str) - GLOB_FREE(tmp->str); - GLOB_FREE(tmp); + struct glob_pattern *tmp = list; + list = list->next; + if (tmp->str) + GLOB_FREE(tmp->str); + GLOB_FREE(tmp); } } @@ -1752,7 +1752,7 @@ join_path(const char *path, size_t len, int dirsep, const char *name, size_t nam if (!buf) return 0; memcpy(buf, path, len); if (dirsep) { - buf[len++] = '/'; + buf[len++] = '/'; } memcpy(buf+len, name, namlen); buf[len+namlen] = '\0'; @@ -1769,8 +1769,8 @@ static int is_case_sensitive(DIR *dirp, const char *path) { struct { - u_int32_t length; - vol_capabilities_attr_t cap[1]; + u_int32_t length; + vol_capabilities_attr_t cap[1]; } __attribute__((aligned(4), packed)) attrbuf[1]; struct attrlist al = {ATTR_BIT_MAP_COUNT, 0, 0, ATTR_VOL_INFO|ATTR_VOL_CAPABILITIES}; const vol_capabilities_attr_t *const cap = attrbuf[0].cap; @@ -1779,13 +1779,13 @@ is_case_sensitive(DIR *dirp, const char *path) # if defined HAVE_FGETATTRLIST if (fgetattrlist(dirfd(dirp), &al, attrbuf, sizeof(attrbuf), FSOPT_NOFOLLOW)) - return -1; + return -1; # else if (getattrlist(path, &al, attrbuf, sizeof(attrbuf), FSOPT_NOFOLLOW)) - return -1; + return -1; # endif if (!(cap->valid[idx] & mask)) - return -1; + return -1; return (cap->capabilities[idx] & mask) != 0; } @@ -1793,10 +1793,10 @@ static char * replace_real_basename(char *path, long base, rb_encoding *enc, int norm_p, int flags, rb_pathtype_t *type) { struct { - u_int32_t length; - attrreference_t ref[1]; - fsobj_type_t objtype; - char path[MAXPATHLEN * 3]; + u_int32_t length; + attrreference_t ref[1]; + fsobj_type_t objtype; + char path[MAXPATHLEN * 3]; } __attribute__((aligned(4), packed)) attrbuf[1]; struct attrlist al = {ATTR_BIT_MAP_COUNT, 0, ATTR_CMN_NAME|ATTR_CMN_OBJTYPE}; const attrreference_t *const ar = attrbuf[0].ref; @@ -1807,9 +1807,9 @@ replace_real_basename(char *path, long base, rb_encoding *enc, int norm_p, int f *type = path_noent; if (getattrlist(path, &al, attrbuf, sizeof(attrbuf), FSOPT_NOFOLLOW)) { - if (!to_be_ignored(errno)) - sys_warning(path, enc); - return path; + if (!to_be_ignored(errno)) + sys_warning(path, enc); + return path; } switch (attrbuf[0].objtype) { @@ -1821,21 +1821,21 @@ replace_real_basename(char *path, long base, rb_encoding *enc, int norm_p, int f name = (char *)ar + ar->attr_dataoffset; len = (long)ar->attr_length - 1; if (name + len > (char *)attrbuf + sizeof(attrbuf)) - return path; + return path; # if NORMALIZE_UTF8PATH if (norm_p && has_nonascii(name, len)) { - if (!NIL_P(utf8str = rb_str_normalize_ospath(name, len))) { - RSTRING_GETMEM(utf8str, name, len); - } + if (!NIL_P(utf8str = rb_str_normalize_ospath(name, len))) { + RSTRING_GETMEM(utf8str, name, len); + } } # endif tmp = GLOB_REALLOC(path, base + len + 1); if (tmp) { - path = tmp; - memcpy(path + base, name, len); - path[base + len] = '\0'; + path = tmp; + memcpy(path + base, name, len); + path[base + len] = '\0'; } IF_NORMALIZE_UTF8PATH(if (!NIL_P(utf8str)) rb_str_resize(utf8str, 0)); return path; @@ -1856,62 +1856,62 @@ replace_real_basename(char *path, long base, rb_encoding *enc, int norm_p, int f long wlen; int e = 0; if (!fundamental_encoding_p(enc)) { - tmp = rb_enc_str_new_cstr(plainname, enc); - tmp = rb_str_encode_ospath(tmp); - plainname = RSTRING_PTR(tmp); + tmp = rb_enc_str_new_cstr(plainname, enc); + tmp = rb_str_encode_ospath(tmp); + plainname = RSTRING_PTR(tmp); } wplain = rb_w32_mbstr_to_wstr(CP_UTF8, plainname, -1, &wlen); if (tmp) rb_str_resize(tmp, 0); if (!wplain) return path; if (GetFileAttributesExW(wplain, GetFileExInfoStandard, &fa)) { - h = FindFirstFileW(wplain, &fd); - e = rb_w32_map_errno(GetLastError()); + h = FindFirstFileW(wplain, &fd); + e = rb_w32_map_errno(GetLastError()); } if (fa.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) { - if (!rb_w32_reparse_symlink_p(wplain)) - fa.dwFileAttributes &= ~FILE_ATTRIBUTE_REPARSE_POINT; + if (!rb_w32_reparse_symlink_p(wplain)) + fa.dwFileAttributes &= ~FILE_ATTRIBUTE_REPARSE_POINT; } free(wplain); if (h == INVALID_HANDLE_VALUE) { - *type = path_noent; - if (e && !to_be_ignored(e)) { - errno = e; - sys_warning(path, enc); - } - return path; + *type = path_noent; + if (e && !to_be_ignored(e)) { + errno = e; + sys_warning(path, enc); + } + return path; } FindClose(h); *type = - (fa.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) ? path_symlink : - (fa.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? path_directory : - path_regular; + (fa.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) ? path_symlink : + (fa.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? path_directory : + path_regular; if (tmp) { - char *buf; - tmp = rb_w32_conv_from_wchar(fd.cFileName, enc); - wlen = RSTRING_LEN(tmp); - buf = GLOB_REALLOC(path, base + wlen + 1); - if (buf) { - path = buf; - memcpy(path + base, RSTRING_PTR(tmp), wlen); - path[base + wlen] = 0; - } - rb_str_resize(tmp, 0); + char *buf; + tmp = rb_w32_conv_from_wchar(fd.cFileName, enc); + wlen = RSTRING_LEN(tmp); + buf = GLOB_REALLOC(path, base + wlen + 1); + if (buf) { + path = buf; + memcpy(path + base, RSTRING_PTR(tmp), wlen); + path[base + wlen] = 0; + } + rb_str_resize(tmp, 0); } else { - char *utf8filename; - wlen = WideCharToMultiByte(CP_UTF8, 0, fd.cFileName, -1, NULL, 0, NULL, NULL); - utf8filename = GLOB_REALLOC(0, wlen); - if (utf8filename) { - char *buf; - WideCharToMultiByte(CP_UTF8, 0, fd.cFileName, -1, utf8filename, wlen, NULL, NULL); - buf = GLOB_REALLOC(path, base + wlen + 1); - if (buf) { - path = buf; - memcpy(path + base, utf8filename, wlen); - path[base + wlen] = 0; - } - GLOB_FREE(utf8filename); - } + char *utf8filename; + wlen = WideCharToMultiByte(CP_UTF8, 0, fd.cFileName, -1, NULL, 0, NULL, NULL); + utf8filename = GLOB_REALLOC(0, wlen); + if (utf8filename) { + char *buf; + WideCharToMultiByte(CP_UTF8, 0, fd.cFileName, -1, utf8filename, wlen, NULL, NULL); + buf = GLOB_REALLOC(path, base + wlen + 1); + if (buf) { + path = buf; + memcpy(path + base, utf8filename, wlen); + path[base + wlen] = 0; + } + GLOB_FREE(utf8filename); + } } return path; } @@ -2003,7 +2003,7 @@ rb_glob_error(const char *path, VALUE a, const void *enc, int error) #ifdef ENOTCAPABLE case ENOTCAPABLE: #endif - errfunc = glob_func_warning; + errfunc = glob_func_warning; } args.path = path; args.enc = enc; @@ -2027,7 +2027,7 @@ dirent_match(const char *pat, rb_encoding *enc, const char *name, const rb_diren if (fnmatch(pat, enc, name, flags) == 0) return 1; #ifdef _WIN32 if (dp->d_altname && (flags & FNM_SHORTNAME)) { - if (fnmatch(pat, enc, dp->d_altname, flags) == 0) return 1; + if (fnmatch(pat, enc, dp->d_altname, flags) == 0) return 1; } #endif return 0; @@ -2068,39 +2068,39 @@ join_path_from_pattern(struct glob_pattern **beg) size_t path_len = 0; for (p = *beg; p; p = p->next) { - const char *str; - switch (p->type) { - case RECURSIVE: - str = "**"; - break; - case MATCH_DIR: - /* append last slash */ - str = ""; - break; - default: - str = p->str; - if (!str) continue; - } - if (!path) { - path_len = strlen(str); - path = GLOB_ALLOC_N(char, path_len + 1); + const char *str; + switch (p->type) { + case RECURSIVE: + str = "**"; + break; + case MATCH_DIR: + /* append last slash */ + str = ""; + break; + default: + str = p->str; + if (!str) continue; + } + if (!path) { + path_len = strlen(str); + path = GLOB_ALLOC_N(char, path_len + 1); if (path) { memcpy(path, str, path_len); path[path_len] = '\0'; } } else { - size_t len = strlen(str); - char *tmp; - tmp = GLOB_REALLOC(path, path_len + len + 2); - if (tmp) { - path = tmp; - path[path_len++] = '/'; - memcpy(path + path_len, str, len); - path_len += len; - path[path_len] = '\0'; - } - } + size_t len = strlen(str); + char *tmp; + tmp = GLOB_REALLOC(path, path_len + len + 2); + if (tmp) { + path = tmp; + path[path_len++] = '/'; + memcpy(path + path_len, str, len); + path_len += len; + path[path_len] = '\0'; + } + } } return path; } @@ -2108,7 +2108,7 @@ join_path_from_pattern(struct glob_pattern **beg) static int push_caller(const char *path, VALUE val, void *enc); static int ruby_brace_expand(const char *str, int flags, ruby_glob_func *func, VALUE arg, - rb_encoding *enc, VALUE var); + rb_encoding *enc, VALUE var); static const size_t rb_dirent_name_offset = offsetof(rb_dirent_t, d_type) + sizeof(uint8_t); @@ -2216,7 +2216,7 @@ glob_opendir(ruby_glob_entries_t *ent, DIR *dirp, int flags, rb_encoding *enc) ent->sort.entries = newp; } #endif - while ((dp = READDIR(dirp, enc)) != NULL) { + while ((dp = READDIR(dirp, enc)) != NULL) { rb_dirent_t *rdp = dirent_copy(dp, NULL); if (!rdp) { goto nomem; @@ -2288,133 +2288,133 @@ glob_helper( rb_check_stack_overflow(); for (cur = beg; cur < end; ++cur) { - struct glob_pattern *p = *cur; - if (p->type == RECURSIVE) { - recursive = 1; - p = p->next; - } - switch (p->type) { - case PLAIN: - plain = 1; - break; - case ALPHA: + struct glob_pattern *p = *cur; + if (p->type == RECURSIVE) { + recursive = 1; + p = p->next; + } + switch (p->type) { + case PLAIN: + plain = 1; + break; + case ALPHA: #if USE_NAME_ON_FS == USE_NAME_ON_FS_REAL_BASENAME - plain = 1; + plain = 1; #else - magical = 1; + magical = 1; #endif - break; - case BRACE: - if (!recursive) { - brace = 1; - } - break; - case MAGICAL: - magical = 2; - break; - case MATCH_ALL: - match_all = 1; - break; - case MATCH_DIR: - match_dir = 1; - break; - case RECURSIVE: - rb_bug("continuous RECURSIVEs"); - } + break; + case BRACE: + if (!recursive) { + brace = 1; + } + break; + case MAGICAL: + magical = 2; + break; + case MATCH_ALL: + match_all = 1; + break; + case MATCH_DIR: + match_dir = 1; + break; + case RECURSIVE: + rb_bug("continuous RECURSIVEs"); + } } if (brace) { - struct push_glob_args args; - char* brace_path = join_path_from_pattern(beg); - if (!brace_path) return -1; - args.fd = fd; - args.path = path; - args.baselen = baselen; - args.namelen = namelen; - args.dirsep = dirsep; - args.pathtype = pathtype; - args.flags = flags; - args.funcs = funcs; - args.arg = arg; - status = ruby_brace_expand(brace_path, flags, push_caller, (VALUE)&args, enc, Qfalse); - GLOB_FREE(brace_path); - return status; + struct push_glob_args args; + char* brace_path = join_path_from_pattern(beg); + if (!brace_path) return -1; + args.fd = fd; + args.path = path; + args.baselen = baselen; + args.namelen = namelen; + args.dirsep = dirsep; + args.pathtype = pathtype; + args.flags = flags; + args.funcs = funcs; + args.arg = arg; + status = ruby_brace_expand(brace_path, flags, push_caller, (VALUE)&args, enc, Qfalse); + GLOB_FREE(brace_path); + return status; } if (*path) { - if (match_all && pathtype == path_unknown) { - if (do_lstat(fd, baselen, path, &st, flags, enc) == 0) { - pathtype = IFTODT(st.st_mode); - } - else { - pathtype = path_noent; - } - } - if (match_dir && (pathtype == path_unknown || pathtype == path_symlink)) { - if (do_stat(fd, baselen, path, &st, flags, enc) == 0) { - pathtype = IFTODT(st.st_mode); - } - else { - pathtype = path_noent; - } - } - if (match_all && pathtype > path_noent) { - const char *subpath = path + baselen + (baselen && path[baselen] == '/'); - status = glob_call_func(funcs->match, subpath, arg, enc); - if (status) return status; - } - if (match_dir && pathtype == path_directory) { - int seplen = (baselen && path[baselen] == '/'); - const char *subpath = path + baselen + seplen; - char *tmp = join_path(subpath, namelen - seplen, dirsep, "", 0); - if (!tmp) return -1; - status = glob_call_func(funcs->match, tmp, arg, enc); - GLOB_FREE(tmp); - if (status) return status; - } + if (match_all && pathtype == path_unknown) { + if (do_lstat(fd, baselen, path, &st, flags, enc) == 0) { + pathtype = IFTODT(st.st_mode); + } + else { + pathtype = path_noent; + } + } + if (match_dir && (pathtype == path_unknown || pathtype == path_symlink)) { + if (do_stat(fd, baselen, path, &st, flags, enc) == 0) { + pathtype = IFTODT(st.st_mode); + } + else { + pathtype = path_noent; + } + } + if (match_all && pathtype > path_noent) { + const char *subpath = path + baselen + (baselen && path[baselen] == '/'); + status = glob_call_func(funcs->match, subpath, arg, enc); + if (status) return status; + } + if (match_dir && pathtype == path_directory) { + int seplen = (baselen && path[baselen] == '/'); + const char *subpath = path + baselen + seplen; + char *tmp = join_path(subpath, namelen - seplen, dirsep, "", 0); + if (!tmp) return -1; + status = glob_call_func(funcs->match, tmp, arg, enc); + GLOB_FREE(tmp); + if (status) return status; + } } if (pathtype == path_noent) return 0; if (magical || recursive) { - rb_dirent_t *dp; - DIR *dirp; + rb_dirent_t *dp; + DIR *dirp; # if USE_NAME_ON_FS == USE_NAME_ON_FS_BY_FNMATCH - char *plainname = 0; + char *plainname = 0; # endif - IF_NORMALIZE_UTF8PATH(int norm_p); + IF_NORMALIZE_UTF8PATH(int norm_p); # if USE_NAME_ON_FS == USE_NAME_ON_FS_BY_FNMATCH - if (cur + 1 == end && (*cur)->type <= ALPHA) { - plainname = join_path(path, pathlen, dirsep, (*cur)->str, strlen((*cur)->str)); - if (!plainname) return -1; - dirp = do_opendir(fd, basename, plainname, flags, enc, funcs->error, arg, &status); - GLOB_FREE(plainname); - } - else + if (cur + 1 == end && (*cur)->type <= ALPHA) { + plainname = join_path(path, pathlen, dirsep, (*cur)->str, strlen((*cur)->str)); + if (!plainname) return -1; + dirp = do_opendir(fd, basename, plainname, flags, enc, funcs->error, arg, &status); + GLOB_FREE(plainname); + } + else # else - ; + ; # endif - dirp = do_opendir(fd, baselen, path, flags, enc, funcs->error, arg, &status); - if (dirp == NULL) { + dirp = do_opendir(fd, baselen, path, flags, enc, funcs->error, arg, &status); + if (dirp == NULL) { # if FNM_SYSCASE || NORMALIZE_UTF8PATH - if ((magical < 2) && !recursive && (errno == EACCES)) { - /* no read permission, fallback */ - goto literally; - } + if ((magical < 2) && !recursive && (errno == EACCES)) { + /* no read permission, fallback */ + goto literally; + } # endif - return status; - } - IF_NORMALIZE_UTF8PATH(norm_p = need_normalization(dirp, *path ? path : ".")); + return status; + } + IF_NORMALIZE_UTF8PATH(norm_p = need_normalization(dirp, *path ? path : ".")); # if NORMALIZE_UTF8PATH - if (!(norm_p || magical || recursive)) { - closedir(dirp); - goto literally; - } + if (!(norm_p || magical || recursive)) { + closedir(dirp); + goto literally; + } # endif # ifdef HAVE_GETATTRLIST - if (is_case_sensitive(dirp, path) == 0) - flags |= FNM_CASEFOLD; + if (is_case_sensitive(dirp, path) == 0) + flags |= FNM_CASEFOLD; # endif ruby_glob_entries_t globent; if (!glob_opendir(&globent, dirp, flags, enc)) { @@ -2428,182 +2428,182 @@ glob_helper( return status; } - int skipdot = (flags & FNM_GLOB_SKIPDOT); - flags |= FNM_GLOB_SKIPDOT; + int skipdot = (flags & FNM_GLOB_SKIPDOT); + flags |= FNM_GLOB_SKIPDOT; - while ((dp = glob_getent(&globent, flags, enc)) != NULL) { - char *buf; - rb_pathtype_t new_pathtype = path_unknown; - const char *name; - size_t namlen; - int dotfile = 0; - IF_NORMALIZE_UTF8PATH(VALUE utf8str = Qnil); + while ((dp = glob_getent(&globent, flags, enc)) != NULL) { + char *buf; + rb_pathtype_t new_pathtype = path_unknown; + const char *name; + size_t namlen; + int dotfile = 0; + IF_NORMALIZE_UTF8PATH(VALUE utf8str = Qnil); - name = dp->d_name; - namlen = dp->d_namlen; - if (name[0] == '.') { - ++dotfile; - if (namlen == 1) { - /* unless DOTMATCH, skip current directories not to recurse infinitely */ - if (recursive && !(flags & FNM_DOTMATCH)) continue; - if (skipdot) continue; - ++dotfile; - new_pathtype = path_directory; /* force to skip stat/lstat */ - } - else if (namlen == 2 && name[1] == '.') { - /* always skip parent directories not to recurse infinitely */ - continue; - } - } + name = dp->d_name; + namlen = dp->d_namlen; + if (name[0] == '.') { + ++dotfile; + if (namlen == 1) { + /* unless DOTMATCH, skip current directories not to recurse infinitely */ + if (recursive && !(flags & FNM_DOTMATCH)) continue; + if (skipdot) continue; + ++dotfile; + new_pathtype = path_directory; /* force to skip stat/lstat */ + } + else if (namlen == 2 && name[1] == '.') { + /* always skip parent directories not to recurse infinitely */ + continue; + } + } # if NORMALIZE_UTF8PATH - if (norm_p && has_nonascii(name, namlen)) { - if (!NIL_P(utf8str = rb_str_normalize_ospath(name, namlen))) { - RSTRING_GETMEM(utf8str, name, namlen); - } - } + if (norm_p && has_nonascii(name, namlen)) { + if (!NIL_P(utf8str = rb_str_normalize_ospath(name, namlen))) { + RSTRING_GETMEM(utf8str, name, namlen); + } + } # endif - buf = join_path(path, pathlen, dirsep, name, namlen); - IF_NORMALIZE_UTF8PATH(if (!NIL_P(utf8str)) rb_str_resize(utf8str, 0)); - if (!buf) { - status = -1; - break; - } - name = buf + pathlen + (dirsep != 0); + buf = join_path(path, pathlen, dirsep, name, namlen); + IF_NORMALIZE_UTF8PATH(if (!NIL_P(utf8str)) rb_str_resize(utf8str, 0)); + if (!buf) { + status = -1; + break; + } + name = buf + pathlen + (dirsep != 0); #if !EMULATE_IFTODT - if (dp->d_type != DT_UNKNOWN) { - /* Got it. We need no more lstat. */ - new_pathtype = dp->d_type; - } + if (dp->d_type != DT_UNKNOWN) { + /* Got it. We need no more lstat. */ + new_pathtype = dp->d_type; + } #endif - if (recursive && dotfile < ((flags & FNM_DOTMATCH) ? 2 : 1) && - new_pathtype == path_unknown) { - /* RECURSIVE never match dot files unless FNM_DOTMATCH is set */ - if (do_lstat(fd, baselen, buf, &st, flags, enc) == 0) - new_pathtype = IFTODT(st.st_mode); - else - new_pathtype = path_noent; - } + if (recursive && dotfile < ((flags & FNM_DOTMATCH) ? 2 : 1) && + new_pathtype == path_unknown) { + /* RECURSIVE never match dot files unless FNM_DOTMATCH is set */ + if (do_lstat(fd, baselen, buf, &st, flags, enc) == 0) + new_pathtype = IFTODT(st.st_mode); + else + new_pathtype = path_noent; + } - new_beg = new_end = GLOB_ALLOC_N(struct glob_pattern *, (end - beg) * 2); - if (!new_beg) { - GLOB_FREE(buf); - status = -1; - break; - } + new_beg = new_end = GLOB_ALLOC_N(struct glob_pattern *, (end - beg) * 2); + if (!new_beg) { + GLOB_FREE(buf); + status = -1; + break; + } - for (cur = beg; cur < end; ++cur) { - struct glob_pattern *p = *cur; - struct dirent_brace_args args; - if (p->type == RECURSIVE) { - if (new_pathtype == path_directory || /* not symlink but real directory */ - new_pathtype == path_exist) { - if (dotfile < ((flags & FNM_DOTMATCH) ? 2 : 1)) - *new_end++ = p; /* append recursive pattern */ - } - p = p->next; /* 0 times recursion */ - } - switch (p->type) { - case BRACE: - args.name = name; - args.dp = dp; - args.flags = flags; - if (ruby_brace_expand(p->str, flags, dirent_match_brace, - (VALUE)&args, enc, Qfalse) > 0) - *new_end++ = p->next; - break; - case ALPHA: + for (cur = beg; cur < end; ++cur) { + struct glob_pattern *p = *cur; + struct dirent_brace_args args; + if (p->type == RECURSIVE) { + if (new_pathtype == path_directory || /* not symlink but real directory */ + new_pathtype == path_exist) { + if (dotfile < ((flags & FNM_DOTMATCH) ? 2 : 1)) + *new_end++ = p; /* append recursive pattern */ + } + p = p->next; /* 0 times recursion */ + } + switch (p->type) { + case BRACE: + args.name = name; + args.dp = dp; + args.flags = flags; + if (ruby_brace_expand(p->str, flags, dirent_match_brace, + (VALUE)&args, enc, Qfalse) > 0) + *new_end++ = p->next; + break; + case ALPHA: # if USE_NAME_ON_FS == USE_NAME_ON_FS_BY_FNMATCH - if (plainname) { - *new_end++ = p->next; - break; - } + if (plainname) { + *new_end++ = p->next; + break; + } # endif - case PLAIN: - case MAGICAL: - if (dirent_match(p->str, enc, name, dp, flags)) - *new_end++ = p->next; - default: - break; - } - } + case PLAIN: + case MAGICAL: + if (dirent_match(p->str, enc, name, dp, flags)) + *new_end++ = p->next; + default: + break; + } + } - status = glob_helper(fd, buf, baselen, name - buf - baselen + namlen, 1, - new_pathtype, new_beg, new_end, - flags, funcs, arg, enc); - GLOB_FREE(buf); - GLOB_FREE(new_beg); - if (status) break; - } + status = glob_helper(fd, buf, baselen, name - buf - baselen + namlen, 1, + new_pathtype, new_beg, new_end, + flags, funcs, arg, enc); + GLOB_FREE(buf); + GLOB_FREE(new_beg); + if (status) break; + } glob_dir_finish(&globent, flags); } else if (plain) { - struct glob_pattern **copy_beg, **copy_end, **cur2; + struct glob_pattern **copy_beg, **copy_end, **cur2; # if FNM_SYSCASE || NORMALIZE_UTF8PATH literally: # endif - copy_beg = copy_end = GLOB_ALLOC_N(struct glob_pattern *, end - beg); - if (!copy_beg) return -1; - for (cur = beg; cur < end; ++cur) - *copy_end++ = (*cur)->type <= ALPHA ? *cur : 0; + copy_beg = copy_end = GLOB_ALLOC_N(struct glob_pattern *, end - beg); + if (!copy_beg) return -1; + for (cur = beg; cur < end; ++cur) + *copy_end++ = (*cur)->type <= ALPHA ? *cur : 0; - for (cur = copy_beg; cur < copy_end; ++cur) { - if (*cur) { - rb_pathtype_t new_pathtype = path_unknown; - char *buf; - char *name; - size_t len = strlen((*cur)->str) + 1; - name = GLOB_ALLOC_N(char, len); - if (!name) { - status = -1; - break; - } - memcpy(name, (*cur)->str, len); - if (escape) - len = remove_backslashes(name, name+len-1, enc) - name; + for (cur = copy_beg; cur < copy_end; ++cur) { + if (*cur) { + rb_pathtype_t new_pathtype = path_unknown; + char *buf; + char *name; + size_t len = strlen((*cur)->str) + 1; + name = GLOB_ALLOC_N(char, len); + if (!name) { + status = -1; + break; + } + memcpy(name, (*cur)->str, len); + if (escape) + len = remove_backslashes(name, name+len-1, enc) - name; - new_beg = new_end = GLOB_ALLOC_N(struct glob_pattern *, end - beg); - if (!new_beg) { - GLOB_FREE(name); - status = -1; - break; - } - *new_end++ = (*cur)->next; - for (cur2 = cur + 1; cur2 < copy_end; ++cur2) { - if (*cur2 && fnmatch((*cur2)->str, enc, name, flags) == 0) { - *new_end++ = (*cur2)->next; - *cur2 = 0; - } - } + new_beg = new_end = GLOB_ALLOC_N(struct glob_pattern *, end - beg); + if (!new_beg) { + GLOB_FREE(name); + status = -1; + break; + } + *new_end++ = (*cur)->next; + for (cur2 = cur + 1; cur2 < copy_end; ++cur2) { + if (*cur2 && fnmatch((*cur2)->str, enc, name, flags) == 0) { + *new_end++ = (*cur2)->next; + *cur2 = 0; + } + } - buf = join_path(path, pathlen, dirsep, name, len); - GLOB_FREE(name); - if (!buf) { - GLOB_FREE(new_beg); - status = -1; - break; - } + buf = join_path(path, pathlen, dirsep, name, len); + GLOB_FREE(name); + if (!buf) { + GLOB_FREE(new_beg); + status = -1; + break; + } #if USE_NAME_ON_FS == USE_NAME_ON_FS_REAL_BASENAME - if ((*cur)->type == ALPHA) { - buf = replace_real_basename(buf, pathlen + (dirsep != 0), enc, - IF_NORMALIZE_UTF8PATH(1)+0, - flags, &new_pathtype); - if (!buf) break; - } + if ((*cur)->type == ALPHA) { + buf = replace_real_basename(buf, pathlen + (dirsep != 0), enc, + IF_NORMALIZE_UTF8PATH(1)+0, + flags, &new_pathtype); + if (!buf) break; + } #endif - status = glob_helper(fd, buf, baselen, - namelen + strlen(buf + pathlen), 1, - new_pathtype, new_beg, new_end, - flags, funcs, arg, enc); - GLOB_FREE(buf); - GLOB_FREE(new_beg); - if (status) break; - } - } + status = glob_helper(fd, buf, baselen, + namelen + strlen(buf + pathlen), 1, + new_pathtype, new_beg, new_end, + flags, funcs, arg, enc); + GLOB_FREE(buf); + GLOB_FREE(new_beg); + if (status) break; + } + } - GLOB_FREE(copy_beg); + GLOB_FREE(copy_beg); } return status; @@ -2618,11 +2618,11 @@ push_caller(const char *path, VALUE val, void *enc) list = glob_make_pattern(path, path + strlen(path), arg->flags, enc); if (!list) { - return -1; + return -1; } status = glob_helper(arg->fd, arg->path, arg->baselen, arg->namelen, arg->dirsep, - arg->pathtype, &list, &list + 1, arg->flags, arg->funcs, - arg->arg, enc); + arg->pathtype, &list, &list + 1, arg->flags, arg->funcs, + arg->arg, enc); glob_free_pattern(list); return status; } @@ -2647,8 +2647,8 @@ push_glob0_caller(const char *path, VALUE val, void *enc) static int ruby_glob0(const char *path, int fd, const char *base, int flags, - const ruby_glob_funcs_t *funcs, VALUE arg, - rb_encoding *enc) + const ruby_glob_funcs_t *funcs, VALUE arg, + rb_encoding *enc) { struct glob_pattern *list; const char *root, *start; @@ -2677,10 +2677,10 @@ ruby_glob0(const char *path, int fd, const char *base, int flags, n = root - start; if (!n && base) { - n = strlen(base); - baselen = n; - start = base; - dirsep = TRUE; + n = strlen(base); + baselen = n; + start = base; + dirsep = TRUE; } buf = GLOB_ALLOC_N(char, n + 1); if (!buf) return -1; @@ -2689,12 +2689,12 @@ ruby_glob0(const char *path, int fd, const char *base, int flags, list = glob_make_pattern(root, root + strlen(root), flags, enc); if (!list) { - GLOB_FREE(buf); - return -1; + GLOB_FREE(buf); + return -1; } status = glob_helper(fd, buf, baselen, n-baselen, dirsep, - path_unknown, &list, &list + 1, - flags, funcs, arg, enc); + path_unknown, &list, &list + 1, + flags, funcs, arg, enc); glob_free_pattern(list); GLOB_FREE(buf); @@ -2708,7 +2708,7 @@ ruby_glob(const char *path, int flags, ruby_glob_func *func, VALUE arg) funcs.match = func; funcs.error = 0; return ruby_glob0(path, AT_FDCWD, 0, flags & ~GLOB_VERBOSE, - &funcs, arg, rb_ascii8bit_encoding()); + &funcs, arg, rb_ascii8bit_encoding()); } static int @@ -2737,7 +2737,7 @@ rb_glob(const char *path, void (*func)(const char *, VALUE, void *), VALUE arg) args.enc = rb_ascii8bit_encoding(); status = ruby_glob0(path, AT_FDCWD, 0, GLOB_VERBOSE, &rb_glob_funcs, - (VALUE)&args, args.enc); + (VALUE)&args, args.enc); if (status) GLOB_JUMP_TAG(status); } @@ -2756,7 +2756,7 @@ push_pattern(const char *path, VALUE ary, void *enc) static int ruby_brace_expand(const char *str, int flags, ruby_glob_func *func, VALUE arg, - rb_encoding *enc, VALUE var) + rb_encoding *enc, VALUE var) { const int escape = !(flags & FNM_NOESCAPE); const char *p = str; @@ -2766,48 +2766,48 @@ ruby_brace_expand(const char *str, int flags, ruby_glob_func *func, VALUE arg, int nest = 0, status = 0; while (*p) { - if (*p == '{' && nest++ == 0) { - lbrace = p; - } - if (*p == '}' && lbrace && --nest == 0) { - rbrace = p; - break; - } - if (*p == '\\' && escape) { - if (!*++p) break; - } - Inc(p, pend, enc); + if (*p == '{' && nest++ == 0) { + lbrace = p; + } + if (*p == '}' && lbrace && --nest == 0) { + rbrace = p; + break; + } + if (*p == '\\' && escape) { + if (!*++p) break; + } + Inc(p, pend, enc); } if (lbrace && rbrace) { - size_t len = strlen(s) + 1; - char *buf = GLOB_ALLOC_N(char, len); - long shift; + size_t len = strlen(s) + 1; + char *buf = GLOB_ALLOC_N(char, len); + long shift; - if (!buf) return -1; - memcpy(buf, s, lbrace-s); - shift = (lbrace-s); - p = lbrace; - while (p < rbrace) { - const char *t = ++p; - nest = 0; - while (p < rbrace && !(*p == ',' && nest == 0)) { - if (*p == '{') nest++; - if (*p == '}') nest--; - if (*p == '\\' && escape) { - if (++p == rbrace) break; - } - Inc(p, pend, enc); - } - memcpy(buf+shift, t, p-t); - strlcpy(buf+shift+(p-t), rbrace+1, len-(shift+(p-t))); - status = ruby_brace_expand(buf, flags, func, arg, enc, var); - if (status) break; - } - GLOB_FREE(buf); + if (!buf) return -1; + memcpy(buf, s, lbrace-s); + shift = (lbrace-s); + p = lbrace; + while (p < rbrace) { + const char *t = ++p; + nest = 0; + while (p < rbrace && !(*p == ',' && nest == 0)) { + if (*p == '{') nest++; + if (*p == '}') nest--; + if (*p == '\\' && escape) { + if (++p == rbrace) break; + } + Inc(p, pend, enc); + } + memcpy(buf+shift, t, p-t); + strlcpy(buf+shift+(p-t), rbrace+1, len-(shift+(p-t))); + status = ruby_brace_expand(buf, flags, func, arg, enc, var); + if (status) break; + } + GLOB_FREE(buf); } else if (!lbrace && !rbrace) { - status = glob_call_func(func, s, arg, enc); + status = glob_call_func(func, s, arg, enc); } RB_GC_GUARD(var); @@ -2858,9 +2858,9 @@ push_glob(VALUE ary, VALUE str, VALUE base, int flags) str = rb_str_encode_ospath(str); #endif if (rb_enc_to_index(enc) == ENCINDEX_US_ASCII) - enc = rb_filesystem_encoding(); + enc = rb_filesystem_encoding(); if (rb_enc_to_index(enc) == ENCINDEX_US_ASCII) - enc = rb_ascii8bit_encoding(); + enc = rb_ascii8bit_encoding(); flags |= GLOB_VERBOSE; args.func = push_pattern; args.value = ary; @@ -2868,23 +2868,23 @@ push_glob(VALUE ary, VALUE str, VALUE base, int flags) args.base = 0; fd = AT_FDCWD; if (!NIL_P(base)) { - if (!RB_TYPE_P(base, T_STRING) || !rb_enc_check(str, base)) { - struct dir_data *dirp = DATA_PTR(base); - if (!dirp->dir) dir_closed(); + if (!RB_TYPE_P(base, T_STRING) || !rb_enc_check(str, base)) { + struct dir_data *dirp = DATA_PTR(base); + if (!dirp->dir) dir_closed(); #ifdef HAVE_DIRFD - if ((fd = dirfd(dirp->dir)) == -1) - rb_sys_fail_path(dir_inspect(base)); + if ((fd = dirfd(dirp->dir)) == -1) + rb_sys_fail_path(dir_inspect(base)); #endif - base = dirp->path; - } - args.base = RSTRING_PTR(base); + base = dirp->path; + } + args.base = RSTRING_PTR(base); } #if defined _WIN32 || defined __APPLE__ enc = rb_utf8_encoding(); #endif return ruby_glob0(RSTRING_PTR(str), fd, args.base, flags, &rb_glob_funcs, - (VALUE)&args, enc); + (VALUE)&args, enc); } static VALUE @@ -2895,13 +2895,13 @@ rb_push_glob(VALUE str, VALUE base, int flags) /* '\0' is delimiter */ /* can contain null bytes as separators */ if (!RB_TYPE_P(str, T_STRING)) { - FilePathValue(str); + FilePathValue(str); } else if (!rb_str_to_cstr(str)) { rb_raise(rb_eArgError, "nul-separated glob pattern is deprecated"); } else { - rb_enc_check(str, rb_enc_from_encoding(rb_usascii_encoding())); + rb_enc_check(str, rb_enc_from_encoding(rb_usascii_encoding())); } ary = rb_ary_new(); @@ -2918,11 +2918,11 @@ dir_globs(VALUE args, VALUE base, int flags) long i; for (i = 0; i < RARRAY_LEN(args); ++i) { - int status; - VALUE str = RARRAY_AREF(args, i); - FilePathValue(str); - status = push_glob(ary, str, base, flags); - if (status) GLOB_JUMP_TAG(status); + int status; + VALUE str = RARRAY_AREF(args, i); + FilePathValue(str); + status = push_glob(ary, str, base, flags); + if (status) GLOB_JUMP_TAG(status); } RB_GC_GUARD(args); @@ -2933,11 +2933,11 @@ static VALUE dir_glob_option_base(VALUE base) { if (base == Qundef || NIL_P(base)) { - return Qnil; + return Qnil; } #if USE_OPENDIR_AT if (rb_typeddata_is_kind_of(base, &dir_data_type)) { - return base; + return base; } #endif FilePathValue(base); @@ -2957,7 +2957,7 @@ dir_s_aref(rb_execution_context_t *ec, VALUE obj, VALUE args, VALUE base, VALUE const int flags = dir_glob_option_sort(sort); base = dir_glob_option_base(base); if (RARRAY_LEN(args) == 1) { - return rb_push_glob(RARRAY_AREF(args, 0), base, flags); + return rb_push_glob(RARRAY_AREF(args, 0), base, flags); } return dir_globs(args, base, flags); } @@ -2969,15 +2969,15 @@ dir_s_glob(rb_execution_context_t *ec, VALUE obj, VALUE str, VALUE rflags, VALUE const int flags = (NUM2INT(rflags) | dir_glob_option_sort(sort)) & ~FNM_CASEFOLD; base = dir_glob_option_base(base); if (NIL_P(ary)) { - ary = rb_push_glob(str, base, flags); + ary = rb_push_glob(str, base, flags); } else { ary = dir_globs(ary, base, flags); } if (rb_block_given_p()) { - rb_ary_each(ary); - return Qnil; + rb_ary_each(ary); + return Qnil; } return ary; } @@ -3174,19 +3174,19 @@ fnmatch_brace(const char *pattern, VALUE val, void *enc) rb_encoding *enc_path = rb_enc_get(path); if (enc_pattern != enc_path) { - if (!rb_enc_asciicompat(enc_pattern)) - return FNM_NOMATCH; - if (!rb_enc_asciicompat(enc_path)) - return FNM_NOMATCH; - if (!rb_enc_str_asciionly_p(path)) { - int cr = ENC_CODERANGE_7BIT; - long len = strlen(pattern); - if (rb_str_coderange_scan_restartable(pattern, pattern + len, - enc_pattern, &cr) != len) - return FNM_NOMATCH; - if (cr != ENC_CODERANGE_7BIT) - return FNM_NOMATCH; - } + if (!rb_enc_asciicompat(enc_pattern)) + return FNM_NOMATCH; + if (!rb_enc_asciicompat(enc_path)) + return FNM_NOMATCH; + if (!rb_enc_str_asciionly_p(path)) { + int cr = ENC_CODERANGE_7BIT; + long len = strlen(pattern); + if (rb_str_coderange_scan_restartable(pattern, pattern + len, + enc_pattern, &cr) != len) + return FNM_NOMATCH; + if (cr != ENC_CODERANGE_7BIT) + return FNM_NOMATCH; + } } return (fnmatch(pattern, enc, RSTRING_PTR(path), arg->flags) == 0); } @@ -3200,27 +3200,27 @@ file_s_fnmatch(int argc, VALUE *argv, VALUE obj) int flags; if (rb_scan_args(argc, argv, "21", &pattern, &path, &rflags) == 3) - flags = NUM2INT(rflags); + flags = NUM2INT(rflags); else - flags = 0; + flags = 0; StringValueCStr(pattern); FilePathStringValue(path); if (flags & FNM_EXTGLOB) { - struct brace_args args; + struct brace_args args; - args.value = path; - args.flags = flags; - if (ruby_brace_expand(RSTRING_PTR(pattern), flags, fnmatch_brace, - (VALUE)&args, rb_enc_get(pattern), pattern) > 0) - return Qtrue; + args.value = path; + args.flags = flags; + if (ruby_brace_expand(RSTRING_PTR(pattern), flags, fnmatch_brace, + (VALUE)&args, rb_enc_get(pattern), pattern) > 0) + return Qtrue; } else { - rb_encoding *enc = rb_enc_compatible(pattern, path); - if (!enc) return Qfalse; - if (fnmatch(RSTRING_PTR(pattern), enc, RSTRING_PTR(path), flags) == 0) - return Qtrue; + rb_encoding *enc = rb_enc_compatible(pattern, path); + if (!enc) return Qfalse; + if (fnmatch(RSTRING_PTR(pattern), enc, RSTRING_PTR(path), flags) == 0) + return Qtrue; } RB_GC_GUARD(pattern); @@ -3244,12 +3244,12 @@ dir_s_home(int argc, VALUE *argv, VALUE obj) rb_check_arity(argc, 0, 1); user = (argc > 0) ? argv[0] : Qnil; if (!NIL_P(user)) { - SafeStringValue(user); - rb_must_asciicompat(user); - u = StringValueCStr(user); - if (*u) { - return rb_home_dir_of(user, rb_str_new(0, 0)); - } + SafeStringValue(user); + rb_must_asciicompat(user); + u = StringValueCStr(user); + if (*u) { + return rb_home_dir_of(user, rb_str_new(0, 0)); + } } return rb_default_home_dir(rb_str_new(0, 0)); @@ -3279,24 +3279,24 @@ nogvl_dir_empty_p(void *ptr) VALUE result = Qtrue; if (!dir) { - int e = errno; - switch (gc_for_fd_with_gvl(e)) { - default: - dir = opendir(path); - if (dir) break; - e = errno; - /* fall through */ - case 0: - if (e == ENOTDIR) return (void *)Qfalse; - errno = e; /* for rb_sys_fail_path */ - return (void *)Qundef; - } + int e = errno; + switch (gc_for_fd_with_gvl(e)) { + default: + dir = opendir(path); + if (dir) break; + e = errno; + /* fall through */ + case 0: + if (e == ENOTDIR) return (void *)Qfalse; + errno = e; /* for rb_sys_fail_path */ + return (void *)Qundef; + } } while ((dp = READDIR(dir, NULL)) != NULL) { - if (!to_be_skipped(dp)) { - result = Qfalse; - break; - } + if (!to_be_skipped(dp)) { + result = Qfalse; + break; + } } closedir(dir); return (void *)result; @@ -3324,27 +3324,27 @@ rb_dir_s_empty_p(VALUE obj, VALUE dirname) #if defined HAVE_GETATTRLIST && defined ATTR_DIR_ENTRYCOUNT { - u_int32_t attrbuf[SIZEUP32(fsobj_tag_t)]; - struct attrlist al = {ATTR_BIT_MAP_COUNT, 0, ATTR_CMN_OBJTAG,}; - if (getattrlist(path, &al, attrbuf, sizeof(attrbuf), 0) != 0) - rb_sys_fail_path(orig); - if (*(const fsobj_tag_t *)(attrbuf+1) == VT_HFS) { - al.commonattr = 0; - al.dirattr = ATTR_DIR_ENTRYCOUNT; - if (getattrlist(path, &al, attrbuf, sizeof(attrbuf), 0) == 0) { - if (attrbuf[0] >= 2 * sizeof(u_int32_t)) - return RBOOL(attrbuf[1] == 0); - if (false_on_notdir) return Qfalse; - } - rb_sys_fail_path(orig); - } + u_int32_t attrbuf[SIZEUP32(fsobj_tag_t)]; + struct attrlist al = {ATTR_BIT_MAP_COUNT, 0, ATTR_CMN_OBJTAG,}; + if (getattrlist(path, &al, attrbuf, sizeof(attrbuf), 0) != 0) + rb_sys_fail_path(orig); + if (*(const fsobj_tag_t *)(attrbuf+1) == VT_HFS) { + al.commonattr = 0; + al.dirattr = ATTR_DIR_ENTRYCOUNT; + if (getattrlist(path, &al, attrbuf, sizeof(attrbuf), 0) == 0) { + if (attrbuf[0] >= 2 * sizeof(u_int32_t)) + return RBOOL(attrbuf[1] == 0); + if (false_on_notdir) return Qfalse; + } + rb_sys_fail_path(orig); + } } #endif result = (VALUE)rb_thread_call_without_gvl(nogvl_dir_empty_p, (void *)path, - RUBY_UBF_IO, 0); + RUBY_UBF_IO, 0); if (result == Qundef) { - rb_sys_fail_path(orig); + rb_sys_fail_path(orig); } return result; } diff --git a/dln.c b/dln.c index b9cfe7dc94..b14ba63c44 100644 --- a/dln.c +++ b/dln.c @@ -110,8 +110,8 @@ init_funcname_len(const char **file) /* Load the file as an object one */ for (base = p; *p; p++) { /* Find position of last '/' */ - if (*p == '.' && !dot) dot = p; - if (isdirsep(*p)) base = p+1, dot = NULL; + if (*p == '.' && !dot) dot = p; + if (isdirsep(*p)) base = p+1, dot = NULL; } *file = base; /* Delete suffix if it exists */ @@ -126,7 +126,7 @@ static const char funcname_prefix[sizeof(FUNCNAME_PREFIX) - 1] = FUNCNAME_PREFIX const size_t plen = sizeof(funcname_prefix);\ char *const tmp = ALLOCA_N(char, plen+flen+1);\ if (!tmp) {\ - dln_memerror();\ + dln_memerror();\ }\ memcpy(tmp, funcname_prefix, plen);\ memcpy(tmp+plen, base, flen);\ @@ -170,14 +170,14 @@ dln_strerror(char *message, size_t size) size_t len = snprintf(message, size, "%d: ", error); #define format_message(sublang) FormatMessage(\ - FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, \ - NULL, error, MAKELANGID(LANG_NEUTRAL, (sublang)), \ - message + len, size - len, NULL) + FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, \ + NULL, error, MAKELANGID(LANG_NEUTRAL, (sublang)), \ + message + len, size - len, NULL) if (format_message(SUBLANG_ENGLISH_US) == 0) - format_message(SUBLANG_DEFAULT); + format_message(SUBLANG_DEFAULT); for (p = message + len; *p; p++) { - if (*p == '\n' || *p == '\r') - *p = ' '; + if (*p == '\n' || *p == '\r') + *p = ' '; } return message; } @@ -200,18 +200,18 @@ aix_loaderror(const char *pathname) snprintf(errbuf, sizeof(errbuf), "load failed - %s. ", pathname); if (loadquery(L_GETMESSAGES, &message[0], sizeof(message)) != -1) { - ERRBUF_APPEND("Please issue below command for detailed reasons:\n\t"); - ERRBUF_APPEND("/usr/sbin/execerror ruby "); - for (i=0; message[i]; i++) { - ERRBUF_APPEND("\""); - ERRBUF_APPEND(message[i]); - ERRBUF_APPEND("\" "); - } - ERRBUF_APPEND("\n"); + ERRBUF_APPEND("Please issue below command for detailed reasons:\n\t"); + ERRBUF_APPEND("/usr/sbin/execerror ruby "); + for (i=0; message[i]; i++) { + ERRBUF_APPEND("\""); + ERRBUF_APPEND(message[i]); + ERRBUF_APPEND("\" "); + } + ERRBUF_APPEND("\n"); } else { - ERRBUF_APPEND(strerror(errno)); - ERRBUF_APPEND("[loadquery failed]"); + ERRBUF_APPEND(strerror(errno)); + ERRBUF_APPEND("[loadquery failed]"); } dln_loaderror("%s", errbuf); } @@ -229,22 +229,22 @@ rb_w32_check_imported(HMODULE ext, HMODULE mine) desc = ImageDirectoryEntryToData(ext, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, &size); if (!desc) return 0; while (desc->Name) { - PIMAGE_THUNK_DATA pint = (PIMAGE_THUNK_DATA)((char *)ext + desc->Characteristics); - PIMAGE_THUNK_DATA piat = (PIMAGE_THUNK_DATA)((char *)ext + desc->FirstThunk); - for (; piat->u1.Function; piat++, pint++) { - static const char prefix[] = "rb_"; - PIMAGE_IMPORT_BY_NAME pii; - const char *name; + PIMAGE_THUNK_DATA pint = (PIMAGE_THUNK_DATA)((char *)ext + desc->Characteristics); + PIMAGE_THUNK_DATA piat = (PIMAGE_THUNK_DATA)((char *)ext + desc->FirstThunk); + for (; piat->u1.Function; piat++, pint++) { + static const char prefix[] = "rb_"; + PIMAGE_IMPORT_BY_NAME pii; + const char *name; - if (IMAGE_SNAP_BY_ORDINAL(pint->u1.Ordinal)) continue; - pii = (PIMAGE_IMPORT_BY_NAME)((char *)ext + (size_t)pint->u1.AddressOfData); - name = (const char *)pii->Name; - if (strncmp(name, prefix, sizeof(prefix) - 1) == 0) { - FARPROC addr = GetProcAddress(mine, name); - if (addr) return (FARPROC)piat->u1.Function == addr; - } - } - desc++; + if (IMAGE_SNAP_BY_ORDINAL(pint->u1.Ordinal)) continue; + pii = (PIMAGE_IMPORT_BY_NAME)((char *)ext + (size_t)pint->u1.AddressOfData); + name = (const char *)pii->Name; + if (strncmp(name, prefix, sizeof(prefix) - 1) == 0) { + FARPROC addr = GetProcAddress(mine, name); + if (addr) return (FARPROC)piat->u1.Function == addr; + } + } + desc++; } return 1; } @@ -252,11 +252,11 @@ rb_w32_check_imported(HMODULE ext, HMODULE mine) #if defined(DLN_NEEDS_ALT_SEPARATOR) && DLN_NEEDS_ALT_SEPARATOR #define translit_separator(src) do { \ - char *tmp = ALLOCA_N(char, strlen(src) + 1), *p = tmp, c; \ - do { \ - *p++ = ((c = *file++) == '/') ? DLN_NEEDS_ALT_SEPARATOR : c; \ - } while (c); \ - (src) = tmp; \ + char *tmp = ALLOCA_N(char, strlen(src) + 1), *p = tmp, c; \ + do { \ + *p++ = ((c = *file++) == '/') ? DLN_NEEDS_ALT_SEPARATOR : c; \ + } while (c); \ + (src) = tmp; \ } while (0) #else #define translit_separator(str) (void)(str) @@ -273,7 +273,7 @@ dln_incompatible_func(void *handle, const char *funcname, void *const fp, const if (!ex) return false; if (ex == fp) return false; if (dladdr(ex, &dli)) { - *libname = dli.dli_fname; + *libname = dli.dli_fname; } return true; } @@ -287,7 +287,7 @@ dln_incompatible_library_p(void *handle, const char **libname) { #define check_func(func) \ if (dln_incompatible_func(handle, EXTERNAL_PREFIX #func, (void *)&func, libname)) \ - return true + return true check_func(ruby_xmalloc); return false; } @@ -337,7 +337,7 @@ dln_open(const char *file) /* Convert the file path to wide char */ WCHAR *winfile = rb_w32_mbstr_to_wstr(CP_UTF8, file, -1, NULL); if (!winfile) { - dln_memerror(); + dln_memerror(); } /* Load file */ @@ -345,15 +345,15 @@ dln_open(const char *file) free(winfile); if (!handle) { - error = dln_strerror(); - goto failed; + error = dln_strerror(); + goto failed; } # if defined(RUBY_EXPORT) if (!rb_w32_check_imported(handle, rb_libruby_handle())) { - FreeLibrary(handle); - error = incompatible; - goto failed; + FreeLibrary(handle); + error = incompatible; + goto failed; } # endif @@ -378,24 +378,24 @@ dln_open(const char *file) # if defined(RUBY_EXPORT) { - const char *libruby_name = NULL; - if (dln_incompatible_library_p(handle, &libruby_name)) { - if (dln_disable_dlclose()) { - /* dlclose() segfaults */ - if (libruby_name) { - dln_fatalerror("linked to incompatible %s - %s", libruby_name, file); - } - dln_fatalerror("%s - %s", incompatible, file); - } - else { - dlclose(handle); - if (libruby_name) { - dln_loaderror("linked to incompatible %s - %s", libruby_name, file); - } - error = incompatible; - goto failed; - } - } + const char *libruby_name = NULL; + if (dln_incompatible_library_p(handle, &libruby_name)) { + if (dln_disable_dlclose()) { + /* dlclose() segfaults */ + if (libruby_name) { + dln_fatalerror("linked to incompatible %s - %s", libruby_name, file); + } + dln_fatalerror("%s - %s", incompatible, file); + } + else { + dlclose(handle); + if (libruby_name) { + dln_loaderror("linked to incompatible %s - %s", libruby_name, file); + } + error = incompatible; + goto failed; + } + } } # endif #endif @@ -471,17 +471,17 @@ dln_load(const char *file) #elif defined(_AIX) { - void (*init_fct)(void); + void (*init_fct)(void); - init_fct = (void(*)(void))load((char*)file, 1, 0); - if (init_fct == NULL) { - aix_loaderror(file); - } - if (loadbind(0, (void*)dln_load, (void*)init_fct) == -1) { - aix_loaderror(file); - } - (*init_fct)(); - return (void*)init_fct; + init_fct = (void(*)(void))load((char*)file, 1, 0); + if (init_fct == NULL) { + aix_loaderror(file); + } + if (loadbind(0, (void*)dln_load, (void*)init_fct) == -1) { + aix_loaderror(file); + } + (*init_fct)(); + return (void*)init_fct; } #else dln_notimplement(); diff --git a/dln_find.c b/dln_find.c index 96e06d34c4..5d380f5d39 100644 --- a/dln_find.c +++ b/dln_find.c @@ -53,26 +53,26 @@ char *getenv(); #endif static char *dln_find_1(const char *fname, const char *path, char *buf, size_t size, int exe_flag - DLN_FIND_EXTRA_ARG_DECL); + DLN_FIND_EXTRA_ARG_DECL); char * dln_find_exe_r(const char *fname, const char *path, char *buf, size_t size - DLN_FIND_EXTRA_ARG_DECL) + DLN_FIND_EXTRA_ARG_DECL) { char *envpath = 0; if (!path) { - path = getenv(PATH_ENV); - if (path) path = envpath = strdup(path); + path = getenv(PATH_ENV); + if (path) path = envpath = strdup(path); } if (!path) { - path = - "/usr/local/bin" PATH_SEP - "/usr/ucb" PATH_SEP - "/usr/bin" PATH_SEP - "/bin" PATH_SEP - "."; + path = + "/usr/local/bin" PATH_SEP + "/usr/ucb" PATH_SEP + "/usr/bin" PATH_SEP + "/bin" PATH_SEP + "."; } buf = dln_find_1(fname, path, buf, size, 1 DLN_FIND_EXTRA_ARG); if (envpath) free(envpath); @@ -81,7 +81,7 @@ dln_find_exe_r(const char *fname, const char *path, char *buf, size_t size char * dln_find_file_r(const char *fname, const char *path, char *buf, size_t size - DLN_FIND_EXTRA_ARG_DECL) + DLN_FIND_EXTRA_ARG_DECL) { if (!path) path = "."; return dln_find_1(fname, path, buf, size, 0 DLN_FIND_EXTRA_ARG); @@ -89,8 +89,8 @@ dln_find_file_r(const char *fname, const char *path, char *buf, size_t size static char * dln_find_1(const char *fname, const char *path, char *fbuf, size_t size, - int exe_flag /* non 0 if looking for executable. */ - DLN_FIND_EXTRA_ARG_DECL) + int exe_flag /* non 0 if looking for executable. */ + DLN_FIND_EXTRA_ARG_DECL) { register const char *dp; register const char *ep; @@ -99,7 +99,7 @@ dln_find_1(const char *fname, const char *path, char *fbuf, size_t size, size_t i, fnlen, fspace; #ifdef DOSISH static const char extension[][5] = { - EXECUTABLE_EXTS, + EXECUTABLE_EXTS, }; size_t j; int is_abs = 0, has_path = 0; @@ -110,21 +110,21 @@ dln_find_1(const char *fname, const char *path, char *fbuf, size_t size, static const char pathname_too_long[] = "openpath: pathname too long (ignored)\n\ \tDirectory \"%.*s\"%s\n\tFile \"%.*s\"%s\n"; #define PATHNAME_TOO_LONG() dln_warning(dln_warning_arg pathname_too_long, \ - ((bp - fbuf) > 100 ? 100 : (int)(bp - fbuf)), fbuf, \ - ((bp - fbuf) > 100 ? "..." : ""), \ - (fnlen > 100 ? 100 : (int)fnlen), fname, \ - (fnlen > 100 ? "..." : "")) + ((bp - fbuf) > 100 ? 100 : (int)(bp - fbuf)), fbuf, \ + ((bp - fbuf) > 100 ? "..." : ""), \ + (fnlen > 100 ? 100 : (int)fnlen), fname, \ + (fnlen > 100 ? "..." : "")) #define RETURN_IF(expr) if (expr) return (char *)fname; RETURN_IF(!fname); fnlen = strlen(fname); if (fnlen >= size) { - dln_warning(dln_warning_arg - "openpath: pathname too long (ignored)\n\tFile \"%.*s\"%s\n", - (fnlen > 100 ? 100 : (int)fnlen), fname, - (fnlen > 100 ? "..." : "")); - return NULL; + dln_warning(dln_warning_arg + "openpath: pathname too long (ignored)\n\tFile \"%.*s\"%s\n", + (fnlen > 100 ? 100 : (int)fnlen), fname, + (fnlen > 100 ? "..." : "")); + return NULL; } #ifdef DOSISH # ifndef CharNext @@ -132,52 +132,52 @@ dln_find_1(const char *fname, const char *path, char *fbuf, size_t size, # endif # ifdef DOSISH_DRIVE_LETTER if (((p[0] | 0x20) - 'a') < 26 && p[1] == ':') { - p += 2; - is_abs = 1; + p += 2; + is_abs = 1; } # endif switch (*p) { case '/': case '\\': - is_abs = 1; - p++; + is_abs = 1; + p++; } has_path = is_abs; while (*p) { - switch (*p) { - case '/': case '\\': - has_path = 1; - ext = 0; - p++; - break; - case '.': - ext = p; - p++; - break; - default: - p = CharNext(p); - } + switch (*p) { + case '/': case '\\': + has_path = 1; + ext = 0; + p++; + break; + case '.': + ext = p; + p++; + break; + default: + p = CharNext(p); + } } if (ext) { - for (j = 0; STRCASECMP(ext, extension[j]); ) { - if (++j == sizeof(extension) / sizeof(extension[0])) { - ext = 0; - break; - } - } + for (j = 0; STRCASECMP(ext, extension[j]); ) { + if (++j == sizeof(extension) / sizeof(extension[0])) { + ext = 0; + break; + } + } } ep = bp = 0; if (!exe_flag) { - RETURN_IF(is_abs); + RETURN_IF(is_abs); } else if (has_path) { - RETURN_IF(ext); - i = p - fname; - if (i + 1 > size) goto toolong; - fspace = size - i - 1; - bp = fbuf; - ep = p; - memcpy(fbuf, fname, i + 1); - goto needs_extension; + RETURN_IF(ext); + i = p - fname; + if (i + 1 > size) goto toolong; + fspace = size - i - 1; + bp = fbuf; + ep = p; + memcpy(fbuf, fname, i + 1); + goto needs_extension; } p = fname; #endif @@ -189,85 +189,85 @@ dln_find_1(const char *fname, const char *path, char *fbuf, size_t size, #undef RETURN_IF for (dp = path;; dp = ++ep) { - register size_t l; + register size_t l; - /* extract a component */ - ep = strchr(dp, PATH_SEP[0]); - if (ep == NULL) - ep = dp+strlen(dp); + /* extract a component */ + ep = strchr(dp, PATH_SEP[0]); + if (ep == NULL) + ep = dp+strlen(dp); - /* find the length of that component */ - l = ep - dp; - bp = fbuf; - fspace = size - 2; - if (l > 0) { - /* - ** If the length of the component is zero length, - ** start from the current directory. If the - ** component begins with "~", start from the - ** user's $HOME environment variable. Otherwise - ** take the path literally. - */ + /* find the length of that component */ + l = ep - dp; + bp = fbuf; + fspace = size - 2; + if (l > 0) { + /* + ** If the length of the component is zero length, + ** start from the current directory. If the + ** component begins with "~", start from the + ** user's $HOME environment variable. Otherwise + ** take the path literally. + */ - if (*dp == '~' && (l == 1 || + if (*dp == '~' && (l == 1 || #if defined(DOSISH) - dp[1] == '\\' || + dp[1] == '\\' || #endif - dp[1] == '/')) { - const char *home; + dp[1] == '/')) { + const char *home; - home = getenv("HOME"); - if (home != NULL) { - i = strlen(home); - if (fspace < i) - goto toolong; - fspace -= i; - memcpy(bp, home, i); - bp += i; - } - dp++; - l--; - } - if (l > 0) { - if (fspace < l) - goto toolong; - fspace -= l; - memcpy(bp, dp, l); - bp += l; - } + home = getenv("HOME"); + if (home != NULL) { + i = strlen(home); + if (fspace < i) + goto toolong; + fspace -= i; + memcpy(bp, home, i); + bp += i; + } + dp++; + l--; + } + if (l > 0) { + if (fspace < l) + goto toolong; + fspace -= l; + memcpy(bp, dp, l); + bp += l; + } - /* add a "/" between directory and filename */ - if (ep[-1] != '/') - *bp++ = '/'; - } + /* add a "/" between directory and filename */ + if (ep[-1] != '/') + *bp++ = '/'; + } - /* now append the file name */ - i = fnlen; - if (fspace < i) { + /* now append the file name */ + i = fnlen; + if (fspace < i) { goto toolong; - } - fspace -= i; - memcpy(bp, fname, i + 1); + } + fspace -= i; + memcpy(bp, fname, i + 1); #if defined(DOSISH) - if (exe_flag && !ext) { + if (exe_flag && !ext) { goto needs_extension; - } + } #endif #ifndef S_ISREG # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG) #endif - if (stat(fbuf, &st) == 0 && S_ISREG(st.st_mode)) { - if (exe_flag == 0) return fbuf; - /* looking for executable */ - if (eaccess(fbuf, X_OK) == 0) return fbuf; - } + if (stat(fbuf, &st) == 0 && S_ISREG(st.st_mode)) { + if (exe_flag == 0) return fbuf; + /* looking for executable */ + if (eaccess(fbuf, X_OK) == 0) return fbuf; + } next: - /* if not, and no other alternatives, life is bleak */ - if (*ep == '\0') { - return NULL; - } + /* if not, and no other alternatives, life is bleak */ + if (*ep == '\0') { + return NULL; + } continue; toolong: @@ -287,6 +287,6 @@ dln_find_1(const char *fname, const char *path, char *fbuf, size_t size, } goto next; #endif - /* otherwise try the next component in the search path */ + /* otherwise try the next component in the search path */ } } diff --git a/dmyenc.c b/dmyenc.c index 7e006e826c..75b8a2da43 100644 --- a/dmyenc.c +++ b/dmyenc.c @@ -5,6 +5,6 @@ void Init_enc(void) { if (require("enc/encdb.so") == 1) { - require("enc/trans/transdb.so"); + require("enc/trans/transdb.so"); } } diff --git a/encoding.c b/encoding.c index 0e52949fa0..b8fedfb797 100644 --- a/encoding.c +++ b/encoding.c @@ -210,7 +210,7 @@ check_encoding(rb_encoding *enc) { int index = rb_enc_to_index(enc); if (rb_enc_from_index(index) != enc) - return -1; + return -1; if (rb_enc_autoload_p(enc)) { index = rb_enc_autoload(enc); } @@ -221,7 +221,7 @@ static int enc_check_encoding(VALUE obj) { if (!is_obj_encoding(obj)) { - return -1; + return -1; } return check_encoding(RDATA(obj)->data); } @@ -231,7 +231,7 @@ static void not_encoding(VALUE enc) { rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (expected Encoding)", - rb_obj_class(enc)); + rb_obj_class(enc)); } static rb_encoding * @@ -239,7 +239,7 @@ must_encoding(VALUE enc) { int index = enc_check_encoding(enc); if (index < 0) { - not_encoding(enc); + not_encoding(enc); } return DATA_PTR(enc); } @@ -249,16 +249,16 @@ must_encindex(int index) { rb_encoding *enc = rb_enc_from_index(index); if (!enc) { - rb_raise(rb_eEncodingError, "encoding index out of bound: %d", - index); + rb_raise(rb_eEncodingError, "encoding index out of bound: %d", + index); } if (ENC_TO_ENCINDEX(enc) != (int)(index & ENC_INDEX_MASK)) { - rb_raise(rb_eEncodingError, "wrong encoding index %d for %s (expected %d)", - index, rb_enc_name(enc), ENC_TO_ENCINDEX(enc)); + rb_raise(rb_eEncodingError, "wrong encoding index %d for %s (expected %d)", + index, rb_enc_name(enc), ENC_TO_ENCINDEX(enc)); } if (rb_enc_autoload_p(enc) && rb_enc_autoload(enc) == -1) { - rb_loaderror("failed to load encoding (%s)", - rb_enc_name(enc)); + rb_loaderror("failed to load encoding (%s)", + rb_enc_name(enc)); } return enc; } @@ -271,16 +271,16 @@ rb_to_encoding_index(VALUE enc) idx = enc_check_encoding(enc); if (idx >= 0) { - return idx; + return idx; } else if (NIL_P(enc = rb_check_string_type(enc))) { - return -1; + return -1; } if (!rb_enc_asciicompat(rb_enc_get(enc))) { - return -1; + return -1; } if (!(name = rb_str_to_cstr(enc))) { - return -1; + return -1; } return rb_enc_find_index(name); } @@ -292,10 +292,10 @@ name_for_encoding(volatile VALUE *enc) const char *n; if (!rb_enc_asciicompat(rb_enc_get(name))) { - rb_raise(rb_eArgError, "invalid encoding name (non ASCII)"); + rb_raise(rb_eArgError, "invalid encoding name (non ASCII)"); } if (!(n = rb_str_to_cstr(name))) { - rb_raise(rb_eArgError, "invalid encoding name (NUL byte)"); + rb_raise(rb_eArgError, "invalid encoding name (NUL byte)"); } return n; } @@ -314,7 +314,7 @@ str_to_encindex(VALUE enc) { int idx = str_find_encindex(enc); if (idx < 0) { - rb_raise(rb_eArgError, "unknown encoding name - %"PRIsVALUE, enc); + rb_raise(rb_eArgError, "unknown encoding name - %"PRIsVALUE, enc); } return idx; } @@ -365,20 +365,20 @@ enc_register_at(struct enc_table *enc_table, int index, const char *name, rb_enc if (!valid_encoding_name_p(name)) return -1; if (!ent->name) { - ent->name = name = strdup(name); + ent->name = name = strdup(name); } else if (STRCASECMP(name, ent->name)) { - return -1; + return -1; } encoding = (rb_raw_encoding *)ent->enc; if (!encoding) { - encoding = xmalloc(sizeof(rb_encoding)); + encoding = xmalloc(sizeof(rb_encoding)); } if (base_encoding) { - *encoding = *base_encoding; + *encoding = *base_encoding; } else { - memset(encoding, 0, sizeof(*ent->enc)); + memset(encoding, 0, sizeof(*ent->enc)); } encoding->name = name; encoding->ruby_encoding_index = index; @@ -405,7 +405,7 @@ static rb_encoding * enc_from_index(struct enc_table *enc_table, int index) { if (UNLIKELY(index < 0 || enc_table->count <= (index &= ENC_INDEX_MASK))) { - return 0; + return 0; } return enc_table->list[index].enc; } @@ -464,7 +464,7 @@ enc_registered(struct enc_table *enc_table, const char *name) if (!name) return -1; if (!enc_table->list) return -1; if (st_lookup(enc_table->names, (st_data_t)name, &idx)) { - return (int)idx; + return (int)idx; } return -1; } @@ -487,7 +487,7 @@ static void enc_check_duplication(struct enc_table *enc_table, const char *name) { if (enc_registered(enc_table, name) >= 0) { - rb_raise(rb_eArgError, "encoding %s is already registered", name); + rb_raise(rb_eArgError, "encoding %s is already registered", name); } } @@ -581,11 +581,11 @@ enc_replicate_with_index(struct enc_table *enc_table, const char *name, rb_encod idx = enc_register(enc_table, name, origenc); } else { - idx = enc_register_at(enc_table, idx, name, origenc); + idx = enc_register_at(enc_table, idx, name, origenc); } if (idx >= 0) { - set_base_encoding(enc_table, idx, origenc); - set_encoding_const(name, rb_enc_from_index(idx)); + set_base_encoding(enc_table, idx, origenc); + set_encoding_const(name, rb_enc_from_index(idx)); } else { rb_raise(rb_eArgError, "failed to replicate encoding"); @@ -705,7 +705,7 @@ static int enc_alias_internal(struct enc_table *enc_table, const char *alias, int idx) { return st_insert2(enc_table->names, (st_data_t)alias, (st_data_t)idx, - enc_dup_name); + enc_dup_name); } static int @@ -713,7 +713,7 @@ enc_alias(struct enc_table *enc_table, const char *alias, int idx) { if (!valid_encoding_name_p(alias)) return -1; if (!enc_alias_internal(enc_table, alias, idx)) - set_encoding_const(alias, enc_from_index(enc_table, idx)); + set_encoding_const(alias, enc_from_index(enc_table, idx)); return idx; } @@ -769,7 +769,7 @@ rb_enc_init(struct enc_table *enc_table) { enc_table_expand(enc_table, ENCODING_COUNT + 1); if (!enc_table->names) { - enc_table->names = st_init_strcasetable(); + enc_table->names = st_init_strcasetable(); } #define OnigEncodingASCII_8BIT OnigEncodingASCII #define ENC_REGISTER(enc) enc_register_at(enc_table, ENCINDEX_##enc, rb_enc_name(&OnigEncoding##enc), &OnigEncoding##enc) @@ -815,9 +815,9 @@ load_encoding(const char *name) int idx; while (s < e) { - if (!ISALNUM(*s)) *s = '_'; - else if (ISUPPER(*s)) *s = (char)TOLOWER(*s); - ++s; + if (!ISALNUM(*s)) *s = '_'; + else if (ISUPPER(*s)) *s = (char)TOLOWER(*s); + ++s; } enclib = rb_fstring(enclib); ruby_debug = Qfalse; @@ -850,16 +850,16 @@ enc_autoload_body(struct enc_table *enc_table, rb_encoding *enc) if (base) { int i = 0; - do { - if (i >= enc_table->count) return -1; - } while (enc_table->list[i].enc != base && (++i, 1)); - if (rb_enc_autoload_p(base)) { - if (rb_enc_autoload(base) < 0) return -1; - } - i = enc->ruby_encoding_index; - enc_register_at(enc_table, i & ENC_INDEX_MASK, rb_enc_name(enc), base); + do { + if (i >= enc_table->count) return -1; + } while (enc_table->list[i].enc != base && (++i, 1)); + if (rb_enc_autoload_p(base)) { + if (rb_enc_autoload(base) < 0) return -1; + } + i = enc->ruby_encoding_index; + enc_register_at(enc_table, i & ENC_INDEX_MASK, rb_enc_name(enc), base); ((rb_raw_encoding *)enc)->ruby_encoding_index = i; - i &= ENC_INDEX_MASK; + i &= ENC_INDEX_MASK; return i; } else { @@ -888,19 +888,19 @@ rb_enc_find_index(const char *name) GLOBAL_ENC_TABLE_EVAL(enc_table, i = enc_registered(enc_table, name)); if (i < 0) { - i = load_encoding(name); + i = load_encoding(name); } else if (!(enc = rb_enc_from_index(i))) { - if (i != UNSPECIFIED_ENCODING) { - rb_raise(rb_eArgError, "encoding %s is not registered", name); - } + if (i != UNSPECIFIED_ENCODING) { + rb_raise(rb_eArgError, "encoding %s is not registered", name); + } } else if (rb_enc_autoload_p(enc)) { - if (rb_enc_autoload(enc) < 0) { - rb_warn("failed to load encoding (%s); use ASCII-8BIT instead", - name); - return 0; - } + if (rb_enc_autoload(enc) < 0) { + rb_warn("failed to load encoding (%s); use ASCII-8BIT instead", + name); + return 0; + } } return i; } @@ -933,11 +933,11 @@ enc_capable(VALUE obj) case T_REGEXP: case T_FILE: case T_SYMBOL: - return TRUE; + return TRUE; case T_DATA: - if (is_data_encoding(obj)) return TRUE; + if (is_data_encoding(obj)) return TRUE; default: - return FALSE; + return FALSE; } } @@ -959,11 +959,11 @@ enc_get_index_str(VALUE str) { int i = ENCODING_GET_INLINED(str); if (i == ENCODING_INLINE_MAX) { - VALUE iv; + VALUE iv; #if 0 - iv = rb_ivar_get(str, rb_id_encoding()); - i = NUM2INT(iv); + iv = rb_ivar_get(str, rb_id_encoding()); + i = NUM2INT(iv); #else /* * Tentatively, assume ASCII-8BIT, if encoding index instance @@ -984,31 +984,31 @@ rb_enc_get_index(VALUE obj) VALUE tmp; if (SPECIAL_CONST_P(obj)) { - if (!SYMBOL_P(obj)) return -1; - obj = rb_sym2str(obj); + if (!SYMBOL_P(obj)) return -1; + obj = rb_sym2str(obj); } switch (BUILTIN_TYPE(obj)) { case T_STRING: case T_SYMBOL: case T_REGEXP: - i = enc_get_index_str(obj); - break; + i = enc_get_index_str(obj); + break; case T_FILE: - tmp = rb_funcallv(obj, rb_intern("internal_encoding"), 0, 0); - if (NIL_P(tmp)) { - tmp = rb_funcallv(obj, rb_intern("external_encoding"), 0, 0); - } - if (is_obj_encoding(tmp)) { - i = enc_check_encoding(tmp); - } - break; + tmp = rb_funcallv(obj, rb_intern("internal_encoding"), 0, 0); + if (NIL_P(tmp)) { + tmp = rb_funcallv(obj, rb_intern("external_encoding"), 0, 0); + } + if (is_obj_encoding(tmp)) { + i = enc_check_encoding(tmp); + } + break; case T_DATA: - if (is_data_encoding(obj)) { - i = enc_check_encoding(obj); - } - break; + if (is_data_encoding(obj)) { + i = enc_check_encoding(obj); + } + break; default: - break; + break; } return i; } @@ -1021,8 +1021,8 @@ enc_set_index(VALUE obj, int idx) } if (idx < ENCODING_INLINE_MAX) { - ENCODING_SET_INLINED(obj, idx); - return; + ENCODING_SET_INLINED(obj, idx); + return; } ENCODING_SET_INLINED(obj, ENCODING_INLINE_MAX); rb_ivar_set(obj, rb_id_encoding(), INT2NUM(idx)); @@ -1046,19 +1046,19 @@ rb_enc_associate_index(VALUE obj, int idx) rb_check_frozen(obj); oldidx = rb_enc_get_index(obj); if (oldidx == idx) - return obj; + return obj; if (SPECIAL_CONST_P(obj)) { - rb_raise(rb_eArgError, "cannot set encoding"); + rb_raise(rb_eArgError, "cannot set encoding"); } enc = must_encindex(idx); if (!ENC_CODERANGE_ASCIIONLY(obj) || - !rb_enc_asciicompat(enc)) { - ENC_CODERANGE_CLEAR(obj); + !rb_enc_asciicompat(enc)) { + ENC_CODERANGE_CLEAR(obj); } termlen = rb_enc_mbminlen(enc); oldtermlen = rb_enc_mbminlen(rb_enc_from_index(oldidx)); if (oldtermlen != termlen && RB_TYPE_P(obj, T_STRING)) { - rb_str_change_terminator_length(obj, oldtermlen, termlen); + rb_str_change_terminator_length(obj, oldtermlen, termlen); } enc_set_index(obj, idx); return obj; @@ -1080,9 +1080,9 @@ static rb_encoding* rb_encoding_check(rb_encoding* enc, VALUE str1, VALUE str2) { if (!enc) - rb_raise(rb_eEncCompatError, "incompatible character encodings: %s and %s", - rb_enc_name(rb_enc_get(str1)), - rb_enc_name(rb_enc_get(str2))); + rb_raise(rb_eEncCompatError, "incompatible character encodings: %s and %s", + rb_enc_name(rb_enc_get(str1)), + rb_enc_name(rb_enc_get(str2))); return enc; } @@ -1111,48 +1111,48 @@ enc_compatible_latter(VALUE str1, VALUE str2, int idx1, int idx2) isstr2 = RB_TYPE_P(str2, T_STRING); if (isstr2 && RSTRING_LEN(str2) == 0) - return enc1; + return enc1; isstr1 = RB_TYPE_P(str1, T_STRING); if (isstr1 && isstr2 && RSTRING_LEN(str1) == 0) - return (rb_enc_asciicompat(enc1) && rb_enc_str_asciionly_p(str2)) ? enc1 : enc2; + return (rb_enc_asciicompat(enc1) && rb_enc_str_asciionly_p(str2)) ? enc1 : enc2; if (!rb_enc_asciicompat(enc1) || !rb_enc_asciicompat(enc2)) { - return 0; + return 0; } /* objects whose encoding is the same of contents */ if (!isstr2 && idx2 == ENCINDEX_US_ASCII) - return enc1; + return enc1; if (!isstr1 && idx1 == ENCINDEX_US_ASCII) - return enc2; + return enc2; if (!isstr1) { - VALUE tmp = str1; - int idx0 = idx1; - str1 = str2; - str2 = tmp; - idx1 = idx2; - idx2 = idx0; - idx0 = isstr1; - isstr1 = isstr2; - isstr2 = idx0; + VALUE tmp = str1; + int idx0 = idx1; + str1 = str2; + str2 = tmp; + idx1 = idx2; + idx2 = idx0; + idx0 = isstr1; + isstr1 = isstr2; + isstr2 = idx0; } if (isstr1) { - int cr1, cr2; + int cr1, cr2; - cr1 = rb_enc_str_coderange(str1); - if (isstr2) { - cr2 = rb_enc_str_coderange(str2); - if (cr1 != cr2) { - /* may need to handle ENC_CODERANGE_BROKEN */ - if (cr1 == ENC_CODERANGE_7BIT) return enc2; - if (cr2 == ENC_CODERANGE_7BIT) return enc1; - } - if (cr2 == ENC_CODERANGE_7BIT) { - return enc1; - } - } - if (cr1 == ENC_CODERANGE_7BIT) - return enc2; + cr1 = rb_enc_str_coderange(str1); + if (isstr2) { + cr2 = rb_enc_str_coderange(str2); + if (cr1 != cr2) { + /* may need to handle ENC_CODERANGE_BROKEN */ + if (cr1 == ENC_CODERANGE_7BIT) return enc2; + if (cr2 == ENC_CODERANGE_7BIT) return enc1; + } + if (cr2 == ENC_CODERANGE_7BIT) { + return enc1; + } + } + if (cr1 == ENC_CODERANGE_7BIT) + return enc2; } return 0; } @@ -1167,10 +1167,10 @@ enc_compatible_str(VALUE str1, VALUE str2) return 0; if (idx1 == idx2) { - return rb_enc_from_index(idx1); + return rb_enc_from_index(idx1); } else { - return enc_compatible_latter(str1, str2, idx1, idx2); + return enc_compatible_latter(str1, str2, idx1, idx2); } } @@ -1184,7 +1184,7 @@ rb_enc_compatible(VALUE str1, VALUE str2) return 0; if (idx1 == idx2) { - return rb_enc_from_index(idx1); + return rb_enc_from_index(idx1); } return enc_compatible_latter(str1, str2, idx1, idx2); @@ -1209,7 +1209,7 @@ rb_obj_encoding(VALUE obj) { int idx = rb_enc_get_index(obj); if (idx < 0) { - rb_raise(rb_eTypeError, "unknown encoding"); + rb_raise(rb_eTypeError, "unknown encoding"); } return rb_enc_from_encoding_index(idx & ENC_INDEX_MASK); } @@ -1276,7 +1276,7 @@ rb_enc_codepoint_len(const char *p, const char *e, int *len_p, rb_encoding *enc) rb_raise(rb_eArgError, "empty string"); r = rb_enc_precise_mbclen(p, e, enc); if (!MBCLEN_CHARFOUND_P(r)) { - rb_raise(rb_eArgError, "invalid byte sequence in %s", rb_enc_name(enc)); + rb_raise(rb_eArgError, "invalid byte sequence in %s", rb_enc_name(enc)); } if (len_p) *len_p = MBCLEN_CHARFOUND_LEN(r); return rb_enc_mbc_to_codepoint(p, e, enc); @@ -1287,7 +1287,7 @@ rb_enc_codelen(int c, rb_encoding *enc) { int n = ONIGENC_CODE_TO_MBCLEN(enc,c); if (n == 0) { - rb_raise(rb_eArgError, "invalid codepoint 0x%x in %s", c, rb_enc_name(enc)); + rb_raise(rb_eArgError, "invalid codepoint 0x%x in %s", c, rb_enc_name(enc)); } return n; } @@ -1319,16 +1319,16 @@ enc_inspect(VALUE self) rb_encoding *enc; if (!is_data_encoding(self)) { - not_encoding(self); + not_encoding(self); } if (!(enc = DATA_PTR(self)) || rb_enc_from_index(rb_enc_to_index(enc)) != enc) { - rb_raise(rb_eTypeError, "broken Encoding"); + rb_raise(rb_eTypeError, "broken Encoding"); } return rb_enc_sprintf(rb_usascii_encoding(), - "#<%"PRIsVALUE":%s%s%s>", rb_obj_class(self), - rb_enc_name(enc), - (ENC_DUMMY_P(enc) ? " (dummy)" : ""), - rb_enc_autoload_p(enc) ? " (autoload)" : ""); + "#<%"PRIsVALUE":%s%s%s>", rb_obj_class(self), + rb_enc_name(enc), + (ENC_DUMMY_P(enc) ? " (dummy)" : ""), + rb_enc_autoload_p(enc) ? " (autoload)" : ""); } /* @@ -1352,8 +1352,8 @@ enc_names_i(st_data_t name, st_data_t idx, st_data_t args) VALUE *arg = (VALUE *)args; if ((int)idx == (int)arg[0]) { - VALUE str = rb_fstring_cstr((char *)name); - rb_ary_push(arg[1], str); + VALUE str = rb_fstring_cstr((char *)name); + rb_ary_push(arg[1], str); } return ST_CONTINUE; } @@ -1440,7 +1440,7 @@ enc_find(VALUE klass, VALUE enc) { int idx; if (is_obj_encoding(enc)) - return enc; + return enc; idx = str_to_encindex(enc); if (idx == UNSPECIFIED_ENCODING) return Qnil; return rb_enc_from_encoding_index(idx); @@ -1561,10 +1561,10 @@ rb_locale_encindex(void) GLOBAL_ENC_TABLE_ENTER(enc_table); if (enc_registered(enc_table, "locale") < 0) { # if defined _WIN32 - void Init_w32_codepage(void); - Init_w32_codepage(); + void Init_w32_codepage(void); + Init_w32_codepage(); # endif - enc_alias_internal(enc_table, "locale", idx); + enc_alias_internal(enc_table, "locale", idx); } GLOBAL_ENC_TABLE_LEAVE(); @@ -1586,7 +1586,7 @@ rb_filesystem_encindex(void) idx = enc_registered(enc_table, "filesystem")); if (idx < 0) - idx = ENCINDEX_ASCII_8BIT; + idx = ENCINDEX_ASCII_8BIT; return idx; } @@ -1609,8 +1609,8 @@ enc_set_default_encoding(struct default_encoding *def, VALUE encoding, const cha int overridden = FALSE; if (def->index != -2) - /* Already set */ - overridden = TRUE; + /* Already set */ + overridden = TRUE; GLOBAL_ENC_TABLE_ENTER(enc_table); { @@ -1809,45 +1809,45 @@ set_encoding_const(const char *name, rb_encoding *enc) if (ISDIGIT(*s)) return; if (ISUPPER(*s)) { - hasupper = 1; - while (*++s && (ISALNUM(*s) || *s == '_')) { - if (ISLOWER(*s)) haslower = 1; - } + hasupper = 1; + while (*++s && (ISALNUM(*s) || *s == '_')) { + if (ISLOWER(*s)) haslower = 1; + } } if (!*s) { - if (s - name > ENCODING_NAMELEN_MAX) return; - valid = 1; - rb_define_const(rb_cEncoding, name, encoding); + if (s - name > ENCODING_NAMELEN_MAX) return; + valid = 1; + rb_define_const(rb_cEncoding, name, encoding); } if (!valid || haslower) { - size_t len = s - name; - if (len > ENCODING_NAMELEN_MAX) return; - if (!haslower || !hasupper) { - do { - if (ISLOWER(*s)) haslower = 1; - if (ISUPPER(*s)) hasupper = 1; - } while (*++s && (!haslower || !hasupper)); - len = s - name; - } - len += strlen(s); - if (len++ > ENCODING_NAMELEN_MAX) return; - MEMCPY(s = ALLOCA_N(char, len), name, char, len); - name = s; - if (!valid) { - if (ISLOWER(*s)) *s = ONIGENC_ASCII_CODE_TO_UPPER_CASE((int)*s); - for (; *s; ++s) { - if (!ISALNUM(*s)) *s = '_'; - } - if (hasupper) { - rb_define_const(rb_cEncoding, name, encoding); - } - } - if (haslower) { - for (s = (char *)name; *s; ++s) { - if (ISLOWER(*s)) *s = ONIGENC_ASCII_CODE_TO_UPPER_CASE((int)*s); - } - rb_define_const(rb_cEncoding, name, encoding); - } + size_t len = s - name; + if (len > ENCODING_NAMELEN_MAX) return; + if (!haslower || !hasupper) { + do { + if (ISLOWER(*s)) haslower = 1; + if (ISUPPER(*s)) hasupper = 1; + } while (*++s && (!haslower || !hasupper)); + len = s - name; + } + len += strlen(s); + if (len++ > ENCODING_NAMELEN_MAX) return; + MEMCPY(s = ALLOCA_N(char, len), name, char, len); + name = s; + if (!valid) { + if (ISLOWER(*s)) *s = ONIGENC_ASCII_CODE_TO_UPPER_CASE((int)*s); + for (; *s; ++s) { + if (!ISALNUM(*s)) *s = '_'; + } + if (hasupper) { + rb_define_const(rb_cEncoding, name, encoding); + } + } + if (haslower) { + for (s = (char *)name; *s; ++s) { + if (ISLOWER(*s)) *s = ONIGENC_ASCII_CODE_TO_UPPER_CASE((int)*s); + } + rb_define_const(rb_cEncoding, name, encoding); + } } } @@ -1898,14 +1898,14 @@ rb_enc_aliases_enc_i(st_data_t name, st_data_t orig, st_data_t arg) VALUE key, str = rb_ary_entry(ary, idx); if (NIL_P(str)) { - rb_encoding *enc = rb_enc_from_index(idx); + rb_encoding *enc = rb_enc_from_index(idx); - if (!enc) return ST_CONTINUE; - if (STRCASECMP((char*)name, rb_enc_name(enc)) == 0) { - return ST_CONTINUE; - } - str = rb_fstring_cstr(rb_enc_name(enc)); - rb_ary_store(ary, idx, str); + if (!enc) return ST_CONTINUE; + if (STRCASECMP((char*)name, rb_enc_name(enc)) == 0) { + return ST_CONTINUE; + } + str = rb_fstring_cstr(rb_enc_name(enc)); + rb_ary_store(ary, idx, str); } key = rb_fstring_cstr((char *)name); rb_hash_aset(aliases, key, str); @@ -2012,7 +2012,7 @@ Init_Encoding(void) rb_gc_register_mark_object(list); for (i = 0; i < enc_table->count; ++i) { - rb_ary_push(list, enc_new(enc_table->list[i].enc)); + rb_ary_push(list, enc_new(enc_table->list[i].enc)); } rb_marshal_define_compat(rb_cEncoding, Qnil, 0, enc_m_loader); diff --git a/enum.c b/enum.c index 205ea6a451..6b69fef8a1 100644 --- a/enum.c +++ b/enum.c @@ -65,9 +65,9 @@ static VALUE enum_yield(int argc, VALUE ary) { if (argc > 1) - return rb_yield_force_blockarg(ary); + return rb_yield_force_blockarg(ary); if (argc == 1) - return rb_yield(ary); + return rb_yield(ary); return rb_yield_values2(0, 0); } @@ -77,9 +77,9 @@ enum_yield_array(VALUE ary) long len = RARRAY_LEN(ary); if (len > 1) - return rb_yield_force_blockarg(ary); + return rb_yield_force_blockarg(ary); if (len == 1) - return rb_yield(RARRAY_AREF(ary, 0)); + return rb_yield(RARRAY_AREF(ary, 0)); return rb_yield_values2(0, 0); } @@ -90,7 +90,7 @@ grep_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args)) ENUM_WANT_SVALUE(); if (RTEST(rb_funcallv(memo->v1, id_eqq, 1, &i)) == RTEST(memo->u3.value)) { - rb_ary_push(memo->v2, i); + rb_ary_push(memo->v2, i); } return Qnil; } @@ -106,7 +106,7 @@ grep_regexp_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args)) converted_element = SYMBOL_P(i) ? i : rb_check_string_type(i); match = NIL_P(converted_element) ? Qfalse : rb_reg_match_p(memo->v1, i, 0); if (match == memo->u3.value) { - rb_ary_push(memo->v2, i); + rb_ary_push(memo->v2, i); } return Qnil; } @@ -118,7 +118,7 @@ grep_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args)) ENUM_WANT_SVALUE(); if (RTEST(rb_funcallv(memo->v1, id_eqq, 1, &i)) == RTEST(memo->u3.value)) { - rb_ary_push(memo->v2, enum_yield(argc, i)); + rb_ary_push(memo->v2, enum_yield(argc, i)); } return Qnil; } @@ -130,14 +130,14 @@ enum_grep0(VALUE obj, VALUE pat, VALUE test) struct MEMO *memo = MEMO_NEW(pat, ary, test); rb_block_call_func_t fn; if (rb_block_given_p()) { - fn = grep_iter_i; + fn = grep_iter_i; } else if (RB_TYPE_P(pat, T_REGEXP) && LIKELY(rb_method_basic_definition_p(CLASS_OF(pat), idEqq))) { - fn = grep_regexp_i; + fn = grep_regexp_i; } else { - fn = grep_i; + fn = grep_i; } rb_block_call(obj, id_each, 0, 0, fn, (VALUE)memo); @@ -214,13 +214,13 @@ static void imemo_count_up(struct MEMO *memo) { if (memo->flags & COUNT_BIGNUM) { - MEMO_V3_SET(memo, rb_int_succ(memo->u3.value)); + MEMO_V3_SET(memo, rb_int_succ(memo->u3.value)); } else if (++memo->u3.cnt == 0) { - /* overflow */ - unsigned long buf[2] = {0, 1}; - MEMO_V3_SET(memo, rb_big_unpack(buf, 2)); - memo->flags |= COUNT_BIGNUM; + /* overflow */ + unsigned long buf[2] = {0, 1}; + MEMO_V3_SET(memo, rb_big_unpack(buf, 2)); + memo->flags |= COUNT_BIGNUM; } } @@ -228,10 +228,10 @@ static VALUE imemo_count_value(struct MEMO *memo) { if (memo->flags & COUNT_BIGNUM) { - return memo->u3.value; + return memo->u3.value; } else { - return ULONG2NUM(memo->u3.cnt); + return ULONG2NUM(memo->u3.cnt); } } @@ -243,7 +243,7 @@ count_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop)) ENUM_WANT_SVALUE(); if (rb_equal(i, memo->v1)) { - imemo_count_up(memo); + imemo_count_up(memo); } return Qnil; } @@ -254,7 +254,7 @@ count_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop)) struct MEMO *memo = MEMO_CAST(memop); if (RTEST(rb_yield_values2(argc, argv))) { - imemo_count_up(memo); + imemo_count_up(memo); } return Qnil; } @@ -302,18 +302,18 @@ enum_count(int argc, VALUE *argv, VALUE obj) rb_block_call_func *func; if (argc == 0) { - if (rb_block_given_p()) { - func = count_iter_i; - } - else { - func = count_all_i; - } + if (rb_block_given_p()) { + func = count_iter_i; + } + else { + func = count_all_i; + } } else { - rb_scan_args(argc, argv, "1", &item); - if (rb_block_given_p()) { - rb_warn("given block not used"); - } + rb_scan_args(argc, argv, "1", &item); + if (rb_block_given_p()) { + rb_warn("given block not used"); + } func = count_i; } @@ -328,10 +328,10 @@ find_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop)) ENUM_WANT_SVALUE(); if (RTEST(enum_yield(argc, i))) { - struct MEMO *memo = MEMO_CAST(memop); - MEMO_V1_SET(memo, i); - memo->u3.cnt = 1; - rb_iter_break(); + struct MEMO *memo = MEMO_CAST(memop); + MEMO_V1_SET(memo, i); + memo->u3.cnt = 1; + rb_iter_break(); } return Qnil; } @@ -368,10 +368,10 @@ enum_find(int argc, VALUE *argv, VALUE obj) memo = MEMO_NEW(Qundef, 0, 0); rb_block_call(obj, id_each, 0, 0, find_i, (VALUE)memo); if (memo->u3.cnt) { - return memo->v1; + return memo->v1; } if (!NIL_P(if_none)) { - return rb_funcallv(if_none, id_call, 0, 0); + return rb_funcallv(if_none, id_call, 0, 0); } return Qnil; } @@ -384,8 +384,8 @@ find_index_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop)) ENUM_WANT_SVALUE(); if (rb_equal(i, memo->v2)) { - MEMO_V1_SET(memo, imemo_count_value(memo)); - rb_iter_break(); + MEMO_V1_SET(memo, imemo_count_value(memo)); + rb_iter_break(); } imemo_count_up(memo); return Qnil; @@ -397,8 +397,8 @@ find_index_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop)) struct MEMO *memo = MEMO_CAST(memop); if (RTEST(rb_yield_values2(argc, argv))) { - MEMO_V1_SET(memo, imemo_count_value(memo)); - rb_iter_break(); + MEMO_V1_SET(memo, imemo_count_value(memo)); + rb_iter_break(); } imemo_count_up(memo); return Qnil; @@ -440,10 +440,10 @@ enum_find_index(int argc, VALUE *argv, VALUE obj) func = find_index_iter_i; } else { - rb_scan_args(argc, argv, "1", &condition_value); - if (rb_block_given_p()) { - rb_warn("given block not used"); - } + rb_scan_args(argc, argv, "1", &condition_value); + if (rb_block_given_p()) { + rb_warn("given block not used"); + } func = find_index_i; } @@ -458,7 +458,7 @@ find_all_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary)) ENUM_WANT_SVALUE(); if (RTEST(enum_yield(argc, i))) { - rb_ary_push(ary, i); + rb_ary_push(ary, i); } return Qnil; } @@ -566,7 +566,7 @@ reject_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary)) ENUM_WANT_SVALUE(); if (!RTEST(enum_yield(argc, i))) { - rb_ary_push(ary, i); + rb_ary_push(ary, i); } return Qnil; } @@ -658,10 +658,10 @@ flat_map_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary)) tmp = rb_check_array_type(i); if (NIL_P(tmp)) { - rb_ary_push(ary, i); + rb_ary_push(ary, i); } else { - rb_ary_concat(ary, tmp); + rb_ary_concat(ary, tmp); } return Qnil; } @@ -780,10 +780,10 @@ inject_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, p)) ENUM_WANT_SVALUE(); if (memo->v1 == Qundef) { - MEMO_V1_SET(memo, i); + MEMO_V1_SET(memo, i); } else { - MEMO_V1_SET(memo, rb_yield_values(2, memo->v1, i)); + MEMO_V1_SET(memo, rb_yield_values(2, memo->v1, i)); } return Qnil; } @@ -797,17 +797,17 @@ inject_op_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, p)) ENUM_WANT_SVALUE(); if (memo->v1 == Qundef) { - MEMO_V1_SET(memo, i); + MEMO_V1_SET(memo, i); } else if (SYMBOL_P(name = memo->u3.value)) { - const ID mid = SYM2ID(name); - MEMO_V1_SET(memo, rb_funcallv_public(memo->v1, mid, 1, &i)); + const ID mid = SYM2ID(name); + MEMO_V1_SET(memo, rb_funcallv_public(memo->v1, mid, 1, &i)); } else { - VALUE args[2]; - args[0] = name; - args[1] = i; - MEMO_V1_SET(memo, rb_f_send(numberof(args), args, memo->v1)); + VALUE args[2]; + args[0] = name; + args[1] = i; + MEMO_V1_SET(memo, rb_f_send(numberof(args), args, memo->v1)); } return Qnil; } @@ -835,9 +835,9 @@ ary_inject_op(VALUE ary, VALUE init, VALUE op) id = SYM2ID(op); if (id == idPLUS) { - if (RB_INTEGER_TYPE_P(v) && - rb_method_basic_definition_p(rb_cInteger, idPLUS) && - rb_obj_respond_to(v, idPLUS, FALSE)) { + if (RB_INTEGER_TYPE_P(v) && + rb_method_basic_definition_p(rb_cInteger, idPLUS) && + rb_obj_respond_to(v, idPLUS, FALSE)) { n = 0; for (; i < RARRAY_LEN(ary); i++) { e = RARRAY_AREF(ary, i); @@ -1021,25 +1021,25 @@ enum_inject(int argc, VALUE *argv, VALUE obj) switch (num_args) { case 0: - init = Qundef; - break; + init = Qundef; + break; case 1: - if (rb_block_given_p()) { - break; - } - id = rb_check_id(&init); - op = id ? ID2SYM(id) : init; - init = Qundef; - iter = inject_op_i; - break; + if (rb_block_given_p()) { + break; + } + id = rb_check_id(&init); + op = id ? ID2SYM(id) : init; + init = Qundef; + iter = inject_op_i; + break; case 2: - if (rb_block_given_p()) { - rb_warning("given block not used"); - } - id = rb_check_id(&op); - if (id) op = ID2SYM(id); - iter = inject_op_i; - break; + if (rb_block_given_p()) { + rb_warning("given block not used"); + } + id = rb_check_id(&op); + if (id) op = ID2SYM(id); + iter = inject_op_i; + break; } if (iter == inject_op_i && @@ -1063,10 +1063,10 @@ partition_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, arys)) ENUM_WANT_SVALUE(); if (RTEST(enum_yield(argc, i))) { - ary = memo->v1; + ary = memo->v1; } else { - ary = memo->v2; + ary = memo->v2; } rb_ary_push(ary, i); return Qnil; @@ -1124,11 +1124,11 @@ group_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash)) group = enum_yield(argc, i); values = rb_hash_aref(hash, group); if (!RB_TYPE_P(values, T_ARRAY)) { - values = rb_ary_new3(1, i); - rb_hash_aset(hash, group, values); + values = rb_ary_new3(1, i); + rb_hash_aset(hash, group, values); } else { - rb_ary_push(values, i); + rb_ary_push(values, i); } return Qnil; } @@ -1288,12 +1288,12 @@ enum_first(int argc, VALUE *argv, VALUE obj) struct MEMO *memo; rb_check_arity(argc, 0, 1); if (argc > 0) { - return enum_take(obj, argv[0]); + return enum_take(obj, argv[0]); } else { - memo = MEMO_NEW(Qnil, 0, 0); - rb_block_call(obj, id_each, 0, 0, first_i, (VALUE)memo); - return memo->v1; + memo = MEMO_NEW(Qnil, 0, 0); + rb_block_call(obj, id_each, 0, 0, first_i, (VALUE)memo); + return memo->v1; } } @@ -1354,18 +1354,18 @@ sort_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, _data)) v = enum_yield(argc, i); if (RBASIC(ary)->klass) { - rb_raise(rb_eRuntimeError, "sort_by reentered"); + rb_raise(rb_eRuntimeError, "sort_by reentered"); } if (RARRAY_LEN(data->buf) != SORT_BY_BUFSIZE*2) { - rb_raise(rb_eRuntimeError, "sort_by reentered"); + rb_raise(rb_eRuntimeError, "sort_by reentered"); } RARRAY_ASET(data->buf, data->n*2, v); RARRAY_ASET(data->buf, data->n*2+1, i); data->n++; if (data->n == SORT_BY_BUFSIZE) { - rb_ary_concat(ary, data->buf); - data->n = 0; + rb_ary_concat(ary, data->buf); + data->n = 0; } return Qnil; } @@ -1379,7 +1379,7 @@ sort_by_cmp(const void *ap, const void *bp, void *data) VALUE ary = (VALUE)data; if (RBASIC(ary)->klass) { - rb_raise(rb_eRuntimeError, "sort_by reentered"); + rb_raise(rb_eRuntimeError, "sort_by reentered"); } a = *(VALUE *)ap; @@ -1481,10 +1481,10 @@ enum_sort_by(VALUE obj) RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size); if (RB_TYPE_P(obj, T_ARRAY) && RARRAY_LEN(obj) <= LONG_MAX/2) { - ary = rb_ary_new2(RARRAY_LEN(obj)*2); + ary = rb_ary_new2(RARRAY_LEN(obj)*2); } else { - ary = rb_ary_new(); + ary = rb_ary_new(); } RBASIC_CLEAR_CLASS(ary); buf = rb_ary_tmp_new(SORT_BY_BUFSIZE*2); @@ -1498,8 +1498,8 @@ enum_sort_by(VALUE obj) ary = data->ary; buf = data->buf; if (data->n) { - rb_ary_resize(buf, data->n*2); - rb_ary_concat(ary, buf); + rb_ary_resize(buf, data->n*2); + rb_ary_concat(ary, buf); } if (RARRAY_LEN(ary) > 2) { RARRAY_PTR_USE(ary, ptr, @@ -1507,10 +1507,10 @@ enum_sort_by(VALUE obj) sort_by_cmp, (void *)ary)); } if (RBASIC(ary)->klass) { - rb_raise(rb_eRuntimeError, "sort_by reentered"); + rb_raise(rb_eRuntimeError, "sort_by reentered"); } for (i=1; iv1 == Qundef) { - MEMO_V1_SET(memo, Qtrue); - } - else if (memo->v1 == Qtrue) { - MEMO_V1_SET(memo, Qfalse); - rb_iter_break(); - } + if (memo->v1 == Qundef) { + MEMO_V1_SET(memo, Qtrue); + } + else if (memo->v1 == Qtrue) { + MEMO_V1_SET(memo, Qfalse); + rb_iter_break(); + } } return Qnil; } @@ -1745,7 +1745,7 @@ nmin_filter(struct nmin_data *data) long i, j; if (data->curlen <= data->n) - return; + return; n = data->n; beg = RARRAY_PTR(data->buf); @@ -1765,46 +1765,46 @@ nmin_filter(struct nmin_data *data) } while (0) while (1) { - long pivot_index = left + (right-left)/2; - long num_pivots = 1; + long pivot_index = left + (right-left)/2; + long num_pivots = 1; - SWAP(pivot_index, right); - pivot_index = right; + SWAP(pivot_index, right); + pivot_index = right; - store_index = left; - i = left; - while (i <= right-num_pivots) { - int c = data->cmpfunc(GETPTR(i), GETPTR(pivot_index), data); - if (data->rev) - c = -c; - if (c == 0) { - SWAP(i, right-num_pivots); - num_pivots++; - continue; - } - if (c < 0) { - SWAP(i, store_index); - store_index++; - } - i++; - } - j = store_index; - for (i = right; right-num_pivots < i; i--) { - if (i <= j) - break; - SWAP(j, i); - j++; - } + store_index = left; + i = left; + while (i <= right-num_pivots) { + int c = data->cmpfunc(GETPTR(i), GETPTR(pivot_index), data); + if (data->rev) + c = -c; + if (c == 0) { + SWAP(i, right-num_pivots); + num_pivots++; + continue; + } + if (c < 0) { + SWAP(i, store_index); + store_index++; + } + i++; + } + j = store_index; + for (i = right; right-num_pivots < i; i--) { + if (i <= j) + break; + SWAP(j, i); + j++; + } - if (store_index <= n && n <= store_index+num_pivots) - break; + if (store_index <= n && n <= store_index+num_pivots) + break; - if (n < store_index) { - right = store_index-1; - } - else { - left = store_index+num_pivots; - } + if (n < store_index) { + right = store_index-1; + } + else { + left = store_index+num_pivots; + } } #undef GETPTR #undef SWAP @@ -1823,9 +1823,9 @@ nmin_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, _data)) ENUM_WANT_SVALUE(); if (data->by) - cmpv = enum_yield(argc, i); + cmpv = enum_yield(argc, i); else - cmpv = i; + cmpv = i; if (data->limit != Qundef) { int c = data->cmpfunc(&cmpv, &data->limit, data); @@ -1836,13 +1836,13 @@ nmin_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, _data)) } if (data->by) - rb_ary_push(data->buf, cmpv); + rb_ary_push(data->buf, cmpv); rb_ary_push(data->buf, i); data->curlen++; if (data->curlen == data->bufmax) { - nmin_filter(data); + nmin_filter(data); } return Qnil; @@ -1867,24 +1867,24 @@ rb_nmin_run(VALUE obj, VALUE num, int by, int rev, int ary) data.limit = Qundef; data.cmpfunc = by ? nmin_cmp : rb_block_given_p() ? nmin_block_cmp : - nmin_cmp; + nmin_cmp; data.rev = rev; data.by = by; if (ary) { - long i; - for (i = 0; i < RARRAY_LEN(obj); i++) { - VALUE args[1]; - args[0] = RARRAY_AREF(obj, i); + long i; + for (i = 0; i < RARRAY_LEN(obj); i++) { + VALUE args[1]; + args[0] = RARRAY_AREF(obj, i); nmin_i(obj, (VALUE)&data, 1, args, Qundef); - } + } } else { - rb_block_call(obj, id_each, 0, 0, nmin_i, (VALUE)&data); + rb_block_call(obj, id_each, 0, 0, nmin_i, (VALUE)&data); } nmin_filter(&data); result = data.buf; if (by) { - long i; + long i; RARRAY_PTR_USE(result, ptr, { ruby_qsort(ptr, RARRAY_LEN(result)/2, @@ -1894,7 +1894,7 @@ rb_nmin_run(VALUE obj, VALUE num, int by, int rev, int ary) ptr[i/2] = ptr[i]; } }); - rb_ary_resize(result, RARRAY_LEN(result)/2); + rb_ary_resize(result, RARRAY_LEN(result)/2); } else { RARRAY_PTR_USE(result, ptr, { @@ -1969,8 +1969,8 @@ enum_one(int argc, VALUE *argv, VALUE obj) DEFINE_ENUMFUNCS(none) { if (RTEST(result)) { - MEMO_V1_SET(memo, Qfalse); - rb_iter_break(); + MEMO_V1_SET(memo, Qfalse); + rb_iter_break(); } return Qnil; } @@ -2038,12 +2038,12 @@ min_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args)) ENUM_WANT_SVALUE(); if (memo->min == Qundef) { - memo->min = i; + memo->min = i; } else { - if (OPTIMIZED_CMP(i, memo->min, memo->cmp_opt) < 0) { - memo->min = i; - } + if (OPTIMIZED_CMP(i, memo->min, memo->cmp_opt) < 0) { + memo->min = i; + } } return Qnil; } @@ -2057,13 +2057,13 @@ min_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, args)) ENUM_WANT_SVALUE(); if (memo->min == Qundef) { - memo->min = i; + memo->min = i; } else { - cmp = rb_yield_values(2, i, memo->min); - if (rb_cmpint(cmp, i, memo->min) < 0) { - memo->min = i; - } + cmp = rb_yield_values(2, i, memo->min); + if (rb_cmpint(cmp, i, memo->min) < 0) { + memo->min = i; + } } return Qnil; } @@ -2141,10 +2141,10 @@ enum_min(int argc, VALUE *argv, VALUE obj) m->cmp_opt.opt_methods = 0; m->cmp_opt.opt_inited = 0; if (rb_block_given_p()) { - rb_block_call(obj, id_each, 0, 0, min_ii, memo); + rb_block_call(obj, id_each, 0, 0, min_ii, memo); } else { - rb_block_call(obj, id_each, 0, 0, min_i, memo); + rb_block_call(obj, id_each, 0, 0, min_i, memo); } result = m->min; if (result == Qundef) return Qnil; @@ -2164,12 +2164,12 @@ max_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args)) ENUM_WANT_SVALUE(); if (memo->max == Qundef) { - memo->max = i; + memo->max = i; } else { - if (OPTIMIZED_CMP(i, memo->max, memo->cmp_opt) > 0) { - memo->max = i; - } + if (OPTIMIZED_CMP(i, memo->max, memo->cmp_opt) > 0) { + memo->max = i; + } } return Qnil; } @@ -2183,13 +2183,13 @@ max_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, args)) ENUM_WANT_SVALUE(); if (memo->max == Qundef) { - memo->max = i; + memo->max = i; } else { - cmp = rb_yield_values(2, i, memo->max); - if (rb_cmpint(cmp, i, memo->max) > 0) { - memo->max = i; - } + cmp = rb_yield_values(2, i, memo->max); + if (rb_cmpint(cmp, i, memo->max) > 0) { + memo->max = i; + } } return Qnil; } @@ -2266,10 +2266,10 @@ enum_max(int argc, VALUE *argv, VALUE obj) m->cmp_opt.opt_methods = 0; m->cmp_opt.opt_inited = 0; if (rb_block_given_p()) { - rb_block_call(obj, id_each, 0, 0, max_ii, (VALUE)memo); + rb_block_call(obj, id_each, 0, 0, max_ii, (VALUE)memo); } else { - rb_block_call(obj, id_each, 0, 0, max_i, (VALUE)memo); + rb_block_call(obj, id_each, 0, 0, max_i, (VALUE)memo); } result = m->max; if (result == Qundef) return Qnil; @@ -2289,18 +2289,18 @@ minmax_i_update(VALUE i, VALUE j, struct minmax_t *memo) int n; if (memo->min == Qundef) { - memo->min = i; - memo->max = j; + memo->min = i; + memo->max = j; } else { - n = OPTIMIZED_CMP(i, memo->min, memo->cmp_opt); - if (n < 0) { - memo->min = i; - } - n = OPTIMIZED_CMP(j, memo->max, memo->cmp_opt); - if (n > 0) { - memo->max = j; - } + n = OPTIMIZED_CMP(i, memo->min, memo->cmp_opt); + if (n < 0) { + memo->min = i; + } + n = OPTIMIZED_CMP(j, memo->max, memo->cmp_opt); + if (n > 0) { + memo->max = j; + } } } @@ -2341,18 +2341,18 @@ minmax_ii_update(VALUE i, VALUE j, struct minmax_t *memo) int n; if (memo->min == Qundef) { - memo->min = i; - memo->max = j; + memo->min = i; + memo->max = j; } else { - n = rb_cmpint(rb_yield_values(2, i, memo->min), i, memo->min); - if (n < 0) { - memo->min = i; - } - n = rb_cmpint(rb_yield_values(2, j, memo->max), j, memo->max); - if (n > 0) { - memo->max = j; - } + n = rb_cmpint(rb_yield_values(2, i, memo->min), i, memo->min); + if (n < 0) { + memo->min = i; + } + n = rb_cmpint(rb_yield_values(2, j, memo->max), j, memo->max); + if (n > 0) { + memo->max = j; + } } } @@ -2429,17 +2429,17 @@ enum_minmax(VALUE obj) m->cmp_opt.opt_methods = 0; m->cmp_opt.opt_inited = 0; if (rb_block_given_p()) { - rb_block_call(obj, id_each, 0, 0, minmax_ii, memo); - if (m->last != Qundef) - minmax_ii_update(m->last, m->last, m); + rb_block_call(obj, id_each, 0, 0, minmax_ii, memo); + if (m->last != Qundef) + minmax_ii_update(m->last, m->last, m); } else { - rb_block_call(obj, id_each, 0, 0, minmax_i, memo); - if (m->last != Qundef) - minmax_i_update(m->last, m->last, m); + rb_block_call(obj, id_each, 0, 0, minmax_i, memo); + if (m->last != Qundef) + minmax_i_update(m->last, m->last, m); } if (m->min != Qundef) { - return rb_assoc_new(m->min, m->max); + return rb_assoc_new(m->min, m->max); } return rb_assoc_new(Qnil, Qnil); } @@ -2455,12 +2455,12 @@ min_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args)) v = enum_yield(argc, i); if (memo->v1 == Qundef) { - MEMO_V1_SET(memo, v); - MEMO_V2_SET(memo, i); + MEMO_V1_SET(memo, v); + MEMO_V2_SET(memo, i); } else if (OPTIMIZED_CMP(v, memo->v1, cmp_opt) < 0) { - MEMO_V1_SET(memo, v); - MEMO_V2_SET(memo, i); + MEMO_V1_SET(memo, v); + MEMO_V2_SET(memo, i); } return Qnil; } @@ -2530,12 +2530,12 @@ max_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args)) v = enum_yield(argc, i); if (memo->v1 == Qundef) { - MEMO_V1_SET(memo, v); - MEMO_V2_SET(memo, i); + MEMO_V1_SET(memo, v); + MEMO_V2_SET(memo, i); } else if (OPTIMIZED_CMP(v, memo->v1, cmp_opt) > 0) { - MEMO_V1_SET(memo, v); - MEMO_V2_SET(memo, i); + MEMO_V1_SET(memo, v); + MEMO_V2_SET(memo, i); } return Qnil; } @@ -2609,20 +2609,20 @@ minmax_by_i_update(VALUE v1, VALUE v2, VALUE i1, VALUE i2, struct minmax_by_t *m struct cmp_opt_data cmp_opt = { 0, 0 }; if (memo->min_bv == Qundef) { - memo->min_bv = v1; - memo->max_bv = v2; - memo->min = i1; - memo->max = i2; + memo->min_bv = v1; + memo->max_bv = v2; + memo->min = i1; + memo->max = i2; } else { - if (OPTIMIZED_CMP(v1, memo->min_bv, cmp_opt) < 0) { - memo->min_bv = v1; - memo->min = i1; - } - if (OPTIMIZED_CMP(v2, memo->max_bv, cmp_opt) > 0) { - memo->max_bv = v2; - memo->max = i2; - } + if (OPTIMIZED_CMP(v1, memo->min_bv, cmp_opt) < 0) { + memo->min_bv = v1; + memo->min = i1; + } + if (OPTIMIZED_CMP(v2, memo->max_bv, cmp_opt) > 0) { + memo->max_bv = v2; + memo->max = i2; + } } } @@ -2717,8 +2717,8 @@ member_i(RB_BLOCK_CALL_FUNC_ARGLIST(iter, args)) struct MEMO *memo = MEMO_CAST(args); if (rb_equal(rb_enum_values_pack(argc, argv), memo->v1)) { - MEMO_V2_SET(memo, Qtrue); - rb_iter_break(); + MEMO_V2_SET(memo, Qtrue); + rb_iter_break(); } return Qnil; } @@ -2935,14 +2935,14 @@ each_slice_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, m)) rb_ary_push(ary, i); if (RARRAY_LEN(ary) == size) { - v = rb_yield(ary); + v = rb_yield(ary); - if (memo->v2) { - MEMO_V1_SET(memo, rb_ary_new2(size)); - } - else { - rb_ary_clear(ary); - } + if (memo->v2) { + MEMO_V1_SET(memo, rb_ary_new2(size)); + } + else { + rb_ary_clear(ary); + } } return v; @@ -3018,14 +3018,14 @@ each_cons_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args)) ENUM_WANT_SVALUE(); if (RARRAY_LEN(ary) == size) { - rb_ary_shift(ary); + rb_ary_shift(ary); } rb_ary_push(ary, i); if (RARRAY_LEN(ary) == size) { - if (memo->v2) { - ary = rb_ary_dup(ary); - } - v = rb_yield(ary); + if (memo->v2) { + ary = rb_ary_dup(ary); + } + v = rb_yield(ary); } return v; } @@ -3130,20 +3130,20 @@ zip_ary(RB_BLOCK_CALL_FUNC_ARGLIST(val, memoval)) tmp = rb_ary_new2(RARRAY_LEN(args) + 1); rb_ary_store(tmp, 0, rb_enum_values_pack(argc, argv)); for (i=0; iu3.cnt == 0) { - rb_ary_push(memo->v1, rb_enum_values_pack(argc, argv)); + rb_ary_push(memo->v1, rb_enum_values_pack(argc, argv)); } else { - memo->u3.cnt--; + memo->u3.cnt--; } return Qnil; } @@ -3433,7 +3433,7 @@ enum_drop(VALUE obj, VALUE n) long len = NUM2LONG(n); if (len < 0) { - rb_raise(rb_eArgError, "attempt to drop negative size"); + rb_raise(rb_eArgError, "attempt to drop negative size"); } result = rb_ary_new(); @@ -3450,10 +3450,10 @@ drop_while_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args)) ENUM_WANT_SVALUE(); if (!memo->u3.state && !RTEST(enum_yield(argc, i))) { - memo->u3.state = TRUE; + memo->u3.state = TRUE; } if (memo->u3.state) { - rb_ary_push(memo->v1, i); + rb_ary_push(memo->v1, i); } return Qnil; } @@ -3508,8 +3508,8 @@ enum_cycle_size(VALUE self, VALUE args, VALUE eobj) VALUE size; if (args && (RARRAY_LEN(args) > 0)) { - n = RARRAY_AREF(args, 0); - if (!NIL_P(n)) mul = NUM2LONG(n); + n = RARRAY_AREF(args, 0); + if (!NIL_P(n)) mul = NUM2LONG(n); } size = enum_size(self, args, 0); @@ -3572,7 +3572,7 @@ enum_cycle(int argc, VALUE *argv, VALUE obj) if (len == 0) return Qnil; while (n < 0 || 0 < --n) { for (i=0; iprev_value)) { - s = rb_assoc_new(argp->prev_value, argp->prev_elts); + s = rb_assoc_new(argp->prev_value, argp->prev_elts); rb_funcallv(argp->yielder, id_lshift, 1, &s); argp->prev_value = argp->prev_elts = Qnil; } - v = rb_assoc_new(v, rb_ary_new3(1, i)); + v = rb_assoc_new(v, rb_ary_new3(1, i)); rb_funcallv(argp->yielder, id_lshift, 1, &v); } else if (NIL_P(v) || v == separator) { if (!NIL_P(argp->prev_value)) { - v = rb_assoc_new(argp->prev_value, argp->prev_elts); + v = rb_assoc_new(argp->prev_value, argp->prev_elts); rb_funcallv(argp->yielder, id_lshift, 1, &v); argp->prev_value = argp->prev_elts = Qnil; } } else if (SYMBOL_P(v) && (s = rb_sym2str(v), RSTRING_PTR(s)[0] == '_')) { - rb_raise(rb_eRuntimeError, "symbols beginning with an underscore are reserved"); + rb_raise(rb_eRuntimeError, "symbols beginning with an underscore are reserved"); } else { if (NIL_P(argp->prev_value)) { @@ -3626,7 +3626,7 @@ chunk_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _argp)) rb_ary_push(argp->prev_elts, i); } else { - s = rb_assoc_new(argp->prev_value, argp->prev_elts); + s = rb_assoc_new(argp->prev_value, argp->prev_elts); rb_funcallv(argp->yielder, id_lshift, 1, &s); argp->prev_value = v; argp->prev_elts = rb_ary_new3(1, i); @@ -3652,8 +3652,8 @@ chunk_i(RB_BLOCK_CALL_FUNC_ARGLIST(yielder, enumerator)) rb_block_call(enumerable, id_each, 0, 0, chunk_ii, arg); memo = MEMO_FOR(struct chunk_arg, arg); if (!NIL_P(memo->prev_elts)) { - arg = rb_assoc_new(memo->prev_value, memo->prev_elts); - rb_funcallv(memo->yielder, id_lshift, 1, &arg); + arg = rb_assoc_new(memo->prev_value, memo->prev_elts); + rb_funcallv(memo->yielder, id_lshift, 1, &arg); } return Qnil; } @@ -4161,9 +4161,9 @@ slicewhen_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo)) memo->prev_elts = rb_ary_new3(1, i); } else { - VALUE args[2]; - args[0] = memo->prev_elt; - args[1] = i; + VALUE args[2]; + args[0] = memo->prev_elt; + args[1] = i; split_p = RTEST(rb_funcallv(memo->pred, id_call, 2, args)); UPDATE_MEMO; @@ -4192,7 +4192,7 @@ slicewhen_i(RB_BLOCK_CALL_FUNC_ARGLIST(yielder, enumerator)) VALUE enumerable; VALUE arg; struct slicewhen_arg *memo = - NEW_PARTIAL_MEMO_FOR(struct slicewhen_arg, arg, inverted); + NEW_PARTIAL_MEMO_FOR(struct slicewhen_arg, arg, inverted); enumerable = rb_ivar_get(enumerator, id_slicewhen_enum); memo->pred = rb_attr_get(enumerator, id_slicewhen_pred); @@ -4665,7 +4665,7 @@ enum_uniq(VALUE obj) { VALUE hash, ret; rb_block_call_func *const func = - rb_block_given_p() ? uniq_iter : uniq_func; + rb_block_given_p() ? uniq_iter : uniq_func; hash = rb_obj_hide(rb_hash_new()); rb_block_call(obj, id_each, 0, 0, func, hash); diff --git a/enumerator.c b/enumerator.c index be469ee38b..89abf4b888 100644 --- a/enumerator.c +++ b/enumerator.c @@ -240,9 +240,9 @@ enumerator_memsize(const void *p) static const rb_data_type_t enumerator_data_type = { "enumerator", { - enumerator_mark, - enumerator_free, - enumerator_memsize, + enumerator_mark, + enumerator_free, + enumerator_memsize, enumerator_compact, }, 0, 0, RUBY_TYPED_FREE_IMMEDIATELY @@ -255,7 +255,7 @@ enumerator_ptr(VALUE obj) TypedData_Get_Struct(obj, struct enumerator, &enumerator_data_type, ptr); if (!ptr || ptr->obj == Qundef) { - rb_raise(rb_eArgError, "uninitialized enumerator"); + rb_raise(rb_eArgError, "uninitialized enumerator"); } return ptr; } @@ -287,9 +287,9 @@ proc_entry_memsize(const void *p) static const rb_data_type_t proc_entry_data_type = { "proc_entry", { - proc_entry_mark, - proc_entry_free, - proc_entry_memsize, + proc_entry_mark, + proc_entry_free, + proc_entry_memsize, proc_entry_compact, }, }; @@ -371,12 +371,12 @@ obj_to_enum(int argc, VALUE *argv, VALUE obj) VALUE enumerator, meth = sym_each; if (argc > 0) { - --argc; - meth = *argv++; + --argc; + meth = *argv++; } enumerator = rb_enumeratorize_with_size(obj, meth, argc, argv, 0); if (rb_block_given_p()) { - enumerator_ptr(enumerator)->size = rb_block_proc(); + enumerator_ptr(enumerator)->size = rb_block_proc(); } return enumerator; } @@ -402,7 +402,7 @@ enumerator_init(VALUE enum_obj, VALUE obj, VALUE meth, int argc, const VALUE *ar TypedData_Get_Struct(enum_obj, struct enumerator, &enumerator_data_type, ptr); if (!ptr) { - rb_raise(rb_eArgError, "unallocated enumerator"); + rb_raise(rb_eArgError, "unallocated enumerator"); } ptr->obj = obj; @@ -482,14 +482,14 @@ enumerator_init_copy(VALUE obj, VALUE orig) if (!OBJ_INIT_COPY(obj, orig)) return obj; ptr0 = enumerator_ptr(orig); if (ptr0->fib) { - /* Fibers cannot be copied */ - rb_raise(rb_eTypeError, "can't copy execution context"); + /* Fibers cannot be copied */ + rb_raise(rb_eTypeError, "can't copy execution context"); } TypedData_Get_Struct(obj, struct enumerator, &enumerator_data_type, ptr1); if (!ptr1) { - rb_raise(rb_eArgError, "unallocated enumerator"); + rb_raise(rb_eArgError, "unallocated enumerator"); } ptr1->obj = ptr0->obj; @@ -547,8 +547,8 @@ enumerator_block_call(VALUE obj, rb_block_call_func *func, VALUE arg) ID meth = e->meth; if (e->args) { - argc = RARRAY_LENINT(e->args); - argv = RARRAY_CONST_PTR(e->args); + argc = RARRAY_LENINT(e->args); + argv = RARRAY_CONST_PTR(e->args); } return rb_block_call_kw(e->obj, meth, argc, argv, func, arg, e->kw_splat); } @@ -593,20 +593,20 @@ static VALUE enumerator_each(int argc, VALUE *argv, VALUE obj) { if (argc > 0) { - struct enumerator *e = enumerator_ptr(obj = rb_obj_dup(obj)); - VALUE args = e->args; - if (args) { + struct enumerator *e = enumerator_ptr(obj = rb_obj_dup(obj)); + VALUE args = e->args; + if (args) { #if SIZEOF_INT < SIZEOF_LONG - /* check int range overflow */ - rb_long2int(RARRAY_LEN(args) + argc); + /* check int range overflow */ + rb_long2int(RARRAY_LEN(args) + argc); #endif - args = rb_ary_dup(args); - rb_ary_cat(args, argv, argc); - } - else { - args = rb_ary_new4(argc, argv); - } - e->args = args; + args = rb_ary_dup(args); + rb_ary_cat(args, argv, argc); + } + else { + args = rb_ary_new4(argc, argv); + } + e->args = args; e->size = Qnil; e->size_fn = 0; } @@ -622,7 +622,7 @@ enumerator_with_index_i(RB_BLOCK_CALL_FUNC_ARGLIST(val, m)) MEMO_V1_SET(memo, rb_int_succ(idx)); if (argc <= 1) - return rb_yield_values(2, val, idx); + return rb_yield_values(2, val, idx); return rb_yield_values(2, rb_ary_new4(argc, argv), idx); } @@ -679,7 +679,7 @@ static VALUE enumerator_with_object_i(RB_BLOCK_CALL_FUNC_ARGLIST(val, memo)) { if (argc <= 1) - return rb_yield_values(2, val, memo); + return rb_yield_values(2, val, memo); return rb_yield_values(2, rb_ary_new4(argc, argv), memo); } @@ -764,21 +764,21 @@ get_next_values(VALUE obj, struct enumerator *e) VALUE curr, vs; if (e->stop_exc) - rb_exc_raise(e->stop_exc); + rb_exc_raise(e->stop_exc); curr = rb_fiber_current(); if (!e->fib || !rb_fiber_alive_p(e->fib)) { - next_init(obj, e); + next_init(obj, e); } vs = rb_fiber_resume(e->fib, 1, &curr); if (e->stop_exc) { - e->fib = 0; - e->dst = Qnil; - e->lookahead = Qundef; - e->feedvalue = Qundef; - rb_exc_raise(e->stop_exc); + e->fib = 0; + e->dst = Qnil; + e->lookahead = Qundef; + e->feedvalue = Qundef; + rb_exc_raise(e->stop_exc); } return vs; } @@ -1020,7 +1020,7 @@ enumerator_feed(VALUE obj, VALUE v) struct enumerator *e = enumerator_ptr(obj); if (e->feedvalue != Qundef) { - rb_raise(rb_eTypeError, "feed value already set"); + rb_raise(rb_eTypeError, "feed value already set"); } e->feedvalue = v; @@ -1065,36 +1065,36 @@ inspect_enumerator(VALUE obj, VALUE dummy, int recur) cname = rb_obj_class(obj); if (!e || e->obj == Qundef) { - return rb_sprintf("#<%"PRIsVALUE": uninitialized>", rb_class_path(cname)); + return rb_sprintf("#<%"PRIsVALUE": uninitialized>", rb_class_path(cname)); } if (recur) { - str = rb_sprintf("#<%"PRIsVALUE": ...>", rb_class_path(cname)); - return str; + str = rb_sprintf("#<%"PRIsVALUE": ...>", rb_class_path(cname)); + return str; } if (e->procs) { - long i; + long i; - eobj = generator_ptr(e->obj)->obj; - /* In case procs chained enumerator traversing all proc entries manually */ - if (rb_obj_class(eobj) == cname) { - str = rb_inspect(eobj); - } - else { - str = rb_sprintf("#<%"PRIsVALUE": %+"PRIsVALUE">", rb_class_path(cname), eobj); - } - for (i = 0; i < RARRAY_LEN(e->procs); i++) { - str = rb_sprintf("#<%"PRIsVALUE": %"PRIsVALUE, cname, str); - append_method(RARRAY_AREF(e->procs, i), str, e->meth, e->args); - rb_str_buf_cat2(str, ">"); - } - return str; + eobj = generator_ptr(e->obj)->obj; + /* In case procs chained enumerator traversing all proc entries manually */ + if (rb_obj_class(eobj) == cname) { + str = rb_inspect(eobj); + } + else { + str = rb_sprintf("#<%"PRIsVALUE": %+"PRIsVALUE">", rb_class_path(cname), eobj); + } + for (i = 0; i < RARRAY_LEN(e->procs); i++) { + str = rb_sprintf("#<%"PRIsVALUE": %"PRIsVALUE, cname, str); + append_method(RARRAY_AREF(e->procs, i), str, e->meth, e->args); + rb_str_buf_cat2(str, ">"); + } + return str; } eobj = rb_attr_get(obj, id_receiver); if (NIL_P(eobj)) { - eobj = e->obj; + eobj = e->obj; } /* (1..100).each_cons(2) => "#" */ @@ -1129,48 +1129,48 @@ append_method(VALUE obj, VALUE str, ID default_method, VALUE default_args) method = rb_attr_get(obj, id_method); if (method != Qfalse) { - if (!NIL_P(method)) { - Check_Type(method, T_SYMBOL); - method = rb_sym2str(method); - } - else { - method = rb_id2str(default_method); - } - rb_str_buf_cat2(str, ":"); - rb_str_buf_append(str, method); + if (!NIL_P(method)) { + Check_Type(method, T_SYMBOL); + method = rb_sym2str(method); + } + else { + method = rb_id2str(default_method); + } + rb_str_buf_cat2(str, ":"); + rb_str_buf_append(str, method); } eargs = rb_attr_get(obj, id_arguments); if (NIL_P(eargs)) { - eargs = default_args; + eargs = default_args; } if (eargs != Qfalse) { - long argc = RARRAY_LEN(eargs); - const VALUE *argv = RARRAY_CONST_PTR(eargs); /* WB: no new reference */ + long argc = RARRAY_LEN(eargs); + const VALUE *argv = RARRAY_CONST_PTR(eargs); /* WB: no new reference */ - if (argc > 0) { - VALUE kwds = Qnil; + if (argc > 0) { + VALUE kwds = Qnil; - rb_str_buf_cat2(str, "("); + rb_str_buf_cat2(str, "("); if (RB_TYPE_P(argv[argc-1], T_HASH) && !RHASH_EMPTY_P(argv[argc-1])) { - int all_key = TRUE; - rb_hash_foreach(argv[argc-1], key_symbol_p, (VALUE)&all_key); - if (all_key) kwds = argv[--argc]; - } + int all_key = TRUE; + rb_hash_foreach(argv[argc-1], key_symbol_p, (VALUE)&all_key); + if (all_key) kwds = argv[--argc]; + } - while (argc--) { - VALUE arg = *argv++; + while (argc--) { + VALUE arg = *argv++; - rb_str_append(str, rb_inspect(arg)); - rb_str_buf_cat2(str, ", "); - } - if (!NIL_P(kwds)) { - rb_hash_foreach(kwds, kwd_append, str); - } - rb_str_set_len(str, RSTRING_LEN(str)-2); - rb_str_buf_cat2(str, ")"); - } + rb_str_append(str, rb_inspect(arg)); + rb_str_buf_cat2(str, ", "); + } + if (!NIL_P(kwds)) { + rb_hash_foreach(kwds, kwd_append, str); + } + rb_str_set_len(str, RSTRING_LEN(str)-2); + rb_str_buf_cat2(str, ")"); + } } return str; @@ -1209,28 +1209,28 @@ enumerator_size(VALUE obj) VALUE size; if (e->procs) { - struct generator *g = generator_ptr(e->obj); - VALUE receiver = rb_check_funcall(g->obj, id_size, 0, 0); - long i = 0; + struct generator *g = generator_ptr(e->obj); + VALUE receiver = rb_check_funcall(g->obj, id_size, 0, 0); + long i = 0; - for (i = 0; i < RARRAY_LEN(e->procs); i++) { - VALUE proc = RARRAY_AREF(e->procs, i); - struct proc_entry *entry = proc_entry_ptr(proc); - lazyenum_size_func *size_fn = entry->fn->size; - if (!size_fn) { - return Qnil; - } - receiver = (*size_fn)(proc, receiver); - } - return receiver; + for (i = 0; i < RARRAY_LEN(e->procs); i++) { + VALUE proc = RARRAY_AREF(e->procs, i); + struct proc_entry *entry = proc_entry_ptr(proc); + lazyenum_size_func *size_fn = entry->fn->size; + if (!size_fn) { + return Qnil; + } + receiver = (*size_fn)(proc, receiver); + } + return receiver; } if (e->size_fn) { - return (*e->size_fn)(e->obj, e->args, obj); + return (*e->size_fn)(e->obj, e->args, obj); } if (e->args) { - argc = (int)RARRAY_LEN(e->args); - argv = RARRAY_CONST_PTR(e->args); + argc = (int)RARRAY_LEN(e->args); + argv = RARRAY_CONST_PTR(e->args); } size = rb_check_funcall_kw(e->size, id_call, argc, argv, e->kw_splat); if (size != Qundef) return size; @@ -1265,9 +1265,9 @@ yielder_memsize(const void *p) static const rb_data_type_t yielder_data_type = { "yielder", { - yielder_mark, - yielder_free, - yielder_memsize, + yielder_mark, + yielder_free, + yielder_memsize, yielder_compact, }, 0, 0, RUBY_TYPED_FREE_IMMEDIATELY @@ -1280,7 +1280,7 @@ yielder_ptr(VALUE obj) TypedData_Get_Struct(obj, struct yielder, &yielder_data_type, ptr); if (!ptr || ptr->proc == Qundef) { - rb_raise(rb_eArgError, "uninitialized yielder"); + rb_raise(rb_eArgError, "uninitialized yielder"); } return ptr; } @@ -1306,7 +1306,7 @@ yielder_init(VALUE obj, VALUE proc) TypedData_Get_Struct(obj, struct yielder, &yielder_data_type, ptr); if (!ptr) { - rb_raise(rb_eArgError, "unallocated yielder"); + rb_raise(rb_eArgError, "unallocated yielder"); } ptr->proc = proc; @@ -1405,9 +1405,9 @@ generator_memsize(const void *p) static const rb_data_type_t generator_data_type = { "generator", { - generator_mark, - generator_free, - generator_memsize, + generator_mark, + generator_free, + generator_memsize, generator_compact, }, 0, 0, RUBY_TYPED_FREE_IMMEDIATELY @@ -1420,7 +1420,7 @@ generator_ptr(VALUE obj) TypedData_Get_Struct(obj, struct generator, &generator_data_type, ptr); if (!ptr || ptr->proc == Qundef) { - rb_raise(rb_eArgError, "uninitialized generator"); + rb_raise(rb_eArgError, "uninitialized generator"); } return ptr; } @@ -1447,7 +1447,7 @@ generator_init(VALUE obj, VALUE proc) TypedData_Get_Struct(obj, struct generator, &generator_data_type, ptr); if (!ptr) { - rb_raise(rb_eArgError, "unallocated generator"); + rb_raise(rb_eArgError, "unallocated generator"); } ptr->proc = proc; @@ -1462,21 +1462,21 @@ generator_initialize(int argc, VALUE *argv, VALUE obj) VALUE proc; if (argc == 0) { - rb_need_block(); + rb_need_block(); - proc = rb_block_proc(); + proc = rb_block_proc(); } else { - rb_scan_args(argc, argv, "1", &proc); + rb_scan_args(argc, argv, "1", &proc); - if (!rb_obj_is_proc(proc)) - rb_raise(rb_eTypeError, - "wrong argument type %"PRIsVALUE" (expected Proc)", - rb_obj_class(proc)); + if (!rb_obj_is_proc(proc)) + rb_raise(rb_eTypeError, + "wrong argument type %"PRIsVALUE" (expected Proc)", + rb_obj_class(proc)); - if (rb_block_given_p()) { - rb_warn("given block not used"); - } + if (rb_block_given_p()) { + rb_warn("given block not used"); + } } return generator_init(obj, proc); @@ -1495,7 +1495,7 @@ generator_init_copy(VALUE obj, VALUE orig) TypedData_Get_Struct(obj, struct generator, &generator_data_type, ptr1); if (!ptr1) { - rb_raise(rb_eArgError, "unallocated generator"); + rb_raise(rb_eArgError, "unallocated generator"); } ptr1->proc = ptr0->proc; @@ -1512,7 +1512,7 @@ generator_each(int argc, VALUE *argv, VALUE obj) rb_ary_push(args, yielder_new()); if (argc > 0) { - rb_ary_cat(args, argv, argc); + rb_ary_cat(args, argv, argc); } return rb_proc_call_kw(ptr->proc, args, RB_PASS_CALLED_KEYWORDS); @@ -1539,22 +1539,22 @@ lazy_init_iterator(RB_BLOCK_CALL_FUNC_ARGLIST(val, m)) { VALUE result; if (argc == 1) { - VALUE args[2]; - args[0] = m; - args[1] = val; - result = rb_yield_values2(2, args); + VALUE args[2]; + args[0] = m; + args[1] = val; + result = rb_yield_values2(2, args); } else { - VALUE args; - int len = rb_long2int((long)argc + 1); - VALUE *nargv = ALLOCV_N(VALUE, args, len); + VALUE args; + int len = rb_long2int((long)argc + 1); + VALUE *nargv = ALLOCV_N(VALUE, args, len); - nargv[0] = m; - if (argc > 0) { - MEMCPY(nargv + 1, argv, VALUE, argc); - } - result = rb_yield_values2(len, nargv); - ALLOCV_END(args); + nargv[0] = m; + if (argc > 0) { + MEMCPY(nargv + 1, argv, VALUE, argc); + } + result = rb_yield_values2(len, nargv); + ALLOCV_END(args); } if (result == Qundef) rb_iter_break(); return Qnil; @@ -1590,7 +1590,7 @@ lazy_init_yielder(RB_BLOCK_CALL_FUNC_ARGLIST(_, m)) struct MEMO *result; result = MEMO_NEW(m, rb_enum_values_pack(argc, argv), - argc > 1 ? LAZY_MEMO_PACKED : 0); + argc > 1 ? LAZY_MEMO_PACKED : 0); return lazy_yielder_result(result, yielder, procs_array, memos, 0); } @@ -1615,19 +1615,19 @@ lazy_yielder_result(struct MEMO *result, VALUE yielder, VALUE procs_array, VALUE int cont = 1; for (; i < RARRAY_LEN(procs_array); i++) { - VALUE proc = RARRAY_AREF(procs_array, i); - struct proc_entry *entry = proc_entry_ptr(proc); - if (!(*entry->fn->proc)(proc, result, memos, i)) { - cont = 0; - break; - } + VALUE proc = RARRAY_AREF(procs_array, i); + struct proc_entry *entry = proc_entry_ptr(proc); + if (!(*entry->fn->proc)(proc, result, memos, i)) { + cont = 0; + break; + } } if (cont) { - rb_funcall2(yielder, idLTLT, 1, &(result->memo_value)); + rb_funcall2(yielder, idLTLT, 1, &(result->memo_value)); } if (LAZY_MEMO_BREAK_P(result)) { - rb_iter_break(); + rb_iter_break(); } return result->memo_value; } @@ -1639,7 +1639,7 @@ lazy_init_block(RB_BLOCK_CALL_FUNC_ARGLIST(val, m)) rb_ivar_set(val, id_memo, rb_ary_new2(RARRAY_LEN(procs))); rb_block_call(RARRAY_AREF(m, 0), id_each, 0, 0, - lazy_init_yielder, rb_ary_new3(2, val, procs)); + lazy_init_yielder, rb_ary_new3(2, val, procs)); return Qnil; } @@ -1652,17 +1652,17 @@ lazy_generator_init(VALUE enumerator, VALUE procs) struct enumerator *e = enumerator_ptr(enumerator); if (RARRAY_LEN(procs) > 0) { - struct generator *old_gen_ptr = generator_ptr(e->obj); - obj = old_gen_ptr->obj; + struct generator *old_gen_ptr = generator_ptr(e->obj); + obj = old_gen_ptr->obj; } else { - obj = enumerator; + obj = enumerator; } generator = generator_allocate(rb_cGenerator); rb_block_call(generator, id_initialize, 0, 0, - lazy_init_block, rb_ary_new3(2, obj, procs)); + lazy_init_block, rb_ary_new3(2, obj, procs)); gen_ptr = generator_ptr(generator); gen_ptr->obj = obj; @@ -1767,11 +1767,11 @@ lazy_initialize(int argc, VALUE *argv, VALUE self) rb_check_arity(argc, 1, 2); if (!rb_block_given_p()) { - rb_raise(rb_eArgError, "tried to call lazy new without a block"); + rb_raise(rb_eArgError, "tried to call lazy new without a block"); } obj = argv[0]; if (argc > 1) { - size = argv[1]; + size = argv[1]; } generator = generator_allocate(rb_cGenerator); rb_block_call(generator, id_initialize, 0, 0, lazy_init_block_i, obj); @@ -1801,11 +1801,11 @@ lazy_set_args(VALUE lazy, VALUE args) ID id = rb_frame_this_func(); rb_ivar_set(lazy, id_method, ID2SYM(id)); if (NIL_P(args)) { - /* Qfalse indicates that the arguments are empty */ - rb_ivar_set(lazy, id_arguments, Qfalse); + /* Qfalse indicates that the arguments are empty */ + rb_ivar_set(lazy, id_arguments, Qfalse); } else { - rb_ivar_set(lazy, id_arguments, args); + rb_ivar_set(lazy, id_arguments, args); } } @@ -1822,7 +1822,7 @@ lazy_set_method(VALUE lazy, VALUE args, rb_enumerator_size_func *size_fn) static VALUE lazy_add_method(VALUE obj, int argc, VALUE *argv, VALUE args, VALUE memo, - const lazyenum_funcs *fn) + const lazyenum_funcs *fn) { struct enumerator *new_e; VALUE new_obj; @@ -1831,9 +1831,9 @@ lazy_add_method(VALUE obj, int argc, VALUE *argv, VALUE args, VALUE memo, struct enumerator *e = enumerator_ptr(obj); struct proc_entry *entry; VALUE entry_obj = TypedData_Make_Struct(rb_cObject, struct proc_entry, - &proc_entry_data_type, entry); + &proc_entry_data_type, entry); if (rb_block_given_p()) { - entry->proc = rb_block_proc(); + entry->proc = rb_block_proc(); } entry->fn = fn; entry->memo = args; @@ -1850,11 +1850,11 @@ lazy_add_method(VALUE obj, int argc, VALUE *argv, VALUE args, VALUE memo, new_e->procs = new_procs; if (argc > 0) { - new_e->meth = rb_to_id(*argv++); - --argc; + new_e->meth = rb_to_id(*argv++); + --argc; } else { - new_e->meth = id_each; + new_e->meth = id_each; } new_e->args = rb_ary_new4(argc, argv); return new_obj; @@ -1934,15 +1934,15 @@ lazy_to_enum(int argc, VALUE *argv, VALUE self) VALUE lazy, meth = sym_each, super_meth; if (argc > 0) { - --argc; - meth = *argv++; + --argc; + meth = *argv++; } if (RTEST((super_meth = rb_hash_aref(lazy_use_super_method, meth)))) { meth = super_meth; } lazy = lazy_to_enum_i(self, meth, argc, argv, 0, rb_keyword_given_p()); if (rb_block_given_p()) { - enumerator_ptr(lazy)->size = rb_block_proc(); + enumerator_ptr(lazy)->size = rb_block_proc(); } return lazy; } @@ -1981,9 +1981,9 @@ lazyenum_yield_values(VALUE proc_entry, struct MEMO *result) int argc = 1; const VALUE *argv = &result->memo_value; if (LAZY_MEMO_PACKED_P(result)) { - const VALUE args = *argv; - argc = RARRAY_LENINT(args); - argv = RARRAY_CONST_PTR(args); + const VALUE args = *argv; + argc = RARRAY_LENINT(args); + argv = RARRAY_CONST_PTR(args); } return rb_proc_call_with_block(entry->proc, argc, argv, Qnil); } @@ -2024,7 +2024,7 @@ static VALUE lazy_map(VALUE obj) { if (!rb_block_given_p()) { - rb_raise(rb_eArgError, "tried to call lazy map without a block"); + rb_raise(rb_eArgError, "tried to call lazy map without a block"); } return lazy_add_method(obj, 0, 0, Qnil, Qnil, &lazy_map_funcs); @@ -2109,7 +2109,7 @@ static VALUE lazy_flat_map(VALUE obj) { if (!rb_block_given_p()) { - rb_raise(rb_eArgError, "tried to call lazy flat_map without a block"); + rb_raise(rb_eArgError, "tried to call lazy flat_map without a block"); } return lazy_add_method(obj, 0, 0, Qnil, Qnil, &lazy_flat_map_funcs); @@ -2139,7 +2139,7 @@ static VALUE lazy_select(VALUE obj) { if (!rb_block_given_p()) { - rb_raise(rb_eArgError, "tried to call lazy select without a block"); + rb_raise(rb_eArgError, "tried to call lazy select without a block"); } return lazy_add_method(obj, 0, 0, Qnil, Qnil, &lazy_select_funcs); @@ -2202,7 +2202,7 @@ static VALUE lazy_reject(VALUE obj) { if (!rb_block_given_p()) { - rb_raise(rb_eArgError, "tried to call lazy reject without a block"); + rb_raise(rb_eArgError, "tried to call lazy reject without a block"); } return lazy_add_method(obj, 0, 0, Qnil, Qnil, &lazy_reject_funcs); @@ -2251,7 +2251,7 @@ static VALUE lazy_grep(VALUE obj, VALUE pattern) { const lazyenum_funcs *const funcs = rb_block_given_p() ? - &lazy_grep_iter_funcs : &lazy_grep_funcs; + &lazy_grep_iter_funcs : &lazy_grep_funcs; return lazy_add_method(obj, 0, 0, pattern, rb_ary_new3(1, pattern), funcs); } @@ -2325,7 +2325,7 @@ lazy_zip_arrays_func(VALUE proc_entry, struct MEMO *result, VALUE memos, long me ary = rb_ary_new2(RARRAY_LEN(arrays) + 1); rb_ary_push(ary, result->memo_value); for (i = 0; i < RARRAY_LEN(arrays); i++) { - rb_ary_push(ary, rb_ary_entry(RARRAY_AREF(arrays, i), count)); + rb_ary_push(ary, rb_ary_entry(RARRAY_AREF(arrays, i), count)); } LAZY_MEMO_SET_VALUE(result, ary); LAZY_MEMO_SET_PACKED(result); @@ -2343,19 +2343,19 @@ lazy_zip_func(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_inde long i; if (NIL_P(arg)) { - arg = rb_ary_new2(RARRAY_LEN(zip_args)); - for (i = 0; i < RARRAY_LEN(zip_args); i++) { - rb_ary_push(arg, rb_funcall(RARRAY_AREF(zip_args, i), id_to_enum, 0)); - } - rb_ary_store(memos, memo_index, arg); + arg = rb_ary_new2(RARRAY_LEN(zip_args)); + for (i = 0; i < RARRAY_LEN(zip_args); i++) { + rb_ary_push(arg, rb_funcall(RARRAY_AREF(zip_args, i), id_to_enum, 0)); + } + rb_ary_store(memos, memo_index, arg); } ary = rb_ary_new2(RARRAY_LEN(arg) + 1); rb_ary_push(ary, result->memo_value); for (i = 0; i < RARRAY_LEN(arg); i++) { - v = rb_rescue2(call_next, RARRAY_AREF(arg, i), next_stopped, 0, - rb_eStopIteration, (VALUE)0); - rb_ary_push(ary, v); + v = rb_rescue2(call_next, RARRAY_AREF(arg, i), next_stopped, 0, + rb_eStopIteration, (VALUE)0); + rb_ary_push(ary, v); } LAZY_MEMO_SET_VALUE(result, ary); LAZY_MEMO_SET_PACKED(result); @@ -2383,24 +2383,24 @@ lazy_zip(int argc, VALUE *argv, VALUE obj) const lazyenum_funcs *funcs = &lazy_zip_funcs[1]; if (rb_block_given_p()) { - return rb_call_super(argc, argv); + return rb_call_super(argc, argv); } ary = rb_ary_new2(argc); for (i = 0; i < argc; i++) { - v = rb_check_array_type(argv[i]); - if (NIL_P(v)) { - for (; i < argc; i++) { - if (!rb_respond_to(argv[i], id_each)) { - rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (must respond to :each)", - rb_obj_class(argv[i])); - } - } - ary = rb_ary_new4(argc, argv); - funcs = &lazy_zip_funcs[0]; - break; - } - rb_ary_push(ary, v); + v = rb_check_array_type(argv[i]); + if (NIL_P(v)) { + for (; i < argc; i++) { + if (!rb_respond_to(argv[i], id_each)) { + rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (must respond to :each)", + rb_obj_class(argv[i])); + } + } + ary = rb_ary_new4(argc, argv); + funcs = &lazy_zip_funcs[0]; + break; + } + rb_ary_push(ary, v); } return lazy_add_method(obj, 0, 0, ary, ary, funcs); @@ -2414,16 +2414,16 @@ lazy_take_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_ind VALUE memo = rb_ary_entry(memos, memo_index); if (NIL_P(memo)) { - memo = entry->memo; + memo = entry->memo; } remain = NUM2LONG(memo); if (remain == 0) { - LAZY_MEMO_SET_BREAK(result); + LAZY_MEMO_SET_BREAK(result); } else { - if (--remain == 0) LAZY_MEMO_SET_BREAK(result); - rb_ary_store(memos, memo_index, LONG2NUM(remain)); + if (--remain == 0) LAZY_MEMO_SET_BREAK(result); + rb_ary_store(memos, memo_index, LONG2NUM(remain)); } return result; } @@ -2433,7 +2433,7 @@ lazy_take_size(VALUE entry, VALUE receiver) { long len = NUM2LONG(RARRAY_AREF(rb_ivar_get(entry, id_arguments), 0)); if (NIL_P(receiver) || (FIXNUM_P(receiver) && FIX2LONG(receiver) < len)) - return receiver; + return receiver; return LONG2NUM(len); } @@ -2456,7 +2456,7 @@ lazy_take(VALUE obj, VALUE n) VALUE argv[2]; if (len < 0) { - rb_raise(rb_eArgError, "attempt to take negative size"); + rb_raise(rb_eArgError, "attempt to take negative size"); } if (len == 0) { @@ -2473,8 +2473,8 @@ lazy_take_while_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long me { VALUE take = lazyenum_yield_values(proc_entry, result); if (!RTEST(take)) { - LAZY_MEMO_SET_BREAK(result); - return 0; + LAZY_MEMO_SET_BREAK(result); + return 0; } return result; } @@ -2494,7 +2494,7 @@ static VALUE lazy_take_while(VALUE obj) { if (!rb_block_given_p()) { - rb_raise(rb_eArgError, "tried to call lazy take_while without a block"); + rb_raise(rb_eArgError, "tried to call lazy take_while without a block"); } return lazy_add_method(obj, 0, 0, Qnil, Qnil, &lazy_take_while_funcs); @@ -2505,10 +2505,10 @@ lazy_drop_size(VALUE proc_entry, VALUE receiver) { long len = NUM2LONG(RARRAY_AREF(rb_ivar_get(proc_entry, id_arguments), 0)); if (NIL_P(receiver)) - return receiver; + return receiver; if (FIXNUM_P(receiver)) { - len = FIX2LONG(receiver) - len; - return LONG2FIX(len < 0 ? 0 : len); + len = FIX2LONG(receiver) - len; + return LONG2FIX(len < 0 ? 0 : len); } return rb_funcall(receiver, '-', 1, LONG2NUM(len)); } @@ -2521,13 +2521,13 @@ lazy_drop_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_ind VALUE memo = rb_ary_entry(memos, memo_index); if (NIL_P(memo)) { - memo = entry->memo; + memo = entry->memo; } remain = NUM2LONG(memo); if (remain > 0) { - --remain; - rb_ary_store(memos, memo_index, LONG2NUM(remain)); - return 0; + --remain; + rb_ary_store(memos, memo_index, LONG2NUM(remain)); + return 0; } return result; @@ -2553,7 +2553,7 @@ lazy_drop(VALUE obj, VALUE n) argv[1] = n; if (len < 0) { - rb_raise(rb_eArgError, "attempt to drop negative size"); + rb_raise(rb_eArgError, "attempt to drop negative size"); } return lazy_add_method(obj, 2, argv, n, rb_ary_new3(1, n), &lazy_drop_funcs); @@ -2566,13 +2566,13 @@ lazy_drop_while_proc(VALUE proc_entry, struct MEMO* result, VALUE memos, long me VALUE memo = rb_ary_entry(memos, memo_index); if (NIL_P(memo)) { - memo = entry->memo; + memo = entry->memo; } if (!RTEST(memo)) { - VALUE drop = lazyenum_yield_values(proc_entry, result); - if (RTEST(drop)) return 0; - rb_ary_store(memos, memo_index, Qtrue); + VALUE drop = lazyenum_yield_values(proc_entry, result); + if (RTEST(drop)) return 0; + rb_ary_store(memos, memo_index, Qtrue); } return result; } @@ -2592,7 +2592,7 @@ static VALUE lazy_drop_while(VALUE obj) { if (!rb_block_given_p()) { - rb_raise(rb_eArgError, "tried to call lazy drop_while without a block"); + rb_raise(rb_eArgError, "tried to call lazy drop_while without a block"); } return lazy_add_method(obj, 0, 0, Qfalse, Qnil, &lazy_drop_while_funcs); diff --git a/error.c b/error.c index 17f524348f..21a532a8fa 100644 --- a/error.c +++ b/error.c @@ -99,25 +99,25 @@ static int err_position_0(char *buf, long len, const char *file, int line) { if (!file) { - return 0; + return 0; } else if (line == 0) { - return snprintf(buf, len, "%s: ", file); + return snprintf(buf, len, "%s: ", file); } else { - return snprintf(buf, len, "%s:%d: ", file, line); + return snprintf(buf, len, "%s:%d: ", file, line); } } RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 5, 0) static VALUE err_vcatf(VALUE str, const char *pre, const char *file, int line, - const char *fmt, va_list args) + const char *fmt, va_list args) { if (file) { - rb_str_cat2(str, file); - if (line) rb_str_catf(str, ":%d", line); - rb_str_cat2(str, ": "); + rb_str_cat2(str, file); + if (line) rb_str_catf(str, ":%d", line); + rb_str_cat2(str, ": "); } if (pre) rb_str_cat2(str, pre); rb_str_vcatf(str, fmt, args); @@ -126,27 +126,27 @@ err_vcatf(VALUE str, const char *pre, const char *file, int line, VALUE rb_syntax_error_append(VALUE exc, VALUE file, int line, int column, - rb_encoding *enc, const char *fmt, va_list args) + rb_encoding *enc, const char *fmt, va_list args) { const char *fn = NIL_P(file) ? NULL : RSTRING_PTR(file); if (!exc) { - VALUE mesg = rb_enc_str_new(0, 0, enc); - err_vcatf(mesg, NULL, fn, line, fmt, args); - rb_str_cat2(mesg, "\n"); - rb_write_error_str(mesg); + VALUE mesg = rb_enc_str_new(0, 0, enc); + err_vcatf(mesg, NULL, fn, line, fmt, args); + rb_str_cat2(mesg, "\n"); + rb_write_error_str(mesg); } else { - VALUE mesg; - if (NIL_P(exc)) { - mesg = rb_enc_str_new(0, 0, enc); - exc = rb_class_new_instance(1, &mesg, rb_eSyntaxError); - } - else { - mesg = rb_attr_get(exc, idMesg); - if (RSTRING_LEN(mesg) > 0 && *(RSTRING_END(mesg)-1) != '\n') - rb_str_cat_cstr(mesg, "\n"); - } - err_vcatf(mesg, NULL, fn, line, fmt, args); + VALUE mesg; + if (NIL_P(exc)) { + mesg = rb_enc_str_new(0, 0, enc); + exc = rb_class_new_instance(1, &mesg, rb_eSyntaxError); + } + else { + mesg = rb_attr_get(exc, idMesg); + if (RSTRING_LEN(mesg) > 0 && *(RSTRING_END(mesg)-1) != '\n') + rb_str_cat_cstr(mesg, "\n"); + } + err_vcatf(mesg, NULL, fn, line, fmt, args); } return exc; @@ -419,9 +419,9 @@ void rb_warn(const char *fmt, ...) { if (!NIL_P(ruby_verbose)) { - with_warning_string(mesg, 0, fmt) { - rb_write_warning_str(mesg); - } + with_warning_string(mesg, 0, fmt) { + rb_write_warning_str(mesg); + } } } @@ -439,9 +439,9 @@ void rb_enc_warn(rb_encoding *enc, const char *fmt, ...) { if (!NIL_P(ruby_verbose)) { - with_warning_string(mesg, enc, fmt) { - rb_write_warning_str(mesg); - } + with_warning_string(mesg, enc, fmt) { + rb_write_warning_str(mesg); + } } } @@ -450,9 +450,9 @@ void rb_warning(const char *fmt, ...) { if (RTEST(ruby_verbose)) { - with_warning_string(mesg, 0, fmt) { - rb_write_warning_str(mesg); - } + with_warning_string(mesg, 0, fmt) { + rb_write_warning_str(mesg); + } } } @@ -480,9 +480,9 @@ void rb_enc_warning(rb_encoding *enc, const char *fmt, ...) { if (RTEST(ruby_verbose)) { - with_warning_string(mesg, enc, fmt) { - rb_write_warning_str(mesg); - } + with_warning_string(mesg, enc, fmt) { + rb_write_warning_str(mesg); + } } } #endif @@ -538,7 +538,7 @@ static inline int end_with_asciichar(VALUE str, int c) { return RB_TYPE_P(str, T_STRING) && - rb_str_end_with_asciichar(str, c); + rb_str_end_with_asciichar(str, c); } /* :nodoc: */ @@ -546,7 +546,7 @@ static VALUE warning_write(int argc, VALUE *argv, VALUE buf) { while (argc-- > 0) { - rb_str_append(buf, *argv++); + rb_str_append(buf, *argv++); } return buf; } @@ -571,38 +571,38 @@ rb_warn_m(rb_execution_context_t *ec, VALUE exc, VALUE msgs, VALUE uplevel, VALU if (!NIL_P(location)) { location = rb_ary_entry(location, 0); } - } - if (argc > 1 || !NIL_P(uplevel) || !end_with_asciichar(str, '\n')) { - VALUE path; - if (NIL_P(uplevel)) { - str = rb_str_tmp_new(0); - } - else if (NIL_P(location) || - NIL_P(path = rb_funcall(location, rb_intern("path"), 0))) { - str = rb_str_new_cstr("warning: "); - } - else { - str = rb_sprintf("%s:%ld: warning: ", - rb_string_value_ptr(&path), - NUM2LONG(rb_funcall(location, rb_intern("lineno"), 0))); - } - RBASIC_SET_CLASS(str, rb_cWarningBuffer); - rb_io_puts(argc, argv, str); - RBASIC_SET_CLASS(str, rb_cString); - } + } + if (argc > 1 || !NIL_P(uplevel) || !end_with_asciichar(str, '\n')) { + VALUE path; + if (NIL_P(uplevel)) { + str = rb_str_tmp_new(0); + } + else if (NIL_P(location) || + NIL_P(path = rb_funcall(location, rb_intern("path"), 0))) { + str = rb_str_new_cstr("warning: "); + } + else { + str = rb_sprintf("%s:%ld: warning: ", + rb_string_value_ptr(&path), + NUM2LONG(rb_funcall(location, rb_intern("lineno"), 0))); + } + RBASIC_SET_CLASS(str, rb_cWarningBuffer); + rb_io_puts(argc, argv, str); + RBASIC_SET_CLASS(str, rb_cString); + } if (!NIL_P(category)) { category = rb_to_symbol_type(category); rb_warning_category_from_name(category); } - if (exc == rb_mWarning) { - rb_must_asciicompat(str); - rb_write_error_str(str); - } - else { + if (exc == rb_mWarning) { + rb_must_asciicompat(str); + rb_write_error_str(str); + } + else { rb_warn_category(str, category); - } + } } return Qnil; } @@ -621,7 +621,7 @@ rb_bug_reporter_add(void (*func)(FILE *, void *), void *data) { struct bug_reporters *reporter; if (bug_reporters_size >= MAX_BUG_REPORTERS) { - return 0; /* failed to register */ + return 0; /* failed to register */ } reporter = &bug_reporters[bug_reporters_size++]; reporter->func = func; @@ -640,7 +640,7 @@ bug_report_file(const char *file, int line) int len = err_position_0(buf, sizeof(buf), file, line); if ((ssize_t)fwrite(buf, 1, len, out) == (ssize_t)len || - (ssize_t)fwrite(buf, 1, len, (out = stdout)) == (ssize_t)len) { + (ssize_t)fwrite(buf, 1, len, (out = stdout)) == (ssize_t)len) { return out; } @@ -657,19 +657,19 @@ bug_important_message(FILE *out, const char *const msg, size_t len) if (!len) return; if (isatty(fileno(out))) { - static const char red[] = "\033[;31;1;7m"; - static const char green[] = "\033[;32;7m"; - static const char reset[] = "\033[m"; - const char *e = strchr(p, '\n'); - const int w = (int)(e - p); - do { - int i = (int)(e - p); - fputs(*p == ' ' ? green : red, out); - fwrite(p, 1, e - p, out); - for (; i < w; ++i) fputc(' ', out); - fputs(reset, out); - fputc('\n', out); - } while ((p = e + 1) < endmsg && (e = strchr(p, '\n')) != 0 && e > p + 1); + static const char red[] = "\033[;31;1;7m"; + static const char green[] = "\033[;32;7m"; + static const char reset[] = "\033[m"; + const char *e = strchr(p, '\n'); + const int w = (int)(e - p); + do { + int i = (int)(e - p); + fputs(*p == ' ' ? green : red, out); + fwrite(p, 1, e - p, out); + for (; i < w; ++i) fputc(' ', out); + fputs(reset, out); + fputc('\n', out); + } while ((p = e + 1) < endmsg && (e = strchr(p, '\n')) != 0 && e > p + 1); } fwrite(p, 1, endmsg - p, out); } @@ -679,18 +679,18 @@ preface_dump(FILE *out) { #if defined __APPLE__ static const char msg[] = "" - "-- Crash Report log information " - "--------------------------------------------\n" - " See Crash Report log file in one of the following locations:\n" + "-- Crash Report log information " + "--------------------------------------------\n" + " See Crash Report log file in one of the following locations:\n" # if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_6 - " * ~/Library/Logs/CrashReporter\n" - " * /Library/Logs/CrashReporter\n" + " * ~/Library/Logs/CrashReporter\n" + " * /Library/Logs/CrashReporter\n" # endif - " * ~/Library/Logs/DiagnosticReports\n" - " * /Library/Logs/DiagnosticReports\n" - " for more details.\n" - "Don't forget to include the above Crash Report log file in bug reports.\n" - "\n"; + " * ~/Library/Logs/DiagnosticReports\n" + " * /Library/Logs/DiagnosticReports\n" + " for more details.\n" + "Don't forget to include the above Crash Report log file in bug reports.\n" + "\n"; const size_t msglen = sizeof(msg) - 1; #else const char *msg = NULL; @@ -704,15 +704,15 @@ postscript_dump(FILE *out) { #if defined __APPLE__ static const char msg[] = "" - "[IMPORTANT]" - /*" ------------------------------------------------"*/ - "\n""Don't forget to include the Crash Report log file under\n" + "[IMPORTANT]" + /*" ------------------------------------------------"*/ + "\n""Don't forget to include the Crash Report log file under\n" # if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_6 - "CrashReporter or " + "CrashReporter or " # endif - "DiagnosticReports directory in bug reports.\n" - /*"------------------------------------------------------------\n"*/ - "\n"; + "DiagnosticReports directory in bug reports.\n" + /*"------------------------------------------------------------\n"*/ + "\n"; const size_t msglen = sizeof(msg) - 1; #else const char *msg = NULL; @@ -747,11 +747,11 @@ bug_report_end(FILE *out) { /* call additional bug reporters */ { - int i; - for (i=0; ifunc)(out, reporter->data); - } + int i; + for (i=0; ifunc)(out, reporter->data); + } } postscript_dump(out); } @@ -759,18 +759,18 @@ bug_report_end(FILE *out) #define report_bug(file, line, fmt, ctx) do { \ FILE *out = bug_report_file(file, line); \ if (out) { \ - bug_report_begin(out, fmt); \ - rb_vm_bugreport(ctx); \ - bug_report_end(out); \ + bug_report_begin(out, fmt); \ + rb_vm_bugreport(ctx); \ + bug_report_end(out); \ } \ } while (0) \ #define report_bug_valist(file, line, fmt, ctx, args) do { \ FILE *out = bug_report_file(file, line); \ if (out) { \ - bug_report_begin_valist(out, fmt, args); \ - rb_vm_bugreport(ctx); \ - bug_report_end(out); \ + bug_report_begin_valist(out, fmt, args); \ + rb_vm_bugreport(ctx); \ + bug_report_end(out); \ } \ } while (0) \ @@ -816,7 +816,7 @@ rb_bug_for_fatal_signal(ruby_sighandler_t default_sighandler, int sig, const voi int line = 0; if (GET_EC()) { - file = rb_source_location_cstr(&line); + file = rb_source_location_cstr(&line); } report_bug(file, line, fmt, ctx); @@ -856,14 +856,14 @@ rb_async_bug_errno(const char *mesg, int errno_arg) WRITE_CONST(2, "\n"); if (errno_arg == 0) { - WRITE_CONST(2, "errno == 0 (NOERROR)\n"); + WRITE_CONST(2, "errno == 0 (NOERROR)\n"); } else { - const char *errno_str = rb_strerrno(errno_arg); + const char *errno_str = rb_strerrno(errno_arg); - if (!errno_str) - errno_str = "undefined errno"; - write_or_abort(2, errno_str, strlen(errno_str)); + if (!errno_str) + errno_str = "undefined errno"; + write_or_abort(2, errno_str, strlen(errno_str)); } WRITE_CONST(2, "\n\n"); write_or_abort(2, rb_dynamic_description, strlen(rb_dynamic_description)); @@ -948,22 +948,22 @@ builtin_class_name(VALUE x) const char *etype; if (NIL_P(x)) { - etype = "nil"; + etype = "nil"; } else if (FIXNUM_P(x)) { - etype = "Integer"; + etype = "Integer"; } else if (SYMBOL_P(x)) { - etype = "Symbol"; + etype = "Symbol"; } else if (RB_TYPE_P(x, T_TRUE)) { - etype = "true"; + etype = "true"; } else if (RB_TYPE_P(x, T_FALSE)) { - etype = "false"; + etype = "false"; } else { - etype = NULL; + etype = NULL; } return etype; } @@ -974,7 +974,7 @@ rb_builtin_class_name(VALUE x) const char *etype = builtin_class_name(x); if (!etype) { - etype = rb_obj_classname(x); + etype = rb_obj_classname(x); } return etype; } @@ -991,14 +991,14 @@ unexpected_type(VALUE x, int xt, int t) if (tname) { mesg = rb_sprintf("wrong argument type %"PRIsVALUE" (expected %s)", displaying_class_of(x), tname); - exc = rb_eTypeError; + exc = rb_eTypeError; } else if (xt > T_MASK && xt <= 0x3f) { - mesg = rb_sprintf("unknown type 0x%x (0x%x given, probably comes" - " from extension library for ruby 1.8)", t, xt); + mesg = rb_sprintf("unknown type 0x%x (0x%x given, probably comes" + " from extension library for ruby 1.8)", t, xt); } else { - mesg = rb_sprintf("unknown type 0x%x (0x%x given)", t, xt); + mesg = rb_sprintf("unknown type 0x%x (0x%x given)", t, xt); } rb_exc_raise(rb_exc_new_str(exc, mesg)); } @@ -1009,7 +1009,7 @@ rb_check_type(VALUE x, int t) int xt; if (RB_UNLIKELY(x == Qundef)) { - rb_bug(UNDEF_LEAKED); + rb_bug(UNDEF_LEAKED); } xt = TYPE(x); @@ -1022,7 +1022,7 @@ rb_check_type(VALUE x, int t) * So it is not enough to just check `T_DATA`, it must be * identified by its `type` using `Check_TypedStruct` instead. */ - unexpected_type(x, xt, t); + unexpected_type(x, xt, t); } } @@ -1030,7 +1030,7 @@ void rb_unexpected_type(VALUE x, int t) { if (RB_UNLIKELY(x == Qundef)) { - rb_bug(UNDEF_LEAKED); + rb_bug(UNDEF_LEAKED); } unexpected_type(x, TYPE(x), t); @@ -1040,8 +1040,8 @@ int rb_typeddata_inherited_p(const rb_data_type_t *child, const rb_data_type_t *parent) { while (child) { - if (child == parent) return 1; - child = child->parent; + if (child == parent) return 1; + child = child->parent; } return 0; } @@ -1050,8 +1050,8 @@ int rb_typeddata_is_kind_of(VALUE obj, const rb_data_type_t *data_type) { if (!RB_TYPE_P(obj, T_DATA) || - !RTYPEDDATA_P(obj) || !rb_typeddata_inherited_p(RTYPEDDATA_TYPE(obj), data_type)) { - return 0; + !RTYPEDDATA_P(obj) || !rb_typeddata_inherited_p(RTYPEDDATA_TYPE(obj), data_type)) { + return 0; } return 1; } @@ -1494,8 +1494,8 @@ exc_backtrace(VALUE exc) obj = rb_attr_get(exc, id_bt); if (rb_backtrace_p(obj)) { - obj = rb_backtrace_to_str_ary(obj); - /* rb_ivar_set(exc, id_bt, obj); */ + obj = rb_backtrace_to_str_ary(obj); + /* rb_ivar_set(exc, id_bt, obj); */ } return obj; @@ -1509,16 +1509,16 @@ rb_get_backtrace(VALUE exc) ID mid = id_backtrace; VALUE info; if (rb_method_basic_definition_p(CLASS_OF(exc), id_backtrace)) { - VALUE klass = rb_eException; - rb_execution_context_t *ec = GET_EC(); - if (NIL_P(exc)) - return Qnil; - EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_CALL, exc, mid, mid, klass, Qundef); - info = exc_backtrace(exc); - EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_RETURN, exc, mid, mid, klass, info); + VALUE klass = rb_eException; + rb_execution_context_t *ec = GET_EC(); + if (NIL_P(exc)) + return Qnil; + EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_CALL, exc, mid, mid, klass, Qundef); + info = exc_backtrace(exc); + EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_RETURN, exc, mid, mid, klass, info); } else { - info = rb_funcallv(exc, mid, 0, 0); + info = rb_funcallv(exc, mid, 0, 0); } if (NIL_P(info)) return Qnil; return rb_check_backtrace(info); @@ -1541,7 +1541,7 @@ exc_backtrace_locations(VALUE exc) obj = rb_attr_get(exc, id_bt_locations); if (!NIL_P(obj)) { - obj = rb_backtrace_to_location_ary(obj); + obj = rb_backtrace_to_location_ary(obj); } return obj; } @@ -1553,17 +1553,17 @@ rb_check_backtrace(VALUE bt) static const char err[] = "backtrace must be Array of String"; if (!NIL_P(bt)) { - if (RB_TYPE_P(bt, T_STRING)) return rb_ary_new3(1, bt); - if (rb_backtrace_p(bt)) return bt; - if (!RB_TYPE_P(bt, T_ARRAY)) { - rb_raise(rb_eTypeError, err); - } - for (i=0;i 0) { - status = *argv; + status = *argv; - switch (status) { - case Qtrue: - status = INT2FIX(EXIT_SUCCESS); - ++argv; - --argc; - break; - case Qfalse: - status = INT2FIX(EXIT_FAILURE); - ++argv; - --argc; - break; - default: - status = rb_check_to_int(status); - if (NIL_P(status)) { - status = INT2FIX(EXIT_SUCCESS); - } - else { + switch (status) { + case Qtrue: + status = INT2FIX(EXIT_SUCCESS); + ++argv; + --argc; + break; + case Qfalse: + status = INT2FIX(EXIT_FAILURE); + ++argv; + --argc; + break; + default: + status = rb_check_to_int(status); + if (NIL_P(status)) { + status = INT2FIX(EXIT_SUCCESS); + } + else { #if EXIT_SUCCESS != 0 - if (status == INT2FIX(0)) - status = INT2FIX(EXIT_SUCCESS); + if (status == INT2FIX(0)) + status = INT2FIX(EXIT_SUCCESS); #endif - ++argv; - --argc; - } - break; - } + ++argv; + --argc; + } + break; + } } else { - status = INT2FIX(EXIT_SUCCESS); + status = INT2FIX(EXIT_SUCCESS); } rb_call_super(argc, argv); rb_ivar_set(exc, id_status, status); @@ -1734,7 +1734,7 @@ exit_success_p(VALUE exc) int status; if (NIL_P(status_val)) - return Qtrue; + return Qtrue; status = NUM2INT(status_val); return RBOOL(WIFEXITED(status) && WEXITSTATUS(status) == EXIT_SUCCESS); } @@ -1897,10 +1897,10 @@ name_err_local_variables(VALUE self) VALUE vars = rb_attr_get(self, id_local_variables); if (NIL_P(vars)) { - VALUE iseqw = rb_attr_get(self, id_iseq); - if (!NIL_P(iseqw)) vars = rb_iseqw_local_variables(iseqw); - if (NIL_P(vars)) vars = rb_ary_new(); - rb_ivar_set(self, id_local_variables, vars); + VALUE iseqw = rb_attr_get(self, id_iseq); + if (!NIL_P(iseqw)) vars = rb_iseqw_local_variables(iseqw); + if (NIL_P(vars)) vars = rb_ary_new(); + rb_ivar_set(self, id_local_variables, vars); } return vars; } @@ -1976,9 +1976,9 @@ name_err_mesg_memsize(const void *p) static const rb_data_type_t name_err_mesg_data_type = { "name_err_mesg", { - name_err_mesg_mark, - name_err_mesg_free, - name_err_mesg_memsize, + name_err_mesg_mark, + name_err_mesg_free, + name_err_mesg_memsize, }, 0, 0, RUBY_TYPED_FREE_IMMEDIATELY }; @@ -2035,13 +2035,13 @@ name_err_mesg_equal(VALUE obj1, VALUE obj2) if (obj1 == obj2) return Qtrue; if (rb_obj_class(obj2) != rb_cNameErrorMesg) - return Qfalse; + return Qfalse; TypedData_Get_Struct(obj1, VALUE, &name_err_mesg_data_type, ptr1); TypedData_Get_Struct(obj2, VALUE, &name_err_mesg_data_type, ptr2); for (i=0; i 0 && RSTRING_PTR(d)[0] == '#'); - break; - } - if (!singleton) { - s = FAKE_CSTR(&s_str, ":"); - c = rb_class_name(CLASS_OF(obj)); - } - else { - c = s = FAKE_CSTR(&s_str, ""); - } + obj = ptr[NAME_ERR_MESG__RECV]; + switch (obj) { + case Qnil: + d = FAKE_CSTR(&d_str, "nil"); + break; + case Qtrue: + d = FAKE_CSTR(&d_str, "true"); + break; + case Qfalse: + d = FAKE_CSTR(&d_str, "false"); + break; + default: + d = rb_protect(name_err_mesg_receiver_name, obj, &state); + if (state || d == Qundef || NIL_P(d)) + d = rb_protect(rb_inspect, obj, &state); + if (state) { + rb_set_errinfo(Qnil); + } + d = rb_check_string_type(d); + if (NIL_P(d)) { + d = rb_any_to_s(obj); + } + singleton = (RSTRING_LEN(d) > 0 && RSTRING_PTR(d)[0] == '#'); + break; + } + if (!singleton) { + s = FAKE_CSTR(&s_str, ":"); + c = rb_class_name(CLASS_OF(obj)); + } + else { + c = s = FAKE_CSTR(&s_str, ""); + } args[0] = rb_obj_as_string(ptr[NAME_ERR_MESG__NAME]); - args[1] = d; - args[2] = s; - args[3] = c; - mesg = rb_str_format(4, args, mesg); + args[1] = d; + args[2] = s; + args[3] = c; + mesg = rb_str_format(4, args, mesg); } return mesg; } @@ -2145,7 +2145,7 @@ name_err_receiver(VALUE self) mesg = rb_attr_get(self, id_mesg); if (!rb_typeddata_is_kind_of(mesg, &name_err_mesg_data_type)) { - rb_raise(rb_eArgError, "no receiver is available"); + rb_raise(rb_eArgError, "no receiver is available"); } ptr = DATA_PTR(mesg); return ptr[NAME_ERR_MESG__RECV]; @@ -2247,17 +2247,17 @@ key_err_initialize(int argc, VALUE *argv, VALUE self) rb_call_super(rb_scan_args(argc, argv, "01:", NULL, &options), argv); if (!NIL_P(options)) { - ID keywords[2]; - VALUE values[numberof(keywords)]; - int i; - keywords[0] = id_receiver; - keywords[1] = id_key; - rb_get_kwargs(options, keywords, 0, numberof(values), values); - for (i = 0; i < numberof(values); ++i) { - if (values[i] != Qundef) { - rb_ivar_set(self, keywords[i], values[i]); - } - } + ID keywords[2]; + VALUE values[numberof(keywords)]; + int i; + keywords[0] = id_receiver; + keywords[1] = id_key; + rb_get_kwargs(options, keywords, 0, numberof(values), values); + for (i = 0; i < numberof(values); ++i) { + if (values[i] != Qundef) { + rb_ivar_set(self, keywords[i], values[i]); + } + } } return self; @@ -2342,9 +2342,9 @@ syntax_error_initialize(int argc, VALUE *argv, VALUE self) { VALUE mesg; if (argc == 0) { - mesg = rb_fstring_lit("compile error"); - argc = 1; - argv = &mesg; + mesg = rb_fstring_lit("compile error"); + argc = 1; + argv = &mesg; } return rb_call_super(argc, argv); } @@ -2387,30 +2387,30 @@ set_syserr(int n, const char *name) st_data_t error; if (!st_lookup(syserr_tbl, n, &error)) { - error = rb_define_class_under(rb_mErrno, name, rb_eSystemCallError); + error = rb_define_class_under(rb_mErrno, name, rb_eSystemCallError); - /* capture nonblock errnos for WaitReadable/WaitWritable subclasses */ - switch (n) { - case EAGAIN: - rb_eEAGAIN = error; + /* capture nonblock errnos for WaitReadable/WaitWritable subclasses */ + switch (n) { + case EAGAIN: + rb_eEAGAIN = error; #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN - break; - case EWOULDBLOCK: + break; + case EWOULDBLOCK: #endif - rb_eEWOULDBLOCK = error; - break; - case EINPROGRESS: - rb_eEINPROGRESS = error; - break; - } + rb_eEWOULDBLOCK = error; + break; + case EINPROGRESS: + rb_eEINPROGRESS = error; + break; + } - rb_define_const(error, "Errno", INT2NUM(n)); - st_add_direct(syserr_tbl, n, error); + rb_define_const(error, "Errno", INT2NUM(n)); + st_add_direct(syserr_tbl, n, error); } else { - rb_define_const(rb_mErrno, name, error); + rb_define_const(rb_mErrno, name, error); } return error; } @@ -2421,10 +2421,10 @@ get_syserr(int n) st_data_t error; if (!st_lookup(syserr_tbl, n, &error)) { - char name[8]; /* some Windows' errno have 5 digits. */ + char name[8]; /* some Windows' errno have 5 digits. */ - snprintf(name, sizeof(name), "E%03d", n); - error = set_syserr(n, name); + snprintf(name, sizeof(name), "E%03d", n); + error = set_syserr(n, name); } return error; } @@ -2450,33 +2450,33 @@ syserr_initialize(int argc, VALUE *argv, VALUE self) VALUE klass = rb_obj_class(self); if (klass == rb_eSystemCallError) { - st_data_t data = (st_data_t)klass; - rb_scan_args(argc, argv, "12", &mesg, &error, &func); - if (argc == 1 && FIXNUM_P(mesg)) { - error = mesg; mesg = Qnil; - } - if (!NIL_P(error) && st_lookup(syserr_tbl, NUM2LONG(error), &data)) { - klass = (VALUE)data; - /* change class */ - if (!RB_TYPE_P(self, T_OBJECT)) { /* insurance to avoid type crash */ - rb_raise(rb_eTypeError, "invalid instance type"); - } - RBASIC_SET_CLASS(self, klass); - } + st_data_t data = (st_data_t)klass; + rb_scan_args(argc, argv, "12", &mesg, &error, &func); + if (argc == 1 && FIXNUM_P(mesg)) { + error = mesg; mesg = Qnil; + } + if (!NIL_P(error) && st_lookup(syserr_tbl, NUM2LONG(error), &data)) { + klass = (VALUE)data; + /* change class */ + if (!RB_TYPE_P(self, T_OBJECT)) { /* insurance to avoid type crash */ + rb_raise(rb_eTypeError, "invalid instance type"); + } + RBASIC_SET_CLASS(self, klass); + } } else { - rb_scan_args(argc, argv, "02", &mesg, &func); - error = rb_const_get(klass, id_Errno); + rb_scan_args(argc, argv, "02", &mesg, &func); + error = rb_const_get(klass, id_Errno); } if (!NIL_P(error)) err = strerror(NUM2INT(error)); else err = "unknown error"; errmsg = rb_enc_str_new_cstr(err, rb_locale_encoding()); if (!NIL_P(mesg)) { - VALUE str = StringValue(mesg); + VALUE str = StringValue(mesg); - if (!NIL_P(func)) rb_str_catf(errmsg, " @ %"PRIsVALUE, func); - rb_str_catf(errmsg, " - %"PRIsVALUE, str); + if (!NIL_P(func)) rb_str_catf(errmsg, " @ %"PRIsVALUE, func); + rb_str_catf(errmsg, " - %"PRIsVALUE, str); } mesg = errmsg; @@ -2512,13 +2512,13 @@ syserr_eqq(VALUE self, VALUE exc) VALUE num, e; if (!rb_obj_is_kind_of(exc, rb_eSystemCallError)) { - if (!rb_respond_to(exc, id_errno)) return Qfalse; + if (!rb_respond_to(exc, id_errno)) return Qfalse; } else if (self == rb_eSystemCallError) return Qtrue; num = rb_attr_get(exc, id_errno); if (NIL_P(num)) { - num = rb_funcallv(exc, id_errno, 0, 0); + num = rb_funcallv(exc, id_errno, 0, 0); } e = rb_const_get(self, id_Errno); return RBOOL(FIXNUM_P(num) ? num == e : rb_equal(num, e)); @@ -3166,8 +3166,8 @@ void rb_notimplement(void) { rb_raise(rb_eNotImpError, - "%"PRIsVALUE"() function is unimplemented on this machine", - rb_id2str(rb_frame_this_func())); + "%"PRIsVALUE"() function is unimplemented on this machine", + rb_id2str(rb_frame_this_func())); } void @@ -3198,7 +3198,7 @@ make_errno_exc(const char *mesg) errno = 0; if (n == 0) { - rb_bug("rb_sys_fail(%s) - errno == 0", mesg ? mesg : ""); + rb_bug("rb_sys_fail(%s) - errno == 0", mesg ? mesg : ""); } return rb_syserr_new(n, mesg); } @@ -3211,8 +3211,8 @@ make_errno_exc_str(VALUE mesg) errno = 0; if (!mesg) mesg = Qnil; if (n == 0) { - const char *s = !NIL_P(mesg) ? RSTRING_PTR(mesg) : ""; - rb_bug("rb_sys_fail_str(%s) - errno == 0", s); + const char *s = !NIL_P(mesg) ? RSTRING_PTR(mesg) : ""; + rb_bug("rb_sys_fail_str(%s) - errno == 0", s); } return rb_syserr_new_str(n, mesg); } @@ -3278,10 +3278,10 @@ rb_syserr_new_path_in(const char *func_name, int n, VALUE path) if (!path) path = Qnil; if (n == 0) { - const char *s = !NIL_P(path) ? RSTRING_PTR(path) : ""; - if (!func_name) func_name = "(null)"; - rb_bug("rb_sys_fail_path_in(%s, %s) - errno == 0", - func_name, s); + const char *s = !NIL_P(path) ? RSTRING_PTR(path) : ""; + if (!func_name) func_name = "(null)"; + rb_bug("rb_sys_fail_path_in(%s, %s) - errno == 0", + func_name, s); } args[0] = path; args[1] = rb_str_new_cstr(func_name); @@ -3339,11 +3339,11 @@ void rb_sys_warn(const char *fmt, ...) { if (!NIL_P(ruby_verbose)) { - int errno_save = errno; - with_warning_string(mesg, 0, fmt) { - syserr_warning(mesg, errno_save); - } - errno = errno_save; + int errno_save = errno; + with_warning_string(mesg, 0, fmt) { + syserr_warning(mesg, errno_save); + } + errno = errno_save; } } @@ -3351,9 +3351,9 @@ void rb_syserr_warn(int err, const char *fmt, ...) { if (!NIL_P(ruby_verbose)) { - with_warning_string(mesg, 0, fmt) { - syserr_warning(mesg, err); - } + with_warning_string(mesg, 0, fmt) { + syserr_warning(mesg, err); + } } } @@ -3361,11 +3361,11 @@ void rb_sys_enc_warn(rb_encoding *enc, const char *fmt, ...) { if (!NIL_P(ruby_verbose)) { - int errno_save = errno; - with_warning_string(mesg, enc, fmt) { - syserr_warning(mesg, errno_save); - } - errno = errno_save; + int errno_save = errno; + with_warning_string(mesg, enc, fmt) { + syserr_warning(mesg, errno_save); + } + errno = errno_save; } } @@ -3373,9 +3373,9 @@ void rb_syserr_enc_warn(int err, rb_encoding *enc, const char *fmt, ...) { if (!NIL_P(ruby_verbose)) { - with_warning_string(mesg, enc, fmt) { - syserr_warning(mesg, err); - } + with_warning_string(mesg, enc, fmt) { + syserr_warning(mesg, err); + } } } #endif @@ -3384,11 +3384,11 @@ void rb_sys_warning(const char *fmt, ...) { if (RTEST(ruby_verbose)) { - int errno_save = errno; - with_warning_string(mesg, 0, fmt) { - syserr_warning(mesg, errno_save); - } - errno = errno_save; + int errno_save = errno; + with_warning_string(mesg, 0, fmt) { + syserr_warning(mesg, errno_save); + } + errno = errno_save; } } @@ -3397,9 +3397,9 @@ void rb_syserr_warning(int err, const char *fmt, ...) { if (RTEST(ruby_verbose)) { - with_warning_string(mesg, 0, fmt) { - syserr_warning(mesg, err); - } + with_warning_string(mesg, 0, fmt) { + syserr_warning(mesg, err); + } } } #endif @@ -3408,11 +3408,11 @@ void rb_sys_enc_warning(rb_encoding *enc, const char *fmt, ...) { if (RTEST(ruby_verbose)) { - int errno_save = errno; - with_warning_string(mesg, enc, fmt) { - syserr_warning(mesg, errno_save); - } - errno = errno_save; + int errno_save = errno; + with_warning_string(mesg, enc, fmt) { + syserr_warning(mesg, errno_save); + } + errno = errno_save; } } @@ -3420,9 +3420,9 @@ void rb_syserr_enc_warning(int err, rb_encoding *enc, const char *fmt, ...) { if (RTEST(ruby_verbose)) { - with_warning_string(mesg, enc, fmt) { - syserr_warning(mesg, err); - } + with_warning_string(mesg, enc, fmt) { + syserr_warning(mesg, err); + } } } @@ -3480,8 +3480,8 @@ rb_error_frozen_object(VALUE frozen_obj) rb_exec_recursive(inspect_frozen_obj, frozen_obj, mesg); if (!NIL_P(debug_info = rb_attr_get(frozen_obj, created_info))) { - VALUE path = rb_ary_entry(debug_info, 0); - VALUE line = rb_ary_entry(debug_info, 1); + VALUE path = rb_ary_entry(debug_info, 0); + VALUE line = rb_ary_entry(debug_info, 1); rb_str_catf(mesg, ", created at %"PRIsVALUE":%"PRIsVALUE, path, line); } diff --git a/eval.c b/eval.c index a059987824..cf32a82214 100644 --- a/eval.c +++ b/eval.c @@ -67,7 +67,7 @@ ruby_setup(void) enum ruby_tag_type state; if (GET_VM()) - return 0; + return 0; ruby_init_stack((void *)&state); @@ -85,9 +85,9 @@ ruby_setup(void) EC_PUSH_TAG(GET_EC()); if ((state = EC_EXEC_TAG()) == TAG_NONE) { - rb_call_inits(); - ruby_prog_init(); - GET_VM()->running = 1; + rb_call_inits(); + ruby_prog_init(); + GET_VM()->running = 1; } EC_POP_TAG(); @@ -101,7 +101,7 @@ ruby_init(void) if (state) { if (RTEST(ruby_debug)) error_print(GET_EC()); - exit(EXIT_FAILURE); + exit(EXIT_FAILURE); } } @@ -115,12 +115,12 @@ ruby_options(int argc, char **argv) ruby_init_stack((void *)&iseq); EC_PUSH_TAG(ec); if ((state = EC_EXEC_TAG()) == TAG_NONE) { - SAVE_ROOT_JMPBUF(GET_THREAD(), iseq = ruby_process_options(argc, argv)); + SAVE_ROOT_JMPBUF(GET_THREAD(), iseq = ruby_process_options(argc, argv)); } else { rb_ec_clear_current_thread_trace_func(ec); state = error_handle(ec, state); - iseq = (void *)INT2FIX(state); + iseq = (void *)INT2FIX(state); } EC_POP_TAG(); return iseq; @@ -200,55 +200,55 @@ rb_ec_cleanup(rb_execution_context_t *ec, int ex0) step_0: step++; errs[1] = ec->errinfo; if (THROW_DATA_P(ec->errinfo)) ec->errinfo = Qnil; - ruby_init_stack(&errs[STACK_UPPER(errs, 0, 1)]); + ruby_init_stack(&errs[STACK_UPPER(errs, 0, 1)]); SAVE_ROOT_JMPBUF(th, rb_ec_teardown(ec)); step_1: step++; - /* protect from Thread#raise */ - th->status = THREAD_KILLED; + /* protect from Thread#raise */ + th->status = THREAD_KILLED; errs[0] = ec->errinfo; - SAVE_ROOT_JMPBUF(th, rb_ractor_terminate_all()); + SAVE_ROOT_JMPBUF(th, rb_ractor_terminate_all()); } else { th = th0; - switch (step) { - case 0: goto step_0; - case 1: goto step_1; - } - if (ex == 0) ex = state; + switch (step) { + case 0: goto step_0; + case 1: goto step_1; + } + if (ex == 0) ex = state; } ec->errinfo = errs[1]; sysex = error_handle(ec, ex); state = 0; for (nerr = 0; nerr < numberof(errs); ++nerr) { - VALUE err = ATOMIC_VALUE_EXCHANGE(errs[nerr], Qnil); + VALUE err = ATOMIC_VALUE_EXCHANGE(errs[nerr], Qnil); VALUE sig; - if (!RTEST(err)) continue; + if (!RTEST(err)) continue; /* ec->errinfo contains a NODE while break'ing */ - if (THROW_DATA_P(err)) continue; + if (THROW_DATA_P(err)) continue; - if (rb_obj_is_kind_of(err, rb_eSystemExit)) { - sysex = sysexit_status(err); - break; - } - else if (rb_obj_is_kind_of(err, rb_eSignal)) { - VALUE sig = rb_ivar_get(err, id_signo); - state = NUM2INT(sig); - break; - } + if (rb_obj_is_kind_of(err, rb_eSystemExit)) { + sysex = sysexit_status(err); + break; + } + else if (rb_obj_is_kind_of(err, rb_eSignal)) { + VALUE sig = rb_ivar_get(err, id_signo); + state = NUM2INT(sig); + break; + } else if (rb_obj_is_kind_of(err, rb_eSystemCallError) && FIXNUM_P(sig = rb_attr_get(err, id_signo))) { - state = NUM2INT(sig); - break; + state = NUM2INT(sig); + break; + } + else if (sysex == EXIT_SUCCESS) { + sysex = EXIT_FAILURE; } - else if (sysex == EXIT_SUCCESS) { - sysex = EXIT_FAILURE; - } } mjit_finish(true); // We still need ISeqs here. @@ -277,9 +277,9 @@ rb_ec_exec_node(rb_execution_context_t *ec, void *n) EC_PUSH_TAG(ec); if ((state = EC_EXEC_TAG()) == TAG_NONE) { rb_thread_t *const th = rb_ec_thread_ptr(ec); - SAVE_ROOT_JMPBUF(th, { - rb_iseq_eval_main(iseq); - }); + SAVE_ROOT_JMPBUF(th, { + rb_iseq_eval_main(iseq); + }); } EC_POP_TAG(); return state; @@ -301,8 +301,8 @@ ruby_executable_node(void *n, int *status) case Qtrue: s = EXIT_SUCCESS; break; case Qfalse: s = EXIT_FAILURE; break; default: - if (!FIXNUM_P(v)) return TRUE; - s = FIX2INT(v); + if (!FIXNUM_P(v)) return TRUE; + s = FIX2INT(v); } if (status) *status = s; return FALSE; @@ -315,7 +315,7 @@ ruby_run_node(void *n) int status; if (!ruby_executable_node(n, &status)) { rb_ec_cleanup(ec, 0); - return status; + return status; } ruby_init_stack((void *)&status); return rb_ec_cleanup(ec, rb_ec_exec_node(ec, n)); @@ -350,12 +350,12 @@ rb_mod_nesting(VALUE _) const rb_cref_t *cref = rb_vm_cref(); while (cref && CREF_NEXT(cref)) { - VALUE klass = CREF_CLASS(cref); - if (!CREF_PUSHED_BY_EVAL(cref) && - !NIL_P(klass)) { - rb_ary_push(ary, klass); - } - cref = CREF_NEXT(cref); + VALUE klass = CREF_CLASS(cref); + if (!CREF_PUSHED_BY_EVAL(cref) && + !NIL_P(klass)) { + rb_ary_push(ary, klass); + } + cref = CREF_NEXT(cref); } return ary; } @@ -391,23 +391,23 @@ rb_mod_s_constants(int argc, VALUE *argv, VALUE mod) void *data = 0; if (argc > 0 || mod != rb_cModule) { - return rb_mod_constants(argc, argv, mod); + return rb_mod_constants(argc, argv, mod); } while (cref) { - klass = CREF_CLASS(cref); - if (!CREF_PUSHED_BY_EVAL(cref) && - !NIL_P(klass)) { - data = rb_mod_const_at(CREF_CLASS(cref), data); - if (!cbase) { - cbase = klass; - } - } - cref = CREF_NEXT(cref); + klass = CREF_CLASS(cref); + if (!CREF_PUSHED_BY_EVAL(cref) && + !NIL_P(klass)) { + data = rb_mod_const_at(CREF_CLASS(cref), data); + if (!cbase) { + cbase = klass; + } + } + cref = CREF_NEXT(cref); } if (cbase) { - data = rb_mod_const_of(cbase, data); + data = rb_mod_const_of(cbase, data); } return rb_const_list(data); } @@ -422,45 +422,45 @@ void rb_class_modify_check(VALUE klass) { if (SPECIAL_CONST_P(klass)) { - Check_Type(klass, T_CLASS); + Check_Type(klass, T_CLASS); } if (RB_TYPE_P(klass, T_MODULE)) { rb_module_set_initialized(klass); } if (OBJ_FROZEN(klass)) { - const char *desc; + const char *desc; - if (FL_TEST(klass, FL_SINGLETON)) { - desc = "object"; - klass = rb_ivar_get(klass, id__attached__); - if (!SPECIAL_CONST_P(klass)) { - switch (BUILTIN_TYPE(klass)) { - case T_MODULE: - case T_ICLASS: - desc = "Module"; - break; - case T_CLASS: - desc = "Class"; - break; + if (FL_TEST(klass, FL_SINGLETON)) { + desc = "object"; + klass = rb_ivar_get(klass, id__attached__); + if (!SPECIAL_CONST_P(klass)) { + switch (BUILTIN_TYPE(klass)) { + case T_MODULE: + case T_ICLASS: + desc = "Module"; + break; + case T_CLASS: + desc = "Class"; + break; default: break; - } - } - } - else { - switch (BUILTIN_TYPE(klass)) { - case T_MODULE: - case T_ICLASS: - desc = "module"; - break; - case T_CLASS: - desc = "class"; - break; - default: + } + } + } + else { + switch (BUILTIN_TYPE(klass)) { + case T_MODULE: + case T_ICLASS: + desc = "module"; + break; + case T_CLASS: + desc = "class"; + break; + default: Check_Type(klass, T_CLASS); UNREACHABLE; - } - } + } + } rb_frozen_error_raise(klass, "can't modify frozen %s: %"PRIsVALUE, desc, klass); } } @@ -474,23 +474,23 @@ exc_setup_cause(VALUE exc, VALUE cause) { #if OPT_SUPPORT_JOKE if (NIL_P(cause)) { - ID id_true_cause; - CONST_ID(id_true_cause, "true_cause"); + ID id_true_cause; + CONST_ID(id_true_cause, "true_cause"); - cause = rb_attr_get(rb_eFatal, id_true_cause); - if (NIL_P(cause)) { - cause = rb_exc_new_cstr(rb_eFatal, "because using such Ruby"); - rb_ivar_set(cause, id_cause, INT2FIX(42)); /* the answer */ - OBJ_FREEZE(cause); - rb_ivar_set(rb_eFatal, id_true_cause, cause); - } + cause = rb_attr_get(rb_eFatal, id_true_cause); + if (NIL_P(cause)) { + cause = rb_exc_new_cstr(rb_eFatal, "because using such Ruby"); + rb_ivar_set(cause, id_cause, INT2FIX(42)); /* the answer */ + OBJ_FREEZE(cause); + rb_ivar_set(rb_eFatal, id_true_cause, cause); + } } #endif if (!NIL_P(cause) && cause != exc) { - rb_ivar_set(exc, id_cause, cause); - if (!rb_ivar_defined(cause, id_cause)) { - rb_ivar_set(cause, id_cause, Qnil); - } + rb_ivar_set(exc, id_cause, cause); + if (!rb_ivar_defined(cause, id_cause)) { + rb_ivar_set(cause, id_cause, Qnil); + } } return exc; } @@ -502,23 +502,23 @@ exc_setup_message(const rb_execution_context_t *ec, VALUE mesg, VALUE *cause) int nocircular = 0; if (NIL_P(mesg)) { - mesg = ec->errinfo; - if (INTERNAL_EXCEPTION_P(mesg)) EC_JUMP_TAG(ec, TAG_FATAL); - nocause = 1; + mesg = ec->errinfo; + if (INTERNAL_EXCEPTION_P(mesg)) EC_JUMP_TAG(ec, TAG_FATAL); + nocause = 1; } if (NIL_P(mesg)) { - mesg = rb_exc_new(rb_eRuntimeError, 0, 0); - nocause = 0; + mesg = rb_exc_new(rb_eRuntimeError, 0, 0); + nocause = 0; nocircular = 1; } if (*cause == Qundef) { - if (nocause) { - *cause = Qnil; + if (nocause) { + *cause = Qnil; nocircular = 1; - } - else if (!rb_ivar_defined(mesg, id_cause)) { - *cause = get_ec_errinfo(ec); - } + } + else if (!rb_ivar_defined(mesg, id_cause)) { + *cause = get_ec_errinfo(ec); + } else { nocircular = 1; } @@ -547,67 +547,67 @@ setup_exception(rb_execution_context_t *ec, int tag, volatile VALUE mesg, VALUE const char *const volatile file0 = file; if ((file && !NIL_P(mesg)) || (cause != Qundef)) { - volatile int state = 0; + volatile int state = 0; - EC_PUSH_TAG(ec); - if (EC_EXEC_TAG() == TAG_NONE && !(state = rb_ec_set_raised(ec))) { - VALUE bt = rb_get_backtrace(mesg); - if (!NIL_P(bt) || cause == Qundef) { - if (OBJ_FROZEN(mesg)) { - mesg = rb_obj_dup(mesg); - } - } + EC_PUSH_TAG(ec); + if (EC_EXEC_TAG() == TAG_NONE && !(state = rb_ec_set_raised(ec))) { + VALUE bt = rb_get_backtrace(mesg); + if (!NIL_P(bt) || cause == Qundef) { + if (OBJ_FROZEN(mesg)) { + mesg = rb_obj_dup(mesg); + } + } if (cause != Qundef && !THROW_DATA_P(cause)) { - exc_setup_cause(mesg, cause); - } - if (NIL_P(bt)) { - VALUE at = rb_ec_backtrace_object(ec); - rb_ivar_set(mesg, idBt_locations, at); - set_backtrace(mesg, at); - } - rb_ec_reset_raised(ec); - } - EC_POP_TAG(); + exc_setup_cause(mesg, cause); + } + if (NIL_P(bt)) { + VALUE at = rb_ec_backtrace_object(ec); + rb_ivar_set(mesg, idBt_locations, at); + set_backtrace(mesg, at); + } + rb_ec_reset_raised(ec); + } + EC_POP_TAG(); file = file0; - if (state) goto fatal; + if (state) goto fatal; } if (!NIL_P(mesg)) { - ec->errinfo = mesg; + ec->errinfo = mesg; } if (RTEST(ruby_debug) && !NIL_P(e = ec->errinfo) && - !rb_obj_is_kind_of(e, rb_eSystemExit)) { - enum ruby_tag_type state; + !rb_obj_is_kind_of(e, rb_eSystemExit)) { + enum ruby_tag_type state; - mesg = e; - EC_PUSH_TAG(ec); - if ((state = EC_EXEC_TAG()) == TAG_NONE) { - ec->errinfo = Qnil; - e = rb_obj_as_string(mesg); - ec->errinfo = mesg; - if (file && line) { - e = rb_sprintf("Exception `%"PRIsVALUE"' at %s:%d - %"PRIsVALUE"\n", - rb_obj_class(mesg), file, line, e); - } - else if (file) { - e = rb_sprintf("Exception `%"PRIsVALUE"' at %s - %"PRIsVALUE"\n", - rb_obj_class(mesg), file, e); - } - else { - e = rb_sprintf("Exception `%"PRIsVALUE"' - %"PRIsVALUE"\n", - rb_obj_class(mesg), e); - } - warn_print_str(e); - } - EC_POP_TAG(); - if (state == TAG_FATAL && ec->errinfo == exception_error) { - ec->errinfo = mesg; - } - else if (state) { - rb_ec_reset_raised(ec); - EC_JUMP_TAG(ec, state); - } + mesg = e; + EC_PUSH_TAG(ec); + if ((state = EC_EXEC_TAG()) == TAG_NONE) { + ec->errinfo = Qnil; + e = rb_obj_as_string(mesg); + ec->errinfo = mesg; + if (file && line) { + e = rb_sprintf("Exception `%"PRIsVALUE"' at %s:%d - %"PRIsVALUE"\n", + rb_obj_class(mesg), file, line, e); + } + else if (file) { + e = rb_sprintf("Exception `%"PRIsVALUE"' at %s - %"PRIsVALUE"\n", + rb_obj_class(mesg), file, e); + } + else { + e = rb_sprintf("Exception `%"PRIsVALUE"' - %"PRIsVALUE"\n", + rb_obj_class(mesg), e); + } + warn_print_str(e); + } + EC_POP_TAG(); + if (state == TAG_FATAL && ec->errinfo == exception_error) { + ec->errinfo = mesg; + } + else if (state) { + rb_ec_reset_raised(ec); + EC_JUMP_TAG(ec, state); + } } if (rb_ec_set_raised(ec)) { @@ -615,8 +615,8 @@ setup_exception(rb_execution_context_t *ec, int tag, volatile VALUE mesg, VALUE } if (tag != TAG_FATAL) { - RUBY_DTRACE_HOOK(RAISE, rb_obj_classname(ec->errinfo)); - EXEC_EVENT_HOOK(ec, RUBY_EVENT_RAISE, ec->cfp->self, 0, 0, 0, mesg); + RUBY_DTRACE_HOOK(RAISE, rb_obj_classname(ec->errinfo)); + EXEC_EVENT_HOOK(ec, RUBY_EVENT_RAISE, ec->cfp->self, 0, 0, 0, mesg); } return; @@ -631,10 +631,10 @@ void rb_ec_setup_exception(const rb_execution_context_t *ec, VALUE mesg, VALUE cause) { if (cause == Qundef) { - cause = get_ec_errinfo(ec); + cause = get_ec_errinfo(ec); } if (cause != mesg) { - rb_ivar_set(mesg, id_cause, cause); + rb_ivar_set(mesg, id_cause, cause); } } @@ -655,7 +655,7 @@ static void rb_exc_exception(VALUE mesg, int tag, VALUE cause) { if (!NIL_P(mesg)) { - mesg = make_exception(1, &mesg, FALSE); + mesg = make_exception(1, &mesg, FALSE); } rb_longjmp(GET_EC(), tag, mesg, cause); } @@ -699,20 +699,20 @@ extract_raise_opts(int argc, VALUE *argv, VALUE *opts) { int i; if (argc > 0) { - VALUE opt; - argc = rb_scan_args(argc, argv, "*:", NULL, &opt); - if (!NIL_P(opt)) { - if (!RHASH_EMPTY_P(opt)) { - ID keywords[1]; - CONST_ID(keywords[0], "cause"); - rb_get_kwargs(opt, keywords, 0, -1-raise_max_opt, opts); - if (!RHASH_EMPTY_P(opt)) argv[argc++] = opt; - return argc; - } - } + VALUE opt; + argc = rb_scan_args(argc, argv, "*:", NULL, &opt); + if (!NIL_P(opt)) { + if (!RHASH_EMPTY_P(opt)) { + ID keywords[1]; + CONST_ID(keywords[0], "cause"); + rb_get_kwargs(opt, keywords, 0, -1-raise_max_opt, opts); + if (!RHASH_EMPTY_P(opt)) argv[argc++] = opt; + return argc; + } + } } for (i = 0; i < raise_max_opt; ++i) { - opts[i] = Qundef; + opts[i] = Qundef; } return argc; } @@ -784,17 +784,17 @@ make_exception(int argc, const VALUE *argv, int isstr) case 0: return Qnil; case 1: - exc = argv[0]; + exc = argv[0]; if (isstr &&! NIL_P(exc)) { - mesg = rb_check_string_type(exc); - if (!NIL_P(mesg)) { + mesg = rb_check_string_type(exc); + if (!NIL_P(mesg)) { return rb_exc_new3(rb_eRuntimeError, mesg); - } - } + } + } case 2: case 3: - break; + break; default: rb_error_arity(argc, 0, 3); } @@ -842,7 +842,7 @@ void rb_jump_tag(int tag) { if (UNLIKELY(tag < TAG_RETURN || tag > TAG_FATAL)) { - unknown_longjmp_status(tag); + unknown_longjmp_status(tag); } EC_JUMP_TAG(GET_EC(), tag); } @@ -851,10 +851,10 @@ int rb_block_given_p(void) { if (rb_vm_frame_block_handler(GET_EC()->cfp) == VM_BLOCK_HANDLER_NONE) { - return FALSE; + return FALSE; } else { - return TRUE; + return TRUE; } } @@ -872,7 +872,7 @@ void rb_need_block(void) { if (!rb_block_given_p()) { - rb_vm_localjump_error("no block given", Qnil, 0); + rb_vm_localjump_error("no block given", Qnil, 0); } } @@ -901,48 +901,48 @@ rb_vrescue2(VALUE (* b_proc) (VALUE), VALUE data1, EC_PUSH_TAG(ec); if ((state = EC_EXEC_TAG()) == TAG_NONE) { retry_entry: - result = (*b_proc) (data1); + result = (*b_proc) (data1); } else if (result) { - /* escape from r_proc */ - if (state == TAG_RETRY) { - state = TAG_NONE; - ec->errinfo = Qnil; - result = Qfalse; - goto retry_entry; - } + /* escape from r_proc */ + if (state == TAG_RETRY) { + state = TAG_NONE; + ec->errinfo = Qnil; + result = Qfalse; + goto retry_entry; + } } else { - rb_vm_rewind_cfp(ec, cfp); + rb_vm_rewind_cfp(ec, cfp); - if (state == TAG_RAISE) { - int handle = FALSE; - VALUE eclass; - va_list ap; + if (state == TAG_RAISE) { + int handle = FALSE; + VALUE eclass; + va_list ap; - result = Qnil; - /* reuses args when raised again after retrying in r_proc */ - va_copy(ap, args); - while ((eclass = va_arg(ap, VALUE)) != 0) { - if (rb_obj_is_kind_of(ec->errinfo, eclass)) { - handle = TRUE; - break; - } - } - va_end(ap); + result = Qnil; + /* reuses args when raised again after retrying in r_proc */ + va_copy(ap, args); + while ((eclass = va_arg(ap, VALUE)) != 0) { + if (rb_obj_is_kind_of(ec->errinfo, eclass)) { + handle = TRUE; + break; + } + } + va_end(ap); - if (handle) { - state = TAG_NONE; - if (r_proc) { - result = (*r_proc) (data2, ec->errinfo); - } - ec->errinfo = e_info; - } - } + if (handle) { + state = TAG_NONE; + if (r_proc) { + result = (*r_proc) (data2, ec->errinfo); + } + ec->errinfo = e_info; + } + } } EC_POP_TAG(); if (state) - EC_JUMP_TAG(ec, state); + EC_JUMP_TAG(ec, state); return result; } @@ -952,7 +952,7 @@ rb_rescue(VALUE (* b_proc)(VALUE), VALUE data1, VALUE (* r_proc)(VALUE, VALUE), VALUE data2) { return rb_rescue2(b_proc, data1, r_proc, data2, rb_eStandardError, - (VALUE)0); + (VALUE)0); } VALUE @@ -965,10 +965,10 @@ rb_protect(VALUE (* proc) (VALUE), VALUE data, int *pstate) EC_PUSH_TAG(ec); if ((state = EC_EXEC_TAG()) == TAG_NONE) { - SAVE_ROOT_JMPBUF(rb_ec_thread_ptr(ec), result = (*proc) (data)); + SAVE_ROOT_JMPBUF(rb_ec_thread_ptr(ec), result = (*proc) (data)); } else { - rb_vm_rewind_cfp(ec, cfp); + rb_vm_rewind_cfp(ec, cfp); } EC_POP_TAG(); @@ -991,18 +991,18 @@ rb_ensure(VALUE (*b_proc)(VALUE), VALUE data1, VALUE (*e_proc)(VALUE), VALUE dat ec->ensure_list = &ensure_list; EC_PUSH_TAG(ec); if ((state = EC_EXEC_TAG()) == TAG_NONE) { - result = (*b_proc) (data1); + result = (*b_proc) (data1); } EC_POP_TAG(); errinfo = ec->errinfo; if (!NIL_P(errinfo) && !RB_TYPE_P(errinfo, T_OBJECT)) { - ec->errinfo = Qnil; + ec->errinfo = Qnil; } ec->ensure_list=ensure_list.next; (*ensure_list.entry.e_proc)(ensure_list.entry.data2); ec->errinfo = errinfo; if (state) - EC_JUMP_TAG(ec, state); + EC_JUMP_TAG(ec, state); return result; } @@ -1012,10 +1012,10 @@ frame_func_id(const rb_control_frame_t *cfp) const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(cfp); if (me) { - return me->def->original_id; + return me->def->original_id; } else { - return 0; + return 0; } } @@ -1025,10 +1025,10 @@ frame_called_id(rb_control_frame_t *cfp) const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(cfp); if (me) { - return me->called_id; + return me->called_id; } else { - return 0; + return 0; } } @@ -1085,8 +1085,8 @@ rb_frame_last_func(void) ID mid; while (!(mid = frame_func_id(cfp)) && - (cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp), - !RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(ec, cfp))); + (cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp), + !RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(ec, cfp))); return mid; } @@ -1106,7 +1106,7 @@ static VALUE rb_mod_append_features(VALUE module, VALUE include) { if (!CLASS_OR_MODULE_P(include)) { - Check_Type(include, T_CLASS); + Check_Type(include, T_CLASS); } rb_include_module(include, module); @@ -1135,14 +1135,14 @@ rb_mod_include(int argc, VALUE *argv, VALUE module) rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS); for (i = 0; i < argc; i++) { - Check_Type(argv[i], T_MODULE); + Check_Type(argv[i], T_MODULE); if (FL_TEST(argv[i], RMODULE_IS_REFINEMENT)) { rb_raise(rb_eTypeError, "Cannot include refinement"); } } while (argc--) { - rb_funcall(argv[argc], id_append_features, 1, module); - rb_funcall(argv[argc], id_included, 1, module); + rb_funcall(argv[argc], id_append_features, 1, module); + rb_funcall(argv[argc], id_included, 1, module); } return module; } @@ -1163,7 +1163,7 @@ static VALUE rb_mod_prepend_features(VALUE module, VALUE prepend) { if (!CLASS_OR_MODULE_P(prepend)) { - Check_Type(prepend, T_CLASS); + Check_Type(prepend, T_CLASS); } rb_prepend_module(prepend, module); @@ -1192,14 +1192,14 @@ rb_mod_prepend(int argc, VALUE *argv, VALUE module) rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS); for (i = 0; i < argc; i++) { - Check_Type(argv[i], T_MODULE); + Check_Type(argv[i], T_MODULE); if (FL_TEST(argv[i], RMODULE_IS_REFINEMENT)) { rb_raise(rb_eTypeError, "Cannot prepend refinement"); } } while (argc--) { - rb_funcall(argv[argc], id_prepend_features, 1, module); - rb_funcall(argv[argc], id_prepended, 1, module); + rb_funcall(argv[argc], id_prepend_features, 1, module); + rb_funcall(argv[argc], id_prepended, 1, module); } return module; } @@ -1208,9 +1208,9 @@ static void ensure_class_or_module(VALUE obj) { if (!RB_TYPE_P(obj, T_CLASS) && !RB_TYPE_P(obj, T_MODULE)) { - rb_raise(rb_eTypeError, - "wrong argument type %"PRIsVALUE" (expected Class or Module)", - rb_obj_class(obj)); + rb_raise(rb_eTypeError, + "wrong argument type %"PRIsVALUE" (expected Class or Module)", + rb_obj_class(obj)); } } @@ -1227,11 +1227,11 @@ static VALUE refinement_superclass(VALUE superclass) { if (RB_TYPE_P(superclass, T_MODULE)) { - /* FIXME: Should ancestors of superclass be used here? */ + /* FIXME: Should ancestors of superclass be used here? */ return rb_include_class_new(RCLASS_ORIGIN(superclass), rb_cBasicObject); } else { - return superclass; + return superclass; } } @@ -1246,23 +1246,23 @@ rb_using_refinement(rb_cref_t *cref, VALUE klass, VALUE module) ensure_class_or_module(klass); Check_Type(module, T_MODULE); if (NIL_P(CREF_REFINEMENTS(cref))) { - CREF_REFINEMENTS_SET(cref, hidden_identity_hash_new()); + CREF_REFINEMENTS_SET(cref, hidden_identity_hash_new()); } else { - if (CREF_OMOD_SHARED(cref)) { - CREF_REFINEMENTS_SET(cref, rb_hash_dup(CREF_REFINEMENTS(cref))); - CREF_OMOD_SHARED_UNSET(cref); - } - if (!NIL_P(c = rb_hash_lookup(CREF_REFINEMENTS(cref), klass))) { - superclass = c; - while (c && RB_TYPE_P(c, T_ICLASS)) { - if (RBASIC(c)->klass == module) { - /* already used refinement */ - return; - } - c = RCLASS_SUPER(c); - } - } + if (CREF_OMOD_SHARED(cref)) { + CREF_REFINEMENTS_SET(cref, rb_hash_dup(CREF_REFINEMENTS(cref))); + CREF_OMOD_SHARED_UNSET(cref); + } + if (!NIL_P(c = rb_hash_lookup(CREF_REFINEMENTS(cref), klass))) { + superclass = c; + while (c && RB_TYPE_P(c, T_ICLASS)) { + if (RBASIC(c)->klass == module) { + /* already used refinement */ + return; + } + c = RCLASS_SUPER(c); + } + } } superclass = refinement_superclass(superclass); c = iclass = rb_include_class_new(module, superclass); @@ -1272,7 +1272,7 @@ rb_using_refinement(rb_cref_t *cref, VALUE klass, VALUE module) module = RCLASS_SUPER(module); while (module && module != klass) { - c = RCLASS_SET_SUPER(c, rb_include_class_new(module, RCLASS_SUPER(c))); + c = RCLASS_SET_SUPER(c, rb_include_class_new(module, RCLASS_SUPER(c))); RB_OBJ_WRITE(c, &RCLASS_REFINED_CLASS(c), klass); module = RCLASS_SUPER(module); } @@ -1296,21 +1296,21 @@ using_module_recursive(const rb_cref_t *cref, VALUE klass) super = RCLASS_SUPER(klass); if (super) { - using_module_recursive(cref, super); + using_module_recursive(cref, super); } switch (BUILTIN_TYPE(klass)) { case T_MODULE: - module = klass; - break; + module = klass; + break; case T_ICLASS: - module = RBASIC(klass)->klass; - break; + module = RBASIC(klass)->klass; + break; default: - rb_raise(rb_eTypeError, "wrong argument type %s (expected Module)", - rb_obj_classname(klass)); - break; + rb_raise(rb_eTypeError, "wrong argument type %s (expected Module)", + rb_obj_classname(klass)); + break; } CONST_ID(id_refinements, "__refinements__"); refinements = rb_attr_get(module, id_refinements); @@ -1346,28 +1346,28 @@ rb_refinement_module_get_refined_class(VALUE module) static void add_activated_refinement(VALUE activated_refinements, - VALUE klass, VALUE refinement) + VALUE klass, VALUE refinement) { VALUE iclass, c, superclass = klass; if (!NIL_P(c = rb_hash_lookup(activated_refinements, klass))) { - superclass = c; - while (c && RB_TYPE_P(c, T_ICLASS)) { - if (RBASIC(c)->klass == refinement) { - /* already used refinement */ - return; - } - c = RCLASS_SUPER(c); - } + superclass = c; + while (c && RB_TYPE_P(c, T_ICLASS)) { + if (RBASIC(c)->klass == refinement) { + /* already used refinement */ + return; + } + c = RCLASS_SUPER(c); + } } superclass = refinement_superclass(superclass); c = iclass = rb_include_class_new(refinement, superclass); RB_OBJ_WRITE(c, &RCLASS_REFINED_CLASS(c), klass); refinement = RCLASS_SUPER(refinement); while (refinement && refinement != klass) { - c = RCLASS_SET_SUPER(c, rb_include_class_new(refinement, RCLASS_SUPER(c))); + c = RCLASS_SET_SUPER(c, rb_include_class_new(refinement, RCLASS_SUPER(c))); RB_OBJ_WRITE(c, &RCLASS_REFINED_CLASS(c), klass); - refinement = RCLASS_SUPER(refinement); + refinement = RCLASS_SUPER(refinement); } rb_hash_aset(activated_refinements, klass, iclass); } @@ -1392,39 +1392,39 @@ rb_mod_refine(VALUE module, VALUE klass) VALUE block_handler = rb_vm_frame_block_handler(th->ec->cfp); if (block_handler == VM_BLOCK_HANDLER_NONE) { - rb_raise(rb_eArgError, "no block given"); + rb_raise(rb_eArgError, "no block given"); } if (vm_block_handler_type(block_handler) != block_handler_type_iseq) { - rb_raise(rb_eArgError, "can't pass a Proc as a block to Module#refine"); + rb_raise(rb_eArgError, "can't pass a Proc as a block to Module#refine"); } ensure_class_or_module(klass); CONST_ID(id_refinements, "__refinements__"); refinements = rb_attr_get(module, id_refinements); if (NIL_P(refinements)) { - refinements = hidden_identity_hash_new(); - rb_ivar_set(module, id_refinements, refinements); + refinements = hidden_identity_hash_new(); + rb_ivar_set(module, id_refinements, refinements); } CONST_ID(id_activated_refinements, "__activated_refinements__"); activated_refinements = rb_attr_get(module, id_activated_refinements); if (NIL_P(activated_refinements)) { - activated_refinements = hidden_identity_hash_new(); - rb_ivar_set(module, id_activated_refinements, - activated_refinements); + activated_refinements = hidden_identity_hash_new(); + rb_ivar_set(module, id_activated_refinements, + activated_refinements); } refinement = rb_hash_lookup(refinements, klass); if (NIL_P(refinement)) { - VALUE superclass = refinement_superclass(klass); - refinement = rb_refinement_new(); - RCLASS_SET_SUPER(refinement, superclass); + VALUE superclass = refinement_superclass(klass); + refinement = rb_refinement_new(); + RCLASS_SET_SUPER(refinement, superclass); RUBY_ASSERT(BUILTIN_TYPE(refinement) == T_MODULE); - FL_SET(refinement, RMODULE_IS_REFINEMENT); - CONST_ID(id_refined_class, "__refined_class__"); - rb_ivar_set(refinement, id_refined_class, klass); - CONST_ID(id_defined_at, "__defined_at__"); - rb_ivar_set(refinement, id_defined_at, module); - rb_hash_aset(refinements, klass, refinement); - add_activated_refinement(activated_refinements, klass, refinement); + FL_SET(refinement, RMODULE_IS_REFINEMENT); + CONST_ID(id_refined_class, "__refined_class__"); + rb_ivar_set(refinement, id_refined_class, klass); + CONST_ID(id_defined_at, "__defined_at__"); + rb_ivar_set(refinement, id_defined_at, module); + rb_hash_aset(refinements, klass, refinement); + add_activated_refinement(activated_refinements, klass, refinement); } rb_yield_refine_block(refinement, activated_refinements); return refinement; @@ -1436,7 +1436,7 @@ ignored_block(VALUE module, const char *klass) const char *anon = ""; Check_Type(module, T_MODULE); if (!RTEST(rb_search_class_path(module))) { - anon = ", maybe for Module.new"; + anon = ", maybe for Module.new"; } rb_warn("%s""using doesn't call the given block""%s.", klass, anon); } @@ -1455,14 +1455,14 @@ mod_using(VALUE self, VALUE module) rb_control_frame_t *prev_cfp = previous_frame(GET_EC()); if (prev_frame_func()) { - rb_raise(rb_eRuntimeError, - "Module#using is not permitted in methods"); + rb_raise(rb_eRuntimeError, + "Module#using is not permitted in methods"); } if (prev_cfp && prev_cfp->self != self) { - rb_raise(rb_eRuntimeError, "Module#using is not called on self"); + rb_raise(rb_eRuntimeError, "Module#using is not called on self"); } if (rb_block_given_p()) { - ignored_block(module, "Module#"); + ignored_block(module, "Module#"); } rb_using_module(rb_vm_cref_replace_with_duplicated_cref(), module); return self; @@ -1509,8 +1509,8 @@ used_modules_i(VALUE _, VALUE mod, VALUE ary) ID id_defined_at; CONST_ID(id_defined_at, "__defined_at__"); while (BUILTIN_TYPE(rb_class_of(mod)) == T_MODULE && FL_TEST(rb_class_of(mod), RMODULE_IS_REFINEMENT)) { - rb_ary_push(ary, rb_attr_get(rb_class_of(mod), id_defined_at)); - mod = RCLASS_SUPER(mod); + rb_ary_push(ary, rb_attr_get(rb_class_of(mod), id_defined_at)); + mod = RCLASS_SUPER(mod); } return ST_CONTINUE; } @@ -1547,10 +1547,10 @@ rb_mod_s_used_modules(VALUE _) VALUE ary = rb_ary_new(); while (cref) { - if (!NIL_P(CREF_REFINEMENTS(cref))) { - rb_hash_foreach(CREF_REFINEMENTS(cref), used_modules_i, ary); - } - cref = CREF_NEXT(cref); + if (!NIL_P(CREF_REFINEMENTS(cref))) { + rb_hash_foreach(CREF_REFINEMENTS(cref), used_modules_i, ary); + } + cref = CREF_NEXT(cref); } return rb_funcall(ary, rb_intern("uniq"), 0); @@ -1561,7 +1561,7 @@ used_refinements_i(VALUE _, VALUE mod, VALUE ary) { while (BUILTIN_TYPE(rb_class_of(mod)) == T_MODULE && FL_TEST(rb_class_of(mod), RMODULE_IS_REFINEMENT)) { rb_ary_push(ary, rb_class_of(mod)); - mod = RCLASS_SUPER(mod); + mod = RCLASS_SUPER(mod); } return ST_CONTINUE; } @@ -1598,10 +1598,10 @@ rb_mod_s_used_refinements(VALUE _) VALUE ary = rb_ary_new(); while (cref) { - if (!NIL_P(CREF_REFINEMENTS(cref))) { - rb_hash_foreach(CREF_REFINEMENTS(cref), used_refinements_i, ary); - } - cref = CREF_NEXT(cref); + if (!NIL_P(CREF_REFINEMENTS(cref))) { + rb_hash_foreach(CREF_REFINEMENTS(cref), used_refinements_i, ary); + } + cref = CREF_NEXT(cref); } return ary; @@ -1748,14 +1748,14 @@ rb_obj_extend(int argc, VALUE *argv, VALUE obj) rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS); for (i = 0; i < argc; i++) { - Check_Type(argv[i], T_MODULE); + Check_Type(argv[i], T_MODULE); if (FL_TEST(argv[i], RMODULE_IS_REFINEMENT)) { rb_raise(rb_eTypeError, "Cannot extend object with refinement"); } } while (argc--) { - rb_funcall(argv[argc], id_extend_object, 1, obj); - rb_funcall(argv[argc], id_extended, 1, obj); + rb_funcall(argv[argc], id_extend_object, 1, obj); + rb_funcall(argv[argc], id_extended, 1, obj); } return obj; } @@ -1775,8 +1775,8 @@ top_include(int argc, VALUE *argv, VALUE self) rb_thread_t *th = GET_THREAD(); if (th->top_wrapper) { - rb_warning("main.include in the wrapped load is effective only in wrapper module"); - return rb_mod_include(argc, argv, th->top_wrapper); + rb_warning("main.include in the wrapped load is effective only in wrapper module"); + return rb_mod_include(argc, argv, th->top_wrapper); } return rb_mod_include(argc, argv, rb_cObject); } @@ -1796,10 +1796,10 @@ top_using(VALUE self, VALUE module) rb_control_frame_t *prev_cfp = previous_frame(GET_EC()); if (CREF_NEXT(cref) || (prev_cfp && rb_vm_frame_method_entry(prev_cfp))) { - rb_raise(rb_eRuntimeError, "main.using is permitted only at toplevel"); + rb_raise(rb_eRuntimeError, "main.using is permitted only at toplevel"); } if (rb_block_given_p()) { - ignored_block(module, "main."); + ignored_block(module, "main."); } rb_using_module(rb_vm_cref_replace_with_duplicated_cref(), module); return self; @@ -1812,17 +1812,17 @@ errinfo_place(const rb_execution_context_t *ec) const rb_control_frame_t *end_cfp = RUBY_VM_END_CONTROL_FRAME(ec); while (RUBY_VM_VALID_CONTROL_FRAME_P(cfp, end_cfp)) { - if (VM_FRAME_RUBYFRAME_P(cfp)) { + if (VM_FRAME_RUBYFRAME_P(cfp)) { if (ISEQ_BODY(cfp->iseq)->type == ISEQ_TYPE_RESCUE) { - return &cfp->ep[VM_ENV_INDEX_LAST_LVAR]; - } + return &cfp->ep[VM_ENV_INDEX_LAST_LVAR]; + } else if (ISEQ_BODY(cfp->iseq)->type == ISEQ_TYPE_ENSURE && - !THROW_DATA_P(cfp->ep[VM_ENV_INDEX_LAST_LVAR]) && - !FIXNUM_P(cfp->ep[VM_ENV_INDEX_LAST_LVAR])) { - return &cfp->ep[VM_ENV_INDEX_LAST_LVAR]; - } - } - cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); + !THROW_DATA_P(cfp->ep[VM_ENV_INDEX_LAST_LVAR]) && + !FIXNUM_P(cfp->ep[VM_ENV_INDEX_LAST_LVAR])) { + return &cfp->ep[VM_ENV_INDEX_LAST_LVAR]; + } + } + cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); } return 0; } @@ -1832,10 +1832,10 @@ rb_ec_get_errinfo(const rb_execution_context_t *ec) { const VALUE *ptr = errinfo_place(ec); if (ptr) { - return *ptr; + return *ptr; } else { - return ec->errinfo; + return ec->errinfo; } } @@ -1861,7 +1861,7 @@ void rb_set_errinfo(VALUE err) { if (!NIL_P(err) && !rb_obj_is_kind_of(err, rb_eException)) { - rb_raise(rb_eTypeError, "assigning non-exception to $!"); + rb_raise(rb_eTypeError, "assigning non-exception to $!"); } GET_EC()->errinfo = err; } @@ -1871,10 +1871,10 @@ errat_getter(ID id, VALUE *_) { VALUE err = get_errinfo(); if (!NIL_P(err)) { - return rb_get_backtrace(err); + return rb_get_backtrace(err); } else { - return Qnil; + return Qnil; } } @@ -1883,7 +1883,7 @@ errat_setter(VALUE val, ID id, VALUE *var) { VALUE err = get_errinfo(); if (NIL_P(err)) { - rb_raise(rb_eArgError, "$! not set"); + rb_raise(rb_eArgError, "$! not set"); } set_backtrace(err, val); } @@ -1904,10 +1904,10 @@ rb_f_method_name(VALUE _) ID fname = prev_frame_func(); /* need *method* ID */ if (fname) { - return ID2SYM(fname); + return ID2SYM(fname); } else { - return Qnil; + return Qnil; } } @@ -1926,10 +1926,10 @@ rb_f_callee_name(VALUE _) ID fname = prev_frame_callee(); /* need *callee* ID */ if (fname) { - return ID2SYM(fname); + return ID2SYM(fname); } else { - return Qnil; + return Qnil; } } @@ -1948,7 +1948,7 @@ f_current_dirname(VALUE _) { VALUE base = rb_current_realfilepath(); if (NIL_P(base)) { - return Qnil; + return Qnil; } base = rb_file_dirname(base); return base; @@ -2045,7 +2045,7 @@ Init_eval(void) rb_define_private_method(rb_cModule, "using", mod_using, 1); rb_define_method(rb_cModule, "refinements", mod_refinements, 0); rb_define_singleton_method(rb_cModule, "used_modules", - rb_mod_s_used_modules, 0); + rb_mod_s_used_modules, 0); rb_define_singleton_method(rb_cModule, "used_refinements", rb_mod_s_used_refinements, 0); rb_undef_method(rb_cClass, "refine"); @@ -2064,9 +2064,9 @@ Init_eval(void) rb_define_singleton_method(rb_cModule, "constants", rb_mod_s_constants, -1); rb_define_private_method(rb_singleton_class(rb_vm_top_self()), - "include", top_include, -1); + "include", top_include, -1); rb_define_private_method(rb_singleton_class(rb_vm_top_self()), - "using", top_using, 1); + "using", top_using, 1); rb_define_method(rb_mKernel, "extend", rb_obj_extend, -1); diff --git a/eval_error.c b/eval_error.c index abbb708bd5..6582b805aa 100644 --- a/eval_error.c +++ b/eval_error.c @@ -10,8 +10,8 @@ #ifdef HAVE_BUILTIN___BUILTIN_CONSTANT_P #define warn_print(x) RB_GNUC_EXTENSION_BLOCK( \ (__builtin_constant_p(x)) ? \ - rb_write_error2((x), (long)strlen(x)) : \ - rb_write_error(x) \ + rb_write_error2((x), (long)strlen(x)) : \ + rb_write_error(x) \ ) #else #define warn_print(x) rb_write_error(x) @@ -29,7 +29,7 @@ error_pos(const VALUE str) { VALUE pos = error_pos_str(); if (!NIL_P(pos)) { - write_warn_str(str, pos); + write_warn_str(str, pos); } } @@ -40,18 +40,18 @@ error_pos_str(void) VALUE sourcefile = rb_source_location(&sourceline); if (!NIL_P(sourcefile)) { - ID caller_name; - if (sourceline == 0) { - return rb_sprintf("%"PRIsVALUE": ", sourcefile); - } - else if ((caller_name = rb_frame_callee()) != 0) { - return rb_sprintf("%"PRIsVALUE":%d:in `%"PRIsVALUE"': ", - sourcefile, sourceline, - rb_id2str(caller_name)); - } - else { - return rb_sprintf("%"PRIsVALUE":%d: ", sourcefile, sourceline); - } + ID caller_name; + if (sourceline == 0) { + return rb_sprintf("%"PRIsVALUE": ", sourcefile); + } + else if ((caller_name = rb_frame_callee()) != 0) { + return rb_sprintf("%"PRIsVALUE":%d:in `%"PRIsVALUE"': ", + sourcefile, sourceline, + rb_id2str(caller_name)); + } + else { + return rb_sprintf("%"PRIsVALUE":%d: ", sourcefile, sourceline); + } } return Qnil; } @@ -62,13 +62,13 @@ set_backtrace(VALUE info, VALUE bt) ID set_backtrace = rb_intern("set_backtrace"); if (rb_backtrace_p(bt)) { - if (rb_method_basic_definition_p(CLASS_OF(info), set_backtrace)) { - rb_exc_set_backtrace(info, bt); - return; - } - else { - bt = rb_backtrace_to_str_ary(bt); - } + if (rb_method_basic_definition_p(CLASS_OF(info), set_backtrace)) { + rb_exc_set_backtrace(info, bt); + return; + } + else { + bt = rb_backtrace_to_str_ary(bt); + } } rb_check_funcall(info, set_backtrace, 1, &bt); } @@ -106,24 +106,24 @@ print_errinfo(const VALUE eclass, const VALUE errat, const VALUE emesg, const VA } if (eclass == rb_eRuntimeError && elen == 0) { - if (highlight) write_warn(str, underline); - write_warn(str, "unhandled exception"); - if (highlight) write_warn(str, reset); - write_warn2(str, "\n", 1); + if (highlight) write_warn(str, underline); + write_warn(str, "unhandled exception"); + if (highlight) write_warn(str, reset); + write_warn2(str, "\n", 1); } else { - VALUE epath; + VALUE epath; - epath = rb_class_name(eclass); - if (elen == 0) { - if (highlight) write_warn(str, underline); - write_warn_str(str, epath); - if (highlight) write_warn(str, reset); - write_warn(str, "\n"); - } - else { - write_warn_str(str, emesg); - write_warn(str, "\n"); + epath = rb_class_name(eclass); + if (elen == 0) { + if (highlight) write_warn(str, underline); + write_warn_str(str, epath); + if (highlight) write_warn(str, reset); + write_warn(str, "\n"); + } + else { + write_warn_str(str, emesg); + write_warn(str, "\n"); } } } @@ -141,73 +141,73 @@ rb_decorate_message(const VALUE eclass, const VALUE emesg, int highlight) elen = RSTRING_LEN(emesg); } if (eclass == rb_eRuntimeError && elen == 0) { - if (highlight) write_warn(str, underline); - write_warn(str, "unhandled exception"); - if (highlight) write_warn(str, reset); + if (highlight) write_warn(str, underline); + write_warn(str, "unhandled exception"); + if (highlight) write_warn(str, reset); } else { - VALUE epath; + VALUE epath; - epath = rb_class_name(eclass); - if (elen == 0) { - if (highlight) write_warn(str, underline); - write_warn_str(str, epath); - if (highlight) write_warn(str, reset); - } - else { + epath = rb_class_name(eclass); + if (elen == 0) { + if (highlight) write_warn(str, underline); + write_warn_str(str, epath); + if (highlight) write_warn(str, reset); + } + else { /* emesg is a String instance */ - const char *tail = 0; + const char *tail = 0; if (highlight) write_warn(str, bold); - if (RSTRING_PTR(epath)[0] == '#') - epath = 0; - if ((tail = memchr(einfo, '\n', elen)) != 0) { + if (RSTRING_PTR(epath)[0] == '#') + epath = 0; + if ((tail = memchr(einfo, '\n', elen)) != 0) { write_warn2(str, einfo, tail - einfo); - tail++; /* skip newline */ - } - else { + tail++; /* skip newline */ + } + else { write_warn_str(str, emesg); - } - if (epath) { - write_warn(str, " ("); - if (highlight) write_warn(str, underline); + } + if (epath) { + write_warn(str, " ("); + if (highlight) write_warn(str, underline); write_warn_str(str, epath); - if (highlight) { - write_warn(str, reset); - write_warn(str, bold); - } - write_warn2(str, ")", 1); - if (highlight) write_warn(str, reset); - } - if (tail && einfo+elen > tail) { - if (!highlight) { + if (highlight) { + write_warn(str, reset); + write_warn(str, bold); + } + write_warn2(str, ")", 1); + if (highlight) write_warn(str, reset); + } + if (tail && einfo+elen > tail) { + if (!highlight) { write_warn2(str, "\n", 1); write_warn2(str, tail, einfo+elen-tail); - } - else { - elen -= tail - einfo; - einfo = tail; + } + else { + elen -= tail - einfo; + einfo = tail; write_warn2(str, "\n", 1); - while (elen > 0) { - tail = memchr(einfo, '\n', elen); - if (!tail || tail > einfo) { - write_warn(str, bold); + while (elen > 0) { + tail = memchr(einfo, '\n', elen); + if (!tail || tail > einfo) { + write_warn(str, bold); write_warn2(str, einfo, tail ? tail-einfo : elen); - write_warn(str, reset); - if (!tail) { - break; - } - } - elen -= tail - einfo; - einfo = tail; - do ++tail; while (tail < einfo+elen && *tail == '\n'); + write_warn(str, reset); + if (!tail) { + break; + } + } + elen -= tail - einfo; + einfo = tail; + do ++tail; while (tail < einfo+elen && *tail == '\n'); write_warn2(str, einfo, tail-einfo); - elen -= tail - einfo; - einfo = tail; - } - } - } - } + elen -= tail - einfo; + einfo = tail; + } + } + } + } } return str; @@ -217,13 +217,13 @@ static void print_backtrace(const VALUE eclass, const VALUE errat, const VALUE str, int reverse, long backtrace_limit) { if (!NIL_P(errat)) { - long i; - long len = RARRAY_LEN(errat); - const int threshold = 1000000000; + long i; + long len = RARRAY_LEN(errat); + const int threshold = 1000000000; int width = (len <= 1) ? INT_MIN : ((int)log10((double)(len > threshold ? - ((len - 1) / threshold) : - len - 1)) + - (len < threshold ? 0 : 9) + 1); + ((len - 1) / threshold) : + len - 1)) + + (len < threshold ? 0 : 9) + 1); long skip_start = -1, skip_len = 0; @@ -244,19 +244,19 @@ print_backtrace(const VALUE eclass, const VALUE errat, const VALUE str, int reve skip_len = len - skip_start; } - for (i = 1; i < len; i++) { - if (i == skip_start) { - write_warn_str(str, rb_sprintf("\t ... %ld levels...\n", skip_len)); - i += skip_len; + for (i = 1; i < len; i++) { + if (i == skip_start) { + write_warn_str(str, rb_sprintf("\t ... %ld levels...\n", skip_len)); + i += skip_len; if (i >= len) break; - } - VALUE line = RARRAY_AREF(errat, reverse ? len - i : i); - if (RB_TYPE_P(line, T_STRING)) { - VALUE bt = rb_str_new_cstr("\t"); - if (reverse) rb_str_catf(bt, "%*ld: ", width, len - i); - write_warn_str(str, rb_str_catf(bt, "from %"PRIsVALUE"\n", line)); - } - } + } + VALUE line = RARRAY_AREF(errat, reverse ? len - i : i); + if (RB_TYPE_P(line, T_STRING)) { + VALUE bt = rb_str_new_cstr("\t"); + if (reverse) rb_str_catf(bt, "%*ld: ", width, len - i); + write_warn_str(str, rb_str_catf(bt, "from %"PRIsVALUE"\n", line)); + } + } } } @@ -304,36 +304,36 @@ rb_error_write(VALUE errinfo, VALUE emesg, VALUE errat, VALUE str, VALUE opt, VA long backtrace_limit = rb_backtrace_length_limit; if (NIL_P(errinfo)) - return; + return; if (errat == Qundef) { - errat = Qnil; + errat = Qnil; } eclass = CLASS_OF(errinfo); if (reverse) { - static const char traceback[] = "Traceback " - "(most recent call last):\n"; - const int bold_part = rb_strlen_lit("Traceback"); - char buff[sizeof(traceback)+sizeof(bold)+sizeof(reset)-2], *p = buff; - const char *msg = traceback; - long len = sizeof(traceback) - 1; - if (RTEST(highlight)) { + static const char traceback[] = "Traceback " + "(most recent call last):\n"; + const int bold_part = rb_strlen_lit("Traceback"); + char buff[sizeof(traceback)+sizeof(bold)+sizeof(reset)-2], *p = buff; + const char *msg = traceback; + long len = sizeof(traceback) - 1; + if (RTEST(highlight)) { #define APPEND(s, l) (memcpy(p, s, l), p += (l)) - APPEND(bold, sizeof(bold)-1); - APPEND(traceback, bold_part); - APPEND(reset, sizeof(reset)-1); - APPEND(traceback + bold_part, sizeof(traceback)-bold_part-1); + APPEND(bold, sizeof(bold)-1); + APPEND(traceback, bold_part); + APPEND(reset, sizeof(reset)-1); + APPEND(traceback + bold_part, sizeof(traceback)-bold_part-1); #undef APPEND - len = p - (msg = buff); - } - write_warn2(str, msg, len); + len = p - (msg = buff); + } + write_warn2(str, msg, len); show_cause(errinfo, str, opt, highlight, reverse, backtrace_limit, &shown_causes); - print_backtrace(eclass, errat, str, TRUE, backtrace_limit); - print_errinfo(eclass, errat, emesg, str, RTEST(highlight)); + print_backtrace(eclass, errat, str, TRUE, backtrace_limit); + print_errinfo(eclass, errat, emesg, str, RTEST(highlight)); } else { - print_errinfo(eclass, errat, emesg, str, RTEST(highlight)); - print_backtrace(eclass, errat, str, FALSE, backtrace_limit); + print_errinfo(eclass, errat, emesg, str, RTEST(highlight)); + print_backtrace(eclass, errat, str, FALSE, backtrace_limit); show_cause(errinfo, str, opt, highlight, reverse, backtrace_limit, &shown_causes); } } @@ -351,16 +351,16 @@ rb_ec_error_print(rb_execution_context_t * volatile ec, volatile VALUE errinfo) rb_hash_aset(opt, ID2SYM(rb_intern_const("highlight")), highlight); if (NIL_P(errinfo)) - return; + return; rb_ec_raised_clear(ec); EC_PUSH_TAG(ec); if (EC_EXEC_TAG() == TAG_NONE) { - errat = rb_get_backtrace(errinfo); + errat = rb_get_backtrace(errinfo); } if (emesg == Qundef) { - emesg = Qnil; - emesg = rb_get_detailed_message(errinfo, opt); + emesg = Qnil; + emesg = rb_get_detailed_message(errinfo, opt); } if (!written) { @@ -375,9 +375,9 @@ rb_ec_error_print(rb_execution_context_t * volatile ec, volatile VALUE errinfo) #define undef_mesg_for(v, k) rb_fstring_lit("undefined"v" method `%1$s' for "k" `%2$s'") #define undef_mesg(v) ( \ - is_mod ? \ - undef_mesg_for(v, "module") : \ - undef_mesg_for(v, "class")) + is_mod ? \ + undef_mesg_for(v, "module") : \ + undef_mesg_for(v, "class")) void rb_print_undef(VALUE klass, ID id, rb_method_visibility_t visi) @@ -403,9 +403,9 @@ rb_print_undef_str(VALUE klass, VALUE name) #define inaccessible_mesg_for(v, k) rb_fstring_lit("method `%1$s' for "k" `%2$s' is "v) #define inaccessible_mesg(v) ( \ - is_mod ? \ - inaccessible_mesg_for(v, "module") : \ - inaccessible_mesg_for(v, "class")) + is_mod ? \ + inaccessible_mesg_for(v, "module") : \ + inaccessible_mesg_for(v, "class")) void rb_print_inaccessible(VALUE klass, ID id, rb_method_visibility_t visi) @@ -438,61 +438,61 @@ error_handle(rb_execution_context_t *ec, int ex) int status = EXIT_FAILURE; if (rb_ec_set_raised(ec)) - return EXIT_FAILURE; + return EXIT_FAILURE; switch (ex & TAG_MASK) { case 0: - status = EXIT_SUCCESS; - break; + status = EXIT_SUCCESS; + break; case TAG_RETURN: - error_pos(Qnil); - warn_print("unexpected return\n"); - break; + error_pos(Qnil); + warn_print("unexpected return\n"); + break; case TAG_NEXT: - error_pos(Qnil); - warn_print("unexpected next\n"); - break; + error_pos(Qnil); + warn_print("unexpected next\n"); + break; case TAG_BREAK: - error_pos(Qnil); - warn_print("unexpected break\n"); - break; + error_pos(Qnil); + warn_print("unexpected break\n"); + break; case TAG_REDO: - error_pos(Qnil); - warn_print("unexpected redo\n"); - break; + error_pos(Qnil); + warn_print("unexpected redo\n"); + break; case TAG_RETRY: - error_pos(Qnil); - warn_print("retry outside of rescue clause\n"); - break; + error_pos(Qnil); + warn_print("retry outside of rescue clause\n"); + break; case TAG_THROW: - /* TODO: fix me */ - error_pos(Qnil); - warn_print("unexpected throw\n"); - break; + /* TODO: fix me */ + error_pos(Qnil); + warn_print("unexpected throw\n"); + break; case TAG_RAISE: { - VALUE errinfo = ec->errinfo; - if (rb_obj_is_kind_of(errinfo, rb_eSystemExit)) { - status = sysexit_status(errinfo); - } - else if (rb_obj_is_instance_of(errinfo, rb_eSignal) && - rb_ivar_get(errinfo, id_signo) != INT2FIX(SIGSEGV)) { - /* no message when exiting by signal */ - } + VALUE errinfo = ec->errinfo; + if (rb_obj_is_kind_of(errinfo, rb_eSystemExit)) { + status = sysexit_status(errinfo); + } + else if (rb_obj_is_instance_of(errinfo, rb_eSignal) && + rb_ivar_get(errinfo, id_signo) != INT2FIX(SIGSEGV)) { + /* no message when exiting by signal */ + } else if (rb_obj_is_kind_of(errinfo, rb_eSystemCallError) && FIXNUM_P(rb_attr_get(errinfo, id_signo))) { - /* no message when exiting by error to be mapped to signal */ + /* no message when exiting by error to be mapped to signal */ } - else { - rb_ec_error_print(ec, errinfo); - } - break; + else { + rb_ec_error_print(ec, errinfo); + } + break; } case TAG_FATAL: - error_print(ec); - break; + error_print(ec); + break; default: - unknown_longjmp_status(ex); - break; + unknown_longjmp_status(ex); + break; } rb_ec_reset_raised(ec); return status; diff --git a/eval_intern.h b/eval_intern.h index 0efbcb0441..6cbaa51361 100644 --- a/eval_intern.h +++ b/eval_intern.h @@ -329,9 +329,9 @@ static inline void translit_char(char *p, int from, int to) { while (*p) { - if ((unsigned char)*p == from) - *p = to; - p = CharNext(p); + if ((unsigned char)*p == from) + *p = to; + p = CharNext(p); } } #endif diff --git a/eval_jump.c b/eval_jump.c index 2ea73b0da3..a6139bc27b 100644 --- a/eval_jump.c +++ b/eval_jump.c @@ -40,7 +40,7 @@ rb_f_at_exit(VALUE _) VALUE proc; if (!rb_block_given_p()) { - rb_raise(rb_eArgError, "called without a block"); + rb_raise(rb_eArgError, "called without a block"); } proc = rb_block_proc(); rb_set_end_proc(rb_call_end_proc, proc); @@ -63,10 +63,10 @@ rb_set_end_proc(void (*func)(VALUE), VALUE data) rb_thread_t *th = GET_THREAD(); if (th->top_wrapper) { - list = &ephemeral_end_procs; + list = &ephemeral_end_procs; } else { - list = &end_procs; + list = &end_procs; } link->next = *list; link->func = func; @@ -81,13 +81,13 @@ rb_mark_end_proc(void) link = end_procs; while (link) { - rb_gc_mark(link->data); - link = link->next; + rb_gc_mark(link->data); + link = link->next; } link = ephemeral_end_procs; while (link) { - rb_gc_mark(link->data); - link = link->next; + rb_gc_mark(link->data); + link = link->next; } } @@ -99,11 +99,11 @@ exec_end_procs_chain(struct end_proc_data *volatile *procs, VALUE *errp) VALUE errinfo = *errp; while ((link = *procs) != 0) { - *procs = link->next; - endproc = *link; - xfree(link); - (*endproc.func) (endproc.data); - *errp = errinfo; + *procs = link->next; + endproc = *link; + xfree(link); + (*endproc.func) (endproc.data); + *errp = errinfo; } } @@ -116,15 +116,15 @@ rb_ec_exec_end_proc(rb_execution_context_t * ec) EC_PUSH_TAG(ec); if ((state = EC_EXEC_TAG()) == TAG_NONE) { again: - exec_end_procs_chain(&ephemeral_end_procs, &ec->errinfo); - exec_end_procs_chain(&end_procs, &ec->errinfo); + exec_end_procs_chain(&ephemeral_end_procs, &ec->errinfo); + exec_end_procs_chain(&end_procs, &ec->errinfo); } else { - EC_TMPPOP_TAG(); + EC_TMPPOP_TAG(); error_handle(ec, state); - if (!NIL_P(ec->errinfo)) errinfo = ec->errinfo; - EC_REPUSH_TAG(); - goto again; + if (!NIL_P(ec->errinfo)) errinfo = ec->errinfo; + EC_REPUSH_TAG(); + goto again; } EC_POP_TAG(); diff --git a/ext/-test-/debug/inspector.c b/ext/-test-/debug/inspector.c index f0c58e59f9..25f9d894d3 100644 --- a/ext/-test-/debug/inspector.c +++ b/ext/-test-/debug/inspector.c @@ -8,13 +8,13 @@ callback(const rb_debug_inspector_t *dbg_context, void *data) long i, len = RARRAY_LEN(locs); VALUE binds = rb_ary_new(); for (i = 0; i < len; ++i) { - VALUE entry = rb_ary_new(); - rb_ary_push(binds, entry); - rb_ary_push(entry, rb_debug_inspector_frame_self_get(dbg_context, i)); - rb_ary_push(entry, rb_debug_inspector_frame_binding_get(dbg_context, i)); - rb_ary_push(entry, rb_debug_inspector_frame_class_get(dbg_context, i)); - rb_ary_push(entry, rb_debug_inspector_frame_iseq_get(dbg_context, i)); - rb_ary_push(entry, rb_ary_entry(locs, i)); + VALUE entry = rb_ary_new(); + rb_ary_push(binds, entry); + rb_ary_push(entry, rb_debug_inspector_frame_self_get(dbg_context, i)); + rb_ary_push(entry, rb_debug_inspector_frame_binding_get(dbg_context, i)); + rb_ary_push(entry, rb_debug_inspector_frame_class_get(dbg_context, i)); + rb_ary_push(entry, rb_debug_inspector_frame_iseq_get(dbg_context, i)); + rb_ary_push(entry, rb_ary_entry(locs, i)); } return binds; } diff --git a/ext/-test-/debug/profile_frames.c b/ext/-test-/debug/profile_frames.c index 1656ff7d4b..5f14755ce7 100644 --- a/ext/-test-/debug/profile_frames.c +++ b/ext/-test-/debug/profile_frames.c @@ -18,19 +18,19 @@ profile_frames(VALUE self, VALUE start_v, VALUE num_v) collected_size = rb_profile_frames(start, buff_size, buff, lines); for (i=0; i p); memmove(p, e, e0 - e); return p + (e0 - e); @@ -44,48 +44,48 @@ printf_test_call(int argc, VALUE *argv, VALUE self) if (RSTRING_LEN(type) != 1) rb_raise(rb_eArgError, "wrong length(%ld)", RSTRING_LEN(type)); switch (cnv = RSTRING_PTR(type)[0]) { case 'd': case 'x': case 'o': case 'X': - n = NUM2INT(num); - break; + n = NUM2INT(num); + break; case 's': - s = StringValueCStr(num); - break; + s = StringValueCStr(num); + break; default: rb_raise(rb_eArgError, "wrong conversion(%c)", cnv); } *p++ = '%'; if (!NIL_P(opt)) { - VALUE v; - Check_Type(opt, T_HASH); - if (RTEST(rb_hash_aref(opt, ID2SYM(rb_intern("space"))))) { - *p++ = ' '; - } - if (RTEST(rb_hash_aref(opt, ID2SYM(rb_intern("hash"))))) { - *p++ = '#'; - } - if (RTEST(rb_hash_aref(opt, ID2SYM(rb_intern("plus"))))) { - *p++ = '+'; - } - if (RTEST(rb_hash_aref(opt, ID2SYM(rb_intern("minus"))))) { - *p++ = '-'; - } - if (RTEST(rb_hash_aref(opt, ID2SYM(rb_intern("zero"))))) { - *p++ = '0'; - } - if (!NIL_P(v = rb_hash_aref(opt, ID2SYM(rb_intern("width"))))) { - p = uint_to_str(p, format + sizeof(format), NUM2UINT(v)); - } - if (!NIL_P(v = rb_hash_aref(opt, ID2SYM(rb_intern("prec"))))) { - *p++ = '.'; - if (FIXNUM_P(v)) - p = uint_to_str(p, format + sizeof(format), NUM2UINT(v)); - } + VALUE v; + Check_Type(opt, T_HASH); + if (RTEST(rb_hash_aref(opt, ID2SYM(rb_intern("space"))))) { + *p++ = ' '; + } + if (RTEST(rb_hash_aref(opt, ID2SYM(rb_intern("hash"))))) { + *p++ = '#'; + } + if (RTEST(rb_hash_aref(opt, ID2SYM(rb_intern("plus"))))) { + *p++ = '+'; + } + if (RTEST(rb_hash_aref(opt, ID2SYM(rb_intern("minus"))))) { + *p++ = '-'; + } + if (RTEST(rb_hash_aref(opt, ID2SYM(rb_intern("zero"))))) { + *p++ = '0'; + } + if (!NIL_P(v = rb_hash_aref(opt, ID2SYM(rb_intern("width"))))) { + p = uint_to_str(p, format + sizeof(format), NUM2UINT(v)); + } + if (!NIL_P(v = rb_hash_aref(opt, ID2SYM(rb_intern("prec"))))) { + *p++ = '.'; + if (FIXNUM_P(v)) + p = uint_to_str(p, format + sizeof(format), NUM2UINT(v)); + } } *p++ = cnv; *p++ = '\0'; if (cnv == 's') { - result = rb_enc_sprintf(rb_usascii_encoding(), format, s); + result = rb_enc_sprintf(rb_usascii_encoding(), format, s); } else { - result = rb_enc_sprintf(rb_usascii_encoding(), format, n); + result = rb_enc_sprintf(rb_usascii_encoding(), format, n); } return rb_assoc_new(result, rb_usascii_str_new_cstr(format)); } diff --git a/ext/-test-/proc/super.c b/ext/-test-/proc/super.c index dbe8af08f1..816520e1df 100644 --- a/ext/-test-/proc/super.c +++ b/ext/-test-/proc/super.c @@ -9,7 +9,7 @@ bug_proc_call_super(RB_BLOCK_CALL_FUNC_ARGLIST(yieldarg, procarg)) args[1] = procarg; ret = rb_call_super(2, args); if (!NIL_P(blockarg)) { - ret = rb_proc_call(blockarg, ret); + ret = rb_proc_call(blockarg, ret); } return ret; } diff --git a/ext/-test-/st/foreach/foreach.c b/ext/-test-/st/foreach/foreach.c index 27ac18046f..cde49fb26d 100644 --- a/ext/-test-/st/foreach/foreach.c +++ b/ext/-test-/st/foreach/foreach.c @@ -12,22 +12,22 @@ static void force_unpack_check(struct checker *c, st_data_t key, st_data_t val) { if (c->nr == 0) { - st_data_t i; + st_data_t i; - if (c->tbl->bins != NULL) rb_bug("should be packed\n"); + if (c->tbl->bins != NULL) rb_bug("should be packed\n"); - /* force unpacking during iteration: */ - for (i = 1; i < expect_size; i++) - st_add_direct(c->tbl, i, i); + /* force unpacking during iteration: */ + for (i = 1; i < expect_size; i++) + st_add_direct(c->tbl, i, i); - if (c->tbl->bins == NULL) rb_bug("should be unpacked\n"); + if (c->tbl->bins == NULL) rb_bug("should be unpacked\n"); } if (key != c->nr) { - rb_bug("unexpected key: %"PRIuVALUE" (expected %"PRIuVALUE")\n", (VALUE)key, (VALUE)c->nr); + rb_bug("unexpected key: %"PRIuVALUE" (expected %"PRIuVALUE")\n", (VALUE)key, (VALUE)c->nr); } if (val != c->nr) { - rb_bug("unexpected val: %"PRIuVALUE" (expected %"PRIuVALUE")\n", (VALUE)val, (VALUE)c->nr); + rb_bug("unexpected val: %"PRIuVALUE" (expected %"PRIuVALUE")\n", (VALUE)val, (VALUE)c->nr); } c->nr++; @@ -39,34 +39,34 @@ unp_fec_i(st_data_t key, st_data_t val, st_data_t args, int error) struct checker *c = (struct checker *)args; if (error) { - if (c->test == ID2SYM(rb_intern("delete2"))) - return ST_STOP; + if (c->test == ID2SYM(rb_intern("delete2"))) + return ST_STOP; - rb_bug("unexpected error"); + rb_bug("unexpected error"); } force_unpack_check(c, key, val); if (c->test == ID2SYM(rb_intern("check"))) { - return ST_CHECK; + return ST_CHECK; } if (c->test == ID2SYM(rb_intern("delete1"))) { - if (c->nr == 1) return ST_DELETE; - return ST_CHECK; + if (c->nr == 1) return ST_DELETE; + return ST_CHECK; } if (c->test == ID2SYM(rb_intern("delete2"))) { - if (c->nr == 1) { - st_data_t k = 0; - st_data_t v; + if (c->nr == 1) { + st_data_t k = 0; + st_data_t v; - if (!st_delete(c->tbl, &k, &v)) { - rb_bug("failed to delete\n"); - } - if (v != 0) { - rb_bug("unexpected value deleted: %"PRIuVALUE" (expected 0)", (VALUE)v); - } - } - return ST_CHECK; + if (!st_delete(c->tbl, &k, &v)) { + rb_bug("failed to delete\n"); + } + if (v != 0) { + rb_bug("unexpected value deleted: %"PRIuVALUE" (expected 0)", (VALUE)v); + } + } + return ST_CHECK; } rb_raise(rb_eArgError, "unexpected arg: %+"PRIsVALUE, c->test); @@ -89,13 +89,13 @@ unp_fec(VALUE self, VALUE test) st_foreach_check(tbl, unp_fec_i, (st_data_t)&c, -1); if (c.test == ID2SYM(rb_intern("delete2"))) { - if (c.nr != 1) { - rb_bug("mismatched iteration: %"PRIuVALUE" (expected 1)\n", (VALUE)c.nr); - } + if (c.nr != 1) { + rb_bug("mismatched iteration: %"PRIuVALUE" (expected 1)\n", (VALUE)c.nr); + } } else if (c.nr != expect_size) { - rb_bug("mismatched iteration: %"PRIuVALUE" (expected %"PRIuVALUE")\n", - (VALUE)c.nr, (VALUE)expect_size); + rb_bug("mismatched iteration: %"PRIuVALUE" (expected %"PRIuVALUE")\n", + (VALUE)c.nr, (VALUE)expect_size); } if (tbl->bins == NULL) rb_bug("should be unpacked\n"); @@ -112,22 +112,22 @@ unp_fe_i(st_data_t key, st_data_t val, st_data_t args) force_unpack_check(c, key, val); if (c->test == ID2SYM(rb_intern("unpacked"))) { - return ST_CONTINUE; + return ST_CONTINUE; } else if (c->test == ID2SYM(rb_intern("unpack_delete"))) { - if (c->nr == 1) { - st_data_t k = 0; - st_data_t v; + if (c->nr == 1) { + st_data_t k = 0; + st_data_t v; - if (!st_delete(c->tbl, &k, &v)) { - rb_bug("failed to delete\n"); - } - if (v != 0) { - rb_bug("unexpected value deleted: %"PRIuVALUE" (expected 0)", (VALUE)v); - } - return ST_CONTINUE; - } - rb_bug("should never get here\n"); + if (!st_delete(c->tbl, &k, &v)) { + rb_bug("failed to delete\n"); + } + if (v != 0) { + rb_bug("unexpected value deleted: %"PRIuVALUE" (expected 0)", (VALUE)v); + } + return ST_CONTINUE; + } + rb_bug("should never get here\n"); } rb_raise(rb_eArgError, "unexpected arg: %+"PRIsVALUE, c->test); @@ -150,13 +150,13 @@ unp_fe(VALUE self, VALUE test) st_foreach(tbl, unp_fe_i, (st_data_t)&c); if (c.test == ID2SYM(rb_intern("unpack_delete"))) { - if (c.nr != 1) { - rb_bug("mismatched iteration: %"PRIuVALUE" (expected 1)\n", (VALUE)c.nr); - } + if (c.nr != 1) { + rb_bug("mismatched iteration: %"PRIuVALUE" (expected 1)\n", (VALUE)c.nr); + } } else if (c.nr != expect_size) { - rb_bug("mismatched iteration: %"PRIuVALUE" (expected %"PRIuVALUE"o)\n", - (VALUE)c.nr, (VALUE)expect_size); + rb_bug("mismatched iteration: %"PRIuVALUE" (expected %"PRIuVALUE"o)\n", + (VALUE)c.nr, (VALUE)expect_size); } if (tbl->bins == NULL) rb_bug("should be unpacked\n"); diff --git a/ext/-test-/st/numhash/numhash.c b/ext/-test-/st/numhash/numhash.c index aa8015e86c..7e8d5d9fe2 100644 --- a/ext/-test-/st/numhash/numhash.c +++ b/ext/-test-/st/numhash/numhash.c @@ -42,7 +42,7 @@ numhash_aref(VALUE self, VALUE key) st_table *tbl = (st_table *)Check_TypedStruct(self, &numhash_type); if (!SPECIAL_CONST_P(key)) rb_raise(rb_eArgError, "not a special const"); if (st_lookup(tbl, (st_data_t)key, &data)) - return (VALUE)data; + return (VALUE)data; return Qnil; } @@ -79,12 +79,12 @@ update_func(st_data_t *key, st_data_t *value, st_data_t arg, int existing) VALUE ret = rb_yield_values(existing ? 2 : 1, (VALUE)*key, (VALUE)*value); switch (ret) { case Qfalse: - return ST_STOP; + return ST_STOP; case Qnil: - return ST_DELETE; + return ST_DELETE; default: - *value = ret; - return ST_CONTINUE; + *value = ret; + return ST_CONTINUE; } } @@ -93,9 +93,9 @@ numhash_update(VALUE self, VALUE key) { st_table *table = (st_table *)Check_TypedStruct(self, &numhash_type); if (st_update(table, (st_data_t)key, update_func, 0)) - return Qtrue; + return Qtrue; else - return Qfalse; + return Qfalse; } #if SIZEOF_LONG == SIZEOF_VOIDP @@ -117,7 +117,7 @@ numhash_delete_safe(VALUE self, VALUE key) st_table *table = (st_table *)Check_TypedStruct(self, &numhash_type); st_data_t val, k = (st_data_t)key; if (st_delete_safe(table, &k, &val, (st_data_t)self)) { - return val; + return val; } return Qnil; } diff --git a/ext/-test-/st/update/update.c b/ext/-test-/st/update/update.c index 979ad3e334..ea7fab12e1 100644 --- a/ext/-test-/st/update/update.c +++ b/ext/-test-/st/update/update.c @@ -7,12 +7,12 @@ update_func(st_data_t *key, st_data_t *value, st_data_t arg, int existing) VALUE ret = rb_yield_values(existing ? 2 : 1, (VALUE)*key, (VALUE)*value); switch (ret) { case Qfalse: - return ST_STOP; + return ST_STOP; case Qnil: - return ST_DELETE; + return ST_DELETE; default: - *value = ret; - return ST_CONTINUE; + *value = ret; + return ST_CONTINUE; } } @@ -20,9 +20,9 @@ static VALUE test_st_update(VALUE self, VALUE key) { if (st_update(RHASH_TBL(self), (st_data_t)key, update_func, 0)) - return Qtrue; + return Qtrue; else - return Qfalse; + return Qfalse; } void diff --git a/ext/-test-/string/coderange.c b/ext/-test-/string/coderange.c index bc998ca372..4197ecca9f 100644 --- a/ext/-test-/string/coderange.c +++ b/ext/-test-/string/coderange.c @@ -8,13 +8,13 @@ coderange_int2sym(int coderange) { switch (coderange) { case ENC_CODERANGE_7BIT: - return sym_7bit; + return sym_7bit; case ENC_CODERANGE_VALID: - return sym_valid; + return sym_valid; case ENC_CODERANGE_UNKNOWN: - return sym_unknown; + return sym_unknown; case ENC_CODERANGE_BROKEN: - return sym_broken; + return sym_broken; } rb_bug("wrong condition of coderange"); UNREACHABLE_RETURN(Qnil); diff --git a/ext/-test-/string/cstr.c b/ext/-test-/string/cstr.c index 1eadb8b4fd..468ee7a3b1 100644 --- a/ext/-test-/string/cstr.c +++ b/ext/-test-/string/cstr.c @@ -42,11 +42,11 @@ bug_str_cstr_term_char(VALUE str) len = rb_enc_mbminlen(enc); c = rb_enc_precise_mbclen(s, s + len, enc); if (!MBCLEN_CHARFOUND_P(c)) { - c = (unsigned char)*s; + c = (unsigned char)*s; } else { - c = rb_enc_mbc_to_codepoint(s, s + len, enc); - if (!c) return Qnil; + c = rb_enc_mbc_to_codepoint(s, s + len, enc); + if (!c) return Qnil; } return rb_enc_uint_chr((unsigned int)c, enc); } @@ -65,14 +65,14 @@ bug_str_unterminated_substring(VALUE str, VALUE vbeg, VALUE vlen) #if USE_RVARGC RSTRING(str)->as.embed.len = (short)len; #else - RSTRING(str)->basic.flags &= ~RSTRING_EMBED_LEN_MASK; - RSTRING(str)->basic.flags |= len << RSTRING_EMBED_LEN_SHIFT; + RSTRING(str)->basic.flags &= ~RSTRING_EMBED_LEN_MASK; + RSTRING(str)->basic.flags |= len << RSTRING_EMBED_LEN_SHIFT; #endif memmove(RSTRING(str)->as.embed.ary, RSTRING(str)->as.embed.ary + beg, len); } else { - RSTRING(str)->as.heap.ptr += beg; - RSTRING(str)->as.heap.len = len; + RSTRING(str)->as.heap.ptr += beg; + RSTRING(str)->as.heap.len = len; } return str; } @@ -104,7 +104,7 @@ bug_str_s_cstr_term_char(VALUE self, VALUE str) const int term_fill_len = (termlen);\ *term_fill_ptr = '\0';\ if (UNLIKELY(term_fill_len > 1))\ - memset(term_fill_ptr, 0, term_fill_len);\ + memset(term_fill_ptr, 0, term_fill_len);\ } while (0) static VALUE diff --git a/ext/-test-/string/qsort.c b/ext/-test-/string/qsort.c index fb7ea3d8cb..4a641e74e3 100644 --- a/ext/-test-/string/qsort.c +++ b/ext/-test-/string/qsort.c @@ -35,22 +35,22 @@ bug_str_qsort_bang(int argc, VALUE *argv, VALUE str) rb_scan_args(argc, argv, "03", &beg, &len, &size); l = RSTRING_LEN(str); if (!NIL_P(beg) && (b = NUM2INT(beg)) < 0 && (b += l) < 0) { - rb_raise(rb_eArgError, "out of bounds"); + rb_raise(rb_eArgError, "out of bounds"); } if (!NIL_P(size) && (s = NUM2INT(size)) < 0) { - rb_raise(rb_eArgError, "negative size"); + rb_raise(rb_eArgError, "negative size"); } if (NIL_P(len) || - (((n = NUM2INT(len)) < 0) ? - (rb_raise(rb_eArgError, "negative length"), 0) : - (b + n * s > l))) { - n = (l - b) / s; + (((n = NUM2INT(len)) < 0) ? + (rb_raise(rb_eArgError, "negative length"), 0) : + (b + n * s > l))) { + n = (l - b) / s; } rb_str_modify(str); d.enc = rb_enc_get(str); d.elsize = s; ruby_qsort(RSTRING_PTR(str) + b, n, s, - rb_block_given_p() ? cmp_1 : cmp_2, &d); + rb_block_given_p() ? cmp_1 : cmp_2, &d); return str; } diff --git a/ext/-test-/struct/member.c b/ext/-test-/struct/member.c index 1d404039b4..f5400fe477 100644 --- a/ext/-test-/struct/member.c +++ b/ext/-test-/struct/member.c @@ -6,7 +6,7 @@ bug_struct_get(VALUE obj, VALUE name) ID id = rb_check_id(&name); if (!id) { - rb_name_error_str(name, "`%"PRIsVALUE"' is not a struct member", name); + rb_name_error_str(name, "`%"PRIsVALUE"' is not a struct member", name); } return rb_struct_getmember(obj, id); } diff --git a/ext/-test-/symbol/type.c b/ext/-test-/symbol/type.c index e51e09eb26..8d0e647340 100644 --- a/ext/-test-/symbol/type.c +++ b/ext/-test-/symbol/type.c @@ -2,12 +2,12 @@ #ifdef HAVE_RB_IS_CONST_NAME # define get_symbol_type(type, t, name) do { \ - ID id = rb_check_id(&name); \ - t = (id ? rb_is_##type##_id(id) : rb_is_##type##_name(name)); \ + ID id = rb_check_id(&name); \ + t = (id ? rb_is_##type##_id(id) : rb_is_##type##_name(name)); \ } while (0) #else # define get_symbol_type(type, t, name) do { \ - t = rb_is_##type##_id(rb_to_id(name)); \ + t = rb_is_##type##_id(rb_to_id(name)); \ } while (0) #endif diff --git a/ext/-test-/tracepoint/gc_hook.c b/ext/-test-/tracepoint/gc_hook.c index 5fd46fa518..a3f4e7f68a 100644 --- a/ext/-test-/tracepoint/gc_hook.c +++ b/ext/-test-/tracepoint/gc_hook.c @@ -28,12 +28,12 @@ static void gc_start_end_i(VALUE tpval, void *data) { if (0) { - rb_trace_arg_t *tparg = rb_tracearg_from_tracepoint(tpval); - fprintf(stderr, "trace: %s\n", rb_tracearg_event_flag(tparg) == RUBY_INTERNAL_EVENT_GC_START ? "gc_start" : "gc_end"); + rb_trace_arg_t *tparg = rb_tracearg_from_tracepoint(tpval); + fprintf(stderr, "trace: %s\n", rb_tracearg_event_flag(tparg) == RUBY_INTERNAL_EVENT_GC_START ? "gc_start" : "gc_end"); } if (invoking == 0) { - rb_postponed_job_register(0, invoke_proc, data); + rb_postponed_job_register(0, invoke_proc, data); } } @@ -45,19 +45,19 @@ set_gc_hook(VALUE module, VALUE proc, rb_event_flag_t event, const char *tp_str, /* disable previous keys */ if (rb_ivar_defined(module, tp_key) != 0 && - RTEST(tpval = rb_ivar_get(module, tp_key))) { - rb_tracepoint_disable(tpval); - rb_ivar_set(module, tp_key, Qnil); + RTEST(tpval = rb_ivar_get(module, tp_key))) { + rb_tracepoint_disable(tpval); + rb_ivar_set(module, tp_key, Qnil); } if (RTEST(proc)) { - if (!rb_obj_is_proc(proc)) { - rb_raise(rb_eTypeError, "trace_func needs to be Proc"); - } + if (!rb_obj_is_proc(proc)) { + rb_raise(rb_eTypeError, "trace_func needs to be Proc"); + } - tpval = rb_tracepoint_new(0, event, gc_start_end_i, (void *)proc); - rb_ivar_set(module, tp_key, tpval); - rb_tracepoint_enable(tpval); + tpval = rb_tracepoint_new(0, event, gc_start_end_i, (void *)proc); + rb_ivar_set(module, tp_key, tpval); + rb_tracepoint_enable(tpval); } return proc; @@ -67,7 +67,7 @@ static VALUE set_after_gc_start(VALUE module, VALUE proc) { return set_gc_hook(module, proc, RUBY_INTERNAL_EVENT_GC_START, - "__set_after_gc_start_tpval__", "__set_after_gc_start_proc__"); + "__set_after_gc_start_tpval__", "__set_after_gc_start_proc__"); } static VALUE diff --git a/ext/-test-/tracepoint/tracepoint.c b/ext/-test-/tracepoint/tracepoint.c index aa8c212f99..2826cc038c 100644 --- a/ext/-test-/tracepoint/tracepoint.c +++ b/ext/-test-/tracepoint/tracepoint.c @@ -21,35 +21,35 @@ tracepoint_track_objspace_events_i(VALUE tpval, void *data) switch (rb_tracearg_event_flag(tparg)) { case RUBY_INTERNAL_EVENT_NEWOBJ: - { - VALUE obj = rb_tracearg_object(tparg); - if (track->objects_count < objects_max) - track->objects[track->objects_count++] = obj; - track->newobj_count++; - break; - } + { + VALUE obj = rb_tracearg_object(tparg); + if (track->objects_count < objects_max) + track->objects[track->objects_count++] = obj; + track->newobj_count++; + break; + } case RUBY_INTERNAL_EVENT_FREEOBJ: - { - track->free_count++; - break; - } + { + track->free_count++; + break; + } case RUBY_INTERNAL_EVENT_GC_START: - { - track->gc_start_count++; - break; - } + { + track->gc_start_count++; + break; + } case RUBY_INTERNAL_EVENT_GC_END_MARK: - { - track->gc_end_mark_count++; - break; - } + { + track->gc_end_mark_count++; + break; + } case RUBY_INTERNAL_EVENT_GC_END_SWEEP: - { - track->gc_end_sweep_count++; - break; - } + { + track->gc_end_sweep_count++; + break; + } default: - rb_raise(rb_eRuntimeError, "unknown event"); + rb_raise(rb_eRuntimeError, "unknown event"); } } @@ -58,9 +58,9 @@ tracepoint_track_objspace_events(VALUE self) { struct tracepoint_track track = {0, 0, 0, 0, 0,}; VALUE tpval = rb_tracepoint_new(0, RUBY_INTERNAL_EVENT_NEWOBJ | RUBY_INTERNAL_EVENT_FREEOBJ | - RUBY_INTERNAL_EVENT_GC_START | RUBY_INTERNAL_EVENT_GC_END_MARK | - RUBY_INTERNAL_EVENT_GC_END_SWEEP, - tracepoint_track_objspace_events_i, &track); + RUBY_INTERNAL_EVENT_GC_START | RUBY_INTERNAL_EVENT_GC_END_MARK | + RUBY_INTERNAL_EVENT_GC_END_SWEEP, + tracepoint_track_objspace_events_i, &track); VALUE result = rb_ary_new(); rb_tracepoint_enable(tpval); diff --git a/ext/-test-/typeddata/typeddata.c b/ext/-test-/typeddata/typeddata.c index 2adfd56ae8..cf3178fd18 100644 --- a/ext/-test-/typeddata/typeddata.c +++ b/ext/-test-/typeddata/typeddata.c @@ -27,7 +27,7 @@ test_make(VALUE klass, VALUE num) unsigned long i, n = NUM2UINT(num); for (i = 0; i < n; i++) { - test_alloc(klass); + test_alloc(klass); } return Qnil; diff --git a/ext/-test-/vm/at_exit.c b/ext/-test-/vm/at_exit.c index 6cfbfafa9e..efc439b26a 100644 --- a/ext/-test-/vm/at_exit.c +++ b/ext/-test-/vm/at_exit.c @@ -23,14 +23,14 @@ register_at_exit(VALUE self, VALUE t) { switch (t) { case Qtrue: - ruby_vm_at_exit(print_begin); - break; + ruby_vm_at_exit(print_begin); + break; case Qfalse: - ruby_vm_at_exit(print_end); - break; + ruby_vm_at_exit(print_end); + break; default: - ruby_vm_at_exit(do_nothing); - break; + ruby_vm_at_exit(do_nothing); + break; } return self; } diff --git a/ext/-test-/win32/console/attribute.c b/ext/-test-/win32/console/attribute.c index e3e80a199f..b43ba23a5c 100644 --- a/ext/-test-/win32/console/attribute.c +++ b/ext/-test-/win32/console/attribute.c @@ -19,13 +19,13 @@ console_info(VALUE klass, VALUE io) CONSOLE_SCREEN_BUFFER_INFO csbi; if (!GetConsoleScreenBufferInfo(h, &csbi)) - rb_syserr_fail(rb_w32_map_errno(GetLastError()), "not console"); + rb_syserr_fail(rb_w32_map_errno(GetLastError()), "not console"); return rb_struct_new(rb_cConsoleScreenBufferInfo, - INT2FIX(csbi.dwSize.X), - INT2FIX(csbi.dwSize.Y), - INT2FIX(csbi.dwCursorPosition.X), - INT2FIX(csbi.dwCursorPosition.Y), - INT2FIX(csbi.wAttributes)); + INT2FIX(csbi.dwSize.X), + INT2FIX(csbi.dwSize.Y), + INT2FIX(csbi.dwCursorPosition.X), + INT2FIX(csbi.dwCursorPosition.Y), + INT2FIX(csbi.wAttributes)); } static VALUE @@ -44,9 +44,9 @@ void Init_attribute(VALUE m) { rb_cConsoleScreenBufferInfo = rb_struct_define_under(m, "ConsoleScreenBufferInfo", - "size_x", "size_y", - "cur_x", "cur_y", - "attr", NULL); + "size_x", "size_y", + "cur_x", "cur_y", + "attr", NULL); rb_define_singleton_method(m, "console_info", console_info, 1); rb_define_singleton_method(m, "console_attribute", console_set_attribute, 2); diff --git a/ext/-test-/win32/fd_setsize/fd_setsize.c b/ext/-test-/win32/fd_setsize/fd_setsize.c index 8da8b1eaa0..e29114a0ca 100644 --- a/ext/-test-/win32/fd_setsize/fd_setsize.c +++ b/ext/-test-/win32/fd_setsize/fd_setsize.c @@ -37,11 +37,11 @@ test_fdset(VALUE self) FD_ZERO(&set); for (i = 0; i < FD_SETSIZE * 2; i++) { - int sd = socket(AF_INET, SOCK_DGRAM, 0); - FD_SET(sd, &set); - if (set.fd_count > FD_SETSIZE) { - return Qfalse; - } + int sd = socket(AF_INET, SOCK_DGRAM, 0); + FD_SET(sd, &set); + if (set.fd_count > FD_SETSIZE) { + return Qfalse; + } } return Qtrue; } diff --git a/ext/cgi/escape/escape.c b/ext/cgi/escape/escape.c index f88b61478b..068647747d 100644 --- a/ext/cgi/escape/escape.c +++ b/ext/cgi/escape/escape.c @@ -37,7 +37,7 @@ escaped_length(VALUE str) { const long len = RSTRING_LEN(str); if (len >= LONG_MAX / HTML_ESCAPE_MAX_LEN) { - ruby_malloc_size_overflow(len, HTML_ESCAPE_MAX_LEN); + ruby_malloc_size_overflow(len, HTML_ESCAPE_MAX_LEN); } return len * HTML_ESCAPE_MAX_LEN; } @@ -81,8 +81,8 @@ optimized_unescape_html(VALUE str) enum {UNICODE_MAX = 0x10ffff}; rb_encoding *enc = rb_enc_get(str); unsigned long charlimit = (strcasecmp(rb_enc_name(enc), "UTF-8") == 0 ? UNICODE_MAX : - strcasecmp(rb_enc_name(enc), "ISO-8859-1") == 0 ? 256 : - 128); + strcasecmp(rb_enc_name(enc), "ISO-8859-1") == 0 ? 256 : + 128); long i, len, beg = 0; size_t clen, plen; int overflow; @@ -94,89 +94,89 @@ optimized_unescape_html(VALUE str) cstr = RSTRING_PTR(str); for (i = 0; i < len; i++) { - unsigned long cc; - char c = cstr[i]; - if (c != '&') continue; - plen = i - beg; - if (++i >= len) break; - c = (unsigned char)cstr[i]; + unsigned long cc; + char c = cstr[i]; + if (c != '&') continue; + plen = i - beg; + if (++i >= len) break; + c = (unsigned char)cstr[i]; #define MATCH(s) (len - i >= (int)rb_strlen_lit(s) && \ - memcmp(&cstr[i], s, rb_strlen_lit(s)) == 0 && \ - (i += rb_strlen_lit(s) - 1, 1)) - switch (c) { - case 'a': - ++i; - if (MATCH("pos;")) { - c = '\''; - } - else if (MATCH("mp;")) { - c = '&'; - } - else continue; - break; - case 'q': - ++i; - if (MATCH("uot;")) { - c = '"'; - } - else continue; - break; - case 'g': - ++i; - if (MATCH("t;")) { - c = '>'; - } - else continue; - break; - case 'l': - ++i; - if (MATCH("t;")) { - c = '<'; - } - else continue; - break; - case '#': - if (len - ++i >= 2 && ISDIGIT(cstr[i])) { - cc = ruby_scan_digits(&cstr[i], len-i, 10, &clen, &overflow); - } - else if ((cstr[i] == 'x' || cstr[i] == 'X') && len - ++i >= 2 && ISXDIGIT(cstr[i])) { - cc = ruby_scan_digits(&cstr[i], len-i, 16, &clen, &overflow); - } - else continue; - i += clen; - if (overflow || cc >= charlimit || cstr[i] != ';') continue; - if (!dest) { - dest = rb_str_buf_new(len); - } - rb_str_cat(dest, cstr + beg, plen); - if (charlimit > 256) { - rb_str_cat(dest, buf, rb_enc_mbcput((OnigCodePoint)cc, buf, enc)); - } - else { - c = (unsigned char)cc; - rb_str_cat(dest, &c, 1); - } - beg = i + 1; - continue; - default: - --i; - continue; - } - if (!dest) { - dest = rb_str_buf_new(len); - } - rb_str_cat(dest, cstr + beg, plen); - rb_str_cat(dest, &c, 1); - beg = i + 1; + memcmp(&cstr[i], s, rb_strlen_lit(s)) == 0 && \ + (i += rb_strlen_lit(s) - 1, 1)) + switch (c) { + case 'a': + ++i; + if (MATCH("pos;")) { + c = '\''; + } + else if (MATCH("mp;")) { + c = '&'; + } + else continue; + break; + case 'q': + ++i; + if (MATCH("uot;")) { + c = '"'; + } + else continue; + break; + case 'g': + ++i; + if (MATCH("t;")) { + c = '>'; + } + else continue; + break; + case 'l': + ++i; + if (MATCH("t;")) { + c = '<'; + } + else continue; + break; + case '#': + if (len - ++i >= 2 && ISDIGIT(cstr[i])) { + cc = ruby_scan_digits(&cstr[i], len-i, 10, &clen, &overflow); + } + else if ((cstr[i] == 'x' || cstr[i] == 'X') && len - ++i >= 2 && ISXDIGIT(cstr[i])) { + cc = ruby_scan_digits(&cstr[i], len-i, 16, &clen, &overflow); + } + else continue; + i += clen; + if (overflow || cc >= charlimit || cstr[i] != ';') continue; + if (!dest) { + dest = rb_str_buf_new(len); + } + rb_str_cat(dest, cstr + beg, plen); + if (charlimit > 256) { + rb_str_cat(dest, buf, rb_enc_mbcput((OnigCodePoint)cc, buf, enc)); + } + else { + c = (unsigned char)cc; + rb_str_cat(dest, &c, 1); + } + beg = i + 1; + continue; + default: + --i; + continue; + } + if (!dest) { + dest = rb_str_buf_new(len); + } + rb_str_cat(dest, cstr + beg, plen); + rb_str_cat(dest, &c, 1); + beg = i + 1; } if (dest) { - rb_str_cat(dest, cstr + beg, len - beg); - preserve_original_state(str, dest); - return dest; + rb_str_cat(dest, cstr + beg, len - beg); + preserve_original_state(str, dest); + return dest; } else { - return rb_str_dup(str); + return rb_str_dup(str); } } @@ -211,33 +211,33 @@ optimized_escape(VALUE str) cstr = RSTRING_PTR(str); for (i = 0; i < len; ++i) { - const unsigned char c = (unsigned char)cstr[i]; - if (!url_unreserved_char(c)) { - if (!dest) { - dest = rb_str_buf_new(len); - } + const unsigned char c = (unsigned char)cstr[i]; + if (!url_unreserved_char(c)) { + if (!dest) { + dest = rb_str_buf_new(len); + } - rb_str_cat(dest, cstr + beg, i - beg); - beg = i + 1; + rb_str_cat(dest, cstr + beg, i - beg); + beg = i + 1; - if (c == ' ') { - rb_str_cat_cstr(dest, "+"); - } - else { - buf[1] = upper_hexdigits[(c >> 4) & 0xf]; - buf[2] = upper_hexdigits[c & 0xf]; - rb_str_cat(dest, buf, 3); - } - } + if (c == ' ') { + rb_str_cat_cstr(dest, "+"); + } + else { + buf[1] = upper_hexdigits[(c >> 4) & 0xf]; + buf[2] = upper_hexdigits[c & 0xf]; + rb_str_cat(dest, buf, 3); + } + } } if (dest) { - rb_str_cat(dest, cstr + beg, len - beg); - preserve_original_state(str, dest); - return dest; + rb_str_cat(dest, cstr + beg, len - beg); + preserve_original_state(str, dest); + return dest; } else { - return rb_str_dup(str); + return rb_str_dup(str); } } @@ -254,52 +254,52 @@ optimized_unescape(VALUE str, VALUE encoding) cstr = RSTRING_PTR(str); for (i = 0; i < len; ++i) { - char buf[1]; - const char c = cstr[i]; - int clen = 0; - if (c == '%') { - if (i + 3 > len) break; - if (!ISXDIGIT(cstr[i+1])) continue; - if (!ISXDIGIT(cstr[i+2])) continue; - buf[0] = ((char_to_number(cstr[i+1]) << 4) - | char_to_number(cstr[i+2])); - clen = 2; - } - else if (c == '+') { - buf[0] = ' '; - } - else { - continue; - } + char buf[1]; + const char c = cstr[i]; + int clen = 0; + if (c == '%') { + if (i + 3 > len) break; + if (!ISXDIGIT(cstr[i+1])) continue; + if (!ISXDIGIT(cstr[i+2])) continue; + buf[0] = ((char_to_number(cstr[i+1]) << 4) + | char_to_number(cstr[i+2])); + clen = 2; + } + else if (c == '+') { + buf[0] = ' '; + } + else { + continue; + } - if (!dest) { - dest = rb_str_buf_new(len); - } + if (!dest) { + dest = rb_str_buf_new(len); + } - rb_str_cat(dest, cstr + beg, i - beg); - i += clen; - beg = i + 1; + rb_str_cat(dest, cstr + beg, i - beg); + i += clen; + beg = i + 1; - rb_str_cat(dest, buf, 1); + rb_str_cat(dest, buf, 1); } if (dest) { - rb_str_cat(dest, cstr + beg, len - beg); - preserve_original_state(str, dest); - cr = ENC_CODERANGE_UNKNOWN; + rb_str_cat(dest, cstr + beg, len - beg); + preserve_original_state(str, dest); + cr = ENC_CODERANGE_UNKNOWN; } else { - dest = rb_str_dup(str); - cr = ENC_CODERANGE(str); + dest = rb_str_dup(str); + cr = ENC_CODERANGE(str); } origenc = rb_enc_get_index(str); if (origenc != encidx) { - rb_enc_associate_index(dest, encidx); - if (!ENC_CODERANGE_CLEAN_P(rb_enc_str_coderange(dest))) { - rb_enc_associate_index(dest, origenc); - if (cr != ENC_CODERANGE_UNKNOWN) - ENC_CODERANGE_SET(dest, cr); - } + rb_enc_associate_index(dest, encidx); + if (!ENC_CODERANGE_CLEAN_P(rb_enc_str_coderange(dest))) { + rb_enc_associate_index(dest, origenc); + if (cr != ENC_CODERANGE_UNKNOWN) + ENC_CODERANGE_SET(dest, cr); + } } return dest; } @@ -317,10 +317,10 @@ cgiesc_escape_html(VALUE self, VALUE str) StringValue(str); if (rb_enc_str_asciicompat_p(str)) { - return optimized_escape_html(str); + return optimized_escape_html(str); } else { - return rb_call_super(1, &str); + return rb_call_super(1, &str); } } @@ -337,10 +337,10 @@ cgiesc_unescape_html(VALUE self, VALUE str) StringValue(str); if (rb_enc_str_asciicompat_p(str)) { - return optimized_unescape_html(str); + return optimized_unescape_html(str); } else { - return rb_call_super(1, &str); + return rb_call_super(1, &str); } } @@ -357,10 +357,10 @@ cgiesc_escape(VALUE self, VALUE str) StringValue(str); if (rb_enc_str_asciicompat_p(str)) { - return optimized_escape(str); + return optimized_escape(str); } else { - return rb_call_super(1, &str); + return rb_call_super(1, &str); } } @@ -368,7 +368,7 @@ static VALUE accept_charset(int argc, VALUE *argv, VALUE self) { if (argc > 0) - return argv[0]; + return argv[0]; return rb_cvar_get(CLASS_OF(self), id_accept_charset); } @@ -387,11 +387,11 @@ cgiesc_unescape(int argc, VALUE *argv, VALUE self) StringValue(str); if (rb_enc_str_asciicompat_p(str)) { - VALUE enc = accept_charset(argc-1, argv+1, self); - return optimized_unescape(str, enc); + VALUE enc = accept_charset(argc-1, argv+1, self); + return optimized_unescape(str, enc); } else { - return rb_call_super(argc, argv); + return rb_call_super(argc, argv); } } diff --git a/ext/coverage/coverage.c b/ext/coverage/coverage.c index 3dc2490d40..2f760c8eb6 100644 --- a/ext/coverage/coverage.c +++ b/ext/coverage/coverage.c @@ -44,27 +44,27 @@ rb_coverage_setup(int argc, VALUE *argv, VALUE klass) int mode; if (current_state != IDLE) { - rb_raise(rb_eRuntimeError, "coverage measurement is already setup"); + rb_raise(rb_eRuntimeError, "coverage measurement is already setup"); } rb_scan_args(argc, argv, "01", &opt); if (argc == 0) { - mode = 0; /* compatible mode */ + mode = 0; /* compatible mode */ } else if (opt == ID2SYM(rb_intern("all"))) { - mode = COVERAGE_TARGET_LINES | COVERAGE_TARGET_BRANCHES | COVERAGE_TARGET_METHODS; + mode = COVERAGE_TARGET_LINES | COVERAGE_TARGET_BRANCHES | COVERAGE_TARGET_METHODS; } else { - mode = 0; - opt = rb_convert_type(opt, T_HASH, "Hash", "to_hash"); + mode = 0; + opt = rb_convert_type(opt, T_HASH, "Hash", "to_hash"); - if (RTEST(rb_hash_lookup(opt, ID2SYM(rb_intern("lines"))))) - mode |= COVERAGE_TARGET_LINES; - if (RTEST(rb_hash_lookup(opt, ID2SYM(rb_intern("branches"))))) - mode |= COVERAGE_TARGET_BRANCHES; - if (RTEST(rb_hash_lookup(opt, ID2SYM(rb_intern("methods"))))) - mode |= COVERAGE_TARGET_METHODS; + if (RTEST(rb_hash_lookup(opt, ID2SYM(rb_intern("lines"))))) + mode |= COVERAGE_TARGET_LINES; + if (RTEST(rb_hash_lookup(opt, ID2SYM(rb_intern("branches"))))) + mode |= COVERAGE_TARGET_BRANCHES; + if (RTEST(rb_hash_lookup(opt, ID2SYM(rb_intern("methods"))))) + mode |= COVERAGE_TARGET_METHODS; if (RTEST(rb_hash_lookup(opt, ID2SYM(rb_intern("oneshot_lines"))))) { if (mode & COVERAGE_TARGET_LINES) rb_raise(rb_eRuntimeError, "cannot enable lines and oneshot_lines simultaneously"); @@ -77,20 +77,20 @@ rb_coverage_setup(int argc, VALUE *argv, VALUE klass) me2counter = rb_ident_hash_new(); } else { - me2counter = Qnil; + me2counter = Qnil; } coverages = rb_get_coverages(); if (!RTEST(coverages)) { - coverages = rb_hash_new(); - rb_obj_hide(coverages); - current_mode = mode; - if (mode == 0) mode = COVERAGE_TARGET_LINES; - rb_set_coverages(coverages, mode, me2counter); + coverages = rb_hash_new(); + rb_obj_hide(coverages); + current_mode = mode; + if (mode == 0) mode = COVERAGE_TARGET_LINES; + rb_set_coverages(coverages, mode, me2counter); current_state = SUSPENDED; } else if (current_mode != mode) { - rb_raise(rb_eRuntimeError, "cannot change the measuring target during coverage measurement"); + rb_raise(rb_eRuntimeError, "cannot change the measuring target during coverage measurement"); } @@ -112,10 +112,10 @@ VALUE rb_coverage_resume(VALUE klass) { if (current_state == IDLE) { - rb_raise(rb_eRuntimeError, "coverage measurement is not set up yet"); + rb_raise(rb_eRuntimeError, "coverage measurement is not set up yet"); } if (current_state == RUNNING) { - rb_raise(rb_eRuntimeError, "coverage measurement is already running"); + rb_raise(rb_eRuntimeError, "coverage measurement is already running"); } rb_resume_coverages(); current_state = RUNNING; @@ -218,45 +218,45 @@ method_coverage_i(void *vstart, void *vend, size_t stride, void *data) void *poisoned = asan_poisoned_object_p(v); asan_unpoison_object(v, false); - if (RB_TYPE_P(v, T_IMEMO) && imemo_type(v) == imemo_ment) { - const rb_method_entry_t *me = (rb_method_entry_t *) v; - VALUE path, first_lineno, first_column, last_lineno, last_column; - VALUE data[5], ncoverage, methods; - VALUE methods_id = ID2SYM(rb_intern("methods")); - VALUE klass; - const rb_method_entry_t *me2 = rb_resolve_me_location(me, data); - if (me != me2) continue; - klass = me->owner; - if (RB_TYPE_P(klass, T_ICLASS)) { - rb_bug("T_ICLASS"); - } - path = data[0]; - first_lineno = data[1]; - first_column = data[2]; - last_lineno = data[3]; - last_column = data[4]; - if (FIX2LONG(first_lineno) <= 0) continue; - ncoverage = rb_hash_aref(ncoverages, path); - if (NIL_P(ncoverage)) continue; - methods = rb_hash_aref(ncoverage, methods_id); + if (RB_TYPE_P(v, T_IMEMO) && imemo_type(v) == imemo_ment) { + const rb_method_entry_t *me = (rb_method_entry_t *) v; + VALUE path, first_lineno, first_column, last_lineno, last_column; + VALUE data[5], ncoverage, methods; + VALUE methods_id = ID2SYM(rb_intern("methods")); + VALUE klass; + const rb_method_entry_t *me2 = rb_resolve_me_location(me, data); + if (me != me2) continue; + klass = me->owner; + if (RB_TYPE_P(klass, T_ICLASS)) { + rb_bug("T_ICLASS"); + } + path = data[0]; + first_lineno = data[1]; + first_column = data[2]; + last_lineno = data[3]; + last_column = data[4]; + if (FIX2LONG(first_lineno) <= 0) continue; + ncoverage = rb_hash_aref(ncoverages, path); + if (NIL_P(ncoverage)) continue; + methods = rb_hash_aref(ncoverage, methods_id); - { - VALUE method_id = ID2SYM(me->def->original_id); - VALUE rcount = rb_hash_aref(me2counter, (VALUE) me); - VALUE key = rb_ary_new_from_args(6, klass, method_id, first_lineno, first_column, last_lineno, last_column); - VALUE rcount2 = rb_hash_aref(methods, key); + { + VALUE method_id = ID2SYM(me->def->original_id); + VALUE rcount = rb_hash_aref(me2counter, (VALUE) me); + VALUE key = rb_ary_new_from_args(6, klass, method_id, first_lineno, first_column, last_lineno, last_column); + VALUE rcount2 = rb_hash_aref(methods, key); - if (NIL_P(rcount)) rcount = LONG2FIX(0); - if (NIL_P(rcount2)) rcount2 = LONG2FIX(0); - if (!POSFIXABLE(FIX2LONG(rcount) + FIX2LONG(rcount2))) { - rcount = LONG2FIX(FIXNUM_MAX); - } - else { - rcount = LONG2FIX(FIX2LONG(rcount) + FIX2LONG(rcount2)); - } - rb_hash_aset(methods, key, rcount); - } - } + if (NIL_P(rcount)) rcount = LONG2FIX(0); + if (NIL_P(rcount2)) rcount2 = LONG2FIX(0); + if (!POSFIXABLE(FIX2LONG(rcount) + FIX2LONG(rcount2))) { + rcount = LONG2FIX(FIXNUM_MAX); + } + else { + rcount = LONG2FIX(FIX2LONG(rcount) + FIX2LONG(rcount2)); + } + rb_hash_aset(methods, key, rcount); + } + } if (poisoned) { asan_poison_object(v); @@ -272,32 +272,32 @@ coverage_peek_result_i(st_data_t key, st_data_t val, st_data_t h) VALUE coverage = (VALUE)val; VALUE coverages = (VALUE)h; if (current_mode == 0) { - /* compatible mode */ - VALUE lines = rb_ary_dup(RARRAY_AREF(coverage, COVERAGE_INDEX_LINES)); - rb_ary_freeze(lines); - coverage = lines; + /* compatible mode */ + VALUE lines = rb_ary_dup(RARRAY_AREF(coverage, COVERAGE_INDEX_LINES)); + rb_ary_freeze(lines); + coverage = lines; } else { - VALUE h = rb_hash_new(); + VALUE h = rb_hash_new(); - if (current_mode & COVERAGE_TARGET_LINES) { - VALUE lines = RARRAY_AREF(coverage, COVERAGE_INDEX_LINES); + if (current_mode & COVERAGE_TARGET_LINES) { + VALUE lines = RARRAY_AREF(coverage, COVERAGE_INDEX_LINES); const char *kw = (current_mode & COVERAGE_TARGET_ONESHOT_LINES) ? "oneshot_lines" : "lines"; - lines = rb_ary_dup(lines); - rb_ary_freeze(lines); + lines = rb_ary_dup(lines); + rb_ary_freeze(lines); rb_hash_aset(h, ID2SYM(rb_intern(kw)), lines); - } + } - if (current_mode & COVERAGE_TARGET_BRANCHES) { - VALUE branches = RARRAY_AREF(coverage, COVERAGE_INDEX_BRANCHES); - rb_hash_aset(h, ID2SYM(rb_intern("branches")), branch_coverage(branches)); - } + if (current_mode & COVERAGE_TARGET_BRANCHES) { + VALUE branches = RARRAY_AREF(coverage, COVERAGE_INDEX_BRANCHES); + rb_hash_aset(h, ID2SYM(rb_intern("branches")), branch_coverage(branches)); + } - if (current_mode & COVERAGE_TARGET_METHODS) { - rb_hash_aset(h, ID2SYM(rb_intern("methods")), rb_hash_new()); - } + if (current_mode & COVERAGE_TARGET_METHODS) { + rb_hash_aset(h, ID2SYM(rb_intern("methods")), rb_hash_new()); + } - coverage = h; + coverage = h; } rb_hash_aset(coverages, path, coverage); @@ -322,13 +322,13 @@ rb_coverage_peek_result(VALUE klass) VALUE coverages = rb_get_coverages(); VALUE ncoverages = rb_hash_new(); if (!RTEST(coverages)) { - rb_raise(rb_eRuntimeError, "coverage measurement is not enabled"); + rb_raise(rb_eRuntimeError, "coverage measurement is not enabled"); } OBJ_WB_UNPROTECT(coverages); st_foreach(RHASH_TBL_RAW(coverages), coverage_peek_result_i, ncoverages); if (current_mode & COVERAGE_TARGET_METHODS) { - rb_objspace_each_objects(method_coverage_i, &ncoverages); + rb_objspace_each_objects(method_coverage_i, &ncoverages); } rb_hash_freeze(ncoverages); @@ -354,7 +354,7 @@ VALUE rb_coverage_suspend(VALUE klass) { if (current_state != RUNNING) { - rb_raise(rb_eRuntimeError, "coverage measurement is not running"); + rb_raise(rb_eRuntimeError, "coverage measurement is not running"); } rb_suspend_coverages(); current_state = SUSPENDED; @@ -377,7 +377,7 @@ rb_coverage_result(int argc, VALUE *argv, VALUE klass) int stop = 1, clear = 1; if (current_state == IDLE) { - rb_raise(rb_eRuntimeError, "coverage measurement is not enabled"); + rb_raise(rb_eRuntimeError, "coverage measurement is not enabled"); } rb_scan_args(argc, argv, "01", &opt); diff --git a/ext/digest/bubblebabble/bubblebabble.c b/ext/digest/bubblebabble/bubblebabble.c index 6557e43c9d..358ab416b9 100644 --- a/ext/digest/bubblebabble/bubblebabble.c +++ b/ext/digest/bubblebabble/bubblebabble.c @@ -37,7 +37,7 @@ bubblebabble_str_new(VALUE str_digest) digest_len = RSTRING_LEN(str_digest); if ((LONG_MAX - 2) / 3 < (digest_len | 1)) { - rb_raise(rb_eRuntimeError, "digest string too long"); + rb_raise(rb_eRuntimeError, "digest string too long"); } str = rb_str_new(0, (digest_len | 1) * 3 + 2); diff --git a/ext/digest/digest.c b/ext/digest/digest.c index 83f4ee42fc..68837a674c 100644 --- a/ext/digest/digest.c +++ b/ext/digest/digest.c @@ -154,7 +154,7 @@ static void rb_digest_instance_method_unimpl(VALUE self, const char *method) { rb_raise(rb_eRuntimeError, "%s does not implement %s()", - rb_obj_classname(self), method); + rb_obj_classname(self), method); } /* @@ -383,8 +383,8 @@ rb_digest_instance_equal(VALUE self, VALUE other) StringValue(str2); if (RSTRING_LEN(str1) == RSTRING_LEN(str2) && - rb_str_cmp(str1, str2) == 0) { - return Qtrue; + rb_str_cmp(str1, str2) == 0) { + return Qtrue; } return Qfalse; } @@ -602,7 +602,7 @@ static inline void algo_init(const rb_digest_metadata_t *algo, void *pctx) { if (algo->init_func(pctx) != 1) { - rb_raise(rb_eRuntimeError, "Digest initialization failed."); + rb_raise(rb_eRuntimeError, "Digest initialization failed."); } } @@ -614,7 +614,7 @@ rb_digest_base_alloc(VALUE klass) void *pctx; if (klass == rb_cDigest_Base) { - rb_raise(rb_eNotImpError, "Digest::Base is an abstract class"); + rb_raise(rb_eNotImpError, "Digest::Base is an abstract class"); } algo = get_digest_base_metadata(klass); @@ -639,7 +639,7 @@ rb_digest_base_copy(VALUE copy, VALUE obj) algo = get_digest_obj_metadata(copy); if (algo != get_digest_obj_metadata(obj)) - rb_raise(rb_eTypeError, "different algorithms"); + rb_raise(rb_eTypeError, "different algorithms"); TypedData_Get_Struct(obj, void, &digest_type, pctx1); TypedData_Get_Struct(copy, void, &digest_type, pctx2); diff --git a/ext/digest/digest.h b/ext/digest/digest.h index 0d4f0e7cc2..8a4c5b7e4e 100644 --- a/ext/digest/digest.h +++ b/ext/digest/digest.h @@ -38,7 +38,7 @@ rb_digest_##name##_update(void *ctx, unsigned char *ptr, size_t size) \ const unsigned int stride = 16384; \ \ for (; size > stride; size -= stride, ptr += stride) { \ - name##_Update(ctx, ptr, stride); \ + name##_Update(ctx, ptr, stride); \ } \ if (size > 0) name##_Update(ctx, ptr, size); \ } diff --git a/ext/digest/md5/md5.c b/ext/digest/md5/md5.c index 3a7fe2cdad..52a787abdb 100644 --- a/ext/digest/md5/md5.c +++ b/ext/digest/md5/md5.c @@ -34,8 +34,8 @@ that follows (in reverse chronological order): 2000-07-03 lpd Patched to eliminate warnings about "constant is - unsigned in ANSI C, signed in traditional"; - made test program self-checking. + unsigned in ANSI C, signed in traditional"; + made test program self-checking. 1999-11-04 lpd Edited comments slightly for automatic TOC extraction. 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5). 1999-05-03 lpd Original version. @@ -64,32 +64,32 @@ int main(void) { static const char *const test[7*2] = { - "", "d41d8cd98f00b204e9800998ecf8427e", - "a", "0cc175b9c0f1b6a831c399e269772661", - "abc", "900150983cd24fb0d6963f7d28e17f72", - "message digest", "f96b697d7cb7938d525a2f31aaf161d0", - "abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b", - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", - "d174ab98d277d9f5a5611c2c9f419d9f", - "12345678901234567890123456789012345678901234567890123456789012345678901234567890", "57edf4a22be3c955ac49da2e2107b67a" + "", "d41d8cd98f00b204e9800998ecf8427e", + "a", "0cc175b9c0f1b6a831c399e269772661", + "abc", "900150983cd24fb0d6963f7d28e17f72", + "message digest", "f96b697d7cb7938d525a2f31aaf161d0", + "abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b", + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", + "d174ab98d277d9f5a5611c2c9f419d9f", + "12345678901234567890123456789012345678901234567890123456789012345678901234567890", "57edf4a22be3c955ac49da2e2107b67a" }; int i; for (i = 0; i < 7*2; i += 2) { - MD5_CTX state; - uint8_t digest[16]; - char hex_output[16*2 + 1]; - int di; + MD5_CTX state; + uint8_t digest[16]; + char hex_output[16*2 + 1]; + int di; - MD5_Init(&state); - MD5_Update(&state, (const uint8_t *)test[i], strlen(test[i])); - MD5_Final(digest, &state); - printf("MD5 (\"%s\") = ", test[i]); - for (di = 0; di < 16; ++di) - sprintf(hex_output + di * 2, "%02x", digest[di]); - puts(hex_output); - if (strcmp(hex_output, test[i + 1])) - printf("**** ERROR, should be: %s\n", test[i + 1]); + MD5_Init(&state); + MD5_Update(&state, (const uint8_t *)test[i], strlen(test[i])); + MD5_Final(digest, &state); + printf("MD5 (\"%s\") = ", test[i]); + for (di = 0; di < 16; ++di) + sprintf(hex_output + di * 2, "%02x", digest[di]); + puts(hex_output); + if (strcmp(hex_output, test[i + 1])) + printf("**** ERROR, should be: %s\n", test[i + 1]); } return 0; } @@ -106,18 +106,18 @@ main(void) { int i; for (i = 1; i <= 64; ++i) { - unsigned long v = (unsigned long)(4294967296.0 * fabs(sin((double)i))); + unsigned long v = (unsigned long)(4294967296.0 * fabs(sin((double)i))); - /* - * The following nonsense is only to avoid compiler warnings about - * "integer constant is unsigned in ANSI C, signed with -traditional". - */ - if (v >> 31) { - printf("#define T%d /* 0x%08lx */ (T_MASK ^ 0x%08lx)\n", i, - v, (unsigned long)(unsigned int)(~v)); - } else { - printf("#define T%d 0x%08lx\n", i, v); - } + /* + * The following nonsense is only to avoid compiler warnings about + * "integer constant is unsigned in ANSI C, signed with -traditional". + */ + if (v >> 31) { + printf("#define T%d /* 0x%08lx */ (T_MASK ^ 0x%08lx)\n", i, + v, (unsigned long)(unsigned int)(~v)); + } else { + printf("#define T%d 0x%08lx\n", i, v); + } } return 0; } @@ -199,8 +199,8 @@ static void md5_process(MD5_CTX *pms, const uint8_t *data /*[64]*/) { uint32_t - a = pms->state[0], b = pms->state[1], - c = pms->state[2], d = pms->state[3]; + a = pms->state[0], b = pms->state[1], + c = pms->state[2], d = pms->state[3]; uint32_t t; #ifdef WORDS_BIGENDIAN @@ -214,7 +214,7 @@ md5_process(MD5_CTX *pms, const uint8_t *data /*[64]*/) int i; for (i = 0; i < 16; ++i, xp += 4) - X[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24); + X[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24); #else @@ -226,12 +226,12 @@ md5_process(MD5_CTX *pms, const uint8_t *data /*[64]*/) const uint32_t *X; if (!(((uintptr_t)data) & 3)) { - /* data are properly aligned */ - X = (const uint32_t *)data; + /* data are properly aligned */ + X = (const uint32_t *)data; } else { - /* not aligned */ - memcpy(xbuf, data, 64); - X = xbuf; + /* not aligned */ + memcpy(xbuf, data, 64); + X = xbuf; } #endif @@ -370,55 +370,55 @@ MD5_Update(MD5_CTX *pms, const uint8_t *data, size_t nbytes) uint32_t nbits = (uint32_t)(nbytes << 3); if (nbytes == 0) - return; + return; /* Update the message length. */ pms->count[1] += nbytes >> 29; pms->count[0] += nbits; if (pms->count[0] < nbits) - pms->count[1]++; + pms->count[1]++; /* Process an initial partial block. */ if (offset) { - size_t copy = (offset + nbytes > 64 ? 64 - offset : nbytes); + size_t copy = (offset + nbytes > 64 ? 64 - offset : nbytes); - memcpy(pms->buffer + offset, p, copy); - if (offset + copy < 64) - return; - p += copy; - left -= copy; - md5_process(pms, pms->buffer); + memcpy(pms->buffer + offset, p, copy); + if (offset + copy < 64) + return; + p += copy; + left -= copy; + md5_process(pms, pms->buffer); } /* Process full blocks. */ for (; left >= 64; p += 64, left -= 64) - md5_process(pms, p); + md5_process(pms, p); /* Process a final partial block. */ if (left) - memcpy(pms->buffer, p, left); + memcpy(pms->buffer, p, left); } int MD5_Finish(MD5_CTX *pms, uint8_t *digest) { static const uint8_t pad[64] = { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; uint8_t data[8]; size_t i; /* Save the length before padding. */ for (i = 0; i < 8; ++i) - data[i] = (uint8_t)(pms->count[i >> 2] >> ((i & 3) << 3)); + data[i] = (uint8_t)(pms->count[i >> 2] >> ((i & 3) << 3)); /* Pad to 56 bytes mod 64. */ MD5_Update(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1); /* Append the length. */ MD5_Update(pms, data, 8); for (i = 0; i < 16; ++i) - digest[i] = (uint8_t)(pms->state[i >> 2] >> ((i & 3) << 3)); + digest[i] = (uint8_t)(pms->state[i >> 2] >> ((i & 3) << 3)); return 1; } diff --git a/ext/digest/md5/md5.h b/ext/digest/md5/md5.h index 1b3383c5ee..0b04f9fc4e 100644 --- a/ext/digest/md5/md5.h +++ b/ext/digest/md5/md5.h @@ -34,8 +34,8 @@ 1999-11-04 lpd Edited comments slightly for automatic TOC extraction. 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5); - added conditionalization for C++ compilation from Martin - Purschke . + added conditionalization for C++ compilation from Martin + Purschke . 1999-05-03 lpd Original version. */ diff --git a/ext/digest/rmd160/rmd160.c b/ext/digest/rmd160/rmd160.c index 058d004f3a..0ea78dcd64 100644 --- a/ext/digest/rmd160/rmd160.c +++ b/ext/digest/rmd160/rmd160.c @@ -128,17 +128,17 @@ int RMD160_Init(RMD160_CTX *context) { - _DIAGASSERT(context != NULL); + _DIAGASSERT(context != NULL); - /* ripemd-160 initialization constants */ - context->state[0] = 0x67452301U; - context->state[1] = 0xefcdab89U; - context->state[2] = 0x98badcfeU; - context->state[3] = 0x10325476U; - context->state[4] = 0xc3d2e1f0U; - context->length[0] = context->length[1] = 0; - context->buflen = 0; - return 1; + /* ripemd-160 initialization constants */ + context->state[0] = 0x67452301U; + context->state[1] = 0xefcdab89U; + context->state[2] = 0x98badcfeU; + context->state[3] = 0x10325476U; + context->state[4] = 0xc3d2e1f0U; + context->length[0] = context->length[1] = 0; + context->buflen = 0; + return 1; } /********************************************************************/ @@ -146,205 +146,205 @@ RMD160_Init(RMD160_CTX *context) void RMD160_Transform(uint32_t state[5], const uint32_t block[16]) { - uint32_t aa, bb, cc, dd, ee; - uint32_t aaa, bbb, ccc, ddd, eee; + uint32_t aa, bb, cc, dd, ee; + uint32_t aaa, bbb, ccc, ddd, eee; - _DIAGASSERT(state != NULL); - _DIAGASSERT(block != NULL); + _DIAGASSERT(state != NULL); + _DIAGASSERT(block != NULL); - aa = aaa = state[0]; - bb = bbb = state[1]; - cc = ccc = state[2]; - dd = ddd = state[3]; - ee = eee = state[4]; + aa = aaa = state[0]; + bb = bbb = state[1]; + cc = ccc = state[2]; + dd = ddd = state[3]; + ee = eee = state[4]; - /* round 1 */ - FF(aa, bb, cc, dd, ee, block[ 0], 11); - FF(ee, aa, bb, cc, dd, block[ 1], 14); - FF(dd, ee, aa, bb, cc, block[ 2], 15); - FF(cc, dd, ee, aa, bb, block[ 3], 12); - FF(bb, cc, dd, ee, aa, block[ 4], 5); - FF(aa, bb, cc, dd, ee, block[ 5], 8); - FF(ee, aa, bb, cc, dd, block[ 6], 7); - FF(dd, ee, aa, bb, cc, block[ 7], 9); - FF(cc, dd, ee, aa, bb, block[ 8], 11); - FF(bb, cc, dd, ee, aa, block[ 9], 13); - FF(aa, bb, cc, dd, ee, block[10], 14); - FF(ee, aa, bb, cc, dd, block[11], 15); - FF(dd, ee, aa, bb, cc, block[12], 6); - FF(cc, dd, ee, aa, bb, block[13], 7); - FF(bb, cc, dd, ee, aa, block[14], 9); - FF(aa, bb, cc, dd, ee, block[15], 8); + /* round 1 */ + FF(aa, bb, cc, dd, ee, block[ 0], 11); + FF(ee, aa, bb, cc, dd, block[ 1], 14); + FF(dd, ee, aa, bb, cc, block[ 2], 15); + FF(cc, dd, ee, aa, bb, block[ 3], 12); + FF(bb, cc, dd, ee, aa, block[ 4], 5); + FF(aa, bb, cc, dd, ee, block[ 5], 8); + FF(ee, aa, bb, cc, dd, block[ 6], 7); + FF(dd, ee, aa, bb, cc, block[ 7], 9); + FF(cc, dd, ee, aa, bb, block[ 8], 11); + FF(bb, cc, dd, ee, aa, block[ 9], 13); + FF(aa, bb, cc, dd, ee, block[10], 14); + FF(ee, aa, bb, cc, dd, block[11], 15); + FF(dd, ee, aa, bb, cc, block[12], 6); + FF(cc, dd, ee, aa, bb, block[13], 7); + FF(bb, cc, dd, ee, aa, block[14], 9); + FF(aa, bb, cc, dd, ee, block[15], 8); - /* round 2 */ - GG(ee, aa, bb, cc, dd, block[ 7], 7); - GG(dd, ee, aa, bb, cc, block[ 4], 6); - GG(cc, dd, ee, aa, bb, block[13], 8); - GG(bb, cc, dd, ee, aa, block[ 1], 13); - GG(aa, bb, cc, dd, ee, block[10], 11); - GG(ee, aa, bb, cc, dd, block[ 6], 9); - GG(dd, ee, aa, bb, cc, block[15], 7); - GG(cc, dd, ee, aa, bb, block[ 3], 15); - GG(bb, cc, dd, ee, aa, block[12], 7); - GG(aa, bb, cc, dd, ee, block[ 0], 12); - GG(ee, aa, bb, cc, dd, block[ 9], 15); - GG(dd, ee, aa, bb, cc, block[ 5], 9); - GG(cc, dd, ee, aa, bb, block[ 2], 11); - GG(bb, cc, dd, ee, aa, block[14], 7); - GG(aa, bb, cc, dd, ee, block[11], 13); - GG(ee, aa, bb, cc, dd, block[ 8], 12); + /* round 2 */ + GG(ee, aa, bb, cc, dd, block[ 7], 7); + GG(dd, ee, aa, bb, cc, block[ 4], 6); + GG(cc, dd, ee, aa, bb, block[13], 8); + GG(bb, cc, dd, ee, aa, block[ 1], 13); + GG(aa, bb, cc, dd, ee, block[10], 11); + GG(ee, aa, bb, cc, dd, block[ 6], 9); + GG(dd, ee, aa, bb, cc, block[15], 7); + GG(cc, dd, ee, aa, bb, block[ 3], 15); + GG(bb, cc, dd, ee, aa, block[12], 7); + GG(aa, bb, cc, dd, ee, block[ 0], 12); + GG(ee, aa, bb, cc, dd, block[ 9], 15); + GG(dd, ee, aa, bb, cc, block[ 5], 9); + GG(cc, dd, ee, aa, bb, block[ 2], 11); + GG(bb, cc, dd, ee, aa, block[14], 7); + GG(aa, bb, cc, dd, ee, block[11], 13); + GG(ee, aa, bb, cc, dd, block[ 8], 12); - /* round 3 */ - HH(dd, ee, aa, bb, cc, block[ 3], 11); - HH(cc, dd, ee, aa, bb, block[10], 13); - HH(bb, cc, dd, ee, aa, block[14], 6); - HH(aa, bb, cc, dd, ee, block[ 4], 7); - HH(ee, aa, bb, cc, dd, block[ 9], 14); - HH(dd, ee, aa, bb, cc, block[15], 9); - HH(cc, dd, ee, aa, bb, block[ 8], 13); - HH(bb, cc, dd, ee, aa, block[ 1], 15); - HH(aa, bb, cc, dd, ee, block[ 2], 14); - HH(ee, aa, bb, cc, dd, block[ 7], 8); - HH(dd, ee, aa, bb, cc, block[ 0], 13); - HH(cc, dd, ee, aa, bb, block[ 6], 6); - HH(bb, cc, dd, ee, aa, block[13], 5); - HH(aa, bb, cc, dd, ee, block[11], 12); - HH(ee, aa, bb, cc, dd, block[ 5], 7); - HH(dd, ee, aa, bb, cc, block[12], 5); + /* round 3 */ + HH(dd, ee, aa, bb, cc, block[ 3], 11); + HH(cc, dd, ee, aa, bb, block[10], 13); + HH(bb, cc, dd, ee, aa, block[14], 6); + HH(aa, bb, cc, dd, ee, block[ 4], 7); + HH(ee, aa, bb, cc, dd, block[ 9], 14); + HH(dd, ee, aa, bb, cc, block[15], 9); + HH(cc, dd, ee, aa, bb, block[ 8], 13); + HH(bb, cc, dd, ee, aa, block[ 1], 15); + HH(aa, bb, cc, dd, ee, block[ 2], 14); + HH(ee, aa, bb, cc, dd, block[ 7], 8); + HH(dd, ee, aa, bb, cc, block[ 0], 13); + HH(cc, dd, ee, aa, bb, block[ 6], 6); + HH(bb, cc, dd, ee, aa, block[13], 5); + HH(aa, bb, cc, dd, ee, block[11], 12); + HH(ee, aa, bb, cc, dd, block[ 5], 7); + HH(dd, ee, aa, bb, cc, block[12], 5); - /* round 4 */ - II(cc, dd, ee, aa, bb, block[ 1], 11); - II(bb, cc, dd, ee, aa, block[ 9], 12); - II(aa, bb, cc, dd, ee, block[11], 14); - II(ee, aa, bb, cc, dd, block[10], 15); - II(dd, ee, aa, bb, cc, block[ 0], 14); - II(cc, dd, ee, aa, bb, block[ 8], 15); - II(bb, cc, dd, ee, aa, block[12], 9); - II(aa, bb, cc, dd, ee, block[ 4], 8); - II(ee, aa, bb, cc, dd, block[13], 9); - II(dd, ee, aa, bb, cc, block[ 3], 14); - II(cc, dd, ee, aa, bb, block[ 7], 5); - II(bb, cc, dd, ee, aa, block[15], 6); - II(aa, bb, cc, dd, ee, block[14], 8); - II(ee, aa, bb, cc, dd, block[ 5], 6); - II(dd, ee, aa, bb, cc, block[ 6], 5); - II(cc, dd, ee, aa, bb, block[ 2], 12); + /* round 4 */ + II(cc, dd, ee, aa, bb, block[ 1], 11); + II(bb, cc, dd, ee, aa, block[ 9], 12); + II(aa, bb, cc, dd, ee, block[11], 14); + II(ee, aa, bb, cc, dd, block[10], 15); + II(dd, ee, aa, bb, cc, block[ 0], 14); + II(cc, dd, ee, aa, bb, block[ 8], 15); + II(bb, cc, dd, ee, aa, block[12], 9); + II(aa, bb, cc, dd, ee, block[ 4], 8); + II(ee, aa, bb, cc, dd, block[13], 9); + II(dd, ee, aa, bb, cc, block[ 3], 14); + II(cc, dd, ee, aa, bb, block[ 7], 5); + II(bb, cc, dd, ee, aa, block[15], 6); + II(aa, bb, cc, dd, ee, block[14], 8); + II(ee, aa, bb, cc, dd, block[ 5], 6); + II(dd, ee, aa, bb, cc, block[ 6], 5); + II(cc, dd, ee, aa, bb, block[ 2], 12); - /* round 5 */ - JJ(bb, cc, dd, ee, aa, block[ 4], 9); - JJ(aa, bb, cc, dd, ee, block[ 0], 15); - JJ(ee, aa, bb, cc, dd, block[ 5], 5); - JJ(dd, ee, aa, bb, cc, block[ 9], 11); - JJ(cc, dd, ee, aa, bb, block[ 7], 6); - JJ(bb, cc, dd, ee, aa, block[12], 8); - JJ(aa, bb, cc, dd, ee, block[ 2], 13); - JJ(ee, aa, bb, cc, dd, block[10], 12); - JJ(dd, ee, aa, bb, cc, block[14], 5); - JJ(cc, dd, ee, aa, bb, block[ 1], 12); - JJ(bb, cc, dd, ee, aa, block[ 3], 13); - JJ(aa, bb, cc, dd, ee, block[ 8], 14); - JJ(ee, aa, bb, cc, dd, block[11], 11); - JJ(dd, ee, aa, bb, cc, block[ 6], 8); - JJ(cc, dd, ee, aa, bb, block[15], 5); - JJ(bb, cc, dd, ee, aa, block[13], 6); + /* round 5 */ + JJ(bb, cc, dd, ee, aa, block[ 4], 9); + JJ(aa, bb, cc, dd, ee, block[ 0], 15); + JJ(ee, aa, bb, cc, dd, block[ 5], 5); + JJ(dd, ee, aa, bb, cc, block[ 9], 11); + JJ(cc, dd, ee, aa, bb, block[ 7], 6); + JJ(bb, cc, dd, ee, aa, block[12], 8); + JJ(aa, bb, cc, dd, ee, block[ 2], 13); + JJ(ee, aa, bb, cc, dd, block[10], 12); + JJ(dd, ee, aa, bb, cc, block[14], 5); + JJ(cc, dd, ee, aa, bb, block[ 1], 12); + JJ(bb, cc, dd, ee, aa, block[ 3], 13); + JJ(aa, bb, cc, dd, ee, block[ 8], 14); + JJ(ee, aa, bb, cc, dd, block[11], 11); + JJ(dd, ee, aa, bb, cc, block[ 6], 8); + JJ(cc, dd, ee, aa, bb, block[15], 5); + JJ(bb, cc, dd, ee, aa, block[13], 6); - /* parallel round 1 */ - JJJ(aaa, bbb, ccc, ddd, eee, block[ 5], 8); - JJJ(eee, aaa, bbb, ccc, ddd, block[14], 9); - JJJ(ddd, eee, aaa, bbb, ccc, block[ 7], 9); - JJJ(ccc, ddd, eee, aaa, bbb, block[ 0], 11); - JJJ(bbb, ccc, ddd, eee, aaa, block[ 9], 13); - JJJ(aaa, bbb, ccc, ddd, eee, block[ 2], 15); - JJJ(eee, aaa, bbb, ccc, ddd, block[11], 15); - JJJ(ddd, eee, aaa, bbb, ccc, block[ 4], 5); - JJJ(ccc, ddd, eee, aaa, bbb, block[13], 7); - JJJ(bbb, ccc, ddd, eee, aaa, block[ 6], 7); - JJJ(aaa, bbb, ccc, ddd, eee, block[15], 8); - JJJ(eee, aaa, bbb, ccc, ddd, block[ 8], 11); - JJJ(ddd, eee, aaa, bbb, ccc, block[ 1], 14); - JJJ(ccc, ddd, eee, aaa, bbb, block[10], 14); - JJJ(bbb, ccc, ddd, eee, aaa, block[ 3], 12); - JJJ(aaa, bbb, ccc, ddd, eee, block[12], 6); + /* parallel round 1 */ + JJJ(aaa, bbb, ccc, ddd, eee, block[ 5], 8); + JJJ(eee, aaa, bbb, ccc, ddd, block[14], 9); + JJJ(ddd, eee, aaa, bbb, ccc, block[ 7], 9); + JJJ(ccc, ddd, eee, aaa, bbb, block[ 0], 11); + JJJ(bbb, ccc, ddd, eee, aaa, block[ 9], 13); + JJJ(aaa, bbb, ccc, ddd, eee, block[ 2], 15); + JJJ(eee, aaa, bbb, ccc, ddd, block[11], 15); + JJJ(ddd, eee, aaa, bbb, ccc, block[ 4], 5); + JJJ(ccc, ddd, eee, aaa, bbb, block[13], 7); + JJJ(bbb, ccc, ddd, eee, aaa, block[ 6], 7); + JJJ(aaa, bbb, ccc, ddd, eee, block[15], 8); + JJJ(eee, aaa, bbb, ccc, ddd, block[ 8], 11); + JJJ(ddd, eee, aaa, bbb, ccc, block[ 1], 14); + JJJ(ccc, ddd, eee, aaa, bbb, block[10], 14); + JJJ(bbb, ccc, ddd, eee, aaa, block[ 3], 12); + JJJ(aaa, bbb, ccc, ddd, eee, block[12], 6); - /* parallel round 2 */ - III(eee, aaa, bbb, ccc, ddd, block[ 6], 9); - III(ddd, eee, aaa, bbb, ccc, block[11], 13); - III(ccc, ddd, eee, aaa, bbb, block[ 3], 15); - III(bbb, ccc, ddd, eee, aaa, block[ 7], 7); - III(aaa, bbb, ccc, ddd, eee, block[ 0], 12); - III(eee, aaa, bbb, ccc, ddd, block[13], 8); - III(ddd, eee, aaa, bbb, ccc, block[ 5], 9); - III(ccc, ddd, eee, aaa, bbb, block[10], 11); - III(bbb, ccc, ddd, eee, aaa, block[14], 7); - III(aaa, bbb, ccc, ddd, eee, block[15], 7); - III(eee, aaa, bbb, ccc, ddd, block[ 8], 12); - III(ddd, eee, aaa, bbb, ccc, block[12], 7); - III(ccc, ddd, eee, aaa, bbb, block[ 4], 6); - III(bbb, ccc, ddd, eee, aaa, block[ 9], 15); - III(aaa, bbb, ccc, ddd, eee, block[ 1], 13); - III(eee, aaa, bbb, ccc, ddd, block[ 2], 11); + /* parallel round 2 */ + III(eee, aaa, bbb, ccc, ddd, block[ 6], 9); + III(ddd, eee, aaa, bbb, ccc, block[11], 13); + III(ccc, ddd, eee, aaa, bbb, block[ 3], 15); + III(bbb, ccc, ddd, eee, aaa, block[ 7], 7); + III(aaa, bbb, ccc, ddd, eee, block[ 0], 12); + III(eee, aaa, bbb, ccc, ddd, block[13], 8); + III(ddd, eee, aaa, bbb, ccc, block[ 5], 9); + III(ccc, ddd, eee, aaa, bbb, block[10], 11); + III(bbb, ccc, ddd, eee, aaa, block[14], 7); + III(aaa, bbb, ccc, ddd, eee, block[15], 7); + III(eee, aaa, bbb, ccc, ddd, block[ 8], 12); + III(ddd, eee, aaa, bbb, ccc, block[12], 7); + III(ccc, ddd, eee, aaa, bbb, block[ 4], 6); + III(bbb, ccc, ddd, eee, aaa, block[ 9], 15); + III(aaa, bbb, ccc, ddd, eee, block[ 1], 13); + III(eee, aaa, bbb, ccc, ddd, block[ 2], 11); - /* parallel round 3 */ - HHH(ddd, eee, aaa, bbb, ccc, block[15], 9); - HHH(ccc, ddd, eee, aaa, bbb, block[ 5], 7); - HHH(bbb, ccc, ddd, eee, aaa, block[ 1], 15); - HHH(aaa, bbb, ccc, ddd, eee, block[ 3], 11); - HHH(eee, aaa, bbb, ccc, ddd, block[ 7], 8); - HHH(ddd, eee, aaa, bbb, ccc, block[14], 6); - HHH(ccc, ddd, eee, aaa, bbb, block[ 6], 6); - HHH(bbb, ccc, ddd, eee, aaa, block[ 9], 14); - HHH(aaa, bbb, ccc, ddd, eee, block[11], 12); - HHH(eee, aaa, bbb, ccc, ddd, block[ 8], 13); - HHH(ddd, eee, aaa, bbb, ccc, block[12], 5); - HHH(ccc, ddd, eee, aaa, bbb, block[ 2], 14); - HHH(bbb, ccc, ddd, eee, aaa, block[10], 13); - HHH(aaa, bbb, ccc, ddd, eee, block[ 0], 13); - HHH(eee, aaa, bbb, ccc, ddd, block[ 4], 7); - HHH(ddd, eee, aaa, bbb, ccc, block[13], 5); + /* parallel round 3 */ + HHH(ddd, eee, aaa, bbb, ccc, block[15], 9); + HHH(ccc, ddd, eee, aaa, bbb, block[ 5], 7); + HHH(bbb, ccc, ddd, eee, aaa, block[ 1], 15); + HHH(aaa, bbb, ccc, ddd, eee, block[ 3], 11); + HHH(eee, aaa, bbb, ccc, ddd, block[ 7], 8); + HHH(ddd, eee, aaa, bbb, ccc, block[14], 6); + HHH(ccc, ddd, eee, aaa, bbb, block[ 6], 6); + HHH(bbb, ccc, ddd, eee, aaa, block[ 9], 14); + HHH(aaa, bbb, ccc, ddd, eee, block[11], 12); + HHH(eee, aaa, bbb, ccc, ddd, block[ 8], 13); + HHH(ddd, eee, aaa, bbb, ccc, block[12], 5); + HHH(ccc, ddd, eee, aaa, bbb, block[ 2], 14); + HHH(bbb, ccc, ddd, eee, aaa, block[10], 13); + HHH(aaa, bbb, ccc, ddd, eee, block[ 0], 13); + HHH(eee, aaa, bbb, ccc, ddd, block[ 4], 7); + HHH(ddd, eee, aaa, bbb, ccc, block[13], 5); - /* parallel round 4 */ - GGG(ccc, ddd, eee, aaa, bbb, block[ 8], 15); - GGG(bbb, ccc, ddd, eee, aaa, block[ 6], 5); - GGG(aaa, bbb, ccc, ddd, eee, block[ 4], 8); - GGG(eee, aaa, bbb, ccc, ddd, block[ 1], 11); - GGG(ddd, eee, aaa, bbb, ccc, block[ 3], 14); - GGG(ccc, ddd, eee, aaa, bbb, block[11], 14); - GGG(bbb, ccc, ddd, eee, aaa, block[15], 6); - GGG(aaa, bbb, ccc, ddd, eee, block[ 0], 14); - GGG(eee, aaa, bbb, ccc, ddd, block[ 5], 6); - GGG(ddd, eee, aaa, bbb, ccc, block[12], 9); - GGG(ccc, ddd, eee, aaa, bbb, block[ 2], 12); - GGG(bbb, ccc, ddd, eee, aaa, block[13], 9); - GGG(aaa, bbb, ccc, ddd, eee, block[ 9], 12); - GGG(eee, aaa, bbb, ccc, ddd, block[ 7], 5); - GGG(ddd, eee, aaa, bbb, ccc, block[10], 15); - GGG(ccc, ddd, eee, aaa, bbb, block[14], 8); + /* parallel round 4 */ + GGG(ccc, ddd, eee, aaa, bbb, block[ 8], 15); + GGG(bbb, ccc, ddd, eee, aaa, block[ 6], 5); + GGG(aaa, bbb, ccc, ddd, eee, block[ 4], 8); + GGG(eee, aaa, bbb, ccc, ddd, block[ 1], 11); + GGG(ddd, eee, aaa, bbb, ccc, block[ 3], 14); + GGG(ccc, ddd, eee, aaa, bbb, block[11], 14); + GGG(bbb, ccc, ddd, eee, aaa, block[15], 6); + GGG(aaa, bbb, ccc, ddd, eee, block[ 0], 14); + GGG(eee, aaa, bbb, ccc, ddd, block[ 5], 6); + GGG(ddd, eee, aaa, bbb, ccc, block[12], 9); + GGG(ccc, ddd, eee, aaa, bbb, block[ 2], 12); + GGG(bbb, ccc, ddd, eee, aaa, block[13], 9); + GGG(aaa, bbb, ccc, ddd, eee, block[ 9], 12); + GGG(eee, aaa, bbb, ccc, ddd, block[ 7], 5); + GGG(ddd, eee, aaa, bbb, ccc, block[10], 15); + GGG(ccc, ddd, eee, aaa, bbb, block[14], 8); - /* parallel round 5 */ - FFF(bbb, ccc, ddd, eee, aaa, block[12] , 8); - FFF(aaa, bbb, ccc, ddd, eee, block[15] , 5); - FFF(eee, aaa, bbb, ccc, ddd, block[10] , 12); - FFF(ddd, eee, aaa, bbb, ccc, block[ 4] , 9); - FFF(ccc, ddd, eee, aaa, bbb, block[ 1] , 12); - FFF(bbb, ccc, ddd, eee, aaa, block[ 5] , 5); - FFF(aaa, bbb, ccc, ddd, eee, block[ 8] , 14); - FFF(eee, aaa, bbb, ccc, ddd, block[ 7] , 6); - FFF(ddd, eee, aaa, bbb, ccc, block[ 6] , 8); - FFF(ccc, ddd, eee, aaa, bbb, block[ 2] , 13); - FFF(bbb, ccc, ddd, eee, aaa, block[13] , 6); - FFF(aaa, bbb, ccc, ddd, eee, block[14] , 5); - FFF(eee, aaa, bbb, ccc, ddd, block[ 0] , 15); - FFF(ddd, eee, aaa, bbb, ccc, block[ 3] , 13); - FFF(ccc, ddd, eee, aaa, bbb, block[ 9] , 11); - FFF(bbb, ccc, ddd, eee, aaa, block[11] , 11); + /* parallel round 5 */ + FFF(bbb, ccc, ddd, eee, aaa, block[12] , 8); + FFF(aaa, bbb, ccc, ddd, eee, block[15] , 5); + FFF(eee, aaa, bbb, ccc, ddd, block[10] , 12); + FFF(ddd, eee, aaa, bbb, ccc, block[ 4] , 9); + FFF(ccc, ddd, eee, aaa, bbb, block[ 1] , 12); + FFF(bbb, ccc, ddd, eee, aaa, block[ 5] , 5); + FFF(aaa, bbb, ccc, ddd, eee, block[ 8] , 14); + FFF(eee, aaa, bbb, ccc, ddd, block[ 7] , 6); + FFF(ddd, eee, aaa, bbb, ccc, block[ 6] , 8); + FFF(ccc, ddd, eee, aaa, bbb, block[ 2] , 13); + FFF(bbb, ccc, ddd, eee, aaa, block[13] , 6); + FFF(aaa, bbb, ccc, ddd, eee, block[14] , 5); + FFF(eee, aaa, bbb, ccc, ddd, block[ 0] , 15); + FFF(ddd, eee, aaa, bbb, ccc, block[ 3] , 13); + FFF(ccc, ddd, eee, aaa, bbb, block[ 9] , 11); + FFF(bbb, ccc, ddd, eee, aaa, block[11] , 11); - /* combine results */ - ddd += cc + state[1]; /* final result for state[0] */ - state[1] = state[2] + dd + eee; - state[2] = state[3] + ee + aaa; - state[3] = state[4] + aa + bbb; - state[4] = state[0] + bb + ccc; - state[0] = ddd; + /* combine results */ + ddd += cc + state[1]; /* final result for state[0] */ + state[1] = state[2] + dd + eee; + state[2] = state[3] + ee + aaa; + state[3] = state[4] + aa + bbb; + state[4] = state[0] + bb + ccc; + state[0] = ddd; } /********************************************************************/ @@ -352,26 +352,26 @@ RMD160_Transform(uint32_t state[5], const uint32_t block[16]) void RMD160_Update(RMD160_CTX *context, const uint8_t *data, size_t nbytes) { - uint32_t X[16]; - uint32_t ofs = 0; - uint32_t i; + uint32_t X[16]; + uint32_t ofs = 0; + uint32_t i; #ifdef WORDS_BIGENDIAN - uint32_t j; + uint32_t j; #endif - _DIAGASSERT(context != NULL); - _DIAGASSERT(data != NULL); + _DIAGASSERT(context != NULL); + _DIAGASSERT(data != NULL); - /* update length[] */ + /* update length[] */ #if SIZEOF_SIZE_T * CHAR_BIT > 32 - context->length[1] += (uint32_t)((context->length[0] + nbytes) >> 32); + context->length[1] += (uint32_t)((context->length[0] + nbytes) >> 32); #else - if (context->length[0] + nbytes < context->length[0]) - context->length[1]++; /* overflow to msb of length */ + if (context->length[0] + nbytes < context->length[0]) + context->length[1]++; /* overflow to msb of length */ #endif - context->length[0] += (uint32_t)nbytes; + context->length[0] += (uint32_t)nbytes; - (void)memset(X, 0, sizeof(X)); + (void)memset(X, 0, sizeof(X)); if ( context->buflen + nbytes < 64 ) { @@ -416,48 +416,48 @@ RMD160_Update(RMD160_CTX *context, const uint8_t *data, size_t nbytes) int RMD160_Finish(RMD160_CTX *context, uint8_t digest[20]) { - uint32_t i; - uint32_t X[16]; + uint32_t i; + uint32_t X[16]; #ifdef WORDS_BIGENDIAN - uint32_t j; + uint32_t j; #endif - _DIAGASSERT(digest != NULL); - _DIAGASSERT(context != NULL); + _DIAGASSERT(digest != NULL); + _DIAGASSERT(context != NULL); - /* append the bit m_n == 1 */ - context->bbuffer[context->buflen] = (uint8_t)'\200'; + /* append the bit m_n == 1 */ + context->bbuffer[context->buflen] = (uint8_t)'\200'; - (void)memset(context->bbuffer + context->buflen + 1, 0, - 63 - context->buflen); + (void)memset(context->bbuffer + context->buflen + 1, 0, + 63 - context->buflen); #ifndef WORDS_BIGENDIAN - (void)memcpy(X, context->bbuffer, sizeof(X)); + (void)memcpy(X, context->bbuffer, sizeof(X)); #else - for (j=0; j < 16; j++) - X[j] = BYTES_TO_DWORD(context->bbuffer + (4 * j)); + for (j=0; j < 16; j++) + X[j] = BYTES_TO_DWORD(context->bbuffer + (4 * j)); #endif - if ((context->buflen) > 55) { - /* length goes to next block */ - RMD160_Transform(context->state, X); - (void)memset(X, 0, sizeof(X)); - } + if ((context->buflen) > 55) { + /* length goes to next block */ + RMD160_Transform(context->state, X); + (void)memset(X, 0, sizeof(X)); + } - /* append length in bits */ - X[14] = context->length[0] << 3; - X[15] = (context->length[0] >> 29) | - (context->length[1] << 3); - RMD160_Transform(context->state, X); + /* append length in bits */ + X[14] = context->length[0] << 3; + X[15] = (context->length[0] >> 29) | + (context->length[1] << 3); + RMD160_Transform(context->state, X); - if (digest != NULL) { - for (i = 0; i < 20; i += 4) { - /* extracts the 8 least significant bits. */ - digest[i] = context->state[i>>2]; - digest[i + 1] = (context->state[i>>2] >> 8); - digest[i + 2] = (context->state[i>>2] >> 16); - digest[i + 3] = (context->state[i>>2] >> 24); - } - } - return 1; + if (digest != NULL) { + for (i = 0; i < 20; i += 4) { + /* extracts the 8 least significant bits. */ + digest[i] = context->state[i>>2]; + digest[i + 1] = (context->state[i>>2] >> 8); + digest[i + 2] = (context->state[i>>2] >> 16); + digest[i + 3] = (context->state[i>>2] >> 24); + } + } + return 1; } /************************ end of file rmd160.c **********************/ diff --git a/ext/digest/rmd160/rmd160.h b/ext/digest/rmd160/rmd160.h index 6324709d96..617b262d90 100644 --- a/ext/digest/rmd160/rmd160.h +++ b/ext/digest/rmd160/rmd160.h @@ -29,10 +29,10 @@ #include "../defs.h" typedef struct { - uint32_t state[5]; /* state (ABCDE) */ - uint32_t length[2]; /* number of bits */ - uint8_t bbuffer[64]; /* overflow buffer */ - uint32_t buflen; /* number of chars in bbuffer */ + uint32_t state[5]; /* state (ABCDE) */ + uint32_t length[2]; /* number of bits */ + uint8_t bbuffer[64]; /* overflow buffer */ + uint32_t buflen; /* number of chars in bbuffer */ } RMD160_CTX; #ifdef RUBY diff --git a/ext/digest/sha1/sha1.c b/ext/digest/sha1/sha1.c index 5311227549..afe952f8ba 100644 --- a/ext/digest/sha1/sha1.c +++ b/ext/digest/sha1/sha1.c @@ -227,16 +227,16 @@ void SHA1_Update(SHA1_CTX *context, const uint8_t *data, size_t len) j = context->count[0]; if ((context->count[0] += len << 3) < j) - context->count[1] += (len>>29)+1; + context->count[1] += (len>>29)+1; j = (j >> 3) & 63; if ((j + len) > 63) { - (void)memcpy(&context->buffer[j], data, (i = 64-j)); - SHA1_Transform(context->state, context->buffer); - for ( ; i + 63 < len; i += 64) - SHA1_Transform(context->state, &data[i]); - j = 0; + (void)memcpy(&context->buffer[j], data, (i = 64-j)); + SHA1_Transform(context->state, context->buffer); + for ( ; i + 63 < len; i += 64) + SHA1_Transform(context->state, &data[i]); + j = 0; } else { - i = 0; + i = 0; } (void)memcpy(&context->buffer[j], &data[i], len - i); } @@ -254,18 +254,18 @@ int SHA1_Finish(SHA1_CTX* context, uint8_t digest[20]) _DIAGASSERT(context != 0); for (i = 0; i < 8; i++) { - finalcount[i] = (uint8_t)((context->count[(i >= 4 ? 0 : 1)] - >> ((3-(i & 3)) * 8) ) & 255); /* Endian independent */ + finalcount[i] = (uint8_t)((context->count[(i >= 4 ? 0 : 1)] + >> ((3-(i & 3)) * 8) ) & 255); /* Endian independent */ } SHA1_Update(context, (const uint8_t *)"\200", 1); while ((context->count[0] & 504) != 448) - SHA1_Update(context, (const uint8_t *)"\0", 1); + SHA1_Update(context, (const uint8_t *)"\0", 1); SHA1_Update(context, finalcount, 8); /* Should cause a SHA1_Transform() */ if (digest) { - for (i = 0; i < 20; i++) - digest[i] = (uint8_t) - ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255); + for (i = 0; i < 20; i++) + digest[i] = (uint8_t) + ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255); } return 1; } diff --git a/ext/digest/sha1/sha1.h b/ext/digest/sha1/sha1.h index 2accc46d46..e1d01b76ab 100644 --- a/ext/digest/sha1/sha1.h +++ b/ext/digest/sha1/sha1.h @@ -14,9 +14,9 @@ #include "../defs.h" typedef struct { - uint32_t state[5]; - uint32_t count[2]; - uint8_t buffer[64]; + uint32_t state[5]; + uint32_t count[2]; + uint8_t buffer[64]; } SHA1_CTX; #ifdef RUBY diff --git a/ext/digest/sha2/sha2.c b/ext/digest/sha2/sha2.c index 21d5acbe96..2a9dbd4fce 100644 --- a/ext/digest/sha2/sha2.c +++ b/ext/digest/sha2/sha2.c @@ -136,17 +136,17 @@ typedef u_int64_t sha2_word64; /* Exactly 8 bytes */ /*** ENDIAN REVERSAL MACROS *******************************************/ #if BYTE_ORDER == LITTLE_ENDIAN #define REVERSE32(w,x) { \ - sha2_word32 tmp = (w); \ - tmp = (tmp >> 16) | (tmp << 16); \ - (x) = ((tmp & (sha2_word32)0xff00ff00UL) >> 8) | ((tmp & (sha2_word32)0x00ff00ffUL) << 8); \ + sha2_word32 tmp = (w); \ + tmp = (tmp >> 16) | (tmp << 16); \ + (x) = ((tmp & (sha2_word32)0xff00ff00UL) >> 8) | ((tmp & (sha2_word32)0x00ff00ffUL) << 8); \ } #define REVERSE64(w,x) { \ - sha2_word64 tmp = (w); \ - tmp = (tmp >> 32) | (tmp << 32); \ - tmp = ((tmp & ULL(0xff00ff00ff00ff00)) >> 8) | \ - ((tmp & ULL(0x00ff00ff00ff00ff)) << 8); \ - (x) = ((tmp & ULL(0xffff0000ffff0000)) >> 16) | \ - ((tmp & ULL(0x0000ffff0000ffff)) << 16); \ + sha2_word64 tmp = (w); \ + tmp = (tmp >> 32) | (tmp << 32); \ + tmp = ((tmp & ULL(0xff00ff00ff00ff00)) >> 8) | \ + ((tmp & ULL(0x00ff00ff00ff00ff)) << 8); \ + (x) = ((tmp & ULL(0xffff0000ffff0000)) >> 16) | \ + ((tmp & ULL(0x0000ffff0000ffff)) << 16); \ } #endif /* BYTE_ORDER == LITTLE_ENDIAN */ @@ -156,10 +156,10 @@ typedef u_int64_t sha2_word64; /* Exactly 8 bytes */ * 64-bit words): */ #define ADDINC128(w,n) { \ - (w)[0] += (sha2_word64)(n); \ - if ((w)[0] < (n)) { \ - (w)[1]++; \ - } \ + (w)[0] += (sha2_word64)(n); \ + if ((w)[0] < (n)) { \ + (w)[1]++; \ + } \ } /* @@ -235,102 +235,102 @@ void SHA512_Transform(SHA512_CTX*, const sha2_word64*); /*** SHA-XYZ INITIAL HASH VALUES AND CONSTANTS ************************/ /* Hash constant words K for SHA-256: */ static const sha2_word32 K256[64] = { - 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, - 0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, - 0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL, - 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL, - 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, - 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, - 0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, - 0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL, - 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL, - 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL, - 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, - 0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, - 0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL, - 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL, - 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, - 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL + 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, + 0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, + 0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL, + 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL, + 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, + 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, + 0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, + 0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL, + 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL, + 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL, + 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, + 0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, + 0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL, + 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL, + 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, + 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL }; /* Initial hash value H for SHA-256: */ static const sha2_word32 sha256_initial_hash_value[8] = { - 0x6a09e667UL, - 0xbb67ae85UL, - 0x3c6ef372UL, - 0xa54ff53aUL, - 0x510e527fUL, - 0x9b05688cUL, - 0x1f83d9abUL, - 0x5be0cd19UL + 0x6a09e667UL, + 0xbb67ae85UL, + 0x3c6ef372UL, + 0xa54ff53aUL, + 0x510e527fUL, + 0x9b05688cUL, + 0x1f83d9abUL, + 0x5be0cd19UL }; /* Hash constant words K for SHA-384 and SHA-512: */ static const sha2_word64 K512[80] = { - ULL(0x428a2f98d728ae22), ULL(0x7137449123ef65cd), - ULL(0xb5c0fbcfec4d3b2f), ULL(0xe9b5dba58189dbbc), - ULL(0x3956c25bf348b538), ULL(0x59f111f1b605d019), - ULL(0x923f82a4af194f9b), ULL(0xab1c5ed5da6d8118), - ULL(0xd807aa98a3030242), ULL(0x12835b0145706fbe), - ULL(0x243185be4ee4b28c), ULL(0x550c7dc3d5ffb4e2), - ULL(0x72be5d74f27b896f), ULL(0x80deb1fe3b1696b1), - ULL(0x9bdc06a725c71235), ULL(0xc19bf174cf692694), - ULL(0xe49b69c19ef14ad2), ULL(0xefbe4786384f25e3), - ULL(0x0fc19dc68b8cd5b5), ULL(0x240ca1cc77ac9c65), - ULL(0x2de92c6f592b0275), ULL(0x4a7484aa6ea6e483), - ULL(0x5cb0a9dcbd41fbd4), ULL(0x76f988da831153b5), - ULL(0x983e5152ee66dfab), ULL(0xa831c66d2db43210), - ULL(0xb00327c898fb213f), ULL(0xbf597fc7beef0ee4), - ULL(0xc6e00bf33da88fc2), ULL(0xd5a79147930aa725), - ULL(0x06ca6351e003826f), ULL(0x142929670a0e6e70), - ULL(0x27b70a8546d22ffc), ULL(0x2e1b21385c26c926), - ULL(0x4d2c6dfc5ac42aed), ULL(0x53380d139d95b3df), - ULL(0x650a73548baf63de), ULL(0x766a0abb3c77b2a8), - ULL(0x81c2c92e47edaee6), ULL(0x92722c851482353b), - ULL(0xa2bfe8a14cf10364), ULL(0xa81a664bbc423001), - ULL(0xc24b8b70d0f89791), ULL(0xc76c51a30654be30), - ULL(0xd192e819d6ef5218), ULL(0xd69906245565a910), - ULL(0xf40e35855771202a), ULL(0x106aa07032bbd1b8), - ULL(0x19a4c116b8d2d0c8), ULL(0x1e376c085141ab53), - ULL(0x2748774cdf8eeb99), ULL(0x34b0bcb5e19b48a8), - ULL(0x391c0cb3c5c95a63), ULL(0x4ed8aa4ae3418acb), - ULL(0x5b9cca4f7763e373), ULL(0x682e6ff3d6b2b8a3), - ULL(0x748f82ee5defb2fc), ULL(0x78a5636f43172f60), - ULL(0x84c87814a1f0ab72), ULL(0x8cc702081a6439ec), - ULL(0x90befffa23631e28), ULL(0xa4506cebde82bde9), - ULL(0xbef9a3f7b2c67915), ULL(0xc67178f2e372532b), - ULL(0xca273eceea26619c), ULL(0xd186b8c721c0c207), - ULL(0xeada7dd6cde0eb1e), ULL(0xf57d4f7fee6ed178), - ULL(0x06f067aa72176fba), ULL(0x0a637dc5a2c898a6), - ULL(0x113f9804bef90dae), ULL(0x1b710b35131c471b), - ULL(0x28db77f523047d84), ULL(0x32caab7b40c72493), - ULL(0x3c9ebe0a15c9bebc), ULL(0x431d67c49c100d4c), - ULL(0x4cc5d4becb3e42b6), ULL(0x597f299cfc657e2a), - ULL(0x5fcb6fab3ad6faec), ULL(0x6c44198c4a475817) + ULL(0x428a2f98d728ae22), ULL(0x7137449123ef65cd), + ULL(0xb5c0fbcfec4d3b2f), ULL(0xe9b5dba58189dbbc), + ULL(0x3956c25bf348b538), ULL(0x59f111f1b605d019), + ULL(0x923f82a4af194f9b), ULL(0xab1c5ed5da6d8118), + ULL(0xd807aa98a3030242), ULL(0x12835b0145706fbe), + ULL(0x243185be4ee4b28c), ULL(0x550c7dc3d5ffb4e2), + ULL(0x72be5d74f27b896f), ULL(0x80deb1fe3b1696b1), + ULL(0x9bdc06a725c71235), ULL(0xc19bf174cf692694), + ULL(0xe49b69c19ef14ad2), ULL(0xefbe4786384f25e3), + ULL(0x0fc19dc68b8cd5b5), ULL(0x240ca1cc77ac9c65), + ULL(0x2de92c6f592b0275), ULL(0x4a7484aa6ea6e483), + ULL(0x5cb0a9dcbd41fbd4), ULL(0x76f988da831153b5), + ULL(0x983e5152ee66dfab), ULL(0xa831c66d2db43210), + ULL(0xb00327c898fb213f), ULL(0xbf597fc7beef0ee4), + ULL(0xc6e00bf33da88fc2), ULL(0xd5a79147930aa725), + ULL(0x06ca6351e003826f), ULL(0x142929670a0e6e70), + ULL(0x27b70a8546d22ffc), ULL(0x2e1b21385c26c926), + ULL(0x4d2c6dfc5ac42aed), ULL(0x53380d139d95b3df), + ULL(0x650a73548baf63de), ULL(0x766a0abb3c77b2a8), + ULL(0x81c2c92e47edaee6), ULL(0x92722c851482353b), + ULL(0xa2bfe8a14cf10364), ULL(0xa81a664bbc423001), + ULL(0xc24b8b70d0f89791), ULL(0xc76c51a30654be30), + ULL(0xd192e819d6ef5218), ULL(0xd69906245565a910), + ULL(0xf40e35855771202a), ULL(0x106aa07032bbd1b8), + ULL(0x19a4c116b8d2d0c8), ULL(0x1e376c085141ab53), + ULL(0x2748774cdf8eeb99), ULL(0x34b0bcb5e19b48a8), + ULL(0x391c0cb3c5c95a63), ULL(0x4ed8aa4ae3418acb), + ULL(0x5b9cca4f7763e373), ULL(0x682e6ff3d6b2b8a3), + ULL(0x748f82ee5defb2fc), ULL(0x78a5636f43172f60), + ULL(0x84c87814a1f0ab72), ULL(0x8cc702081a6439ec), + ULL(0x90befffa23631e28), ULL(0xa4506cebde82bde9), + ULL(0xbef9a3f7b2c67915), ULL(0xc67178f2e372532b), + ULL(0xca273eceea26619c), ULL(0xd186b8c721c0c207), + ULL(0xeada7dd6cde0eb1e), ULL(0xf57d4f7fee6ed178), + ULL(0x06f067aa72176fba), ULL(0x0a637dc5a2c898a6), + ULL(0x113f9804bef90dae), ULL(0x1b710b35131c471b), + ULL(0x28db77f523047d84), ULL(0x32caab7b40c72493), + ULL(0x3c9ebe0a15c9bebc), ULL(0x431d67c49c100d4c), + ULL(0x4cc5d4becb3e42b6), ULL(0x597f299cfc657e2a), + ULL(0x5fcb6fab3ad6faec), ULL(0x6c44198c4a475817) }; /* Initial hash value H for SHA-384 */ static const sha2_word64 sha384_initial_hash_value[8] = { - ULL(0xcbbb9d5dc1059ed8), - ULL(0x629a292a367cd507), - ULL(0x9159015a3070dd17), - ULL(0x152fecd8f70e5939), - ULL(0x67332667ffc00b31), - ULL(0x8eb44a8768581511), - ULL(0xdb0c2e0d64f98fa7), - ULL(0x47b5481dbefa4fa4) + ULL(0xcbbb9d5dc1059ed8), + ULL(0x629a292a367cd507), + ULL(0x9159015a3070dd17), + ULL(0x152fecd8f70e5939), + ULL(0x67332667ffc00b31), + ULL(0x8eb44a8768581511), + ULL(0xdb0c2e0d64f98fa7), + ULL(0x47b5481dbefa4fa4) }; /* Initial hash value H for SHA-512 */ static const sha2_word64 sha512_initial_hash_value[8] = { - ULL(0x6a09e667f3bcc908), - ULL(0xbb67ae8584caa73b), - ULL(0x3c6ef372fe94f82b), - ULL(0xa54ff53a5f1d36f1), - ULL(0x510e527fade682d1), - ULL(0x9b05688c2b3e6c1f), - ULL(0x1f83d9abfb41bd6b), - ULL(0x5be0cd19137e2179) + ULL(0x6a09e667f3bcc908), + ULL(0xbb67ae8584caa73b), + ULL(0x3c6ef372fe94f82b), + ULL(0xa54ff53a5f1d36f1), + ULL(0x510e527fade682d1), + ULL(0x9b05688c2b3e6c1f), + ULL(0x1f83d9abfb41bd6b), + ULL(0x5be0cd19137e2179) }; /* @@ -342,13 +342,13 @@ static const char *sha2_hex_digits = "0123456789abcdef"; /*** SHA-256: *********************************************************/ int SHA256_Init(SHA256_CTX* context) { - if (context == (SHA256_CTX*)0) { - return 0; - } - MEMCPY_BCOPY(context->state, sha256_initial_hash_value, SHA256_DIGEST_LENGTH); - MEMSET_BZERO(context->buffer, SHA256_BLOCK_LENGTH); - context->bitcount = 0; - return 1; + if (context == (SHA256_CTX*)0) { + return 0; + } + MEMCPY_BCOPY(context->state, sha256_initial_hash_value, SHA256_DIGEST_LENGTH); + MEMSET_BZERO(context->buffer, SHA256_BLOCK_LENGTH); + context->bitcount = 0; + return 1; } #ifdef SHA2_UNROLL_TRANSFORM @@ -358,328 +358,328 @@ int SHA256_Init(SHA256_CTX* context) { #if BYTE_ORDER == LITTLE_ENDIAN #define ROUND256_0_TO_15(a,b,c,d,e,f,g,h) \ - REVERSE32(*data++, W256[j]); \ - T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \ + REVERSE32(*data++, W256[j]); \ + T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \ K256[j] + W256[j]; \ - (d) += T1; \ - (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ - j++ + (d) += T1; \ + (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ + j++ #else /* BYTE_ORDER == LITTLE_ENDIAN */ #define ROUND256_0_TO_15(a,b,c,d,e,f,g,h) \ - T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \ - K256[j] + (W256[j] = *data++); \ - (d) += T1; \ - (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ - j++ + T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \ + K256[j] + (W256[j] = *data++); \ + (d) += T1; \ + (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ + j++ #endif /* BYTE_ORDER == LITTLE_ENDIAN */ #define ROUND256(a,b,c,d,e,f,g,h) \ - s0 = W256[(j+1)&0x0f]; \ - s0 = sigma0_256(s0); \ - s1 = W256[(j+14)&0x0f]; \ - s1 = sigma1_256(s1); \ - T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + K256[j] + \ - (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); \ - (d) += T1; \ - (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ - j++ + s0 = W256[(j+1)&0x0f]; \ + s0 = sigma0_256(s0); \ + s1 = W256[(j+14)&0x0f]; \ + s1 = sigma1_256(s1); \ + T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + K256[j] + \ + (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); \ + (d) += T1; \ + (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ + j++ void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) { - sha2_word32 a, b, c, d, e, f, g, h, s0, s1; - sha2_word32 T1, *W256; - int j; + sha2_word32 a, b, c, d, e, f, g, h, s0, s1; + sha2_word32 T1, *W256; + int j; - W256 = (sha2_word32*)context->buffer; + W256 = (sha2_word32*)context->buffer; - /* Initialize registers with the prev. intermediate value */ - a = context->state[0]; - b = context->state[1]; - c = context->state[2]; - d = context->state[3]; - e = context->state[4]; - f = context->state[5]; - g = context->state[6]; - h = context->state[7]; + /* Initialize registers with the prev. intermediate value */ + a = context->state[0]; + b = context->state[1]; + c = context->state[2]; + d = context->state[3]; + e = context->state[4]; + f = context->state[5]; + g = context->state[6]; + h = context->state[7]; - j = 0; - do { - /* Rounds 0 to 15 (unrolled): */ - ROUND256_0_TO_15(a,b,c,d,e,f,g,h); - ROUND256_0_TO_15(h,a,b,c,d,e,f,g); - ROUND256_0_TO_15(g,h,a,b,c,d,e,f); - ROUND256_0_TO_15(f,g,h,a,b,c,d,e); - ROUND256_0_TO_15(e,f,g,h,a,b,c,d); - ROUND256_0_TO_15(d,e,f,g,h,a,b,c); - ROUND256_0_TO_15(c,d,e,f,g,h,a,b); - ROUND256_0_TO_15(b,c,d,e,f,g,h,a); - } while (j < 16); + j = 0; + do { + /* Rounds 0 to 15 (unrolled): */ + ROUND256_0_TO_15(a,b,c,d,e,f,g,h); + ROUND256_0_TO_15(h,a,b,c,d,e,f,g); + ROUND256_0_TO_15(g,h,a,b,c,d,e,f); + ROUND256_0_TO_15(f,g,h,a,b,c,d,e); + ROUND256_0_TO_15(e,f,g,h,a,b,c,d); + ROUND256_0_TO_15(d,e,f,g,h,a,b,c); + ROUND256_0_TO_15(c,d,e,f,g,h,a,b); + ROUND256_0_TO_15(b,c,d,e,f,g,h,a); + } while (j < 16); - /* Now for the remaining rounds to 64: */ - do { - ROUND256(a,b,c,d,e,f,g,h); - ROUND256(h,a,b,c,d,e,f,g); - ROUND256(g,h,a,b,c,d,e,f); - ROUND256(f,g,h,a,b,c,d,e); - ROUND256(e,f,g,h,a,b,c,d); - ROUND256(d,e,f,g,h,a,b,c); - ROUND256(c,d,e,f,g,h,a,b); - ROUND256(b,c,d,e,f,g,h,a); - } while (j < 64); + /* Now for the remaining rounds to 64: */ + do { + ROUND256(a,b,c,d,e,f,g,h); + ROUND256(h,a,b,c,d,e,f,g); + ROUND256(g,h,a,b,c,d,e,f); + ROUND256(f,g,h,a,b,c,d,e); + ROUND256(e,f,g,h,a,b,c,d); + ROUND256(d,e,f,g,h,a,b,c); + ROUND256(c,d,e,f,g,h,a,b); + ROUND256(b,c,d,e,f,g,h,a); + } while (j < 64); - /* Compute the current intermediate hash value */ - context->state[0] += a; - context->state[1] += b; - context->state[2] += c; - context->state[3] += d; - context->state[4] += e; - context->state[5] += f; - context->state[6] += g; - context->state[7] += h; + /* Compute the current intermediate hash value */ + context->state[0] += a; + context->state[1] += b; + context->state[2] += c; + context->state[3] += d; + context->state[4] += e; + context->state[5] += f; + context->state[6] += g; + context->state[7] += h; - /* Clean up */ - a = b = c = d = e = f = g = h = T1 = 0; + /* Clean up */ + a = b = c = d = e = f = g = h = T1 = 0; } #else /* SHA2_UNROLL_TRANSFORM */ void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) { - sha2_word32 a, b, c, d, e, f, g, h, s0, s1; - sha2_word32 T1, T2, *W256; - int j; + sha2_word32 a, b, c, d, e, f, g, h, s0, s1; + sha2_word32 T1, T2, *W256; + int j; - W256 = (sha2_word32*)context->buffer; + W256 = (sha2_word32*)context->buffer; - /* Initialize registers with the prev. intermediate value */ - a = context->state[0]; - b = context->state[1]; - c = context->state[2]; - d = context->state[3]; - e = context->state[4]; - f = context->state[5]; - g = context->state[6]; - h = context->state[7]; + /* Initialize registers with the prev. intermediate value */ + a = context->state[0]; + b = context->state[1]; + c = context->state[2]; + d = context->state[3]; + e = context->state[4]; + f = context->state[5]; + g = context->state[6]; + h = context->state[7]; - j = 0; - do { + j = 0; + do { #if BYTE_ORDER == LITTLE_ENDIAN - /* Copy data while converting to host byte order */ - REVERSE32(*data++,W256[j]); - /* Apply the SHA-256 compression function to update a..h */ - T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + W256[j]; + /* Copy data while converting to host byte order */ + REVERSE32(*data++,W256[j]); + /* Apply the SHA-256 compression function to update a..h */ + T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + W256[j]; #else /* BYTE_ORDER == LITTLE_ENDIAN */ - /* Apply the SHA-256 compression function to update a..h with copy */ - T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + (W256[j] = *data++); + /* Apply the SHA-256 compression function to update a..h with copy */ + T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + (W256[j] = *data++); #endif /* BYTE_ORDER == LITTLE_ENDIAN */ - T2 = Sigma0_256(a) + Maj(a, b, c); - h = g; - g = f; - f = e; - e = d + T1; - d = c; - c = b; - b = a; - a = T1 + T2; + T2 = Sigma0_256(a) + Maj(a, b, c); + h = g; + g = f; + f = e; + e = d + T1; + d = c; + c = b; + b = a; + a = T1 + T2; - j++; - } while (j < 16); + j++; + } while (j < 16); - do { - /* Part of the message block expansion: */ - s0 = W256[(j+1)&0x0f]; - s0 = sigma0_256(s0); - s1 = W256[(j+14)&0x0f]; - s1 = sigma1_256(s1); + do { + /* Part of the message block expansion: */ + s0 = W256[(j+1)&0x0f]; + s0 = sigma0_256(s0); + s1 = W256[(j+14)&0x0f]; + s1 = sigma1_256(s1); - /* Apply the SHA-256 compression function to update a..h */ - T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + - (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); - T2 = Sigma0_256(a) + Maj(a, b, c); - h = g; - g = f; - f = e; - e = d + T1; - d = c; - c = b; - b = a; - a = T1 + T2; + /* Apply the SHA-256 compression function to update a..h */ + T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + + (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); + T2 = Sigma0_256(a) + Maj(a, b, c); + h = g; + g = f; + f = e; + e = d + T1; + d = c; + c = b; + b = a; + a = T1 + T2; - j++; - } while (j < 64); + j++; + } while (j < 64); - /* Compute the current intermediate hash value */ - context->state[0] += a; - context->state[1] += b; - context->state[2] += c; - context->state[3] += d; - context->state[4] += e; - context->state[5] += f; - context->state[6] += g; - context->state[7] += h; + /* Compute the current intermediate hash value */ + context->state[0] += a; + context->state[1] += b; + context->state[2] += c; + context->state[3] += d; + context->state[4] += e; + context->state[5] += f; + context->state[6] += g; + context->state[7] += h; - /* Clean up */ - a = b = c = d = e = f = g = h = T1 = T2 = 0; + /* Clean up */ + a = b = c = d = e = f = g = h = T1 = T2 = 0; } #endif /* SHA2_UNROLL_TRANSFORM */ void SHA256_Update(SHA256_CTX* context, const sha2_byte *data, size_t len) { - unsigned int freespace, usedspace; + unsigned int freespace, usedspace; - if (len == 0) { - /* Calling with no data is valid - we do nothing */ - return; - } + if (len == 0) { + /* Calling with no data is valid - we do nothing */ + return; + } - /* Sanity check: */ - assert(context != (SHA256_CTX*)0 && data != (sha2_byte*)0); + /* Sanity check: */ + assert(context != (SHA256_CTX*)0 && data != (sha2_byte*)0); - usedspace = (unsigned int)((context->bitcount >> 3) % SHA256_BLOCK_LENGTH); - if (usedspace > 0) { - /* Calculate how much free space is available in the buffer */ - freespace = SHA256_BLOCK_LENGTH - usedspace; + usedspace = (unsigned int)((context->bitcount >> 3) % SHA256_BLOCK_LENGTH); + if (usedspace > 0) { + /* Calculate how much free space is available in the buffer */ + freespace = SHA256_BLOCK_LENGTH - usedspace; - if (len >= freespace) { - /* Fill the buffer completely and process it */ - MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace); - context->bitcount += freespace << 3; - len -= freespace; - data += freespace; - SHA256_Transform(context, (sha2_word32*)context->buffer); - } else { - /* The buffer is not yet full */ - MEMCPY_BCOPY(&context->buffer[usedspace], data, len); - context->bitcount += len << 3; - /* Clean up: */ - usedspace = freespace = 0; - return; - } - } - while (len >= SHA256_BLOCK_LENGTH) { - /* Process as many complete blocks as we can */ - MEMCPY_BCOPY(context->buffer, data, SHA256_BLOCK_LENGTH); - SHA256_Transform(context, (sha2_word32*)context->buffer); - context->bitcount += SHA256_BLOCK_LENGTH << 3; - len -= SHA256_BLOCK_LENGTH; - data += SHA256_BLOCK_LENGTH; - } - if (len > 0) { - /* There's left-overs, so save 'em */ - MEMCPY_BCOPY(context->buffer, data, len); - context->bitcount += len << 3; - } - /* Clean up: */ - usedspace = freespace = 0; + if (len >= freespace) { + /* Fill the buffer completely and process it */ + MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace); + context->bitcount += freespace << 3; + len -= freespace; + data += freespace; + SHA256_Transform(context, (sha2_word32*)context->buffer); + } else { + /* The buffer is not yet full */ + MEMCPY_BCOPY(&context->buffer[usedspace], data, len); + context->bitcount += len << 3; + /* Clean up: */ + usedspace = freespace = 0; + return; + } + } + while (len >= SHA256_BLOCK_LENGTH) { + /* Process as many complete blocks as we can */ + MEMCPY_BCOPY(context->buffer, data, SHA256_BLOCK_LENGTH); + SHA256_Transform(context, (sha2_word32*)context->buffer); + context->bitcount += SHA256_BLOCK_LENGTH << 3; + len -= SHA256_BLOCK_LENGTH; + data += SHA256_BLOCK_LENGTH; + } + if (len > 0) { + /* There's left-overs, so save 'em */ + MEMCPY_BCOPY(context->buffer, data, len); + context->bitcount += len << 3; + } + /* Clean up: */ + usedspace = freespace = 0; } int SHA256_Final(sha2_byte digest[SHA256_DIGEST_LENGTH], SHA256_CTX* context) { - sha2_word32 *d = (sha2_word32*)digest; - unsigned int usedspace; + sha2_word32 *d = (sha2_word32*)digest; + unsigned int usedspace; - /* Sanity check: */ - assert(context != (SHA256_CTX*)0); + /* Sanity check: */ + assert(context != (SHA256_CTX*)0); - /* If no digest buffer is passed, we don't bother doing this: */ - if (digest != (sha2_byte*)0) { - usedspace = (unsigned int)((context->bitcount >> 3) % SHA256_BLOCK_LENGTH); + /* If no digest buffer is passed, we don't bother doing this: */ + if (digest != (sha2_byte*)0) { + usedspace = (unsigned int)((context->bitcount >> 3) % SHA256_BLOCK_LENGTH); #if BYTE_ORDER == LITTLE_ENDIAN - /* Convert FROM host byte order */ - REVERSE64(context->bitcount,context->bitcount); + /* Convert FROM host byte order */ + REVERSE64(context->bitcount,context->bitcount); #endif - if (usedspace > 0) { - /* Begin padding with a 1 bit: */ - context->buffer[usedspace++] = 0x80; + if (usedspace > 0) { + /* Begin padding with a 1 bit: */ + context->buffer[usedspace++] = 0x80; - if (usedspace <= SHA256_SHORT_BLOCK_LENGTH) { - /* Set-up for the last transform: */ - MEMSET_BZERO(&context->buffer[usedspace], SHA256_SHORT_BLOCK_LENGTH - usedspace); - } else { - if (usedspace < SHA256_BLOCK_LENGTH) { - MEMSET_BZERO(&context->buffer[usedspace], SHA256_BLOCK_LENGTH - usedspace); - } - /* Do second-to-last transform: */ - SHA256_Transform(context, (sha2_word32*)context->buffer); + if (usedspace <= SHA256_SHORT_BLOCK_LENGTH) { + /* Set-up for the last transform: */ + MEMSET_BZERO(&context->buffer[usedspace], SHA256_SHORT_BLOCK_LENGTH - usedspace); + } else { + if (usedspace < SHA256_BLOCK_LENGTH) { + MEMSET_BZERO(&context->buffer[usedspace], SHA256_BLOCK_LENGTH - usedspace); + } + /* Do second-to-last transform: */ + SHA256_Transform(context, (sha2_word32*)context->buffer); - /* And set-up for the last transform: */ - MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH); - } - } else { - /* Set-up for the last transform: */ - MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH); + /* And set-up for the last transform: */ + MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH); + } + } else { + /* Set-up for the last transform: */ + MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH); - /* Begin padding with a 1 bit: */ - *context->buffer = 0x80; - } - /* Set the bit count: */ - MEMCPY_BCOPY(&context->buffer[SHA256_SHORT_BLOCK_LENGTH], &context->bitcount, - sizeof(sha2_word64)); + /* Begin padding with a 1 bit: */ + *context->buffer = 0x80; + } + /* Set the bit count: */ + MEMCPY_BCOPY(&context->buffer[SHA256_SHORT_BLOCK_LENGTH], &context->bitcount, + sizeof(sha2_word64)); - /* Final transform: */ - SHA256_Transform(context, (sha2_word32*)context->buffer); + /* Final transform: */ + SHA256_Transform(context, (sha2_word32*)context->buffer); #if BYTE_ORDER == LITTLE_ENDIAN - { - /* Convert TO host byte order */ - int j; - for (j = 0; j < 8; j++) { - REVERSE32(context->state[j],context->state[j]); - *d++ = context->state[j]; - } - } + { + /* Convert TO host byte order */ + int j; + for (j = 0; j < 8; j++) { + REVERSE32(context->state[j],context->state[j]); + *d++ = context->state[j]; + } + } #else - MEMCPY_BCOPY(d, context->state, SHA256_DIGEST_LENGTH); + MEMCPY_BCOPY(d, context->state, SHA256_DIGEST_LENGTH); #endif - } + } - /* Clean up state data: */ - MEMSET_BZERO(context, sizeof(*context)); - usedspace = 0; - return 1; + /* Clean up state data: */ + MEMSET_BZERO(context, sizeof(*context)); + usedspace = 0; + return 1; } char *SHA256_End(SHA256_CTX* context, char buffer[SHA256_DIGEST_STRING_LENGTH]) { - sha2_byte digest[SHA256_DIGEST_LENGTH], *d = digest; - int i; + sha2_byte digest[SHA256_DIGEST_LENGTH], *d = digest; + int i; - /* Sanity check: */ - assert(context != (SHA256_CTX*)0); + /* Sanity check: */ + assert(context != (SHA256_CTX*)0); - if (buffer != (char*)0) { - SHA256_Final(digest, context); - for (i = 0; i < SHA256_DIGEST_LENGTH; i++) { - *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4]; - *buffer++ = sha2_hex_digits[*d & 0x0f]; - d++; - } - *buffer = (char)0; - } else { - MEMSET_BZERO(context, sizeof(*context)); - } - MEMSET_BZERO(digest, SHA256_DIGEST_LENGTH); - return buffer; + if (buffer != (char*)0) { + SHA256_Final(digest, context); + for (i = 0; i < SHA256_DIGEST_LENGTH; i++) { + *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4]; + *buffer++ = sha2_hex_digits[*d & 0x0f]; + d++; + } + *buffer = (char)0; + } else { + MEMSET_BZERO(context, sizeof(*context)); + } + MEMSET_BZERO(digest, SHA256_DIGEST_LENGTH); + return buffer; } char* SHA256_Data(const sha2_byte* data, size_t len, char digest[SHA256_DIGEST_STRING_LENGTH]) { - SHA256_CTX context; + SHA256_CTX context; - SHA256_Init(&context); - SHA256_Update(&context, data, len); - return SHA256_End(&context, digest); + SHA256_Init(&context); + SHA256_Update(&context, data, len); + return SHA256_End(&context, digest); } /*** SHA-512: *********************************************************/ int SHA512_Init(SHA512_CTX* context) { - if (context == (SHA512_CTX*)0) { - return 0; - } - MEMCPY_BCOPY(context->state, sha512_initial_hash_value, SHA512_DIGEST_LENGTH); - MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH); - context->bitcount[0] = context->bitcount[1] = 0; - return 1; + if (context == (SHA512_CTX*)0) { + return 0; + } + MEMCPY_BCOPY(context->state, sha512_initial_hash_value, SHA512_DIGEST_LENGTH); + MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH); + context->bitcount[0] = context->bitcount[1] = 0; + return 1; } #ifdef SHA2_UNROLL_TRANSFORM @@ -688,394 +688,394 @@ int SHA512_Init(SHA512_CTX* context) { #if BYTE_ORDER == LITTLE_ENDIAN #define ROUND512_0_TO_15(a,b,c,d,e,f,g,h) \ - REVERSE64(*data++, W512[j]); \ - T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \ + REVERSE64(*data++, W512[j]); \ + T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \ K512[j] + W512[j]; \ - (d) += T1, \ - (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)), \ - j++ + (d) += T1, \ + (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)), \ + j++ #else /* BYTE_ORDER == LITTLE_ENDIAN */ #define ROUND512_0_TO_15(a,b,c,d,e,f,g,h) \ - T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \ + T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \ K512[j] + (W512[j] = *data++); \ - (d) += T1; \ - (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \ - j++ + (d) += T1; \ + (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \ + j++ #endif /* BYTE_ORDER == LITTLE_ENDIAN */ #define ROUND512(a,b,c,d,e,f,g,h) \ - s0 = W512[(j+1)&0x0f]; \ - s0 = sigma0_512(s0); \ - s1 = W512[(j+14)&0x0f]; \ - s1 = sigma1_512(s1); \ - T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + K512[j] + \ + s0 = W512[(j+1)&0x0f]; \ + s0 = sigma0_512(s0); \ + s1 = W512[(j+14)&0x0f]; \ + s1 = sigma1_512(s1); \ + T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + K512[j] + \ (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0); \ - (d) += T1; \ - (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \ - j++ + (d) += T1; \ + (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \ + j++ void SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) { - sha2_word64 a, b, c, d, e, f, g, h, s0, s1; - sha2_word64 T1, *W512 = (sha2_word64*)context->buffer; - int j; + sha2_word64 a, b, c, d, e, f, g, h, s0, s1; + sha2_word64 T1, *W512 = (sha2_word64*)context->buffer; + int j; - /* Initialize registers with the prev. intermediate value */ - a = context->state[0]; - b = context->state[1]; - c = context->state[2]; - d = context->state[3]; - e = context->state[4]; - f = context->state[5]; - g = context->state[6]; - h = context->state[7]; + /* Initialize registers with the prev. intermediate value */ + a = context->state[0]; + b = context->state[1]; + c = context->state[2]; + d = context->state[3]; + e = context->state[4]; + f = context->state[5]; + g = context->state[6]; + h = context->state[7]; - j = 0; - do { - ROUND512_0_TO_15(a,b,c,d,e,f,g,h); - ROUND512_0_TO_15(h,a,b,c,d,e,f,g); - ROUND512_0_TO_15(g,h,a,b,c,d,e,f); - ROUND512_0_TO_15(f,g,h,a,b,c,d,e); - ROUND512_0_TO_15(e,f,g,h,a,b,c,d); - ROUND512_0_TO_15(d,e,f,g,h,a,b,c); - ROUND512_0_TO_15(c,d,e,f,g,h,a,b); - ROUND512_0_TO_15(b,c,d,e,f,g,h,a); - } while (j < 16); + j = 0; + do { + ROUND512_0_TO_15(a,b,c,d,e,f,g,h); + ROUND512_0_TO_15(h,a,b,c,d,e,f,g); + ROUND512_0_TO_15(g,h,a,b,c,d,e,f); + ROUND512_0_TO_15(f,g,h,a,b,c,d,e); + ROUND512_0_TO_15(e,f,g,h,a,b,c,d); + ROUND512_0_TO_15(d,e,f,g,h,a,b,c); + ROUND512_0_TO_15(c,d,e,f,g,h,a,b); + ROUND512_0_TO_15(b,c,d,e,f,g,h,a); + } while (j < 16); - /* Now for the remaining rounds up to 79: */ - do { - ROUND512(a,b,c,d,e,f,g,h); - ROUND512(h,a,b,c,d,e,f,g); - ROUND512(g,h,a,b,c,d,e,f); - ROUND512(f,g,h,a,b,c,d,e); - ROUND512(e,f,g,h,a,b,c,d); - ROUND512(d,e,f,g,h,a,b,c); - ROUND512(c,d,e,f,g,h,a,b); - ROUND512(b,c,d,e,f,g,h,a); - } while (j < 80); + /* Now for the remaining rounds up to 79: */ + do { + ROUND512(a,b,c,d,e,f,g,h); + ROUND512(h,a,b,c,d,e,f,g); + ROUND512(g,h,a,b,c,d,e,f); + ROUND512(f,g,h,a,b,c,d,e); + ROUND512(e,f,g,h,a,b,c,d); + ROUND512(d,e,f,g,h,a,b,c); + ROUND512(c,d,e,f,g,h,a,b); + ROUND512(b,c,d,e,f,g,h,a); + } while (j < 80); - /* Compute the current intermediate hash value */ - context->state[0] += a; - context->state[1] += b; - context->state[2] += c; - context->state[3] += d; - context->state[4] += e; - context->state[5] += f; - context->state[6] += g; - context->state[7] += h; + /* Compute the current intermediate hash value */ + context->state[0] += a; + context->state[1] += b; + context->state[2] += c; + context->state[3] += d; + context->state[4] += e; + context->state[5] += f; + context->state[6] += g; + context->state[7] += h; - /* Clean up */ - a = b = c = d = e = f = g = h = T1 = 0; + /* Clean up */ + a = b = c = d = e = f = g = h = T1 = 0; } #else /* SHA2_UNROLL_TRANSFORM */ void SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) { - sha2_word64 a, b, c, d, e, f, g, h, s0, s1; - sha2_word64 T1, T2, *W512 = (sha2_word64*)context->buffer; - int j; + sha2_word64 a, b, c, d, e, f, g, h, s0, s1; + sha2_word64 T1, T2, *W512 = (sha2_word64*)context->buffer; + int j; - /* Initialize registers with the prev. intermediate value */ - a = context->state[0]; - b = context->state[1]; - c = context->state[2]; - d = context->state[3]; - e = context->state[4]; - f = context->state[5]; - g = context->state[6]; - h = context->state[7]; + /* Initialize registers with the prev. intermediate value */ + a = context->state[0]; + b = context->state[1]; + c = context->state[2]; + d = context->state[3]; + e = context->state[4]; + f = context->state[5]; + g = context->state[6]; + h = context->state[7]; - j = 0; - do { + j = 0; + do { #if BYTE_ORDER == LITTLE_ENDIAN - /* Convert TO host byte order */ - REVERSE64(*data++, W512[j]); - /* Apply the SHA-512 compression function to update a..h */ - T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + W512[j]; + /* Convert TO host byte order */ + REVERSE64(*data++, W512[j]); + /* Apply the SHA-512 compression function to update a..h */ + T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + W512[j]; #else /* BYTE_ORDER == LITTLE_ENDIAN */ - /* Apply the SHA-512 compression function to update a..h with copy */ - T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + (W512[j] = *data++); + /* Apply the SHA-512 compression function to update a..h with copy */ + T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + (W512[j] = *data++); #endif /* BYTE_ORDER == LITTLE_ENDIAN */ - T2 = Sigma0_512(a) + Maj(a, b, c); - h = g; - g = f; - f = e; - e = d + T1; - d = c; - c = b; - b = a; - a = T1 + T2; + T2 = Sigma0_512(a) + Maj(a, b, c); + h = g; + g = f; + f = e; + e = d + T1; + d = c; + c = b; + b = a; + a = T1 + T2; - j++; - } while (j < 16); + j++; + } while (j < 16); - do { - /* Part of the message block expansion: */ - s0 = W512[(j+1)&0x0f]; - s0 = sigma0_512(s0); - s1 = W512[(j+14)&0x0f]; - s1 = sigma1_512(s1); + do { + /* Part of the message block expansion: */ + s0 = W512[(j+1)&0x0f]; + s0 = sigma0_512(s0); + s1 = W512[(j+14)&0x0f]; + s1 = sigma1_512(s1); - /* Apply the SHA-512 compression function to update a..h */ - T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + - (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0); - T2 = Sigma0_512(a) + Maj(a, b, c); - h = g; - g = f; - f = e; - e = d + T1; - d = c; - c = b; - b = a; - a = T1 + T2; + /* Apply the SHA-512 compression function to update a..h */ + T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + + (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0); + T2 = Sigma0_512(a) + Maj(a, b, c); + h = g; + g = f; + f = e; + e = d + T1; + d = c; + c = b; + b = a; + a = T1 + T2; - j++; - } while (j < 80); + j++; + } while (j < 80); - /* Compute the current intermediate hash value */ - context->state[0] += a; - context->state[1] += b; - context->state[2] += c; - context->state[3] += d; - context->state[4] += e; - context->state[5] += f; - context->state[6] += g; - context->state[7] += h; + /* Compute the current intermediate hash value */ + context->state[0] += a; + context->state[1] += b; + context->state[2] += c; + context->state[3] += d; + context->state[4] += e; + context->state[5] += f; + context->state[6] += g; + context->state[7] += h; - /* Clean up */ - a = b = c = d = e = f = g = h = T1 = T2 = 0; + /* Clean up */ + a = b = c = d = e = f = g = h = T1 = T2 = 0; } #endif /* SHA2_UNROLL_TRANSFORM */ void SHA512_Update(SHA512_CTX* context, const sha2_byte *data, size_t len) { - unsigned int freespace, usedspace; + unsigned int freespace, usedspace; - if (len == 0) { - /* Calling with no data is valid - we do nothing */ - return; - } + if (len == 0) { + /* Calling with no data is valid - we do nothing */ + return; + } - /* Sanity check: */ - assert(context != (SHA512_CTX*)0 && data != (sha2_byte*)0); + /* Sanity check: */ + assert(context != (SHA512_CTX*)0 && data != (sha2_byte*)0); - usedspace = (unsigned int)((context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH); - if (usedspace > 0) { - /* Calculate how much free space is available in the buffer */ - freespace = SHA512_BLOCK_LENGTH - usedspace; + usedspace = (unsigned int)((context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH); + if (usedspace > 0) { + /* Calculate how much free space is available in the buffer */ + freespace = SHA512_BLOCK_LENGTH - usedspace; - if (len >= freespace) { - /* Fill the buffer completely and process it */ - MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace); - ADDINC128(context->bitcount, freespace << 3); - len -= freespace; - data += freespace; - SHA512_Transform(context, (sha2_word64*)context->buffer); - } else { - /* The buffer is not yet full */ - MEMCPY_BCOPY(&context->buffer[usedspace], data, len); - ADDINC128(context->bitcount, len << 3); - /* Clean up: */ - usedspace = freespace = 0; - return; - } - } - while (len >= SHA512_BLOCK_LENGTH) { - /* Process as many complete blocks as we can */ - MEMCPY_BCOPY(context->buffer, data, SHA512_BLOCK_LENGTH); - SHA512_Transform(context, (sha2_word64*)context->buffer); - ADDINC128(context->bitcount, SHA512_BLOCK_LENGTH << 3); - len -= SHA512_BLOCK_LENGTH; - data += SHA512_BLOCK_LENGTH; - } - if (len > 0) { - /* There's left-overs, so save 'em */ - MEMCPY_BCOPY(context->buffer, data, len); - ADDINC128(context->bitcount, len << 3); - } - /* Clean up: */ - usedspace = freespace = 0; + if (len >= freespace) { + /* Fill the buffer completely and process it */ + MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace); + ADDINC128(context->bitcount, freespace << 3); + len -= freespace; + data += freespace; + SHA512_Transform(context, (sha2_word64*)context->buffer); + } else { + /* The buffer is not yet full */ + MEMCPY_BCOPY(&context->buffer[usedspace], data, len); + ADDINC128(context->bitcount, len << 3); + /* Clean up: */ + usedspace = freespace = 0; + return; + } + } + while (len >= SHA512_BLOCK_LENGTH) { + /* Process as many complete blocks as we can */ + MEMCPY_BCOPY(context->buffer, data, SHA512_BLOCK_LENGTH); + SHA512_Transform(context, (sha2_word64*)context->buffer); + ADDINC128(context->bitcount, SHA512_BLOCK_LENGTH << 3); + len -= SHA512_BLOCK_LENGTH; + data += SHA512_BLOCK_LENGTH; + } + if (len > 0) { + /* There's left-overs, so save 'em */ + MEMCPY_BCOPY(context->buffer, data, len); + ADDINC128(context->bitcount, len << 3); + } + /* Clean up: */ + usedspace = freespace = 0; } void SHA512_Last(SHA512_CTX* context) { - unsigned int usedspace; + unsigned int usedspace; - usedspace = (unsigned int)((context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH); + usedspace = (unsigned int)((context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH); #if BYTE_ORDER == LITTLE_ENDIAN - /* Convert FROM host byte order */ - REVERSE64(context->bitcount[0],context->bitcount[0]); - REVERSE64(context->bitcount[1],context->bitcount[1]); + /* Convert FROM host byte order */ + REVERSE64(context->bitcount[0],context->bitcount[0]); + REVERSE64(context->bitcount[1],context->bitcount[1]); #endif - if (usedspace > 0) { - /* Begin padding with a 1 bit: */ - context->buffer[usedspace++] = 0x80; + if (usedspace > 0) { + /* Begin padding with a 1 bit: */ + context->buffer[usedspace++] = 0x80; - if (usedspace <= SHA512_SHORT_BLOCK_LENGTH) { - /* Set-up for the last transform: */ - MEMSET_BZERO(&context->buffer[usedspace], SHA512_SHORT_BLOCK_LENGTH - usedspace); - } else { - if (usedspace < SHA512_BLOCK_LENGTH) { - MEMSET_BZERO(&context->buffer[usedspace], SHA512_BLOCK_LENGTH - usedspace); - } - /* Do second-to-last transform: */ - SHA512_Transform(context, (sha2_word64*)context->buffer); + if (usedspace <= SHA512_SHORT_BLOCK_LENGTH) { + /* Set-up for the last transform: */ + MEMSET_BZERO(&context->buffer[usedspace], SHA512_SHORT_BLOCK_LENGTH - usedspace); + } else { + if (usedspace < SHA512_BLOCK_LENGTH) { + MEMSET_BZERO(&context->buffer[usedspace], SHA512_BLOCK_LENGTH - usedspace); + } + /* Do second-to-last transform: */ + SHA512_Transform(context, (sha2_word64*)context->buffer); - /* And set-up for the last transform: */ - MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH - 2); - } - } else { - /* Prepare for final transform: */ - MEMSET_BZERO(context->buffer, SHA512_SHORT_BLOCK_LENGTH); + /* And set-up for the last transform: */ + MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH - 2); + } + } else { + /* Prepare for final transform: */ + MEMSET_BZERO(context->buffer, SHA512_SHORT_BLOCK_LENGTH); - /* Begin padding with a 1 bit: */ - *context->buffer = 0x80; - } - /* Store the length of input data (in bits): */ - MEMCPY_BCOPY(&context->buffer[SHA512_SHORT_BLOCK_LENGTH], &context->bitcount[1], - sizeof(sha2_word64)); - MEMCPY_BCOPY(&context->buffer[SHA512_SHORT_BLOCK_LENGTH+8], &context->bitcount[0], - sizeof(sha2_word64)); + /* Begin padding with a 1 bit: */ + *context->buffer = 0x80; + } + /* Store the length of input data (in bits): */ + MEMCPY_BCOPY(&context->buffer[SHA512_SHORT_BLOCK_LENGTH], &context->bitcount[1], + sizeof(sha2_word64)); + MEMCPY_BCOPY(&context->buffer[SHA512_SHORT_BLOCK_LENGTH+8], &context->bitcount[0], + sizeof(sha2_word64)); - /* Final transform: */ - SHA512_Transform(context, (sha2_word64*)context->buffer); + /* Final transform: */ + SHA512_Transform(context, (sha2_word64*)context->buffer); } int SHA512_Final(sha2_byte digest[SHA512_DIGEST_LENGTH], SHA512_CTX* context) { - sha2_word64 *d = (sha2_word64*)digest; + sha2_word64 *d = (sha2_word64*)digest; - /* Sanity check: */ - assert(context != (SHA512_CTX*)0); + /* Sanity check: */ + assert(context != (SHA512_CTX*)0); - /* If no digest buffer is passed, we don't bother doing this: */ - if (digest != (sha2_byte*)0) { - SHA512_Last(context); + /* If no digest buffer is passed, we don't bother doing this: */ + if (digest != (sha2_byte*)0) { + SHA512_Last(context); - /* Save the hash data for output: */ + /* Save the hash data for output: */ #if BYTE_ORDER == LITTLE_ENDIAN - { - /* Convert TO host byte order */ - int j; - for (j = 0; j < 8; j++) { - REVERSE64(context->state[j],context->state[j]); - *d++ = context->state[j]; - } - } + { + /* Convert TO host byte order */ + int j; + for (j = 0; j < 8; j++) { + REVERSE64(context->state[j],context->state[j]); + *d++ = context->state[j]; + } + } #else - MEMCPY_BCOPY(d, context->state, SHA512_DIGEST_LENGTH); + MEMCPY_BCOPY(d, context->state, SHA512_DIGEST_LENGTH); #endif - } + } - /* Zero out state data */ - MEMSET_BZERO(context, sizeof(*context)); - return 1; + /* Zero out state data */ + MEMSET_BZERO(context, sizeof(*context)); + return 1; } char *SHA512_End(SHA512_CTX* context, char buffer[SHA512_DIGEST_STRING_LENGTH]) { - sha2_byte digest[SHA512_DIGEST_LENGTH], *d = digest; - int i; + sha2_byte digest[SHA512_DIGEST_LENGTH], *d = digest; + int i; - /* Sanity check: */ - assert(context != (SHA512_CTX*)0); + /* Sanity check: */ + assert(context != (SHA512_CTX*)0); - if (buffer != (char*)0) { - SHA512_Final(digest, context); - for (i = 0; i < SHA512_DIGEST_LENGTH; i++) { - *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4]; - *buffer++ = sha2_hex_digits[*d & 0x0f]; - d++; - } - *buffer = (char)0; - } else { - MEMSET_BZERO(context, sizeof(*context)); - } - MEMSET_BZERO(digest, SHA512_DIGEST_LENGTH); - return buffer; + if (buffer != (char*)0) { + SHA512_Final(digest, context); + for (i = 0; i < SHA512_DIGEST_LENGTH; i++) { + *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4]; + *buffer++ = sha2_hex_digits[*d & 0x0f]; + d++; + } + *buffer = (char)0; + } else { + MEMSET_BZERO(context, sizeof(*context)); + } + MEMSET_BZERO(digest, SHA512_DIGEST_LENGTH); + return buffer; } char* SHA512_Data(const sha2_byte* data, size_t len, char digest[SHA512_DIGEST_STRING_LENGTH]) { - SHA512_CTX context; + SHA512_CTX context; - SHA512_Init(&context); - SHA512_Update(&context, data, len); - return SHA512_End(&context, digest); + SHA512_Init(&context); + SHA512_Update(&context, data, len); + return SHA512_End(&context, digest); } /*** SHA-384: *********************************************************/ int SHA384_Init(SHA384_CTX* context) { - if (context == (SHA384_CTX*)0) { - return 0; - } - MEMCPY_BCOPY(context->state, sha384_initial_hash_value, SHA512_DIGEST_LENGTH); - MEMSET_BZERO(context->buffer, SHA384_BLOCK_LENGTH); - context->bitcount[0] = context->bitcount[1] = 0; - return 1; + if (context == (SHA384_CTX*)0) { + return 0; + } + MEMCPY_BCOPY(context->state, sha384_initial_hash_value, SHA512_DIGEST_LENGTH); + MEMSET_BZERO(context->buffer, SHA384_BLOCK_LENGTH); + context->bitcount[0] = context->bitcount[1] = 0; + return 1; } void SHA384_Update(SHA384_CTX* context, const sha2_byte* data, size_t len) { - SHA512_Update((SHA512_CTX*)context, data, len); + SHA512_Update((SHA512_CTX*)context, data, len); } int SHA384_Final(sha2_byte digest[SHA384_DIGEST_LENGTH], SHA384_CTX* context) { - sha2_word64 *d = (sha2_word64*)digest; + sha2_word64 *d = (sha2_word64*)digest; - /* Sanity check: */ - assert(context != (SHA384_CTX*)0); + /* Sanity check: */ + assert(context != (SHA384_CTX*)0); - /* If no digest buffer is passed, we don't bother doing this: */ - if (digest != (sha2_byte*)0) { - SHA512_Last((SHA512_CTX*)context); + /* If no digest buffer is passed, we don't bother doing this: */ + if (digest != (sha2_byte*)0) { + SHA512_Last((SHA512_CTX*)context); - /* Save the hash data for output: */ + /* Save the hash data for output: */ #if BYTE_ORDER == LITTLE_ENDIAN - { - /* Convert TO host byte order */ - int j; - for (j = 0; j < 6; j++) { - REVERSE64(context->state[j],context->state[j]); - *d++ = context->state[j]; - } - } + { + /* Convert TO host byte order */ + int j; + for (j = 0; j < 6; j++) { + REVERSE64(context->state[j],context->state[j]); + *d++ = context->state[j]; + } + } #else - MEMCPY_BCOPY(d, context->state, SHA384_DIGEST_LENGTH); + MEMCPY_BCOPY(d, context->state, SHA384_DIGEST_LENGTH); #endif - } + } - /* Zero out state data */ - MEMSET_BZERO(context, sizeof(*context)); - return 1; + /* Zero out state data */ + MEMSET_BZERO(context, sizeof(*context)); + return 1; } char *SHA384_End(SHA384_CTX* context, char buffer[SHA384_DIGEST_STRING_LENGTH]) { - sha2_byte digest[SHA384_DIGEST_LENGTH], *d = digest; - int i; + sha2_byte digest[SHA384_DIGEST_LENGTH], *d = digest; + int i; - /* Sanity check: */ - assert(context != (SHA384_CTX*)0); + /* Sanity check: */ + assert(context != (SHA384_CTX*)0); - if (buffer != (char*)0) { - SHA384_Final(digest, context); - for (i = 0; i < SHA384_DIGEST_LENGTH; i++) { - *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4]; - *buffer++ = sha2_hex_digits[*d & 0x0f]; - d++; - } - *buffer = (char)0; - } else { - MEMSET_BZERO(context, sizeof(*context)); - } - MEMSET_BZERO(digest, SHA384_DIGEST_LENGTH); - return buffer; + if (buffer != (char*)0) { + SHA384_Final(digest, context); + for (i = 0; i < SHA384_DIGEST_LENGTH; i++) { + *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4]; + *buffer++ = sha2_hex_digits[*d & 0x0f]; + d++; + } + *buffer = (char)0; + } else { + MEMSET_BZERO(context, sizeof(*context)); + } + MEMSET_BZERO(digest, SHA384_DIGEST_LENGTH); + return buffer; } char* SHA384_Data(const sha2_byte* data, size_t len, char digest[SHA384_DIGEST_STRING_LENGTH]) { - SHA384_CTX context; + SHA384_CTX context; - SHA384_Init(&context); - SHA384_Update(&context, data, len); - return SHA384_End(&context, digest); + SHA384_Init(&context); + SHA384_Update(&context, data, len); + return SHA384_End(&context, digest); } diff --git a/ext/digest/sha2/sha2.h b/ext/digest/sha2/sha2.h index e58f15ae12..c2a29b99ad 100644 --- a/ext/digest/sha2/sha2.h +++ b/ext/digest/sha2/sha2.h @@ -120,14 +120,14 @@ typedef unsigned long long uint64_t; /* 8-bytes (64-bits) */ * cc -DSHA2_USE_INTTYPES_H ... */ typedef struct _SHA256_CTX { - uint32_t state[8]; - uint64_t bitcount; - uint8_t buffer[SHA256_BLOCK_LENGTH]; + uint32_t state[8]; + uint64_t bitcount; + uint8_t buffer[SHA256_BLOCK_LENGTH]; } SHA256_CTX; typedef struct _SHA512_CTX { - uint64_t state[8]; - uint64_t bitcount[2]; - uint8_t buffer[SHA512_BLOCK_LENGTH]; + uint64_t state[8]; + uint64_t bitcount[2]; + uint8_t buffer[SHA512_BLOCK_LENGTH]; } SHA512_CTX; typedef SHA512_CTX SHA384_CTX; diff --git a/ext/digest/sha2/sha2init.c b/ext/digest/sha2/sha2init.c index 6ed275eb71..94cccf3feb 100644 --- a/ext/digest/sha2/sha2init.c +++ b/ext/digest/sha2/sha2init.c @@ -47,7 +47,7 @@ Init_sha2(void) cDigest_SHA##bitlen = rb_define_class_under(mDigest, "SHA" #bitlen, cDigest_Base); \ \ rb_ivar_set(cDigest_SHA##bitlen, id_metadata, \ - rb_digest_make_metadata(&sha##bitlen)); + rb_digest_make_metadata(&sha##bitlen)); FOREACH_BITLEN(DEFINE_ALGO_CLASS) } diff --git a/ext/io/nonblock/nonblock.c b/ext/io/nonblock/nonblock.c index b8a40ff38e..cbd43d993a 100644 --- a/ext/io/nonblock/nonblock.c +++ b/ext/io/nonblock/nonblock.c @@ -42,7 +42,7 @@ rb_io_nonblock_p(VALUE io) rb_io_t *fptr; GetOpenFile(io, fptr); if (get_fcntl_flags(fptr->fd) & O_NONBLOCK) - return Qtrue; + return Qtrue; return Qfalse; } #else @@ -54,21 +54,21 @@ static void set_fcntl_flags(int fd, int f) { if (fcntl(fd, F_SETFL, f) == -1) - rb_sys_fail(0); + rb_sys_fail(0); } static int io_nonblock_set(int fd, int f, int nb) { if (nb) { - if ((f & O_NONBLOCK) != 0) - return 0; - f |= O_NONBLOCK; + if ((f & O_NONBLOCK) != 0) + return 0; + f |= O_NONBLOCK; } else { - if ((f & O_NONBLOCK) == 0) - return 0; - f &= ~O_NONBLOCK; + if ((f & O_NONBLOCK) == 0) + return 0; + f &= ~O_NONBLOCK; } set_fcntl_flags(fd, f); return 1; @@ -127,9 +127,9 @@ rb_io_nonblock_set(VALUE io, VALUE nb) rb_io_t *fptr; GetOpenFile(io, fptr); if (RTEST(nb)) - rb_io_set_nonblock(fptr); + rb_io_set_nonblock(fptr); else - io_nonblock_set(fptr->fd, get_fcntl_flags(fptr->fd), RTEST(nb)); + io_nonblock_set(fptr->fd, get_fcntl_flags(fptr->fd), RTEST(nb)); return io; } @@ -160,15 +160,15 @@ rb_io_nonblock_block(int argc, VALUE *argv, VALUE io) GetOpenFile(io, fptr); if (argc > 0) { - VALUE v; - rb_scan_args(argc, argv, "01", &v); - nb = RTEST(v); + VALUE v; + rb_scan_args(argc, argv, "01", &v); + nb = RTEST(v); } f = get_fcntl_flags(fptr->fd); restore[0] = fptr->fd; restore[1] = f; if (!io_nonblock_set(fptr->fd, f, nb)) - return rb_yield(io); + return rb_yield(io); return rb_ensure(rb_yield, io, io_nonblock_restore, (VALUE)restore); } #else diff --git a/ext/io/wait/wait.c b/ext/io/wait/wait.c index 30637da584..d74afb580b 100644 --- a/ext/io/wait/wait.c +++ b/ext/io/wait/wait.c @@ -47,11 +47,11 @@ get_timeout(int argc, VALUE *argv, struct timeval *timerec) VALUE timeout = Qnil; rb_check_arity(argc, 0, 1); if (!argc || NIL_P(timeout = argv[0])) { - return NULL; + return NULL; } else { - *timerec = rb_time_interval(timeout); - return timerec; + *timerec = rb_time_interval(timeout); + return timerec; } } @@ -60,7 +60,7 @@ wait_for_single_fd(rb_io_t *fptr, int events, struct timeval *tv) { int i = rb_wait_for_single_fd(fptr->fd, events, tv); if (i < 0) - rb_sys_fail(0); + rb_sys_fail(0); rb_io_check_closed(fptr); return (i & events); } @@ -180,7 +180,7 @@ io_wait_readable(int argc, VALUE *argv, VALUE io) #ifndef HAVE_RB_IO_WAIT if (wait_for_single_fd(fptr, RB_WAITFD_IN, tv)) { - return io; + return io; } return Qnil; #else @@ -216,7 +216,7 @@ io_wait_writable(int argc, VALUE *argv, VALUE io) #ifndef HAVE_RB_IO_WAIT tv = get_timeout(argc, argv, &timerec); if (wait_for_single_fd(fptr, RB_WAITFD_OUT, tv)) { - return io; + return io; } return Qnil; #else @@ -260,31 +260,31 @@ static int wait_mode_sym(VALUE mode) { if (mode == ID2SYM(rb_intern("r"))) { - return RB_WAITFD_IN; + return RB_WAITFD_IN; } if (mode == ID2SYM(rb_intern("read"))) { - return RB_WAITFD_IN; + return RB_WAITFD_IN; } if (mode == ID2SYM(rb_intern("readable"))) { - return RB_WAITFD_IN; + return RB_WAITFD_IN; } if (mode == ID2SYM(rb_intern("w"))) { - return RB_WAITFD_OUT; + return RB_WAITFD_OUT; } if (mode == ID2SYM(rb_intern("write"))) { - return RB_WAITFD_OUT; + return RB_WAITFD_OUT; } if (mode == ID2SYM(rb_intern("writable"))) { - return RB_WAITFD_OUT; + return RB_WAITFD_OUT; } if (mode == ID2SYM(rb_intern("rw"))) { - return RB_WAITFD_IN|RB_WAITFD_OUT; + return RB_WAITFD_IN|RB_WAITFD_OUT; } if (mode == ID2SYM(rb_intern("read_write"))) { - return RB_WAITFD_IN|RB_WAITFD_OUT; + return RB_WAITFD_IN|RB_WAITFD_OUT; } if (mode == ID2SYM(rb_intern("readable_writable"))) { - return RB_WAITFD_IN|RB_WAITFD_OUT; + return RB_WAITFD_IN|RB_WAITFD_OUT; } rb_raise(rb_eArgError, "unsupported mode: %"PRIsVALUE, mode); return 0; @@ -333,20 +333,20 @@ io_wait(int argc, VALUE *argv, VALUE io) GetOpenFile(io, fptr); for (i = 0; i < argc; ++i) { - if (SYMBOL_P(argv[i])) { - event |= wait_mode_sym(argv[i]); - } - else { - *(tv = &timerec) = rb_time_interval(argv[i]); - } + if (SYMBOL_P(argv[i])) { + event |= wait_mode_sym(argv[i]); + } + else { + *(tv = &timerec) = rb_time_interval(argv[i]); + } } /* rb_time_interval() and might_mode() might convert the argument */ rb_io_check_closed(fptr); if (!event) event = RB_WAITFD_IN; if ((event & RB_WAITFD_IN) && rb_io_read_pending(fptr)) - return Qtrue; + return Qtrue; if (wait_for_single_fd(fptr, event, tv)) - return io; + return io; return Qnil; #else VALUE timeout = Qundef; diff --git a/ext/nkf/nkf.c b/ext/nkf/nkf.c index a8fd937c31..c6ddee1976 100644 --- a/ext/nkf/nkf.c +++ b/ext/nkf/nkf.c @@ -65,11 +65,11 @@ rb_encoding* rb_nkf_enc_get(const char *name) { int idx = rb_enc_find_index(name); if (idx < 0) { - nkf_encoding *nkf_enc = nkf_enc_find(name); - idx = rb_enc_find_index(nkf_enc_name(nkf_enc_to_base_encoding(nkf_enc))); - if (idx < 0) { - idx = rb_define_dummy_encoding(name); - } + nkf_encoding *nkf_enc = nkf_enc_find(name); + idx = rb_enc_find_index(nkf_enc_name(nkf_enc_to_base_encoding(nkf_enc))); + if (idx < 0) { + idx = rb_define_dummy_encoding(name); + } } return rb_enc_from_index(idx); } @@ -83,40 +83,40 @@ int nkf_split_options(const char *arg) int is_single_quoted = FALSE; int is_double_quoted = FALSE; for(i = 0; arg[i]; i++){ - if(j == 255){ - return -1; - }else if(is_single_quoted){ - if(arg[i] == '\''){ - is_single_quoted = FALSE; - }else{ - option[j++] = arg[i]; - } - }else if(is_escaped){ - is_escaped = FALSE; - option[j++] = arg[i]; - }else if(arg[i] == '\\'){ - is_escaped = TRUE; - }else if(is_double_quoted){ - if(arg[i] == '"'){ - is_double_quoted = FALSE; - }else{ - option[j++] = arg[i]; - } - }else if(arg[i] == '\''){ - is_single_quoted = TRUE; - }else if(arg[i] == '"'){ - is_double_quoted = TRUE; - }else if(arg[i] == ' '){ - option[j] = '\0'; - options(option); - j = 0; - }else{ - option[j++] = arg[i]; - } + if(j == 255){ + return -1; + }else if(is_single_quoted){ + if(arg[i] == '\''){ + is_single_quoted = FALSE; + }else{ + option[j++] = arg[i]; + } + }else if(is_escaped){ + is_escaped = FALSE; + option[j++] = arg[i]; + }else if(arg[i] == '\\'){ + is_escaped = TRUE; + }else if(is_double_quoted){ + if(arg[i] == '"'){ + is_double_quoted = FALSE; + }else{ + option[j++] = arg[i]; + } + }else if(arg[i] == '\''){ + is_single_quoted = TRUE; + }else if(arg[i] == '"'){ + is_double_quoted = TRUE; + }else if(arg[i] == ' '){ + option[j] = '\0'; + options(option); + j = 0; + }else{ + option[j++] = arg[i]; + } } if(j){ - option[j] = '\0'; - options(option); + option[j] = '\0'; + options(option); } return count; } @@ -170,9 +170,9 @@ rb_nkf_convert(VALUE obj, VALUE opt, VALUE src) rb_str_set_len(tmp, output_ctr); if (mimeout_f) - rb_enc_associate(tmp, rb_usascii_encoding()); + rb_enc_associate(tmp, rb_usascii_encoding()); else - rb_enc_associate(tmp, rb_nkf_enc_get(nkf_enc_name(output_encoding))); + rb_enc_associate(tmp, rb_nkf_enc_get(nkf_enc_name(output_encoding))); return tmp; } diff --git a/ext/objspace/object_tracing.c b/ext/objspace/object_tracing.c index 66d6baa491..0bf866a8f1 100644 --- a/ext/objspace/object_tracing.c +++ b/ext/objspace/object_tracing.c @@ -31,24 +31,24 @@ static const char * make_unique_str(st_table *tbl, const char *str, long len) { if (!str) { - return NULL; + return NULL; } else { - st_data_t n; - char *result; + st_data_t n; + char *result; - if (st_lookup(tbl, (st_data_t)str, &n)) { - st_insert(tbl, (st_data_t)str, n+1); - st_get_key(tbl, (st_data_t)str, &n); - result = (char *)n; - } - else { - result = (char *)ruby_xmalloc(len+1); - strncpy(result, str, len); - result[len] = 0; - st_add_direct(tbl, (st_data_t)result, 1); - } - return result; + if (st_lookup(tbl, (st_data_t)str, &n)) { + st_insert(tbl, (st_data_t)str, n+1); + st_get_key(tbl, (st_data_t)str, &n); + result = (char *)n; + } + else { + result = (char *)ruby_xmalloc(len+1); + strncpy(result, str, len); + result[len] = 0; + st_add_direct(tbl, (st_data_t)result, 1); + } + return result; } } @@ -56,17 +56,17 @@ static void delete_unique_str(st_table *tbl, const char *str) { if (str) { - st_data_t n; + st_data_t n; - st_lookup(tbl, (st_data_t)str, &n); - if (n == 1) { - n = (st_data_t)str; - st_delete(tbl, &n, 0); - ruby_xfree((char *)n); - } - else { - st_insert(tbl, (st_data_t)str, n-1); - } + st_lookup(tbl, (st_data_t)str, &n); + if (n == 1) { + n = (st_data_t)str; + st_delete(tbl, &n, 0); + ruby_xfree((char *)n); + } + else { + st_insert(tbl, (st_data_t)str, n-1); + } } } @@ -87,18 +87,18 @@ newobj_i(VALUE tpval, void *data) st_data_t v; if (st_lookup(arg->object_table, (st_data_t)obj, &v)) { - info = (struct allocation_info *)v; - if (arg->keep_remains) { - if (info->living) { - /* do nothing. there is possibility to keep living if FREEOBJ events while suppressing tracing */ - } - } - /* reuse info */ - delete_unique_str(arg->str_table, info->path); - delete_unique_str(arg->str_table, info->class_path); + info = (struct allocation_info *)v; + if (arg->keep_remains) { + if (info->living) { + /* do nothing. there is possibility to keep living if FREEOBJ events while suppressing tracing */ + } + } + /* reuse info */ + delete_unique_str(arg->str_table, info->path); + delete_unique_str(arg->str_table, info->class_path); } else { - info = (struct allocation_info *)ruby_xmalloc(sizeof(struct allocation_info)); + info = (struct allocation_info *)ruby_xmalloc(sizeof(struct allocation_info)); } info->living = 1; info->flags = RBASIC(obj)->flags; @@ -122,18 +122,18 @@ freeobj_i(VALUE tpval, void *data) struct allocation_info *info; if (arg->keep_remains) { - if (st_lookup(arg->object_table, obj, &v)) { - info = (struct allocation_info *)v; - info->living = 0; - } + if (st_lookup(arg->object_table, obj, &v)) { + info = (struct allocation_info *)v; + info->living = 0; + } } else { - if (st_delete(arg->object_table, &obj, &v)) { - info = (struct allocation_info *)v; - delete_unique_str(arg->str_table, info->path); - delete_unique_str(arg->str_table, info->class_path); - ruby_xfree(info); - } + if (st_delete(arg->object_table, &obj, &v)) { + info = (struct allocation_info *)v; + delete_unique_str(arg->str_table, info->path); + delete_unique_str(arg->str_table, info->class_path); + ruby_xfree(info); + } } } @@ -236,12 +236,12 @@ get_traceobj_arg(void) VALUE obj = TypedData_Make_Struct(rb_cObject, struct traceobj_arg, &allocation_info_tracer_type, tmp_trace_arg); traceobj_arg = obj; rb_gc_register_mark_object(traceobj_arg); - tmp_trace_arg->running = 0; - tmp_trace_arg->keep_remains = tmp_keep_remains; - tmp_trace_arg->newobj_trace = 0; - tmp_trace_arg->freeobj_trace = 0; - tmp_trace_arg->object_table = st_init_numtable(); - tmp_trace_arg->str_table = st_init_strtable(); + tmp_trace_arg->running = 0; + tmp_trace_arg->keep_remains = tmp_keep_remains; + tmp_trace_arg->newobj_trace = 0; + tmp_trace_arg->freeobj_trace = 0; + tmp_trace_arg->object_table = st_init_numtable(); + tmp_trace_arg->str_table = st_init_strtable(); } return tmp_trace_arg; } @@ -258,15 +258,15 @@ trace_object_allocations_start(VALUE self) struct traceobj_arg *arg = get_traceobj_arg(); if (arg->running++ > 0) { - /* do nothing */ + /* do nothing */ } else { - if (arg->newobj_trace == 0) { - arg->newobj_trace = rb_tracepoint_new(0, RUBY_INTERNAL_EVENT_NEWOBJ, newobj_i, arg); - arg->freeobj_trace = rb_tracepoint_new(0, RUBY_INTERNAL_EVENT_FREEOBJ, freeobj_i, arg); - } - rb_tracepoint_enable(arg->newobj_trace); - rb_tracepoint_enable(arg->freeobj_trace); + if (arg->newobj_trace == 0) { + arg->newobj_trace = rb_tracepoint_new(0, RUBY_INTERNAL_EVENT_NEWOBJ, newobj_i, arg); + arg->freeobj_trace = rb_tracepoint_new(0, RUBY_INTERNAL_EVENT_FREEOBJ, freeobj_i, arg); + } + rb_tracepoint_enable(arg->newobj_trace); + rb_tracepoint_enable(arg->freeobj_trace); } return Qnil; @@ -287,7 +287,7 @@ trace_object_allocations_stop(VALUE self) struct traceobj_arg *arg = get_traceobj_arg(); if (arg->running > 0) { - arg->running--; + arg->running--; } if (arg->running == 0) { @@ -374,8 +374,8 @@ object_allocations_reporter_i(st_data_t key, st_data_t val, st_data_t ptr) else fprintf(out, "C: %p", (void *)info->klass); fprintf(out, "@%s:%lu", info->path ? info->path : "", info->line); if (!NIL_P(info->mid)) { - VALUE m = rb_sym2str(info->mid); - fprintf(out, " (%s)", RSTRING_PTR(m)); + VALUE m = rb_sym2str(info->mid); + fprintf(out, " (%s)", RSTRING_PTR(m)); } fprintf(out, ")\n"); @@ -387,7 +387,7 @@ object_allocations_reporter(FILE *out, void *ptr) { fprintf(out, "== object_allocations_reporter: START\n"); if (tmp_trace_arg) { - st_foreach(tmp_trace_arg->object_table, object_allocations_reporter_i, (st_data_t)out); + st_foreach(tmp_trace_arg->object_table, object_allocations_reporter_i, (st_data_t)out); } fprintf(out, "== object_allocations_reporter: END\n"); } @@ -397,8 +397,8 @@ trace_object_allocations_debug_start(VALUE self) { tmp_keep_remains = 1; if (object_allocations_reporter_registered == 0) { - object_allocations_reporter_registered = 1; - rb_bug_reporter_add(object_allocations_reporter, 0); + object_allocations_reporter_registered = 1; + rb_bug_reporter_add(object_allocations_reporter, 0); } return trace_object_allocations_start(self); @@ -408,10 +408,10 @@ static struct allocation_info * lookup_allocation_info(VALUE obj) { if (tmp_trace_arg) { - st_data_t info; - if (st_lookup(tmp_trace_arg->object_table, obj, &info)) { - return (struct allocation_info *)info; - } + st_data_t info; + if (st_lookup(tmp_trace_arg->object_table, obj, &info)) { + return (struct allocation_info *)info; + } } return NULL; } @@ -435,10 +435,10 @@ allocation_sourcefile(VALUE self, VALUE obj) struct allocation_info *info = lookup_allocation_info(obj); if (info && info->path) { - return rb_str_new2(info->path); + return rb_str_new2(info->path); } else { - return Qnil; + return Qnil; } } @@ -455,10 +455,10 @@ allocation_sourceline(VALUE self, VALUE obj) struct allocation_info *info = lookup_allocation_info(obj); if (info) { - return INT2FIX(info->line); + return INT2FIX(info->line); } else { - return Qnil; + return Qnil; } } @@ -486,10 +486,10 @@ allocation_class_path(VALUE self, VALUE obj) struct allocation_info *info = lookup_allocation_info(obj); if (info && info->class_path) { - return rb_str_new2(info->class_path); + return rb_str_new2(info->class_path); } else { - return Qnil; + return Qnil; } } @@ -518,10 +518,10 @@ allocation_method_id(VALUE self, VALUE obj) { struct allocation_info *info = lookup_allocation_info(obj); if (info) { - return info->mid; + return info->mid; } else { - return Qnil; + return Qnil; } } @@ -550,10 +550,10 @@ allocation_generation(VALUE self, VALUE obj) { struct allocation_info *info = lookup_allocation_info(obj); if (info) { - return SIZET2NUM(info->generation); + return SIZET2NUM(info->generation); } else { - return Qnil; + return Qnil; } } diff --git a/ext/objspace/objspace.c b/ext/objspace/objspace.c index 9cc66bcfe8..fd5f770696 100644 --- a/ext/objspace/objspace.c +++ b/ext/objspace/objspace.c @@ -140,7 +140,7 @@ memsize_of_all_m(int argc, VALUE *argv, VALUE self) struct total_data data = {0, 0}; if (argc > 0) { - rb_scan_args(argc, argv, "01", &data.klass); + rb_scan_args(argc, argv, "01", &data.klass); } each_object_with_flags(total_i, &data); @@ -190,33 +190,33 @@ type2sym(enum ruby_value_type i) VALUE type; switch (i) { #define CASE_TYPE(t) case t: type = ID2SYM(rb_intern(#t)); break; - CASE_TYPE(T_NONE); - CASE_TYPE(T_OBJECT); - CASE_TYPE(T_CLASS); - CASE_TYPE(T_MODULE); - CASE_TYPE(T_FLOAT); - CASE_TYPE(T_STRING); - CASE_TYPE(T_REGEXP); - CASE_TYPE(T_ARRAY); - CASE_TYPE(T_HASH); - CASE_TYPE(T_STRUCT); - CASE_TYPE(T_BIGNUM); - CASE_TYPE(T_FILE); - CASE_TYPE(T_DATA); - CASE_TYPE(T_MATCH); - CASE_TYPE(T_COMPLEX); - CASE_TYPE(T_RATIONAL); - CASE_TYPE(T_NIL); - CASE_TYPE(T_TRUE); - CASE_TYPE(T_FALSE); - CASE_TYPE(T_SYMBOL); - CASE_TYPE(T_FIXNUM); - CASE_TYPE(T_UNDEF); - CASE_TYPE(T_IMEMO); - CASE_TYPE(T_NODE); - CASE_TYPE(T_ICLASS); + CASE_TYPE(T_NONE); + CASE_TYPE(T_OBJECT); + CASE_TYPE(T_CLASS); + CASE_TYPE(T_MODULE); + CASE_TYPE(T_FLOAT); + CASE_TYPE(T_STRING); + CASE_TYPE(T_REGEXP); + CASE_TYPE(T_ARRAY); + CASE_TYPE(T_HASH); + CASE_TYPE(T_STRUCT); + CASE_TYPE(T_BIGNUM); + CASE_TYPE(T_FILE); + CASE_TYPE(T_DATA); + CASE_TYPE(T_MATCH); + CASE_TYPE(T_COMPLEX); + CASE_TYPE(T_RATIONAL); + CASE_TYPE(T_NIL); + CASE_TYPE(T_TRUE); + CASE_TYPE(T_FALSE); + CASE_TYPE(T_SYMBOL); + CASE_TYPE(T_FIXNUM); + CASE_TYPE(T_UNDEF); + CASE_TYPE(T_IMEMO); + CASE_TYPE(T_NODE); + CASE_TYPE(T_ICLASS); CASE_TYPE(T_MOVED); - CASE_TYPE(T_ZOMBIE); + CASE_TYPE(T_ZOMBIE); #undef CASE_TYPE default: rb_bug("type2sym: unknown type (%d)", i); } @@ -255,17 +255,17 @@ count_objects_size(int argc, VALUE *argv, VALUE os) VALUE hash = setup_hash(argc, argv); for (i = 0; i <= T_MASK; i++) { - counts[i] = 0; + counts[i] = 0; } each_object_with_flags(cos_i, &counts[0]); for (i = 0; i <= T_MASK; i++) { - if (counts[i]) { - VALUE type = type2sym(i); - total += counts[i]; - rb_hash_aset(hash, type, SIZET2NUM(counts[i])); - } + if (counts[i]) { + VALUE type = type2sym(i); + total += counts[i]; + rb_hash_aset(hash, type, SIZET2NUM(counts[i])); + } } rb_hash_aset(hash, ID2SYM(rb_intern("TOTAL")), SIZET2NUM(total)); return hash; @@ -379,127 +379,127 @@ count_nodes(int argc, VALUE *argv, VALUE os) VALUE hash = setup_hash(argc, argv); for (i = 0; i <= NODE_LAST; i++) { - nodes[i] = 0; + nodes[i] = 0; } each_object_with_flags(cn_i, &nodes[0]); for (i=0; ilast_category) { - category_str = data->last_category_str; - category_objects = data->last_category_objects; + category_str = data->last_category_str; + category_objects = data->last_category_objects; } else { - data->last_category = category; - category_str = data->last_category_str = rb_str_new2(category); - category_objects = data->last_category_objects = rb_ident_hash_new(); - if (!NIL_P(rb_hash_lookup(data->categories, category_str))) { - rb_bug("reachable_object_from_root_i: category should insert at once"); - } - rb_hash_aset(data->categories, category_str, category_objects); + data->last_category = category; + category_str = data->last_category_str = rb_str_new2(category); + category_objects = data->last_category_objects = rb_ident_hash_new(); + if (!NIL_P(rb_hash_lookup(data->categories, category_str))) { + rb_bug("reachable_object_from_root_i: category should insert at once"); + } + rb_hash_aset(data->categories, category_str, category_objects); } if (rb_objspace_markable_object_p(obj) && - obj != data->categories && - obj != data->last_category_objects) { - if (rb_objspace_internal_object_p(obj)) { - obj = iow_newobj(obj); - } - rb_hash_aset(category_objects, obj, obj); + obj != data->categories && + obj != data->last_category_objects) { + if (rb_objspace_internal_object_p(obj)) { + obj = iow_newobj(obj); + } + rb_hash_aset(category_objects, obj, obj); } } @@ -872,14 +872,14 @@ static VALUE wrap_klass_iow(VALUE klass) { if (!RTEST(klass)) { - return Qnil; + return Qnil; } else if (RB_TYPE_P(klass, T_ICLASS) || CLASS_OF(klass) == Qfalse /* hidden object */) { - return iow_newobj(klass); + return iow_newobj(klass); } else { - return klass; + return klass; } } @@ -898,7 +898,7 @@ objspace_internal_class_of(VALUE self, VALUE obj) VALUE klass; if (rb_typeddata_is_kind_of(obj, &iow_data_type)) { - obj = (VALUE)DATA_PTR(obj); + obj = (VALUE)DATA_PTR(obj); } if (RB_TYPE_P(obj, T_IMEMO)) { @@ -925,17 +925,17 @@ objspace_internal_super_of(VALUE self, VALUE obj) VALUE super; if (rb_typeddata_is_kind_of(obj, &iow_data_type)) { - obj = (VALUE)DATA_PTR(obj); + obj = (VALUE)DATA_PTR(obj); } switch (OBJ_BUILTIN_TYPE(obj)) { case T_MODULE: case T_CLASS: case T_ICLASS: - super = RCLASS_SUPER(obj); - break; + super = RCLASS_SUPER(obj); + break; default: - rb_raise(rb_eArgError, "class or module is expected"); + rb_raise(rb_eArgError, "class or module is expected"); } return wrap_klass_iow(super); diff --git a/ext/objspace/objspace_dump.c b/ext/objspace/objspace_dump.c index c6c85aec99..e4f1216a9a 100644 --- a/ext/objspace/objspace_dump.c +++ b/ext/objspace/objspace_dump.c @@ -235,32 +235,32 @@ obj_type(VALUE obj) { switch (BUILTIN_TYPE(obj)) { #define CASE_TYPE(type) case T_##type: return #type - CASE_TYPE(NONE); - CASE_TYPE(NIL); - CASE_TYPE(OBJECT); - CASE_TYPE(CLASS); - CASE_TYPE(ICLASS); - CASE_TYPE(MODULE); - CASE_TYPE(FLOAT); - CASE_TYPE(STRING); - CASE_TYPE(REGEXP); - CASE_TYPE(ARRAY); - CASE_TYPE(HASH); - CASE_TYPE(STRUCT); - CASE_TYPE(BIGNUM); - CASE_TYPE(FILE); - CASE_TYPE(FIXNUM); - CASE_TYPE(TRUE); - CASE_TYPE(FALSE); - CASE_TYPE(DATA); - CASE_TYPE(MATCH); - CASE_TYPE(SYMBOL); - CASE_TYPE(RATIONAL); - CASE_TYPE(COMPLEX); - CASE_TYPE(IMEMO); - CASE_TYPE(UNDEF); - CASE_TYPE(NODE); - CASE_TYPE(ZOMBIE); + CASE_TYPE(NONE); + CASE_TYPE(NIL); + CASE_TYPE(OBJECT); + CASE_TYPE(CLASS); + CASE_TYPE(ICLASS); + CASE_TYPE(MODULE); + CASE_TYPE(FLOAT); + CASE_TYPE(STRING); + CASE_TYPE(REGEXP); + CASE_TYPE(ARRAY); + CASE_TYPE(HASH); + CASE_TYPE(STRUCT); + CASE_TYPE(BIGNUM); + CASE_TYPE(FILE); + CASE_TYPE(FIXNUM); + CASE_TYPE(TRUE); + CASE_TYPE(FALSE); + CASE_TYPE(DATA); + CASE_TYPE(MATCH); + CASE_TYPE(SYMBOL); + CASE_TYPE(RATIONAL); + CASE_TYPE(COMPLEX); + CASE_TYPE(IMEMO); + CASE_TYPE(UNDEF); + CASE_TYPE(NODE); + CASE_TYPE(ZOMBIE); #undef CASE_TYPE default: break; } @@ -583,8 +583,8 @@ heap_i(void *vstart, void *vend, size_t stride, void *data) asan_unpoison_object(v, false); dc->cur_page_slot_size = stride; - if (dc->full_heap || RBASIC(v)->flags) - dump_object(v, dc); + if (dc->full_heap || RBASIC(v)->flags) + dump_object(v, dc); if (ptr) { asan_poison_object(v); diff --git a/ext/pathname/pathname.c b/ext/pathname/pathname.c index e2c3c36dbf..8ee4bcec5b 100644 --- a/ext/pathname/pathname.c +++ b/ext/pathname/pathname.c @@ -1226,7 +1226,7 @@ path_entries(VALUE self) ary = rb_funcall(rb_cDir, id_entries, 1, str); ary = rb_convert_type(ary, T_ARRAY, "Array", "to_ary"); for (i = 0; i < RARRAY_LEN(ary); i++) { - VALUE elt = RARRAY_AREF(ary, i); + VALUE elt = RARRAY_AREF(ary, i); elt = rb_class_new_instance(1, &elt, klass); rb_ary_store(ary, i, elt); } diff --git a/ext/pty/pty.c b/ext/pty/pty.c index c85f1dcae3..155d215942 100644 --- a/ext/pty/pty.c +++ b/ext/pty/pty.c @@ -107,8 +107,8 @@ chfunc(void *data, char *errbuf, size_t errbuf_len) int slave = carg->slave; #define ERROR_EXIT(str) do { \ - strlcpy(errbuf, (str), errbuf_len); \ - return -1; \ + strlcpy(errbuf, (str), errbuf_len); \ + return -1; \ } while (0) /* @@ -166,7 +166,7 @@ chfunc(void *data, char *errbuf, size_t errbuf_len) static void establishShell(int argc, VALUE *argv, struct pty_info *info, - char SlaveName[DEVICELEN]) + char SlaveName[DEVICELEN]) { int master, slave, status = 0; rb_pid_t pid; @@ -176,22 +176,22 @@ establishShell(int argc, VALUE *argv, struct pty_info *info, char errbuf[32]; if (argc == 0) { - const char *shellname = "/bin/sh"; + const char *shellname = "/bin/sh"; - if ((p = getenv("SHELL")) != NULL) { - shellname = p; - } - else { + if ((p = getenv("SHELL")) != NULL) { + shellname = p; + } + else { #if defined HAVE_PWD_H - const char *username = getenv("USER"); - struct passwd *pwent = getpwnam(username ? username : getlogin()); - if (pwent && pwent->pw_shell) - shellname = pwent->pw_shell; + const char *username = getenv("USER"); + struct passwd *pwent = getpwnam(username ? username : getlogin()); + if (pwent && pwent->pw_shell) + shellname = pwent->pw_shell; #endif - } - v = rb_str_new2(shellname); - argc = 1; - argv = &v; + } + v = rb_str_new2(shellname); + argc = 1; + argv = &v; } carg.execarg_obj = rb_execarg_new(argc, argv, 1, 0); @@ -207,13 +207,13 @@ establishShell(int argc, VALUE *argv, struct pty_info *info, pid = rb_fork_async_signal_safe(&status, chfunc, &carg, Qnil, errbuf, sizeof(errbuf)); if (pid < 0) { - int e = errno; - close(master); - close(slave); + int e = errno; + close(master); + close(slave); rb_execarg_parent_end(carg.execarg_obj); - errno = e; - if (status) rb_jump_tag(status); - rb_sys_fail(errbuf[0] ? errbuf : "fork failed"); + errno = e; + if (status) rb_jump_tag(status); + rb_sys_fail(errbuf[0] ? errbuf : "fork failed"); } close(slave); @@ -268,14 +268,14 @@ get_device_once(int *master, int *slave, char SlaveName[DEVICELEN], int nomesg, rb_fd_fix_cloexec(masterfd); #else { - int flags = O_RDWR|O_NOCTTY; + int flags = O_RDWR|O_NOCTTY; # if defined(O_CLOEXEC) - /* glibc posix_openpt() in GNU/Linux calls open("/dev/ptmx", flags) internally. - * So version dependency on GNU/Linux is the same as O_CLOEXEC with open(). - * O_CLOEXEC is available since Linux 2.6.23. Linux 2.6.18 silently ignore it. */ - flags |= O_CLOEXEC; + /* glibc posix_openpt() in GNU/Linux calls open("/dev/ptmx", flags) internally. + * So version dependency on GNU/Linux is the same as O_CLOEXEC with open(). + * O_CLOEXEC is available since Linux 2.6.23. Linux 2.6.18 silently ignore it. */ + flags |= O_CLOEXEC; # endif - if ((masterfd = posix_openpt(flags)) == -1) goto error; + if ((masterfd = posix_openpt(flags)) == -1) goto error; } rb_fd_fix_cloexec(masterfd); if (rb_grantpt(masterfd) == -1) goto error; @@ -310,15 +310,15 @@ get_device_once(int *master, int *slave, char SlaveName[DEVICELEN], int nomesg, * or the same interface function. */ if (openpty(master, slave, SlaveName, - (struct termios *)0, (struct winsize *)0) == -1) { - if (!fail) return -1; - rb_raise(rb_eRuntimeError, "openpty() failed"); + (struct termios *)0, (struct winsize *)0) == -1) { + if (!fail) return -1; + rb_raise(rb_eRuntimeError, "openpty() failed"); } rb_fd_fix_cloexec(*master); rb_fd_fix_cloexec(*slave); if (no_mesg(SlaveName, nomesg) == -1) { - if (!fail) return -1; - rb_raise(rb_eRuntimeError, "can't chmod slave pty"); + if (!fail) return -1; + rb_raise(rb_eRuntimeError, "can't chmod slave pty"); } return 0; @@ -329,8 +329,8 @@ get_device_once(int *master, int *slave, char SlaveName[DEVICELEN], int nomesg, mode_t mode = nomesg ? 0600 : 0622; if (!(name = _getpty(master, O_RDWR, mode, 0))) { - if (!fail) return -1; - rb_raise(rb_eRuntimeError, "_getpty() failed"); + if (!fail) return -1; + rb_raise(rb_eRuntimeError, "_getpty() failed"); } rb_fd_fix_cloexec(*master); @@ -386,42 +386,42 @@ get_device_once(int *master, int *slave, char SlaveName[DEVICELEN], int nomesg, char MasterName[DEVICELEN]; #define HEX1(c) \ - c"0",c"1",c"2",c"3",c"4",c"5",c"6",c"7", \ - c"8",c"9",c"a",c"b",c"c",c"d",c"e",c"f" + c"0",c"1",c"2",c"3",c"4",c"5",c"6",c"7", \ + c"8",c"9",c"a",c"b",c"c",c"d",c"e",c"f" #if defined(_IBMESA) /* AIX/ESA */ static const char MasterDevice[] = "/dev/ptyp%s"; static const char SlaveDevice[] = "/dev/ttyp%s"; static const char deviceNo[][3] = { - HEX1("0"), HEX1("1"), HEX1("2"), HEX1("3"), - HEX1("4"), HEX1("5"), HEX1("6"), HEX1("7"), - HEX1("8"), HEX1("9"), HEX1("a"), HEX1("b"), - HEX1("c"), HEX1("d"), HEX1("e"), HEX1("f"), + HEX1("0"), HEX1("1"), HEX1("2"), HEX1("3"), + HEX1("4"), HEX1("5"), HEX1("6"), HEX1("7"), + HEX1("8"), HEX1("9"), HEX1("a"), HEX1("b"), + HEX1("c"), HEX1("d"), HEX1("e"), HEX1("f"), }; #else /* 4.2BSD */ static const char MasterDevice[] = "/dev/pty%s"; static const char SlaveDevice[] = "/dev/tty%s"; static const char deviceNo[][3] = { - HEX1("p"), HEX1("q"), HEX1("r"), HEX1("s"), + HEX1("p"), HEX1("q"), HEX1("r"), HEX1("s"), }; #endif #undef HEX1 for (i = 0; i < numberof(deviceNo); i++) { - const char *const devno = deviceNo[i]; - snprintf(MasterName, sizeof MasterName, MasterDevice, devno); - if ((masterfd = rb_cloexec_open(MasterName,O_RDWR,0)) >= 0) { + const char *const devno = deviceNo[i]; + snprintf(MasterName, sizeof MasterName, MasterDevice, devno); + if ((masterfd = rb_cloexec_open(MasterName,O_RDWR,0)) >= 0) { rb_update_max_fd(masterfd); - *master = masterfd; - snprintf(SlaveName, DEVICELEN, SlaveDevice, devno); - if ((slavefd = rb_cloexec_open(SlaveName,O_RDWR,0)) >= 0) { + *master = masterfd; + snprintf(SlaveName, DEVICELEN, SlaveDevice, devno); + if ((slavefd = rb_cloexec_open(SlaveName,O_RDWR,0)) >= 0) { rb_update_max_fd(slavefd); - *slave = slavefd; - if (chown(SlaveName, getuid(), getgid()) != 0) goto error; - if (chmod(SlaveName, nomesg ? 0600 : 0622) != 0) goto error; - return 0; - } - close(masterfd); - } + *slave = slavefd; + if (chown(SlaveName, getuid(), getgid()) != 0) goto error; + if (chmod(SlaveName, nomesg ? 0600 : 0622) != 0) goto error; + return 0; + } + close(masterfd); + } } error: if (slavefd != -1) close(slavefd); @@ -435,8 +435,8 @@ static void getDevice(int *master, int *slave, char SlaveName[DEVICELEN], int nomesg) { if (get_device_once(master, slave, SlaveName, nomesg, 0)) { - rb_gc(); - get_device_once(master, slave, SlaveName, nomesg, 1); + rb_gc(); + get_device_once(master, slave, SlaveName, nomesg, 1); } } @@ -519,7 +519,7 @@ pty_open(VALUE klass) assoc = rb_assoc_new(master_io, slave_file); if (rb_block_given_p()) { - return rb_ensure(rb_yield, assoc, pty_close_pty, assoc); + return rb_ensure(rb_yield, assoc, pty_close_pty, assoc); } return assoc; } @@ -531,7 +531,7 @@ pty_detach_process(VALUE v) #ifdef WNOHANG int st; if (rb_waitpid(info->child_pid, &st, WNOHANG) <= 0) - return Qnil; + return Qnil; #endif rb_detach_process(info->child_pid); return Qnil; @@ -604,8 +604,8 @@ pty_getpty(int argc, VALUE *argv, VALUE self) rb_ary_store(res,2,PIDT2NUM(info.child_pid)); if (rb_block_given_p()) { - rb_ensure(rb_yield, res, pty_detach_process, (VALUE)&info); - return Qnil; + rb_ensure(rb_yield, res, pty_detach_process, (VALUE)&info); + return Qnil; } return res; } @@ -625,13 +625,13 @@ raise_from_check(rb_pid_t pid, int status) ---->> Either IF_STOPPED or WIFSTOPPED is needed <<---- #endif /* WIFSTOPPED | IF_STOPPED */ if (WIFSTOPPED(status)) { /* suspend */ - state = "stopped"; + state = "stopped"; } else if (kill(pid, 0) == 0) { - state = "changed"; + state = "changed"; } else { - state = "exited"; + state = "exited"; } msg = rb_sprintf("pty - %s: %ld", state, (long)pid); exc = rb_exc_new_str(eChildExited, msg); @@ -664,12 +664,12 @@ pty_check(int argc, VALUE *argv, VALUE self) int status; const int flag = #ifdef WNOHANG - WNOHANG| + WNOHANG| #endif #ifdef WUNTRACED - WUNTRACED| + WUNTRACED| #endif - 0; + 0; rb_scan_args(argc, argv, "11", &pid, &exc); cpid = rb_waitpid(NUM2PIDT(pid), &status, flag); diff --git a/ext/readline/readline.c b/ext/readline/readline.c index 5ae037dd41..fc254ce315 100644 --- a/ext/readline/readline.c +++ b/ext/readline/readline.c @@ -376,8 +376,8 @@ prepare_readline(void) { static int initialized = 0; if (!initialized) { - rl_initialize(); - initialized = 1; + rl_initialize(); + initialized = 1; } if (readline_instream) { diff --git a/ext/socket/addrinfo.h b/ext/socket/addrinfo.h index f0b977d79c..eb9eb8ae0e 100644 --- a/ext/socket/addrinfo.h +++ b/ext/socket/addrinfo.h @@ -129,14 +129,14 @@ #ifndef HAVE_TYPE_STRUCT_ADDRINFO struct addrinfo { - int ai_flags; /* AI_PASSIVE, AI_CANONNAME */ - int ai_family; /* PF_xxx */ - int ai_socktype; /* SOCK_xxx */ - int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */ - size_t ai_addrlen; /* length of ai_addr */ - char *ai_canonname; /* canonical name for hostname */ - struct sockaddr *ai_addr; /* binary address */ - struct addrinfo *ai_next; /* next structure in linked list */ + int ai_flags; /* AI_PASSIVE, AI_CANONNAME */ + int ai_family; /* PF_xxx */ + int ai_socktype; /* SOCK_xxx */ + int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */ + size_t ai_addrlen; /* length of ai_addr */ + char *ai_canonname; /* canonical name for hostname */ + struct sockaddr *ai_addr; /* binary address */ + struct addrinfo *ai_next; /* next structure in linked list */ }; #endif @@ -158,18 +158,18 @@ struct addrinfo { #endif extern int getaddrinfo __P(( - const char *hostname, const char *servname, - const struct addrinfo *hints, - struct addrinfo **res)); + const char *hostname, const char *servname, + const struct addrinfo *hints, + struct addrinfo **res)); extern int getnameinfo __P(( - const struct sockaddr *sa, - socklen_t salen, - char *host, - socklen_t hostlen, - char *serv, - socklen_t servlen, - int flags)); + const struct sockaddr *sa, + socklen_t salen, + char *host, + socklen_t hostlen, + char *serv, + socklen_t servlen, + int flags)); extern void freehostent __P((struct hostent *)); extern void freeaddrinfo __P((struct addrinfo *)); diff --git a/ext/socket/ancdata.c b/ext/socket/ancdata.c index aa62cab0ec..071e3323bb 100644 --- a/ext/socket/ancdata.c +++ b/ext/socket/ancdata.c @@ -333,11 +333,11 @@ ancillary_timestamp(VALUE self) if (level == SOL_SOCKET && type == SCM_BINTIME && RSTRING_LEN(data) == sizeof(struct bintime)) { struct bintime bt; - VALUE d, timev; + VALUE d, timev; memcpy((char*)&bt, RSTRING_PTR(data), sizeof(bt)); - d = ULL2NUM(0x100000000ULL); - d = mul(d,d); - timev = add(TIMET2NUM(bt.sec), quo(ULL2NUM(bt.frac), d)); + d = ULL2NUM(0x100000000ULL); + d = mul(d,d); + timev = add(TIMET2NUM(bt.sec), quo(ULL2NUM(bt.frac), d)); result = rb_time_num_new(timev, Qnil); } # endif @@ -697,7 +697,7 @@ anc_inspect_passcred_credentials(int level, int type, VALUE data, VALUE ret) struct ucred cred; memcpy(&cred, RSTRING_PTR(data), sizeof(struct ucred)); rb_str_catf(ret, " pid=%u uid=%u gid=%u", cred.pid, cred.uid, cred.gid); - rb_str_cat2(ret, " (ucred)"); + rb_str_cat2(ret, " (ucred)"); return 1; } else { @@ -712,7 +712,7 @@ static int anc_inspect_socket_creds(int level, int type, VALUE data, VALUE ret) { if (level != SOL_SOCKET && type != SCM_CREDS) - return 0; + return 0; /* * FreeBSD has struct cmsgcred and struct sockcred. @@ -727,46 +727,46 @@ anc_inspect_socket_creds(int level, int type, VALUE data, VALUE ret) #if defined(HAVE_TYPE_STRUCT_CMSGCRED) /* FreeBSD */ if (RSTRING_LEN(data) == sizeof(struct cmsgcred)) { - struct cmsgcred cred; + struct cmsgcred cred; memcpy(&cred, RSTRING_PTR(data), sizeof(struct cmsgcred)); rb_str_catf(ret, " pid=%u", cred.cmcred_pid); rb_str_catf(ret, " uid=%u", cred.cmcred_uid); rb_str_catf(ret, " euid=%u", cred.cmcred_euid); rb_str_catf(ret, " gid=%u", cred.cmcred_gid); - if (cred.cmcred_ngroups) { - int i; - const char *sep = " groups="; - for (i = 0; i < cred.cmcred_ngroups; i++) { - rb_str_catf(ret, "%s%u", sep, cred.cmcred_groups[i]); - sep = ","; - } - } - rb_str_cat2(ret, " (cmsgcred)"); + if (cred.cmcred_ngroups) { + int i; + const char *sep = " groups="; + for (i = 0; i < cred.cmcred_ngroups; i++) { + rb_str_catf(ret, "%s%u", sep, cred.cmcred_groups[i]); + sep = ","; + } + } + rb_str_cat2(ret, " (cmsgcred)"); return 1; } #endif #if defined(HAVE_TYPE_STRUCT_SOCKCRED) /* FreeBSD, NetBSD */ if ((size_t)RSTRING_LEN(data) >= SOCKCREDSIZE(0)) { - struct sockcred cred0, *cred; + struct sockcred cred0, *cred; memcpy(&cred0, RSTRING_PTR(data), SOCKCREDSIZE(0)); - if ((size_t)RSTRING_LEN(data) == SOCKCREDSIZE(cred0.sc_ngroups)) { - cred = (struct sockcred *)ALLOCA_N(char, SOCKCREDSIZE(cred0.sc_ngroups)); - memcpy(cred, RSTRING_PTR(data), SOCKCREDSIZE(cred0.sc_ngroups)); - rb_str_catf(ret, " uid=%u", cred->sc_uid); - rb_str_catf(ret, " euid=%u", cred->sc_euid); - rb_str_catf(ret, " gid=%u", cred->sc_gid); - rb_str_catf(ret, " egid=%u", cred->sc_egid); - if (cred0.sc_ngroups) { - int i; - const char *sep = " groups="; - for (i = 0; i < cred0.sc_ngroups; i++) { - rb_str_catf(ret, "%s%u", sep, cred->sc_groups[i]); - sep = ","; - } - } - rb_str_cat2(ret, " (sockcred)"); - return 1; - } + if ((size_t)RSTRING_LEN(data) == SOCKCREDSIZE(cred0.sc_ngroups)) { + cred = (struct sockcred *)ALLOCA_N(char, SOCKCREDSIZE(cred0.sc_ngroups)); + memcpy(cred, RSTRING_PTR(data), SOCKCREDSIZE(cred0.sc_ngroups)); + rb_str_catf(ret, " uid=%u", cred->sc_uid); + rb_str_catf(ret, " euid=%u", cred->sc_euid); + rb_str_catf(ret, " gid=%u", cred->sc_gid); + rb_str_catf(ret, " egid=%u", cred->sc_egid); + if (cred0.sc_ngroups) { + int i; + const char *sep = " groups="; + for (i = 0; i < cred0.sc_ngroups; i++) { + rb_str_catf(ret, "%s%u", sep, cred->sc_groups[i]); + sep = ","; + } + } + rb_str_cat2(ret, " (sockcred)"); + return 1; + } } #endif return 0; @@ -906,37 +906,37 @@ inspect_bintime_as_abstime(int level, int optname, VALUE data, VALUE ret) if (RSTRING_LEN(data) == sizeof(struct bintime)) { struct bintime bt; struct tm tm; - uint64_t frac_h, frac_l; - uint64_t scale_h, scale_l; - uint64_t tmp1, tmp2; - uint64_t res_h, res_l; + uint64_t frac_h, frac_l; + uint64_t scale_h, scale_l; + uint64_t tmp1, tmp2; + uint64_t res_h, res_l; char buf[32]; memcpy((char*)&bt, RSTRING_PTR(data), sizeof(bt)); LOCALTIME(bt.sec, tm); strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &tm); - /* res_h = frac * 10**19 / 2**64 */ + /* res_h = frac * 10**19 / 2**64 */ - frac_h = bt.frac >> 32; - frac_l = bt.frac & 0xffffffff; + frac_h = bt.frac >> 32; + frac_l = bt.frac & 0xffffffff; - scale_h = 0x8ac72304; /* 0x8ac7230489e80000 == 10**19 */ - scale_l = 0x89e80000; + scale_h = 0x8ac72304; /* 0x8ac7230489e80000 == 10**19 */ + scale_l = 0x89e80000; - res_h = frac_h * scale_h; - res_l = frac_l * scale_l; + res_h = frac_h * scale_h; + res_l = frac_l * scale_l; - tmp1 = frac_h * scale_l; - res_h += tmp1 >> 32; - tmp2 = res_l; - res_l += tmp1 & 0xffffffff; - if (res_l < tmp2) res_h++; + tmp1 = frac_h * scale_l; + res_h += tmp1 >> 32; + tmp2 = res_l; + res_l += tmp1 & 0xffffffff; + if (res_l < tmp2) res_h++; - tmp1 = frac_l * scale_h; - res_h += tmp1 >> 32; - tmp2 = res_l; - res_l += tmp1 & 0xffffffff; - if (res_l < tmp2) res_h++; + tmp1 = frac_l * scale_h; + res_h += tmp1 >> 32; + tmp2 = res_l; + res_l += tmp1 & 0xffffffff; + if (res_l < tmp2) res_h++; rb_str_catf(ret, " %s.%019"PRIu64, buf, res_h); return 1; @@ -1136,8 +1136,8 @@ rb_sendmsg(int fd, const struct msghdr *msg, int flags) static VALUE bsock_sendmsg_internal(VALUE sock, VALUE data, VALUE vflags, - VALUE dest_sockaddr, VALUE controls, VALUE ex, - int nonblock) + VALUE dest_sockaddr, VALUE controls, VALUE ex, + int nonblock) { rb_io_t *fptr; struct msghdr mh; @@ -1160,15 +1160,15 @@ bsock_sendmsg_internal(VALUE sock, VALUE data, VALUE vflags, tmp = rb_str_tmp_frozen_acquire(data); if (!RB_TYPE_P(controls, T_ARRAY)) { - controls = rb_ary_new(); + controls = rb_ary_new(); } controls_num = RARRAY_LENINT(controls); if (controls_num) { #if defined(HAVE_STRUCT_MSGHDR_MSG_CONTROL) - int i; - size_t last_pad = 0; - const VALUE *controls_ptr = RARRAY_CONST_PTR(controls); + int i; + size_t last_pad = 0; + const VALUE *controls_ptr = RARRAY_CONST_PTR(controls); #if defined(__NetBSD__) int last_level = 0; int last_type = 0; @@ -1215,9 +1215,9 @@ bsock_sendmsg_internal(VALUE sock, VALUE data, VALUE vflags, last_level = cmh.cmsg_level; last_type = cmh.cmsg_type; #endif - last_pad = cspace - cmh.cmsg_len; + last_pad = cspace - cmh.cmsg_len; } - if (last_pad) { + if (last_pad) { /* * This code removes the last padding from msg_controllen. * @@ -1242,10 +1242,10 @@ bsock_sendmsg_internal(VALUE sock, VALUE data, VALUE vflags, if (last_level == SOL_SOCKET && last_type == SCM_RIGHTS) rb_str_set_len(controls_str, RSTRING_LEN(controls_str)-last_pad); #endif - } - RB_GC_GUARD(controls); + } + RB_GC_GUARD(controls); #else - rb_raise(rb_eNotImpError, "control message for sendmsg is unimplemented"); + rb_raise(rb_eNotImpError, "control message for sendmsg is unimplemented"); #endif } @@ -1256,7 +1256,7 @@ bsock_sendmsg_internal(VALUE sock, VALUE data, VALUE vflags, #endif if (!NIL_P(dest_sockaddr)) - SockAddrStringValue(dest_sockaddr); + SockAddrStringValue(dest_sockaddr); rb_io_check_closed(fptr); @@ -1284,20 +1284,20 @@ bsock_sendmsg_internal(VALUE sock, VALUE data, VALUE vflags, ss = rb_sendmsg(fptr->fd, &mh, flags); if (ss == -1) { - int e; + int e; if (!nonblock && rb_io_maybe_wait_writable(errno, fptr->self, Qnil)) { rb_io_check_closed(fptr); goto retry; } - e = errno; - if (nonblock && (e == EWOULDBLOCK || e == EAGAIN)) { - if (ex == Qfalse) { - return sym_wait_writable; - } - rb_readwrite_syserr_fail(RB_IO_WAIT_WRITABLE, e, - "sendmsg(2) would block"); - } - rb_syserr_fail(e, "sendmsg(2)"); + e = errno; + if (nonblock && (e == EWOULDBLOCK || e == EAGAIN)) { + if (ex == Qfalse) { + return sym_wait_writable; + } + rb_readwrite_syserr_fail(RB_IO_WAIT_WRITABLE, e, + "sendmsg(2) would block"); + } + rb_syserr_fail(e, "sendmsg(2)"); } #if defined(HAVE_STRUCT_MSGHDR_MSG_CONTROL) RB_GC_GUARD(controls_str); @@ -1311,20 +1311,20 @@ bsock_sendmsg_internal(VALUE sock, VALUE data, VALUE vflags, #if defined(HAVE_SENDMSG) VALUE rsock_bsock_sendmsg(VALUE sock, VALUE data, VALUE flags, VALUE dest_sockaddr, - VALUE controls) + VALUE controls) { return bsock_sendmsg_internal(sock, data, flags, dest_sockaddr, controls, - Qtrue, 0); + Qtrue, 0); } #endif #if defined(HAVE_SENDMSG) VALUE rsock_bsock_sendmsg_nonblock(VALUE sock, VALUE data, VALUE flags, - VALUE dest_sockaddr, VALUE controls, VALUE ex) + VALUE dest_sockaddr, VALUE controls, VALUE ex) { return bsock_sendmsg_internal(sock, data, flags, dest_sockaddr, - controls, ex, 1); + controls, ex, 1); } #endif @@ -1422,12 +1422,12 @@ make_io_for_unix_rights(VALUE ctl, struct cmsghdr *cmh, char *msg_end) { if (cmh->cmsg_level == SOL_SOCKET && cmh->cmsg_type == SCM_RIGHTS) { int *fdp, *end; - VALUE ary = rb_ary_new(); - rb_ivar_set(ctl, rb_intern("unix_rights"), ary); + VALUE ary = rb_ary_new(); + rb_ivar_set(ctl, rb_intern("unix_rights"), ary); fdp = (int *)CMSG_DATA(cmh); end = (int *)((char *)cmh + cmh->cmsg_len); while ((char *)fdp + sizeof(int) <= (char *)end && - (char *)fdp + sizeof(int) <= msg_end) { + (char *)fdp + sizeof(int) <= msg_end) { int fd = *fdp; struct stat stbuf; VALUE io; @@ -1443,15 +1443,15 @@ make_io_for_unix_rights(VALUE ctl, struct cmsghdr *cmh, char *msg_end) rb_ary_push(ary, io); fdp++; } - OBJ_FREEZE(ary); + OBJ_FREEZE(ary); } } #endif static VALUE bsock_recvmsg_internal(VALUE sock, - VALUE vmaxdatlen, VALUE vflags, VALUE vmaxctllen, - VALUE scm_rights, VALUE ex, int nonblock) + VALUE vmaxdatlen, VALUE vflags, VALUE vmaxctllen, + VALUE scm_rights, VALUE ex, int nonblock) { rb_io_t *fptr; int grow_buffer; @@ -1505,28 +1505,28 @@ bsock_recvmsg_internal(VALUE sock, #if !defined(HAVE_STRUCT_MSGHDR_MSG_CONTROL) if (grow_buffer) { - int socktype; - socklen_t optlen = (socklen_t)sizeof(socktype); + int socktype; + socklen_t optlen = (socklen_t)sizeof(socktype); if (getsockopt(fptr->fd, SOL_SOCKET, SO_TYPE, (void*)&socktype, &optlen) == -1) { - rb_sys_fail("getsockopt(SO_TYPE)"); - } - if (socktype == SOCK_STREAM) - grow_buffer = 0; + rb_sys_fail("getsockopt(SO_TYPE)"); + } + if (socktype == SOCK_STREAM) + grow_buffer = 0; } #endif retry: if (NIL_P(dat_str)) - dat_str = rb_str_tmp_new(maxdatlen); + dat_str = rb_str_tmp_new(maxdatlen); else - rb_str_resize(dat_str, maxdatlen); + rb_str_resize(dat_str, maxdatlen); datbuf = RSTRING_PTR(dat_str); #if defined(HAVE_STRUCT_MSGHDR_MSG_CONTROL) if (NIL_P(ctl_str)) - ctl_str = rb_str_tmp_new(maxctllen); + ctl_str = rb_str_tmp_new(maxctllen); else - rb_str_resize(ctl_str, maxctllen); + rb_str_resize(ctl_str, maxctllen); ctlbuf = RSTRING_PTR(ctl_str); #endif @@ -1556,20 +1556,20 @@ bsock_recvmsg_internal(VALUE sock, ss = rb_recvmsg(fptr->fd, &mh, flags); if (ss == -1) { - int e; + int e; if (!nonblock && rb_io_maybe_wait_readable(errno, fptr->self, Qnil)) { rb_io_check_closed(fptr); goto retry; } - e = errno; - if (nonblock && (e == EWOULDBLOCK || e == EAGAIN)) { + e = errno; + if (nonblock && (e == EWOULDBLOCK || e == EAGAIN)) { if (ex == Qfalse) { return sym_wait_readable; } - rb_readwrite_syserr_fail(RB_IO_WAIT_READABLE, e, "recvmsg(2) would block"); + rb_readwrite_syserr_fail(RB_IO_WAIT_READABLE, e, "recvmsg(2) would block"); } #if defined(HAVE_STRUCT_MSGHDR_MSG_CONTROL) - if (!gc_done && (e == EMFILE || e == EMSGSIZE)) { + if (!gc_done && (e == EMFILE || e == EMSGSIZE)) { /* * When SCM_RIGHTS hit the file descriptors limit: * - Linux 2.6.18 causes success with MSG_CTRUNC @@ -1579,24 +1579,24 @@ bsock_recvmsg_internal(VALUE sock, gc_and_retry: rb_gc(); gc_done = 1; - goto retry; + goto retry; } #else - if (NIL_P(vmaxdatlen) && grow_buffer && e == EMSGSIZE) - ss = (ssize_t)iov.iov_len; - else + if (NIL_P(vmaxdatlen) && grow_buffer && e == EMSGSIZE) + ss = (ssize_t)iov.iov_len; + else #endif - rb_syserr_fail(e, "recvmsg(2)"); + rb_syserr_fail(e, "recvmsg(2)"); } if (grow_buffer) { - int grown = 0; - if (NIL_P(vmaxdatlen) && ss != -1 && ss == (ssize_t)iov.iov_len) { + int grown = 0; + if (NIL_P(vmaxdatlen) && ss != -1 && ss == (ssize_t)iov.iov_len) { if (SIZE_MAX/2 < maxdatlen) rb_raise(rb_eArgError, "max data length too big"); - maxdatlen *= 2; - grown = 1; - } + maxdatlen *= 2; + grown = 1; + } #if defined(HAVE_STRUCT_MSGHDR_MSG_CONTROL) if (NIL_P(vmaxctllen) && (mh.msg_flags & MSG_CTRUNC)) { #define BIG_ENOUGH_SPACE 65536 @@ -1605,9 +1605,9 @@ bsock_recvmsg_internal(VALUE sock, /* there are big space bug truncated. * file descriptors limit? */ if (!gc_done) { - rsock_discard_cmsg_resource(&mh, (flags & MSG_PEEK) != 0); + rsock_discard_cmsg_resource(&mh, (flags & MSG_PEEK) != 0); goto gc_and_retry; - } + } } else { if (SIZE_MAX/2 < maxctllen) @@ -1616,13 +1616,13 @@ bsock_recvmsg_internal(VALUE sock, grown = 1; } #undef BIG_ENOUGH_SPACE - } + } #endif - if (grown) { + if (grown) { rsock_discard_cmsg_resource(&mh, (flags & MSG_PEEK) != 0); - goto retry; - } - else { + goto retry; + } + else { grow_buffer = 0; if (flags != orig_flags) { rsock_discard_cmsg_resource(&mh, (flags & MSG_PEEK) != 0); @@ -1636,31 +1636,31 @@ bsock_recvmsg_internal(VALUE sock, dat_str = rb_str_new(datbuf, ss); else { rb_str_resize(dat_str, ss); - rb_obj_reveal(dat_str, rb_cString); + rb_obj_reveal(dat_str, rb_cString); } ret = rb_ary_new3(3, dat_str, rsock_io_socket_addrinfo(sock, mh.msg_name, mh.msg_namelen), #if defined(HAVE_STRUCT_MSGHDR_MSG_CONTROL) - INT2NUM(mh.msg_flags) + INT2NUM(mh.msg_flags) #else - Qnil + Qnil #endif - ); + ); #if defined(HAVE_STRUCT_MSGHDR_MSG_CONTROL) family = rsock_getfamily(fptr); if (mh.msg_controllen) { - char *msg_end = (char *)mh.msg_control + mh.msg_controllen; + char *msg_end = (char *)mh.msg_control + mh.msg_controllen; for (cmh = CMSG_FIRSTHDR(&mh); cmh != NULL; cmh = CMSG_NXTHDR(&mh, cmh)) { VALUE ctl; - char *ctl_end; + char *ctl_end; size_t clen; if (cmh->cmsg_len == 0) { rb_raise(rb_eTypeError, "invalid control message (cmsg_len == 0)"); } ctl_end = (char*)cmh + cmh->cmsg_len; - clen = (ctl_end <= msg_end ? ctl_end : msg_end) - (char*)CMSG_DATA(cmh); + clen = (ctl_end <= msg_end ? ctl_end : msg_end) - (char*)CMSG_DATA(cmh); ctl = ancdata_new(family, cmh->cmsg_level, cmh->cmsg_type, rb_str_new((char*)CMSG_DATA(cmh), clen)); if (request_scm_rights) make_io_for_unix_rights(ctl, cmh, msg_end); @@ -1679,7 +1679,7 @@ bsock_recvmsg_internal(VALUE sock, #if defined(HAVE_RECVMSG) VALUE rsock_bsock_recvmsg(VALUE sock, VALUE dlen, VALUE flags, VALUE clen, - VALUE scm_rights) + VALUE scm_rights) { VALUE ex = Qtrue; return bsock_recvmsg_internal(sock, dlen, flags, clen, scm_rights, ex, 0); @@ -1689,7 +1689,7 @@ rsock_bsock_recvmsg(VALUE sock, VALUE dlen, VALUE flags, VALUE clen, #if defined(HAVE_RECVMSG) VALUE rsock_bsock_recvmsg_nonblock(VALUE sock, VALUE dlen, VALUE flags, VALUE clen, - VALUE scm_rights, VALUE ex) + VALUE scm_rights, VALUE ex) { return bsock_recvmsg_internal(sock, dlen, flags, clen, scm_rights, ex, 1); } diff --git a/ext/socket/basicsocket.c b/ext/socket/basicsocket.c index 44fb7a4eb7..93196c924d 100644 --- a/ext/socket/basicsocket.c +++ b/ext/socket/basicsocket.c @@ -94,16 +94,16 @@ bsock_shutdown(int argc, VALUE *argv, VALUE sock) rb_scan_args(argc, argv, "01", &howto); if (howto == Qnil) - how = SHUT_RDWR; + how = SHUT_RDWR; else { - how = rsock_shutdown_how_arg(howto); + how = rsock_shutdown_how_arg(howto); if (how != SHUT_WR && how != SHUT_RD && how != SHUT_RDWR) { - rb_raise(rb_eArgError, "`how' should be either :SHUT_RD, :SHUT_WR, :SHUT_RDWR"); - } + rb_raise(rb_eArgError, "`how' should be either :SHUT_RD, :SHUT_WR, :SHUT_RDWR"); + } } GetOpenFile(sock, fptr); if (shutdown(fptr->fd, how) == -1) - rb_sys_fail("shutdown(2)"); + rb_sys_fail("shutdown(2)"); return INT2FIX(0); } @@ -126,7 +126,7 @@ bsock_close_read(VALUE sock) GetOpenFile(sock, fptr); shutdown(fptr->fd, 0); if (!(fptr->mode & FMODE_WRITABLE)) { - return rb_io_close(sock); + return rb_io_close(sock); } fptr->mode &= ~FMODE_READABLE; @@ -155,7 +155,7 @@ bsock_close_write(VALUE sock) GetOpenFile(sock, fptr); if (!(fptr->mode & FMODE_READABLE)) { - return rb_io_close(sock); + return rb_io_close(sock); } shutdown(fptr->fd, 1); fptr->mode &= ~FMODE_WRITABLE; @@ -246,21 +246,21 @@ bsock_setsockopt(int argc, VALUE *argv, VALUE sock) switch (TYPE(val)) { case T_FIXNUM: - i = FIX2INT(val); - goto numval; + i = FIX2INT(val); + goto numval; case T_FALSE: - i = 0; - goto numval; + i = 0; + goto numval; case T_TRUE: - i = 1; + i = 1; numval: - v = (char*)&i; vlen = (int)sizeof(i); - break; + v = (char*)&i; vlen = (int)sizeof(i); + break; default: - StringValue(val); - v = RSTRING_PTR(val); - vlen = RSTRING_SOCKLEN(val); - break; + StringValue(val); + v = RSTRING_PTR(val); + vlen = RSTRING_SOCKLEN(val); + break; } rb_io_check_closed(fptr); @@ -357,7 +357,7 @@ bsock_getsockopt(VALUE sock, VALUE lev, VALUE optname) rb_io_check_closed(fptr); if (getsockopt(fptr->fd, level, option, buf, &len) < 0) - rsock_sys_fail_path("getsockopt(2)", fptr->pathv); + rsock_sys_fail_path("getsockopt(2)", fptr->pathv); return rsock_sockopt_new(family, level, option, rb_str_new(buf, len)); } @@ -385,7 +385,7 @@ bsock_getsockname(VALUE sock) GetOpenFile(sock, fptr); if (getsockname(fptr->fd, &buf.addr, &len) < 0) - rb_sys_fail("getsockname(2)"); + rb_sys_fail("getsockname(2)"); if (len0 < len) len = len0; return rb_str_new((char*)&buf, len); } @@ -416,7 +416,7 @@ bsock_getpeername(VALUE sock) GetOpenFile(sock, fptr); if (getpeername(fptr->fd, &buf.addr, &len) < 0) - rb_sys_fail("getpeername(2)"); + rb_sys_fail("getpeername(2)"); if (len0 < len) len = len0; return rb_str_new((char*)&buf, len); } @@ -453,7 +453,7 @@ bsock_getpeereid(VALUE self) gid_t egid; GetOpenFile(self, fptr); if (getpeereid(fptr->fd, &euid, &egid) == -1) - rb_sys_fail("getpeereid(3)"); + rb_sys_fail("getpeereid(3)"); return rb_assoc_new(UIDT2NUM(euid), GIDT2NUM(egid)); #elif defined(SO_PEERCRED) /* GNU/Linux */ rb_io_t *fptr; @@ -461,7 +461,7 @@ bsock_getpeereid(VALUE self) socklen_t len = sizeof(cred); GetOpenFile(self, fptr); if (getsockopt(fptr->fd, SOL_SOCKET, SO_PEERCRED, &cred, &len) == -1) - rb_sys_fail("getsockopt(SO_PEERCRED)"); + rb_sys_fail("getsockopt(SO_PEERCRED)"); return rb_assoc_new(UIDT2NUM(cred.uid), GIDT2NUM(cred.gid)); #elif defined(HAVE_GETPEERUCRED) /* Solaris */ rb_io_t *fptr; @@ -469,7 +469,7 @@ bsock_getpeereid(VALUE self) VALUE ret; GetOpenFile(self, fptr); if (getpeerucred(fptr->fd, &uc) == -1) - rb_sys_fail("getpeerucred(3C)"); + rb_sys_fail("getpeerucred(3C)"); ret = rb_assoc_new(UIDT2NUM(ucred_geteuid(uc)), GIDT2NUM(ucred_getegid(uc))); ucred_free(uc); return ret; @@ -506,7 +506,7 @@ bsock_local_address(VALUE sock) GetOpenFile(sock, fptr); if (getsockname(fptr->fd, &buf.addr, &len) < 0) - rb_sys_fail("getsockname(2)"); + rb_sys_fail("getsockname(2)"); if (len0 < len) len = len0; return rsock_fd_socket_addrinfo(fptr->fd, &buf.addr, len); } @@ -540,7 +540,7 @@ bsock_remote_address(VALUE sock) GetOpenFile(sock, fptr); if (getpeername(fptr->fd, &buf.addr, &len) < 0) - rb_sys_fail("getpeername(2)"); + rb_sys_fail("getpeername(2)"); if (len0 < len) len = len0; return rsock_fd_socket_addrinfo(fptr->fd, &buf.addr, len); } @@ -656,10 +656,10 @@ bsock_do_not_reverse_lookup_set(VALUE sock, VALUE state) GetOpenFile(sock, fptr); if (RTEST(state)) { - fptr->mode |= FMODE_NOREVLOOKUP; + fptr->mode |= FMODE_NOREVLOOKUP; } else { - fptr->mode &= ~FMODE_NOREVLOOKUP; + fptr->mode &= ~FMODE_NOREVLOOKUP; } return sock; } @@ -747,9 +747,9 @@ rsock_init_basicsocket(void) rb_undef_method(rb_cBasicSocket, "initialize"); rb_define_singleton_method(rb_cBasicSocket, "do_not_reverse_lookup", - bsock_do_not_rev_lookup, 0); + bsock_do_not_rev_lookup, 0); rb_define_singleton_method(rb_cBasicSocket, "do_not_reverse_lookup=", - bsock_do_not_rev_lookup_set, 1); + bsock_do_not_rev_lookup_set, 1); rb_define_singleton_method(rb_cBasicSocket, "for_fd", bsock_s_for_fd, 1); rb_define_method(rb_cBasicSocket, "close_read", bsock_close_read, 0); @@ -770,23 +770,23 @@ rsock_init_basicsocket(void) /* for ext/socket/lib/socket.rb use only: */ rb_define_private_method(rb_cBasicSocket, - "__recv_nonblock", bsock_recv_nonblock, 4); + "__recv_nonblock", bsock_recv_nonblock, 4); #if MSG_DONTWAIT_RELIABLE rb_define_private_method(rb_cBasicSocket, - "__read_nonblock", rsock_read_nonblock, 3); + "__read_nonblock", rsock_read_nonblock, 3); rb_define_private_method(rb_cBasicSocket, - "__write_nonblock", rsock_write_nonblock, 2); + "__write_nonblock", rsock_write_nonblock, 2); #endif /* in ancdata.c */ rb_define_private_method(rb_cBasicSocket, "__sendmsg", - rsock_bsock_sendmsg, 4); + rsock_bsock_sendmsg, 4); rb_define_private_method(rb_cBasicSocket, "__sendmsg_nonblock", - rsock_bsock_sendmsg_nonblock, 5); + rsock_bsock_sendmsg_nonblock, 5); rb_define_private_method(rb_cBasicSocket, "__recvmsg", - rsock_bsock_recvmsg, 4); + rsock_bsock_recvmsg, 4); rb_define_private_method(rb_cBasicSocket, "__recvmsg_nonblock", - rsock_bsock_recvmsg_nonblock, 5); + rsock_bsock_recvmsg_nonblock, 5); } diff --git a/ext/socket/constants.c b/ext/socket/constants.c index 1bbb53b173..1213f2ae17 100644 --- a/ext/socket/constants.c +++ b/ext/socket/constants.c @@ -26,14 +26,14 @@ constant_arg(VALUE arg, int (*str_to_int)(const char*, long, int*), const char * goto str; } else if (!NIL_P(tmp = rb_check_string_type(arg))) { - arg = tmp; + arg = tmp; str: ptr = RSTRING_PTR(arg); if (str_to_int(ptr, RSTRING_LEN(arg), &ret) == -1) - rb_raise(rb_eSocket, "%s: %s", errmsg, ptr); + rb_raise(rb_eSocket, "%s: %s", errmsg, ptr); } else { - ret = NUM2INT(arg); + ret = NUM2INT(arg); } return ret; } diff --git a/ext/socket/getaddrinfo.c b/ext/socket/getaddrinfo.c index ce6dc40478..95a2feb3be 100644 --- a/ext/socket/getaddrinfo.c +++ b/ext/socket/getaddrinfo.c @@ -98,42 +98,42 @@ static struct in6_addr faith_prefix = IN6ADDR_ANY_INIT; static const char in_addrany[] = { 0, 0, 0, 0 }; static const char in6_addrany[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static const char in_loopback[] = { 127, 0, 0, 1 }; static const char in6_loopback[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; struct sockinet { - u_char si_len; - u_char si_family; - u_short si_port; + u_char si_len; + u_char si_family; + u_short si_port; }; static const struct afd { - int a_af; - int a_addrlen; - int a_socklen; - int a_off; - const char *a_addrany; - const char *a_loopback; + int a_af; + int a_addrlen; + int a_socklen; + int a_off; + const char *a_addrany; + const char *a_loopback; } afdl [] = { #ifdef INET6 #define N_INET6 0 - {PF_INET6, sizeof(struct in6_addr), - sizeof(struct sockaddr_in6), - offsetof(struct sockaddr_in6, sin6_addr), - in6_addrany, in6_loopback}, + {PF_INET6, sizeof(struct in6_addr), + sizeof(struct sockaddr_in6), + offsetof(struct sockaddr_in6, sin6_addr), + in6_addrany, in6_loopback}, #define N_INET 1 #else #define N_INET 0 #endif - {PF_INET, sizeof(struct in_addr), - sizeof(struct sockaddr_in), - offsetof(struct sockaddr_in, sin_addr), - in_addrany, in_loopback}, - {0, 0, 0, 0, NULL, NULL}, + {PF_INET, sizeof(struct in_addr), + sizeof(struct sockaddr_in), + offsetof(struct sockaddr_in, sin_addr), + in_addrany, in_loopback}, + {0, 0, 0, 0, NULL, NULL}, }; #ifdef INET6 @@ -143,58 +143,58 @@ static const struct afd { #endif static int get_name __P((const char *, const struct afd *, - struct addrinfo **, char *, struct addrinfo *, - int)); + struct addrinfo **, char *, struct addrinfo *, + int)); static int get_addr __P((const char *, int, struct addrinfo **, - struct addrinfo *, int)); + struct addrinfo *, int)); static int str_isnumber __P((const char *)); #ifndef HAVE_GAI_STRERROR static const char *const ai_errlist[] = { - "success.", - "address family for hostname not supported.", /* EAI_ADDRFAMILY */ - "temporary failure in name resolution.", /* EAI_AGAIN */ - "invalid value for ai_flags.", /* EAI_BADFLAGS */ - "non-recoverable failure in name resolution.", /* EAI_FAIL */ - "ai_family not supported.", /* EAI_FAMILY */ - "memory allocation failure.", /* EAI_MEMORY */ - "no address associated with hostname.", /* EAI_NODATA */ - "hostname nor servname provided, or not known.",/* EAI_NONAME */ - "servname not supported for ai_socktype.", /* EAI_SERVICE */ - "ai_socktype not supported.", /* EAI_SOCKTYPE */ - "system error returned in errno.", /* EAI_SYSTEM */ - "invalid value for hints.", /* EAI_BADHINTS */ - "resolved protocol is unknown.", /* EAI_PROTOCOL */ - "unknown error.", /* EAI_MAX */ + "success.", + "address family for hostname not supported.", /* EAI_ADDRFAMILY */ + "temporary failure in name resolution.", /* EAI_AGAIN */ + "invalid value for ai_flags.", /* EAI_BADFLAGS */ + "non-recoverable failure in name resolution.", /* EAI_FAIL */ + "ai_family not supported.", /* EAI_FAMILY */ + "memory allocation failure.", /* EAI_MEMORY */ + "no address associated with hostname.", /* EAI_NODATA */ + "hostname nor servname provided, or not known.",/* EAI_NONAME */ + "servname not supported for ai_socktype.", /* EAI_SERVICE */ + "ai_socktype not supported.", /* EAI_SOCKTYPE */ + "system error returned in errno.", /* EAI_SYSTEM */ + "invalid value for hints.", /* EAI_BADHINTS */ + "resolved protocol is unknown.", /* EAI_PROTOCOL */ + "unknown error.", /* EAI_MAX */ }; #endif #define GET_CANONNAME(ai, str) \ if (pai->ai_flags & AI_CANONNAME) {\ - if (((ai)->ai_canonname = (char *)malloc(strlen(str) + 1)) != NULL) {\ - strcpy((ai)->ai_canonname, (str));\ - } else {\ - error = EAI_MEMORY;\ - goto free;\ - }\ + if (((ai)->ai_canonname = (char *)malloc(strlen(str) + 1)) != NULL) {\ + strcpy((ai)->ai_canonname, (str));\ + } else {\ + error = EAI_MEMORY;\ + goto free;\ + }\ } #define GET_AI(ai, afd, addr, port) {\ - char *p;\ - if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\ - ((afd)->a_socklen)))\ - == NULL) {\ - error = EAI_MEMORY;\ - goto free;\ - }\ - memcpy((ai), pai, sizeof(struct addrinfo));\ - (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\ - (ai)->ai_family = (afd)->a_af;\ - (ai)->ai_addrlen = (afd)->a_socklen;\ - INIT_SOCKADDR((ai)->ai_addr, (afd)->a_af, (afd)->a_socklen);\ - ((struct sockinet *)(ai)->ai_addr)->si_port = (port);\ - p = (char *)((ai)->ai_addr);\ - memcpy(p + (afd)->a_off, (addr), (afd)->a_addrlen);\ + char *p;\ + if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\ + ((afd)->a_socklen)))\ + == NULL) {\ + error = EAI_MEMORY;\ + goto free;\ + }\ + memcpy((ai), pai, sizeof(struct addrinfo));\ + (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\ + (ai)->ai_family = (afd)->a_af;\ + (ai)->ai_addrlen = (afd)->a_socklen;\ + INIT_SOCKADDR((ai)->ai_addr, (afd)->a_af, (afd)->a_socklen);\ + ((struct sockinet *)(ai)->ai_addr)->si_port = (port);\ + p = (char *)((ai)->ai_addr);\ + memcpy(p + (afd)->a_off, (addr), (afd)->a_addrlen);\ } #define ERR(err) { error = (err); goto bad; } @@ -206,36 +206,36 @@ const char * gai_strerror(int ecode) { - if (ecode < 0 || ecode > EAI_MAX) - ecode = EAI_MAX; - return (char *)ai_errlist[ecode]; + if (ecode < 0 || ecode > EAI_MAX) + ecode = EAI_MAX; + return (char *)ai_errlist[ecode]; } #endif void freeaddrinfo(struct addrinfo *ai) { - struct addrinfo *next; + struct addrinfo *next; - do { - next = ai->ai_next; - if (ai->ai_canonname) - free(ai->ai_canonname); - /* no need to free(ai->ai_addr) */ - free(ai); - } while ((ai = next) != NULL); + do { + next = ai->ai_next; + if (ai->ai_canonname) + free(ai->ai_canonname); + /* no need to free(ai->ai_addr) */ + free(ai); + } while ((ai = next) != NULL); } static int str_isnumber(const char *p) { - char *q = (char *)p; - while (*q) { - if (! isdigit(*q)) - return NO; - q++; - } - return YES; + char *q = (char *)p; + while (*q) { + if (! isdigit(*q)) + return NO; + q++; + } + return YES; } #ifndef HAVE_INET_PTON @@ -243,435 +243,435 @@ str_isnumber(const char *p) static int inet_pton(int af, const char *hostname, void *pton) { - struct in_addr in; + struct in_addr in; #ifdef HAVE_INET_ATON - if (!inet_aton(hostname, &in)) - return 0; + if (!inet_aton(hostname, &in)) + return 0; #else - int d1, d2, d3, d4; - char ch; + int d1, d2, d3, d4; + char ch; - if (sscanf(hostname, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 && - 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 && - 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) { - in.s_addr = htonl( - ((long) d1 << 24) | ((long) d2 << 16) | - ((long) d3 << 8) | ((long) d4 << 0)); - } - else { - return 0; - } + if (sscanf(hostname, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 && + 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 && + 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) { + in.s_addr = htonl( + ((long) d1 << 24) | ((long) d2 << 16) | + ((long) d3 << 8) | ((long) d4 << 0)); + } + else { + return 0; + } #endif - memcpy(pton, &in, sizeof(in)); - return 1; + memcpy(pton, &in, sizeof(in)); + return 1; } #endif int getaddrinfo(const char *hostname, const char *servname, const struct addrinfo *hints, struct addrinfo **res) { - struct addrinfo sentinel; - struct addrinfo *top = NULL; - struct addrinfo *cur; - int i, error = 0; - char pton[PTON_MAX]; - struct addrinfo ai; - struct addrinfo *pai; - u_short port; + struct addrinfo sentinel; + struct addrinfo *top = NULL; + struct addrinfo *cur; + int i, error = 0; + char pton[PTON_MAX]; + struct addrinfo ai; + struct addrinfo *pai; + u_short port; #ifdef FAITH - static int firsttime = 1; + static int firsttime = 1; - if (firsttime) { - /* translator hack */ - { - char *q = getenv("GAI"); - if (q && inet_pton(AF_INET6, q, &faith_prefix) == 1) - translate = YES; - } - firsttime = 0; - } + if (firsttime) { + /* translator hack */ + { + char *q = getenv("GAI"); + if (q && inet_pton(AF_INET6, q, &faith_prefix) == 1) + translate = YES; + } + firsttime = 0; + } #endif - /* initialize file static vars */ - sentinel.ai_next = NULL; - cur = &sentinel; - pai = &ai; - pai->ai_flags = 0; - pai->ai_family = PF_UNSPEC; - pai->ai_socktype = ANY; - pai->ai_protocol = ANY; - pai->ai_addrlen = 0; - pai->ai_canonname = NULL; - pai->ai_addr = NULL; - pai->ai_next = NULL; - port = ANY; + /* initialize file static vars */ + sentinel.ai_next = NULL; + cur = &sentinel; + pai = &ai; + pai->ai_flags = 0; + pai->ai_family = PF_UNSPEC; + pai->ai_socktype = ANY; + pai->ai_protocol = ANY; + pai->ai_addrlen = 0; + pai->ai_canonname = NULL; + pai->ai_addr = NULL; + pai->ai_next = NULL; + port = ANY; - if (hostname == NULL && servname == NULL) - return EAI_NONAME; - if (hints) { - /* error check for hints */ - if (hints->ai_addrlen || hints->ai_canonname || - hints->ai_addr || hints->ai_next) - ERR(EAI_BADHINTS); /* xxx */ - if (hints->ai_flags & ~AI_MASK) - ERR(EAI_BADFLAGS); - switch (hints->ai_family) { - case PF_UNSPEC: - case PF_INET: + if (hostname == NULL && servname == NULL) + return EAI_NONAME; + if (hints) { + /* error check for hints */ + if (hints->ai_addrlen || hints->ai_canonname || + hints->ai_addr || hints->ai_next) + ERR(EAI_BADHINTS); /* xxx */ + if (hints->ai_flags & ~AI_MASK) + ERR(EAI_BADFLAGS); + switch (hints->ai_family) { + case PF_UNSPEC: + case PF_INET: #ifdef INET6 - case PF_INET6: + case PF_INET6: #endif - break; - default: - ERR(EAI_FAMILY); - } - memcpy(pai, hints, sizeof(*pai)); - switch (pai->ai_socktype) { - case ANY: - switch (pai->ai_protocol) { - case ANY: - break; - case IPPROTO_UDP: - pai->ai_socktype = SOCK_DGRAM; - break; - case IPPROTO_TCP: - pai->ai_socktype = SOCK_STREAM; - break; - default: + break; + default: + ERR(EAI_FAMILY); + } + memcpy(pai, hints, sizeof(*pai)); + switch (pai->ai_socktype) { + case ANY: + switch (pai->ai_protocol) { + case ANY: + break; + case IPPROTO_UDP: + pai->ai_socktype = SOCK_DGRAM; + break; + case IPPROTO_TCP: + pai->ai_socktype = SOCK_STREAM; + break; + default: #if defined(SOCK_RAW) - pai->ai_socktype = SOCK_RAW; + pai->ai_socktype = SOCK_RAW; #endif - break; - } - break; + break; + } + break; #if defined(SOCK_RAW) - case SOCK_RAW: - break; + case SOCK_RAW: + break; #endif - case SOCK_DGRAM: - if (pai->ai_protocol != IPPROTO_UDP && - pai->ai_protocol != ANY) - ERR(EAI_BADHINTS); /*xxx*/ - pai->ai_protocol = IPPROTO_UDP; - break; - case SOCK_STREAM: - if (pai->ai_protocol != IPPROTO_TCP && - pai->ai_protocol != ANY) - ERR(EAI_BADHINTS); /*xxx*/ - pai->ai_protocol = IPPROTO_TCP; - break; - default: - ERR(EAI_SOCKTYPE); - break; - } - } + case SOCK_DGRAM: + if (pai->ai_protocol != IPPROTO_UDP && + pai->ai_protocol != ANY) + ERR(EAI_BADHINTS); /*xxx*/ + pai->ai_protocol = IPPROTO_UDP; + break; + case SOCK_STREAM: + if (pai->ai_protocol != IPPROTO_TCP && + pai->ai_protocol != ANY) + ERR(EAI_BADHINTS); /*xxx*/ + pai->ai_protocol = IPPROTO_TCP; + break; + default: + ERR(EAI_SOCKTYPE); + break; + } + } - /* - * service port - */ - if (servname) { - if (str_isnumber(servname)) { - if (pai->ai_socktype == ANY) { - /* caller accept *ANY* socktype */ - pai->ai_socktype = SOCK_DGRAM; - pai->ai_protocol = IPPROTO_UDP; - } - port = htons((unsigned short)atoi(servname)); + /* + * service port + */ + if (servname) { + if (str_isnumber(servname)) { + if (pai->ai_socktype == ANY) { + /* caller accept *ANY* socktype */ + pai->ai_socktype = SOCK_DGRAM; + pai->ai_protocol = IPPROTO_UDP; + } + port = htons((unsigned short)atoi(servname)); } else if (pai->ai_flags & AI_NUMERICSERV) { ERR(EAI_NONAME); - } else { - struct servent *sp; - const char *proto; + } else { + struct servent *sp; + const char *proto; - proto = NULL; - switch (pai->ai_socktype) { - case ANY: - proto = NULL; - break; - case SOCK_DGRAM: - proto = "udp"; - break; - case SOCK_STREAM: - proto = "tcp"; - break; - default: - fprintf(stderr, "panic!\n"); - break; - } - if ((sp = getservbyname((char*)servname, proto)) == NULL) - ERR(EAI_SERVICE); - port = sp->s_port; - if (pai->ai_socktype == ANY) - if (strcmp(sp->s_proto, "udp") == 0) { - pai->ai_socktype = SOCK_DGRAM; - pai->ai_protocol = IPPROTO_UDP; - } else if (strcmp(sp->s_proto, "tcp") == 0) { - pai->ai_socktype = SOCK_STREAM; - pai->ai_protocol = IPPROTO_TCP; - } else - ERR(EAI_PROTOCOL); /*xxx*/ - } - } + proto = NULL; + switch (pai->ai_socktype) { + case ANY: + proto = NULL; + break; + case SOCK_DGRAM: + proto = "udp"; + break; + case SOCK_STREAM: + proto = "tcp"; + break; + default: + fprintf(stderr, "panic!\n"); + break; + } + if ((sp = getservbyname((char*)servname, proto)) == NULL) + ERR(EAI_SERVICE); + port = sp->s_port; + if (pai->ai_socktype == ANY) + if (strcmp(sp->s_proto, "udp") == 0) { + pai->ai_socktype = SOCK_DGRAM; + pai->ai_protocol = IPPROTO_UDP; + } else if (strcmp(sp->s_proto, "tcp") == 0) { + pai->ai_socktype = SOCK_STREAM; + pai->ai_protocol = IPPROTO_TCP; + } else + ERR(EAI_PROTOCOL); /*xxx*/ + } + } - /* - * hostname == NULL. - * passive socket -> anyaddr (0.0.0.0 or ::) - * non-passive socket -> localhost (127.0.0.1 or ::1) - */ - if (hostname == NULL) { - const struct afd *afd; - int s; + /* + * hostname == NULL. + * passive socket -> anyaddr (0.0.0.0 or ::) + * non-passive socket -> localhost (127.0.0.1 or ::1) + */ + if (hostname == NULL) { + const struct afd *afd; + int s; - for (afd = &afdl[0]; afd->a_af; afd++) { - if (!(pai->ai_family == PF_UNSPEC - || pai->ai_family == afd->a_af)) { - continue; - } + for (afd = &afdl[0]; afd->a_af; afd++) { + if (!(pai->ai_family == PF_UNSPEC + || pai->ai_family == afd->a_af)) { + continue; + } - /* - * filter out AFs that are not supported by the kernel - * XXX errno? - */ - s = socket(afd->a_af, SOCK_DGRAM, 0); - if (s < 0) - continue; + /* + * filter out AFs that are not supported by the kernel + * XXX errno? + */ + s = socket(afd->a_af, SOCK_DGRAM, 0); + if (s < 0) + continue; - close(s); + close(s); - if (pai->ai_flags & AI_PASSIVE) { - GET_AI(cur->ai_next, afd, afd->a_addrany, port); - /* xxx meaningless? - * GET_CANONNAME(cur->ai_next, "anyaddr"); - */ - } else { - GET_AI(cur->ai_next, afd, afd->a_loopback, - port); - /* xxx meaningless? - * GET_CANONNAME(cur->ai_next, "localhost"); - */ - } - cur = cur->ai_next; - } - top = sentinel.ai_next; - if (top) - goto good; - else - ERR(EAI_FAMILY); - } + if (pai->ai_flags & AI_PASSIVE) { + GET_AI(cur->ai_next, afd, afd->a_addrany, port); + /* xxx meaningless? + * GET_CANONNAME(cur->ai_next, "anyaddr"); + */ + } else { + GET_AI(cur->ai_next, afd, afd->a_loopback, + port); + /* xxx meaningless? + * GET_CANONNAME(cur->ai_next, "localhost"); + */ + } + cur = cur->ai_next; + } + top = sentinel.ai_next; + if (top) + goto good; + else + ERR(EAI_FAMILY); + } - /* hostname as numeric name */ - for (i = 0; afdl[i].a_af; i++) { - if (inet_pton(afdl[i].a_af, hostname, pton)) { - u_long v4a; + /* hostname as numeric name */ + for (i = 0; afdl[i].a_af; i++) { + if (inet_pton(afdl[i].a_af, hostname, pton)) { + u_long v4a; #ifdef INET6 - u_char pfx; + u_char pfx; #endif - switch (afdl[i].a_af) { - case AF_INET: - v4a = ((struct in_addr *)pton)->s_addr; - if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a)) - pai->ai_flags &= ~AI_CANONNAME; - v4a >>= IN_CLASSA_NSHIFT; - if (v4a == 0 || v4a == IN_LOOPBACKNET) - pai->ai_flags &= ~AI_CANONNAME; - break; + switch (afdl[i].a_af) { + case AF_INET: + v4a = ((struct in_addr *)pton)->s_addr; + if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a)) + pai->ai_flags &= ~AI_CANONNAME; + v4a >>= IN_CLASSA_NSHIFT; + if (v4a == 0 || v4a == IN_LOOPBACKNET) + pai->ai_flags &= ~AI_CANONNAME; + break; #ifdef INET6 - case AF_INET6: - pfx = ((struct in6_addr *)pton)->s6_addr[0]; - if (pfx == 0 || pfx == 0xfe || pfx == 0xff) - pai->ai_flags &= ~AI_CANONNAME; - break; + case AF_INET6: + pfx = ((struct in6_addr *)pton)->s6_addr[0]; + if (pfx == 0 || pfx == 0xfe || pfx == 0xff) + pai->ai_flags &= ~AI_CANONNAME; + break; #endif - } + } - if (pai->ai_family == afdl[i].a_af || - pai->ai_family == PF_UNSPEC) { - if (! (pai->ai_flags & AI_CANONNAME)) { - GET_AI(top, &afdl[i], pton, port); - goto good; - } - /* - * if AI_CANONNAME and if reverse lookup - * fail, return ai anyway to pacify - * calling application. - * - * XXX getaddrinfo() is a name->address - * translation function, and it looks strange - * that we do addr->name translation here. - */ - get_name(pton, &afdl[i], &top, pton, pai, port); - goto good; - } else - ERR(EAI_FAMILY); /*xxx*/ - } - } + if (pai->ai_family == afdl[i].a_af || + pai->ai_family == PF_UNSPEC) { + if (! (pai->ai_flags & AI_CANONNAME)) { + GET_AI(top, &afdl[i], pton, port); + goto good; + } + /* + * if AI_CANONNAME and if reverse lookup + * fail, return ai anyway to pacify + * calling application. + * + * XXX getaddrinfo() is a name->address + * translation function, and it looks strange + * that we do addr->name translation here. + */ + get_name(pton, &afdl[i], &top, pton, pai, port); + goto good; + } else + ERR(EAI_FAMILY); /*xxx*/ + } + } - if (pai->ai_flags & AI_NUMERICHOST) - ERR(EAI_NONAME); + if (pai->ai_flags & AI_NUMERICHOST) + ERR(EAI_NONAME); - /* hostname as alphabetical name */ - error = get_addr(hostname, pai->ai_family, &top, pai, port); - if (error == 0) { - if (top) { + /* hostname as alphabetical name */ + error = get_addr(hostname, pai->ai_family, &top, pai, port); + if (error == 0) { + if (top) { good: - *res = top; - return SUCCESS; - } else - error = EAI_FAIL; - } + *res = top; + return SUCCESS; + } else + error = EAI_FAIL; + } free: - if (top) - freeaddrinfo(top); + if (top) + freeaddrinfo(top); bad: - *res = NULL; - return error; + *res = NULL; + return error; } static int get_name(const char *addr, const struct afd *afd, struct addrinfo **res, char *numaddr, struct addrinfo *pai, int port0) { - u_short port = port0 & 0xffff; - struct hostent *hp; - struct addrinfo *cur; - int error = 0; + u_short port = port0 & 0xffff; + struct hostent *hp; + struct addrinfo *cur; + int error = 0; #ifdef INET6 - int h_error; + int h_error; #endif #ifdef INET6 - hp = getipnodebyaddr(addr, afd->a_addrlen, afd->a_af, &h_error); + hp = getipnodebyaddr(addr, afd->a_addrlen, afd->a_af, &h_error); #else - hp = gethostbyaddr((char*)addr, afd->a_addrlen, AF_INET); + hp = gethostbyaddr((char*)addr, afd->a_addrlen, AF_INET); #endif - if (hp && hp->h_name && hp->h_name[0] && hp->h_addr_list[0]) { - GET_AI(cur, afd, hp->h_addr_list[0], port); - GET_CANONNAME(cur, hp->h_name); - } else - GET_AI(cur, afd, numaddr, port); + if (hp && hp->h_name && hp->h_name[0] && hp->h_addr_list[0]) { + GET_AI(cur, afd, hp->h_addr_list[0], port); + GET_CANONNAME(cur, hp->h_name); + } else + GET_AI(cur, afd, numaddr, port); #ifdef INET6 - if (hp) - freehostent(hp); + if (hp) + freehostent(hp); #endif - *res = cur; - return SUCCESS; + *res = cur; + return SUCCESS; free: - if (cur) - freeaddrinfo(cur); + if (cur) + freeaddrinfo(cur); #ifdef INET6 - if (hp) - freehostent(hp); + if (hp) + freehostent(hp); #endif /* bad: */ - *res = NULL; - return error; + *res = NULL; + return error; } static int get_addr(const char *hostname, int af, struct addrinfo **res, struct addrinfo *pai, int port0) { - u_short port = port0 & 0xffff; - struct addrinfo sentinel; - struct hostent *hp; - struct addrinfo *top, *cur; - const struct afd *afd; - int i, error = 0, h_error; - char *ap; + u_short port = port0 & 0xffff; + struct addrinfo sentinel; + struct hostent *hp; + struct addrinfo *top, *cur; + const struct afd *afd; + int i, error = 0, h_error; + char *ap; - top = NULL; - sentinel.ai_next = NULL; - cur = &sentinel; + top = NULL; + sentinel.ai_next = NULL; + cur = &sentinel; #ifdef INET6 - if (af == AF_UNSPEC) { - hp = getipnodebyname(hostname, AF_INET6, - AI_ADDRCONFIG|AI_ALL|AI_V4MAPPED, &h_error); - } else - hp = getipnodebyname(hostname, af, AI_ADDRCONFIG, &h_error); + if (af == AF_UNSPEC) { + hp = getipnodebyname(hostname, AF_INET6, + AI_ADDRCONFIG|AI_ALL|AI_V4MAPPED, &h_error); + } else + hp = getipnodebyname(hostname, af, AI_ADDRCONFIG, &h_error); #else - if (strlen(hostname) >= NI_MAXHOST) ERR(EAI_NODATA); - hp = gethostbyname((char*)hostname); - h_error = h_errno; + if (strlen(hostname) >= NI_MAXHOST) ERR(EAI_NODATA); + hp = gethostbyname((char*)hostname); + h_error = h_errno; #endif - if (hp == NULL) { - switch (h_error) { - case HOST_NOT_FOUND: - case NO_DATA: - error = EAI_NODATA; - break; - case TRY_AGAIN: - error = EAI_AGAIN; - break; - case NO_RECOVERY: - default: - error = EAI_FAIL; - break; - } - goto bad; - } + if (hp == NULL) { + switch (h_error) { + case HOST_NOT_FOUND: + case NO_DATA: + error = EAI_NODATA; + break; + case TRY_AGAIN: + error = EAI_AGAIN; + break; + case NO_RECOVERY: + default: + error = EAI_FAIL; + break; + } + goto bad; + } - if ((hp->h_name == NULL) || (hp->h_name[0] == 0) || - (hp->h_addr_list[0] == NULL)) - ERR(EAI_FAIL); + if ((hp->h_name == NULL) || (hp->h_name[0] == 0) || + (hp->h_addr_list[0] == NULL)) + ERR(EAI_FAIL); - for (i = 0; (ap = hp->h_addr_list[i]) != NULL; i++) { - switch (af) { + for (i = 0; (ap = hp->h_addr_list[i]) != NULL; i++) { + switch (af) { #ifdef INET6 - case AF_INET6: - afd = &afdl[N_INET6]; - break; + case AF_INET6: + afd = &afdl[N_INET6]; + break; #endif #ifndef INET6 - default: /* AF_UNSPEC */ + default: /* AF_UNSPEC */ #endif - case AF_INET: - afd = &afdl[N_INET]; - break; + case AF_INET: + afd = &afdl[N_INET]; + break; #ifdef INET6 - default: /* AF_UNSPEC */ - if (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)ap)) { - ap += sizeof(struct in6_addr) - - sizeof(struct in_addr); - afd = &afdl[N_INET]; - } else - afd = &afdl[N_INET6]; - break; + default: /* AF_UNSPEC */ + if (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)ap)) { + ap += sizeof(struct in6_addr) - + sizeof(struct in_addr); + afd = &afdl[N_INET]; + } else + afd = &afdl[N_INET6]; + break; #endif - } + } #ifdef FAITH - if (translate && afd->a_af == AF_INET) { - struct in6_addr *in6; + if (translate && afd->a_af == AF_INET) { + struct in6_addr *in6; - GET_AI(cur->ai_next, &afdl[N_INET6], ap, port); - in6 = &((struct sockaddr_in6 *)cur->ai_next->ai_addr)->sin6_addr; - memcpy(&in6->s6_addr, &faith_prefix, - sizeof(struct in6_addr) - sizeof(struct in_addr)); - memcpy(&in6->s6_addr + sizeof(struct in_addr), ap, - sizeof(struct in_addr)); - } else + GET_AI(cur->ai_next, &afdl[N_INET6], ap, port); + in6 = &((struct sockaddr_in6 *)cur->ai_next->ai_addr)->sin6_addr; + memcpy(&in6->s6_addr, &faith_prefix, + sizeof(struct in6_addr) - sizeof(struct in_addr)); + memcpy(&in6->s6_addr + sizeof(struct in_addr), ap, + sizeof(struct in_addr)); + } else #endif /* FAITH */ - GET_AI(cur->ai_next, afd, ap, port); - if (cur == &sentinel) { - top = cur->ai_next; - GET_CANONNAME(top, hp->h_name); - } - cur = cur->ai_next; - } + GET_AI(cur->ai_next, afd, ap, port); + if (cur == &sentinel) { + top = cur->ai_next; + GET_CANONNAME(top, hp->h_name); + } + cur = cur->ai_next; + } #ifdef INET6 - freehostent(hp); + freehostent(hp); #endif - *res = top; - return SUCCESS; + *res = top; + return SUCCESS; free: - if (top) - freeaddrinfo(top); + if (top) + freeaddrinfo(top); #ifdef INET6 - if (hp) - freehostent(hp); + if (hp) + freehostent(hp); #endif bad: - *res = NULL; - return error; + *res = NULL; + return error; } diff --git a/ext/socket/getnameinfo.c b/ext/socket/getnameinfo.c index 94a5eb9439..ae5284fab6 100644 --- a/ext/socket/getnameinfo.c +++ b/ext/socket/getnameinfo.c @@ -84,30 +84,30 @@ typedef int socklen_t; #define NO 0 struct sockinet { - u_char si_len; - u_char si_family; - u_short si_port; + u_char si_len; + u_char si_family; + u_short si_port; }; static struct afd { - int a_af; - int a_addrlen; - int a_socklen; - int a_off; + int a_af; + int a_addrlen; + int a_socklen; + int a_off; } afdl [] = { #ifdef INET6 #define N_INET6 0 - {PF_INET6, sizeof(struct in6_addr), - sizeof(struct sockaddr_in6), - offsetof(struct sockaddr_in6, sin6_addr)}, + {PF_INET6, sizeof(struct in6_addr), + sizeof(struct sockaddr_in6), + offsetof(struct sockaddr_in6, sin6_addr)}, #define N_INET 1 #else #define N_INET 0 #endif - {PF_INET, sizeof(struct in_addr), - sizeof(struct sockaddr_in), - offsetof(struct sockaddr_in, sin_addr)}, - {0, 0, 0, 0}, + {PF_INET, sizeof(struct in_addr), + sizeof(struct sockaddr_in), + offsetof(struct sockaddr_in, sin_addr)}, + {0, 0, 0, 0}, }; #define ENI_NOSOCKET 0 @@ -121,123 +121,123 @@ static struct afd { int getnameinfo(const struct sockaddr *sa, socklen_t salen, char *host, socklen_t hostlen, char *serv, socklen_t servlen, int flags) { - struct afd *afd; - struct hostent *hp; - u_short port; - int family, len, i; - char *addr, *p; - u_long v4a; + struct afd *afd; + struct hostent *hp; + u_short port; + int family, len, i; + char *addr, *p; + u_long v4a; #ifdef INET6 - u_char pfx; + u_char pfx; #endif - int h_error; - char numserv[512]; - char numaddr[512]; + int h_error; + char numserv[512]; + char numaddr[512]; - if (sa == NULL) - return ENI_NOSOCKET; + if (sa == NULL) + return ENI_NOSOCKET; - if (!VALIDATE_SOCKLEN(sa, salen)) return ENI_SALEN; + if (!VALIDATE_SOCKLEN(sa, salen)) return ENI_SALEN; len = salen; - family = sa->sa_family; - for (i = 0; afdl[i].a_af; i++) - if (afdl[i].a_af == family) { - afd = &afdl[i]; - goto found; - } - return ENI_FAMILY; + family = sa->sa_family; + for (i = 0; afdl[i].a_af; i++) + if (afdl[i].a_af == family) { + afd = &afdl[i]; + goto found; + } + return ENI_FAMILY; found: - if (len != afd->a_socklen) return ENI_SALEN; + if (len != afd->a_socklen) return ENI_SALEN; - port = ((struct sockinet *)sa)->si_port; /* network byte order */ - addr = (char *)sa + afd->a_off; + port = ((struct sockinet *)sa)->si_port; /* network byte order */ + addr = (char *)sa + afd->a_off; - if (serv == NULL || servlen == 0) { - /* what we should do? */ - } else if (flags & NI_NUMERICSERV) { - snprintf(numserv, sizeof(numserv), "%d", ntohs(port)); - if (strlen(numserv) + 1 > servlen) - return ENI_MEMORY; - strcpy(serv, numserv); - } else { + if (serv == NULL || servlen == 0) { + /* what we should do? */ + } else if (flags & NI_NUMERICSERV) { + snprintf(numserv, sizeof(numserv), "%d", ntohs(port)); + if (strlen(numserv) + 1 > servlen) + return ENI_MEMORY; + strcpy(serv, numserv); + } else { #if defined(HAVE_GETSERVBYPORT) - struct servent *sp = getservbyport(port, (flags & NI_DGRAM) ? "udp" : "tcp"); - if (sp) { - if (strlen(sp->s_name) + 1 > servlen) - return ENI_MEMORY; - strcpy(serv, sp->s_name); - } else - return ENI_NOSERVNAME; + struct servent *sp = getservbyport(port, (flags & NI_DGRAM) ? "udp" : "tcp"); + if (sp) { + if (strlen(sp->s_name) + 1 > servlen) + return ENI_MEMORY; + strcpy(serv, sp->s_name); + } else + return ENI_NOSERVNAME; #else - return ENI_NOSERVNAME; + return ENI_NOSERVNAME; #endif - } + } - switch (sa->sa_family) { - case AF_INET: - v4a = ntohl(((struct sockaddr_in *)sa)->sin_addr.s_addr); - if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a)) - flags |= NI_NUMERICHOST; - v4a >>= IN_CLASSA_NSHIFT; - if (v4a == 0) - flags |= NI_NUMERICHOST; - break; + switch (sa->sa_family) { + case AF_INET: + v4a = ntohl(((struct sockaddr_in *)sa)->sin_addr.s_addr); + if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a)) + flags |= NI_NUMERICHOST; + v4a >>= IN_CLASSA_NSHIFT; + if (v4a == 0) + flags |= NI_NUMERICHOST; + break; #ifdef INET6 - case AF_INET6: + case AF_INET6: #ifdef HAVE_ADDR8 - pfx = ((struct sockaddr_in6 *)sa)->sin6_addr.s6_addr8[0]; + pfx = ((struct sockaddr_in6 *)sa)->sin6_addr.s6_addr8[0]; #else - pfx = ((struct sockaddr_in6 *)sa)->sin6_addr.s6_addr[0]; + pfx = ((struct sockaddr_in6 *)sa)->sin6_addr.s6_addr[0]; #endif - if (pfx == 0 || pfx == 0xfe || pfx == 0xff) - flags |= NI_NUMERICHOST; - break; + if (pfx == 0 || pfx == 0xfe || pfx == 0xff) + flags |= NI_NUMERICHOST; + break; #endif - } - if (host == NULL || hostlen == 0) { - /* what should we do? */ - } else if (flags & NI_NUMERICHOST) { - if (inet_ntop(afd->a_af, addr, numaddr, sizeof(numaddr)) - == NULL) - return ENI_SYSTEM; - if (strlen(numaddr) > hostlen) - return ENI_MEMORY; - strcpy(host, numaddr); - } else { + } + if (host == NULL || hostlen == 0) { + /* what should we do? */ + } else if (flags & NI_NUMERICHOST) { + if (inet_ntop(afd->a_af, addr, numaddr, sizeof(numaddr)) + == NULL) + return ENI_SYSTEM; + if (strlen(numaddr) > hostlen) + return ENI_MEMORY; + strcpy(host, numaddr); + } else { #ifdef INET6 - hp = getipnodebyaddr(addr, afd->a_addrlen, afd->a_af, &h_error); + hp = getipnodebyaddr(addr, afd->a_addrlen, afd->a_af, &h_error); #else - hp = gethostbyaddr(addr, afd->a_addrlen, afd->a_af); - h_error = h_errno; + hp = gethostbyaddr(addr, afd->a_addrlen, afd->a_af); + h_error = h_errno; #endif - if (hp) { - if (flags & NI_NOFQDN) { - p = strchr(hp->h_name, '.'); - if (p) *p = '\0'; - } - if (strlen(hp->h_name) + 1 > hostlen) { + if (hp) { + if (flags & NI_NOFQDN) { + p = strchr(hp->h_name, '.'); + if (p) *p = '\0'; + } + if (strlen(hp->h_name) + 1 > hostlen) { #ifdef INET6 - freehostent(hp); + freehostent(hp); #endif - return ENI_MEMORY; - } - strcpy(host, hp->h_name); + return ENI_MEMORY; + } + strcpy(host, hp->h_name); #ifdef INET6 - freehostent(hp); + freehostent(hp); #endif - } else { - if (flags & NI_NAMEREQD) - return ENI_NOHOSTNAME; - if (inet_ntop(afd->a_af, addr, numaddr, sizeof(numaddr)) - == NULL) - return ENI_NOHOSTNAME; - if (strlen(numaddr) > hostlen) - return ENI_MEMORY; - strcpy(host, numaddr); - } - } - return SUCCESS; + } else { + if (flags & NI_NAMEREQD) + return ENI_NOHOSTNAME; + if (inet_ntop(afd->a_af, addr, numaddr, sizeof(numaddr)) + == NULL) + return ENI_NOHOSTNAME; + if (strlen(numaddr) > hostlen) + return ENI_MEMORY; + strcpy(host, numaddr); + } + } + return SUCCESS; } diff --git a/ext/socket/ifaddr.c b/ext/socket/ifaddr.c index 1da259bd6f..ab163dcc8f 100644 --- a/ext/socket/ifaddr.c +++ b/ext/socket/ifaddr.c @@ -104,7 +104,7 @@ rsock_getifaddrs(void) rb_sys_fail("getifaddrs"); if (!ifaddrs) { - return rb_ary_new(); + return rb_ary_new(); } numifaddrs = 0; @@ -128,9 +128,9 @@ rsock_getifaddrs(void) result = rb_ary_new2(numifaddrs); rb_ary_push(result, addr); for (i = 1; i < numifaddrs; i++) { - addr = TypedData_Wrap_Struct(rb_cSockIfaddr, &ifaddr_type, &root->ary[i]); - root->refcount++; - rb_ary_push(result, addr); + addr = TypedData_Wrap_Struct(rb_cSockIfaddr, &ifaddr_type, &root->ary[i]); + root->refcount++; + rb_ary_push(result, addr); } return result; diff --git a/ext/socket/init.c b/ext/socket/init.c index 359696e626..0cff3d6794 100644 --- a/ext/socket/init.c +++ b/ext/socket/init.c @@ -41,7 +41,7 @@ rsock_raise_socket_error(const char *reason, int error) #ifdef EAI_SYSTEM int e; if (error == EAI_SYSTEM && (e = errno) != 0) - rb_syserr_fail(e, reason); + rb_syserr_fail(e, reason); #endif #ifdef _WIN32 rb_encoding *enc = rb_default_internal_encoding(); @@ -71,7 +71,7 @@ rsock_init_sock(VALUE sock, int fd) fp->mode = FMODE_READWRITE|FMODE_DUPLEX; rb_io_ascii8bit_binmode(sock); if (rsock_do_not_reverse_lookup) { - fp->mode |= FMODE_NOREVLOOKUP; + fp->mode |= FMODE_NOREVLOOKUP; } rb_io_synchronized(fp); @@ -85,7 +85,7 @@ rsock_sendto_blocking(void *data) VALUE mesg = arg->mesg; ssize_t ret; do_write_retry(sendto(arg->fd, RSTRING_PTR(mesg), RSTRING_LEN(mesg), - arg->flags, arg->to, arg->tolen)); + arg->flags, arg->to, arg->tolen)); return (VALUE)ret; } @@ -96,7 +96,7 @@ rsock_send_blocking(void *data) VALUE mesg = arg->mesg; ssize_t ret; do_write_retry(send(arg->fd, RSTRING_PTR(mesg), RSTRING_LEN(mesg), - arg->flags)); + arg->flags)); return (VALUE)ret; } @@ -132,9 +132,9 @@ rsock_strbuf(VALUE str, long buflen) StringValue(str); len = RSTRING_LEN(str); if (len >= buflen) { - rb_str_modify(str); + rb_str_modify(str); } else { - rb_str_modify_expand(str, buflen - len); + rb_str_modify_expand(str, buflen - len); } return str; } @@ -197,32 +197,32 @@ rsock_s_recvfrom(VALUE socket, int argc, VALUE *argv, enum sock_recv_type from) rb_str_set_len(str, slen); switch (from) { case RECV_RECV: - return str; + return str; case RECV_IP: #if 0 - if (arg.alen != sizeof(struct sockaddr_in)) { - rb_raise(rb_eTypeError, "sockaddr size differs - should not happen"); - } + if (arg.alen != sizeof(struct sockaddr_in)) { + rb_raise(rb_eTypeError, "sockaddr size differs - should not happen"); + } #endif - if (arg.alen && arg.alen != sizeof(arg.buf)) /* OSX doesn't return a from result for connection-oriented sockets */ - return rb_assoc_new(str, rsock_ipaddr(&arg.buf.addr, arg.alen, fptr->mode & FMODE_NOREVLOOKUP)); - else - return rb_assoc_new(str, Qnil); + if (arg.alen && arg.alen != sizeof(arg.buf)) /* OSX doesn't return a from result for connection-oriented sockets */ + return rb_assoc_new(str, rsock_ipaddr(&arg.buf.addr, arg.alen, fptr->mode & FMODE_NOREVLOOKUP)); + else + return rb_assoc_new(str, Qnil); #ifdef HAVE_SYS_UN_H case RECV_UNIX: return rb_assoc_new(str, rsock_unixaddr(&arg.buf.un, arg.alen)); #endif case RECV_SOCKET: - return rb_assoc_new(str, rsock_io_socket_addrinfo(socket, &arg.buf.addr, arg.alen)); + return rb_assoc_new(str, rsock_io_socket_addrinfo(socket, &arg.buf.addr, arg.alen)); default: - rb_bug("rsock_s_recvfrom called with bad value"); + rb_bug("rsock_s_recvfrom called with bad value"); } } VALUE rsock_s_recvfrom_nonblock(VALUE sock, VALUE len, VALUE flg, VALUE str, - VALUE ex, enum sock_recv_type from) + VALUE ex, enum sock_recv_type from) { rb_io_t *fptr; union_sockaddr buf; @@ -245,14 +245,14 @@ rsock_s_recvfrom_nonblock(VALUE sock, VALUE len, VALUE flg, VALUE str, GetOpenFile(sock, fptr); if (rb_io_read_pending(fptr)) { - rb_raise(rb_eIOError, "recvfrom for buffered IO"); + rb_raise(rb_eIOError, "recvfrom for buffered IO"); } fd = fptr->fd; rb_io_check_closed(fptr); if (!MSG_DONTWAIT_RELIABLE) - rb_io_set_nonblock(fptr); + rb_io_set_nonblock(fptr); len0 = alen; slen = recvfrom(fd, RSTRING_PTR(str), buflen, flags, &buf.addr, &alen); @@ -260,20 +260,20 @@ rsock_s_recvfrom_nonblock(VALUE sock, VALUE len, VALUE flg, VALUE str, alen = len0; if (slen < 0) { - int e = errno; - switch (e) { - case EAGAIN: + int e = errno; + switch (e) { + case EAGAIN: #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN - case EWOULDBLOCK: + case EWOULDBLOCK: #endif if (ex == Qfalse) - return sym_wait_readable; + return sym_wait_readable; rb_readwrite_syserr_fail(RB_IO_WAIT_READABLE, e, "recvfrom(2) would block"); - } - rb_syserr_fail(e, "recvfrom(2)"); + } + rb_syserr_fail(e, "recvfrom(2)"); } if (slen != RSTRING_LEN(str)) { - rb_str_set_len(str, slen); + rb_str_set_len(str, slen); } switch (from) { case RECV_RECV: @@ -324,31 +324,31 @@ rsock_read_nonblock(VALUE sock, VALUE length, VALUE buf, VALUE ex) GetOpenFile(sock, fptr); if (len == 0) { - rb_str_set_len(str, 0); - return str; + rb_str_set_len(str, 0); + return str; } ptr = RSTRING_PTR(str); n = read_buffered_data(ptr, len, fptr); if (n <= 0) { - n = (long)recv(fptr->fd, ptr, len, MSG_DONTWAIT); - if (n < 0) { - int e = errno; - if ((e == EWOULDBLOCK || e == EAGAIN)) { - if (ex == Qfalse) return sym_wait_readable; - rb_readwrite_syserr_fail(RB_IO_WAIT_READABLE, - e, "read would block"); - } - rb_syserr_fail_path(e, fptr->pathv); - } + n = (long)recv(fptr->fd, ptr, len, MSG_DONTWAIT); + if (n < 0) { + int e = errno; + if ((e == EWOULDBLOCK || e == EAGAIN)) { + if (ex == Qfalse) return sym_wait_readable; + rb_readwrite_syserr_fail(RB_IO_WAIT_READABLE, + e, "read would block"); + } + rb_syserr_fail_path(e, fptr->pathv); + } } if (n != RSTRING_LEN(str)) { - rb_str_modify(str); - rb_str_set_len(str, n); + rb_str_modify(str); + rb_str_set_len(str, n); } if (n == 0) { - if (ex == Qfalse) return Qnil; - rb_eof_error(); + if (ex == Qfalse) return Qnil; + rb_eof_error(); } return str; @@ -362,7 +362,7 @@ rsock_write_nonblock(VALUE sock, VALUE str, VALUE ex) long n; if (!RB_TYPE_P(str, T_STRING)) - str = rb_obj_as_string(str); + str = rb_obj_as_string(str); sock = rb_io_get_write_io(sock); GetOpenFile(sock, fptr); @@ -374,7 +374,7 @@ rsock_write_nonblock(VALUE sock, VALUE str, VALUE ex) * are not userspace-buffered in Ruby by default. */ if (fptr->wbuf.len > 0) { - rb_io_flush(sock); + rb_io_flush(sock); } #ifdef __APPLE__ @@ -382,19 +382,19 @@ rsock_write_nonblock(VALUE sock, VALUE str, VALUE ex) #endif n = (long)send(fptr->fd, RSTRING_PTR(str), RSTRING_LEN(str), MSG_DONTWAIT); if (n < 0) { - int e = errno; + int e = errno; #ifdef __APPLE__ - if (e == EPROTOTYPE) { - goto again; - } + if (e == EPROTOTYPE) { + goto again; + } #endif - if (e == EWOULDBLOCK || e == EAGAIN) { - if (ex == Qfalse) return sym_wait_writable; - rb_readwrite_syserr_fail(RB_IO_WAIT_WRITABLE, e, - "write would block"); - } - rb_syserr_fail_path(e, fptr->pathv); + if (e == EWOULDBLOCK || e == EAGAIN) { + if (ex == Qfalse) return sym_wait_writable; + rb_readwrite_syserr_fail(RB_IO_WAIT_WRITABLE, e, + "write would block"); + } + rb_syserr_fail_path(e, fptr->pathv); } return LONG2FIX(n); @@ -497,11 +497,11 @@ wait_connectable(int fd, struct timeval *timeout) * interrupted connect() */ - /* when the connection timed out, no errno is set and revents is 0. */ - if (timeout && revents == 0) { - errno = ETIMEDOUT; - return -1; - } + /* when the connection timed out, no errno is set and revents is 0. */ + if (timeout && revents == 0) { + errno = ETIMEDOUT; + return -1; + } case EINTR: #ifdef ERESTART case ERESTART: @@ -516,7 +516,7 @@ wait_connectable(int fd, struct timeval *timeout) #ifdef EISCONN case EISCONN: #endif - return 0; /* success */ + return 0; /* success */ default: /* likely (but not limited to): ECONNREFUSED, ETIMEDOUT, EHOSTUNREACH */ errno = sockerr; @@ -634,27 +634,27 @@ cloexec_accept(int socket, struct sockaddr *address, socklen_t *address_len) VALUE rsock_s_accept_nonblock(VALUE klass, VALUE ex, rb_io_t *fptr, - struct sockaddr *sockaddr, socklen_t *len) + struct sockaddr *sockaddr, socklen_t *len) { int fd2; rb_io_set_nonblock(fptr); fd2 = cloexec_accept(fptr->fd, (struct sockaddr*)sockaddr, len); if (fd2 < 0) { - int e = errno; - switch (e) { - case EAGAIN: + int e = errno; + switch (e) { + case EAGAIN: #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN - case EWOULDBLOCK: + case EWOULDBLOCK: #endif - case ECONNABORTED: + case ECONNABORTED: #if defined EPROTO - case EPROTO: + case EPROTO: #endif if (ex == Qfalse) - return sym_wait_readable; + return sym_wait_readable; rb_readwrite_syserr_fail(RB_IO_WAIT_READABLE, e, "accept(2) would block"); - } + } rb_syserr_fail(e, "accept(2)"); } rb_update_max_fd(fd2); @@ -730,11 +730,11 @@ rsock_getfamily(rb_io_t *fptr) if (cached) { switch (cached) { #ifdef AF_UNIX - case FMODE_UNIX: return AF_UNIX; + case FMODE_UNIX: return AF_UNIX; #endif - case FMODE_INET: return AF_INET; - case FMODE_INET6: return AF_INET6; - } + case FMODE_INET: return AF_INET; + case FMODE_INET6: return AF_INET6; + } } ss.addr.sa_family = AF_UNSPEC; diff --git a/ext/socket/ipsocket.c b/ext/socket/ipsocket.c index b5cdc60080..0c13620258 100644 --- a/ext/socket/ipsocket.c +++ b/ext/socket/ipsocket.c @@ -14,8 +14,8 @@ struct inetsock_arg { VALUE sock; struct { - VALUE host, serv; - struct rb_addrinfo *res; + VALUE host, serv; + struct rb_addrinfo *res; } remote, local; int type; int fd; @@ -28,15 +28,15 @@ inetsock_cleanup(VALUE v) { struct inetsock_arg *arg = (void *)v; if (arg->remote.res) { - rb_freeaddrinfo(arg->remote.res); - arg->remote.res = 0; + rb_freeaddrinfo(arg->remote.res); + arg->remote.res = 0; } if (arg->local.res) { - rb_freeaddrinfo(arg->local.res); - arg->local.res = 0; + rb_freeaddrinfo(arg->local.res); + arg->local.res = 0; } if (arg->fd >= 0) { - close(arg->fd); + close(arg->fd); } return Qnil; } @@ -61,8 +61,8 @@ init_inetsock_internal(VALUE v) } arg->remote.res = rsock_addrinfo(arg->remote.host, arg->remote.serv, - family, SOCK_STREAM, - (type == INET_SERVER) ? AI_PASSIVE : 0); + family, SOCK_STREAM, + (type == INET_SERVER) ? AI_PASSIVE : 0); /* @@ -70,15 +70,15 @@ init_inetsock_internal(VALUE v) */ if (type != INET_SERVER && (!NIL_P(arg->local.host) || !NIL_P(arg->local.serv))) { - arg->local.res = rsock_addrinfo(arg->local.host, arg->local.serv, - family, SOCK_STREAM, 0); + arg->local.res = rsock_addrinfo(arg->local.host, arg->local.serv, + family, SOCK_STREAM, 0); } arg->fd = fd = -1; for (res = arg->remote.res->ai; res; res = res->ai_next) { #if !defined(INET6) && defined(AF_INET6) - if (res->ai_family == AF_INET6) - continue; + if (res->ai_family == AF_INET6) + continue; #endif lres = NULL; if (arg->local.res) { @@ -94,73 +94,73 @@ init_inetsock_internal(VALUE v) lres = arg->local.res->ai; } } - status = rsock_socket(res->ai_family,res->ai_socktype,res->ai_protocol); - syscall = "socket(2)"; - fd = status; - if (fd < 0) { - error = errno; - continue; - } - arg->fd = fd; - if (type == INET_SERVER) { + status = rsock_socket(res->ai_family,res->ai_socktype,res->ai_protocol); + syscall = "socket(2)"; + fd = status; + if (fd < 0) { + error = errno; + continue; + } + arg->fd = fd; + if (type == INET_SERVER) { #if !defined(_WIN32) && !defined(__CYGWIN__) - status = 1; - setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, - (char*)&status, (socklen_t)sizeof(status)); + status = 1; + setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, + (char*)&status, (socklen_t)sizeof(status)); #endif - status = bind(fd, res->ai_addr, res->ai_addrlen); - syscall = "bind(2)"; - } - else { - if (lres) { + status = bind(fd, res->ai_addr, res->ai_addrlen); + syscall = "bind(2)"; + } + else { + if (lres) { #if !defined(_WIN32) && !defined(__CYGWIN__) status = 1; setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&status, (socklen_t)sizeof(status)); #endif - status = bind(fd, lres->ai_addr, lres->ai_addrlen); - local = status; - syscall = "bind(2)"; - } + status = bind(fd, lres->ai_addr, lres->ai_addrlen); + local = status; + syscall = "bind(2)"; + } - if (status >= 0) { - status = rsock_connect(fd, res->ai_addr, res->ai_addrlen, - (type == INET_SOCKS), tv); - syscall = "connect(2)"; - } - } + if (status >= 0) { + status = rsock_connect(fd, res->ai_addr, res->ai_addrlen, + (type == INET_SOCKS), tv); + syscall = "connect(2)"; + } + } - if (status < 0) { - error = errno; - close(fd); - arg->fd = fd = -1; - continue; - } else - break; + if (status < 0) { + error = errno; + close(fd); + arg->fd = fd = -1; + continue; + } else + break; } if (status < 0) { - VALUE host, port; + VALUE host, port; - if (local < 0) { - host = arg->local.host; - port = arg->local.serv; - } else { - host = arg->remote.host; - port = arg->remote.serv; - } + if (local < 0) { + host = arg->local.host; + port = arg->local.serv; + } else { + host = arg->remote.host; + port = arg->remote.serv; + } - rsock_syserr_fail_host_port(error, syscall, host, port); + rsock_syserr_fail_host_port(error, syscall, host, port); } arg->fd = -1; if (type == INET_SERVER) { - status = listen(fd, SOMAXCONN); - if (status < 0) { - error = errno; - close(fd); - rb_syserr_fail(error, "listen(2)"); - } + status = listen(fd, SOMAXCONN); + if (status < 0) { + error = errno; + close(fd); + rb_syserr_fail(error, "listen(2)"); + } } /* create new instance */ @@ -169,8 +169,8 @@ init_inetsock_internal(VALUE v) VALUE rsock_init_inetsock(VALUE sock, VALUE remote_host, VALUE remote_serv, - VALUE local_host, VALUE local_serv, int type, - VALUE resolv_timeout, VALUE connect_timeout) + VALUE local_host, VALUE local_serv, int type, + VALUE resolv_timeout, VALUE connect_timeout) { struct inetsock_arg arg; arg.sock = sock; @@ -185,7 +185,7 @@ rsock_init_inetsock(VALUE sock, VALUE remote_host, VALUE remote_serv, arg.resolv_timeout = resolv_timeout; arg.connect_timeout = connect_timeout; return rb_ensure(init_inetsock_internal, (VALUE)&arg, - inetsock_cleanup, (VALUE)&arg); + inetsock_cleanup, (VALUE)&arg); } static ID id_numeric, id_hostname; @@ -201,11 +201,11 @@ rsock_revlookup_flag(VALUE revlookup, int *norevlookup) case Qfalse: return_norevlookup(1); case Qnil: break; default: - Check_Type(revlookup, T_SYMBOL); - id = SYM2ID(revlookup); - if (id == id_numeric) return_norevlookup(1); - if (id == id_hostname) return_norevlookup(0); - rb_raise(rb_eArgError, "invalid reverse_lookup flag: :%s", rb_id2name(id)); + Check_Type(revlookup, T_SYMBOL); + id = SYM2ID(revlookup); + if (id == id_numeric) return_norevlookup(1); + if (id == id_hostname) return_norevlookup(0); + rb_raise(rb_eArgError, "invalid reverse_lookup flag: :%s", rb_id2name(id)); } return 0; #undef return_norevlookup @@ -226,24 +226,24 @@ ip_inspect(VALUE sock) socklen_t len = (socklen_t)sizeof addr; ID id; if (fptr && fptr->fd >= 0 && - getsockname(fptr->fd, &addr.addr, &len) >= 0 && - (id = rsock_intern_family(addr.addr.sa_family)) != 0) { - VALUE family = rb_id2str(id); - char hbuf[1024], pbuf[1024]; - long slen = RSTRING_LEN(str); - const char last = (slen > 1 && RSTRING_PTR(str)[slen - 1] == '>') ? - (--slen, '>') : 0; - str = rb_str_subseq(str, 0, slen); - rb_str_cat_cstr(str, ", "); - rb_str_append(str, family); - if (!rb_getnameinfo(&addr.addr, len, hbuf, sizeof(hbuf), - pbuf, sizeof(pbuf), NI_NUMERICHOST | NI_NUMERICSERV)) { - rb_str_cat_cstr(str, ", "); - rb_str_cat_cstr(str, hbuf); - rb_str_cat_cstr(str, ", "); - rb_str_cat_cstr(str, pbuf); - } - if (last) rb_str_cat(str, &last, 1); + getsockname(fptr->fd, &addr.addr, &len) >= 0 && + (id = rsock_intern_family(addr.addr.sa_family)) != 0) { + VALUE family = rb_id2str(id); + char hbuf[1024], pbuf[1024]; + long slen = RSTRING_LEN(str); + const char last = (slen > 1 && RSTRING_PTR(str)[slen - 1] == '>') ? + (--slen, '>') : 0; + str = rb_str_subseq(str, 0, slen); + rb_str_cat_cstr(str, ", "); + rb_str_append(str, family); + if (!rb_getnameinfo(&addr.addr, len, hbuf, sizeof(hbuf), + pbuf, sizeof(pbuf), NI_NUMERICHOST | NI_NUMERICSERV)) { + rb_str_cat_cstr(str, ", "); + rb_str_cat_cstr(str, hbuf); + rb_str_cat_cstr(str, ", "); + rb_str_cat_cstr(str, pbuf); + } + if (last) rb_str_cat(str, &last, 1); } return str; } @@ -282,9 +282,9 @@ ip_addr(int argc, VALUE *argv, VALUE sock) GetOpenFile(sock, fptr); if (argc < 1 || !rsock_revlookup_flag(argv[0], &norevlookup)) - norevlookup = fptr->mode & FMODE_NOREVLOOKUP; + norevlookup = fptr->mode & FMODE_NOREVLOOKUP; if (getsockname(fptr->fd, &addr.addr, &len) < 0) - rb_sys_fail("getsockname(2)"); + rb_sys_fail("getsockname(2)"); return rsock_ipaddr(&addr.addr, len, norevlookup); } @@ -323,9 +323,9 @@ ip_peeraddr(int argc, VALUE *argv, VALUE sock) GetOpenFile(sock, fptr); if (argc < 1 || !rsock_revlookup_flag(argv[0], &norevlookup)) - norevlookup = fptr->mode & FMODE_NOREVLOOKUP; + norevlookup = fptr->mode & FMODE_NOREVLOOKUP; if (getpeername(fptr->fd, &addr.addr, &len) < 0) - rb_sys_fail("getpeername(2)"); + rb_sys_fail("getpeername(2)"); return rsock_ipaddr(&addr.addr, len, norevlookup); } diff --git a/ext/socket/option.c b/ext/socket/option.c index 4b33b3f1d3..2dbe6379c4 100644 --- a/ext/socket/option.c +++ b/ext/socket/option.c @@ -31,7 +31,7 @@ VALUE rb_cSockOpt; ((len) == (size) ? \ (void)0 : \ rb_raise(rb_eTypeError, "size differ. expected as "#size"=%d but %ld", \ - (int)size, (long)(len))) + (int)size, (long)(len))) static VALUE sockopt_pack_byte(VALUE value) @@ -309,7 +309,7 @@ sockopt_bool(VALUE self) StringValue(data); len = RSTRING_LEN(data); if (len == 1) { - return *RSTRING_PTR(data) == 0 ? Qfalse : Qtrue; + return *RSTRING_PTR(data) == 0 ? Qfalse : Qtrue; } check_size(len, sizeof(int)); memcpy((char*)&i, RSTRING_PTR(data), len); @@ -420,7 +420,7 @@ sockopt_ipv4_multicast_loop(VALUE self) #if defined(IPPROTO_IP) && defined(IP_MULTICAST_LOOP) if (family == AF_INET && level == IPPROTO_IP && optname == IP_MULTICAST_LOOP) { - return XCAT(sockopt_,TYPE_IP_MULTICAST_LOOP)(self); + return XCAT(sockopt_,TYPE_IP_MULTICAST_LOOP)(self); } #endif rb_raise(rb_eTypeError, "ipv4_multicast_loop socket option expected"); @@ -471,7 +471,7 @@ sockopt_ipv4_multicast_ttl(VALUE self) #if defined(IPPROTO_IP) && defined(IP_MULTICAST_TTL) if (family == AF_INET && level == IPPROTO_IP && optname == IP_MULTICAST_TTL) { - return XCAT(sockopt_,TYPE_IP_MULTICAST_TTL)(self); + return XCAT(sockopt_,TYPE_IP_MULTICAST_TTL)(self); } #endif rb_raise(rb_eTypeError, "ipv4_multicast_ttl socket option expected"); @@ -657,8 +657,8 @@ inet_ntop(int af, const void *addr, char *numaddr, size_t numaddr_len) #else unsigned long x = ntohl(*(unsigned long*)addr); snprintf(numaddr, numaddr_len, "%d.%d.%d.%d", - (int) (x>>24) & 0xff, (int) (x>>16) & 0xff, - (int) (x>> 8) & 0xff, (int) (x>> 0) & 0xff); + (int) (x>>24) & 0xff, (int) (x>>16) & 0xff, + (int) (x>> 8) & 0xff, (int) (x>> 0) & 0xff); #endif return numaddr; } @@ -1059,16 +1059,16 @@ inspect_tcp_info(int level, int optname, VALUE data, VALUE ret) rb_str_catf(ret, " fackets=%u", s.tcpi_fackets); #endif #ifdef HAVE_STRUCT_TCP_INFO_TCPI_LAST_DATA_SENT - inspect_tcpi_last_data_sent(ret, s.tcpi_last_data_sent); + inspect_tcpi_last_data_sent(ret, s.tcpi_last_data_sent); #endif #ifdef HAVE_STRUCT_TCP_INFO_TCPI_LAST_ACK_SENT - inspect_tcpi_last_ack_sent(ret, s.tcpi_last_ack_sent); + inspect_tcpi_last_ack_sent(ret, s.tcpi_last_ack_sent); #endif #ifdef HAVE_STRUCT_TCP_INFO_TCPI_LAST_DATA_RECV - inspect_tcpi_last_data_recv(ret, s.tcpi_last_data_recv); + inspect_tcpi_last_data_recv(ret, s.tcpi_last_data_recv); #endif #ifdef HAVE_STRUCT_TCP_INFO_TCPI_LAST_ACK_RECV - inspect_tcpi_last_ack_recv(ret, s.tcpi_last_ack_recv); + inspect_tcpi_last_ack_recv(ret, s.tcpi_last_ack_recv); #endif #ifdef HAVE_STRUCT_TCP_INFO_TCPI_PMTU rb_str_catf(ret, " pmtu=%u", s.tcpi_pmtu); @@ -1077,10 +1077,10 @@ inspect_tcp_info(int level, int optname, VALUE data, VALUE ret) rb_str_catf(ret, " rcv_ssthresh=%u", s.tcpi_rcv_ssthresh); #endif #ifdef HAVE_STRUCT_TCP_INFO_TCPI_RTT - inspect_tcpi_rtt(ret, s.tcpi_rtt); + inspect_tcpi_rtt(ret, s.tcpi_rtt); #endif #ifdef HAVE_STRUCT_TCP_INFO_TCPI_RTTVAR - inspect_tcpi_rttvar(ret, s.tcpi_rttvar); + inspect_tcpi_rttvar(ret, s.tcpi_rttvar); #endif #ifdef HAVE_STRUCT_TCP_INFO_TCPI_SND_SSTHRESH rb_str_catf(ret, " snd_ssthresh=%u", s.tcpi_snd_ssthresh); @@ -1150,7 +1150,7 @@ inspect_peercred(int level, int optname, VALUE data, VALUE ret) RUBY_SOCK_PEERCRED cred; memcpy(&cred, RSTRING_PTR(data), sizeof(RUBY_SOCK_PEERCRED)); rb_str_catf(ret, " pid=%u euid=%u egid=%u", - (unsigned)cred.pid, (unsigned)cred.uid, (unsigned)cred.gid); + (unsigned)cred.pid, (unsigned)cred.uid, (unsigned)cred.gid); rb_str_cat2(ret, " (ucred)"); return 1; } @@ -1171,14 +1171,14 @@ inspect_local_peercred(int level, int optname, VALUE data, VALUE ret) return 0; rb_str_catf(ret, " version=%u", cred.cr_version); rb_str_catf(ret, " euid=%u", cred.cr_uid); - if (cred.cr_ngroups) { - int i; - const char *sep = " groups="; - for (i = 0; i < cred.cr_ngroups; i++) { - rb_str_catf(ret, "%s%u", sep, cred.cr_groups[i]); - sep = ","; - } - } + if (cred.cr_ngroups) { + int i; + const char *sep = " groups="; + for (i = 0; i < cred.cr_ngroups; i++) { + rb_str_catf(ret, "%s%u", sep, cred.cr_groups[i]); + sep = ","; + } + } rb_str_cat2(ret, " (xucred)"); return 1; } @@ -1216,42 +1216,42 @@ sockopt_inspect(VALUE self) family_id = rsock_intern_family_noprefix(family); if (family_id) - rb_str_catf(ret, " %s", rb_id2name(family_id)); + rb_str_catf(ret, " %s", rb_id2name(family_id)); else rb_str_catf(ret, " family:%d", family); if (level == SOL_SOCKET) { rb_str_cat2(ret, " SOCKET"); - optname_id = rsock_intern_so_optname(optname); - if (optname_id) - rb_str_catf(ret, " %s", rb_id2name(optname_id)); - else - rb_str_catf(ret, " optname:%d", optname); + optname_id = rsock_intern_so_optname(optname); + if (optname_id) + rb_str_catf(ret, " %s", rb_id2name(optname_id)); + else + rb_str_catf(ret, " optname:%d", optname); } #ifdef HAVE_SYS_UN_H else if (family == AF_UNIX) { - rb_str_catf(ret, " level:%d", level); + rb_str_catf(ret, " level:%d", level); - optname_id = rsock_intern_local_optname(optname); - if (optname_id) - rb_str_catf(ret, " %s", rb_id2name(optname_id)); - else - rb_str_catf(ret, " optname:%d", optname); + optname_id = rsock_intern_local_optname(optname); + if (optname_id) + rb_str_catf(ret, " %s", rb_id2name(optname_id)); + else + rb_str_catf(ret, " optname:%d", optname); } #endif else if (IS_IP_FAMILY(family)) { - level_id = rsock_intern_iplevel(level); - if (level_id) - rb_str_catf(ret, " %s", rb_id2name(level_id)); - else - rb_str_catf(ret, " level:%d", level); + level_id = rsock_intern_iplevel(level); + if (level_id) + rb_str_catf(ret, " %s", rb_id2name(level_id)); + else + rb_str_catf(ret, " level:%d", level); - v = optname_to_sym(level, optname); - if (SYMBOL_P(v)) - rb_str_catf(ret, " %"PRIsVALUE, rb_sym2str(v)); - else - rb_str_catf(ret, " optname:%d", optname); + v = optname_to_sym(level, optname); + if (SYMBOL_P(v)) + rb_str_catf(ret, " %"PRIsVALUE, rb_sym2str(v)); + else + rb_str_catf(ret, " optname:%d", optname); } else { rb_str_catf(ret, " level:%d", level); diff --git a/ext/socket/raddrinfo.c b/ext/socket/raddrinfo.c index 8772572d2e..b914aa6520 100644 --- a/ext/socket/raddrinfo.c +++ b/ext/socket/raddrinfo.c @@ -24,28 +24,28 @@ static const int lookup_order_table[] = { static int ruby_getaddrinfo(const char *nodename, const char *servname, - const struct addrinfo *hints, struct addrinfo **res) + const struct addrinfo *hints, struct addrinfo **res) { struct addrinfo tmp_hints; int i, af, error; if (hints->ai_family != PF_UNSPEC) { - return getaddrinfo(nodename, servname, hints, res); + return getaddrinfo(nodename, servname, hints, res); } for (i = 0; i < LOOKUP_ORDERS; i++) { - af = lookup_order_table[i]; - MEMCPY(&tmp_hints, hints, struct addrinfo, 1); - tmp_hints.ai_family = af; - error = getaddrinfo(nodename, servname, &tmp_hints, res); - if (error) { - if (tmp_hints.ai_family == PF_UNSPEC) { - break; - } - } - else { - break; - } + af = lookup_order_table[i]; + MEMCPY(&tmp_hints, hints, struct addrinfo, 1); + tmp_hints.ai_family = af; + error = getaddrinfo(nodename, servname, &tmp_hints, res); + if (error) { + if (tmp_hints.ai_family == PF_UNSPEC) { + break; + } + } + else { + break; + } } return error; @@ -56,17 +56,17 @@ ruby_getaddrinfo(const char *nodename, const char *servname, #if defined(_AIX) static int ruby_getaddrinfo__aix(const char *nodename, const char *servname, - const struct addrinfo *hints, struct addrinfo **res) + const struct addrinfo *hints, struct addrinfo **res) { int error = getaddrinfo(nodename, servname, hints, res); struct addrinfo *r; if (error) - return error; + return error; for (r = *res; r != NULL; r = r->ai_next) { - if (r->ai_addr->sa_family == 0) - r->ai_addr->sa_family = r->ai_family; - if (r->ai_addr->sa_len == 0) - r->ai_addr->sa_len = r->ai_addrlen; + if (r->ai_addr->sa_family == 0) + r->ai_addr->sa_family = r->ai_family; + if (r->ai_addr->sa_len == 0) + r->ai_addr->sa_len = r->ai_addrlen; } return 0; } @@ -74,21 +74,21 @@ ruby_getaddrinfo__aix(const char *nodename, const char *servname, #define getaddrinfo(node,serv,hints,res) ruby_getaddrinfo__aix((node),(serv),(hints),(res)) static int ruby_getnameinfo__aix(const struct sockaddr *sa, size_t salen, - char *host, size_t hostlen, - char *serv, size_t servlen, int flags) + char *host, size_t hostlen, + char *serv, size_t servlen, int flags) { struct sockaddr_in6 *sa6; u_int32_t *a6; if (sa->sa_family == AF_INET6) { - sa6 = (struct sockaddr_in6 *)sa; - a6 = sa6->sin6_addr.u6_addr.u6_addr32; + sa6 = (struct sockaddr_in6 *)sa; + a6 = sa6->sin6_addr.u6_addr.u6_addr32; - if (a6[0] == 0 && a6[1] == 0 && a6[2] == 0 && a6[3] == 0) { - strncpy(host, "::", hostlen); - snprintf(serv, servlen, "%d", sa6->sin6_port); - return 0; - } + if (a6[0] == 0 && a6[1] == 0 && a6[2] == 0 && a6[3] == 0) { + strncpy(host, "::", hostlen); + snprintf(serv, servlen, "%d", sa6->sin6_port); + return 0; + } } return getnameinfo(sa, salen, host, hostlen, serv, servlen, flags); } @@ -102,7 +102,7 @@ static int str_is_number(const char *); #if defined(__APPLE__) static int ruby_getaddrinfo__darwin(const char *nodename, const char *servname, - const struct addrinfo *hints, struct addrinfo **res) + const struct addrinfo *hints, struct addrinfo **res) { /* fix [ruby-core:29427] */ const char *tmp_servname; @@ -112,12 +112,12 @@ ruby_getaddrinfo__darwin(const char *nodename, const char *servname, tmp_servname = servname; MEMCPY(&tmp_hints, hints, struct addrinfo, 1); if (nodename && servname) { - if (str_is_number(tmp_servname) && atoi(servname) == 0) { - tmp_servname = NULL; + if (str_is_number(tmp_servname) && atoi(servname) == 0) { + tmp_servname = NULL; #ifdef AI_NUMERICSERV - if (tmp_hints.ai_flags) tmp_hints.ai_flags &= ~AI_NUMERICSERV; + if (tmp_hints.ai_flags) tmp_hints.ai_flags &= ~AI_NUMERICSERV; #endif - } + } } error = getaddrinfo(nodename, tmp_servname, &tmp_hints, res); @@ -193,7 +193,7 @@ nogvl_getaddrinfo(void *arg) * it cause getaddrinfo to return EAI_SYSTEM/ENOENT. [ruby-list:49420] */ if (ret == EAI_SYSTEM && errno == ENOENT) - ret = EAI_NONAME; + ret = EAI_NONAME; #endif return (void *)(VALUE)ret; } @@ -212,15 +212,15 @@ numeric_getaddrinfo(const char *node, const char *service, int port; if (node && parse_numeric_port(service, &port)) { - static const struct { - int socktype; - int protocol; - } list[] = { - { SOCK_STREAM, IPPROTO_TCP }, - { SOCK_DGRAM, IPPROTO_UDP }, - { SOCK_RAW, 0 } - }; - struct addrinfo *ai = NULL; + static const struct { + int socktype; + int protocol; + } list[] = { + { SOCK_STREAM, IPPROTO_TCP }, + { SOCK_DGRAM, IPPROTO_UDP }, + { SOCK_RAW, 0 } + }; + struct addrinfo *ai = NULL; int hint_family = hints ? hints->ai_family : PF_UNSPEC; int hint_socktype = hints ? hints->ai_socktype : 0; int hint_protocol = hints ? hints->ai_protocol : 0; @@ -319,9 +319,9 @@ nogvl_getnameinfo(void *arg) { struct getnameinfo_arg *ptr = arg; return (void *)(VALUE)getnameinfo(ptr->sa, ptr->salen, - ptr->host, (socklen_t)ptr->hostlen, - ptr->serv, (socklen_t)ptr->servlen, - ptr->flags); + ptr->host, (socklen_t)ptr->hostlen, + ptr->serv, (socklen_t)ptr->servlen, + ptr->flags); } #endif @@ -587,7 +587,7 @@ rsock_fd_family(int fd) if (fd < 0 || getsockname(fd, &sa, &sa_len) != 0 || (size_t)sa_len < offsetof(struct sockaddr, sa_family) + sizeof(sa.sa_family)) { - return AF_UNSPEC; + return AF_UNSPEC; } return sa.sa_family; } @@ -677,19 +677,19 @@ rsock_unix_sockaddr_len(VALUE path) { #ifdef __linux__ if (RSTRING_LEN(path) == 0) { - /* autobind; see unix(7) for details. */ - return (socklen_t) sizeof(sa_family_t); + /* autobind; see unix(7) for details. */ + return (socklen_t) sizeof(sa_family_t); } else if (RSTRING_PTR(path)[0] == '\0') { - /* abstract namespace; see unix(7) for details. */ + /* abstract namespace; see unix(7) for details. */ if (SOCKLEN_MAX - offsetof(struct sockaddr_un, sun_path) < (size_t)RSTRING_LEN(path)) rb_raise(rb_eArgError, "Linux abstract socket too long"); - return (socklen_t) offsetof(struct sockaddr_un, sun_path) + - RSTRING_SOCKLEN(path); + return (socklen_t) offsetof(struct sockaddr_un, sun_path) + + RSTRING_SOCKLEN(path); } else { #endif - return (socklen_t) sizeof(struct sockaddr_un); + return (socklen_t) sizeof(struct sockaddr_un); #ifdef __linux__ } #endif @@ -727,7 +727,7 @@ make_hostent_internal(VALUE v) rb_ary_push(ary, rb_str_new2(hostp)); if (addr->ai_canonname && strlen(addr->ai_canonname) < NI_MAXHOST && - (h = gethostbyname(addr->ai_canonname))) { + (h = gethostbyname(addr->ai_canonname))) { names = rb_ary_new(); if (h->h_aliases != NULL) { for (pch = h->h_aliases; *pch; pch++) { @@ -875,19 +875,19 @@ call_getaddrinfo(VALUE node, VALUE service, hints.ai_family = NIL_P(family) ? PF_UNSPEC : rsock_family_arg(family); if (!NIL_P(socktype)) { - hints.ai_socktype = rsock_socktype_arg(socktype); + hints.ai_socktype = rsock_socktype_arg(socktype); } if (!NIL_P(protocol)) { - hints.ai_protocol = NUM2INT(protocol); + hints.ai_protocol = NUM2INT(protocol); } if (!NIL_P(flags)) { - hints.ai_flags = NUM2INT(flags); + hints.ai_flags = NUM2INT(flags); } res = rsock_getaddrinfo(node, service, &hints, socktype_hack); if (res == NULL) - rb_raise(rb_eSocket, "host not found"); + rb_raise(rb_eSocket, "host not found"); return res; } @@ -1037,7 +1037,7 @@ init_unix_addrinfo(rb_addrinfo_t *rai, VALUE path, int socktype) len = rsock_unix_sockaddr_len(path); init_addrinfo(rai, (struct sockaddr *)&un, len, - PF_UNIX, socktype, 0, Qnil, Qnil); + PF_UNIX, socktype, 0, Qnil, Qnil); } static long @@ -1119,7 +1119,7 @@ addrinfo_initialize(int argc, VALUE *argv, VALUE self) int af; StringValue(afamily); if (rsock_family_to_int(RSTRING_PTR(afamily), RSTRING_LEN(afamily), &af) == -1) - rb_raise(rb_eSocket, "unknown address family: %s", StringValueCStr(afamily)); + rb_raise(rb_eSocket, "unknown address family: %s", StringValueCStr(afamily)); switch (af) { case AF_INET: /* ["AF_INET", 46102, "localhost.localdomain", "127.0.0.1"] */ #ifdef INET6 @@ -1209,45 +1209,45 @@ rsock_inspect_sockaddr(struct sockaddr *sockaddr_arg, socklen_t socklen, VALUE r else { switch (sockaddr->addr.sa_family) { case AF_UNSPEC: - { - rb_str_cat2(ret, "UNSPEC"); + { + rb_str_cat2(ret, "UNSPEC"); break; - } + } case AF_INET: { struct sockaddr_in *addr; int port; - addr = &sockaddr->in; - if ((socklen_t)(((char*)&addr->sin_addr)-(char*)addr+0+1) <= socklen) - rb_str_catf(ret, "%d", ((unsigned char*)&addr->sin_addr)[0]); - else - rb_str_cat2(ret, "?"); - if ((socklen_t)(((char*)&addr->sin_addr)-(char*)addr+1+1) <= socklen) - rb_str_catf(ret, ".%d", ((unsigned char*)&addr->sin_addr)[1]); - else - rb_str_cat2(ret, ".?"); - if ((socklen_t)(((char*)&addr->sin_addr)-(char*)addr+2+1) <= socklen) - rb_str_catf(ret, ".%d", ((unsigned char*)&addr->sin_addr)[2]); - else - rb_str_cat2(ret, ".?"); - if ((socklen_t)(((char*)&addr->sin_addr)-(char*)addr+3+1) <= socklen) - rb_str_catf(ret, ".%d", ((unsigned char*)&addr->sin_addr)[3]); - else - rb_str_cat2(ret, ".?"); + addr = &sockaddr->in; + if ((socklen_t)(((char*)&addr->sin_addr)-(char*)addr+0+1) <= socklen) + rb_str_catf(ret, "%d", ((unsigned char*)&addr->sin_addr)[0]); + else + rb_str_cat2(ret, "?"); + if ((socklen_t)(((char*)&addr->sin_addr)-(char*)addr+1+1) <= socklen) + rb_str_catf(ret, ".%d", ((unsigned char*)&addr->sin_addr)[1]); + else + rb_str_cat2(ret, ".?"); + if ((socklen_t)(((char*)&addr->sin_addr)-(char*)addr+2+1) <= socklen) + rb_str_catf(ret, ".%d", ((unsigned char*)&addr->sin_addr)[2]); + else + rb_str_cat2(ret, ".?"); + if ((socklen_t)(((char*)&addr->sin_addr)-(char*)addr+3+1) <= socklen) + rb_str_catf(ret, ".%d", ((unsigned char*)&addr->sin_addr)[3]); + else + rb_str_cat2(ret, ".?"); - if ((socklen_t)(((char*)&addr->sin_port)-(char*)addr+(int)sizeof(addr->sin_port)) < socklen) { - port = ntohs(addr->sin_port); - if (port) - rb_str_catf(ret, ":%d", port); - } - else { - rb_str_cat2(ret, ":?"); - } - if ((socklen_t)sizeof(struct sockaddr_in) != socklen) - rb_str_catf(ret, " (%d bytes for %d bytes sockaddr_in)", - (int)socklen, - (int)sizeof(struct sockaddr_in)); + if ((socklen_t)(((char*)&addr->sin_port)-(char*)addr+(int)sizeof(addr->sin_port)) < socklen) { + port = ntohs(addr->sin_port); + if (port) + rb_str_catf(ret, ":%d", port); + } + else { + rb_str_cat2(ret, ":?"); + } + if ((socklen_t)sizeof(struct sockaddr_in) != socklen) + rb_str_catf(ret, " (%d bytes for %d bytes sockaddr_in)", + (int)socklen, + (int)sizeof(struct sockaddr_in)); break; } @@ -1398,20 +1398,20 @@ rsock_inspect_sockaddr(struct sockaddr *sockaddr_arg, socklen_t socklen, VALUE r #endif #if defined(AF_LINK) && defined(HAVE_TYPE_STRUCT_SOCKADDR_DL) - /* AF_LINK is defined in 4.4BSD derivations since Net2. - link_ntoa is also defined at Net2. + /* AF_LINK is defined in 4.4BSD derivations since Net2. + link_ntoa is also defined at Net2. However Debian GNU/kFreeBSD defines AF_LINK but don't have link_ntoa. */ case AF_LINK: - { - /* - * Simple implementation using link_ntoa(): - * This doesn't work on Debian GNU/kFreeBSD 6.0.7 (squeeze). + { + /* + * Simple implementation using link_ntoa(): + * This doesn't work on Debian GNU/kFreeBSD 6.0.7 (squeeze). * Also, the format is bit different. - * - * rb_str_catf(ret, "LINK %s", link_ntoa(&sockaddr->dl)); - * break; - */ + * + * rb_str_catf(ret, "LINK %s", link_ntoa(&sockaddr->dl)); + * break; + */ struct sockaddr_dl *addr = &sockaddr->dl; char *np = NULL, *ap = NULL, *endp; int nlen = 0, alen = 0; @@ -1438,14 +1438,14 @@ rsock_inspect_sockaddr(struct sockaddr *sockaddr_arg, socklen_t socklen, VALUE r alen = (int)(endp - ap); } - CATSEP; + CATSEP; if (np) rb_str_catf(ret, "%.*s", nlen, np); else rb_str_cat2(ret, "?"); if (ap && 0 < alen) { - CATSEP; + CATSEP; for (i = 0; i < alen; i++) rb_str_catf(ret, "%s%02x", i == 0 ? "" : ":", (unsigned char)ap[i]); } @@ -1456,10 +1456,10 @@ rsock_inspect_sockaddr(struct sockaddr *sockaddr_arg, socklen_t socklen, VALUE r /* longer length is possible behavior because struct sockaddr_dl has "minimum work area, can be larger" as the last field. * cf. Net2:/usr/src/sys/net/if_dl.h. */ socklen < (socklen_t)(offsetof(struct sockaddr_dl, sdl_data) + addr->sdl_nlen + addr->sdl_alen + addr->sdl_slen)) { - CATSEP; + CATSEP; rb_str_catf(ret, "(%d bytes for %d bytes sockaddr_dl)", (int)socklen, (int)sizeof(struct sockaddr_dl)); - } + } rb_str_cat2(ret, "]"); #undef CATSEP @@ -2009,7 +2009,7 @@ addrinfo_ip_unpack(VALUE self) VALUE ret, portstr; if (!IS_IP_FAMILY(family)) - rb_raise(rb_eSocket, "need IPv4 or IPv6 address"); + rb_raise(rb_eSocket, "need IPv4 or IPv6 address"); vflags = INT2NUM(NI_NUMERICHOST|NI_NUMERICSERV); ret = addrinfo_getnameinfo(1, &vflags, self); @@ -2036,7 +2036,7 @@ addrinfo_ip_address(VALUE self) VALUE ret; if (!IS_IP_FAMILY(family)) - rb_raise(rb_eSocket, "need IPv4 or IPv6 address"); + rb_raise(rb_eSocket, "need IPv4 or IPv6 address"); vflags = INT2NUM(NI_NUMERICHOST|NI_NUMERICSERV); ret = addrinfo_getnameinfo(1, &vflags, self); @@ -2062,9 +2062,9 @@ addrinfo_ip_port(VALUE self) if (!IS_IP_FAMILY(family)) { bad_family: #ifdef AF_INET6 - rb_raise(rb_eSocket, "need IPv4 or IPv6 address"); + rb_raise(rb_eSocket, "need IPv4 or IPv6 address"); #else - rb_raise(rb_eSocket, "need IPv4 address"); + rb_raise(rb_eSocket, "need IPv4 address"); #endif } @@ -2084,7 +2084,7 @@ addrinfo_ip_port(VALUE self) #endif default: - goto bad_family; + goto bad_family; } return INT2NUM(port); @@ -2362,7 +2362,7 @@ addrinfo_unix_path(VALUE self) long n; if (family != AF_UNIX) - rb_raise(rb_eSocket, "need AF_UNIX address"); + rb_raise(rb_eSocket, "need AF_UNIX address"); addr = &rai->addr.un; @@ -2429,10 +2429,10 @@ addrinfo_s_getaddrinfo(int argc, VALUE *argv, VALUE self) VALUE node, service, family, socktype, protocol, flags, opts, timeout; rb_scan_args(argc, argv, "24:", &node, &service, &family, &socktype, - &protocol, &flags, &opts); + &protocol, &flags, &opts); rb_get_kwargs(opts, &id_timeout, 0, 1, &timeout); if (timeout == Qundef) { - timeout = Qnil; + timeout = Qnil; } return addrinfo_list_new(node, service, family, socktype, protocol, flags, timeout); diff --git a/ext/socket/rubysocket.h b/ext/socket/rubysocket.h index c0d40addca..9ec893ee8c 100644 --- a/ext/socket/rubysocket.h +++ b/ext/socket/rubysocket.h @@ -368,23 +368,23 @@ enum sock_recv_type { }; VALUE rsock_s_recvfrom_nonblock(VALUE sock, VALUE len, VALUE flg, VALUE str, - VALUE ex, enum sock_recv_type from); + VALUE ex, enum sock_recv_type from); VALUE rsock_s_recvfrom(VALUE sock, int argc, VALUE *argv, enum sock_recv_type from); int rsock_connect(int fd, const struct sockaddr *sockaddr, int len, int socks, struct timeval *timeout); VALUE rsock_s_accept(VALUE klass, VALUE io, struct sockaddr *sockaddr, socklen_t *len); VALUE rsock_s_accept_nonblock(VALUE klass, VALUE ex, rb_io_t *fptr, - struct sockaddr *sockaddr, socklen_t *len); + struct sockaddr *sockaddr, socklen_t *len); VALUE rsock_sock_listen(VALUE sock, VALUE log); VALUE rsock_sockopt_new(int family, int level, int optname, VALUE data); #if defined(HAVE_SENDMSG) VALUE rsock_bsock_sendmsg(VALUE sock, VALUE data, VALUE flags, - VALUE dest_sockaddr, VALUE controls); + VALUE dest_sockaddr, VALUE controls); VALUE rsock_bsock_sendmsg_nonblock(VALUE sock, VALUE data, VALUE flags, - VALUE dest_sockaddr, VALUE controls, VALUE ex); + VALUE dest_sockaddr, VALUE controls, VALUE ex); #else #define rsock_bsock_sendmsg rb_f_notimplement #define rsock_bsock_sendmsg_nonblock rb_f_notimplement @@ -392,9 +392,9 @@ VALUE rsock_bsock_sendmsg_nonblock(VALUE sock, VALUE data, VALUE flags, #if defined(HAVE_RECVMSG) VALUE rsock_bsock_recvmsg(VALUE sock, VALUE dlen, VALUE clen, VALUE flags, - VALUE scm_rights); + VALUE scm_rights); VALUE rsock_bsock_recvmsg_nonblock(VALUE sock, VALUE dlen, VALUE clen, - VALUE flags, VALUE scm_rights, VALUE ex); + VALUE flags, VALUE scm_rights, VALUE ex); ssize_t rsock_recvmsg(int socket, struct msghdr *message, int flags); #else #define rsock_bsock_recvmsg rb_f_notimplement diff --git a/ext/socket/socket.c b/ext/socket/socket.c index 4ba1c6cd61..b1965deb9e 100644 --- a/ext/socket/socket.c +++ b/ext/socket/socket.c @@ -26,7 +26,7 @@ rsock_syserr_fail_host_port(int err, const char *mesg, VALUE host, VALUE port) VALUE message; message = rb_sprintf("%s for %+"PRIsVALUE" port % "PRIsVALUE"", - mesg, host, port); + mesg, host, port); rb_syserr_fail_str(err, message); } @@ -43,11 +43,11 @@ rsock_syserr_fail_path(int err, const char *mesg, VALUE path) VALUE message; if (RB_TYPE_P(path, T_STRING)) { - message = rb_sprintf("%s for % "PRIsVALUE"", mesg, path); - rb_syserr_fail_str(err, message); + message = rb_sprintf("%s for % "PRIsVALUE"", mesg, path); + rb_syserr_fail_str(err, message); } else { - rb_syserr_fail(err, mesg); + rb_syserr_fail(err, mesg); } } @@ -96,12 +96,12 @@ rsock_syserr_fail_raddrinfo_or_sockaddr(int err, const char *mesg, VALUE addr, V if (NIL_P(rai)) { StringValue(addr); - rsock_syserr_fail_sockaddr(err, mesg, + rsock_syserr_fail_sockaddr(err, mesg, (struct sockaddr *)RSTRING_PTR(addr), (socklen_t)RSTRING_LEN(addr)); /* overflow should be checked already */ } else - rsock_syserr_fail_raddrinfo(err, mesg, rai); + rsock_syserr_fail_raddrinfo(err, mesg, rai); } static void @@ -256,7 +256,7 @@ rsock_sock_s_socketpair(int argc, VALUE *argv, VALUE klass) p = NUM2INT(protocol); ret = rsock_socketpair(d, t, p, sp); if (ret < 0) { - rb_sys_fail("socketpair(2)"); + rb_sys_fail("socketpair(2)"); } s1 = rsock_init_sock(rb_obj_alloc(klass), sp[0]); @@ -395,7 +395,7 @@ sock_connect(VALUE sock, VALUE addr) fd = fptr->fd; n = rsock_connect(fd, (struct sockaddr*)RSTRING_PTR(addr), RSTRING_SOCKLEN(addr), 0, NULL); if (n < 0) { - rsock_sys_fail_raddrinfo_or_sockaddr("connect(2)", addr, rai); + rsock_sys_fail_raddrinfo_or_sockaddr("connect(2)", addr, rai); } return INT2FIX(n); @@ -415,19 +415,19 @@ sock_connect_nonblock(VALUE sock, VALUE addr, VALUE ex) rb_io_set_nonblock(fptr); n = connect(fptr->fd, (struct sockaddr*)RSTRING_PTR(addr), RSTRING_SOCKLEN(addr)); if (n < 0) { - int e = errno; - if (e == EINPROGRESS) { + int e = errno; + if (e == EINPROGRESS) { if (ex == Qfalse) { return sym_wait_writable; } rb_readwrite_syserr_fail(RB_IO_WAIT_WRITABLE, e, "connect(2) would block"); - } - if (e == EISCONN) { + } + if (e == EISCONN) { if (ex == Qfalse) { return INT2FIX(0); } - } - rsock_syserr_fail_raddrinfo_or_sockaddr(e, "connect(2)", addr, rai); + } + rsock_syserr_fail_raddrinfo_or_sockaddr(e, "connect(2)", addr, rai); } return INT2FIX(n); @@ -528,7 +528,7 @@ sock_bind(VALUE sock, VALUE addr) SockAddrStringValueWithAddrinfo(addr, rai); GetOpenFile(sock, fptr); if (bind(fptr->fd, (struct sockaddr*)RSTRING_PTR(addr), RSTRING_SOCKLEN(addr)) < 0) - rsock_sys_fail_raddrinfo_or_sockaddr("bind(2)", addr, rai); + rsock_sys_fail_raddrinfo_or_sockaddr("bind(2)", addr, rai); return INT2FIX(0); } @@ -612,7 +612,7 @@ rsock_sock_listen(VALUE sock, VALUE log) backlog = NUM2INT(log); GetOpenFile(sock, fptr); if (listen(fptr->fd, backlog) < 0) - rb_sys_fail("listen(2)"); + rb_sys_fail("listen(2)"); return INT2FIX(0); } @@ -774,7 +774,7 @@ sock_accept_nonblock(VALUE sock, VALUE ex) sock2 = rsock_s_accept_nonblock(rb_cSocket, ex, fptr, addr, &len); if (SYMBOL_P(sock2)) /* :wait_readable */ - return sock2; + return sock2; return rb_assoc_new(sock2, rsock_io_socket_addrinfo(sock2, &buf.addr, len)); } @@ -855,19 +855,19 @@ sock_gethostname(VALUE obj) name = rb_str_new(0, len); while (gethostname(RSTRING_PTR(name), len) < 0) { - int e = errno; - switch (e) { - case ENAMETOOLONG: + int e = errno; + switch (e) { + case ENAMETOOLONG: #ifdef __linux__ - case EINVAL: - /* glibc before version 2.1 uses EINVAL instead of ENAMETOOLONG */ + case EINVAL: + /* glibc before version 2.1 uses EINVAL instead of ENAMETOOLONG */ #endif - break; - default: - rb_syserr_fail(e, "gethostname(3)"); - } - rb_str_modify_expand(name, len); - len += len; + break; + default: + rb_syserr_fail(e, "gethostname(3)"); + } + rb_str_modify_expand(name, len); + len += len; } rb_str_resize(name, strlen(RSTRING_PTR(name))); return name; @@ -897,18 +897,18 @@ make_addrinfo(struct rb_addrinfo *res0, int norevlookup) struct addrinfo *res; if (res0 == NULL) { - rb_raise(rb_eSocket, "host not found"); + rb_raise(rb_eSocket, "host not found"); } base = rb_ary_new(); for (res = res0->ai; res; res = res->ai_next) { - ary = rsock_ipaddr(res->ai_addr, res->ai_addrlen, norevlookup); - if (res->ai_canonname) { - RARRAY_ASET(ary, 2, rb_str_new2(res->ai_canonname)); - } - rb_ary_push(ary, INT2FIX(res->ai_family)); - rb_ary_push(ary, INT2FIX(res->ai_socktype)); - rb_ary_push(ary, INT2FIX(res->ai_protocol)); - rb_ary_push(base, ary); + ary = rsock_ipaddr(res->ai_addr, res->ai_addrlen, norevlookup); + if (res->ai_canonname) { + RARRAY_ASET(ary, 2, rb_str_new2(res->ai_canonname)); + } + rb_ary_push(ary, INT2FIX(res->ai_family)); + rb_ary_push(ary, INT2FIX(res->ai_socktype)); + rb_ary_push(ary, INT2FIX(res->ai_protocol)); + rb_ary_push(base, ary); } return base; } @@ -920,18 +920,18 @@ sock_sockaddr(struct sockaddr *addr, socklen_t len) switch (addr->sa_family) { case AF_INET: - ptr = (char*)&((struct sockaddr_in*)addr)->sin_addr.s_addr; - len = (socklen_t)sizeof(((struct sockaddr_in*)addr)->sin_addr.s_addr); - break; + ptr = (char*)&((struct sockaddr_in*)addr)->sin_addr.s_addr; + len = (socklen_t)sizeof(((struct sockaddr_in*)addr)->sin_addr.s_addr); + break; #ifdef AF_INET6 case AF_INET6: - ptr = (char*)&((struct sockaddr_in6*)addr)->sin6_addr.s6_addr; - len = (socklen_t)sizeof(((struct sockaddr_in6*)addr)->sin6_addr.s6_addr); - break; + ptr = (char*)&((struct sockaddr_in6*)addr)->sin6_addr.s6_addr; + len = (socklen_t)sizeof(((struct sockaddr_in6*)addr)->sin6_addr.s6_addr); + break; #endif default: rb_raise(rb_eSocket, "unknown socket family:%d", addr->sa_family); - break; + break; } return rb_str_new(ptr, len); } @@ -961,7 +961,7 @@ sock_s_gethostbyname(VALUE obj, VALUE host) { rb_warn("Socket.gethostbyname is deprecated; use Addrinfo.getaddrinfo instead."); struct rb_addrinfo *res = - rsock_addrinfo(host, Qnil, AF_UNSPEC, SOCK_STREAM, AI_CANONNAME); + rsock_addrinfo(host, Qnil, AF_UNSPEC, SOCK_STREAM, AI_CANONNAME); return rsock_make_hostent(host, res, sock_sockaddr); } @@ -1004,20 +1004,20 @@ sock_s_gethostbyaddr(int argc, VALUE *argv, VALUE _) rb_scan_args(argc, argv, "11", &addr, &family); StringValue(addr); if (!NIL_P(family)) { - t = rsock_family_arg(family); + t = rsock_family_arg(family); } #ifdef AF_INET6 else if (RSTRING_LEN(addr) == 16) { - t = AF_INET6; + t = AF_INET6; } #endif h = gethostbyaddr(RSTRING_PTR(addr), RSTRING_SOCKLEN(addr), t); if (h == NULL) { #ifdef HAVE_HSTRERROR - extern int h_errno; - rb_raise(rb_eSocket, "%s", (char*)hstrerror(h_errno)); + extern int h_errno; + rb_raise(rb_eSocket, "%s", (char*)hstrerror(h_errno)); #else - rb_raise(rb_eSocket, "host not found"); + rb_raise(rb_eSocket, "host not found"); #endif } ary = rb_ary_new(); @@ -1025,14 +1025,14 @@ sock_s_gethostbyaddr(int argc, VALUE *argv, VALUE _) names = rb_ary_new(); rb_ary_push(ary, names); if (h->h_aliases != NULL) { - for (pch = h->h_aliases; *pch; pch++) { - rb_ary_push(names, rb_str_new2(*pch)); - } + for (pch = h->h_aliases; *pch; pch++) { + rb_ary_push(names, rb_str_new2(*pch)); + } } rb_ary_push(ary, INT2NUM(h->h_addrtype)); #ifdef h_addr for (pch = h->h_addr_list; *pch; pch++) { - rb_ary_push(ary, rb_str_new(*pch, h->h_length)); + rb_ary_push(ary, rb_str_new(*pch, h->h_length)); } #else rb_ary_push(ary, rb_str_new(h->h_addr, h->h_length)); @@ -1069,15 +1069,15 @@ sock_s_getservbyname(int argc, VALUE *argv, VALUE _) if (!NIL_P(proto)) protoname = StringValueCStr(proto); sp = getservbyname(servicename, protoname); if (sp) { - port = ntohs(sp->s_port); + port = ntohs(sp->s_port); } else { - char *end; + char *end; - port = STRTOUL(servicename, &end, 0); - if (*end != '\0') { - rb_raise(rb_eSocket, "no such service %s/%s", servicename, protoname); - } + port = STRTOUL(servicename, &end, 0); + if (*end != '\0') { + rb_raise(rb_eSocket, "no such service %s/%s", servicename, protoname); + } } return INT2FIX(port); } @@ -1106,14 +1106,14 @@ sock_s_getservbyport(int argc, VALUE *argv, VALUE _) rb_scan_args(argc, argv, "11", &port, &proto); portnum = NUM2LONG(port); if (portnum != (uint16_t)portnum) { - const char *s = portnum > 0 ? "big" : "small"; - rb_raise(rb_eRangeError, "integer %ld too %s to convert into `int16_t'", portnum, s); + const char *s = portnum > 0 ? "big" : "small"; + rb_raise(rb_eRangeError, "integer %ld too %s to convert into `int16_t'", portnum, s); } if (!NIL_P(proto)) protoname = StringValueCStr(proto); sp = getservbyport((int)htons((uint16_t)portnum), protoname); if (!sp) { - rb_raise(rb_eSocket, "no such service for port %d/%s", (int)portnum, protoname); + rb_raise(rb_eSocket, "no such service for port %d/%s", (int)portnum, protoname); } return rb_str_new2(sp->s_name); } @@ -1167,16 +1167,16 @@ sock_s_getaddrinfo(int argc, VALUE *argv, VALUE _) hints.ai_family = NIL_P(family) ? PF_UNSPEC : rsock_family_arg(family); if (!NIL_P(socktype)) { - hints.ai_socktype = rsock_socktype_arg(socktype); + hints.ai_socktype = rsock_socktype_arg(socktype); } if (!NIL_P(protocol)) { - hints.ai_protocol = NUM2INT(protocol); + hints.ai_protocol = NUM2INT(protocol); } if (!NIL_P(flags)) { - hints.ai_flags = NUM2INT(flags); + hints.ai_flags = NUM2INT(flags); } if (NIL_P(revlookup) || !rsock_revlookup_flag(revlookup, &norevlookup)) { - norevlookup = rsock_do_not_reverse_lookup; + norevlookup = rsock_do_not_reverse_lookup; } res = rsock_getaddrinfo(host, port, &hints, 0); @@ -1226,82 +1226,82 @@ sock_s_getnameinfo(int argc, VALUE *argv, VALUE _) fl = 0; if (!NIL_P(flags)) { - fl = NUM2INT(flags); + fl = NUM2INT(flags); } tmp = rb_check_sockaddr_string_type(sa); if (!NIL_P(tmp)) { - sa = tmp; - if (sizeof(ss) < (size_t)RSTRING_LEN(sa)) { - rb_raise(rb_eTypeError, "sockaddr length too big"); - } - memcpy(&ss, RSTRING_PTR(sa), RSTRING_LEN(sa)); + sa = tmp; + if (sizeof(ss) < (size_t)RSTRING_LEN(sa)) { + rb_raise(rb_eTypeError, "sockaddr length too big"); + } + memcpy(&ss, RSTRING_PTR(sa), RSTRING_LEN(sa)); if (!VALIDATE_SOCKLEN(&ss.addr, RSTRING_LEN(sa))) { - rb_raise(rb_eTypeError, "sockaddr size differs - should not happen"); - } - sap = &ss.addr; + rb_raise(rb_eTypeError, "sockaddr size differs - should not happen"); + } + sap = &ss.addr; salen = RSTRING_SOCKLEN(sa); - goto call_nameinfo; + goto call_nameinfo; } tmp = rb_check_array_type(sa); if (!NIL_P(tmp)) { - sa = tmp; - MEMZERO(&hints, struct addrinfo, 1); - if (RARRAY_LEN(sa) == 3) { - af = RARRAY_AREF(sa, 0); - port = RARRAY_AREF(sa, 1); - host = RARRAY_AREF(sa, 2); - } - else if (RARRAY_LEN(sa) >= 4) { - af = RARRAY_AREF(sa, 0); - port = RARRAY_AREF(sa, 1); - host = RARRAY_AREF(sa, 3); - if (NIL_P(host)) { - host = RARRAY_AREF(sa, 2); - } - else { - /* - * 4th element holds numeric form, don't resolve. - * see rsock_ipaddr(). - */ + sa = tmp; + MEMZERO(&hints, struct addrinfo, 1); + if (RARRAY_LEN(sa) == 3) { + af = RARRAY_AREF(sa, 0); + port = RARRAY_AREF(sa, 1); + host = RARRAY_AREF(sa, 2); + } + else if (RARRAY_LEN(sa) >= 4) { + af = RARRAY_AREF(sa, 0); + port = RARRAY_AREF(sa, 1); + host = RARRAY_AREF(sa, 3); + if (NIL_P(host)) { + host = RARRAY_AREF(sa, 2); + } + else { + /* + * 4th element holds numeric form, don't resolve. + * see rsock_ipaddr(). + */ #ifdef AI_NUMERICHOST /* AIX 4.3.3 doesn't have AI_NUMERICHOST. */ - hints.ai_flags |= AI_NUMERICHOST; + hints.ai_flags |= AI_NUMERICHOST; #endif - } - } - else { - rb_raise(rb_eArgError, "array size should be 3 or 4, %ld given", - RARRAY_LEN(sa)); - } - hints.ai_socktype = (fl & NI_DGRAM) ? SOCK_DGRAM : SOCK_STREAM; - /* af */ + } + } + else { + rb_raise(rb_eArgError, "array size should be 3 or 4, %ld given", + RARRAY_LEN(sa)); + } + hints.ai_socktype = (fl & NI_DGRAM) ? SOCK_DGRAM : SOCK_STREAM; + /* af */ hints.ai_family = NIL_P(af) ? PF_UNSPEC : rsock_family_arg(af); - res = rsock_getaddrinfo(host, port, &hints, 0); - sap = res->ai->ai_addr; + res = rsock_getaddrinfo(host, port, &hints, 0); + sap = res->ai->ai_addr; salen = res->ai->ai_addrlen; } else { - rb_raise(rb_eTypeError, "expecting String or Array"); + rb_raise(rb_eTypeError, "expecting String or Array"); } call_nameinfo: error = rb_getnameinfo(sap, salen, hbuf, sizeof(hbuf), - pbuf, sizeof(pbuf), fl); + pbuf, sizeof(pbuf), fl); if (error) goto error_exit_name; if (res) { - for (r = res->ai->ai_next; r; r = r->ai_next) { - char hbuf2[1024], pbuf2[1024]; + for (r = res->ai->ai_next; r; r = r->ai_next) { + char hbuf2[1024], pbuf2[1024]; - sap = r->ai_addr; + sap = r->ai_addr; salen = r->ai_addrlen; - error = rb_getnameinfo(sap, salen, hbuf2, sizeof(hbuf2), - pbuf2, sizeof(pbuf2), fl); - if (error) goto error_exit_name; - if (strcmp(hbuf, hbuf2) != 0|| strcmp(pbuf, pbuf2) != 0) { - rb_freeaddrinfo(res); - rb_raise(rb_eSocket, "sockaddr resolved to multiple nodename"); - } - } - rb_freeaddrinfo(res); + error = rb_getnameinfo(sap, salen, hbuf2, sizeof(hbuf2), + pbuf2, sizeof(pbuf2), fl); + if (error) goto error_exit_name; + if (strcmp(hbuf, hbuf2) != 0|| strcmp(pbuf, pbuf2) != 0) { + rb_freeaddrinfo(res); + rb_raise(rb_eSocket, "sockaddr resolved to multiple nodename"); + } + } + rb_freeaddrinfo(res); } return rb_assoc_new(rb_str_new2(hbuf), rb_str_new2(pbuf)); @@ -1437,8 +1437,8 @@ sock_s_unpack_sockaddr_un(VALUE self, VALUE addr) rb_raise(rb_eArgError, "not an AF_UNIX sockaddr"); } if (sizeof(struct sockaddr_un) < (size_t)RSTRING_LEN(addr)) { - rb_raise(rb_eTypeError, "too long sockaddr_un - %ld longer than %d", - RSTRING_LEN(addr), (int)sizeof(struct sockaddr_un)); + rb_raise(rb_eTypeError, "too long sockaddr_un - %ld longer than %d", + RSTRING_LEN(addr), (int)sizeof(struct sockaddr_un)); } path = rsock_unixpath_str(sockaddr, RSTRING_SOCKLEN(addr)); return path; @@ -1502,19 +1502,19 @@ sockaddr_obj(struct sockaddr *addr, socklen_t len) #if defined(__KAME__) && defined(AF_INET6) if (addr->sa_family == AF_INET6) { - /* KAME uses the 2nd 16bit word of link local IPv6 address as interface index internally */ + /* KAME uses the 2nd 16bit word of link local IPv6 address as interface index internally */ /* http://orange.kame.net/dev/cvsweb.cgi/kame/IMPLEMENTATION */ - /* convert fe80:1::1 to fe80::1%1 */ + /* convert fe80:1::1 to fe80::1%1 */ len = (socklen_t)sizeof(struct sockaddr_in6); - memcpy(&addr6, addr, len); - addr = (struct sockaddr *)&addr6; - if (IN6_IS_ADDR_LINKLOCAL(&addr6.sin6_addr) && - addr6.sin6_scope_id == 0 && - (addr6.sin6_addr.s6_addr[2] || addr6.sin6_addr.s6_addr[3])) { - addr6.sin6_scope_id = (addr6.sin6_addr.s6_addr[2] << 8) | addr6.sin6_addr.s6_addr[3]; - addr6.sin6_addr.s6_addr[2] = 0; - addr6.sin6_addr.s6_addr[3] = 0; - } + memcpy(&addr6, addr, len); + addr = (struct sockaddr *)&addr6; + if (IN6_IS_ADDR_LINKLOCAL(&addr6.sin6_addr) && + addr6.sin6_scope_id == 0 && + (addr6.sin6_addr.s6_addr[2] || addr6.sin6_addr.s6_addr[3])) { + addr6.sin6_scope_id = (addr6.sin6_addr.s6_addr[2] << 8) | addr6.sin6_addr.s6_addr[3]; + addr6.sin6_addr.s6_addr[2] = 0; + addr6.sin6_addr.s6_addr[3] = 0; + } } #endif @@ -1612,8 +1612,8 @@ socket_s_ip_address_list(VALUE self) ret = ioctl(fd, SIOCGLIFNUM, &ln); if (ret == -1) { - reason = "SIOCGLIFNUM"; - goto finish; + reason = "SIOCGLIFNUM"; + goto finish; } memset(&lc, 0, sizeof(lc)); @@ -1624,13 +1624,13 @@ socket_s_ip_address_list(VALUE self) ret = ioctl(fd, SIOCGLIFCONF, &lc); if (ret == -1) { - reason = "SIOCGLIFCONF"; - goto finish; + reason = "SIOCGLIFCONF"; + goto finish; } list = rb_ary_new(); for (i = 0; i < ln.lifn_count; i++) { - struct lifreq *req = &lc.lifc_req[i]; + struct lifreq *req = &lc.lifc_req[i]; if (IS_IP_FAMILY(req->lifr_addr.ss_family)) { if (req->lifr_addr.ss_family == AF_INET6 && IN6_IS_ADDR_LINKLOCAL(&((struct sockaddr_in6 *)(&req->lifr_addr))->sin6_addr) && @@ -1651,13 +1651,13 @@ socket_s_ip_address_list(VALUE self) finish: save_errno = errno; if (lc.lifc_buf != NULL) - xfree(lc.lifc_req); + xfree(lc.lifc_req); if (fd != -1) - close(fd); + close(fd); errno = save_errno; if (reason) - rb_syserr_fail(save_errno, reason); + rb_syserr_fail(save_errno, reason); return list; #elif defined(SIOCGIFCONF) @@ -1695,17 +1695,17 @@ socket_s_ip_address_list(VALUE self) /* fprintf(stderr, "conf.ifc_len: %d\n", conf.ifc_len); */ if (bufsize - EXTRA_SPACE < conf.ifc_len) { - if (bufsize < conf.ifc_len) { - /* NetBSD returns required size for all interfaces. */ - bufsize = conf.ifc_len + EXTRA_SPACE; - } - else { - bufsize = bufsize << 1; - } - if (buf == initbuf) - buf = NULL; - buf = xrealloc(buf, bufsize); - goto retry; + if (bufsize < conf.ifc_len) { + /* NetBSD returns required size for all interfaces. */ + bufsize = conf.ifc_len + EXTRA_SPACE; + } + else { + bufsize = bufsize << 1; + } + if (buf == initbuf) + buf = NULL; + buf = xrealloc(buf, bufsize); + goto retry; } close(fd); @@ -1714,10 +1714,10 @@ socket_s_ip_address_list(VALUE self) list = rb_ary_new(); req = conf.ifc_req; while ((char*)req < (char*)conf.ifc_req + conf.ifc_len) { - struct sockaddr *addr = &req->ifr_addr; + struct sockaddr *addr = &req->ifr_addr; if (IS_IP_FAMILY(addr->sa_family)) { - rb_ary_push(list, sockaddr_obj(addr, sockaddr_len(addr))); - } + rb_ary_push(list, sockaddr_obj(addr, sockaddr_len(addr))); + } #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN # ifndef _SIZEOF_ADDR_IFREQ # define _SIZEOF_ADDR_IFREQ(r) \ @@ -1726,9 +1726,9 @@ socket_s_ip_address_list(VALUE self) (r).ifr_addr.sa_len - sizeof(struct sockaddr) : \ 0)) # endif - req = (struct ifreq *)((char*)req + _SIZEOF_ADDR_IFREQ(*req)); + req = (struct ifreq *)((char*)req + _SIZEOF_ADDR_IFREQ(*req)); #else - req = (struct ifreq *)((char*)req + sizeof(struct ifreq)); + req = (struct ifreq *)((char*)req + sizeof(struct ifreq)); #endif } @@ -1738,57 +1738,57 @@ socket_s_ip_address_list(VALUE self) if (buf != initbuf) xfree(buf); if (fd != -1) - close(fd); + close(fd); errno = save_errno; if (reason) - rb_syserr_fail(save_errno, reason); + rb_syserr_fail(save_errno, reason); return list; #undef EXTRA_SPACE #elif defined(_WIN32) typedef struct ip_adapter_unicast_address_st { - unsigned LONG_LONG dummy0; - struct ip_adapter_unicast_address_st *Next; - struct { - struct sockaddr *lpSockaddr; - int iSockaddrLength; - } Address; - int dummy1; - int dummy2; - int dummy3; - long dummy4; - long dummy5; - long dummy6; + unsigned LONG_LONG dummy0; + struct ip_adapter_unicast_address_st *Next; + struct { + struct sockaddr *lpSockaddr; + int iSockaddrLength; + } Address; + int dummy1; + int dummy2; + int dummy3; + long dummy4; + long dummy5; + long dummy6; } ip_adapter_unicast_address_t; typedef struct ip_adapter_anycast_address_st { - unsigned LONG_LONG dummy0; - struct ip_adapter_anycast_address_st *Next; - struct { - struct sockaddr *lpSockaddr; - int iSockaddrLength; - } Address; + unsigned LONG_LONG dummy0; + struct ip_adapter_anycast_address_st *Next; + struct { + struct sockaddr *lpSockaddr; + int iSockaddrLength; + } Address; } ip_adapter_anycast_address_t; typedef struct ip_adapter_addresses_st { - unsigned LONG_LONG dummy0; - struct ip_adapter_addresses_st *Next; - void *dummy1; - ip_adapter_unicast_address_t *FirstUnicastAddress; - ip_adapter_anycast_address_t *FirstAnycastAddress; - void *dummy2; - void *dummy3; - void *dummy4; - void *dummy5; - void *dummy6; - BYTE dummy7[8]; - DWORD dummy8; - DWORD dummy9; - DWORD dummy10; - DWORD IfType; - int OperStatus; - DWORD dummy12; - DWORD dummy13[16]; - void *dummy14; + unsigned LONG_LONG dummy0; + struct ip_adapter_addresses_st *Next; + void *dummy1; + ip_adapter_unicast_address_t *FirstUnicastAddress; + ip_adapter_anycast_address_t *FirstAnycastAddress; + void *dummy2; + void *dummy3; + void *dummy4; + void *dummy5; + void *dummy6; + BYTE dummy7[8]; + DWORD dummy8; + DWORD dummy9; + DWORD dummy10; + DWORD IfType; + int OperStatus; + DWORD dummy12; + DWORD dummy13[16]; + void *dummy14; } ip_adapter_addresses_t; typedef ULONG (WINAPI *GetAdaptersAddresses_t)(ULONG, ULONG, PVOID, ip_adapter_addresses_t *, PULONG); HMODULE h; @@ -1800,49 +1800,49 @@ socket_s_ip_address_list(VALUE self) h = LoadLibrary("iphlpapi.dll"); if (!h) - rb_notimplement(); + rb_notimplement(); pGetAdaptersAddresses = (GetAdaptersAddresses_t)GetProcAddress(h, "GetAdaptersAddresses"); if (!pGetAdaptersAddresses) { - FreeLibrary(h); - rb_notimplement(); + FreeLibrary(h); + rb_notimplement(); } ret = pGetAdaptersAddresses(AF_UNSPEC, 0, NULL, NULL, &len); if (ret != ERROR_SUCCESS && ret != ERROR_BUFFER_OVERFLOW) { - errno = rb_w32_map_errno(ret); - FreeLibrary(h); - rb_sys_fail("GetAdaptersAddresses"); + errno = rb_w32_map_errno(ret); + FreeLibrary(h); + rb_sys_fail("GetAdaptersAddresses"); } adapters = (ip_adapter_addresses_t *)ALLOCA_N(BYTE, len); ret = pGetAdaptersAddresses(AF_UNSPEC, 0, NULL, adapters, &len); if (ret != ERROR_SUCCESS) { - errno = rb_w32_map_errno(ret); - FreeLibrary(h); - rb_sys_fail("GetAdaptersAddresses"); + errno = rb_w32_map_errno(ret); + FreeLibrary(h); + rb_sys_fail("GetAdaptersAddresses"); } list = rb_ary_new(); for (; adapters; adapters = adapters->Next) { - ip_adapter_unicast_address_t *uni; - ip_adapter_anycast_address_t *any; - if (adapters->OperStatus != 1) /* 1 means IfOperStatusUp */ - continue; - for (uni = adapters->FirstUnicastAddress; uni; uni = uni->Next) { + ip_adapter_unicast_address_t *uni; + ip_adapter_anycast_address_t *any; + if (adapters->OperStatus != 1) /* 1 means IfOperStatusUp */ + continue; + for (uni = adapters->FirstUnicastAddress; uni; uni = uni->Next) { #ifndef INET6 - if (uni->Address.lpSockaddr->sa_family == AF_INET) + if (uni->Address.lpSockaddr->sa_family == AF_INET) #else - if (IS_IP_FAMILY(uni->Address.lpSockaddr->sa_family)) + if (IS_IP_FAMILY(uni->Address.lpSockaddr->sa_family)) #endif - rb_ary_push(list, sockaddr_obj(uni->Address.lpSockaddr, uni->Address.iSockaddrLength)); - } - for (any = adapters->FirstAnycastAddress; any; any = any->Next) { + rb_ary_push(list, sockaddr_obj(uni->Address.lpSockaddr, uni->Address.iSockaddrLength)); + } + for (any = adapters->FirstAnycastAddress; any; any = any->Next) { #ifndef INET6 - if (any->Address.lpSockaddr->sa_family == AF_INET) + if (any->Address.lpSockaddr->sa_family == AF_INET) #else - if (IS_IP_FAMILY(any->Address.lpSockaddr->sa_family)) + if (IS_IP_FAMILY(any->Address.lpSockaddr->sa_family)) #endif - rb_ary_push(list, sockaddr_obj(any->Address.lpSockaddr, any->Address.iSockaddrLength)); - } + rb_ary_push(list, sockaddr_obj(any->Address.lpSockaddr, any->Address.iSockaddrLength)); + } } FreeLibrary(h); @@ -1986,7 +1986,7 @@ Init_socket(void) /* for ext/socket/lib/socket.rb use only: */ rb_define_private_method(rb_cSocket, - "__connect_nonblock", sock_connect_nonblock, 2); + "__connect_nonblock", sock_connect_nonblock, 2); rb_define_method(rb_cSocket, "bind", sock_bind, 1); rb_define_method(rb_cSocket, "listen", rsock_sock_listen, 1); @@ -1994,7 +1994,7 @@ Init_socket(void) /* for ext/socket/lib/socket.rb use only: */ rb_define_private_method(rb_cSocket, - "__accept_nonblock", sock_accept_nonblock, 1); + "__accept_nonblock", sock_accept_nonblock, 1); rb_define_method(rb_cSocket, "sysaccept", sock_sysaccept, 0); @@ -2002,7 +2002,7 @@ Init_socket(void) /* for ext/socket/lib/socket.rb use only: */ rb_define_private_method(rb_cSocket, - "__recvfrom_nonblock", sock_recvfrom_nonblock, 4); + "__recvfrom_nonblock", sock_recvfrom_nonblock, 4); rb_define_singleton_method(rb_cSocket, "socketpair", rsock_sock_s_socketpair, -1); rb_define_singleton_method(rb_cSocket, "pair", rsock_sock_s_socketpair, -1); diff --git a/ext/socket/sockssocket.c b/ext/socket/sockssocket.c index b8b7e12998..f263ac3804 100644 --- a/ext/socket/sockssocket.c +++ b/ext/socket/sockssocket.c @@ -30,8 +30,8 @@ socks_init(VALUE sock, VALUE host, VALUE port) static int init = 0; if (init == 0) { - SOCKSinit("ruby"); - init = 1; + SOCKSinit("ruby"); + init = 1; } return rsock_init_inetsock(sock, host, port, Qnil, Qnil, INET_SOCKS, Qnil, Qnil); diff --git a/ext/socket/tcpserver.c b/ext/socket/tcpserver.c index 675733c6f9..04e5a0bb51 100644 --- a/ext/socket/tcpserver.c +++ b/ext/socket/tcpserver.c @@ -133,7 +133,7 @@ rsock_init_tcpserver(void) rb_cTCPServer = rb_define_class("TCPServer", rb_cTCPSocket); rb_define_method(rb_cTCPServer, "accept", tcp_accept, 0); rb_define_private_method(rb_cTCPServer, - "__accept_nonblock", tcp_accept_nonblock, 1); + "__accept_nonblock", tcp_accept_nonblock, 1); rb_define_method(rb_cTCPServer, "sysaccept", tcp_sysaccept, 0); rb_define_method(rb_cTCPServer, "initialize", tcp_svr_init, -1); rb_define_method(rb_cTCPServer, "listen", rsock_sock_listen, 1); /* in socket.c */ diff --git a/ext/socket/tcpsocket.c b/ext/socket/tcpsocket.c index 51e77a0de9..03787272f3 100644 --- a/ext/socket/tcpsocket.c +++ b/ext/socket/tcpsocket.c @@ -32,22 +32,22 @@ tcp_init(int argc, VALUE *argv, VALUE sock) VALUE connect_timeout = Qnil; if (!keyword_ids[0]) { - CONST_ID(keyword_ids[0], "resolv_timeout"); - CONST_ID(keyword_ids[1], "connect_timeout"); + CONST_ID(keyword_ids[0], "resolv_timeout"); + CONST_ID(keyword_ids[1], "connect_timeout"); } rb_scan_args(argc, argv, "22:", &remote_host, &remote_serv, - &local_host, &local_serv, &opt); + &local_host, &local_serv, &opt); if (!NIL_P(opt)) { - rb_get_kwargs(opt, keyword_ids, 0, 2, kwargs); - if (kwargs[0] != Qundef) { resolv_timeout = kwargs[0]; } - if (kwargs[1] != Qundef) { connect_timeout = kwargs[1]; } + rb_get_kwargs(opt, keyword_ids, 0, 2, kwargs); + if (kwargs[0] != Qundef) { resolv_timeout = kwargs[0]; } + if (kwargs[1] != Qundef) { connect_timeout = kwargs[1]; } } return rsock_init_inetsock(sock, remote_host, remote_serv, - local_host, local_serv, INET_CLIENT, - resolv_timeout, connect_timeout); + local_host, local_serv, INET_CLIENT, + resolv_timeout, connect_timeout); } static VALUE @@ -80,7 +80,7 @@ tcp_s_gethostbyname(VALUE obj, VALUE host) { rb_warn("TCPSocket.gethostbyname is deprecated; use Addrinfo.getaddrinfo instead."); struct rb_addrinfo *res = - rsock_addrinfo(host, Qnil, AF_UNSPEC, SOCK_STREAM, AI_CANONNAME); + rsock_addrinfo(host, Qnil, AF_UNSPEC, SOCK_STREAM, AI_CANONNAME); return rsock_make_hostent(host, res, tcp_sockaddr); } diff --git a/ext/socket/udpsocket.c b/ext/socket/udpsocket.c index 2bfd7c8560..3500107972 100644 --- a/ext/socket/udpsocket.c +++ b/ext/socket/udpsocket.c @@ -33,11 +33,11 @@ udp_init(int argc, VALUE *argv, VALUE sock) int fd; if (rb_scan_args(argc, argv, "01", &arg) == 1) { - family = rsock_family_arg(arg); + family = rsock_family_arg(arg); } fd = rsock_socket(family, SOCK_DGRAM, 0); if (fd < 0) { - rb_sys_fail("socket(2) - udp"); + rb_sys_fail("socket(2) - udp"); } return rsock_init_sock(sock, fd); @@ -60,9 +60,9 @@ udp_connect_internal(VALUE v) rb_io_check_closed(fptr = arg->fptr); fd = fptr->fd; for (res = arg->res->ai; res; res = res->ai_next) { - if (rsock_connect(fd, res->ai_addr, res->ai_addrlen, 0, NULL) >= 0) { - return Qtrue; - } + if (rsock_connect(fd, res->ai_addr, res->ai_addrlen, 0, NULL) >= 0) { + return Qtrue; + } } return Qfalse; } @@ -92,7 +92,7 @@ udp_connect(VALUE sock, VALUE host, VALUE port) GetOpenFile(sock, arg.fptr); arg.res = rsock_addrinfo(host, port, rsock_fd_family(arg.fptr->fd), SOCK_DGRAM, 0); ret = rb_ensure(udp_connect_internal, (VALUE)&arg, - rsock_freeaddrinfo, (VALUE)arg.res); + rsock_freeaddrinfo, (VALUE)arg.res); if (!ret) rsock_sys_fail_host_port("connect(2)", host, port); return INT2FIX(0); } @@ -108,10 +108,10 @@ udp_bind_internal(VALUE v) rb_io_check_closed(fptr = arg->fptr); fd = fptr->fd; for (res = arg->res->ai; res; res = res->ai_next) { - if (bind(fd, res->ai_addr, res->ai_addrlen) < 0) { - continue; - } - return Qtrue; + if (bind(fd, res->ai_addr, res->ai_addrlen) < 0) { + continue; + } + return Qtrue; } return Qfalse; } @@ -137,7 +137,7 @@ udp_bind(VALUE sock, VALUE host, VALUE port) GetOpenFile(sock, arg.fptr); arg.res = rsock_addrinfo(host, port, rsock_fd_family(arg.fptr->fd), SOCK_DGRAM, 0); ret = rb_ensure(udp_bind_internal, (VALUE)&arg, - rsock_freeaddrinfo, (VALUE)arg.res); + rsock_freeaddrinfo, (VALUE)arg.res); if (!ret) rsock_sys_fail_host_port("bind(2)", host, port); return INT2FIX(0); } @@ -207,7 +207,7 @@ udp_send(int argc, VALUE *argv, VALUE sock) VALUE ret; if (argc == 2 || argc == 3) { - return rsock_bsock_send(argc, argv, sock); + return rsock_bsock_send(argc, argv, sock); } rb_scan_args(argc, argv, "4", &arg.sarg.mesg, &flags, &host, &port); @@ -217,7 +217,7 @@ udp_send(int argc, VALUE *argv, VALUE sock) arg.sarg.flags = NUM2INT(flags); arg.res = rsock_addrinfo(host, port, rsock_fd_family(arg.fptr->fd), SOCK_DGRAM, 0); ret = rb_ensure(udp_send_internal, (VALUE)&arg, - rsock_freeaddrinfo, (VALUE)arg.res); + rsock_freeaddrinfo, (VALUE)arg.res); if (!ret) rsock_sys_fail_host_port("sendto(2)", host, port); return ret; } @@ -246,5 +246,5 @@ rsock_init_udpsocket(void) /* for ext/socket/lib/socket.rb use only: */ rb_define_private_method(rb_cUDPSocket, - "__recvfrom_nonblock", udp_recvfrom_nonblock, 4); + "__recvfrom_nonblock", udp_recvfrom_nonblock, 4); } diff --git a/ext/socket/unixserver.c b/ext/socket/unixserver.c index 890f9d3fae..3a899cca1f 100644 --- a/ext/socket/unixserver.c +++ b/ext/socket/unixserver.c @@ -66,7 +66,7 @@ unix_accept_nonblock(VALUE sock, VALUE ex) GetOpenFile(sock, fptr); fromlen = (socklen_t)sizeof(from); return rsock_s_accept_nonblock(rb_cUNIXSocket, ex, fptr, - (struct sockaddr *)&from, &fromlen); + (struct sockaddr *)&from, &fromlen); } /* @@ -113,7 +113,7 @@ rsock_init_unixserver(void) rb_define_method(rb_cUNIXServer, "accept", unix_accept, 0); rb_define_private_method(rb_cUNIXServer, - "__accept_nonblock", unix_accept_nonblock, 1); + "__accept_nonblock", unix_accept_nonblock, 1); rb_define_method(rb_cUNIXServer, "sysaccept", unix_sysaccept, 0); rb_define_method(rb_cUNIXServer, "listen", rsock_sock_listen, 1); /* in socket.c */ diff --git a/ext/socket/unixsocket.c b/ext/socket/unixsocket.c index 857cfa6002..ecffbd4e92 100644 --- a/ext/socket/unixsocket.c +++ b/ext/socket/unixsocket.c @@ -22,7 +22,7 @@ unixsock_connect_internal(VALUE a) { struct unixsock_arg *arg = (struct unixsock_arg *)a; return (VALUE)rsock_connect(arg->fd, (struct sockaddr*)arg->sockaddr, - arg->sockaddrlen, 0, NULL); + arg->sockaddrlen, 0, NULL); } static VALUE @@ -66,42 +66,42 @@ rsock_init_unixsock(VALUE sock, VALUE path, int server) fd = rsock_socket(AF_UNIX, SOCK_STREAM, 0); if (fd < 0) { - rsock_sys_fail_path("socket(2)", path); + rsock_sys_fail_path("socket(2)", path); } if (server) { status = bind(fd, (struct sockaddr*)&sockaddr, sockaddrlen); } else { - int prot; - struct unixsock_arg arg; - arg.sockaddr = &sockaddr; - arg.sockaddrlen = sockaddrlen; - arg.fd = fd; + int prot; + struct unixsock_arg arg; + arg.sockaddr = &sockaddr; + arg.sockaddrlen = sockaddrlen; + arg.fd = fd; status = (int)rb_protect(unixsock_connect_internal, (VALUE)&arg, &prot); - if (prot) { - close(fd); - rb_jump_tag(prot); - } + if (prot) { + close(fd); + rb_jump_tag(prot); + } } if (status < 0) { - int e = errno; - close(fd); - rsock_syserr_fail_path(e, "connect(2)", path); + int e = errno; + close(fd); + rsock_syserr_fail_path(e, "connect(2)", path); } if (server) { - if (listen(fd, SOMAXCONN) < 0) { - int e = errno; - close(fd); - rsock_syserr_fail_path(e, "listen(2)", path); - } + if (listen(fd, SOMAXCONN) < 0) { + int e = errno; + close(fd); + rsock_syserr_fail_path(e, "listen(2)", path); + } } rsock_init_sock(sock, fd); if (server) { - GetOpenFile(sock, fptr); + GetOpenFile(sock, fptr); fptr->pathv = rb_str_new_frozen(path); } @@ -143,13 +143,13 @@ unix_path(VALUE sock) GetOpenFile(sock, fptr); if (NIL_P(fptr->pathv)) { - struct sockaddr_un addr; - socklen_t len = (socklen_t)sizeof(addr); - socklen_t len0 = len; - if (getsockname(fptr->fd, (struct sockaddr*)&addr, &len) < 0) + struct sockaddr_un addr; + socklen_t len = (socklen_t)sizeof(addr); + socklen_t len0 = len; + if (getsockname(fptr->fd, (struct sockaddr*)&addr, &len) < 0) rsock_sys_fail_path("getsockname(2)", fptr->pathv); if (len0 < len) len = len0; - fptr->pathv = rb_obj_freeze(rsock_unixpath_str(&addr, len)); + fptr->pathv = rb_obj_freeze(rsock_unixpath_str(&addr, len)); } return rb_str_dup(fptr->pathv); } @@ -240,21 +240,21 @@ unix_send_io(VALUE sock, VALUE val) #if FD_PASSING_BY_MSG_CONTROL union { - struct cmsghdr hdr; - char pad[sizeof(struct cmsghdr)+8+sizeof(int)+8]; + struct cmsghdr hdr; + char pad[sizeof(struct cmsghdr)+8+sizeof(int)+8]; } cmsg; #endif if (rb_obj_is_kind_of(val, rb_cIO)) { rb_io_t *valfptr; - GetOpenFile(val, valfptr); - fd = valfptr->fd; + GetOpenFile(val, valfptr); + fd = valfptr->fd; } else if (FIXNUM_P(val)) { fd = FIX2INT(val); } else { - rb_raise(rb_eTypeError, "neither IO nor file descriptor"); + rb_raise(rb_eTypeError, "neither IO nor file descriptor"); } GetOpenFile(sock, fptr); @@ -285,8 +285,8 @@ unix_send_io(VALUE sock, VALUE val) arg.fd = fptr->fd; while ((int)BLOCKING_REGION_FD(sendmsg_blocking, &arg) == -1) { - if (!rb_io_wait_writable(arg.fd)) - rsock_sys_fail_path("sendmsg(2)", fptr->pathv); + if (!rb_io_wait_writable(arg.fd)) + rsock_sys_fail_path("sendmsg(2)", fptr->pathv); } return Qnil; @@ -348,16 +348,16 @@ unix_recv_io(int argc, VALUE *argv, VALUE sock) int fd; #if FD_PASSING_BY_MSG_CONTROL union { - struct cmsghdr hdr; - char pad[sizeof(struct cmsghdr)+8+sizeof(int)+8]; + struct cmsghdr hdr; + char pad[sizeof(struct cmsghdr)+8+sizeof(int)+8]; } cmsg; #endif rb_scan_args(argc, argv, "02", &klass, &mode); if (argc == 0) - klass = rb_cIO; + klass = rb_cIO; if (argc <= 1) - mode = Qnil; + mode = Qnil; retry: GetOpenFile(sock, fptr); @@ -400,8 +400,8 @@ retry: rb_gc_for_fd(e); goto retry; } - if (!rb_io_wait_readable(arg.fd)) - rsock_syserr_fail_path(e, "recvmsg(2)", fptr->pathv); + if (!rb_io_wait_readable(arg.fd)) + rsock_syserr_fail_path(e, "recvmsg(2)", fptr->pathv); } #if FD_PASSING_BY_MSG_CONTROL @@ -412,41 +412,41 @@ retry: rb_gc_for_fd(EMFILE); goto retry; } - rb_raise(rb_eSocket, - "file descriptor was not passed (msg_controllen=%d smaller than sizeof(struct cmsghdr)=%d)", - (int)arg.msg.msg_controllen, (int)sizeof(struct cmsghdr)); + rb_raise(rb_eSocket, + "file descriptor was not passed (msg_controllen=%d smaller than sizeof(struct cmsghdr)=%d)", + (int)arg.msg.msg_controllen, (int)sizeof(struct cmsghdr)); } if (cmsg.hdr.cmsg_level != SOL_SOCKET) { - rb_raise(rb_eSocket, - "file descriptor was not passed (cmsg_level=%d, %d expected)", - cmsg.hdr.cmsg_level, SOL_SOCKET); + rb_raise(rb_eSocket, + "file descriptor was not passed (cmsg_level=%d, %d expected)", + cmsg.hdr.cmsg_level, SOL_SOCKET); } if (cmsg.hdr.cmsg_type != SCM_RIGHTS) { - rb_raise(rb_eSocket, - "file descriptor was not passed (cmsg_type=%d, %d expected)", - cmsg.hdr.cmsg_type, SCM_RIGHTS); + rb_raise(rb_eSocket, + "file descriptor was not passed (cmsg_type=%d, %d expected)", + cmsg.hdr.cmsg_type, SCM_RIGHTS); } if (arg.msg.msg_controllen < (socklen_t)CMSG_LEN(sizeof(int))) { - rb_raise(rb_eSocket, - "file descriptor was not passed (msg_controllen=%d smaller than CMSG_LEN(sizeof(int))=%d)", - (int)arg.msg.msg_controllen, (int)CMSG_LEN(sizeof(int))); + rb_raise(rb_eSocket, + "file descriptor was not passed (msg_controllen=%d smaller than CMSG_LEN(sizeof(int))=%d)", + (int)arg.msg.msg_controllen, (int)CMSG_LEN(sizeof(int))); } if ((socklen_t)CMSG_SPACE(sizeof(int)) < arg.msg.msg_controllen) { - rb_raise(rb_eSocket, - "file descriptor was not passed (msg_controllen=%d bigger than CMSG_SPACE(sizeof(int))=%d)", - (int)arg.msg.msg_controllen, (int)CMSG_SPACE(sizeof(int))); + rb_raise(rb_eSocket, + "file descriptor was not passed (msg_controllen=%d bigger than CMSG_SPACE(sizeof(int))=%d)", + (int)arg.msg.msg_controllen, (int)CMSG_SPACE(sizeof(int))); } if (cmsg.hdr.cmsg_len != CMSG_LEN(sizeof(int))) { - rsock_discard_cmsg_resource(&arg.msg, 0); - rb_raise(rb_eSocket, - "file descriptor was not passed (cmsg_len=%d, %d expected)", - (int)cmsg.hdr.cmsg_len, (int)CMSG_LEN(sizeof(int))); + rsock_discard_cmsg_resource(&arg.msg, 0); + rb_raise(rb_eSocket, + "file descriptor was not passed (cmsg_len=%d, %d expected)", + (int)cmsg.hdr.cmsg_len, (int)CMSG_LEN(sizeof(int))); } #else if (arg.msg.msg_accrightslen != sizeof(fd)) { - rb_raise(rb_eSocket, - "file descriptor was not passed (accrightslen=%d, %d expected)", - arg.msg.msg_accrightslen, (int)sizeof(fd)); + rb_raise(rb_eSocket, + "file descriptor was not passed (accrightslen=%d, %d expected)", + arg.msg.msg_accrightslen, (int)sizeof(fd)); } #endif @@ -458,15 +458,15 @@ retry: rb_maygvl_fd_fix_cloexec(fd); if (klass == Qnil) - return INT2FIX(fd); + return INT2FIX(fd); else { - ID for_fd; - int ff_argc; - VALUE ff_argv[2]; - CONST_ID(for_fd, "for_fd"); - ff_argc = mode == Qnil ? 1 : 2; - ff_argv[0] = INT2FIX(fd); - ff_argv[1] = mode; + ID for_fd; + int ff_argc; + VALUE ff_argv[2]; + CONST_ID(for_fd, "for_fd"); + ff_argc = mode == Qnil ? 1 : 2; + ff_argv[0] = INT2FIX(fd); + ff_argv[1] = mode; return rb_funcallv(klass, for_fd, ff_argc, ff_argv); } } @@ -556,9 +556,9 @@ unix_s_socketpair(int argc, VALUE *argv, VALUE klass) domain = INT2FIX(PF_UNIX); rb_scan_args(argc, argv, "02", &type, &protocol); if (argc == 0) - type = INT2FIX(SOCK_STREAM); + type = INT2FIX(SOCK_STREAM); if (argc <= 1) - protocol = INT2FIX(0); + protocol = INT2FIX(0); args[0] = domain; args[1] = type; diff --git a/ext/syslog/syslog.c b/ext/syslog/syslog.c index 4c540fc9c7..8f3674aa8d 100644 --- a/ext/syslog/syslog.c +++ b/ext/syslog/syslog.c @@ -165,15 +165,15 @@ static VALUE mSyslog_open(int argc, VALUE *argv, VALUE self) syslog_ident = strdup(ident_ptr); if (NIL_P(opt)) { - syslog_options = LOG_PID | LOG_CONS; + syslog_options = LOG_PID | LOG_CONS; } else { - syslog_options = NUM2INT(opt); + syslog_options = NUM2INT(opt); } if (NIL_P(fac)) { - syslog_facility = LOG_USER; + syslog_facility = LOG_USER; } else { - syslog_facility = NUM2INT(fac); + syslog_facility = NUM2INT(fac); } openlog(syslog_ident, syslog_options, syslog_facility); @@ -307,7 +307,7 @@ static VALUE mSyslog_log(int argc, VALUE *argv, VALUE self) pri = *argv++; if (!FIXNUM_P(pri)) { - rb_raise(rb_eTypeError, "type mismatch: %"PRIsVALUE" given", rb_obj_class(pri)); + rb_raise(rb_eTypeError, "type mismatch: %"PRIsVALUE" given", rb_obj_class(pri)); } syslog_write(FIX2INT(pri), argc, argv); @@ -322,14 +322,14 @@ static VALUE mSyslog_inspect(VALUE self) Check_Type(self, T_MODULE); if (!syslog_opened) - return rb_sprintf("<#%"PRIsVALUE": opened=false>", self); + return rb_sprintf("<#%"PRIsVALUE": opened=false>", self); return rb_sprintf("<#%"PRIsVALUE": opened=true, ident=\"%s\", options=%d, facility=%d, mask=%d>", - self, - syslog_ident, - syslog_options, - syslog_facility, - syslog_mask); + self, + syslog_ident, + syslog_options, + syslog_facility, + syslog_mask); } /* Returns self, for backward compatibility. diff --git a/ext/win32/resolv/resolv.c b/ext/win32/resolv/resolv.c index f19243ccc1..8a50ef7824 100644 --- a/ext/win32/resolv/resolv.c +++ b/ext/win32/resolv/resolv.c @@ -29,19 +29,19 @@ get_dns_server_list(VALUE self) ret = GetNetworkParams(NULL, &buflen); if (ret != NO_ERROR && ret != ERROR_BUFFER_OVERFLOW) { - w32error_raise(ret); + w32error_raise(ret); } fixedinfo = ALLOCV(buf, buflen); ret = GetNetworkParams(fixedinfo, &buflen); if (ret == NO_ERROR) { - const IP_ADDR_STRING *ipaddr = &fixedinfo->DnsServerList; - nameservers = rb_ary_new(); - do { - const char *s = ipaddr->IpAddress.String; - if (!*s) continue; - if (strcmp(s, "0.0.0.0") == 0) continue; - rb_ary_push(nameservers, rb_str_new_cstr(s)); - } while ((ipaddr = ipaddr->Next) != NULL); + const IP_ADDR_STRING *ipaddr = &fixedinfo->DnsServerList; + nameservers = rb_ary_new(); + do { + const char *s = ipaddr->IpAddress.String; + if (!*s) continue; + if (strcmp(s, "0.0.0.0") == 0) continue; + rb_ary_push(nameservers, rb_str_new_cstr(s)); + } while ((ipaddr = ipaddr->Next) != NULL); } ALLOCV_END(buf); if (ret != NO_ERROR) w32error_raise(ret); diff --git a/ext/win32ole/win32ole.c b/ext/win32ole/win32ole.c index d77347b3a3..3f083bb12d 100644 --- a/ext/win32ole/win32ole.c +++ b/ext/win32ole/win32ole.c @@ -454,12 +454,12 @@ vtdate2rbtime(double date) double sec; VariantTimeToSystemTime(date, &st); v = rb_funcall(rb_cTime, rb_intern("new"), 6, - RB_INT2FIX(st.wYear), - RB_INT2FIX(st.wMonth), - RB_INT2FIX(st.wDay), - RB_INT2FIX(st.wHour), - RB_INT2FIX(st.wMinute), - RB_INT2FIX(st.wSecond)); + RB_INT2FIX(st.wYear), + RB_INT2FIX(st.wMonth), + RB_INT2FIX(st.wDay), + RB_INT2FIX(st.wHour), + RB_INT2FIX(st.wMinute), + RB_INT2FIX(st.wSecond)); st.wYear = RB_FIX2INT(rb_funcall(v, rb_intern("year"), 0)); st.wMonth = RB_FIX2INT(rb_funcall(v, rb_intern("month"), 0)); st.wDay = RB_FIX2INT(rb_funcall(v, rb_intern("mday"), 0)); @@ -568,16 +568,16 @@ load_conv_function51932(void) void *p; if (!pIMultiLanguage) { #if defined(HAVE_TYPE_IMULTILANGUAGE2) - hr = CoCreateInstance(&CLSID_CMultiLanguage, NULL, CLSCTX_INPROC_SERVER, - &IID_IMultiLanguage2, &p); + hr = CoCreateInstance(&CLSID_CMultiLanguage, NULL, CLSCTX_INPROC_SERVER, + &IID_IMultiLanguage2, &p); #elif defined(HAVE_TYPE_IMULTILANGUAGE) - hr = CoCreateInstance(&CLSID_CMultiLanguage, NULL, CLSCTX_INPROC_SERVER, - &IID_IMultiLanguage, &p); + hr = CoCreateInstance(&CLSID_CMultiLanguage, NULL, CLSCTX_INPROC_SERVER, + &IID_IMultiLanguage, &p); #endif - if (FAILED(hr)) { - failed_load_conv51932(); - } - pIMultiLanguage = p; + if (FAILED(hr)) { + failed_load_conv51932(); + } + pIMultiLanguage = p; } } #define need_conv_function51932() (load_conv_function51932(), 1) @@ -624,7 +624,7 @@ ole_init_cp(void) rb_encoding *encdef; encdef = rb_default_internal_encoding(); if (!encdef) { - encdef = rb_default_external_encoding(); + encdef = rb_default_external_encoding(); } cp = ole_encoding2cp(encdef); set_ole_codepage(cp); @@ -650,38 +650,38 @@ ole_cp2encoding(UINT cp) int idx; if (!code_page_installed(cp)) { - switch(cp) { - case CP_ACP: - cp = GetACP(); - break; - case CP_OEMCP: - cp = GetOEMCP(); - break; - case CP_MACCP: - case CP_THREAD_ACP: - if (!pGetCPInfoEx) { - pGetCPInfoEx = (BOOL (*)(UINT, DWORD, struct myCPINFOEX *)) - GetProcAddress(GetModuleHandle("kernel32"), "GetCPInfoEx"); - if (!pGetCPInfoEx) { - pGetCPInfoEx = (void*)-1; - } - } - buf = ALLOCA_N(struct myCPINFOEX, 1); - ZeroMemory(buf, sizeof(struct myCPINFOEX)); - if (pGetCPInfoEx == (void*)-1 || !pGetCPInfoEx(cp, 0, buf)) { - rb_raise(eWIN32OLERuntimeError, "cannot map codepage to encoding."); - break; /* never reach here */ - } - cp = buf->CodePage; - break; - case CP_SYMBOL: - case CP_UTF7: - case CP_UTF8: - break; - case 51932: - load_conv_function51932(); - break; - default: + switch(cp) { + case CP_ACP: + cp = GetACP(); + break; + case CP_OEMCP: + cp = GetOEMCP(); + break; + case CP_MACCP: + case CP_THREAD_ACP: + if (!pGetCPInfoEx) { + pGetCPInfoEx = (BOOL (*)(UINT, DWORD, struct myCPINFOEX *)) + GetProcAddress(GetModuleHandle("kernel32"), "GetCPInfoEx"); + if (!pGetCPInfoEx) { + pGetCPInfoEx = (void*)-1; + } + } + buf = ALLOCA_N(struct myCPINFOEX, 1); + ZeroMemory(buf, sizeof(struct myCPINFOEX)); + if (pGetCPInfoEx == (void*)-1 || !pGetCPInfoEx(cp, 0, buf)) { + rb_raise(eWIN32OLERuntimeError, "cannot map codepage to encoding."); + break; /* never reach here */ + } + cp = buf->CodePage; + break; + case CP_SYMBOL: + case CP_UTF7: + case CP_UTF8: + break; + case 51932: + load_conv_function51932(); + break; + default: rb_raise(eWIN32OLERuntimeError, "codepage should be WIN32OLE::CP_ACP, WIN32OLE::CP_OEMCP, WIN32OLE::CP_MACCP, WIN32OLE::CP_THREAD_ACP, WIN32OLE::CP_SYMBOL, WIN32OLE::CP_UTF7, WIN32OLE::CP_UTF8, or installed codepage."); break; } @@ -690,7 +690,7 @@ ole_cp2encoding(UINT cp) enc_name = rb_sprintf("CP%d", cp); idx = rb_enc_find_index(enc_cstr = StringValueCStr(enc_name)); if (idx < 0) - idx = rb_define_dummy_encoding(enc_cstr); + idx = rb_define_dummy_encoding(enc_cstr); return rb_enc_from_index(idx); } @@ -700,14 +700,14 @@ ole_ml_wc2mb_conv0(LPWSTR pw, LPSTR pm, UINT *size) { DWORD dw = 0; return pIMultiLanguage->lpVtbl->ConvertStringFromUnicode(pIMultiLanguage, - &dw, cWIN32OLE_cp, pw, NULL, pm, size); + &dw, cWIN32OLE_cp, pw, NULL, pm, size); } #define ole_ml_wc2mb_conv(pw, pm, size, onfailure) do { \ - HRESULT hr = ole_ml_wc2mb_conv0(pw, pm, &size); \ - if (FAILED(hr)) { \ - onfailure; \ - ole_raise(hr, eWIN32OLERuntimeError, "fail to convert Unicode to CP%d", cWIN32OLE_cp); \ - } \ + HRESULT hr = ole_ml_wc2mb_conv0(pw, pm, &size); \ + if (FAILED(hr)) { \ + onfailure; \ + ole_raise(hr, eWIN32OLERuntimeError, "fail to convert Unicode to CP%d", cWIN32OLE_cp); \ + } \ } while (0) #endif @@ -720,11 +720,11 @@ ole_wc2mb_alloc(LPWSTR pw, char *(alloc)(UINT size, void *arg), void *arg) UINT size = 0; if (conv_51932(cWIN32OLE_cp)) { #ifndef pIMultiLanguage - ole_ml_wc2mb_conv(pw, NULL, size, {}); - pm = alloc(size, arg); - if (size) ole_ml_wc2mb_conv(pw, pm, size, xfree(pm)); - pm[size] = '\0'; - return pm; + ole_ml_wc2mb_conv(pw, NULL, size, {}); + pm = alloc(size, arg); + if (size) ole_ml_wc2mb_conv(pw, pm, size, xfree(pm)); + pm[size] = '\0'; + return pm; #endif } size = ole_wc2mb_conv(pw, NULL, 0); @@ -816,8 +816,8 @@ ole_initialize(void) HRESULT hr; if(!g_uninitialize_hooked) { - rb_add_event_hook(ole_uninitialize_hook, RUBY_EVENT_THREAD_END, Qnil); - g_uninitialize_hooked = TRUE; + rb_add_event_hook(ole_uninitialize_hook, RUBY_EVENT_THREAD_END, Qnil); + g_uninitialize_hooked = TRUE; } if(g_ole_initialized == FALSE) { @@ -911,21 +911,21 @@ ole_mb2wc(char *pm, int len, UINT cp) if (conv_51932(cp)) { #ifndef pIMultiLanguage - DWORD dw = 0; - UINT n = len; - HRESULT hr = pIMultiLanguage->lpVtbl->ConvertStringToUnicode(pIMultiLanguage, - &dw, cp, pm, &n, NULL, &size); - if (FAILED(hr)) { + DWORD dw = 0; + UINT n = len; + HRESULT hr = pIMultiLanguage->lpVtbl->ConvertStringToUnicode(pIMultiLanguage, + &dw, cp, pm, &n, NULL, &size); + if (FAILED(hr)) { ole_raise(hr, eWIN32OLERuntimeError, "fail to convert CP%d to Unicode", cp); - } - pw = SysAllocStringLen(NULL, size); - n = len; - hr = pIMultiLanguage->lpVtbl->ConvertStringToUnicode(pIMultiLanguage, - &dw, cp, pm, &n, pw, &size); - if (FAILED(hr)) { + } + pw = SysAllocStringLen(NULL, size); + n = len; + hr = pIMultiLanguage->lpVtbl->ConvertStringToUnicode(pIMultiLanguage, + &dw, cp, pm, &n, pw, &size); + if (FAILED(hr)) { ole_raise(hr, eWIN32OLERuntimeError, "fail to convert CP%d to Unicode", cp); - } - return pw; + } + return pw; #endif } size = MultiByteToWideChar(cp, 0, pm, len, NULL, 0); @@ -1737,11 +1737,11 @@ reg_get_val(HKEY hkey, const char *subkey) if (err == ERROR_SUCCESS) { pbuf[size] = '\0'; if (dwtype == REG_EXPAND_SZ) { - char* pbuf2 = (char *)pbuf; - DWORD len = ExpandEnvironmentStrings(pbuf2, NULL, 0); - pbuf = ALLOC_N(char, len + 1); - ExpandEnvironmentStrings(pbuf2, pbuf, len + 1); - free(pbuf2); + char* pbuf2 = (char *)pbuf; + DWORD len = ExpandEnvironmentStrings(pbuf2, NULL, 0); + pbuf = ALLOC_N(char, len + 1); + ExpandEnvironmentStrings(pbuf2, pbuf, len + 1); + free(pbuf2); } val = rb_str_new2((char *)pbuf); } @@ -2555,7 +2555,7 @@ hash2named_arg(VALUE key, VALUE val, VALUE pop) rb_raise(rb_eTypeError, "wrong argument type (expected String or Symbol)"); } if (RB_TYPE_P(key, T_SYMBOL)) { - key = rb_sym2str(key); + key = rb_sym2str(key); } /* pNamedArgs[0] is , so "index + 1" */ @@ -2619,10 +2619,10 @@ ole_invoke(int argc, VALUE *argv, VALUE self, USHORT wFlags, BOOL is_bracket) rb_scan_args(argc, argv, "1*", &cmd, ¶mS); if(!RB_TYPE_P(cmd, T_STRING) && !RB_TYPE_P(cmd, T_SYMBOL) && !is_bracket) { - rb_raise(rb_eTypeError, "method is wrong type (expected String or Symbol)"); + rb_raise(rb_eTypeError, "method is wrong type (expected String or Symbol)"); } if (RB_TYPE_P(cmd, T_SYMBOL)) { - cmd = rb_sym2str(cmd); + cmd = rb_sym2str(cmd); } pole = oledata_get_struct(self); if(!pole->pDispatch) { @@ -2631,7 +2631,7 @@ ole_invoke(int argc, VALUE *argv, VALUE self, USHORT wFlags, BOOL is_bracket) if (is_bracket) { DispID = DISPID_VALUE; argc += 1; - rb_ary_unshift(paramS, cmd); + rb_ary_unshift(paramS, cmd); } else { wcmdname = ole_vstr2wc(cmd); hr = pole->pDispatch->lpVtbl->GetIDsOfNames( pole->pDispatch, &IID_NULL, @@ -3639,7 +3639,7 @@ fole_respond_to(VALUE self, VALUE method) pole = oledata_get_struct(self); wcmdname = ole_vstr2wc(method); hr = pole->pDispatch->lpVtbl->GetIDsOfNames( pole->pDispatch, &IID_NULL, - &wcmdname, 1, cWIN32OLE_lcid, &DispID); + &wcmdname, 1, cWIN32OLE_lcid, &DispID); SysFreeString(wcmdname); return SUCCEEDED(hr) ? Qtrue : Qfalse; } diff --git a/ext/win32ole/win32ole_event.c b/ext/win32ole/win32ole_event.c index 93e4d6bad5..45ebf13433 100644 --- a/ext/win32ole/win32ole_event.c +++ b/ext/win32ole/win32ole_event.c @@ -200,7 +200,7 @@ STDMETHODIMP EVENTSINK_Invoke( } outargv = Qnil; if (is_outarg == Qtrue) { - outargv = rb_ary_new(); + outargv = rb_ary_new(); rb_ary_push(args, outargv); } @@ -413,15 +413,15 @@ hash2ptr_dispparams(VALUE hash, ITypeInfo *pTypeInfo, DISPID dispid, DISPPARAMS bstrs, pdispparams->cArgs + 1, &len); if (FAILED(hr)) - return; + return; for (i = 0; i < len - 1; i++) { - key = WC2VSTR(bstrs[i + 1]); + key = WC2VSTR(bstrs[i + 1]); val = rb_hash_aref(hash, RB_UINT2NUM(i)); - if (val == Qnil) - val = rb_hash_aref(hash, key); - if (val == Qnil) - val = rb_hash_aref(hash, rb_str_intern(key)); + if (val == Qnil) + val = rb_hash_aref(hash, key); + if (val == Qnil) + val = rb_hash_aref(hash, rb_str_intern(key)); pvar = &pdispparams->rgvarg[pdispparams->cArgs-i-1]; ole_val2ptr_variant(val, pvar); } @@ -433,7 +433,7 @@ hash2result(VALUE hash) VALUE ret = Qnil; ret = rb_hash_aref(hash, rb_str_new2("return")); if (ret == Qnil) - ret = rb_hash_aref(hash, rb_str_intern(rb_str_new2("return"))); + ret = rb_hash_aref(hash, rb_str_intern(rb_str_new2("return"))); return ret; } @@ -610,7 +610,7 @@ find_coclass( hr = pTypeInfo->lpVtbl->GetContainingTypeLib(pTypeInfo, &pTypeLib, NULL); if (FAILED(hr)) { - return hr; + return hr; } count = pTypeLib->lpVtbl->GetTypeInfoCount(pTypeLib); for (i = 0; i < count && !found; i++) { diff --git a/ext/win32ole/win32ole_typelib.c b/ext/win32ole/win32ole_typelib.c index 651dc2d75f..fb68bebda8 100644 --- a/ext/win32ole/win32ole_typelib.c +++ b/ext/win32ole/win32ole_typelib.c @@ -285,7 +285,7 @@ oletypelib_get_libattr(ITypeLib *pTypeLib, TLIBATTR **ppTLibAttr) hr = pTypeLib->lpVtbl->GetLibAttr(pTypeLib, ppTLibAttr); if (FAILED(hr)) { ole_raise(hr, eWIN32OLERuntimeError, - "failed to get library attribute(TLIBATTR) from ITypeLib"); + "failed to get library attribute(TLIBATTR) from ITypeLib"); } } @@ -588,13 +588,13 @@ foletypelib_path(VALUE self) pTypeLib = itypelib(self); oletypelib_get_libattr(pTypeLib, &pTLibAttr); hr = QueryPathOfRegTypeLib(&pTLibAttr->guid, - pTLibAttr->wMajorVerNum, - pTLibAttr->wMinorVerNum, - lcid, - &bstr); + pTLibAttr->wMajorVerNum, + pTLibAttr->wMinorVerNum, + lcid, + &bstr); if (FAILED(hr)) { - pTypeLib->lpVtbl->ReleaseTLibAttr(pTypeLib, pTLibAttr); - ole_raise(hr, eWIN32OLERuntimeError, "failed to QueryPathOfRegTypeTypeLib"); + pTypeLib->lpVtbl->ReleaseTLibAttr(pTypeLib, pTLibAttr); + ole_raise(hr, eWIN32OLERuntimeError, "failed to QueryPathOfRegTypeTypeLib"); } pTypeLib->lpVtbl->ReleaseTLibAttr(pTypeLib, pTLibAttr); @@ -722,7 +722,7 @@ typelib_file_from_typelib(VALUE ole) if (ver == Qnil) break; err = reg_open_vkey(hclsid, ver, &hversion); - if (err != ERROR_SUCCESS || fver > atof(StringValuePtr(ver))) + if (err != ERROR_SUCCESS || fver > atof(StringValuePtr(ver))) continue; fver = atof(StringValuePtr(ver)); typelib = reg_get_val(hversion, NULL); diff --git a/file.c b/file.c index 417bfc5814..5265d3a3a5 100644 --- a/file.c +++ b/file.c @@ -182,15 +182,15 @@ file_path_convert(VALUE name) int fname_encidx = ENCODING_GET(name); int fs_encidx; if (ENCINDEX_US_ASCII != fname_encidx && - ENCINDEX_ASCII_8BIT != fname_encidx && - (fs_encidx = rb_filesystem_encindex()) != fname_encidx && - rb_default_internal_encoding() && - !rb_enc_str_asciionly_p(name)) { - /* Don't call rb_filesystem_encoding() before US-ASCII and ASCII-8BIT */ - /* fs_encoding should be ascii compatible */ - rb_encoding *fname_encoding = rb_enc_from_index(fname_encidx); - rb_encoding *fs_encoding = rb_enc_from_index(fs_encidx); - name = rb_str_conv_enc(name, fname_encoding, fs_encoding); + ENCINDEX_ASCII_8BIT != fname_encidx && + (fs_encidx = rb_filesystem_encindex()) != fname_encidx && + rb_default_internal_encoding() && + !rb_enc_str_asciionly_p(name)) { + /* Don't call rb_filesystem_encoding() before US-ASCII and ASCII-8BIT */ + /* fs_encoding should be ascii compatible */ + rb_encoding *fname_encoding = rb_enc_from_index(fname_encidx); + rb_encoding *fs_encoding = rb_enc_from_index(fs_encidx); + name = rb_str_conv_enc(name, fname_encoding, fs_encoding); } #endif return name; @@ -201,8 +201,8 @@ check_path_encoding(VALUE str) { rb_encoding *enc = rb_enc_get(str); if (!rb_enc_asciicompat(enc)) { - rb_raise(rb_eEncCompatError, "path name must be ASCII-compatible (%s): %"PRIsVALUE, - rb_enc_name(enc), rb_str_inspect(str)); + rb_raise(rb_eEncCompatError, "path name must be ASCII-compatible (%s): %"PRIsVALUE, + rb_enc_name(enc), rb_str_inspect(str)); } return enc; } @@ -214,7 +214,7 @@ rb_get_path_check_to_string(VALUE obj) ID to_path; if (RB_TYPE_P(obj, T_STRING)) { - return obj; + return obj; } CONST_ID(to_path, "to_path"); tmp = rb_check_funcall_default(obj, to_path, 0, 0, obj); @@ -229,7 +229,7 @@ rb_get_path_check_convert(VALUE obj) check_path_encoding(obj); if (!rb_str_to_cstr(obj)) { - rb_raise(rb_eArgError, "path name contains null byte"); + rb_raise(rb_eArgError, "path name contains null byte"); } return rb_str_new4(obj); @@ -254,13 +254,13 @@ rb_str_encode_ospath(VALUE path) int encidx = ENCODING_GET(path); #if 0 && defined _WIN32 if (encidx == ENCINDEX_ASCII_8BIT) { - encidx = rb_filesystem_encindex(); + encidx = rb_filesystem_encindex(); } #endif if (encidx != ENCINDEX_ASCII_8BIT && encidx != ENCINDEX_UTF_8) { - rb_encoding *enc = rb_enc_from_index(encidx); - rb_encoding *utf8 = rb_utf8_encoding(); - path = rb_str_conv_enc(path, enc, utf8); + rb_encoding *enc = rb_enc_from_index(encidx); + rb_encoding *utf8 = rb_utf8_encoding(); + path = rb_str_conv_enc(path, enc, utf8); } #endif return path; @@ -274,9 +274,9 @@ rb_str_append_normalized_ospath(VALUE str, const char *ptr, long len) CFIndex buflen = 0; CFRange all; CFStringRef s = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, - (const UInt8 *)ptr, len, - kCFStringEncodingUTF8, FALSE, - kCFAllocatorNull); + (const UInt8 *)ptr, len, + kCFStringEncodingUTF8, FALSE, + kCFAllocatorNull); CFMutableStringRef m = CFStringCreateMutableCopy(kCFAllocatorDefault, len, s); long oldlen = RSTRING_LEN(str); @@ -285,7 +285,7 @@ rb_str_append_normalized_ospath(VALUE str, const char *ptr, long len) CFStringGetBytes(m, all, kCFStringEncodingUTF8, '?', FALSE, NULL, 0, &buflen); rb_str_modify_expand(str, buflen); CFStringGetBytes(m, all, kCFStringEncodingUTF8, '?', FALSE, - (UInt8 *)(RSTRING_PTR(str) + oldlen), buflen, &buflen); + (UInt8 *)(RSTRING_PTR(str) + oldlen), buflen, &buflen); rb_str_set_len(str, oldlen + buflen); CFRelease(m); CFRelease(s); @@ -303,34 +303,34 @@ rb_str_normalize_ospath(const char *ptr, long len) rb_enc_associate(str, enc); while (p < e) { - int l, c; - int r = rb_enc_precise_mbclen(p, e, enc); - if (!MBCLEN_CHARFOUND_P(r)) { - /* invalid byte shall not happen but */ - static const char invalid[3] = "\xEF\xBF\xBD"; - rb_str_append_normalized_ospath(str, p1, p-p1); - rb_str_cat(str, invalid, sizeof(invalid)); - p += 1; - p1 = p; - continue; - } - l = MBCLEN_CHARFOUND_LEN(r); - c = rb_enc_mbc_to_codepoint(p, e, enc); - if ((0x2000 <= c && c <= 0x2FFF) || (0xF900 <= c && c <= 0xFAFF) || - (0x2F800 <= c && c <= 0x2FAFF)) { - if (p - p1 > 0) { - rb_str_append_normalized_ospath(str, p1, p-p1); - } - rb_str_cat(str, p, l); - p += l; - p1 = p; - } - else { - p += l; - } + int l, c; + int r = rb_enc_precise_mbclen(p, e, enc); + if (!MBCLEN_CHARFOUND_P(r)) { + /* invalid byte shall not happen but */ + static const char invalid[3] = "\xEF\xBF\xBD"; + rb_str_append_normalized_ospath(str, p1, p-p1); + rb_str_cat(str, invalid, sizeof(invalid)); + p += 1; + p1 = p; + continue; + } + l = MBCLEN_CHARFOUND_LEN(r); + c = rb_enc_mbc_to_codepoint(p, e, enc); + if ((0x2000 <= c && c <= 0x2FFF) || (0xF900 <= c && c <= 0xFAFF) || + (0x2F800 <= c && c <= 0x2FAFF)) { + if (p - p1 > 0) { + rb_str_append_normalized_ospath(str, p1, p-p1); + } + rb_str_cat(str, p, l); + p += l; + p1 = p; + } + else { + p += l; + } } if (p - p1 > 0) { - rb_str_append_normalized_ospath(str, p1, p-p1); + rb_str_append_normalized_ospath(str, p1, p-p1); } return str; @@ -343,27 +343,27 @@ ignored_char_p(const char *p, const char *e, rb_encoding *enc) if (p+3 > e) return 0; switch ((unsigned char)*p) { case 0xe2: - switch ((unsigned char)p[1]) { - case 0x80: - c = (unsigned char)p[2]; - /* c >= 0x200c && c <= 0x200f */ - if (c >= 0x8c && c <= 0x8f) return 3; - /* c >= 0x202a && c <= 0x202e */ - if (c >= 0xaa && c <= 0xae) return 3; - return 0; - case 0x81: - c = (unsigned char)p[2]; - /* c >= 0x206a && c <= 0x206f */ - if (c >= 0xaa && c <= 0xaf) return 3; - return 0; - } - break; + switch ((unsigned char)p[1]) { + case 0x80: + c = (unsigned char)p[2]; + /* c >= 0x200c && c <= 0x200f */ + if (c >= 0x8c && c <= 0x8f) return 3; + /* c >= 0x202a && c <= 0x202e */ + if (c >= 0xaa && c <= 0xae) return 3; + return 0; + case 0x81: + c = (unsigned char)p[2]; + /* c >= 0x206a && c <= 0x206f */ + if (c >= 0xaa && c <= 0xaf) return 3; + return 0; + } + break; case 0xef: - /* c == 0xfeff */ - if ((unsigned char)p[1] == 0xbb && - (unsigned char)p[2] == 0xbf) - return 3; - break; + /* c == 0xfeff */ + if ((unsigned char)p[1] == 0xbb && + (unsigned char)p[2] == 0xbf) + return 3; + break; } return 0; } @@ -393,10 +393,10 @@ no_gvl_apply2files(void *ptr) struct apply_arg *aa = ptr; for (aa->i = 0; aa->i < aa->argc; aa->i++) { - if (aa->func(aa->fn[aa->i].ptr, aa->arg) < 0) { - aa->errnum = errno; - break; - } + if (aa->func(aa->fn[aa->i].ptr, aa->arg) < 0) { + aa->errnum = errno; + break; + } } return 0; } @@ -420,24 +420,24 @@ apply2files(int (*func)(const char *, void *), int argc, VALUE *argv, void *arg) aa->func = func; for (aa->i = 0; aa->i < argc; aa->i++) { - VALUE path = rb_get_path(argv[aa->i]); + VALUE path = rb_get_path(argv[aa->i]); - path = rb_str_encode_ospath(path); - aa->fn[aa->i].ptr = RSTRING_PTR(path); - aa->fn[aa->i].path = path; + path = rb_str_encode_ospath(path); + aa->fn[aa->i].ptr = RSTRING_PTR(path); + aa->fn[aa->i].path = path; } rb_thread_call_without_gvl(no_gvl_apply2files, aa, RUBY_UBF_IO, 0); if (aa->errnum) { #ifdef UTIME_EINVAL - if (func == utime_internal) { - utime_failed(aa); - } + if (func == utime_internal) { + utime_failed(aa); + } #endif - rb_syserr_fail_path(aa->errnum, aa->fn[aa->i].path); + rb_syserr_fail_path(aa->errnum, aa->fn[aa->i].path); } if (v) { - ALLOCV_END(v); + ALLOCV_END(v); } return LONG2FIX(argc); } @@ -496,9 +496,9 @@ stat_new_0(VALUE klass, const struct stat *st) VALUE obj = TypedData_Wrap_Struct(klass, &stat_data_type, 0); if (st) { - nst = ALLOC(struct stat); - *nst = *st; - RTYPEDDATA_DATA(obj) = nst; + nst = ALLOC(struct stat); + *nst = *st; + RTYPEDDATA_DATA(obj) = nst; } return obj; } @@ -1065,24 +1065,24 @@ rb_stat_inspect(VALUE self) VALUE str; size_t i; static const struct { - const char *name; - VALUE (*func)(VALUE); + const char *name; + VALUE (*func)(VALUE); } member[] = { - {"dev", rb_stat_dev}, - {"ino", rb_stat_ino}, - {"mode", rb_stat_mode}, - {"nlink", rb_stat_nlink}, - {"uid", rb_stat_uid}, - {"gid", rb_stat_gid}, - {"rdev", rb_stat_rdev}, - {"size", rb_stat_size}, - {"blksize", rb_stat_blksize}, - {"blocks", rb_stat_blocks}, - {"atime", rb_stat_atime}, - {"mtime", rb_stat_mtime}, - {"ctime", rb_stat_ctime}, + {"dev", rb_stat_dev}, + {"ino", rb_stat_ino}, + {"mode", rb_stat_mode}, + {"nlink", rb_stat_nlink}, + {"uid", rb_stat_uid}, + {"gid", rb_stat_gid}, + {"rdev", rb_stat_rdev}, + {"size", rb_stat_size}, + {"blksize", rb_stat_blksize}, + {"blocks", rb_stat_blocks}, + {"atime", rb_stat_atime}, + {"mtime", rb_stat_mtime}, + {"ctime", rb_stat_ctime}, #if defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC) - {"birthtime", rb_stat_birthtime}, + {"birthtime", rb_stat_birthtime}, #endif }; @@ -1097,23 +1097,23 @@ rb_stat_inspect(VALUE self) rb_str_buf_cat2(str, " "); for (i = 0; i < sizeof(member)/sizeof(member[0]); i++) { - VALUE v; + VALUE v; - if (i > 0) { - rb_str_buf_cat2(str, ", "); - } - rb_str_buf_cat2(str, member[i].name); - rb_str_buf_cat2(str, "="); - v = (*member[i].func)(self); - if (i == 2) { /* mode */ - rb_str_catf(str, "0%lo", (unsigned long)NUM2ULONG(v)); - } - else if (i == 0 || i == 6) { /* dev/rdev */ - rb_str_catf(str, "0x%"PRI_DEVT_PREFIX"x", NUM2DEVT(v)); - } - else { - rb_str_append(str, rb_inspect(v)); - } + if (i > 0) { + rb_str_buf_cat2(str, ", "); + } + rb_str_buf_cat2(str, member[i].name); + rb_str_buf_cat2(str, "="); + v = (*member[i].func)(self); + if (i == 2) { /* mode */ + rb_str_catf(str, "0%lo", (unsigned long)NUM2ULONG(v)); + } + else if (i == 0 || i == 6) { /* dev/rdev */ + rb_str_catf(str, "0x%"PRI_DEVT_PREFIX"x", NUM2DEVT(v)); + } + else { + rb_str_append(str, rb_inspect(v)); + } } rb_str_buf_cat2(str, ">"); @@ -1123,8 +1123,8 @@ rb_stat_inspect(VALUE self) typedef struct no_gvl_stat_data { struct stat *st; union { - const char *path; - int fd; + const char *path; + int fd; } file; } no_gvl_stat_data; @@ -1162,7 +1162,7 @@ stat_without_gvl(const char *path, struct stat *st) data.st = st; return (int)(VALUE)rb_thread_call_without_gvl(no_gvl_stat, &data, - RUBY_UBF_IO, NULL); + RUBY_UBF_IO, NULL); } #if !defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC) && \ @@ -1292,16 +1292,16 @@ rb_stat(VALUE file, struct stat *st) tmp = rb_check_convert_type_with_id(file, T_FILE, "IO", idTo_io); if (!NIL_P(tmp)) { - rb_io_t *fptr; + rb_io_t *fptr; - GetOpenFile(tmp, fptr); - result = fstat_without_gvl(fptr->fd, st); - file = tmp; + GetOpenFile(tmp, fptr); + result = fstat_without_gvl(fptr->fd, st); + file = tmp; } else { - FilePathValue(file); - file = rb_str_encode_ospath(file); - result = stat_without_gvl(RSTRING_PTR(file), st); + FilePathValue(file); + file = rb_str_encode_ospath(file); + result = stat_without_gvl(RSTRING_PTR(file), st); } RB_GC_GUARD(file); return result; @@ -1325,7 +1325,7 @@ rb_file_s_stat(VALUE klass, VALUE fname) FilePathValue(fname); fname = rb_str_encode_ospath(fname); if (stat_without_gvl(RSTRING_PTR(fname), &st) < 0) { - rb_sys_fail_path(fname); + rb_sys_fail_path(fname); } return rb_stat_new(&st); } @@ -1353,7 +1353,7 @@ rb_io_stat(VALUE obj) GetOpenFile(obj, fptr); if (fstat(fptr->fd, &st) == -1) { - rb_sys_fail_path(fptr->pathv); + rb_sys_fail_path(fptr->pathv); } return rb_stat_new(&st); } @@ -1375,7 +1375,7 @@ lstat_without_gvl(const char *path, struct stat *st) data.st = st; return (int)(VALUE)rb_thread_call_without_gvl(no_gvl_lstat, &data, - RUBY_UBF_IO, NULL); + RUBY_UBF_IO, NULL); } #endif /* HAVE_LSTAT */ @@ -1401,7 +1401,7 @@ rb_file_s_lstat(VALUE klass, VALUE fname) FilePathValue(fname); fname = rb_str_encode_ospath(fname); if (lstat_without_gvl(StringValueCStr(fname), &st) == -1) { - rb_sys_fail_path(fname); + rb_sys_fail_path(fname); } return rb_stat_new(&st); #else @@ -1435,7 +1435,7 @@ rb_file_lstat(VALUE obj) if (NIL_P(fptr->pathv)) return Qnil; path = rb_str_encode_ospath(fptr->pathv); if (lstat_without_gvl(RSTRING_PTR(path), &st) == -1) { - rb_sys_fail_path(fptr->pathv); + rb_sys_fail_path(fptr->pathv); } return rb_stat_new(&st); #else @@ -1456,19 +1456,19 @@ rb_group_member(GETGROUPS_T gid) int anum = -1; if (getgid() == gid || getegid() == gid) - return TRUE; + return TRUE; groups = getgroups(0, NULL); gary = ALLOCV_N(GETGROUPS_T, v, groups); anum = getgroups(groups, gary); while (--anum >= 0) { - if (gary[anum] == gid) { - rv = TRUE; - break; - } + if (gary[anum] == gid) { + rv = TRUE; + break; + } } if (v) - ALLOCV_END(v); + ALLOCV_END(v); return rv; #endif @@ -1494,28 +1494,28 @@ eaccess(const char *path, int mode) /* no setuid nor setgid. run shortcut. */ if (getuid() == euid && getgid() == getegid()) - return access(path, mode); + return access(path, mode); if (STAT(path, &st) < 0) - return -1; + return -1; if (euid == 0) { - /* Root can read or write any file. */ - if (!(mode & X_OK)) - return 0; + /* Root can read or write any file. */ + if (!(mode & X_OK)) + return 0; - /* Root can execute any file that has any one of the execute - bits set. */ - if (st.st_mode & S_IXUGO) - return 0; + /* Root can execute any file that has any one of the execute + bits set. */ + if (st.st_mode & S_IXUGO) + return 0; - return -1; + return -1; } if (st.st_uid == euid) /* owner */ - mode <<= 6; + mode <<= 6; else if (rb_group_member(st.st_gid)) - mode <<= 3; + mode <<= 3; if ((int)(st.st_mode & mode) == mode) return 0; @@ -1550,7 +1550,7 @@ rb_eaccess(VALUE fname, int mode) aa.mode = mode; return (int)(VALUE)rb_thread_call_without_gvl(nogvl_eaccess, &aa, - RUBY_UBF_IO, 0); + RUBY_UBF_IO, 0); } static void * @@ -1572,7 +1572,7 @@ rb_access(VALUE fname, int mode) aa.mode = mode; return (int)(VALUE)rb_thread_call_without_gvl(nogvl_access, &aa, - RUBY_UBF_IO, 0); + RUBY_UBF_IO, 0); } /* @@ -1871,7 +1871,7 @@ rb_file_world_readable_p(VALUE obj, VALUE fname) if (rb_stat(fname, &st) < 0) return Qnil; if ((st.st_mode & (S_IROTH)) == S_IROTH) { - return UINT2NUM(st.st_mode & (S_IRUGO|S_IWUGO|S_IXUGO)); + return UINT2NUM(st.st_mode & (S_IRUGO|S_IWUGO|S_IXUGO)); } #endif return Qnil; @@ -1935,7 +1935,7 @@ rb_file_world_writable_p(VALUE obj, VALUE fname) if (rb_stat(fname, &st) < 0) return Qnil; if ((st.st_mode & (S_IWOTH)) == S_IWOTH) { - return UINT2NUM(st.st_mode & (S_IRUGO|S_IWUGO|S_IXUGO)); + return UINT2NUM(st.st_mode & (S_IRUGO|S_IWUGO|S_IXUGO)); } #endif return Qnil; @@ -2218,9 +2218,9 @@ rb_file_s_size(VALUE klass, VALUE fname) struct stat st; if (rb_stat(fname, &st) < 0) { - int e = errno; - FilePathValue(fname); - rb_syserr_fail_path(e, fname); + int e = errno; + FilePathValue(fname); + rb_syserr_fail_path(e, fname); } return OFFT2NUM(st.st_size); } @@ -2231,36 +2231,36 @@ rb_file_ftype(const struct stat *st) const char *t; if (S_ISREG(st->st_mode)) { - t = "file"; + t = "file"; } else if (S_ISDIR(st->st_mode)) { - t = "directory"; + t = "directory"; } else if (S_ISCHR(st->st_mode)) { - t = "characterSpecial"; + t = "characterSpecial"; } #ifdef S_ISBLK else if (S_ISBLK(st->st_mode)) { - t = "blockSpecial"; + t = "blockSpecial"; } #endif #ifdef S_ISFIFO else if (S_ISFIFO(st->st_mode)) { - t = "fifo"; + t = "fifo"; } #endif #ifdef S_ISLNK else if (S_ISLNK(st->st_mode)) { - t = "link"; + t = "link"; } #endif #ifdef S_ISSOCK else if (S_ISSOCK(st->st_mode)) { - t = "socket"; + t = "socket"; } #endif else { - t = "unknown"; + t = "unknown"; } return rb_usascii_str_new2(t); @@ -2289,7 +2289,7 @@ rb_file_s_ftype(VALUE klass, VALUE fname) FilePathValue(fname); fname = rb_str_encode_ospath(fname); if (lstat_without_gvl(StringValueCStr(fname), &st) == -1) { - rb_sys_fail_path(fname); + rb_sys_fail_path(fname); } return rb_file_ftype(&st); @@ -2313,9 +2313,9 @@ rb_file_s_atime(VALUE klass, VALUE fname) struct stat st; if (rb_stat(fname, &st) < 0) { - int e = errno; - FilePathValue(fname); - rb_syserr_fail_path(e, fname); + int e = errno; + FilePathValue(fname); + rb_syserr_fail_path(e, fname); } return stat_atime(&st); } @@ -2339,7 +2339,7 @@ rb_file_atime(VALUE obj) GetOpenFile(obj, fptr); if (fstat(fptr->fd, &st) == -1) { - rb_sys_fail_path(fptr->pathv); + rb_sys_fail_path(fptr->pathv); } return stat_atime(&st); } @@ -2362,9 +2362,9 @@ rb_file_s_mtime(VALUE klass, VALUE fname) struct stat st; if (rb_stat(fname, &st) < 0) { - int e = errno; - FilePathValue(fname); - rb_syserr_fail_path(e, fname); + int e = errno; + FilePathValue(fname); + rb_syserr_fail_path(e, fname); } return stat_mtime(&st); } @@ -2387,7 +2387,7 @@ rb_file_mtime(VALUE obj) GetOpenFile(obj, fptr); if (fstat(fptr->fd, &st) == -1) { - rb_sys_fail_path(fptr->pathv); + rb_sys_fail_path(fptr->pathv); } return stat_mtime(&st); } @@ -2414,9 +2414,9 @@ rb_file_s_ctime(VALUE klass, VALUE fname) struct stat st; if (rb_stat(fname, &st) < 0) { - int e = errno; - FilePathValue(fname); - rb_syserr_fail_path(e, fname); + int e = errno; + FilePathValue(fname); + rb_syserr_fail_path(e, fname); } return stat_ctime(&st); } @@ -2442,7 +2442,7 @@ rb_file_ctime(VALUE obj) GetOpenFile(obj, fptr); if (fstat(fptr->fd, &st) == -1) { - rb_sys_fail_path(fptr->pathv); + rb_sys_fail_path(fptr->pathv); } return stat_ctime(&st); } @@ -2468,9 +2468,9 @@ rb_file_s_birthtime(VALUE klass, VALUE fname) statx_data st; if (rb_statx(fname, &st, STATX_BTIME) < 0) { - int e = errno; - FilePathValue(fname); - rb_syserr_fail_path(e, fname); + int e = errno; + FilePathValue(fname); + rb_syserr_fail_path(e, fname); } return statx_birthtime(&st, fname); } @@ -2499,7 +2499,7 @@ rb_file_birthtime(VALUE obj) GetOpenFile(obj, fptr); if (fstatx_without_gvl(fptr->fd, &st, STATX_BTIME) == -1) { - rb_sys_fail_path(fptr->pathv); + rb_sys_fail_path(fptr->pathv); } return statx_birthtime(&st, fptr->pathv); } @@ -2603,18 +2603,18 @@ rb_file_chmod(VALUE obj, VALUE vmode) GetOpenFile(obj, fptr); #ifdef HAVE_FCHMOD if (fchmod(fptr->fd, mode) == -1) { - if (HAVE_FCHMOD || errno != ENOSYS) - rb_sys_fail_path(fptr->pathv); + if (HAVE_FCHMOD || errno != ENOSYS) + rb_sys_fail_path(fptr->pathv); } else { - if (!HAVE_FCHMOD) return INT2FIX(0); + if (!HAVE_FCHMOD) return INT2FIX(0); } #endif #if !defined HAVE_FCHMOD || !HAVE_FCHMOD if (NIL_P(fptr->pathv)) return Qnil; path = rb_str_encode_ospath(fptr->pathv); if (chmod(RSTRING_PTR(path), mode) == -1) - rb_sys_fail_path(fptr->pathv); + rb_sys_fail_path(fptr->pathv); #endif return INT2FIX(0); @@ -2655,7 +2655,7 @@ static inline rb_uid_t to_uid(VALUE u) { if (NIL_P(u)) { - return (rb_uid_t)-1; + return (rb_uid_t)-1; } return NUM2UIDT(u); } @@ -2664,7 +2664,7 @@ static inline rb_gid_t to_gid(VALUE g) { if (NIL_P(g)) { - return (rb_gid_t)-1; + return (rb_gid_t)-1; } return NUM2GIDT(g); } @@ -2740,10 +2740,10 @@ rb_file_chown(VALUE obj, VALUE owner, VALUE group) if (NIL_P(fptr->pathv)) return Qnil; path = rb_str_encode_ospath(fptr->pathv); if (chown(RSTRING_PTR(path), o, g) == -1) - rb_sys_fail_path(fptr->pathv); + rb_sys_fail_path(fptr->pathv); #else if (fchown(fptr->fd, o, g) == -1) - rb_sys_fail_path(fptr->pathv); + rb_sys_fail_path(fptr->pathv); #endif return INT2FIX(0); @@ -2800,32 +2800,32 @@ utime_failed(struct apply_arg *aa) struct utime_args *ua = aa->arg; if (ua->tsp && e == EINVAL) { - VALUE e[2], a = Qnil, m = Qnil; - int d = 0; - VALUE atime = ua->atime; - VALUE mtime = ua->mtime; + VALUE e[2], a = Qnil, m = Qnil; + int d = 0; + VALUE atime = ua->atime; + VALUE mtime = ua->mtime; - if (!NIL_P(atime)) { - a = rb_inspect(atime); - } - if (!NIL_P(mtime) && mtime != atime && !rb_equal(atime, mtime)) { - m = rb_inspect(mtime); - } - if (NIL_P(a)) e[0] = m; - else if (NIL_P(m) || rb_str_cmp(a, m) == 0) e[0] = a; - else { - e[0] = rb_str_plus(a, rb_str_new_cstr(" or ")); - rb_str_append(e[0], m); - d = 1; - } - if (!NIL_P(e[0])) { - if (path) { - if (!d) e[0] = rb_str_dup(e[0]); - rb_str_append(rb_str_cat2(e[0], " for "), path); - } - e[1] = INT2FIX(EINVAL); - rb_exc_raise(rb_class_new_instance(2, e, rb_eSystemCallError)); - } + if (!NIL_P(atime)) { + a = rb_inspect(atime); + } + if (!NIL_P(mtime) && mtime != atime && !rb_equal(atime, mtime)) { + m = rb_inspect(mtime); + } + if (NIL_P(a)) e[0] = m; + else if (NIL_P(m) || rb_str_cmp(a, m) == 0) e[0] = a; + else { + e[0] = rb_str_plus(a, rb_str_new_cstr(" or ")); + rb_str_append(e[0], m); + d = 1; + } + if (!NIL_P(e[0])) { + if (path) { + if (!d) e[0] = rb_str_dup(e[0]); + rb_str_append(rb_str_cat2(e[0], " for "), path); + } + e[1] = INT2FIX(EINVAL); + rb_exc_raise(rb_class_new_instance(2, e, rb_eSystemCallError)); + } } rb_syserr_fail_path(e, path); } @@ -2882,14 +2882,14 @@ utime_internal(const char *path, void *arg) if (v->follow ? try_utimensat_follow : try_utimensat) { # ifdef AT_SYMLINK_NOFOLLOW - if (v->follow) { - flags = AT_SYMLINK_NOFOLLOW; - } + if (v->follow) { + flags = AT_SYMLINK_NOFOLLOW; + } # endif - int result = utimensat(AT_FDCWD, path, tsp, flags); + int result = utimensat(AT_FDCWD, path, tsp, flags); # ifdef TRY_UTIMENSAT - if (result < 0 && errno == ENOSYS) { + if (result < 0 && errno == ENOSYS) { # ifdef AT_SYMLINK_NOFOLLOW try_utimensat_follow = 0; # endif @@ -2953,12 +2953,12 @@ utime_internal_i(int argc, VALUE *argv, int follow) args.follow = follow; if (!NIL_P(args.atime) || !NIL_P(args.mtime)) { - tsp = tss; - tsp[0] = rb_time_timespec(args.atime); - if (args.atime == args.mtime) - tsp[1] = tsp[0]; - else - tsp[1] = rb_time_timespec(args.mtime); + tsp = tss; + tsp[0] = rb_time_timespec(args.atime); + if (args.atime == args.mtime) + tsp[1] = tsp[0]; + else + tsp[1] = rb_time_timespec(args.mtime); } args.tsp = tsp; @@ -3022,7 +3022,7 @@ syserr_fail2_in(const char *func, int e, VALUE s1, VALUE s2) #endif if (e == EEXIST) { - rb_syserr_fail_path(e, rb_str_ellipsize(s2, max_pathlen)); + rb_syserr_fail_path(e, rb_str_ellipsize(s2, max_pathlen)); } str = rb_str_new_cstr("("); rb_str_append(str, rb_str_ellipsize(s1, max_pathlen)); @@ -3058,7 +3058,7 @@ rb_file_s_link(VALUE klass, VALUE from, VALUE to) to = rb_str_encode_ospath(to); if (link(StringValueCStr(from), StringValueCStr(to)) < 0) { - sys_fail2(from, to); + sys_fail2(from, to); } return INT2FIX(0); } @@ -3088,7 +3088,7 @@ rb_file_s_symlink(VALUE klass, VALUE from, VALUE to) to = rb_str_encode_ospath(to); if (symlink(StringValueCStr(from), StringValueCStr(to)) < 0) { - sys_fail2(from, to); + sys_fail2(from, to); } return INT2FIX(0); } @@ -3139,7 +3139,7 @@ readlink_without_gvl(VALUE path, VALUE buf, size_t size) ra.size = size; return (ssize_t)rb_thread_call_without_gvl(nogvl_readlink, &ra, - RUBY_UBF_IO, 0); + RUBY_UBF_IO, 0); } VALUE @@ -3154,17 +3154,17 @@ rb_readlink(VALUE path, rb_encoding *enc) v = rb_enc_str_new(0, size, enc); while ((rv = readlink_without_gvl(path, v, size)) == size #ifdef _AIX - || (rv < 0 && errno == ERANGE) /* quirky behavior of GPFS */ + || (rv < 0 && errno == ERANGE) /* quirky behavior of GPFS */ #endif - ) { - rb_str_modify_expand(v, size); - size *= 2; - rb_str_set_len(v, size); + ) { + rb_str_modify_expand(v, size); + size *= 2; + rb_str_set_len(v, size); } if (rv < 0) { - int e = errno; - rb_str_resize(v, 0); - rb_syserr_fail_path(e, path); + int e = errno; + rb_str_resize(v, 0); + rb_syserr_fail_path(e, path); } rb_str_resize(v, rv); @@ -3242,18 +3242,18 @@ rb_file_s_rename(VALUE klass, VALUE from, VALUE to) errno = 0; #endif if ((int)(VALUE)rb_thread_call_without_gvl(no_gvl_rename, &ra, - RUBY_UBF_IO, 0) < 0) { - int e = errno; + RUBY_UBF_IO, 0) < 0) { + int e = errno; #if defined DOSISH - switch (e) { - case EEXIST: - if (chmod(ra.dst, 0666) == 0 && - unlink(ra.dst) == 0 && - rename(ra.src, ra.dst) == 0) - return INT2FIX(0); - } + switch (e) { + case EEXIST: + if (chmod(ra.dst, 0666) == 0 && + unlink(ra.dst) == 0 && + rename(ra.src, ra.dst) == 0) + return INT2FIX(0); + } #endif - syserr_fail2(e, from, to); + syserr_fail2(e, from, to); } return INT2FIX(0); @@ -3281,11 +3281,11 @@ rb_file_s_umask(int argc, VALUE *argv, VALUE _) switch (argc) { case 0: - omask = umask(0); - umask(omask); + omask = umask(0); + umask(omask); break; case 1: - omask = umask(NUM2MODET(argv[0])); + omask = umask(NUM2MODET(argv[0])); break; default: rb_error_arity(argc, 0, 1); @@ -3350,10 +3350,10 @@ static inline int has_drive_letter(const char *buf) { if (ISALPHA(buf[0]) && buf[1] == ':') { - return 1; + return 1; } else { - return 0; + return 0; } } @@ -3374,13 +3374,13 @@ getcwdofdrv(int drv) */ oldcwd = ruby_getcwd(); if (chdir(drive) == 0) { - drvcwd = ruby_getcwd(); - chdir(oldcwd); - xfree(oldcwd); + drvcwd = ruby_getcwd(); + chdir(oldcwd); + xfree(oldcwd); } else { - /* perhaps the drive is not exist. we return only drive letter */ - drvcwd = strdup(drive); + /* perhaps the drive is not exist. we return only drive letter */ + drvcwd = strdup(drive); } return drvcwd; } @@ -3391,10 +3391,10 @@ not_same_drive(VALUE path, int drive) const char *p = RSTRING_PTR(path); if (RSTRING_LEN(path) < 2) return 0; if (has_drive_letter(p)) { - return TOLOWER(p[0]) != TOLOWER(drive); + return TOLOWER(p[0]) != TOLOWER(drive); } else { - return has_unc(p); + return has_unc(p); } } #endif @@ -3415,7 +3415,7 @@ char * rb_enc_path_next(const char *s, const char *e, rb_encoding *enc) { while (s < e && !isdirsep(*s)) { - Inc(s, e, enc); + Inc(s, e, enc); } return (char *)s; } @@ -3431,16 +3431,16 @@ rb_enc_path_skip_prefix(const char *path, const char *end, rb_encoding *enc) #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER) #ifdef DOSISH_UNC if (path + 2 <= end && isdirsep(path[0]) && isdirsep(path[1])) { - path += 2; - while (path < end && isdirsep(*path)) path++; - if ((path = rb_enc_path_next(path, end, enc)) < end && path[0] && path[1] && !isdirsep(path[1])) - path = rb_enc_path_next(path + 1, end, enc); - return (char *)path; + path += 2; + while (path < end && isdirsep(*path)) path++; + if ((path = rb_enc_path_next(path, end, enc)) < end && path[0] && path[1] && !isdirsep(path[1])) + path = rb_enc_path_next(path + 1, end, enc); + return (char *)path; } #endif #ifdef DOSISH_DRIVE_LETTER if (has_drive_letter(path)) - return (char *)(path + 2); + return (char *)(path + 2); #endif #endif return (char *)path; @@ -3464,15 +3464,15 @@ rb_enc_path_last_separator(const char *path, const char *end, rb_encoding *enc) { char *last = NULL; while (path < end) { - if (isdirsep(*path)) { - const char *tmp = path++; - while (path < end && isdirsep(*path)) path++; - if (path >= end) break; - last = (char *)tmp; - } - else { - Inc(path, end, enc); - } + if (isdirsep(*path)) { + const char *tmp = path++; + while (path < end && isdirsep(*path)) path++; + if (path >= end) break; + last = (char *)tmp; + } + else { + Inc(path, end, enc); + } } return last; } @@ -3481,14 +3481,14 @@ static char * chompdirsep(const char *path, const char *end, rb_encoding *enc) { while (path < end) { - if (isdirsep(*path)) { - const char *last = path++; - while (path < end && isdirsep(*path)) path++; - if (path >= end) return (char *)last; - } - else { - Inc(path, end, enc); - } + if (isdirsep(*path)) { + const char *last = path++; + while (path < end && isdirsep(*path)) path++; + if (path >= end) return (char *)last; + } + else { + Inc(path, end, enc); + } } return (char *)path; } @@ -3520,20 +3520,20 @@ ntfs_tail(const char *path, const char *end, rb_encoding *enc) { while (path < end && *path == '.') path++; while (path < end && !isADS(*path)) { - if (istrailinggarbage(*path)) { - const char *last = path++; - while (path < end && istrailinggarbage(*path)) path++; - if (path >= end || isADS(*path)) return (char *)last; - } - else if (isdirsep(*path)) { - const char *last = path++; - while (path < end && isdirsep(*path)) path++; - if (path >= end) return (char *)last; - if (isADS(*path)) path++; - } - else { - Inc(path, end, enc); - } + if (istrailinggarbage(*path)) { + const char *last = path++; + while (path < end && istrailinggarbage(*path)) path++; + if (path >= end || isADS(*path)) return (char *)last; + } + else if (isdirsep(*path)) { + const char *last = path++; + while (path < end && isdirsep(*path)) path++; + if (path >= end) return (char *)last; + if (isADS(*path)) path++; + } + else { + Inc(path, end, enc); + } } return (char *)path; } @@ -3542,11 +3542,11 @@ ntfs_tail(const char *path, const char *end, rb_encoding *enc) #define BUFCHECK(cond) do {\ bdiff = p - buf;\ if (cond) {\ - do {buflen *= 2;} while (cond);\ - rb_str_resize(result, buflen);\ - buf = RSTRING_PTR(result);\ - p = buf + bdiff;\ - pend = buf + buflen;\ + do {buflen *= 2;} while (cond);\ + rb_str_resize(result, buflen);\ + buf = RSTRING_PTR(result);\ + p = buf + bdiff;\ + pend = buf + buflen;\ }\ } while (0) @@ -3595,9 +3595,9 @@ copy_home_path(VALUE result, const char *dir) #if defined DOSISH || defined __CYGWIN__ enc = rb_enc_from_index(encidx); for (bend = (p = buf) + dirlen; p < bend; Inc(p, bend, enc)) { - if (*p == '\\') { - *p = '/'; - } + if (*p == '\\') { + *p = '/'; + } } #endif return result; @@ -3628,11 +3628,11 @@ rb_home_dir_of(VALUE user, VALUE result) pwPtr = getpwnam(username); #else if (strcasecmp(username, getlogin()) == 0) - dir = pwPtr = getenv("HOME"); + dir = pwPtr = getenv("HOME"); #endif if (!pwPtr) { - endpwent(); - rb_raise(rb_eArgError, "user %"PRIsVALUE" doesn't exist", user); + endpwent(); + rb_raise(rb_eArgError, "user %"PRIsVALUE" doesn't exist", user); } #ifdef HAVE_PWD_H dir = pwPtr->pw_dir; @@ -3689,7 +3689,7 @@ rb_default_home_dir(VALUE result) } #endif if (!dir) { - rb_raise(rb_eArgError, "couldn't find HOME environment -- expanding `~'"); + rb_raise(rb_eArgError, "couldn't find HOME environment -- expanding `~'"); } return copy_home_path(result, dir); } @@ -3714,15 +3714,15 @@ append_fspath(VALUE result, VALUE fname, char *dir, rb_encoding **enc, rb_encodi size_t dirlen = strlen(dir), buflen = rb_str_capacity(result); if (NORMALIZE_UTF8PATH || *enc != fsenc) { - rb_encoding *direnc = fs_enc_check(fname, dirname = ospath_new(dir, dirlen, fsenc)); - if (direnc != fsenc) { - dirname = rb_str_conv_enc(dirname, fsenc, direnc); - RSTRING_GETMEM(dirname, cwdp, dirlen); - } - else if (NORMALIZE_UTF8PATH) { - RSTRING_GETMEM(dirname, cwdp, dirlen); - } - *enc = direnc; + rb_encoding *direnc = fs_enc_check(fname, dirname = ospath_new(dir, dirlen, fsenc)); + if (direnc != fsenc) { + dirname = rb_str_conv_enc(dirname, fsenc, direnc); + RSTRING_GETMEM(dirname, cwdp, dirlen); + } + else if (NORMALIZE_UTF8PATH) { + RSTRING_GETMEM(dirname, cwdp, dirlen); + } + *enc = direnc; } do {buflen *= 2;} while (dirlen > buflen); rb_str_resize(result, buflen); @@ -3748,115 +3748,115 @@ rb_file_expand_path_internal(VALUE fname, VALUE dname, int abs_mode, int long_na BUFINIT(); if (s[0] == '~' && abs_mode == 0) { /* execute only if NOT absolute_path() */ - long userlen = 0; - if (isdirsep(s[1]) || s[1] == '\0') { - buf = 0; - b = 0; - rb_str_set_len(result, 0); - if (*++s) ++s; - rb_default_home_dir(result); - } - else { - s = nextdirsep(b = s, fend, enc); - b++; /* b[0] is '~' */ - userlen = s - b; - BUFCHECK(bdiff + userlen >= buflen); - memcpy(p, b, userlen); - ENC_CODERANGE_CLEAR(result); - rb_str_set_len(result, userlen); - rb_enc_associate(result, enc); - rb_home_dir_of(result, result); - buf = p + 1; - p += userlen; - } - if (!rb_is_absolute_path(RSTRING_PTR(result))) { - if (userlen) { - rb_enc_raise(enc, rb_eArgError, "non-absolute home of %.*s%.0"PRIsVALUE, - (int)userlen, b, fname); - } - else { - rb_raise(rb_eArgError, "non-absolute home"); - } - } - BUFINIT(); - p = pend; + long userlen = 0; + if (isdirsep(s[1]) || s[1] == '\0') { + buf = 0; + b = 0; + rb_str_set_len(result, 0); + if (*++s) ++s; + rb_default_home_dir(result); + } + else { + s = nextdirsep(b = s, fend, enc); + b++; /* b[0] is '~' */ + userlen = s - b; + BUFCHECK(bdiff + userlen >= buflen); + memcpy(p, b, userlen); + ENC_CODERANGE_CLEAR(result); + rb_str_set_len(result, userlen); + rb_enc_associate(result, enc); + rb_home_dir_of(result, result); + buf = p + 1; + p += userlen; + } + if (!rb_is_absolute_path(RSTRING_PTR(result))) { + if (userlen) { + rb_enc_raise(enc, rb_eArgError, "non-absolute home of %.*s%.0"PRIsVALUE, + (int)userlen, b, fname); + } + else { + rb_raise(rb_eArgError, "non-absolute home"); + } + } + BUFINIT(); + p = pend; } #ifdef DOSISH_DRIVE_LETTER /* skip drive letter */ else if (has_drive_letter(s)) { - if (isdirsep(s[2])) { - /* specified drive letter, and full path */ - /* skip drive letter */ - BUFCHECK(bdiff + 2 >= buflen); - memcpy(p, s, 2); - p += 2; - s += 2; - rb_enc_copy(result, fname); - } - else { - /* specified drive, but not full path */ - int same = 0; - if (!NIL_P(dname) && !not_same_drive(dname, s[0])) { - rb_file_expand_path_internal(dname, Qnil, abs_mode, long_name, result); - BUFINIT(); - if (has_drive_letter(p) && TOLOWER(p[0]) == TOLOWER(s[0])) { - /* ok, same drive */ - same = 1; - } - } - if (!same) { - char *e = append_fspath(result, fname, getcwdofdrv(*s), &enc, fsenc); - BUFINIT(); - p = e; - } - else { - rb_enc_associate(result, enc = fs_enc_check(result, fname)); - p = pend; - } - p = chompdirsep(skiproot(buf, p, enc), p, enc); - s += 2; - } + if (isdirsep(s[2])) { + /* specified drive letter, and full path */ + /* skip drive letter */ + BUFCHECK(bdiff + 2 >= buflen); + memcpy(p, s, 2); + p += 2; + s += 2; + rb_enc_copy(result, fname); + } + else { + /* specified drive, but not full path */ + int same = 0; + if (!NIL_P(dname) && !not_same_drive(dname, s[0])) { + rb_file_expand_path_internal(dname, Qnil, abs_mode, long_name, result); + BUFINIT(); + if (has_drive_letter(p) && TOLOWER(p[0]) == TOLOWER(s[0])) { + /* ok, same drive */ + same = 1; + } + } + if (!same) { + char *e = append_fspath(result, fname, getcwdofdrv(*s), &enc, fsenc); + BUFINIT(); + p = e; + } + else { + rb_enc_associate(result, enc = fs_enc_check(result, fname)); + p = pend; + } + p = chompdirsep(skiproot(buf, p, enc), p, enc); + s += 2; + } } #endif else if (!rb_is_absolute_path(s)) { - if (!NIL_P(dname)) { - rb_file_expand_path_internal(dname, Qnil, abs_mode, long_name, result); - rb_enc_associate(result, fs_enc_check(result, fname)); - BUFINIT(); - p = pend; - } - else { - char *e = append_fspath(result, fname, ruby_getcwd(), &enc, fsenc); - BUFINIT(); - p = e; - } + if (!NIL_P(dname)) { + rb_file_expand_path_internal(dname, Qnil, abs_mode, long_name, result); + rb_enc_associate(result, fs_enc_check(result, fname)); + BUFINIT(); + p = pend; + } + else { + char *e = append_fspath(result, fname, ruby_getcwd(), &enc, fsenc); + BUFINIT(); + p = e; + } #if defined DOSISH || defined __CYGWIN__ - if (isdirsep(*s)) { - /* specified full path, but not drive letter nor UNC */ - /* we need to get the drive letter or UNC share name */ - p = skipprefix(buf, p, enc); - } - else + if (isdirsep(*s)) { + /* specified full path, but not drive letter nor UNC */ + /* we need to get the drive letter or UNC share name */ + p = skipprefix(buf, p, enc); + } + else #endif - p = chompdirsep(skiproot(buf, p, enc), p, enc); + p = chompdirsep(skiproot(buf, p, enc), p, enc); } else { - size_t len; - b = s; - do s++; while (isdirsep(*s)); - len = s - b; - p = buf + len; - BUFCHECK(bdiff >= buflen); - memset(buf, '/', len); - rb_str_set_len(result, len); - rb_enc_associate(result, fs_enc_check(result, fname)); + size_t len; + b = s; + do s++; while (isdirsep(*s)); + len = s - b; + p = buf + len; + BUFCHECK(bdiff >= buflen); + memset(buf, '/', len); + rb_str_set_len(result, len); + rb_enc_associate(result, fs_enc_check(result, fname)); } if (p > buf && p[-1] == '/') - --p; + --p; else { - rb_str_set_len(result, p-buf); - BUFCHECK(bdiff + 1 >= buflen); - *p = '/'; + rb_str_set_len(result, p-buf); + BUFCHECK(bdiff + 1 >= buflen); + *p = '/'; } rb_str_set_len(result, p-buf+1); @@ -3866,213 +3866,213 @@ rb_file_expand_path_internal(VALUE fname, VALUE dname, int abs_mode, int long_na b = s; while (*s) { - switch (*s) { - case '.': - if (b == s++) { /* beginning of path element */ - switch (*s) { - case '\0': - b = s; - break; - case '.': - if (*(s+1) == '\0' || isdirsep(*(s+1))) { - /* We must go back to the parent */ - char *n; - *p = '\0'; - if (!(n = strrdirsep(root, p, enc))) { - *p = '/'; - } - else { - p = n; - } - b = ++s; - } + switch (*s) { + case '.': + if (b == s++) { /* beginning of path element */ + switch (*s) { + case '\0': + b = s; + break; + case '.': + if (*(s+1) == '\0' || isdirsep(*(s+1))) { + /* We must go back to the parent */ + char *n; + *p = '\0'; + if (!(n = strrdirsep(root, p, enc))) { + *p = '/'; + } + else { + p = n; + } + b = ++s; + } #if USE_NTFS - else { - do ++s; while (istrailinggarbage(*s)); - } + else { + do ++s; while (istrailinggarbage(*s)); + } #endif - break; - case '/': + break; + case '/': #if defined DOSISH || defined __CYGWIN__ - case '\\': + case '\\': #endif - b = ++s; - break; - default: - /* ordinary path element, beginning don't move */ - break; - } - } + b = ++s; + break; + default: + /* ordinary path element, beginning don't move */ + break; + } + } #if USE_NTFS - else { - --s; - case ' ': { - const char *e = s; - while (s < fend && istrailinggarbage(*s)) s++; - if (s >= fend) { - s = e; - goto endpath; - } - } - } + else { + --s; + case ' ': { + const char *e = s; + while (s < fend && istrailinggarbage(*s)) s++; + if (s >= fend) { + s = e; + goto endpath; + } + } + } #endif - break; - case '/': + break; + case '/': #if defined DOSISH || defined __CYGWIN__ - case '\\': + case '\\': #endif - if (s > b) { - WITH_ROOTDIFF(BUFCOPY(b, s-b)); - *p = '/'; - } - b = ++s; - break; - default: + if (s > b) { + WITH_ROOTDIFF(BUFCOPY(b, s-b)); + *p = '/'; + } + b = ++s; + break; + default: #ifdef __APPLE__ - { - int n = ignored_char_p(s, fend, enc); - if (n) { - if (s > b) { - WITH_ROOTDIFF(BUFCOPY(b, s-b)); - *p = '\0'; - } - b = s += n; - break; - } - } + { + int n = ignored_char_p(s, fend, enc); + if (n) { + if (s > b) { + WITH_ROOTDIFF(BUFCOPY(b, s-b)); + *p = '\0'; + } + b = s += n; + break; + } + } #endif - Inc(s, fend, enc); - break; - } + Inc(s, fend, enc); + break; + } } if (s > b) { #if USE_NTFS # if USE_NTFS_ADS - static const char prime[] = ":$DATA"; - enum {prime_len = sizeof(prime) -1}; + static const char prime[] = ":$DATA"; + enum {prime_len = sizeof(prime) -1}; # endif endpath: # if USE_NTFS_ADS - if (s > b + prime_len && strncasecmp(s - prime_len, prime, prime_len) == 0) { - /* alias of stream */ - /* get rid of a bug of x64 VC++ */ - if (isADS(*(s - (prime_len+1)))) { - s -= prime_len + 1; /* prime */ - } - else if (memchr(b, ':', s - prime_len - b)) { - s -= prime_len; /* alternative */ - } - } + if (s > b + prime_len && strncasecmp(s - prime_len, prime, prime_len) == 0) { + /* alias of stream */ + /* get rid of a bug of x64 VC++ */ + if (isADS(*(s - (prime_len+1)))) { + s -= prime_len + 1; /* prime */ + } + else if (memchr(b, ':', s - prime_len - b)) { + s -= prime_len; /* alternative */ + } + } # endif #endif - BUFCOPY(b, s-b); - rb_str_set_len(result, p-buf); + BUFCOPY(b, s-b); + rb_str_set_len(result, p-buf); } if (p == skiproot(buf, p + !!*p, enc) - 1) p++; #if USE_NTFS *p = '\0'; if ((s = strrdirsep(b = buf, p, enc)) != 0 && !strpbrk(s, "*?")) { - VALUE tmp, v; - size_t len; - int encidx; - WCHAR *wstr; - WIN32_FIND_DATAW wfd; - HANDLE h; + VALUE tmp, v; + size_t len; + int encidx; + WCHAR *wstr; + WIN32_FIND_DATAW wfd; + HANDLE h; #ifdef __CYGWIN__ #ifdef HAVE_CYGWIN_CONV_PATH - char *w32buf = NULL; - const int flags = CCP_POSIX_TO_WIN_A | CCP_RELATIVE; + char *w32buf = NULL; + const int flags = CCP_POSIX_TO_WIN_A | CCP_RELATIVE; #else - char w32buf[MAXPATHLEN]; + char w32buf[MAXPATHLEN]; #endif - const char *path; - ssize_t bufsize; - int lnk_added = 0, is_symlink = 0; - struct stat st; - p = (char *)s; - len = strlen(p); - if (lstat_without_gvl(buf, &st) == 0 && S_ISLNK(st.st_mode)) { - is_symlink = 1; - if (len > 4 && STRCASECMP(p + len - 4, ".lnk") != 0) { - lnk_added = 1; - } - } - path = *buf ? buf : "/"; + const char *path; + ssize_t bufsize; + int lnk_added = 0, is_symlink = 0; + struct stat st; + p = (char *)s; + len = strlen(p); + if (lstat_without_gvl(buf, &st) == 0 && S_ISLNK(st.st_mode)) { + is_symlink = 1; + if (len > 4 && STRCASECMP(p + len - 4, ".lnk") != 0) { + lnk_added = 1; + } + } + path = *buf ? buf : "/"; #ifdef HAVE_CYGWIN_CONV_PATH - bufsize = cygwin_conv_path(flags, path, NULL, 0); - if (bufsize > 0) { - bufsize += len; - if (lnk_added) bufsize += 4; - w32buf = ALLOCA_N(char, bufsize); - if (cygwin_conv_path(flags, path, w32buf, bufsize) == 0) { - b = w32buf; - } - } + bufsize = cygwin_conv_path(flags, path, NULL, 0); + if (bufsize > 0) { + bufsize += len; + if (lnk_added) bufsize += 4; + w32buf = ALLOCA_N(char, bufsize); + if (cygwin_conv_path(flags, path, w32buf, bufsize) == 0) { + b = w32buf; + } + } #else - bufsize = MAXPATHLEN; - if (cygwin_conv_to_win32_path(path, w32buf) == 0) { - b = w32buf; - } + bufsize = MAXPATHLEN; + if (cygwin_conv_to_win32_path(path, w32buf) == 0) { + b = w32buf; + } #endif - if (is_symlink && b == w32buf) { - *p = '\\'; - strlcat(w32buf, p, bufsize); - if (lnk_added) { - strlcat(w32buf, ".lnk", bufsize); - } - } - else { - lnk_added = 0; - } - *p = '/'; + if (is_symlink && b == w32buf) { + *p = '\\'; + strlcat(w32buf, p, bufsize); + if (lnk_added) { + strlcat(w32buf, ".lnk", bufsize); + } + } + else { + lnk_added = 0; + } + *p = '/'; #endif - rb_str_set_len(result, p - buf + strlen(p)); - encidx = ENCODING_GET(result); - tmp = result; - if (encidx != ENCINDEX_UTF_8 && !is_ascii_string(result)) { - tmp = rb_str_encode_ospath(result); - } - len = MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, NULL, 0); - wstr = ALLOCV_N(WCHAR, v, len); - MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, wstr, len); - if (tmp != result) rb_str_set_len(tmp, 0); - h = FindFirstFileW(wstr, &wfd); - ALLOCV_END(v); - if (h != INVALID_HANDLE_VALUE) { - size_t wlen; - FindClose(h); - len = lstrlenW(wfd.cFileName); + rb_str_set_len(result, p - buf + strlen(p)); + encidx = ENCODING_GET(result); + tmp = result; + if (encidx != ENCINDEX_UTF_8 && !is_ascii_string(result)) { + tmp = rb_str_encode_ospath(result); + } + len = MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, NULL, 0); + wstr = ALLOCV_N(WCHAR, v, len); + MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, wstr, len); + if (tmp != result) rb_str_set_len(tmp, 0); + h = FindFirstFileW(wstr, &wfd); + ALLOCV_END(v); + if (h != INVALID_HANDLE_VALUE) { + size_t wlen; + FindClose(h); + len = lstrlenW(wfd.cFileName); #ifdef __CYGWIN__ - if (lnk_added && len > 4 && - wcscasecmp(wfd.cFileName + len - 4, L".lnk") == 0) { - wfd.cFileName[len -= 4] = L'\0'; - } + if (lnk_added && len > 4 && + wcscasecmp(wfd.cFileName + len - 4, L".lnk") == 0) { + wfd.cFileName[len -= 4] = L'\0'; + } #else - p = (char *)s; + p = (char *)s; #endif - ++p; - wlen = (int)len; - len = WideCharToMultiByte(CP_UTF8, 0, wfd.cFileName, wlen, NULL, 0, NULL, NULL); - if (tmp == result) { - BUFCHECK(bdiff + len >= buflen); - WideCharToMultiByte(CP_UTF8, 0, wfd.cFileName, wlen, p, len + 1, NULL, NULL); - } - else { - rb_str_modify_expand(tmp, len); - WideCharToMultiByte(CP_UTF8, 0, wfd.cFileName, wlen, RSTRING_PTR(tmp), len + 1, NULL, NULL); - rb_str_cat_conv_enc_opts(result, bdiff, RSTRING_PTR(tmp), len, - rb_utf8_encoding(), 0, Qnil); - BUFINIT(); - rb_str_resize(tmp, 0); - } - p += len; - } + ++p; + wlen = (int)len; + len = WideCharToMultiByte(CP_UTF8, 0, wfd.cFileName, wlen, NULL, 0, NULL, NULL); + if (tmp == result) { + BUFCHECK(bdiff + len >= buflen); + WideCharToMultiByte(CP_UTF8, 0, wfd.cFileName, wlen, p, len + 1, NULL, NULL); + } + else { + rb_str_modify_expand(tmp, len); + WideCharToMultiByte(CP_UTF8, 0, wfd.cFileName, wlen, RSTRING_PTR(tmp), len + 1, NULL, NULL); + rb_str_cat_conv_enc_opts(result, bdiff, RSTRING_PTR(tmp), len, + rb_utf8_encoding(), 0, Qnil); + BUFINIT(); + rb_str_resize(tmp, 0); + } + p += len; + } #ifdef __CYGWIN__ - else { - p += strlen(p); - } + else { + p += strlen(p); + } #endif } #endif @@ -4221,27 +4221,27 @@ enum rb_realpath_mode { static int realpath_rec(long *prefixlenp, VALUE *resolvedp, const char *unresolved, VALUE fallback, - VALUE loopcheck, enum rb_realpath_mode mode, int last) + VALUE loopcheck, enum rb_realpath_mode mode, int last) { const char *pend = unresolved + strlen(unresolved); rb_encoding *enc = rb_enc_get(*resolvedp); ID resolving; CONST_ID(resolving, "resolving"); while (unresolved < pend) { - const char *testname = unresolved; - const char *unresolved_firstsep = rb_enc_path_next(unresolved, pend, enc); - long testnamelen = unresolved_firstsep - unresolved; - const char *unresolved_nextname = unresolved_firstsep; + const char *testname = unresolved; + const char *unresolved_firstsep = rb_enc_path_next(unresolved, pend, enc); + long testnamelen = unresolved_firstsep - unresolved; + const char *unresolved_nextname = unresolved_firstsep; while (unresolved_nextname < pend && isdirsep(*unresolved_nextname)) - unresolved_nextname++; + unresolved_nextname++; unresolved = unresolved_nextname; if (testnamelen == 1 && testname[0] == '.') { } else if (testnamelen == 2 && testname[0] == '.' && testname[1] == '.') { if (*prefixlenp < RSTRING_LEN(*resolvedp)) { - const char *resolved_str = RSTRING_PTR(*resolvedp); - const char *resolved_names = resolved_str + *prefixlenp; - const char *lastsep = strrdirsep(resolved_names, resolved_str + RSTRING_LEN(*resolvedp), enc); + const char *resolved_str = RSTRING_PTR(*resolvedp); + const char *resolved_names = resolved_str + *prefixlenp; + const char *lastsep = strrdirsep(resolved_names, resolved_str + RSTRING_LEN(*resolvedp), enc); long len = lastsep ? lastsep - resolved_names : 0; rb_str_resize(*resolvedp, *prefixlenp + len); } @@ -4252,20 +4252,20 @@ realpath_rec(long *prefixlenp, VALUE *resolvedp, const char *unresolved, VALUE f if (*prefixlenp < RSTRING_LEN(testpath)) rb_str_cat2(testpath, "/"); #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER) - if (*prefixlenp > 1 && *prefixlenp == RSTRING_LEN(testpath)) { - const char *prefix = RSTRING_PTR(testpath); - const char *last = rb_enc_left_char_head(prefix, prefix + *prefixlenp - 1, prefix + *prefixlenp, enc); - if (!isdirsep(*last)) rb_str_cat2(testpath, "/"); - } + if (*prefixlenp > 1 && *prefixlenp == RSTRING_LEN(testpath)) { + const char *prefix = RSTRING_PTR(testpath); + const char *last = rb_enc_left_char_head(prefix, prefix + *prefixlenp - 1, prefix + *prefixlenp, enc); + if (!isdirsep(*last)) rb_str_cat2(testpath, "/"); + } #endif rb_str_cat(testpath, testname, testnamelen); checkval = rb_hash_aref(loopcheck, testpath); if (!NIL_P(checkval)) { if (checkval == ID2SYM(resolving)) { - if (mode == RB_REALPATH_CHECK) { - errno = ELOOP; - return -1; - } + if (mode == RB_REALPATH_CHECK) { + errno = ELOOP; + return -1; + } rb_syserr_fail_path(ELOOP, testpath); } else { @@ -4277,49 +4277,49 @@ realpath_rec(long *prefixlenp, VALUE *resolvedp, const char *unresolved, VALUE f int ret; ret = lstat_without_gvl(RSTRING_PTR(testpath), &sbuf); if (ret == -1) { - int e = errno; - if (e == ENOENT && !NIL_P(fallback)) { - if (stat_without_gvl(RSTRING_PTR(fallback), &sbuf) == 0) { - rb_str_replace(*resolvedp, fallback); - return 0; - } - } - if (mode == RB_REALPATH_CHECK) return -1; - if (e == ENOENT) { - if (mode == RB_REALPATH_STRICT || !last || *unresolved_firstsep) - rb_syserr_fail_path(e, testpath); + int e = errno; + if (e == ENOENT && !NIL_P(fallback)) { + if (stat_without_gvl(RSTRING_PTR(fallback), &sbuf) == 0) { + rb_str_replace(*resolvedp, fallback); + return 0; + } + } + if (mode == RB_REALPATH_CHECK) return -1; + if (e == ENOENT) { + if (mode == RB_REALPATH_STRICT || !last || *unresolved_firstsep) + rb_syserr_fail_path(e, testpath); *resolvedp = testpath; break; } else { - rb_syserr_fail_path(e, testpath); + rb_syserr_fail_path(e, testpath); } } #ifdef HAVE_READLINK if (S_ISLNK(sbuf.st_mode)) { - VALUE link; - VALUE link_orig = Qnil; - const char *link_prefix, *link_names; + VALUE link; + VALUE link_orig = Qnil; + const char *link_prefix, *link_names; long link_prefixlen; rb_hash_aset(loopcheck, testpath, ID2SYM(resolving)); - link = rb_readlink(testpath, enc); + link = rb_readlink(testpath, enc); link_prefix = RSTRING_PTR(link); - link_names = skipprefixroot(link_prefix, link_prefix + RSTRING_LEN(link), rb_enc_get(link)); - link_prefixlen = link_names - link_prefix; - if (link_prefixlen > 0) { - rb_encoding *tmpenc, *linkenc = rb_enc_get(link); - link_orig = link; - link = rb_str_subseq(link, 0, link_prefixlen); - tmpenc = fs_enc_check(*resolvedp, link); - if (tmpenc != linkenc) link = rb_str_conv_enc(link, linkenc, tmpenc); - *resolvedp = link; - *prefixlenp = link_prefixlen; - } - if (realpath_rec(prefixlenp, resolvedp, link_names, testpath, - loopcheck, mode, !*unresolved_firstsep)) - return -1; - RB_GC_GUARD(link_orig); - rb_hash_aset(loopcheck, testpath, rb_str_dup_frozen(*resolvedp)); + link_names = skipprefixroot(link_prefix, link_prefix + RSTRING_LEN(link), rb_enc_get(link)); + link_prefixlen = link_names - link_prefix; + if (link_prefixlen > 0) { + rb_encoding *tmpenc, *linkenc = rb_enc_get(link); + link_orig = link; + link = rb_str_subseq(link, 0, link_prefixlen); + tmpenc = fs_enc_check(*resolvedp, link); + if (tmpenc != linkenc) link = rb_str_conv_enc(link, linkenc, tmpenc); + *resolvedp = link; + *prefixlenp = link_prefixlen; + } + if (realpath_rec(prefixlenp, resolvedp, link_names, testpath, + loopcheck, mode, !*unresolved_firstsep)) + return -1; + RB_GC_GUARD(link_orig); + rb_hash_aset(loopcheck, testpath, rb_str_dup_frozen(*resolvedp)); } else #endif @@ -4365,11 +4365,11 @@ rb_check_realpath_emulate(VALUE basedir, VALUE path, rb_encoding *origenc, enum } if (!NIL_P(basedir)) { - RSTRING_GETMEM(basedir, ptr, len); - basedir_names = skipprefixroot(ptr, ptr + len, rb_enc_get(basedir)); + RSTRING_GETMEM(basedir, ptr, len); + basedir_names = skipprefixroot(ptr, ptr + len, rb_enc_get(basedir)); if (ptr != basedir_names) { - resolved = rb_str_subseq(basedir, 0, basedir_names - ptr); - goto root_found; + resolved = rb_str_subseq(basedir, 0, basedir_names - ptr); + goto root_found; } } @@ -4388,38 +4388,38 @@ rb_check_realpath_emulate(VALUE basedir, VALUE path, rb_encoding *origenc, enum } #ifdef FILE_ALT_SEPARATOR while (prefixptr < ptr) { - if (*prefixptr == FILE_ALT_SEPARATOR) { - *prefixptr = '/'; - } - Inc(prefixptr, pend, enc); + if (*prefixptr == FILE_ALT_SEPARATOR) { + *prefixptr = '/'; + } + Inc(prefixptr, pend, enc); } #endif switch (rb_enc_to_index(enc)) { case ENCINDEX_ASCII_8BIT: case ENCINDEX_US_ASCII: - rb_enc_associate_index(resolved, rb_filesystem_encindex()); + rb_enc_associate_index(resolved, rb_filesystem_encindex()); } loopcheck = rb_hash_new(); if (curdir_names) { - if (realpath_rec(&prefixlen, &resolved, curdir_names, Qnil, loopcheck, mode, 0)) - return Qnil; + if (realpath_rec(&prefixlen, &resolved, curdir_names, Qnil, loopcheck, mode, 0)) + return Qnil; } if (basedir_names) { - if (realpath_rec(&prefixlen, &resolved, basedir_names, Qnil, loopcheck, mode, 0)) - return Qnil; + if (realpath_rec(&prefixlen, &resolved, basedir_names, Qnil, loopcheck, mode, 0)) + return Qnil; } if (realpath_rec(&prefixlen, &resolved, path_names, Qnil, loopcheck, mode, 1)) - return Qnil; + return Qnil; if (origenc && origenc != rb_enc_get(resolved)) { - if (rb_enc_str_asciionly_p(resolved)) { - rb_enc_associate(resolved, origenc); - } - else { - resolved = rb_str_conv_enc(resolved, NULL, origenc); - } + if (rb_enc_str_asciionly_p(resolved)) { + rb_enc_associate(resolved, origenc); + } + else { + resolved = rb_str_conv_enc(resolved, NULL, origenc); + } } RB_GC_GUARD(unresolved_path); @@ -4529,7 +4529,7 @@ VALUE rb_realpath_internal(VALUE basedir, VALUE path, int strict) { const enum rb_realpath_mode mode = - strict ? RB_REALPATH_STRICT : RB_REALPATH_DIR; + strict ? RB_REALPATH_STRICT : RB_REALPATH_DIR; return rb_check_realpath_internal(basedir, path, rb_enc_get(path), mode); } @@ -4593,15 +4593,15 @@ rmext(const char *p, long l0, long l1, const char *e, long l2, rb_encoding *enc) c = rb_enc_codepoint_len(e, e + l2, &len1, enc); if (rb_enc_ascget(e + len1, e + l2, &len2, enc) == '*' && len1 + len2 == l2) { - if (c == '.') return l0; - s = p; - e = p + l1; - last = e; - while (s < e) { - if (rb_enc_codepoint_len(s, e, &len1, enc) == c) last = s; - s += len1; - } - return last - p; + if (c == '.') return l0; + s = p; + e = p + l1; + last = e; + while (s < e) { + if (rb_enc_codepoint_len(s, e, &len1, enc) == c) last = s; + s += len1; + } + return last - p; } if (l1 < l2) return l1; @@ -4613,7 +4613,7 @@ rmext(const char *p, long l0, long l1, const char *e, long l2, rb_encoding *enc) #define fncomp strncmp #endif if (fncomp(s, e, l2) == 0) { - return l1-l2; + return l1-l2; } return 0; } @@ -4633,51 +4633,51 @@ ruby_enc_find_basename(const char *name, long *baselen, long *alllen, rb_encodin root = name; #endif while (isdirsep(*name)) - name++; + name++; if (!*name) { - p = name - 1; - f = 1; + p = name - 1; + f = 1; #if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC - if (name != root) { - /* has slashes */ - } + if (name != root) { + /* has slashes */ + } #ifdef DOSISH_DRIVE_LETTER - else if (*p == ':') { - p++; - f = 0; - } + else if (*p == ':') { + p++; + f = 0; + } #endif #ifdef DOSISH_UNC - else { - p = "/"; - } + else { + p = "/"; + } #endif #endif } else { - if (!(p = strrdirsep(name, end, enc))) { - p = name; - } - else { - while (isdirsep(*p)) p++; /* skip last / */ - } + if (!(p = strrdirsep(name, end, enc))) { + p = name; + } + else { + while (isdirsep(*p)) p++; /* skip last / */ + } #if USE_NTFS - n = ntfs_tail(p, end, enc) - p; + n = ntfs_tail(p, end, enc) - p; #else - n = chompdirsep(p, end, enc) - p; + n = chompdirsep(p, end, enc) - p; #endif - for (q = p; q - p < n && *q == '.'; q++); - for (e = 0; q - p < n; Inc(q, end, enc)) { - if (*q == '.') e = q; - } - if (e) f = e - p; - else f = n; + for (q = p; q - p < n && *q == '.'; q++); + for (e = 0; q - p < n; Inc(q, end, enc)) { + if (*q == '.') e = q; + } + if (e) f = e - p; + else f = n; } if (baselen) - *baselen = f; + *baselen = f; if (alllen) - *alllen = n; + *alllen = n; return p; } @@ -4708,33 +4708,33 @@ rb_file_s_basename(int argc, VALUE *argv, VALUE _) fext = Qnil; if (rb_check_arity(argc, 1, 2) == 2) { - fext = argv[1]; - StringValue(fext); - enc = check_path_encoding(fext); + fext = argv[1]; + StringValue(fext); + enc = check_path_encoding(fext); } fname = argv[0]; FilePathStringValue(fname); if (NIL_P(fext) || !(enc = rb_enc_compatible(fname, fext))) { - enc = rb_enc_get(fname); - fext = Qnil; + enc = rb_enc_get(fname); + fext = Qnil; } if ((n = RSTRING_LEN(fname)) == 0 || !*(name = RSTRING_PTR(fname))) - return rb_str_new_shared(fname); + return rb_str_new_shared(fname); p = ruby_enc_find_basename(name, &f, &n, enc); if (n >= 0) { - if (NIL_P(fext)) { - f = n; - } - else { - const char *fp; - fp = StringValueCStr(fext); - if (!(f = rmext(p, f, n, fp, RSTRING_LEN(fext), enc))) { - f = n; - } - RB_GC_GUARD(fext); - } - if (f == RSTRING_LEN(fname)) return rb_str_new_shared(fname); + if (NIL_P(fext)) { + f = n; + } + else { + const char *fp; + fp = StringValueCStr(fext); + if (!(f = rmext(p, f, n, fp, RSTRING_LEN(fext), enc))) { + f = n; + } + RB_GC_GUARD(fext); + } + if (f == RSTRING_LEN(fname)) return rb_str_new_shared(fname); } basename = rb_str_new(p, f); @@ -4768,7 +4768,7 @@ rb_file_s_dirname(int argc, VALUE *argv, VALUE klass) { int n = 1; if ((argc = rb_check_arity(argc, 1, 2)) > 1) { - n = NUM2INT(argv[1]); + n = NUM2INT(argv[1]); } return rb_file_dirname_n(argv[0], n); } @@ -4796,58 +4796,58 @@ rb_file_dirname_n(VALUE fname, int n) root = skiproot(name, end, enc); #ifdef DOSISH_UNC if (root > name + 1 && isdirsep(*name)) - root = skipprefix(name = root - 2, end, enc); + root = skipprefix(name = root - 2, end, enc); #else if (root > name + 1) - name = root - 1; + name = root - 1; #endif if (n > (end - root + 1) / 2) { - p = root; + p = root; } else { - int i; - switch (n) { - case 0: - p = end; - break; - case 1: - if (!(p = strrdirsep(root, end, enc))) p = root; - break; - default: - seps = ALLOCV_N(const char *, sepsv, n); - for (i = 0; i < n; ++i) seps[i] = root; - i = 0; - for (p = root; p < end; ) { - if (isdirsep(*p)) { - const char *tmp = p++; - while (p < end && isdirsep(*p)) p++; - if (p >= end) break; - seps[i++] = tmp; - if (i == n) i = 0; - } - else { - Inc(p, end, enc); - } - } - p = seps[i]; - ALLOCV_END(sepsv); - break; - } + int i; + switch (n) { + case 0: + p = end; + break; + case 1: + if (!(p = strrdirsep(root, end, enc))) p = root; + break; + default: + seps = ALLOCV_N(const char *, sepsv, n); + for (i = 0; i < n; ++i) seps[i] = root; + i = 0; + for (p = root; p < end; ) { + if (isdirsep(*p)) { + const char *tmp = p++; + while (p < end && isdirsep(*p)) p++; + if (p >= end) break; + seps[i++] = tmp; + if (i == n) i = 0; + } + else { + Inc(p, end, enc); + } + } + p = seps[i]; + ALLOCV_END(sepsv); + break; + } } if (p == name) - return rb_usascii_str_new2("."); + return rb_usascii_str_new2("."); #ifdef DOSISH_DRIVE_LETTER if (has_drive_letter(name) && isdirsep(*(name + 2))) { - const char *top = skiproot(name + 2, end, enc); - dirname = rb_str_new(name, 3); - rb_str_cat(dirname, top, p - top); + const char *top = skiproot(name + 2, end, enc); + dirname = rb_str_new(name, 3); + rb_str_cat(dirname, top, p - top); } else #endif dirname = rb_str_new(name, p - name); #ifdef DOSISH_DRIVE_LETTER if (has_drive_letter(name) && root == name + 2 && p - name == 2) - rb_str_cat(dirname, ".", 1); + rb_str_cat(dirname, ".", 1); #endif rb_enc_copy(dirname, fname); return dirname; @@ -4872,48 +4872,48 @@ ruby_enc_find_extname(const char *name, long *len, rb_encoding *enc) p = strrdirsep(name, end, enc); /* get the last path component */ if (!p) - p = name; + p = name; else - do name = ++p; while (isdirsep(*p)); + do name = ++p; while (isdirsep(*p)); e = 0; while (*p && *p == '.') p++; while (*p) { - if (*p == '.' || istrailinggarbage(*p)) { + if (*p == '.' || istrailinggarbage(*p)) { #if USE_NTFS - const char *last = p++, *dot = last; - while (istrailinggarbage(*p)) { - if (*p == '.') dot = p; - p++; - } - if (!*p || isADS(*p)) { - p = last; - break; - } - if (*last == '.' || dot > last) e = dot; - continue; + const char *last = p++, *dot = last; + while (istrailinggarbage(*p)) { + if (*p == '.') dot = p; + p++; + } + if (!*p || isADS(*p)) { + p = last; + break; + } + if (*last == '.' || dot > last) e = dot; + continue; #else - e = p; /* get the last dot of the last component */ + e = p; /* get the last dot of the last component */ #endif - } + } #if USE_NTFS - else if (isADS(*p)) { - break; - } + else if (isADS(*p)) { + break; + } #endif - else if (isdirsep(*p)) - break; - Inc(p, end, enc); + else if (isdirsep(*p)) + break; + Inc(p, end, enc); } if (len) { - /* no dot, or the only dot is first or end? */ - if (!e || e == name) - *len = 0; - else if (e+1 == p) - *len = 1; - else - *len = p - e; + /* no dot, or the only dot is first or end? */ + if (!e || e == name) + *len = 0; + else if (e+1 == p) + *len = 1; + else + *len = p - e; } return e; } @@ -4956,7 +4956,7 @@ rb_file_s_extname(VALUE klass, VALUE fname) len = RSTRING_LEN(fname); e = ruby_enc_find_extname(name, &len, rb_enc_get(fname)); if (len < 1) - return rb_str_new(0, 0); + return rb_str_new(0, 0); extname = rb_str_subseq(fname, e - name, len); /* keep the dot, too! */ return extname; } @@ -5016,53 +5016,53 @@ rb_file_join(VALUE ary) len = 1; for (i=0; ipath, ta->pos); #else /* defined(HAVE_CHSIZE) */ { - int tmpfd = rb_cloexec_open(ta->path, 0, 0); + int tmpfd = rb_cloexec_open(ta->path, 0, 0); - if (tmpfd < 0) - return (void *)-1; - rb_update_max_fd(tmpfd); - if (chsize(tmpfd, ta->pos) < 0) { - int e = errno; - close(tmpfd); - errno = e; - return (void *)-1; - } - close(tmpfd); - return 0; + if (tmpfd < 0) + return (void *)-1; + rb_update_max_fd(tmpfd); + if (chsize(tmpfd, ta->pos) < 0) { + int e = errno; + close(tmpfd); + errno = e; + return (void *)-1; + } + close(tmpfd); + return 0; } #endif } @@ -5150,9 +5150,9 @@ rb_file_s_truncate(VALUE klass, VALUE path, VALUE len) ta.path = StringValueCStr(path); r = (int)(VALUE)rb_thread_call_without_gvl(nogvl_truncate, &ta, - RUBY_UBF_IO, NULL); + RUBY_UBF_IO, NULL); if (r < 0) - rb_sys_fail_path(path); + rb_sys_fail_path(path); return INT2FIX(0); #undef NUM2POS } @@ -5207,12 +5207,12 @@ rb_file_truncate(VALUE obj, VALUE len) fa.pos = NUM2POS(len); GetOpenFile(obj, fptr); if (!(fptr->mode & FMODE_WRITABLE)) { - rb_raise(rb_eIOError, "not opened for writing"); + rb_raise(rb_eIOError, "not opened for writing"); } rb_io_flush_raw(obj, 0); fa.fd = fptr->fd; if ((int)rb_thread_io_blocking_region(nogvl_ftruncate, &fa, fa.fd) < 0) { - rb_sys_fail_path(fptr->pathv); + rb_sys_fail_path(fptr->pathv); } return INT2FIX(0); #undef NUM2POS @@ -5248,8 +5248,8 @@ rb_thread_flock(void *data) #ifdef __CYGWIN__ if (GetLastError() == ERROR_NOT_LOCKED) { - ret = 0; - errno = old_errno; + ret = 0; + errno = old_errno; } #endif return (VALUE)ret; @@ -5311,33 +5311,33 @@ rb_file_flock(VALUE obj, VALUE operation) op[0] = fptr->fd; if (fptr->mode & FMODE_WRITABLE) { - rb_io_flush_raw(obj, 0); + rb_io_flush_raw(obj, 0); } while ((int)rb_thread_io_blocking_region(rb_thread_flock, op, fptr->fd) < 0) { - int e = errno; - switch (e) { - case EAGAIN: - case EACCES: + int e = errno; + switch (e) { + case EAGAIN: + case EACCES: #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN - case EWOULDBLOCK: + case EWOULDBLOCK: #endif - if (op1 & LOCK_NB) return Qfalse; + if (op1 & LOCK_NB) return Qfalse; - time.tv_sec = 0; - time.tv_usec = 100 * 1000; /* 0.1 sec */ - rb_thread_wait_for(time); - rb_io_check_closed(fptr); - continue; + time.tv_sec = 0; + time.tv_usec = 100 * 1000; /* 0.1 sec */ + rb_thread_wait_for(time); + rb_io_check_closed(fptr); + continue; - case EINTR: + case EINTR: #if defined(ERESTART) - case ERESTART: + case ERESTART: #endif - break; + break; - default: - rb_syserr_fail_path(e, fptr->pathv); - } + default: + rb_syserr_fail_path(e, fptr->pathv); + } } return INT2FIX(0); } @@ -5350,9 +5350,9 @@ test_check(int n, int argc, VALUE *argv) n+=1; rb_check_arity(argc, n, n); for (i=1; i", cmd)) { - struct stat st1, st2; + struct stat st1, st2; struct timespec t1, t2; - CHECK(2); - if (rb_stat(argv[1], &st1) < 0) return Qfalse; - if (rb_stat(argv[2], &st2) < 0) return Qfalse; + CHECK(2); + if (rb_stat(argv[1], &st1) < 0) return Qfalse; + if (rb_stat(argv[2], &st2) < 0) return Qfalse; t1 = stat_mtimespec(&st1); t2 = stat_mtimespec(&st2); - switch (cmd) { - case '=': - if (t1.tv_sec == t2.tv_sec && t1.tv_nsec == t2.tv_nsec) return Qtrue; - return Qfalse; + switch (cmd) { + case '=': + if (t1.tv_sec == t2.tv_sec && t1.tv_nsec == t2.tv_nsec) return Qtrue; + return Qfalse; - case '>': - if (t1.tv_sec > t2.tv_sec) return Qtrue; - if (t1.tv_sec == t2.tv_sec && t1.tv_nsec > t2.tv_nsec) return Qtrue; - return Qfalse; + case '>': + if (t1.tv_sec > t2.tv_sec) return Qtrue; + if (t1.tv_sec == t2.tv_sec && t1.tv_nsec > t2.tv_nsec) return Qtrue; + return Qfalse; - case '<': - if (t1.tv_sec < t2.tv_sec) return Qtrue; - if (t1.tv_sec == t2.tv_sec && t1.tv_nsec < t2.tv_nsec) return Qtrue; - return Qfalse; - } + case '<': + if (t1.tv_sec < t2.tv_sec) return Qtrue; + if (t1.tv_sec == t2.tv_sec && t1.tv_nsec < t2.tv_nsec) return Qtrue; + return Qfalse; + } } unknown: /* unknown command */ @@ -5597,11 +5597,11 @@ rb_stat_init(VALUE obj, VALUE fname) FilePathValue(fname); fname = rb_str_encode_ospath(fname); if (STAT(StringValueCStr(fname), &st) == -1) { - rb_sys_fail_path(fname); + rb_sys_fail_path(fname); } if (DATA_PTR(obj)) { - xfree(DATA_PTR(obj)); - DATA_PTR(obj) = NULL; + xfree(DATA_PTR(obj)); + DATA_PTR(obj) = NULL; } nst = ALLOC(struct stat); *nst = st; @@ -5618,13 +5618,13 @@ rb_stat_init_copy(VALUE copy, VALUE orig) if (!OBJ_INIT_COPY(copy, orig)) return copy; if (DATA_PTR(copy)) { - xfree(DATA_PTR(copy)); - DATA_PTR(copy) = 0; + xfree(DATA_PTR(copy)); + DATA_PTR(copy) = 0; } if (DATA_PTR(orig)) { - nst = ALLOC(struct stat); - *nst = *(struct stat*)DATA_PTR(orig); - DATA_PTR(copy) = nst; + nst = ALLOC(struct stat); + *nst = *(struct stat*)DATA_PTR(orig); + DATA_PTR(copy) = nst; } return copy; @@ -5844,11 +5844,11 @@ rb_stat_r(VALUE obj) #endif #ifdef S_IRUSR if (rb_stat_owned(obj)) - return RBOOL(st->st_mode & S_IRUSR); + return RBOOL(st->st_mode & S_IRUSR); #endif #ifdef S_IRGRP if (rb_stat_grpowned(obj)) - return RBOOL(st->st_mode & S_IRGRP); + return RBOOL(st->st_mode & S_IRGRP); #endif #ifdef S_IROTH if (!(st->st_mode & S_IROTH)) return Qfalse; @@ -5877,11 +5877,11 @@ rb_stat_R(VALUE obj) #endif #ifdef S_IRUSR if (rb_stat_rowned(obj)) - return RBOOL(st->st_mode & S_IRUSR); + return RBOOL(st->st_mode & S_IRUSR); #endif #ifdef S_IRGRP if (rb_group_member(get_stat(obj)->st_gid)) - return RBOOL(st->st_mode & S_IRGRP); + return RBOOL(st->st_mode & S_IRGRP); #endif #ifdef S_IROTH if (!(st->st_mode & S_IROTH)) return Qfalse; @@ -5908,10 +5908,10 @@ rb_stat_wr(VALUE obj) #ifdef S_IROTH struct stat *st = get_stat(obj); if ((st->st_mode & (S_IROTH)) == S_IROTH) { - return UINT2NUM(st->st_mode & (S_IRUGO|S_IWUGO|S_IXUGO)); + return UINT2NUM(st->st_mode & (S_IRUGO|S_IWUGO|S_IXUGO)); } else { - return Qnil; + return Qnil; } #endif } @@ -5937,11 +5937,11 @@ rb_stat_w(VALUE obj) #endif #ifdef S_IWUSR if (rb_stat_owned(obj)) - return RBOOL(st->st_mode & S_IWUSR); + return RBOOL(st->st_mode & S_IWUSR); #endif #ifdef S_IWGRP if (rb_stat_grpowned(obj)) - return RBOOL(st->st_mode & S_IWGRP); + return RBOOL(st->st_mode & S_IWGRP); #endif #ifdef S_IWOTH if (!(st->st_mode & S_IWOTH)) return Qfalse; @@ -5970,11 +5970,11 @@ rb_stat_W(VALUE obj) #endif #ifdef S_IWUSR if (rb_stat_rowned(obj)) - return RBOOL(st->st_mode & S_IWUSR); + return RBOOL(st->st_mode & S_IWUSR); #endif #ifdef S_IWGRP if (rb_group_member(get_stat(obj)->st_gid)) - return RBOOL(st->st_mode & S_IWGRP); + return RBOOL(st->st_mode & S_IWGRP); #endif #ifdef S_IWOTH if (!(st->st_mode & S_IWOTH)) return Qfalse; @@ -6001,10 +6001,10 @@ rb_stat_ww(VALUE obj) #ifdef S_IROTH struct stat *st = get_stat(obj); if ((st->st_mode & (S_IWOTH)) == S_IWOTH) { - return UINT2NUM(st->st_mode & (S_IRUGO|S_IWUGO|S_IXUGO)); + return UINT2NUM(st->st_mode & (S_IRUGO|S_IWUGO|S_IXUGO)); } else { - return Qnil; + return Qnil; } #endif } @@ -6029,16 +6029,16 @@ rb_stat_x(VALUE obj) #ifdef USE_GETEUID if (geteuid() == 0) { - return RBOOL(st->st_mode & S_IXUGO); + return RBOOL(st->st_mode & S_IXUGO); } #endif #ifdef S_IXUSR if (rb_stat_owned(obj)) - return RBOOL(st->st_mode & S_IXUSR); + return RBOOL(st->st_mode & S_IXUSR); #endif #ifdef S_IXGRP if (rb_stat_grpowned(obj)) - return RBOOL(st->st_mode & S_IXGRP); + return RBOOL(st->st_mode & S_IXGRP); #endif #ifdef S_IXOTH if (!(st->st_mode & S_IXOTH)) return Qfalse; @@ -6061,16 +6061,16 @@ rb_stat_X(VALUE obj) #ifdef USE_GETEUID if (getuid() == 0) { - return RBOOL(st->st_mode & S_IXUGO); + return RBOOL(st->st_mode & S_IXUGO); } #endif #ifdef S_IXUSR if (rb_stat_rowned(obj)) - return RBOOL(st->st_mode & S_IXUSR); + return RBOOL(st->st_mode & S_IXUSR); #endif #ifdef S_IXGRP if (rb_group_member(get_stat(obj)->st_gid)) - return RBOOL(st->st_mode & S_IXGRP); + return RBOOL(st->st_mode & S_IXGRP); #endif #ifdef S_IXOTH if (!(st->st_mode & S_IXOTH)) return Qfalse; @@ -6235,14 +6235,14 @@ rb_file_s_mkfifo(int argc, VALUE *argv, VALUE _) ma.mode = 0666; rb_check_arity(argc, 1, 2); if (argc > 1) { - ma.mode = NUM2MODET(argv[1]); + ma.mode = NUM2MODET(argv[1]); } path = argv[0]; FilePathValue(path); path = rb_str_encode_ospath(path); ma.path = RSTRING_PTR(path); if (rb_thread_call_without_gvl(nogvl_mkfifo, &ma, RUBY_UBF_IO, 0)) { - rb_sys_fail_path(path); + rb_sys_fail_path(path); } return INT2FIX(0); } @@ -6292,16 +6292,16 @@ path_check_0(VALUE path) char *p = 0, *s; if (!rb_is_absolute_path(p0)) { - char *buf = ruby_getcwd(); - VALUE newpath; + char *buf = ruby_getcwd(); + VALUE newpath; - newpath = rb_str_new2(buf); - xfree(buf); + newpath = rb_str_new2(buf); + xfree(buf); - rb_str_cat2(newpath, "/"); - rb_str_cat2(newpath, p0); - path = newpath; - p0 = RSTRING_PTR(path); + rb_str_cat2(newpath, "/"); + rb_str_cat2(newpath, p0); + path = newpath; + p0 = RSTRING_PTR(path); } e0 = p0 + RSTRING_LEN(path); enc = rb_enc_get(path); @@ -6309,28 +6309,28 @@ path_check_0(VALUE path) #ifndef S_IWOTH # define S_IWOTH 002 #endif - if (STAT(p0, &st) == 0 && S_ISDIR(st.st_mode) && (st.st_mode & S_IWOTH) + if (STAT(p0, &st) == 0 && S_ISDIR(st.st_mode) && (st.st_mode & S_IWOTH) #ifdef S_ISVTX - && !(p && (st.st_mode & S_ISVTX)) + && !(p && (st.st_mode & S_ISVTX)) #endif - && !access(p0, W_OK)) { - rb_enc_warn(enc, "Insecure world writable dir %s in PATH, mode 0%" + && !access(p0, W_OK)) { + rb_enc_warn(enc, "Insecure world writable dir %s in PATH, mode 0%" #if SIZEOF_DEV_T > SIZEOF_INT - PRI_MODET_PREFIX"o", + PRI_MODET_PREFIX"o", #else - "o", + "o", #endif - p0, st.st_mode); - if (p) *p = '/'; - RB_GC_GUARD(path); - return 0; - } - s = strrdirsep(p0, e0, enc); - if (p) *p = '/'; - if (!s || s == p0) return 1; - p = s; - e0 = p; - *p = '\0'; + p0, st.st_mode); + if (p) *p = '/'; + RB_GC_GUARD(path); + return 0; + } + s = strrdirsep(p0, e0, enc); + if (p) *p = '/'; + if (!s || s == p0) return 1; + p = s; + e0 = p; + *p = '\0'; } } #endif @@ -6350,13 +6350,13 @@ rb_path_check(const char *path) if (!p) p = pend; for (;;) { - if (!path_check_0(rb_str_new(p0, p - p0))) { - return 0; /* not safe */ - } - p0 = p + 1; - if (p0 > pend) break; - p = strchr(p0, sep); - if (!p) p = pend; + if (!path_check_0(rb_str_new(p0, p - p0))) { + return 0; /* not safe */ + } + p0 = p + 1; + if (p0 > pend) break; + p = strchr(p0, sep); + if (!p) p = pend; } #endif return 1; @@ -6371,18 +6371,18 @@ ruby_is_fd_loadable(int fd) struct stat st; if (fstat(fd, &st) < 0) - return 0; + return 0; if (S_ISREG(st.st_mode)) - return 1; + return 1; if (S_ISFIFO(st.st_mode) || S_ISCHR(st.st_mode)) - return -1; + return -1; if (S_ISDIR(st.st_mode)) - errno = EISDIR; + errno = EISDIR; else - errno = ENXIO; + errno = ENXIO; return 0; #endif @@ -6399,11 +6399,11 @@ rb_file_load_ok(const char *path) */ int mode = (O_RDONLY | #if defined O_NONBLOCK - O_NONBLOCK | + O_NONBLOCK | #elif defined O_NDELAY - O_NDELAY | + O_NDELAY | #endif - 0); + 0); int fd = rb_cloexec_open(path, mode, 0); if (fd == -1) return 0; rb_update_max_fd(fd); @@ -6445,24 +6445,24 @@ rb_find_file_ext(VALUE *filep, const char *const *ext) if (!ext[0]) return 0; if (f[0] == '~') { - fname = file_expand_path_1(fname); - f = RSTRING_PTR(fname); - *filep = fname; - expanded = 1; + fname = file_expand_path_1(fname); + f = RSTRING_PTR(fname); + *filep = fname; + expanded = 1; } if (expanded || rb_is_absolute_path(f) || is_explicit_relative(f)) { - if (!expanded) fname = file_expand_path_1(fname); - fnlen = RSTRING_LEN(fname); - for (i=0; ext[i]; i++) { - rb_str_cat2(fname, ext[i]); - if (rb_file_load_ok(RSTRING_PTR(fname))) { - *filep = copy_path_class(fname, *filep); - return (int)(i+1); - } - rb_str_set_len(fname, fnlen); - } - return 0; + if (!expanded) fname = file_expand_path_1(fname); + fnlen = RSTRING_LEN(fname); + for (i=0; ext[i]; i++) { + rb_str_cat2(fname, ext[i]); + if (rb_file_load_ok(RSTRING_PTR(fname))) { + *filep = copy_path_class(fname, *filep); + return (int)(i+1); + } + rb_str_set_len(fname, fnlen); + } + return 0; } RB_GC_GUARD(load_path) = rb_get_expanded_load_path(); @@ -6474,19 +6474,19 @@ rb_find_file_ext(VALUE *filep, const char *const *ext) tmp = rb_str_tmp_new(MAXPATHLEN + 2); rb_enc_associate_index(tmp, rb_usascii_encindex()); for (j=0; ext[j]; j++) { - rb_str_cat2(fname, ext[j]); - for (i = 0; i < RARRAY_LEN(load_path); i++) { - VALUE str = RARRAY_AREF(load_path, i); + rb_str_cat2(fname, ext[j]); + for (i = 0; i < RARRAY_LEN(load_path); i++) { + VALUE str = RARRAY_AREF(load_path, i); RB_GC_GUARD(str) = rb_get_path(str); - if (RSTRING_LEN(str) == 0) continue; - rb_file_expand_path_internal(fname, str, 0, 0, tmp); - if (rb_file_load_ok(RSTRING_PTR(tmp))) { - *filep = copy_path_class(tmp, *filep); - return (int)(j+1); - } - } - rb_str_set_len(fname, fnlen); + if (RSTRING_LEN(str) == 0) continue; + rb_file_expand_path_internal(fname, str, 0, 0, tmp); + if (rb_file_load_ok(RSTRING_PTR(tmp))) { + *filep = copy_path_class(tmp, *filep); + return (int)(j+1); + } + } + rb_str_set_len(fname, fnlen); } rb_str_resize(tmp, 0); RB_GC_GUARD(load_path); @@ -6501,39 +6501,39 @@ rb_find_file(VALUE path) int expanded = 0; if (f[0] == '~') { - tmp = file_expand_path_1(path); - path = copy_path_class(tmp, path); - f = RSTRING_PTR(path); - expanded = 1; + tmp = file_expand_path_1(path); + path = copy_path_class(tmp, path); + f = RSTRING_PTR(path); + expanded = 1; } if (expanded || rb_is_absolute_path(f) || is_explicit_relative(f)) { - if (!rb_file_load_ok(f)) return 0; - if (!expanded) - path = copy_path_class(file_expand_path_1(path), path); - return path; + if (!rb_file_load_ok(f)) return 0; + if (!expanded) + path = copy_path_class(file_expand_path_1(path), path); + return path; } RB_GC_GUARD(load_path) = rb_get_expanded_load_path(); if (load_path) { - long i; + long i; - tmp = rb_str_tmp_new(MAXPATHLEN + 2); - rb_enc_associate_index(tmp, rb_usascii_encindex()); - for (i = 0; i < RARRAY_LEN(load_path); i++) { - VALUE str = RARRAY_AREF(load_path, i); + tmp = rb_str_tmp_new(MAXPATHLEN + 2); + rb_enc_associate_index(tmp, rb_usascii_encindex()); + for (i = 0; i < RARRAY_LEN(load_path); i++) { + VALUE str = RARRAY_AREF(load_path, i); RB_GC_GUARD(str) = rb_get_path(str); - if (RSTRING_LEN(str) > 0) { - rb_file_expand_path_internal(path, str, 0, 0, tmp); - f = RSTRING_PTR(tmp); - if (rb_file_load_ok(f)) goto found; - } - } - rb_str_resize(tmp, 0); - return 0; + if (RSTRING_LEN(str) > 0) { + rb_file_expand_path_internal(path, str, 0, 0, tmp); + f = RSTRING_PTR(tmp); + if (rb_file_load_ok(f)) goto found; + } + } + rb_str_resize(tmp, 0); + return 0; } else { - return 0; /* no path, no load */ + return 0; /* no path, no load */ } found: diff --git a/gc.c b/gc.c index 4b619fd33f..56e4480861 100644 --- a/gc.c +++ b/gc.c @@ -579,46 +579,46 @@ struct RMoved { typedef struct RVALUE { union { - struct { - VALUE flags; /* always 0 for freed obj */ - struct RVALUE *next; - } free; + struct { + VALUE flags; /* always 0 for freed obj */ + struct RVALUE *next; + } free; struct RMoved moved; - struct RBasic basic; - struct RObject object; - struct RClass klass; - struct RFloat flonum; - struct RString string; - struct RArray array; - struct RRegexp regexp; - struct RHash hash; - struct RData data; - struct RTypedData typeddata; - struct RStruct rstruct; - struct RBignum bignum; - struct RFile file; - struct RMatch match; - struct RRational rational; - struct RComplex complex; + struct RBasic basic; + struct RObject object; + struct RClass klass; + struct RFloat flonum; + struct RString string; + struct RArray array; + struct RRegexp regexp; + struct RHash hash; + struct RData data; + struct RTypedData typeddata; + struct RStruct rstruct; + struct RBignum bignum; + struct RFile file; + struct RMatch match; + struct RRational rational; + struct RComplex complex; struct RSymbol symbol; - union { - rb_cref_t cref; - struct vm_svar svar; - struct vm_throw_data throw_data; - struct vm_ifunc ifunc; - struct MEMO memo; - struct rb_method_entry_struct ment; - const rb_iseq_t iseq; - rb_env_t env; - struct rb_imemo_tmpbuf_struct alloc; - rb_ast_t ast; - } imemo; - struct { - struct RBasic basic; - VALUE v1; - VALUE v2; - VALUE v3; - } values; + union { + rb_cref_t cref; + struct vm_svar svar; + struct vm_throw_data throw_data; + struct vm_ifunc ifunc; + struct MEMO memo; + struct rb_method_entry_struct ment; + const rb_iseq_t iseq; + rb_env_t env; + struct rb_imemo_tmpbuf_struct alloc; + rb_ast_t ast; + } imemo; + struct { + struct RBasic basic; + VALUE v1; + VALUE v2; + VALUE v3; + } values; } as; #if GC_DEBUG const char *file; @@ -716,27 +716,27 @@ enum gc_mode { typedef struct rb_objspace { struct { - size_t limit; - size_t increase; + size_t limit; + size_t increase; #if MALLOC_ALLOCATED_SIZE - size_t allocated_size; - size_t allocations; + size_t allocated_size; + size_t allocations; #endif } malloc_params; struct { - unsigned int mode : 2; - unsigned int immediate_sweep : 1; - unsigned int dont_gc : 1; - unsigned int dont_incremental : 1; - unsigned int during_gc : 1; + unsigned int mode : 2; + unsigned int immediate_sweep : 1; + unsigned int dont_gc : 1; + unsigned int dont_incremental : 1; + unsigned int during_gc : 1; unsigned int during_compacting : 1; - unsigned int gc_stressful: 1; - unsigned int has_hook: 1; - unsigned int during_minor_gc : 1; + unsigned int gc_stressful: 1; + unsigned int has_hook: 1; + unsigned int during_minor_gc : 1; #if GC_ENABLE_INCREMENTAL_MARK - unsigned int during_incremental_marking : 1; + unsigned int during_incremental_marking : 1; #endif unsigned int measure_gc : 1; } flags; @@ -748,70 +748,70 @@ typedef struct rb_objspace { rb_size_pool_t size_pools[SIZE_POOL_COUNT]; struct { - rb_atomic_t finalizing; + rb_atomic_t finalizing; } atomic_flags; mark_stack_t mark_stack; size_t marked_slots; struct { - struct heap_page **sorted; - size_t allocated_pages; - size_t allocatable_pages; - size_t sorted_length; - uintptr_t range[2]; - size_t freeable_pages; + struct heap_page **sorted; + size_t allocated_pages; + size_t allocatable_pages; + size_t sorted_length; + uintptr_t range[2]; + size_t freeable_pages; - /* final */ - size_t final_slots; - VALUE deferred_final; + /* final */ + size_t final_slots; + VALUE deferred_final; } heap_pages; st_table *finalizer_table; struct { - int run; - unsigned int latest_gc_info; - gc_profile_record *records; - gc_profile_record *current_record; - size_t next_index; - size_t size; + int run; + unsigned int latest_gc_info; + gc_profile_record *records; + gc_profile_record *current_record; + size_t next_index; + size_t size; #if GC_PROFILE_MORE_DETAIL - double prepare_time; + double prepare_time; #endif - double invoke_time; + double invoke_time; - size_t minor_gc_count; - size_t major_gc_count; - size_t compact_count; - size_t read_barrier_faults; + size_t minor_gc_count; + size_t major_gc_count; + size_t compact_count; + size_t read_barrier_faults; #if RGENGC_PROFILE > 0 - size_t total_generated_normal_object_count; - size_t total_generated_shady_object_count; - size_t total_shade_operation_count; - size_t total_promoted_count; - size_t total_remembered_normal_object_count; - size_t total_remembered_shady_object_count; + size_t total_generated_normal_object_count; + size_t total_generated_shady_object_count; + size_t total_shade_operation_count; + size_t total_promoted_count; + size_t total_remembered_normal_object_count; + size_t total_remembered_shady_object_count; #if RGENGC_PROFILE >= 2 - size_t generated_normal_object_count_types[RUBY_T_MASK]; - size_t generated_shady_object_count_types[RUBY_T_MASK]; - size_t shade_operation_count_types[RUBY_T_MASK]; - size_t promoted_types[RUBY_T_MASK]; - size_t remembered_normal_object_count_types[RUBY_T_MASK]; - size_t remembered_shady_object_count_types[RUBY_T_MASK]; + size_t generated_normal_object_count_types[RUBY_T_MASK]; + size_t generated_shady_object_count_types[RUBY_T_MASK]; + size_t shade_operation_count_types[RUBY_T_MASK]; + size_t promoted_types[RUBY_T_MASK]; + size_t remembered_normal_object_count_types[RUBY_T_MASK]; + size_t remembered_shady_object_count_types[RUBY_T_MASK]; #endif #endif /* RGENGC_PROFILE */ - /* temporary profiling space */ - double gc_sweep_start_time; - size_t total_allocated_objects_at_gc_start; - size_t heap_used_at_gc_start; + /* temporary profiling space */ + double gc_sweep_start_time; + size_t total_allocated_objects_at_gc_start; + size_t heap_used_at_gc_start; - /* basic statistics */ - size_t count; - size_t total_freed_objects; + /* basic statistics */ + size_t count; + size_t total_freed_objects; uint64_t total_time_ns; struct timespec start_time; } profile; @@ -820,22 +820,22 @@ typedef struct rb_objspace { VALUE gc_stress_mode; struct { - VALUE parent_object; - int need_major_gc; - size_t last_major_gc; - size_t uncollectible_wb_unprotected_objects; - size_t uncollectible_wb_unprotected_objects_limit; - size_t old_objects; - size_t old_objects_limit; + VALUE parent_object; + int need_major_gc; + size_t last_major_gc; + size_t uncollectible_wb_unprotected_objects; + size_t uncollectible_wb_unprotected_objects_limit; + size_t old_objects; + size_t old_objects_limit; #if RGENGC_ESTIMATE_OLDMALLOC - size_t oldmalloc_increase; - size_t oldmalloc_increase_limit; + size_t oldmalloc_increase; + size_t oldmalloc_increase_limit; #endif #if RGENGC_CHECK_MODE >= 2 - struct st_table *allrefs_table; - size_t error_count; + struct st_table *allrefs_table; + size_t error_count; #endif } rgengc; @@ -849,8 +849,8 @@ typedef struct rb_objspace { #if GC_ENABLE_INCREMENTAL_MARK struct { - size_t pooled_slots; - size_t step_slots; + size_t pooled_slots; + size_t step_slots; } rincgc; #endif @@ -935,10 +935,10 @@ struct heap_page { short pinned_slots; short final_slots; struct { - unsigned int before_sweep : 1; - unsigned int has_remembered_objects : 1; - unsigned int has_uncollectible_shady_objects : 1; - unsigned int in_tomb : 1; + unsigned int before_sweep : 1; + unsigned int has_remembered_objects : 1; + unsigned int has_uncollectible_shady_objects : 1; + unsigned int in_tomb : 1; } flags; rb_size_pool_t *size_pool; @@ -1034,9 +1034,9 @@ gc_mode_verify(enum gc_mode mode) case gc_mode_marking: case gc_mode_sweeping: case gc_mode_compacting: - break; + break; default: - rb_bug("gc_mode_verify: unreachable (%d)", (int)mode); + rb_bug("gc_mode_verify: unreachable (%d)", (int)mode); } #endif return mode; @@ -1698,14 +1698,14 @@ RVALUE_AGE_INC(rb_objspace_t *objspace, VALUE obj) int age = RVALUE_FLAGS_AGE(flags); if (RGENGC_CHECK_MODE && age == RVALUE_OLD_AGE) { - rb_bug("RVALUE_AGE_INC: can not increment age of OLD object %s.", obj_info(obj)); + rb_bug("RVALUE_AGE_INC: can not increment age of OLD object %s.", obj_info(obj)); } age++; RBASIC(obj)->flags = RVALUE_FLAGS_AGE_SET(flags, age); if (age == RVALUE_OLD_AGE) { - RVALUE_OLD_UNCOLLECTIBLE_SET(objspace, obj); + RVALUE_OLD_UNCOLLECTIBLE_SET(objspace, obj); } check_rvalue_consistency(obj); } @@ -1749,13 +1749,13 @@ RVALUE_DEMOTE(rb_objspace_t *objspace, VALUE obj) GC_ASSERT(RVALUE_OLD_P(obj)); if (!is_incremental_marking(objspace) && RVALUE_REMEMBERED(obj)) { - CLEAR_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj); + CLEAR_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj); } RVALUE_DEMOTE_RAW(objspace, obj); if (RVALUE_MARKED(obj)) { - objspace->rgengc.old_objects--; + objspace->rgengc.old_objects--; } check_rvalue_consistency(obj); @@ -1836,30 +1836,30 @@ void rb_objspace_free(rb_objspace_t *objspace) { if (is_lazy_sweeping(objspace)) - rb_bug("lazy sweeping underway when freeing object space"); + rb_bug("lazy sweeping underway when freeing object space"); if (objspace->profile.records) { - free(objspace->profile.records); - objspace->profile.records = 0; + free(objspace->profile.records); + objspace->profile.records = 0; } if (global_list) { - struct gc_list *list, *next; - for (list = global_list; list; list = next) { - next = list->next; - xfree(list); - } + struct gc_list *list, *next; + for (list = global_list; list; list = next) { + next = list->next; + xfree(list); + } } if (heap_pages_sorted) { - size_t i; - for (i = 0; i < heap_allocated_pages; ++i) { - heap_page_free(objspace, heap_pages_sorted[i]); - } - free(heap_pages_sorted); - heap_allocated_pages = 0; - heap_pages_sorted_length = 0; - heap_pages_lomem = 0; - heap_pages_himem = 0; + size_t i; + for (i = 0; i < heap_allocated_pages; ++i) { + heap_page_free(objspace, heap_pages_sorted[i]); + } + free(heap_pages_sorted); + heap_allocated_pages = 0; + heap_pages_sorted_length = 0; + heap_pages_lomem = 0; + heap_pages_himem = 0; for (int i = 0; i < SIZE_POOL_COUNT; i++) { rb_size_pool_t *size_pool = &size_pools[i]; @@ -1886,15 +1886,15 @@ heap_pages_expand_sorted_to(rb_objspace_t *objspace, size_t next_length) next_length, size); if (heap_pages_sorted_length > 0) { - sorted = (struct heap_page **)realloc(heap_pages_sorted, size); - if (sorted) heap_pages_sorted = sorted; + sorted = (struct heap_page **)realloc(heap_pages_sorted, size); + if (sorted) heap_pages_sorted = sorted; } else { - sorted = heap_pages_sorted = (struct heap_page **)malloc(size); + sorted = heap_pages_sorted = (struct heap_page **)malloc(size); } if (sorted == 0) { - rb_memerror(); + rb_memerror(); } heap_pages_sorted_length = next_length; @@ -1916,7 +1916,7 @@ heap_pages_expand_sorted(rb_objspace_t *objspace) } if (next_length > heap_pages_sorted_length) { - heap_pages_expand_sorted_to(objspace, next_length); + heap_pages_expand_sorted_to(objspace, next_length); } GC_ASSERT(heap_allocatable_pages(objspace) + heap_eden_total_pages(objspace) <= heap_pages_sorted_length); @@ -2060,7 +2060,7 @@ heap_pages_free_unused_pages(rb_objspace_t *objspace) GC_ASSERT(himem <= heap_pages_himem); heap_pages_himem = himem; - GC_ASSERT(j == heap_allocated_pages); + GC_ASSERT(j == heap_allocated_pages); } } @@ -2124,14 +2124,14 @@ heap_page_allocate(rb_objspace_t *objspace, rb_size_pool_t *size_pool) /* assign heap_page body (contains heap_page_header and RVALUEs) */ struct heap_page_body *page_body = heap_page_body_allocate(); if (page_body == 0) { - rb_memerror(); + rb_memerror(); } /* assign heap_page entry */ page = calloc1(sizeof(struct heap_page)); if (page == 0) { heap_page_body_free(page_body); - rb_memerror(); + rb_memerror(); } /* adjust obj_limit (object number available in this page) */ @@ -2152,7 +2152,7 @@ heap_page_allocate(rb_objspace_t *objspace, rb_size_pool_t *size_pool) GC_ASSERT(NUM_IN_PAGE(start) * BASE_SLOT_SIZE % stride == 0); - limit = (HEAP_PAGE_SIZE - (int)(start - (uintptr_t)page_body))/(int)stride; + limit = (HEAP_PAGE_SIZE - (int)(start - (uintptr_t)page_body))/(int)stride; } end = start + (limit * (int)stride); @@ -2160,23 +2160,23 @@ heap_page_allocate(rb_objspace_t *objspace, rb_size_pool_t *size_pool) lo = 0; hi = (uintptr_t)heap_allocated_pages; while (lo < hi) { - struct heap_page *mid_page; + struct heap_page *mid_page; - mid = (lo + hi) / 2; - mid_page = heap_pages_sorted[mid]; - if ((uintptr_t)mid_page->start < start) { - lo = mid + 1; - } - else if ((uintptr_t)mid_page->start > start) { - hi = mid; - } - else { - rb_bug("same heap page is allocated: %p at %"PRIuVALUE, (void *)page_body, (VALUE)mid); - } + mid = (lo + hi) / 2; + mid_page = heap_pages_sorted[mid]; + if ((uintptr_t)mid_page->start < start) { + lo = mid + 1; + } + else if ((uintptr_t)mid_page->start > start) { + hi = mid; + } + else { + rb_bug("same heap page is allocated: %p at %"PRIuVALUE, (void *)page_body, (VALUE)mid); + } } if (hi < (uintptr_t)heap_allocated_pages) { - MEMMOVE(&heap_pages_sorted[hi+1], &heap_pages_sorted[hi], struct heap_page_header*, heap_allocated_pages - hi); + MEMMOVE(&heap_pages_sorted[hi+1], &heap_pages_sorted[hi], struct heap_page_header*, heap_allocated_pages - hi); } heap_pages_sorted[hi] = page; @@ -2190,8 +2190,8 @@ heap_page_allocate(rb_objspace_t *objspace, rb_size_pool_t *size_pool) size_pool->total_allocated_pages++; if (heap_allocated_pages > heap_pages_sorted_length) { - rb_bug("heap_page_allocate: allocated(%"PRIdSIZE") > sorted(%"PRIdSIZE")", - heap_allocated_pages, heap_pages_sorted_length); + rb_bug("heap_page_allocate: allocated(%"PRIdSIZE") > sorted(%"PRIdSIZE")", + heap_allocated_pages, heap_pages_sorted_length); } if (heap_pages_lomem == 0 || heap_pages_lomem > start) heap_pages_lomem = start; @@ -2204,8 +2204,8 @@ heap_page_allocate(rb_objspace_t *objspace, rb_size_pool_t *size_pool) page_body->header.page = page; for (p = start; p != end; p += stride) { - gc_report(3, objspace, "assign_heap_page: %p is added to freelist\n", (void *)p); - heap_page_add_freeobj(objspace, page, (VALUE)p); + gc_report(3, objspace, "assign_heap_page: %p is added to freelist\n", (void *)p); + heap_page_add_freeobj(objspace, page, (VALUE)p); } page->free_slots = limit; @@ -2220,11 +2220,11 @@ heap_page_resurrect(rb_objspace_t *objspace, rb_size_pool_t *size_pool) ccan_list_for_each_safe(&SIZE_POOL_TOMB_HEAP(size_pool)->pages, page, next, page_node) { asan_unpoison_memory_region(&page->freelist, sizeof(RVALUE*), false); - if (page->freelist != NULL) { - heap_unlink_page(objspace, &size_pool->tomb_heap, page); + if (page->freelist != NULL) { + heap_unlink_page(objspace, &size_pool->tomb_heap, page); asan_poison_memory_region(&page->freelist, sizeof(RVALUE*)); - return page; - } + return page; + } } return NULL; @@ -2241,8 +2241,8 @@ heap_page_create(rb_objspace_t *objspace, rb_size_pool_t *size_pool) page = heap_page_resurrect(objspace, size_pool); if (page == NULL) { - page = heap_page_allocate(objspace, size_pool); - method = "allocate"; + page = heap_page_allocate(objspace, size_pool); + method = "allocate"; } if (0) fprintf(stderr, "heap_page_create: %s - %p, " "heap_allocated_pages: %"PRIdSIZE", " @@ -2279,7 +2279,7 @@ heap_add_pages(rb_objspace_t *objspace, rb_size_pool_t *size_pool, rb_heap_t *he size_pool_allocatable_pages_set(objspace, size_pool, add); for (i = 0; i < add; i++) { - heap_assign_page(objspace, size_pool, heap); + heap_assign_page(objspace, size_pool, heap); } GC_ASSERT(size_pool->allocatable_pages == 0); @@ -2292,36 +2292,36 @@ heap_extend_pages(rb_objspace_t *objspace, rb_size_pool_t *size_pool, size_t fre size_t next_used; if (goal_ratio == 0.0) { - next_used = (size_t)(used * gc_params.growth_factor); + next_used = (size_t)(used * gc_params.growth_factor); } else if (total_slots == 0) { int multiple = size_pool->slot_size / BASE_SLOT_SIZE; next_used = (gc_params.heap_init_slots * multiple) / HEAP_PAGE_OBJ_LIMIT; } else { - /* Find `f' where free_slots = f * total_slots * goal_ratio - * => f = (total_slots - free_slots) / ((1 - goal_ratio) * total_slots) - */ - double f = (double)(total_slots - free_slots) / ((1 - goal_ratio) * total_slots); + /* Find `f' where free_slots = f * total_slots * goal_ratio + * => f = (total_slots - free_slots) / ((1 - goal_ratio) * total_slots) + */ + double f = (double)(total_slots - free_slots) / ((1 - goal_ratio) * total_slots); - if (f > gc_params.growth_factor) f = gc_params.growth_factor; - if (f < 1.0) f = 1.1; + if (f > gc_params.growth_factor) f = gc_params.growth_factor; + if (f < 1.0) f = 1.1; - next_used = (size_t)(f * used); + next_used = (size_t)(f * used); - if (0) { - fprintf(stderr, - "free_slots(%8"PRIuSIZE")/total_slots(%8"PRIuSIZE")=%1.2f," - " G(%1.2f), f(%1.2f)," - " used(%8"PRIuSIZE") => next_used(%8"PRIuSIZE")\n", - free_slots, total_slots, free_slots/(double)total_slots, - goal_ratio, f, used, next_used); - } + if (0) { + fprintf(stderr, + "free_slots(%8"PRIuSIZE")/total_slots(%8"PRIuSIZE")=%1.2f," + " G(%1.2f), f(%1.2f)," + " used(%8"PRIuSIZE") => next_used(%8"PRIuSIZE")\n", + free_slots, total_slots, free_slots/(double)total_slots, + goal_ratio, f, used, next_used); + } } if (gc_params.growth_max_slots > 0) { - size_t max_used = (size_t)(used + gc_params.growth_max_slots/HEAP_PAGE_OBJ_LIMIT); - if (next_used > max_used) next_used = max_used; + size_t max_used = (size_t)(used + gc_params.growth_max_slots/HEAP_PAGE_OBJ_LIMIT); + if (next_used > max_used) next_used = max_used; } size_t extend_page_count = next_used - used; @@ -2335,15 +2335,15 @@ static int heap_increment(rb_objspace_t *objspace, rb_size_pool_t *size_pool, rb_heap_t *heap) { if (size_pool->allocatable_pages > 0) { - gc_report(1, objspace, "heap_increment: heap_pages_sorted_length: %"PRIdSIZE", " + gc_report(1, objspace, "heap_increment: heap_pages_sorted_length: %"PRIdSIZE", " "heap_pages_inc: %"PRIdSIZE", heap->total_pages: %"PRIdSIZE"\n", - heap_pages_sorted_length, size_pool->allocatable_pages, heap->total_pages); + heap_pages_sorted_length, size_pool->allocatable_pages, heap->total_pages); - GC_ASSERT(heap_allocatable_pages(objspace) + heap_eden_total_pages(objspace) <= heap_pages_sorted_length); - GC_ASSERT(heap_allocated_pages <= heap_pages_sorted_length); + GC_ASSERT(heap_allocatable_pages(objspace) + heap_eden_total_pages(objspace) <= heap_pages_sorted_length); + GC_ASSERT(heap_allocated_pages <= heap_pages_sorted_length); - heap_assign_page(objspace, size_pool, heap); - return TRUE; + heap_assign_page(objspace, size_pool, heap); + return TRUE; } return FALSE; } @@ -2353,7 +2353,7 @@ gc_continue(rb_objspace_t *objspace, rb_size_pool_t *size_pool, rb_heap_t *heap) { /* Continue marking if in incremental marking. */ if (heap->free_pages == NULL && is_incremental_marking(objspace)) { - gc_marks_continue(objspace, size_pool, heap); + gc_marks_continue(objspace, size_pool, heap); } /* Continue sweeping if in lazy sweeping or the previous incremental @@ -2437,7 +2437,7 @@ gc_event_hook_body(rb_execution_context_t *ec, rb_objspace_t *objspace, const rb #define gc_event_hook_prep(objspace, event, data, prep) do { \ if (UNLIKELY(gc_event_hook_needed_p(objspace, event))) { \ prep; \ - gc_event_hook_body(GET_EC(), (objspace), (event), (data)); \ + gc_event_hook_body(GET_EC(), (objspace), (event), (data)); \ } \ } while (0) @@ -2932,7 +2932,7 @@ rb_newobj_of(VALUE klass, VALUE flags) #define UNEXPECTED_NODE(func) \ rb_bug(#func"(): GC does not handle T_NODE 0x%x(%p) 0x%"PRIxVALUE, \ - BUILTIN_TYPE(obj), (void*)(obj), RBASIC(obj)->flags) + BUILTIN_TYPE(obj), (void*)(obj), RBASIC(obj)->flags) const char * rb_imemo_name(enum imemo_type type) @@ -3084,11 +3084,11 @@ size_t rb_objspace_data_type_memsize(VALUE obj) { if (RTYPEDDATA_P(obj)) { - const rb_data_type_t *type = RTYPEDDATA_TYPE(obj); - const void *ptr = RTYPEDDATA_DATA(obj); - if (ptr && type->function.dsize) { - return type->function.dsize(ptr); - } + const rb_data_type_t *type = RTYPEDDATA_TYPE(obj); + const void *ptr = RTYPEDDATA_DATA(obj); + if (ptr && type->function.dsize) { + return type->function.dsize(ptr); + } } return 0; } @@ -3097,10 +3097,10 @@ const char * rb_objspace_data_type_name(VALUE obj) { if (RTYPEDDATA_P(obj)) { - return RTYPEDDATA_TYPE(obj)->wrap_struct_name; + return RTYPEDDATA_TYPE(obj)->wrap_struct_name; } else { - return 0; + return 0; } } @@ -3382,15 +3382,15 @@ obj_free(rb_objspace_t *objspace, VALUE obj) case T_FIXNUM: case T_TRUE: case T_FALSE: - rb_bug("obj_free() called for broken object"); - break; + rb_bug("obj_free() called for broken object"); + break; default: break; } if (FL_TEST(obj, FL_EXIVAR)) { - rb_free_generic_ivar((VALUE)obj); - FL_UNSET(obj, FL_EXIVAR); + rb_free_generic_ivar((VALUE)obj); + FL_UNSET(obj, FL_EXIVAR); } if (FL_TEST(obj, FL_SEEN_OBJ_ID) && !FL_TEST(obj, FL_FINALIZE)) { @@ -3401,10 +3401,10 @@ obj_free(rb_objspace_t *objspace, VALUE obj) #if RGENGC_CHECK_MODE #define CHECK(x) if (x(obj) != FALSE) rb_bug("obj_free: " #x "(%s) != FALSE", obj_info(obj)) - CHECK(RVALUE_WB_UNPROTECTED); - CHECK(RVALUE_MARKED); - CHECK(RVALUE_MARKING); - CHECK(RVALUE_UNCOLLECTIBLE); + CHECK(RVALUE_WB_UNPROTECTED); + CHECK(RVALUE_MARKED); + CHECK(RVALUE_MARKING); + CHECK(RVALUE_UNCOLLECTIBLE); #undef CHECK #endif @@ -3423,24 +3423,24 @@ obj_free(rb_objspace_t *objspace, VALUE obj) break; case T_MODULE: case T_CLASS: - rb_id_table_free(RCLASS_M_TBL(obj)); + rb_id_table_free(RCLASS_M_TBL(obj)); cc_table_free(objspace, obj, FALSE); - if (RCLASS_IV_TBL(obj)) { - st_free_table(RCLASS_IV_TBL(obj)); - } - if (RCLASS_CONST_TBL(obj)) { - rb_free_const_table(RCLASS_CONST_TBL(obj)); - } - if (RCLASS_IV_INDEX_TBL(obj)) { + if (RCLASS_IV_TBL(obj)) { + st_free_table(RCLASS_IV_TBL(obj)); + } + if (RCLASS_CONST_TBL(obj)) { + rb_free_const_table(RCLASS_CONST_TBL(obj)); + } + if (RCLASS_IV_INDEX_TBL(obj)) { iv_index_tbl_free(RCLASS_IV_INDEX_TBL(obj)); - } - if (RCLASS_CVC_TBL(obj)) { + } + if (RCLASS_CVC_TBL(obj)) { rb_id_table_foreach_values(RCLASS_CVC_TBL(obj), cvar_table_free_i, NULL); rb_id_table_free(RCLASS_CVC_TBL(obj)); - } + } rb_class_remove_subclass_head(obj); - rb_class_remove_from_module_subclasses(obj); - rb_class_remove_from_super_subclasses(obj); + rb_class_remove_from_module_subclasses(obj); + rb_class_remove_from_super_subclasses(obj); if (FL_TEST_RAW(obj, RCLASS_SUPERCLASSES_INCLUDE_SELF)) { xfree(RCLASS_SUPERCLASSES(obj)); } @@ -3449,19 +3449,19 @@ obj_free(rb_objspace_t *objspace, VALUE obj) #endif #if !USE_RVARGC - if (RCLASS_EXT(obj)) + if (RCLASS_EXT(obj)) xfree(RCLASS_EXT(obj)); #endif (void)RB_DEBUG_COUNTER_INC_IF(obj_module_ptr, BUILTIN_TYPE(obj) == T_MODULE); (void)RB_DEBUG_COUNTER_INC_IF(obj_class_ptr, BUILTIN_TYPE(obj) == T_CLASS); - break; + break; case T_STRING: - rb_str_free(obj); - break; + rb_str_free(obj); + break; case T_ARRAY: rb_ary_free(obj); - break; + break; case T_HASH: #if USE_DEBUG_COUNTER switch (RHASH_SIZE(obj)) { @@ -3519,53 +3519,53 @@ obj_free(rb_objspace_t *objspace, VALUE obj) GC_ASSERT(RHASH_ST_TABLE_P(obj)); st_free_table(RHASH(obj)->as.st); } - break; + break; case T_REGEXP: - if (RANY(obj)->as.regexp.ptr) { - onig_free(RANY(obj)->as.regexp.ptr); + if (RANY(obj)->as.regexp.ptr) { + onig_free(RANY(obj)->as.regexp.ptr); RB_DEBUG_COUNTER_INC(obj_regexp_ptr); - } - break; + } + break; case T_DATA: - if (DATA_PTR(obj)) { - int free_immediately = FALSE; - void (*dfree)(void *); - void *data = DATA_PTR(obj); + if (DATA_PTR(obj)) { + int free_immediately = FALSE; + void (*dfree)(void *); + void *data = DATA_PTR(obj); - if (RTYPEDDATA_P(obj)) { - free_immediately = (RANY(obj)->as.typeddata.type->flags & RUBY_TYPED_FREE_IMMEDIATELY) != 0; - dfree = RANY(obj)->as.typeddata.type->function.dfree; - if (0 && free_immediately == 0) { - /* to expose non-free-immediate T_DATA */ - fprintf(stderr, "not immediate -> %s\n", RANY(obj)->as.typeddata.type->wrap_struct_name); - } - } - else { - dfree = RANY(obj)->as.data.dfree; - } + if (RTYPEDDATA_P(obj)) { + free_immediately = (RANY(obj)->as.typeddata.type->flags & RUBY_TYPED_FREE_IMMEDIATELY) != 0; + dfree = RANY(obj)->as.typeddata.type->function.dfree; + if (0 && free_immediately == 0) { + /* to expose non-free-immediate T_DATA */ + fprintf(stderr, "not immediate -> %s\n", RANY(obj)->as.typeddata.type->wrap_struct_name); + } + } + else { + dfree = RANY(obj)->as.data.dfree; + } - if (dfree) { - if (dfree == RUBY_DEFAULT_FREE) { - xfree(data); + if (dfree) { + if (dfree == RUBY_DEFAULT_FREE) { + xfree(data); RB_DEBUG_COUNTER_INC(obj_data_xfree); - } - else if (free_immediately) { - (*dfree)(data); + } + else if (free_immediately) { + (*dfree)(data); RB_DEBUG_COUNTER_INC(obj_data_imm_free); - } - else { - make_zombie(objspace, obj, dfree, data); + } + else { + make_zombie(objspace, obj, dfree, data); RB_DEBUG_COUNTER_INC(obj_data_zombie); - return FALSE; - } - } + return FALSE; + } + } else { RB_DEBUG_COUNTER_INC(obj_data_empty); } - } - break; + } + break; case T_MATCH: - if (RANY(obj)->as.match.rmatch) { + if (RANY(obj)->as.match.rmatch) { struct rmatch *rm = RANY(obj)->as.match.rmatch; #if USE_DEBUG_COUNTER if (rm->regs.num_regs >= 8) { @@ -3578,21 +3578,21 @@ obj_free(rb_objspace_t *objspace, VALUE obj) RB_DEBUG_COUNTER_INC(obj_match_under4); } #endif - onig_region_free(&rm->regs, 0); + onig_region_free(&rm->regs, 0); if (rm->char_offset) - xfree(rm->char_offset); - xfree(rm); + xfree(rm->char_offset); + xfree(rm); RB_DEBUG_COUNTER_INC(obj_match_ptr); - } - break; + } + break; case T_FILE: - if (RANY(obj)->as.file.fptr) { - make_io_zombie(objspace, obj); + if (RANY(obj)->as.file.fptr) { + make_io_zombie(objspace, obj); RB_DEBUG_COUNTER_INC(obj_file_ptr); - return FALSE; - } - break; + return FALSE; + } + break; case T_RATIONAL: RB_DEBUG_COUNTER_INC(obj_rational); break; @@ -3600,44 +3600,44 @@ obj_free(rb_objspace_t *objspace, VALUE obj) RB_DEBUG_COUNTER_INC(obj_complex); break; case T_MOVED: - break; + break; case T_ICLASS: - /* Basically , T_ICLASS shares table with the module */ + /* Basically , T_ICLASS shares table with the module */ if (RICLASS_OWNS_M_TBL_P(obj)) { /* Method table is not shared for origin iclasses of classes */ rb_id_table_free(RCLASS_M_TBL(obj)); } - if (RCLASS_CALLABLE_M_TBL(obj) != NULL) { - rb_id_table_free(RCLASS_CALLABLE_M_TBL(obj)); - } + if (RCLASS_CALLABLE_M_TBL(obj) != NULL) { + rb_id_table_free(RCLASS_CALLABLE_M_TBL(obj)); + } rb_class_remove_subclass_head(obj); cc_table_free(objspace, obj, FALSE); - rb_class_remove_from_module_subclasses(obj); - rb_class_remove_from_super_subclasses(obj); + rb_class_remove_from_module_subclasses(obj); + rb_class_remove_from_super_subclasses(obj); #if !USE_RVARGC xfree(RCLASS_EXT(obj)); #endif RB_DEBUG_COUNTER_INC(obj_iclass_ptr); - break; + break; case T_FLOAT: RB_DEBUG_COUNTER_INC(obj_float); - break; + break; case T_BIGNUM: - if (!BIGNUM_EMBED_P(obj) && BIGNUM_DIGITS(obj)) { - xfree(BIGNUM_DIGITS(obj)); + if (!BIGNUM_EMBED_P(obj) && BIGNUM_DIGITS(obj)) { + xfree(BIGNUM_DIGITS(obj)); RB_DEBUG_COUNTER_INC(obj_bignum_ptr); - } + } else { RB_DEBUG_COUNTER_INC(obj_bignum_embed); } - break; + break; case T_NODE: - UNEXPECTED_NODE(obj_free); - break; + UNEXPECTED_NODE(obj_free); + break; case T_STRUCT: if ((RBASIC(obj)->flags & RSTRUCT_EMBED_LEN_MASK) || @@ -3650,39 +3650,39 @@ obj_free(rb_objspace_t *objspace, VALUE obj) else { xfree((void *)RANY(obj)->as.rstruct.as.heap.ptr); RB_DEBUG_COUNTER_INC(obj_struct_ptr); - } - break; + } + break; case T_SYMBOL: - { + { rb_gc_free_dsymbol(obj); RB_DEBUG_COUNTER_INC(obj_symbol); - } - break; + } + break; case T_IMEMO: - switch (imemo_type(obj)) { - case imemo_ment: - rb_free_method_entry(&RANY(obj)->as.imemo.ment); + switch (imemo_type(obj)) { + case imemo_ment: + rb_free_method_entry(&RANY(obj)->as.imemo.ment); RB_DEBUG_COUNTER_INC(obj_imemo_ment); - break; - case imemo_iseq: - rb_iseq_free(&RANY(obj)->as.imemo.iseq); + break; + case imemo_iseq: + rb_iseq_free(&RANY(obj)->as.imemo.iseq); RB_DEBUG_COUNTER_INC(obj_imemo_iseq); - break; - case imemo_env: - GC_ASSERT(VM_ENV_ESCAPED_P(RANY(obj)->as.imemo.env.ep)); - xfree((VALUE *)RANY(obj)->as.imemo.env.env); + break; + case imemo_env: + GC_ASSERT(VM_ENV_ESCAPED_P(RANY(obj)->as.imemo.env.ep)); + xfree((VALUE *)RANY(obj)->as.imemo.env.env); RB_DEBUG_COUNTER_INC(obj_imemo_env); - break; - case imemo_tmpbuf: - xfree(RANY(obj)->as.imemo.alloc.ptr); + break; + case imemo_tmpbuf: + xfree(RANY(obj)->as.imemo.alloc.ptr); RB_DEBUG_COUNTER_INC(obj_imemo_tmpbuf); - break; - case imemo_ast: - rb_ast_free(&RANY(obj)->as.imemo.ast); + break; + case imemo_ast: + rb_ast_free(&RANY(obj)->as.imemo.ast); RB_DEBUG_COUNTER_INC(obj_imemo_ast); - break; + break; case imemo_cref: RB_DEBUG_COUNTER_INC(obj_imemo_cref); break; @@ -3710,20 +3710,20 @@ obj_free(rb_objspace_t *objspace, VALUE obj) case imemo_constcache: RB_DEBUG_COUNTER_INC(obj_imemo_constcache); break; - } - return TRUE; + } + return TRUE; default: - rb_bug("gc_sweep(): unknown data type 0x%x(%p) 0x%"PRIxVALUE, - BUILTIN_TYPE(obj), (void*)obj, RBASIC(obj)->flags); + rb_bug("gc_sweep(): unknown data type 0x%x(%p) 0x%"PRIxVALUE, + BUILTIN_TYPE(obj), (void*)obj, RBASIC(obj)->flags); } if (FL_TEST(obj, FL_FINALIZE)) { make_zombie(objspace, obj, 0, 0); - return FALSE; + return FALSE; } else { - return TRUE; + return TRUE; } } @@ -3985,25 +3985,25 @@ internal_object_p(VALUE obj) if (used_p) { switch (BUILTIN_TYPE(obj)) { - case T_NODE: - UNEXPECTED_NODE(internal_object_p); - break; - case T_NONE: + case T_NODE: + UNEXPECTED_NODE(internal_object_p); + break; + case T_NONE: case T_MOVED: - case T_IMEMO: - case T_ICLASS: - case T_ZOMBIE: - break; - case T_CLASS: - if (!p->as.basic.klass) break; - if (FL_TEST(obj, FL_SINGLETON)) { - return rb_singleton_class_internal_p(obj); - } - return 0; - default: - if (!p->as.basic.klass) break; - return 0; - } + case T_IMEMO: + case T_ICLASS: + case T_ZOMBIE: + break; + case T_CLASS: + if (!p->as.basic.klass) break; + if (FL_TEST(obj, FL_SINGLETON)) { + return rb_singleton_class_internal_p(obj); + } + return 0; + default: + if (!p->as.basic.klass) break; + return 0; + } } if (ptr || ! used_p) { asan_poison_object(obj); @@ -4024,14 +4024,14 @@ os_obj_of_i(void *vstart, void *vend, size_t stride, void *data) VALUE v = (VALUE)vstart; for (; v != (VALUE)vend; v += stride) { - if (!internal_object_p(v)) { - if (!oes->of || rb_obj_is_kind_of(v, oes->of)) { + if (!internal_object_p(v)) { + if (!oes->of || rb_obj_is_kind_of(v, oes->of)) { if (!rb_multi_ractor_p() || rb_ractor_shareable_p(v)) { rb_yield(v); oes->num++; } - } - } + } + } } return 0; @@ -4123,8 +4123,8 @@ static void should_be_callable(VALUE block) { if (!rb_obj_respond_to(block, idCall, TRUE)) { - rb_raise(rb_eArgError, "wrong type argument %"PRIsVALUE" (should be callable)", - rb_obj_class(block)); + rb_raise(rb_eArgError, "wrong type argument %"PRIsVALUE" (should be callable)", + rb_obj_class(block)); } } @@ -4132,8 +4132,8 @@ static void should_be_finalizable(VALUE obj) { if (!FL_ABLE(obj)) { - rb_raise(rb_eArgError, "cannot define finalizer for %s", - rb_obj_classname(obj)); + rb_raise(rb_eArgError, "cannot define finalizer for %s", + rb_obj_classname(obj)); } rb_check_frozen(obj); } @@ -4208,10 +4208,10 @@ define_final(int argc, VALUE *argv, VALUE os) rb_scan_args(argc, argv, "11", &obj, &block); should_be_finalizable(obj); if (argc == 1) { - block = rb_block_proc(); + block = rb_block_proc(); } else { - should_be_callable(block); + should_be_callable(block); } if (rb_callable_receiver(block) == obj) { @@ -4231,28 +4231,28 @@ define_final0(VALUE obj, VALUE block) RBASIC(obj)->flags |= FL_FINALIZE; if (st_lookup(finalizer_table, obj, &data)) { - table = (VALUE)data; + table = (VALUE)data; - /* avoid duplicate block, table is usually small */ - { - long len = RARRAY_LEN(table); - long i; + /* avoid duplicate block, table is usually small */ + { + long len = RARRAY_LEN(table); + long i; for (i = 0; i < len; i++) { VALUE recv = RARRAY_AREF(table, i); if (rb_equal(recv, block)) { block = recv; goto end; - } - } - } + } + } + } - rb_ary_push(table, block); + rb_ary_push(table, block); } else { - table = rb_ary_new3(1, block); - RBASIC_CLEAR_CLASS(table); - st_add_direct(finalizer_table, obj, table); + table = rb_ary_new3(1, block); + RBASIC_CLEAR_CLASS(table); + st_add_direct(finalizer_table, obj, table); } end: block = rb_ary_new3(2, INT2FIX(0), block); @@ -4277,8 +4277,8 @@ rb_gc_copy_finalizer(VALUE dest, VALUE obj) if (!FL_TEST(obj, FL_FINALIZE)) return; if (st_lookup(finalizer_table, obj, &data)) { - table = (VALUE)data; - st_insert(finalizer_table, dest, table); + table = (VALUE)data; + st_insert(finalizer_table, dest, table); } FL_SET(dest, FL_FINALIZE); } @@ -4293,9 +4293,9 @@ static void warn_exception_in_finalizer(rb_execution_context_t *ec, VALUE final) { if (final != Qundef && !NIL_P(ruby_verbose)) { - VALUE errinfo = ec->errinfo; - rb_warn("Exception in finalizer %+"PRIsVALUE, final); - rb_ec_error_print(ec, errinfo); + VALUE errinfo = ec->errinfo; + rb_warn("Exception in finalizer %+"PRIsVALUE, final); + rb_ec_error_print(ec, errinfo); } } @@ -4305,16 +4305,16 @@ run_finalizer(rb_objspace_t *objspace, VALUE obj, VALUE table) long i; enum ruby_tag_type state; volatile struct { - VALUE errinfo; - VALUE objid; - VALUE final; - rb_control_frame_t *cfp; - long finished; + VALUE errinfo; + VALUE objid; + VALUE final; + rb_control_frame_t *cfp; + long finished; } saved; rb_execution_context_t * volatile ec = GET_EC(); #define RESTORE_FINALIZER() (\ - ec->cfp = saved.cfp, \ - ec->errinfo = saved.errinfo) + ec->cfp = saved.cfp, \ + ec->errinfo = saved.errinfo) saved.errinfo = ec->errinfo; saved.objid = rb_obj_id(obj); @@ -4325,13 +4325,13 @@ run_finalizer(rb_objspace_t *objspace, VALUE obj, VALUE table) EC_PUSH_TAG(ec); state = EC_EXEC_TAG(); if (state != TAG_NONE) { - ++saved.finished; /* skip failed finalizer */ - warn_exception_in_finalizer(ec, ATOMIC_VALUE_EXCHANGE(saved.final, Qundef)); + ++saved.finished; /* skip failed finalizer */ + warn_exception_in_finalizer(ec, ATOMIC_VALUE_EXCHANGE(saved.final, Qundef)); } for (i = saved.finished; - RESTORE_FINALIZER(), idfree) { - RZOMBIE(zombie)->dfree(RZOMBIE(zombie)->data); + RZOMBIE(zombie)->dfree(RZOMBIE(zombie)->data); } key = (st_data_t)zombie; if (st_delete(finalizer_table, &key, &table)) { - run_finalizer(objspace, zombie, (VALUE)table); + run_finalizer(objspace, zombie, (VALUE)table); } } @@ -4362,7 +4362,7 @@ finalize_list(rb_objspace_t *objspace, VALUE zombie) next_zombie = RZOMBIE(zombie)->next; page = GET_HEAP_PAGE(zombie); - run_final(objspace, zombie); + run_final(objspace, zombie); RB_VM_LOCK_ENTER(); { @@ -4391,7 +4391,7 @@ finalize_deferred_heap_pages(rb_objspace_t *objspace) { VALUE zombie; while ((zombie = ATOMIC_VALUE_EXCHANGE(heap_pages_deferred_final, 0)) != 0) { - finalize_list(objspace, zombie); + finalize_list(objspace, zombie); } } @@ -4418,7 +4418,7 @@ static void gc_finalize_deferred_register(rb_objspace_t *objspace) { if (rb_postponed_job_register_one(0, gc_finalize_deferred, objspace) == 0) { - rb_bug("gc_finalize_deferred_register: can't register finalizer."); + rb_bug("gc_finalize_deferred_register: can't register finalizer."); } } @@ -4464,16 +4464,16 @@ rb_objspace_call_finalizer(rb_objspace_t *objspace) /* force to run finalizer */ while (finalizer_table->num_entries) { - struct force_finalize_list *list = 0; - st_foreach(finalizer_table, force_chain_object, (st_data_t)&list); - while (list) { - struct force_finalize_list *curr = list; - st_data_t obj = (st_data_t)curr->obj; - run_finalizer(objspace, curr->obj, curr->table); - st_delete(finalizer_table, &obj, 0); - list = curr->next; - xfree(curr); - } + struct force_finalize_list *list = 0; + st_foreach(finalizer_table, force_chain_object, (st_data_t)&list); + while (list) { + struct force_finalize_list *curr = list; + st_data_t obj = (st_data_t)curr->obj; + run_finalizer(objspace, curr->obj, curr->table); + st_delete(finalizer_table, &obj, 0); + list = curr->next; + xfree(curr); + } } /* prohibit GC because force T_DATA finalizers can break an object graph consistency */ @@ -4494,36 +4494,36 @@ rb_objspace_call_finalizer(rb_objspace_t *objspace) VALUE vp = (VALUE)p; void *poisoned = asan_unpoison_object_temporary(vp); switch (BUILTIN_TYPE(vp)) { - case T_DATA: - if (!DATA_PTR(p) || !RANY(p)->as.data.dfree) break; + case T_DATA: + if (!DATA_PTR(p) || !RANY(p)->as.data.dfree) break; if (rb_obj_is_thread(vp)) break; if (rb_obj_is_mutex(vp)) break; if (rb_obj_is_fiber(vp)) break; if (rb_obj_is_main_ractor(vp)) break; if (RTYPEDDATA_P(vp)) { - RDATA(p)->dfree = RANY(p)->as.typeddata.type->function.dfree; - } + RDATA(p)->dfree = RANY(p)->as.typeddata.type->function.dfree; + } RANY(p)->as.free.flags = 0; - if (RANY(p)->as.data.dfree == RUBY_DEFAULT_FREE) { - xfree(DATA_PTR(p)); - } - else if (RANY(p)->as.data.dfree) { + if (RANY(p)->as.data.dfree == RUBY_DEFAULT_FREE) { + xfree(DATA_PTR(p)); + } + else if (RANY(p)->as.data.dfree) { make_zombie(objspace, vp, RANY(p)->as.data.dfree, RANY(p)->as.data.data); - } - break; - case T_FILE: - if (RANY(p)->as.file.fptr) { + } + break; + case T_FILE: + if (RANY(p)->as.file.fptr) { make_io_zombie(objspace, vp); - } - break; + } + break; default: break; - } + } if (poisoned) { GC_ASSERT(BUILTIN_TYPE(vp) == T_NONE); asan_poison_object(vp); } - } + } } gc_exit(objspace, gc_enter_event_finalizer, &lock_lev); @@ -4547,13 +4547,13 @@ static inline int is_garbage_object(rb_objspace_t *objspace, VALUE ptr) { if (!is_lazy_sweeping(objspace) || - is_swept_object(objspace, ptr) || - MARKED_IN_BITMAP(GET_HEAP_MARK_BITS(ptr), ptr)) { + is_swept_object(objspace, ptr) || + MARKED_IN_BITMAP(GET_HEAP_MARK_BITS(ptr), ptr)) { - return FALSE; + return FALSE; } else { - return TRUE; + return TRUE; } } @@ -4564,16 +4564,16 @@ is_live_object(rb_objspace_t *objspace, VALUE ptr) case T_NONE: case T_MOVED: case T_ZOMBIE: - return FALSE; + return FALSE; default: break; } if (!is_garbage_object(objspace, ptr)) { - return TRUE; + return TRUE; } else { - return FALSE; + return FALSE; } } @@ -4829,41 +4829,41 @@ obj_memsize_of(VALUE obj, int use_all_types) size_t size = 0; if (SPECIAL_CONST_P(obj)) { - return 0; + return 0; } if (FL_TEST(obj, FL_EXIVAR)) { - size += rb_generic_ivar_memsize(obj); + size += rb_generic_ivar_memsize(obj); } switch (BUILTIN_TYPE(obj)) { case T_OBJECT: - if (!(RBASIC(obj)->flags & ROBJECT_EMBED)) { - size += ROBJECT_NUMIV(obj) * sizeof(VALUE); - } - break; + if (!(RBASIC(obj)->flags & ROBJECT_EMBED)) { + size += ROBJECT_NUMIV(obj) * sizeof(VALUE); + } + break; case T_MODULE: case T_CLASS: - if (RCLASS_EXT(obj)) { + if (RCLASS_EXT(obj)) { if (RCLASS_M_TBL(obj)) { size += rb_id_table_memsize(RCLASS_M_TBL(obj)); } - if (RCLASS_IV_TBL(obj)) { - size += st_memsize(RCLASS_IV_TBL(obj)); - } - if (RCLASS_CVC_TBL(obj)) { - size += rb_id_table_memsize(RCLASS_CVC_TBL(obj)); - } - if (RCLASS_IV_INDEX_TBL(obj)) { + if (RCLASS_IV_TBL(obj)) { + size += st_memsize(RCLASS_IV_TBL(obj)); + } + if (RCLASS_CVC_TBL(obj)) { + size += rb_id_table_memsize(RCLASS_CVC_TBL(obj)); + } + if (RCLASS_IV_INDEX_TBL(obj)) { // TODO: more correct value - size += st_memsize(RCLASS_IV_INDEX_TBL(obj)); - } + size += st_memsize(RCLASS_IV_INDEX_TBL(obj)); + } if (RCLASS_EXT(obj)->iv_tbl) { size += st_memsize(RCLASS_EXT(obj)->iv_tbl); - } + } if (RCLASS_EXT(obj)->const_tbl) { size += rb_id_table_memsize(RCLASS_EXT(obj)->const_tbl); - } + } if (RCLASS_CC_TBL(obj)) { size += cc_table_memsize(RCLASS_CC_TBL(obj)); } @@ -4871,94 +4871,94 @@ obj_memsize_of(VALUE obj, int use_all_types) size += (RCLASS_SUPERCLASS_DEPTH(obj) + 1) * sizeof(VALUE); } #if !USE_RVARGC - size += sizeof(rb_classext_t); + size += sizeof(rb_classext_t); #endif - } - break; + } + break; case T_ICLASS: if (RICLASS_OWNS_M_TBL_P(obj)) { - if (RCLASS_M_TBL(obj)) { - size += rb_id_table_memsize(RCLASS_M_TBL(obj)); - } - } + if (RCLASS_M_TBL(obj)) { + size += rb_id_table_memsize(RCLASS_M_TBL(obj)); + } + } if (RCLASS_EXT(obj) && RCLASS_CC_TBL(obj)) { size += cc_table_memsize(RCLASS_CC_TBL(obj)); } - break; + break; case T_STRING: - size += rb_str_memsize(obj); - break; + size += rb_str_memsize(obj); + break; case T_ARRAY: - size += rb_ary_memsize(obj); - break; + size += rb_ary_memsize(obj); + break; case T_HASH: if (RHASH_AR_TABLE_P(obj)) { if (RHASH_AR_TABLE(obj) != NULL) { size_t rb_hash_ar_table_size(void); size += rb_hash_ar_table_size(); } - } + } else { VM_ASSERT(RHASH_ST_TABLE(obj) != NULL); size += st_memsize(RHASH_ST_TABLE(obj)); } - break; + break; case T_REGEXP: - if (RREGEXP_PTR(obj)) { - size += onig_memsize(RREGEXP_PTR(obj)); - } - break; + if (RREGEXP_PTR(obj)) { + size += onig_memsize(RREGEXP_PTR(obj)); + } + break; case T_DATA: - if (use_all_types) size += rb_objspace_data_type_memsize(obj); - break; + if (use_all_types) size += rb_objspace_data_type_memsize(obj); + break; case T_MATCH: - if (RMATCH(obj)->rmatch) { + if (RMATCH(obj)->rmatch) { struct rmatch *rm = RMATCH(obj)->rmatch; - size += onig_region_memsize(&rm->regs); - size += sizeof(struct rmatch_offset) * rm->char_offset_num_allocated; - size += sizeof(struct rmatch); - } - break; + size += onig_region_memsize(&rm->regs); + size += sizeof(struct rmatch_offset) * rm->char_offset_num_allocated; + size += sizeof(struct rmatch); + } + break; case T_FILE: - if (RFILE(obj)->fptr) { - size += rb_io_memsize(RFILE(obj)->fptr); - } - break; + if (RFILE(obj)->fptr) { + size += rb_io_memsize(RFILE(obj)->fptr); + } + break; case T_RATIONAL: case T_COMPLEX: break; case T_IMEMO: size += imemo_memsize(obj); - break; + break; case T_FLOAT: case T_SYMBOL: - break; + break; case T_BIGNUM: - if (!(RBASIC(obj)->flags & BIGNUM_EMBED_FLAG) && BIGNUM_DIGITS(obj)) { - size += BIGNUM_LEN(obj) * sizeof(BDIGIT); - } - break; + if (!(RBASIC(obj)->flags & BIGNUM_EMBED_FLAG) && BIGNUM_DIGITS(obj)) { + size += BIGNUM_LEN(obj) * sizeof(BDIGIT); + } + break; case T_NODE: - UNEXPECTED_NODE(obj_memsize_of); - break; + UNEXPECTED_NODE(obj_memsize_of); + break; case T_STRUCT: - if ((RBASIC(obj)->flags & RSTRUCT_EMBED_LEN_MASK) == 0 && - RSTRUCT(obj)->as.heap.ptr) { - size += sizeof(VALUE) * RSTRUCT_LEN(obj); - } - break; + if ((RBASIC(obj)->flags & RSTRUCT_EMBED_LEN_MASK) == 0 && + RSTRUCT(obj)->as.heap.ptr) { + size += sizeof(VALUE) * RSTRUCT_LEN(obj); + } + break; case T_ZOMBIE: case T_MOVED: - break; + break; default: - rb_bug("objspace/memsize_of(): unknown data type 0x%x(%p)", - BUILTIN_TYPE(obj), (void*)obj); + rb_bug("objspace/memsize_of(): unknown data type 0x%x(%p)", + BUILTIN_TYPE(obj), (void*)obj); } return size + GET_HEAP_PAGE(obj)->slot_size; @@ -5072,7 +5072,7 @@ count_objects(int argc, VALUE *argv, VALUE os) } for (i = 0; i < heap_allocated_pages; i++) { - struct heap_page *page = heap_pages_sorted[i]; + struct heap_page *page = heap_pages_sorted[i]; short stride = page->slot_size; uintptr_t p = (uintptr_t)page->start; @@ -5084,16 +5084,16 @@ count_objects(int argc, VALUE *argv, VALUE os) void *poisoned = asan_unpoison_object_temporary(vp); if (RANY(p)->as.basic.flags) { counts[BUILTIN_TYPE(vp)]++; - } - else { - freed++; - } + } + else { + freed++; + } if (poisoned) { GC_ASSERT(BUILTIN_TYPE(vp) == T_NONE); asan_poison_object(vp); } - } - total += page->total_slots; + } + total += page->total_slots; } if (NIL_P(hash)) { @@ -5637,15 +5637,15 @@ gc_sweep_page(rb_objspace_t *objspace, rb_heap_t *heap, struct gc_sweep_context #if GC_PROFILE_MORE_DETAIL if (gc_prof_enabled(objspace)) { - gc_profile_record *record = gc_prof_record(objspace); - record->removing_objects += ctx->final_slots + ctx->freed_slots; - record->empty_objects += ctx->empty_slots; + gc_profile_record *record = gc_prof_record(objspace); + record->removing_objects += ctx->final_slots + ctx->freed_slots; + record->empty_objects += ctx->empty_slots; } #endif if (0) fprintf(stderr, "gc_sweep_page(%"PRIdSIZE"): total_slots: %d, freed_slots: %d, empty_slots: %d, final_slots: %d\n", - rb_gc_count(), - sweep_page->total_slots, - ctx->freed_slots, ctx->empty_slots, ctx->final_slots); + rb_gc_count(), + sweep_page->total_slots, + ctx->freed_slots, ctx->empty_slots, ctx->final_slots); sweep_page->free_slots += ctx->freed_slots + ctx->empty_slots; objspace->profile.total_freed_objects += ctx->freed_slots; @@ -5653,7 +5653,7 @@ gc_sweep_page(rb_objspace_t *objspace, rb_heap_t *heap, struct gc_sweep_context if (heap_pages_deferred_final && !finalizing) { rb_thread_t *th = GET_THREAD(); if (th) { - gc_finalize_deferred_register(objspace); + gc_finalize_deferred_register(objspace); } } @@ -5936,41 +5936,41 @@ gc_sweep_step(rb_objspace_t *objspace, rb_size_pool_t *size_pool, rb_heap_t *hea heap->sweeping_page = ccan_list_next(&heap->pages, sweep_page, page_node); - if (sweep_page->final_slots + free_slots == sweep_page->total_slots && - heap_pages_freeable_pages > 0 && - unlink_limit > 0) { - heap_pages_freeable_pages--; - unlink_limit--; - /* there are no living objects -> move this page to tomb heap */ - heap_unlink_page(objspace, heap, sweep_page); - heap_add_page(objspace, size_pool, SIZE_POOL_TOMB_HEAP(size_pool), sweep_page); - } - else if (free_slots > 0) { + if (sweep_page->final_slots + free_slots == sweep_page->total_slots && + heap_pages_freeable_pages > 0 && + unlink_limit > 0) { + heap_pages_freeable_pages--; + unlink_limit--; + /* there are no living objects -> move this page to tomb heap */ + heap_unlink_page(objspace, heap, sweep_page); + heap_add_page(objspace, size_pool, SIZE_POOL_TOMB_HEAP(size_pool), sweep_page); + } + else if (free_slots > 0) { #if USE_RVARGC size_pool->freed_slots += ctx.freed_slots; size_pool->empty_slots += ctx.empty_slots; #endif #if GC_ENABLE_INCREMENTAL_MARK - if (need_pool) { + if (need_pool) { heap_add_poolpage(objspace, heap, sweep_page); need_pool = FALSE; - } - else { + } + else { heap_add_freepage(heap, sweep_page); swept_slots += free_slots; if (swept_slots > GC_INCREMENTAL_SWEEP_SLOT_COUNT) { break; } - } + } #else heap_add_freepage(heap, sweep_page); break; #endif - } - else { - sweep_page->free_next = NULL; - } + } + else { + sweep_page->free_next = NULL; + } } while ((sweep_page = heap->sweeping_page)); if (!heap->sweeping_page) { @@ -6142,11 +6142,11 @@ gc_sweep(rb_objspace_t *objspace) if (immediate_sweep) { #if !GC_ENABLE_LAZY_SWEEP - gc_prof_sweep_timer_start(objspace); + gc_prof_sweep_timer_start(objspace); #endif - gc_sweep_rest(objspace); + gc_sweep_rest(objspace); #if !GC_ENABLE_LAZY_SWEEP - gc_prof_sweep_timer_stop(objspace); + gc_prof_sweep_timer_stop(objspace); #endif } else { @@ -6191,8 +6191,8 @@ mark_stack_size(mark_stack_t *stack) stack_chunk_t *chunk = stack->chunk ? stack->chunk->next : NULL; while (chunk) { - size += stack->limit; - chunk = chunk->next; + size += stack->limit; + chunk = chunk->next; } return size; } @@ -6317,11 +6317,11 @@ push_mark_stack(mark_stack_t *stack, VALUE data) case T_ZOMBIE: case T_UNDEF: case T_MASK: - rb_bug("push_mark_stack() called for broken object"); - break; + rb_bug("push_mark_stack() called for broken object"); + break; case T_NODE: - UNEXPECTED_NODE(push_mark_stack); + UNEXPECTED_NODE(push_mark_stack); break; } @@ -6341,7 +6341,7 @@ pop_mark_stack(mark_stack_t *stack, VALUE *data) pop_mark_stack_chunk(stack); } else { - *data = stack->chunk->data[--stack->index]; + *data = stack->chunk->data[--stack->index]; } return TRUE; } @@ -6374,7 +6374,7 @@ init_mark_stack(mark_stack_t *stack) # define STACK_LENGTH (size_t)(STACK_END - STACK_START + 1) #else # define STACK_LENGTH ((STACK_END < STACK_START) ? (size_t)(STACK_START - STACK_END) \ - : (size_t)(STACK_END - STACK_START + 1)) + : (size_t)(STACK_END - STACK_START + 1)) #endif #if !STACK_GROW_DIRECTION int ruby_stack_grow_direction; @@ -6443,7 +6443,7 @@ each_location(rb_objspace_t *objspace, register const VALUE *x, register long n, while (n--) { v = *x; cb(objspace, v); - x++; + x++; } } @@ -6642,7 +6642,7 @@ mark_method_entry(rb_objspace_t *objspace, const rb_method_entry_t *me) gc_mark(objspace, me->defined_class); if (def) { - switch (def->type) { + switch (def->type) { case VM_METHOD_TYPE_ISEQ: if (def->body.iseq.iseqptr) gc_mark(objspace, (VALUE)def->body.iseq.iseqptr); gc_mark(objspace, (VALUE)def->body.iseq.cref); @@ -6653,29 +6653,29 @@ mark_method_entry(rb_objspace_t *objspace, const rb_method_entry_t *me) gc_mark_and_pin(objspace, (VALUE)me); } break; - case VM_METHOD_TYPE_ATTRSET: - case VM_METHOD_TYPE_IVAR: - gc_mark(objspace, def->body.attr.location); - break; - case VM_METHOD_TYPE_BMETHOD: + case VM_METHOD_TYPE_ATTRSET: + case VM_METHOD_TYPE_IVAR: + gc_mark(objspace, def->body.attr.location); + break; + case VM_METHOD_TYPE_BMETHOD: gc_mark(objspace, def->body.bmethod.proc); if (def->body.bmethod.hooks) rb_hook_list_mark(def->body.bmethod.hooks); - break; - case VM_METHOD_TYPE_ALIAS: - gc_mark(objspace, (VALUE)def->body.alias.original_me); - return; - case VM_METHOD_TYPE_REFINED: - gc_mark(objspace, (VALUE)def->body.refined.orig_me); - gc_mark(objspace, (VALUE)def->body.refined.owner); - break; - case VM_METHOD_TYPE_CFUNC: - case VM_METHOD_TYPE_ZSUPER: - case VM_METHOD_TYPE_MISSING: - case VM_METHOD_TYPE_OPTIMIZED: - case VM_METHOD_TYPE_UNDEF: - case VM_METHOD_TYPE_NOTIMPLEMENTED: - break; - } + break; + case VM_METHOD_TYPE_ALIAS: + gc_mark(objspace, (VALUE)def->body.alias.original_me); + return; + case VM_METHOD_TYPE_REFINED: + gc_mark(objspace, (VALUE)def->body.refined.orig_me); + gc_mark(objspace, (VALUE)def->body.refined.owner); + break; + case VM_METHOD_TYPE_CFUNC: + case VM_METHOD_TYPE_ZSUPER: + case VM_METHOD_TYPE_MISSING: + case VM_METHOD_TYPE_OPTIMIZED: + case VM_METHOD_TYPE_UNDEF: + case VM_METHOD_TYPE_NOTIMPLEMENTED: + break; + } } } @@ -6692,7 +6692,7 @@ static void mark_m_tbl(rb_objspace_t *objspace, struct rb_id_table *tbl) { if (tbl) { - rb_id_table_foreach_values(tbl, mark_method_entry_i, objspace); + rb_id_table_foreach_values(tbl, mark_method_entry_i, objspace); } } @@ -6770,8 +6770,8 @@ static void mark_current_machine_context(rb_objspace_t *objspace, rb_execution_context_t *ec) { union { - rb_jmp_buf j; - VALUE v[sizeof(rb_jmp_buf) / (sizeof(VALUE))]; + rb_jmp_buf j; + VALUE v[sizeof(rb_jmp_buf) / (sizeof(VALUE))]; } save_regs_gc_mark; VALUE *stack_start, *stack_end; @@ -6810,15 +6810,15 @@ rb_gc_mark_machine_stack(const rb_execution_context_t *ec) static void each_stack_location(rb_objspace_t *objspace, const rb_execution_context_t *ec, - const VALUE *stack_start, const VALUE *stack_end, void (*cb)(rb_objspace_t *, VALUE)) + const VALUE *stack_start, const VALUE *stack_end, void (*cb)(rb_objspace_t *, VALUE)) { gc_mark_locations(objspace, stack_start, stack_end, cb); #if defined(__mc68000__) gc_mark_locations(objspace, - (VALUE*)((char*)stack_start + 2), - (VALUE*)((char*)stack_end - 2), cb); + (VALUE*)((char*)stack_start + 2), + (VALUE*)((char*)stack_end - 2), cb); #endif } @@ -6881,20 +6881,20 @@ gc_remember_unprotected(rb_objspace_t *objspace, VALUE obj) bits_t *uncollectible_bits = &page->uncollectible_bits[0]; if (!MARKED_IN_BITMAP(uncollectible_bits, obj)) { - page->flags.has_uncollectible_shady_objects = TRUE; - MARK_IN_BITMAP(uncollectible_bits, obj); - objspace->rgengc.uncollectible_wb_unprotected_objects++; + page->flags.has_uncollectible_shady_objects = TRUE; + MARK_IN_BITMAP(uncollectible_bits, obj); + objspace->rgengc.uncollectible_wb_unprotected_objects++; #if RGENGC_PROFILE > 0 - objspace->profile.total_remembered_shady_object_count++; + objspace->profile.total_remembered_shady_object_count++; #if RGENGC_PROFILE >= 2 - objspace->profile.remembered_shady_object_count_types[BUILTIN_TYPE(obj)]++; + objspace->profile.remembered_shady_object_count_types[BUILTIN_TYPE(obj)]++; #endif #endif - return TRUE; + return TRUE; } else { - return FALSE; + return FALSE; } } @@ -6904,32 +6904,32 @@ rgengc_check_relation(rb_objspace_t *objspace, VALUE obj) const VALUE old_parent = objspace->rgengc.parent_object; if (old_parent) { /* parent object is old */ - if (RVALUE_WB_UNPROTECTED(obj)) { - if (gc_remember_unprotected(objspace, obj)) { - gc_report(2, objspace, "relation: (O->S) %s -> %s\n", obj_info(old_parent), obj_info(obj)); - } - } - else { - if (!RVALUE_OLD_P(obj)) { - if (RVALUE_MARKED(obj)) { - /* An object pointed from an OLD object should be OLD. */ - gc_report(2, objspace, "relation: (O->unmarked Y) %s -> %s\n", obj_info(old_parent), obj_info(obj)); - RVALUE_AGE_SET_OLD(objspace, obj); - if (is_incremental_marking(objspace)) { - if (!RVALUE_MARKING(obj)) { - gc_grey(objspace, obj); - } - } - else { - rgengc_remember(objspace, obj); - } - } - else { - gc_report(2, objspace, "relation: (O->Y) %s -> %s\n", obj_info(old_parent), obj_info(obj)); - RVALUE_AGE_SET_CANDIDATE(objspace, obj); - } - } - } + if (RVALUE_WB_UNPROTECTED(obj)) { + if (gc_remember_unprotected(objspace, obj)) { + gc_report(2, objspace, "relation: (O->S) %s -> %s\n", obj_info(old_parent), obj_info(obj)); + } + } + else { + if (!RVALUE_OLD_P(obj)) { + if (RVALUE_MARKED(obj)) { + /* An object pointed from an OLD object should be OLD. */ + gc_report(2, objspace, "relation: (O->unmarked Y) %s -> %s\n", obj_info(old_parent), obj_info(obj)); + RVALUE_AGE_SET_OLD(objspace, obj); + if (is_incremental_marking(objspace)) { + if (!RVALUE_MARKING(obj)) { + gc_grey(objspace, obj); + } + } + else { + rgengc_remember(objspace, obj); + } + } + else { + gc_report(2, objspace, "relation: (O->Y) %s -> %s\n", obj_info(old_parent), obj_info(obj)); + RVALUE_AGE_SET_CANDIDATE(objspace, obj); + } + } + } } GC_ASSERT(old_parent == objspace->rgengc.parent_object); @@ -6945,7 +6945,7 @@ gc_grey(rb_objspace_t *objspace, VALUE obj) #if GC_ENABLE_INCREMENTAL_MARK if (is_incremental_marking(objspace)) { - MARK_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj); + MARK_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj); } #endif @@ -6961,14 +6961,14 @@ gc_aging(rb_objspace_t *objspace, VALUE obj) check_rvalue_consistency(obj); if (!RVALUE_PAGE_WB_UNPROTECTED(page, obj)) { - if (!RVALUE_OLD_P(obj)) { - gc_report(3, objspace, "gc_aging: YOUNG: %s\n", obj_info(obj)); - RVALUE_AGE_INC(objspace, obj); - } - else if (is_full_marking(objspace)) { - GC_ASSERT(RVALUE_PAGE_UNCOLLECTIBLE(page, obj) == FALSE); - RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET(objspace, page, obj); - } + if (!RVALUE_OLD_P(obj)) { + gc_report(3, objspace, "gc_aging: YOUNG: %s\n", obj_info(obj)); + RVALUE_AGE_INC(objspace, obj); + } + else if (is_full_marking(objspace)) { + GC_ASSERT(RVALUE_PAGE_UNCOLLECTIBLE(page, obj) == FALSE); + RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET(objspace, page, obj); + } } check_rvalue_consistency(obj); @@ -6982,8 +6982,8 @@ static void gc_mark_ptr(rb_objspace_t *objspace, VALUE obj) { if (LIKELY(during_gc)) { - rgengc_check_relation(objspace, obj); - if (!gc_mark_set(objspace, obj)) return; /* already marked */ + rgengc_check_relation(objspace, obj); + if (!gc_mark_set(objspace, obj)) return; /* already marked */ if (0) { // for debug GC marking miss if (objspace->rgengc.parent_object) { @@ -7000,8 +7000,8 @@ gc_mark_ptr(rb_objspace_t *objspace, VALUE obj) rp(obj); rb_bug("try to mark T_NONE object"); /* check here will help debugging */ } - gc_aging(objspace, obj); - gc_grey(objspace, obj); + gc_aging(objspace, obj); + gc_grey(objspace, obj); } else { reachable_objects_from_callback(obj); @@ -7060,10 +7060,10 @@ static inline void gc_mark_set_parent(rb_objspace_t *objspace, VALUE obj) { if (RVALUE_OLD_P(obj)) { - objspace->rgengc.parent_object = obj; + objspace->rgengc.parent_object = obj; } else { - objspace->rgengc.parent_object = Qfalse; + objspace->rgengc.parent_object = Qfalse; } } @@ -7072,8 +7072,8 @@ gc_mark_imemo(rb_objspace_t *objspace, VALUE obj) { switch (imemo_type(obj)) { case imemo_env: - { - const rb_env_t *env = (const rb_env_t *)obj; + { + const rb_env_t *env = (const rb_env_t *)obj; if (LIKELY(env->ep)) { // just after newobj() can be NULL here. @@ -7084,50 +7084,50 @@ gc_mark_imemo(rb_objspace_t *objspace, VALUE obj) gc_mark(objspace, (VALUE)rb_vm_env_prev_env(env)); gc_mark(objspace, (VALUE)env->iseq); } - } - return; + } + return; case imemo_cref: - gc_mark(objspace, RANY(obj)->as.imemo.cref.klass_or_self); - gc_mark(objspace, (VALUE)RANY(obj)->as.imemo.cref.next); - gc_mark(objspace, RANY(obj)->as.imemo.cref.refinements); - return; + gc_mark(objspace, RANY(obj)->as.imemo.cref.klass_or_self); + gc_mark(objspace, (VALUE)RANY(obj)->as.imemo.cref.next); + gc_mark(objspace, RANY(obj)->as.imemo.cref.refinements); + return; case imemo_svar: - gc_mark(objspace, RANY(obj)->as.imemo.svar.cref_or_me); - gc_mark(objspace, RANY(obj)->as.imemo.svar.lastline); - gc_mark(objspace, RANY(obj)->as.imemo.svar.backref); - gc_mark(objspace, RANY(obj)->as.imemo.svar.others); - return; + gc_mark(objspace, RANY(obj)->as.imemo.svar.cref_or_me); + gc_mark(objspace, RANY(obj)->as.imemo.svar.lastline); + gc_mark(objspace, RANY(obj)->as.imemo.svar.backref); + gc_mark(objspace, RANY(obj)->as.imemo.svar.others); + return; case imemo_throw_data: - gc_mark(objspace, RANY(obj)->as.imemo.throw_data.throw_obj); - return; + gc_mark(objspace, RANY(obj)->as.imemo.throw_data.throw_obj); + return; case imemo_ifunc: - gc_mark_maybe(objspace, (VALUE)RANY(obj)->as.imemo.ifunc.data); - return; + gc_mark_maybe(objspace, (VALUE)RANY(obj)->as.imemo.ifunc.data); + return; case imemo_memo: - gc_mark(objspace, RANY(obj)->as.imemo.memo.v1); - gc_mark(objspace, RANY(obj)->as.imemo.memo.v2); - gc_mark_maybe(objspace, RANY(obj)->as.imemo.memo.u3.value); - return; + gc_mark(objspace, RANY(obj)->as.imemo.memo.v1); + gc_mark(objspace, RANY(obj)->as.imemo.memo.v2); + gc_mark_maybe(objspace, RANY(obj)->as.imemo.memo.u3.value); + return; case imemo_ment: - mark_method_entry(objspace, &RANY(obj)->as.imemo.ment); - return; + mark_method_entry(objspace, &RANY(obj)->as.imemo.ment); + return; case imemo_iseq: - rb_iseq_mark((rb_iseq_t *)obj); - return; + rb_iseq_mark((rb_iseq_t *)obj); + return; case imemo_tmpbuf: - { - const rb_imemo_tmpbuf_t *m = &RANY(obj)->as.imemo.alloc; - do { - rb_gc_mark_locations(m->ptr, m->ptr + m->cnt); - } while ((m = m->next) != NULL); - } - return; + { + const rb_imemo_tmpbuf_t *m = &RANY(obj)->as.imemo.alloc; + do { + rb_gc_mark_locations(m->ptr, m->ptr + m->cnt); + } while ((m = m->next) != NULL); + } + return; case imemo_ast: - rb_ast_mark(&RANY(obj)->as.imemo.ast); - return; + rb_ast_mark(&RANY(obj)->as.imemo.ast); + return; case imemo_parser_strterm: - rb_strterm_mark(obj); - return; + rb_strterm_mark(obj); + return; case imemo_callinfo: return; case imemo_callcache: @@ -7145,7 +7145,7 @@ gc_mark_imemo(rb_objspace_t *objspace, VALUE obj) return; #if VM_CHECK_MODE > 0 default: - VM_UNREACHABLE(gc_mark_imemo); + VM_UNREACHABLE(gc_mark_imemo); #endif } } @@ -7157,7 +7157,7 @@ gc_mark_children(rb_objspace_t *objspace, VALUE obj) gc_mark_set_parent(objspace, obj); if (FL_TEST(obj, FL_EXIVAR)) { - rb_mark_generic_ivar(obj); + rb_mark_generic_ivar(obj); } switch (BUILTIN_TYPE(obj)) { @@ -7170,16 +7170,16 @@ gc_mark_children(rb_objspace_t *objspace, VALUE obj) case T_NIL: case T_FIXNUM: - rb_bug("rb_gc_mark() called for broken object"); - break; + rb_bug("rb_gc_mark() called for broken object"); + break; case T_NODE: - UNEXPECTED_NODE(rb_gc_mark); - break; + UNEXPECTED_NODE(rb_gc_mark); + break; case T_IMEMO: - gc_mark_imemo(objspace, obj); - return; + gc_mark_imemo(objspace, obj); + return; default: break; @@ -7193,41 +7193,41 @@ gc_mark_children(rb_objspace_t *objspace, VALUE obj) if (RCLASS_SUPER(obj)) { gc_mark(objspace, RCLASS_SUPER(obj)); } - if (!RCLASS_EXT(obj)) break; + if (!RCLASS_EXT(obj)) break; mark_m_tbl(objspace, RCLASS_M_TBL(obj)); cc_table_mark(objspace, obj); mark_tbl_no_pin(objspace, RCLASS_IV_TBL(obj)); - mark_const_tbl(objspace, RCLASS_CONST_TBL(obj)); - break; + mark_const_tbl(objspace, RCLASS_CONST_TBL(obj)); + break; case T_ICLASS: if (RICLASS_OWNS_M_TBL_P(obj)) { - mark_m_tbl(objspace, RCLASS_M_TBL(obj)); - } + mark_m_tbl(objspace, RCLASS_M_TBL(obj)); + } if (RCLASS_SUPER(obj)) { gc_mark(objspace, RCLASS_SUPER(obj)); } - if (!RCLASS_EXT(obj)) break; + if (!RCLASS_EXT(obj)) break; if (RCLASS_INCLUDER(obj)) { gc_mark(objspace, RCLASS_INCLUDER(obj)); } - mark_m_tbl(objspace, RCLASS_CALLABLE_M_TBL(obj)); + mark_m_tbl(objspace, RCLASS_CALLABLE_M_TBL(obj)); cc_table_mark(objspace, obj); - break; + break; case T_ARRAY: if (ARY_SHARED_P(obj)) { VALUE root = ARY_SHARED_ROOT(obj); gc_mark(objspace, root); } - else { - long i, len = RARRAY_LEN(obj); + else { + long i, len = RARRAY_LEN(obj); const VALUE *ptr = RARRAY_CONST_PTR_TRANSIENT(obj); - for (i=0; i < len; i++) { + for (i=0; i < len; i++) { gc_mark(objspace, ptr[i]); - } + } if (LIKELY(during_gc)) { if (!ARY_EMBED_P(obj) && RARRAY_TRANSIENT_P(obj)) { @@ -7235,29 +7235,29 @@ gc_mark_children(rb_objspace_t *objspace, VALUE obj) } } } - break; + break; case T_HASH: mark_hash(objspace, obj); - break; + break; case T_STRING: - if (STR_SHARED_P(obj)) { - gc_mark(objspace, any->as.string.as.heap.aux.shared); - } - break; + if (STR_SHARED_P(obj)) { + gc_mark(objspace, any->as.string.as.heap.aux.shared); + } + break; case T_DATA: - { - void *const ptr = DATA_PTR(obj); - if (ptr) { - RUBY_DATA_FUNC mark_func = RTYPEDDATA_P(obj) ? - any->as.typeddata.type->function.dmark : - any->as.data.dmark; - if (mark_func) (*mark_func)(ptr); - } - } - break; + { + void *const ptr = DATA_PTR(obj); + if (ptr) { + RUBY_DATA_FUNC mark_func = RTYPEDDATA_P(obj) ? + any->as.typeddata.type->function.dmark : + any->as.data.dmark; + if (mark_func) (*mark_func)(ptr); + } + } + break; case T_OBJECT: { @@ -7273,7 +7273,7 @@ gc_mark_children(rb_objspace_t *objspace, VALUE obj) rb_transient_heap_mark(obj, ptr); } } - break; + break; case T_FILE: if (any->as.file.fptr) { @@ -7289,27 +7289,27 @@ gc_mark_children(rb_objspace_t *objspace, VALUE obj) case T_REGEXP: gc_mark(objspace, any->as.regexp.src); - break; + break; case T_MATCH: - gc_mark(objspace, any->as.match.regexp); - if (any->as.match.str) { - gc_mark(objspace, any->as.match.str); - } - break; + gc_mark(objspace, any->as.match.regexp); + if (any->as.match.str) { + gc_mark(objspace, any->as.match.str); + } + break; case T_RATIONAL: - gc_mark(objspace, any->as.rational.num); - gc_mark(objspace, any->as.rational.den); - break; + gc_mark(objspace, any->as.rational.num); + gc_mark(objspace, any->as.rational.den); + break; case T_COMPLEX: - gc_mark(objspace, any->as.complex.real); - gc_mark(objspace, any->as.complex.imag); - break; + gc_mark(objspace, any->as.complex.real); + gc_mark(objspace, any->as.complex.imag); + break; case T_STRUCT: - { + { long i; const long len = RSTRUCT_LEN(obj); const VALUE * const ptr = RSTRUCT_CONST_PTR(obj); @@ -7322,19 +7322,19 @@ gc_mark_children(rb_objspace_t *objspace, VALUE obj) RSTRUCT_TRANSIENT_P(obj)) { rb_transient_heap_mark(obj, ptr); } - } - break; + } + break; default: #if GC_DEBUG - rb_gcdebug_print_obj_condition((VALUE)obj); + rb_gcdebug_print_obj_condition((VALUE)obj); #endif if (BUILTIN_TYPE(obj) == T_MOVED) rb_bug("rb_gc_mark(): %p is T_MOVED", (void *)obj); - if (BUILTIN_TYPE(obj) == T_NONE) rb_bug("rb_gc_mark(): %p is T_NONE", (void *)obj); - if (BUILTIN_TYPE(obj) == T_ZOMBIE) rb_bug("rb_gc_mark(): %p is T_ZOMBIE", (void *)obj); - rb_bug("rb_gc_mark(): unknown data type 0x%x(%p) %s", - BUILTIN_TYPE(obj), (void *)any, - is_pointer_to_heap(objspace, any) ? "corrupted object" : "non object"); + if (BUILTIN_TYPE(obj) == T_NONE) rb_bug("rb_gc_mark(): %p is T_NONE", (void *)obj); + if (BUILTIN_TYPE(obj) == T_ZOMBIE) rb_bug("rb_gc_mark(): %p is T_ZOMBIE", (void *)obj); + rb_bug("rb_gc_mark(): unknown data type 0x%x(%p) %s", + BUILTIN_TYPE(obj), (void *)any, + is_pointer_to_heap(objspace, any) ? "corrupted object" : "non object"); } } @@ -7353,39 +7353,39 @@ gc_mark_stacked_objects(rb_objspace_t *objspace, int incremental, size_t count) #endif while (pop_mark_stack(mstack, &obj)) { - if (obj == Qundef) continue; /* skip */ + if (obj == Qundef) continue; /* skip */ - if (RGENGC_CHECK_MODE && !RVALUE_MARKED(obj)) { - rb_bug("gc_mark_stacked_objects: %s is not marked.", obj_info(obj)); - } + if (RGENGC_CHECK_MODE && !RVALUE_MARKED(obj)) { + rb_bug("gc_mark_stacked_objects: %s is not marked.", obj_info(obj)); + } gc_mark_children(objspace, obj); #if GC_ENABLE_INCREMENTAL_MARK - if (incremental) { - if (RGENGC_CHECK_MODE && !RVALUE_MARKING(obj)) { - rb_bug("gc_mark_stacked_objects: incremental, but marking bit is 0"); - } - CLEAR_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj); - popped_count++; + if (incremental) { + if (RGENGC_CHECK_MODE && !RVALUE_MARKING(obj)) { + rb_bug("gc_mark_stacked_objects: incremental, but marking bit is 0"); + } + CLEAR_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj); + popped_count++; - if (popped_count + (objspace->marked_slots - marked_slots_at_the_beginning) > count) { - break; - } - } - else { - /* just ignore marking bits */ - } + if (popped_count + (objspace->marked_slots - marked_slots_at_the_beginning) > count) { + break; + } + } + else { + /* just ignore marking bits */ + } #endif } if (RGENGC_CHECK_MODE >= 3) gc_verify_internal_consistency(objspace); if (is_mark_stack_empty(mstack)) { - shrink_stack_chunk_cache(mstack); - return TRUE; + shrink_stack_chunk_cache(mstack); + return TRUE; } else { - return FALSE; + return FALSE; } } @@ -7412,13 +7412,13 @@ show_mark_ticks(void) int i; fprintf(stderr, "mark ticks result:\n"); for (i=0; ipos == refs->size) { - refs->size *= 2; - SIZED_REALLOC_N(refs->list, VALUE, refs->size, refs->size/2); + refs->size *= 2; + SIZED_REALLOC_N(refs->list, VALUE, refs->size, refs->size/2); } refs->list[refs->pos++] = obj; @@ -7544,14 +7544,14 @@ reflist_dump(struct reflist *refs) { int i; for (i=0; ipos; i++) { - VALUE obj = refs->list[i]; - if (IS_ROOTSIG(obj)) { /* root */ - fprintf(stderr, "", GET_ROOTSIG(obj)); - } - else { - fprintf(stderr, "<%s>", obj_info(obj)); - } - if (i+1 < refs->pos) fprintf(stderr, ", "); + VALUE obj = refs->list[i]; + if (IS_ROOTSIG(obj)) { /* root */ + fprintf(stderr, "", GET_ROOTSIG(obj)); + } + else { + fprintf(stderr, "<%s>", obj_info(obj)); + } + if (i+1 < refs->pos) fprintf(stderr, ", "); } } @@ -7560,8 +7560,8 @@ reflist_referred_from_machine_context(struct reflist *refs) { int i; for (i=0; ipos; i++) { - VALUE obj = refs->list[i]; - if (IS_ROOTSIG(obj) && strcmp(GET_ROOTSIG(obj), "machine_context") == 0) return 1; + VALUE obj = refs->list[i]; + if (IS_ROOTSIG(obj) && strcmp(GET_ROOTSIG(obj), "machine_context") == 0) return 1; } return 0; } @@ -7589,13 +7589,13 @@ allrefs_add(struct allrefs *data, VALUE obj) if (st_lookup(data->references, obj, &r)) { refs = (struct reflist *)r; - reflist_add(refs, data->root_obj); - return 0; + reflist_add(refs, data->root_obj); + return 0; } else { - refs = reflist_create(data->root_obj); - st_insert(data->references, obj, (st_data_t)refs); - return 1; + refs = reflist_create(data->root_obj); + st_insert(data->references, obj, (st_data_t)refs); + return 1; } } @@ -7605,7 +7605,7 @@ allrefs_i(VALUE obj, void *ptr) struct allrefs *data = (struct allrefs *)ptr; if (allrefs_add(data, obj)) { - push_mark_stack(&data->mark_stack, obj); + push_mark_stack(&data->mark_stack, obj); } } @@ -7617,7 +7617,7 @@ allrefs_roots_i(VALUE obj, void *ptr) data->root_obj = MAKE_ROOTSIG(data->category); if (allrefs_add(data, obj)) { - push_mark_stack(&data->mark_stack, obj); + push_mark_stack(&data->mark_stack, obj); } } #define PUSH_MARK_FUNC_DATA(v) do { \ @@ -7650,7 +7650,7 @@ objspace_allrefs(rb_objspace_t *objspace) /* traverse rest objects reachable from root objects */ while (pop_mark_stack(&data.mark_stack, &obj)) { - rb_objspace_reachable_objects_from(data.root_obj = obj, allrefs_i, &data); + rb_objspace_reachable_objects_from(data.root_obj = obj, allrefs_i, &data); } free_stack_chunks(&data.mark_stack); @@ -7703,18 +7703,18 @@ gc_check_after_marks_i(st_data_t k, st_data_t v, st_data_t ptr) /* object should be marked or oldgen */ if (!MARKED_IN_BITMAP(GET_HEAP_MARK_BITS(obj), obj)) { - fprintf(stderr, "gc_check_after_marks_i: %s is not marked and not oldgen.\n", obj_info(obj)); - fprintf(stderr, "gc_check_after_marks_i: %p is referred from ", (void *)obj); - reflist_dump(refs); + fprintf(stderr, "gc_check_after_marks_i: %s is not marked and not oldgen.\n", obj_info(obj)); + fprintf(stderr, "gc_check_after_marks_i: %p is referred from ", (void *)obj); + reflist_dump(refs); - if (reflist_referred_from_machine_context(refs)) { - fprintf(stderr, " (marked from machine stack).\n"); - /* marked from machine context can be false positive */ - } - else { - objspace->rgengc.error_count++; - fprintf(stderr, "\n"); - } + if (reflist_referred_from_machine_context(refs)) { + fprintf(stderr, " (marked from machine stack).\n"); + /* marked from machine context can be false positive */ + } + else { + objspace->rgengc.error_count++; + fprintf(stderr, "\n"); + } } return ST_CONTINUE; } @@ -7731,14 +7731,14 @@ gc_marks_check(rb_objspace_t *objspace, st_foreach_callback_func *checker_func, objspace->rgengc.allrefs_table = objspace_allrefs(objspace); if (checker_func) { - st_foreach(objspace->rgengc.allrefs_table, checker_func, (st_data_t)objspace); + st_foreach(objspace->rgengc.allrefs_table, checker_func, (st_data_t)objspace); } if (objspace->rgengc.error_count > 0) { #if RGENGC_CHECK_MODE >= 5 - allrefs_dump(objspace); + allrefs_dump(objspace); #endif - if (checker_name) rb_bug("%s: GC has problem.", checker_name); + if (checker_name) rb_bug("%s: GC has problem.", checker_name); } objspace_allrefs_destruct(objspace->rgengc.allrefs_table); @@ -7772,12 +7772,12 @@ check_generation_i(const VALUE child, void *ptr) if (RGENGC_CHECK_MODE) GC_ASSERT(RVALUE_OLD_P(parent)); if (!RVALUE_OLD_P(child)) { - if (!RVALUE_REMEMBERED(parent) && - !RVALUE_REMEMBERED(child) && - !RVALUE_UNCOLLECTIBLE(child)) { - fprintf(stderr, "verify_internal_consistency_reachable_i: WB miss (O->Y) %s -> %s\n", obj_info(parent), obj_info(child)); - data->err_count++; - } + if (!RVALUE_REMEMBERED(parent) && + !RVALUE_REMEMBERED(child) && + !RVALUE_UNCOLLECTIBLE(child)) { + fprintf(stderr, "verify_internal_consistency_reachable_i: WB miss (O->Y) %s -> %s\n", obj_info(parent), obj_info(child)); + data->err_count++; + } } } @@ -7788,9 +7788,9 @@ check_color_i(const VALUE child, void *ptr) const VALUE parent = data->parent; if (!RVALUE_WB_UNPROTECTED(parent) && RVALUE_WHITE_P(child)) { - fprintf(stderr, "verify_internal_consistency_reachable_i: WB miss (B->W) - %s -> %s\n", - obj_info(parent), obj_info(child)); - data->err_count++; + fprintf(stderr, "verify_internal_consistency_reachable_i: WB miss (B->W) - %s -> %s\n", + obj_info(parent), obj_info(child)); + data->err_count++; } } @@ -7817,9 +7817,9 @@ verify_internal_consistency_i(void *page_start, void *page_end, size_t stride, for (obj = (VALUE)page_start; obj != (VALUE)page_end; obj += stride) { void *poisoned = asan_unpoison_object_temporary(obj); - if (is_live_object(objspace, obj)) { - /* count objects */ - data->live_object_count++; + if (is_live_object(objspace, obj)) { + /* count objects */ + data->live_object_count++; data->parent = obj; /* Normally, we don't expect T_MOVED objects to be in the heap. @@ -7829,30 +7829,30 @@ verify_internal_consistency_i(void *page_start, void *page_end, size_t stride, rb_objspace_reachable_objects_from(obj, check_children_i, (void *)data); } - /* check health of children */ - if (RVALUE_OLD_P(obj)) data->old_object_count++; - if (RVALUE_WB_UNPROTECTED(obj) && RVALUE_UNCOLLECTIBLE(obj)) data->remembered_shady_count++; + /* check health of children */ + if (RVALUE_OLD_P(obj)) data->old_object_count++; + if (RVALUE_WB_UNPROTECTED(obj) && RVALUE_UNCOLLECTIBLE(obj)) data->remembered_shady_count++; - if (!is_marking(objspace) && RVALUE_OLD_P(obj)) { - /* reachable objects from an oldgen object should be old or (young with remember) */ - data->parent = obj; - rb_objspace_reachable_objects_from(obj, check_generation_i, (void *)data); - } + if (!is_marking(objspace) && RVALUE_OLD_P(obj)) { + /* reachable objects from an oldgen object should be old or (young with remember) */ + data->parent = obj; + rb_objspace_reachable_objects_from(obj, check_generation_i, (void *)data); + } - if (is_incremental_marking(objspace)) { - if (RVALUE_BLACK_P(obj)) { - /* reachable objects from black objects should be black or grey objects */ - data->parent = obj; - rb_objspace_reachable_objects_from(obj, check_color_i, (void *)data); - } - } - } - else { - if (BUILTIN_TYPE(obj) == T_ZOMBIE) { - GC_ASSERT((RBASIC(obj)->flags & ~FL_SEEN_OBJ_ID) == T_ZOMBIE); - data->zombie_object_count++; - } - } + if (is_incremental_marking(objspace)) { + if (RVALUE_BLACK_P(obj)) { + /* reachable objects from black objects should be black or grey objects */ + data->parent = obj; + rb_objspace_reachable_objects_from(obj, check_color_i, (void *)data); + } + } + } + else { + if (BUILTIN_TYPE(obj) == T_ZOMBIE) { + GC_ASSERT((RBASIC(obj)->flags & ~FL_SEEN_OBJ_ID) == T_ZOMBIE); + data->zombie_object_count++; + } + } if (poisoned) { GC_ASSERT(BUILTIN_TYPE(obj) == T_NONE); asan_poison_object(obj); @@ -7880,15 +7880,15 @@ gc_verify_heap_page(rb_objspace_t *objspace, struct heap_page *page, VALUE obj) void *poisoned = asan_unpoison_object_temporary(val); enum ruby_value_type type = BUILTIN_TYPE(val); - if (type == T_NONE) free_objects++; - if (type == T_ZOMBIE) zombie_objects++; - if (RVALUE_PAGE_UNCOLLECTIBLE(page, val) && RVALUE_PAGE_WB_UNPROTECTED(page, val)) { - has_remembered_shady = TRUE; - } - if (RVALUE_PAGE_MARKING(page, val)) { - has_remembered_old = TRUE; - remembered_old_objects++; - } + if (type == T_NONE) free_objects++; + if (type == T_ZOMBIE) zombie_objects++; + if (RVALUE_PAGE_UNCOLLECTIBLE(page, val) && RVALUE_PAGE_WB_UNPROTECTED(page, val)) { + has_remembered_shady = TRUE; + } + if (RVALUE_PAGE_MARKING(page, val)) { + has_remembered_old = TRUE; + remembered_old_objects++; + } if (poisoned) { GC_ASSERT(BUILTIN_TYPE(val) == T_NONE); @@ -7897,31 +7897,31 @@ gc_verify_heap_page(rb_objspace_t *objspace, struct heap_page *page, VALUE obj) } if (!is_incremental_marking(objspace) && - page->flags.has_remembered_objects == FALSE && has_remembered_old == TRUE) { + page->flags.has_remembered_objects == FALSE && has_remembered_old == TRUE) { for (uintptr_t ptr = start; ptr < end; ptr += slot_size) { VALUE val = (VALUE)ptr; - if (RVALUE_PAGE_MARKING(page, val)) { - fprintf(stderr, "marking -> %s\n", obj_info(val)); - } - } - rb_bug("page %p's has_remembered_objects should be false, but there are remembered old objects (%d). %s", - (void *)page, remembered_old_objects, obj ? obj_info(obj) : ""); + if (RVALUE_PAGE_MARKING(page, val)) { + fprintf(stderr, "marking -> %s\n", obj_info(val)); + } + } + rb_bug("page %p's has_remembered_objects should be false, but there are remembered old objects (%d). %s", + (void *)page, remembered_old_objects, obj ? obj_info(obj) : ""); } if (page->flags.has_uncollectible_shady_objects == FALSE && has_remembered_shady == TRUE) { - rb_bug("page %p's has_remembered_shady should be false, but there are remembered shady objects. %s", - (void *)page, obj ? obj_info(obj) : ""); + rb_bug("page %p's has_remembered_shady should be false, but there are remembered shady objects. %s", + (void *)page, obj ? obj_info(obj) : ""); } if (0) { - /* free_slots may not equal to free_objects */ - if (page->free_slots != free_objects) { - rb_bug("page %p's free_slots should be %d, but %d\n", (void *)page, page->free_slots, free_objects); - } + /* free_slots may not equal to free_objects */ + if (page->free_slots != free_objects) { + rb_bug("page %p's free_slots should be %d, but %d\n", (void *)page, page->free_slots, free_objects); + } } if (page->final_slots != zombie_objects) { - rb_bug("page %p's final_slots should be %d, but %d\n", (void *)page, page->final_slots, zombie_objects); + rb_bug("page %p's final_slots should be %d, but %d\n", (void *)page, page->final_slots, zombie_objects); } return remembered_old_objects; @@ -7948,9 +7948,9 @@ gc_verify_heap_pages_(rb_objspace_t *objspace, struct ccan_list_head *head) } asan_poison_memory_region(&page->freelist, sizeof(RVALUE*)); - if (page->flags.has_remembered_objects == FALSE) { - remembered_old_objects += gc_verify_heap_page(objspace, page, Qfalse); - } + if (page->flags.has_remembered_objects == FALSE) { + remembered_old_objects += gc_verify_heap_page(objspace, page, Qfalse); + } } return remembered_old_objects; @@ -8005,11 +8005,11 @@ gc_verify_internal_consistency_(rb_objspace_t *objspace) if (data.err_count != 0) { #if RGENGC_CHECK_MODE >= 5 - objspace->rgengc.error_count = data.err_count; - gc_marks_check(objspace, NULL, NULL); - allrefs_dump(objspace); + objspace->rgengc.error_count = data.err_count; + gc_marks_check(objspace, NULL, NULL); + allrefs_dump(objspace); #endif - rb_bug("gc_verify_internal_consistency: found internal inconsistency."); + rb_bug("gc_verify_internal_consistency: found internal inconsistency."); } /* check heap_page status */ @@ -8020,39 +8020,39 @@ gc_verify_internal_consistency_(rb_objspace_t *objspace) if (!is_lazy_sweeping(objspace) && !finalizing && ruby_single_main_ractor != NULL) { - if (objspace_live_slots(objspace) != data.live_object_count) { - fprintf(stderr, "heap_pages_final_slots: %"PRIdSIZE", " + if (objspace_live_slots(objspace) != data.live_object_count) { + fprintf(stderr, "heap_pages_final_slots: %"PRIdSIZE", " "objspace->profile.total_freed_objects: %"PRIdSIZE"\n", - heap_pages_final_slots, objspace->profile.total_freed_objects); - rb_bug("inconsistent live slot number: expect %"PRIuSIZE", but %"PRIuSIZE".", + heap_pages_final_slots, objspace->profile.total_freed_objects); + rb_bug("inconsistent live slot number: expect %"PRIuSIZE", but %"PRIuSIZE".", objspace_live_slots(objspace), data.live_object_count); - } + } } if (!is_marking(objspace)) { - if (objspace->rgengc.old_objects != data.old_object_count) { - rb_bug("inconsistent old slot number: expect %"PRIuSIZE", but %"PRIuSIZE".", + if (objspace->rgengc.old_objects != data.old_object_count) { + rb_bug("inconsistent old slot number: expect %"PRIuSIZE", but %"PRIuSIZE".", objspace->rgengc.old_objects, data.old_object_count); - } - if (objspace->rgengc.uncollectible_wb_unprotected_objects != data.remembered_shady_count) { + } + if (objspace->rgengc.uncollectible_wb_unprotected_objects != data.remembered_shady_count) { rb_bug("inconsistent number of wb unprotected objects: expect %"PRIuSIZE", but %"PRIuSIZE".", objspace->rgengc.uncollectible_wb_unprotected_objects, data.remembered_shady_count); - } + } } if (!finalizing) { - size_t list_count = 0; + size_t list_count = 0; - { - VALUE z = heap_pages_deferred_final; - while (z) { - list_count++; - z = RZOMBIE(z)->next; - } - } + { + VALUE z = heap_pages_deferred_final; + while (z) { + list_count++; + z = RZOMBIE(z)->next; + } + } - if (heap_pages_final_slots != data.zombie_object_count || - heap_pages_final_slots != list_count) { + if (heap_pages_final_slots != data.zombie_object_count || + heap_pages_final_slots != list_count) { rb_bug("inconsistent finalizing object count:\n" " expect %"PRIuSIZE"\n" @@ -8061,7 +8061,7 @@ gc_verify_internal_consistency_(rb_objspace_t *objspace) heap_pages_final_slots, data.zombie_object_count, list_count); - } + } } gc_report(5, objspace, "gc_verify_internal_consistency: OK\n"); @@ -8132,20 +8132,20 @@ gc_marks_start(rb_objspace_t *objspace, int full_mark) size_t incremental_marking_steps = (objspace->rincgc.pooled_slots / INCREMENTAL_MARK_STEP_ALLOCATIONS) + 1; objspace->rincgc.step_slots = (objspace->marked_slots * 2) / incremental_marking_steps; - if (0) fprintf(stderr, "objspace->marked_slots: %"PRIdSIZE", " + if (0) fprintf(stderr, "objspace->marked_slots: %"PRIdSIZE", " "objspace->rincgc.pooled_page_num: %"PRIdSIZE", " "objspace->rincgc.step_slots: %"PRIdSIZE", \n", objspace->marked_slots, objspace->rincgc.pooled_slots, objspace->rincgc.step_slots); #endif - objspace->flags.during_minor_gc = FALSE; + objspace->flags.during_minor_gc = FALSE; if (ruby_enable_autocompact) { objspace->flags.during_compacting |= TRUE; } - objspace->profile.major_gc_count++; - objspace->rgengc.uncollectible_wb_unprotected_objects = 0; - objspace->rgengc.old_objects = 0; - objspace->rgengc.last_major_gc = objspace->profile.count; - objspace->marked_slots = 0; + objspace->profile.major_gc_count++; + objspace->rgengc.uncollectible_wb_unprotected_objects = 0; + objspace->rgengc.old_objects = 0; + objspace->rgengc.last_major_gc = objspace->profile.count; + objspace->marked_slots = 0; for (int i = 0; i < SIZE_POOL_COUNT; i++) { rb_size_pool_t *size_pool = &size_pools[i]; @@ -8155,10 +8155,10 @@ gc_marks_start(rb_objspace_t *objspace, int full_mark) } } else { - objspace->flags.during_minor_gc = TRUE; - objspace->marked_slots = - objspace->rgengc.old_objects + objspace->rgengc.uncollectible_wb_unprotected_objects; /* uncollectible objects are marked already */ - objspace->profile.minor_gc_count++; + objspace->flags.during_minor_gc = TRUE; + objspace->marked_slots = + objspace->rgengc.old_objects + objspace->rgengc.uncollectible_wb_unprotected_objects; /* uncollectible objects are marked already */ + objspace->profile.minor_gc_count++; for (int i = 0; i < SIZE_POOL_COUNT; i++) { rgengc_rememberset_mark(objspace, SIZE_POOL_EDEN_HEAP(&size_pools[i])); @@ -8195,22 +8195,22 @@ gc_marks_wb_unprotected_objects(rb_objspace_t *objspace, rb_heap_t *heap) struct heap_page *page = 0; ccan_list_for_each(&heap->pages, page, page_node) { - bits_t *mark_bits = page->mark_bits; - bits_t *wbun_bits = page->wb_unprotected_bits; + bits_t *mark_bits = page->mark_bits; + bits_t *wbun_bits = page->wb_unprotected_bits; uintptr_t p = page->start; - size_t j; + size_t j; bits_t bits = mark_bits[0] & wbun_bits[0]; bits >>= NUM_IN_PAGE(p); gc_marks_wb_unprotected_objects_plane(objspace, p, bits); p += (BITS_BITLENGTH - NUM_IN_PAGE(p)) * BASE_SLOT_SIZE; - for (j=1; jmark_stack) == 0) { - rb_bug("gc_marks_finish: mark stack is not empty (%"PRIdSIZE").", + if (RGENGC_CHECK_MODE && is_mark_stack_empty(&objspace->mark_stack) == 0) { + rb_bug("gc_marks_finish: mark stack is not empty (%"PRIdSIZE").", mark_stack_size(&objspace->mark_stack)); - } + } - gc_mark_roots(objspace, 0); + gc_mark_roots(objspace, 0); while (gc_mark_stacked_objects_incremental(objspace, INT_MAX) == false); #if RGENGC_CHECK_MODE >= 2 - if (gc_verify_heap_pages(objspace) != 0) { - rb_bug("gc_marks_finish (incremental): there are remembered old objects."); - } + if (gc_verify_heap_pages(objspace) != 0) { + rb_bug("gc_marks_finish (incremental): there are remembered old objects."); + } #endif - objspace->flags.during_incremental_marking = FALSE; - /* check children of all marked wb-unprotected objects */ + objspace->flags.during_incremental_marking = FALSE; + /* check children of all marked wb-unprotected objects */ for (int i = 0; i < SIZE_POOL_COUNT; i++) { gc_marks_wb_unprotected_objects(objspace, SIZE_POOL_EDEN_HEAP(&size_pools[i])); } @@ -8250,10 +8250,10 @@ gc_marks_finish(rb_objspace_t *objspace) #endif if (is_full_marking(objspace)) { - /* See the comment about RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR */ - const double r = gc_params.oldobject_limit_factor; - objspace->rgengc.uncollectible_wb_unprotected_objects_limit = (size_t)(objspace->rgengc.uncollectible_wb_unprotected_objects * r); - objspace->rgengc.old_objects_limit = (size_t)(objspace->rgengc.old_objects * r); + /* See the comment about RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR */ + const double r = gc_params.oldobject_limit_factor; + objspace->rgengc.uncollectible_wb_unprotected_objects_limit = (size_t)(objspace->rgengc.uncollectible_wb_unprotected_objects * r); + objspace->rgengc.old_objects_limit = (size_t)(objspace->rgengc.old_objects * r); } #if RGENGC_CHECK_MODE >= 4 @@ -8263,81 +8263,81 @@ gc_marks_finish(rb_objspace_t *objspace) #endif { - /* decide full GC is needed or not */ + /* decide full GC is needed or not */ size_t total_slots = heap_allocatable_slots(objspace) + heap_eden_total_slots(objspace); - size_t sweep_slots = total_slots - objspace->marked_slots; /* will be swept slots */ - size_t max_free_slots = (size_t)(total_slots * gc_params.heap_free_slots_max_ratio); - size_t min_free_slots = (size_t)(total_slots * gc_params.heap_free_slots_min_ratio); - int full_marking = is_full_marking(objspace); + size_t sweep_slots = total_slots - objspace->marked_slots; /* will be swept slots */ + size_t max_free_slots = (size_t)(total_slots * gc_params.heap_free_slots_max_ratio); + size_t min_free_slots = (size_t)(total_slots * gc_params.heap_free_slots_min_ratio); + int full_marking = is_full_marking(objspace); const int r_cnt = GET_VM()->ractor.cnt; const int r_mul = r_cnt > 8 ? 8 : r_cnt; // upto 8 GC_ASSERT(heap_eden_total_slots(objspace) >= objspace->marked_slots); - /* setup free-able page counts */ + /* setup free-able page counts */ if (max_free_slots < gc_params.heap_init_slots * r_mul) { max_free_slots = gc_params.heap_init_slots * r_mul; } - if (sweep_slots > max_free_slots) { - heap_pages_freeable_pages = (sweep_slots - max_free_slots) / HEAP_PAGE_OBJ_LIMIT; - } - else { - heap_pages_freeable_pages = 0; - } + if (sweep_slots > max_free_slots) { + heap_pages_freeable_pages = (sweep_slots - max_free_slots) / HEAP_PAGE_OBJ_LIMIT; + } + else { + heap_pages_freeable_pages = 0; + } /* check free_min */ if (min_free_slots < gc_params.heap_free_slots * r_mul) { min_free_slots = gc_params.heap_free_slots * r_mul; } - if (sweep_slots < min_free_slots) { - if (!full_marking) { - if (objspace->profile.count - objspace->rgengc.last_major_gc < RVALUE_OLD_AGE) { - full_marking = TRUE; - /* do not update last_major_gc, because full marking is not done. */ + if (sweep_slots < min_free_slots) { + if (!full_marking) { + if (objspace->profile.count - objspace->rgengc.last_major_gc < RVALUE_OLD_AGE) { + full_marking = TRUE; + /* do not update last_major_gc, because full marking is not done. */ /* goto increment; */ - } - else { - gc_report(1, objspace, "gc_marks_finish: next is full GC!!)\n"); - objspace->rgengc.need_major_gc |= GPR_FLAG_MAJOR_BY_NOFREE; - } - } + } + else { + gc_report(1, objspace, "gc_marks_finish: next is full GC!!)\n"); + objspace->rgengc.need_major_gc |= GPR_FLAG_MAJOR_BY_NOFREE; + } + } #if !USE_RVARGC if (full_marking) { /* increment: */ - gc_report(1, objspace, "gc_marks_finish: heap_set_increment!!\n"); + gc_report(1, objspace, "gc_marks_finish: heap_set_increment!!\n"); rb_size_pool_t *size_pool = &size_pools[0]; size_pool_allocatable_pages_set(objspace, size_pool, heap_extend_pages(objspace, size_pool, sweep_slots, total_slots, heap_allocated_pages + heap_allocatable_pages(objspace))); heap_increment(objspace, size_pool, SIZE_POOL_EDEN_HEAP(size_pool)); - } + } #endif - } + } - if (full_marking) { - /* See the comment about RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR */ - const double r = gc_params.oldobject_limit_factor; - objspace->rgengc.uncollectible_wb_unprotected_objects_limit = (size_t)(objspace->rgengc.uncollectible_wb_unprotected_objects * r); - objspace->rgengc.old_objects_limit = (size_t)(objspace->rgengc.old_objects * r); - } + if (full_marking) { + /* See the comment about RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR */ + const double r = gc_params.oldobject_limit_factor; + objspace->rgengc.uncollectible_wb_unprotected_objects_limit = (size_t)(objspace->rgengc.uncollectible_wb_unprotected_objects * r); + objspace->rgengc.old_objects_limit = (size_t)(objspace->rgengc.old_objects * r); + } - if (objspace->rgengc.uncollectible_wb_unprotected_objects > objspace->rgengc.uncollectible_wb_unprotected_objects_limit) { - objspace->rgengc.need_major_gc |= GPR_FLAG_MAJOR_BY_SHADY; - } - if (objspace->rgengc.old_objects > objspace->rgengc.old_objects_limit) { - objspace->rgengc.need_major_gc |= GPR_FLAG_MAJOR_BY_OLDGEN; - } - if (RGENGC_FORCE_MAJOR_GC) { - objspace->rgengc.need_major_gc = GPR_FLAG_MAJOR_BY_FORCE; - } + if (objspace->rgengc.uncollectible_wb_unprotected_objects > objspace->rgengc.uncollectible_wb_unprotected_objects_limit) { + objspace->rgengc.need_major_gc |= GPR_FLAG_MAJOR_BY_SHADY; + } + if (objspace->rgengc.old_objects > objspace->rgengc.old_objects_limit) { + objspace->rgengc.need_major_gc |= GPR_FLAG_MAJOR_BY_OLDGEN; + } + if (RGENGC_FORCE_MAJOR_GC) { + objspace->rgengc.need_major_gc = GPR_FLAG_MAJOR_BY_FORCE; + } - gc_report(1, objspace, "gc_marks_finish (marks %"PRIdSIZE" objects, " + gc_report(1, objspace, "gc_marks_finish (marks %"PRIdSIZE" objects, " "old %"PRIdSIZE" objects, total %"PRIdSIZE" slots, " "sweep %"PRIdSIZE" slots, increment: %"PRIdSIZE", next GC: %s)\n", objspace->marked_slots, objspace->rgengc.old_objects, heap_eden_total_slots(objspace), sweep_slots, heap_allocatable_pages(objspace), - objspace->rgengc.need_major_gc ? "major" : "minor"); + objspace->rgengc.need_major_gc ? "major" : "minor"); } rb_transient_heap_finish_marking(); @@ -8561,7 +8561,7 @@ gc_marks_rest(rb_objspace_t *objspace) while (gc_mark_stacked_objects_incremental(objspace, INT_MAX) == FALSE); } else { - gc_mark_stacked_objects_all(objspace); + gc_mark_stacked_objects_all(objspace); } gc_marks_finish(objspace); @@ -8620,29 +8620,29 @@ static void gc_report_body(int level, rb_objspace_t *objspace, const char *fmt, ...) { if (level <= RGENGC_DEBUG) { - char buf[1024]; - FILE *out = stderr; - va_list args; - const char *status = " "; + char buf[1024]; + FILE *out = stderr; + va_list args; + const char *status = " "; - if (during_gc) { - status = is_full_marking(objspace) ? "+" : "-"; - } - else { - if (is_lazy_sweeping(objspace)) { - status = "S"; - } - if (is_incremental_marking(objspace)) { - status = "M"; - } - } + if (during_gc) { + status = is_full_marking(objspace) ? "+" : "-"; + } + else { + if (is_lazy_sweeping(objspace)) { + status = "S"; + } + if (is_incremental_marking(objspace)) { + status = "M"; + } + } - va_start(args, fmt); - vsnprintf(buf, 1024, fmt, args); - va_end(args); + va_start(args, fmt); + vsnprintf(buf, 1024, fmt, args); + va_end(args); - fprintf(out, "%s|", status); - fputs(buf, out); + fprintf(out, "%s|", status); + fputs(buf, out); } } @@ -8663,12 +8663,12 @@ rgengc_remembersetbits_set(rb_objspace_t *objspace, VALUE obj) GC_ASSERT(!is_incremental_marking(objspace)); if (MARKED_IN_BITMAP(bits, obj)) { - return FALSE; + return FALSE; } else { - page->flags.has_remembered_objects = TRUE; - MARK_IN_BITMAP(bits, obj); - return TRUE; + page->flags.has_remembered_objects = TRUE; + MARK_IN_BITMAP(bits, obj); + return TRUE; } } @@ -8679,22 +8679,22 @@ static int rgengc_remember(rb_objspace_t *objspace, VALUE obj) { gc_report(6, objspace, "rgengc_remember: %s %s\n", obj_info(obj), - rgengc_remembersetbits_get(objspace, obj) ? "was already remembered" : "is remembered now"); + rgengc_remembersetbits_get(objspace, obj) ? "was already remembered" : "is remembered now"); check_rvalue_consistency(obj); if (RGENGC_CHECK_MODE) { - if (RVALUE_WB_UNPROTECTED(obj)) rb_bug("rgengc_remember: %s is not wb protected.", obj_info(obj)); + if (RVALUE_WB_UNPROTECTED(obj)) rb_bug("rgengc_remember: %s is not wb protected.", obj_info(obj)); } #if RGENGC_PROFILE > 0 if (!rgengc_remembered(objspace, obj)) { - if (RVALUE_WB_UNPROTECTED(obj) == 0) { - objspace->profile.total_remembered_normal_object_count++; + if (RVALUE_WB_UNPROTECTED(obj) == 0) { + objspace->profile.total_remembered_normal_object_count++; #if RGENGC_PROFILE >= 2 - objspace->profile.remembered_normal_object_count_types[BUILTIN_TYPE(obj)]++; + objspace->profile.remembered_normal_object_count_types[BUILTIN_TYPE(obj)]++; #endif - } + } } #endif /* RGENGC_PROFILE > 0 */ @@ -8750,38 +8750,38 @@ rgengc_rememberset_mark(rb_objspace_t *objspace, rb_heap_t *heap) gc_report(1, objspace, "rgengc_rememberset_mark: start\n"); ccan_list_for_each(&heap->pages, page, page_node) { - if (page->flags.has_remembered_objects | page->flags.has_uncollectible_shady_objects) { + if (page->flags.has_remembered_objects | page->flags.has_uncollectible_shady_objects) { uintptr_t p = page->start; - bits_t bitset, bits[HEAP_PAGE_BITMAP_LIMIT]; - bits_t *marking_bits = page->marking_bits; - bits_t *uncollectible_bits = page->uncollectible_bits; - bits_t *wb_unprotected_bits = page->wb_unprotected_bits; + bits_t bitset, bits[HEAP_PAGE_BITMAP_LIMIT]; + bits_t *marking_bits = page->marking_bits; + bits_t *uncollectible_bits = page->uncollectible_bits; + bits_t *wb_unprotected_bits = page->wb_unprotected_bits; #if PROFILE_REMEMBERSET_MARK - if (page->flags.has_remembered_objects && page->flags.has_uncollectible_shady_objects) has_both++; - else if (page->flags.has_remembered_objects) has_old++; - else if (page->flags.has_uncollectible_shady_objects) has_shady++; + if (page->flags.has_remembered_objects && page->flags.has_uncollectible_shady_objects) has_both++; + else if (page->flags.has_remembered_objects) has_old++; + else if (page->flags.has_uncollectible_shady_objects) has_shady++; #endif - for (j=0; jflags.has_remembered_objects = FALSE; + for (j=0; jflags.has_remembered_objects = FALSE; bitset = bits[0]; bitset >>= NUM_IN_PAGE(p); rgengc_rememberset_mark_plane(objspace, p, bitset); p += (BITS_BITLENGTH - NUM_IN_PAGE(p)) * BASE_SLOT_SIZE; - for (j=1; j < HEAP_PAGE_BITMAP_LIMIT; j++) { - bitset = bits[j]; + for (j=1; j < HEAP_PAGE_BITMAP_LIMIT; j++) { + bitset = bits[j]; rgengc_rememberset_mark_plane(objspace, p, bitset); p += BITS_BITLENGTH * BASE_SLOT_SIZE; - } - } + } + } #if PROFILE_REMEMBERSET_MARK - else { - skip++; - } + else { + skip++; + } #endif } @@ -8797,12 +8797,12 @@ rgengc_mark_and_rememberset_clear(rb_objspace_t *objspace, rb_heap_t *heap) struct heap_page *page = 0; ccan_list_for_each(&heap->pages, page, page_node) { - memset(&page->mark_bits[0], 0, HEAP_PAGE_BITMAP_SIZE); - memset(&page->uncollectible_bits[0], 0, HEAP_PAGE_BITMAP_SIZE); + memset(&page->mark_bits[0], 0, HEAP_PAGE_BITMAP_SIZE); + memset(&page->uncollectible_bits[0], 0, HEAP_PAGE_BITMAP_SIZE); memset(&page->marking_bits[0], 0, HEAP_PAGE_BITMAP_SIZE); memset(&page->pinned_bits[0], 0, HEAP_PAGE_BITMAP_SIZE); - page->flags.has_uncollectible_shady_objects = FALSE; - page->flags.has_remembered_objects = FALSE; + page->flags.has_uncollectible_shady_objects = FALSE; + page->flags.has_remembered_objects = FALSE; } } @@ -8814,9 +8814,9 @@ static void gc_writebarrier_generational(VALUE a, VALUE b, rb_objspace_t *objspace) { if (RGENGC_CHECK_MODE) { - if (!RVALUE_OLD_P(a)) rb_bug("gc_writebarrier_generational: %s is not an old object.", obj_info(a)); - if ( RVALUE_OLD_P(b)) rb_bug("gc_writebarrier_generational: %s is an old object.", obj_info(b)); - if (is_incremental_marking(objspace)) rb_bug("gc_writebarrier_generational: called while incremental marking: %s -> %s", obj_info(a), obj_info(b)); + if (!RVALUE_OLD_P(a)) rb_bug("gc_writebarrier_generational: %s is not an old object.", obj_info(a)); + if ( RVALUE_OLD_P(b)) rb_bug("gc_writebarrier_generational: %s is an old object.", obj_info(b)); + if (is_incremental_marking(objspace)) rb_bug("gc_writebarrier_generational: called while incremental marking: %s -> %s", obj_info(a), obj_info(b)); } #if 1 @@ -8827,17 +8827,17 @@ gc_writebarrier_generational(VALUE a, VALUE b, rb_objspace_t *objspace) rgengc_remember(objspace, a); } RB_VM_LOCK_LEAVE_NO_BARRIER(); - gc_report(1, objspace, "gc_writebarrier_generational: %s (remembered) -> %s\n", obj_info(a), obj_info(b)); + gc_report(1, objspace, "gc_writebarrier_generational: %s (remembered) -> %s\n", obj_info(a), obj_info(b)); } #else /* mark `b' and remember */ MARK_IN_BITMAP(GET_HEAP_MARK_BITS(b), b); if (RVALUE_WB_UNPROTECTED(b)) { - gc_remember_unprotected(objspace, b); + gc_remember_unprotected(objspace, b); } else { - RVALUE_AGE_SET_OLD(objspace, b); - rgengc_remember(objspace, b); + RVALUE_AGE_SET_OLD(objspace, b); + rgengc_remember(objspace, b); } gc_report(1, objspace, "gc_writebarrier_generational: %s -> %s (remembered)\n", obj_info(a), obj_info(b)); @@ -8866,26 +8866,26 @@ gc_writebarrier_incremental(VALUE a, VALUE b, rb_objspace_t *objspace) gc_report(2, objspace, "gc_writebarrier_incremental: [LG] %p -> %s\n", (void *)a, obj_info(b)); if (RVALUE_BLACK_P(a)) { - if (RVALUE_WHITE_P(b)) { - if (!RVALUE_WB_UNPROTECTED(a)) { - gc_report(2, objspace, "gc_writebarrier_incremental: [IN] %p -> %s\n", (void *)a, obj_info(b)); - gc_mark_from(objspace, b, a); - } - } - else if (RVALUE_OLD_P(a) && !RVALUE_OLD_P(b)) { - if (!RVALUE_WB_UNPROTECTED(b)) { - gc_report(1, objspace, "gc_writebarrier_incremental: [GN] %p -> %s\n", (void *)a, obj_info(b)); - RVALUE_AGE_SET_OLD(objspace, b); + if (RVALUE_WHITE_P(b)) { + if (!RVALUE_WB_UNPROTECTED(a)) { + gc_report(2, objspace, "gc_writebarrier_incremental: [IN] %p -> %s\n", (void *)a, obj_info(b)); + gc_mark_from(objspace, b, a); + } + } + else if (RVALUE_OLD_P(a) && !RVALUE_OLD_P(b)) { + if (!RVALUE_WB_UNPROTECTED(b)) { + gc_report(1, objspace, "gc_writebarrier_incremental: [GN] %p -> %s\n", (void *)a, obj_info(b)); + RVALUE_AGE_SET_OLD(objspace, b); - if (RVALUE_BLACK_P(b)) { - gc_grey(objspace, b); - } - } - else { - gc_report(1, objspace, "gc_writebarrier_incremental: [LL] %p -> %s\n", (void *)a, obj_info(b)); - gc_remember_unprotected(objspace, b); - } - } + if (RVALUE_BLACK_P(b)) { + gc_grey(objspace, b); + } + } + else { + gc_report(1, objspace, "gc_writebarrier_incremental: [LL] %p -> %s\n", (void *)a, obj_info(b)); + gc_remember_unprotected(objspace, b); + } + } if (UNLIKELY(objspace->flags.during_compacting)) { MARK_IN_BITMAP(GET_HEAP_PINNED_BITS(b), b); @@ -8936,33 +8936,33 @@ void rb_gc_writebarrier_unprotect(VALUE obj) { if (RVALUE_WB_UNPROTECTED(obj)) { - return; + return; } else { - rb_objspace_t *objspace = &rb_objspace; + rb_objspace_t *objspace = &rb_objspace; - gc_report(2, objspace, "rb_gc_writebarrier_unprotect: %s %s\n", obj_info(obj), - rgengc_remembered(objspace, obj) ? " (already remembered)" : ""); + gc_report(2, objspace, "rb_gc_writebarrier_unprotect: %s %s\n", obj_info(obj), + rgengc_remembered(objspace, obj) ? " (already remembered)" : ""); - if (RVALUE_OLD_P(obj)) { - gc_report(1, objspace, "rb_gc_writebarrier_unprotect: %s\n", obj_info(obj)); - RVALUE_DEMOTE(objspace, obj); - gc_mark_set(objspace, obj); - gc_remember_unprotected(objspace, obj); + if (RVALUE_OLD_P(obj)) { + gc_report(1, objspace, "rb_gc_writebarrier_unprotect: %s\n", obj_info(obj)); + RVALUE_DEMOTE(objspace, obj); + gc_mark_set(objspace, obj); + gc_remember_unprotected(objspace, obj); #if RGENGC_PROFILE - objspace->profile.total_shade_operation_count++; + objspace->profile.total_shade_operation_count++; #if RGENGC_PROFILE >= 2 - objspace->profile.shade_operation_count_types[BUILTIN_TYPE(obj)]++; + objspace->profile.shade_operation_count_types[BUILTIN_TYPE(obj)]++; #endif /* RGENGC_PROFILE >= 2 */ #endif /* RGENGC_PROFILE */ - } - else { - RVALUE_AGE_RESET(obj); - } + } + else { + RVALUE_AGE_RESET(obj); + } RB_DEBUG_COUNTER_INC(obj_wb_unprotect); - MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(obj), obj); + MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(obj), obj); } } @@ -8977,14 +8977,14 @@ rb_gc_writebarrier_remember(VALUE obj) gc_report(1, objspace, "rb_gc_writebarrier_remember: %s\n", obj_info(obj)); if (is_incremental_marking(objspace)) { - if (RVALUE_BLACK_P(obj)) { - gc_grey(objspace, obj); - } + if (RVALUE_BLACK_P(obj)) { + gc_grey(objspace, obj); + } } else { - if (RVALUE_OLD_P(obj)) { - rgengc_remember(objspace, obj); - } + if (RVALUE_OLD_P(obj)) { + rgengc_remember(objspace, obj); + } } } @@ -9009,25 +9009,25 @@ rb_gc_unprotect_logging(void *objptr, const char *filename, int line) VALUE obj = (VALUE)objptr; if (rgengc_unprotect_logging_table == 0) { - rgengc_unprotect_logging_table = st_init_strtable(); - atexit(rgengc_unprotect_logging_exit_func); + rgengc_unprotect_logging_table = st_init_strtable(); + atexit(rgengc_unprotect_logging_exit_func); } if (RVALUE_WB_UNPROTECTED(obj) == 0) { - char buff[0x100]; - st_data_t cnt = 1; - char *ptr = buff; + char buff[0x100]; + st_data_t cnt = 1; + char *ptr = buff; - snprintf(ptr, 0x100 - 1, "%s|%s:%d", obj_info(obj), filename, line); + snprintf(ptr, 0x100 - 1, "%s|%s:%d", obj_info(obj), filename, line); - if (st_lookup(rgengc_unprotect_logging_table, (st_data_t)ptr, &cnt)) { - cnt++; - } - else { - ptr = (strdup)(buff); - if (!ptr) rb_memerror(); - } - st_insert(rgengc_unprotect_logging_table, (st_data_t)ptr, cnt); + if (st_lookup(rgengc_unprotect_logging_table, (st_data_t)ptr, &cnt)) { + cnt++; + } + else { + ptr = (strdup)(buff); + if (!ptr) rb_memerror(); + } + st_insert(rgengc_unprotect_logging_table, (st_data_t)ptr, cnt); } } @@ -9037,13 +9037,13 @@ rb_copy_wb_protected_attribute(VALUE dest, VALUE obj) rb_objspace_t *objspace = &rb_objspace; if (RVALUE_WB_UNPROTECTED(obj) && !RVALUE_WB_UNPROTECTED(dest)) { - if (!RVALUE_OLD_P(dest)) { - MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(dest), dest); - RVALUE_AGE_RESET_RAW(dest); - } - else { - RVALUE_DEMOTE(objspace, dest); - } + if (!RVALUE_OLD_P(dest)) { + MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(dest), dest); + RVALUE_AGE_RESET_RAW(dest); + } + else { + RVALUE_DEMOTE(objspace, dest); + } } check_rvalue_consistency(dest); @@ -9072,11 +9072,11 @@ rb_obj_gc_flags(VALUE obj, ID* flags, size_t max) if (!ID_marked) { #define I(s) ID_##s = rb_intern(#s); - I(marked); - I(wb_protected); - I(old); - I(marking); - I(uncollectible); + I(marked); + I(wb_protected); + I(old); + I(marking); + I(uncollectible); I(pinned); #undef I } @@ -9163,19 +9163,19 @@ rb_gc_unregister_address(VALUE *addr) struct gc_list *tmp = global_list; if (tmp->varptr == addr) { - global_list = tmp->next; - xfree(tmp); - return; + global_list = tmp->next; + xfree(tmp); + return; } while (tmp->next) { - if (tmp->next->varptr == addr) { - struct gc_list *t = tmp->next; + if (tmp->next->varptr == addr) { + struct gc_list *t = tmp->next; - tmp->next = tmp->next->next; - xfree(t); - break; - } - tmp = tmp->next; + tmp->next = tmp->next->next; + xfree(t); + break; + } + tmp = tmp->next; } } @@ -9219,7 +9219,7 @@ ready_to_gc(rb_objspace_t *objspace) return FALSE; } else { - return TRUE; + return TRUE; } } @@ -9228,65 +9228,65 @@ gc_reset_malloc_info(rb_objspace_t *objspace, bool full_mark) { gc_prof_set_malloc_info(objspace); { - size_t inc = ATOMIC_SIZE_EXCHANGE(malloc_increase, 0); - size_t old_limit = malloc_limit; + size_t inc = ATOMIC_SIZE_EXCHANGE(malloc_increase, 0); + size_t old_limit = malloc_limit; - if (inc > malloc_limit) { - malloc_limit = (size_t)(inc * gc_params.malloc_limit_growth_factor); - if (malloc_limit > gc_params.malloc_limit_max) { - malloc_limit = gc_params.malloc_limit_max; - } - } - else { - malloc_limit = (size_t)(malloc_limit * 0.98); /* magic number */ - if (malloc_limit < gc_params.malloc_limit_min) { - malloc_limit = gc_params.malloc_limit_min; - } - } + if (inc > malloc_limit) { + malloc_limit = (size_t)(inc * gc_params.malloc_limit_growth_factor); + if (malloc_limit > gc_params.malloc_limit_max) { + malloc_limit = gc_params.malloc_limit_max; + } + } + else { + malloc_limit = (size_t)(malloc_limit * 0.98); /* magic number */ + if (malloc_limit < gc_params.malloc_limit_min) { + malloc_limit = gc_params.malloc_limit_min; + } + } - if (0) { - if (old_limit != malloc_limit) { - fprintf(stderr, "[%"PRIuSIZE"] malloc_limit: %"PRIuSIZE" -> %"PRIuSIZE"\n", - rb_gc_count(), old_limit, malloc_limit); - } - else { - fprintf(stderr, "[%"PRIuSIZE"] malloc_limit: not changed (%"PRIuSIZE")\n", - rb_gc_count(), malloc_limit); - } - } + if (0) { + if (old_limit != malloc_limit) { + fprintf(stderr, "[%"PRIuSIZE"] malloc_limit: %"PRIuSIZE" -> %"PRIuSIZE"\n", + rb_gc_count(), old_limit, malloc_limit); + } + else { + fprintf(stderr, "[%"PRIuSIZE"] malloc_limit: not changed (%"PRIuSIZE")\n", + rb_gc_count(), malloc_limit); + } + } } /* reset oldmalloc info */ #if RGENGC_ESTIMATE_OLDMALLOC if (!full_mark) { - if (objspace->rgengc.oldmalloc_increase > objspace->rgengc.oldmalloc_increase_limit) { - objspace->rgengc.need_major_gc |= GPR_FLAG_MAJOR_BY_OLDMALLOC; - objspace->rgengc.oldmalloc_increase_limit = - (size_t)(objspace->rgengc.oldmalloc_increase_limit * gc_params.oldmalloc_limit_growth_factor); + if (objspace->rgengc.oldmalloc_increase > objspace->rgengc.oldmalloc_increase_limit) { + objspace->rgengc.need_major_gc |= GPR_FLAG_MAJOR_BY_OLDMALLOC; + objspace->rgengc.oldmalloc_increase_limit = + (size_t)(objspace->rgengc.oldmalloc_increase_limit * gc_params.oldmalloc_limit_growth_factor); - if (objspace->rgengc.oldmalloc_increase_limit > gc_params.oldmalloc_limit_max) { - objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_max; - } - } + if (objspace->rgengc.oldmalloc_increase_limit > gc_params.oldmalloc_limit_max) { + objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_max; + } + } - if (0) fprintf(stderr, "%"PRIdSIZE"\t%d\t%"PRIuSIZE"\t%"PRIuSIZE"\t%"PRIdSIZE"\n", - rb_gc_count(), - objspace->rgengc.need_major_gc, - objspace->rgengc.oldmalloc_increase, - objspace->rgengc.oldmalloc_increase_limit, - gc_params.oldmalloc_limit_max); + if (0) fprintf(stderr, "%"PRIdSIZE"\t%d\t%"PRIuSIZE"\t%"PRIuSIZE"\t%"PRIdSIZE"\n", + rb_gc_count(), + objspace->rgengc.need_major_gc, + objspace->rgengc.oldmalloc_increase, + objspace->rgengc.oldmalloc_increase_limit, + gc_params.oldmalloc_limit_max); } else { - /* major GC */ - objspace->rgengc.oldmalloc_increase = 0; + /* major GC */ + objspace->rgengc.oldmalloc_increase = 0; - if ((objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_BY_OLDMALLOC) == 0) { - objspace->rgengc.oldmalloc_increase_limit = - (size_t)(objspace->rgengc.oldmalloc_increase_limit / ((gc_params.oldmalloc_limit_growth_factor - 1)/10 + 1)); - if (objspace->rgengc.oldmalloc_increase_limit < gc_params.oldmalloc_limit_min) { - objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min; - } - } + if ((objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_BY_OLDMALLOC) == 0) { + objspace->rgengc.oldmalloc_increase_limit = + (size_t)(objspace->rgengc.oldmalloc_increase_limit / ((gc_params.oldmalloc_limit_growth_factor - 1)/10 + 1)); + if (objspace->rgengc.oldmalloc_increase_limit < gc_params.oldmalloc_limit_min) { + objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min; + } + } } #endif } @@ -9349,49 +9349,49 @@ gc_start(rb_objspace_t *objspace, unsigned int reason) #endif if (ruby_gc_stressful) { - int flag = FIXNUM_P(ruby_gc_stress_mode) ? FIX2INT(ruby_gc_stress_mode) : 0; + int flag = FIXNUM_P(ruby_gc_stress_mode) ? FIX2INT(ruby_gc_stress_mode) : 0; - if ((flag & (1<flags.immediate_sweep = !(flag & (1<flags.immediate_sweep = !(flag & (1<rgengc.need_major_gc) { - reason |= objspace->rgengc.need_major_gc; - do_full_mark = TRUE; - } - else if (RGENGC_FORCE_MAJOR_GC) { - reason = GPR_FLAG_MAJOR_BY_FORCE; - do_full_mark = TRUE; - } + if (objspace->rgengc.need_major_gc) { + reason |= objspace->rgengc.need_major_gc; + do_full_mark = TRUE; + } + else if (RGENGC_FORCE_MAJOR_GC) { + reason = GPR_FLAG_MAJOR_BY_FORCE; + do_full_mark = TRUE; + } - objspace->rgengc.need_major_gc = GPR_FLAG_NONE; + objspace->rgengc.need_major_gc = GPR_FLAG_NONE; } if (do_full_mark && (reason & GPR_FLAG_MAJOR_MASK) == 0) { - reason |= GPR_FLAG_MAJOR_BY_FORCE; /* GC by CAPI, METHOD, and so on. */ + reason |= GPR_FLAG_MAJOR_BY_FORCE; /* GC by CAPI, METHOD, and so on. */ } #if GC_ENABLE_INCREMENTAL_MARK if (!GC_ENABLE_INCREMENTAL_MARK || objspace->flags.dont_incremental || immediate_mark) { - objspace->flags.during_incremental_marking = FALSE; + objspace->flags.during_incremental_marking = FALSE; } else { - objspace->flags.during_incremental_marking = do_full_mark; + objspace->flags.during_incremental_marking = do_full_mark; } #endif if (!GC_ENABLE_LAZY_SWEEP || objspace->flags.dont_incremental) { - objspace->flags.immediate_sweep = TRUE; + objspace->flags.immediate_sweep = TRUE; } if (objspace->flags.immediate_sweep) reason |= GPR_FLAG_IMMEDIATE_SWEEP; gc_report(1, objspace, "gc_start(reason: %x) => %u, %d, %d\n", - reason, - do_full_mark, !is_incremental_marking(objspace), objspace->flags.immediate_sweep); + reason, + do_full_mark, !is_incremental_marking(objspace), objspace->flags.immediate_sweep); #if USE_DEBUG_COUNTER RB_DEBUG_COUNTER_INC(gc_count); @@ -9427,7 +9427,7 @@ gc_start(rb_objspace_t *objspace, unsigned int reason) gc_prof_timer_start(objspace); { - gc_marks(objspace, do_full_mark); + gc_marks(objspace, do_full_mark); } gc_prof_timer_stop(objspace); @@ -9443,17 +9443,17 @@ gc_rest(rb_objspace_t *objspace) if (marking || sweeping) { unsigned int lock_lev; - gc_enter(objspace, gc_enter_event_rest, &lock_lev); + gc_enter(objspace, gc_enter_event_rest, &lock_lev); if (RGENGC_CHECK_MODE >= 2) gc_verify_internal_consistency(objspace); - if (is_incremental_marking(objspace)) { + if (is_incremental_marking(objspace)) { gc_marks_rest(objspace); } - if (is_lazy_sweeping(objspace)) { - gc_sweep_rest(objspace); - } - gc_exit(objspace, gc_enter_event_rest, &lock_lev); + if (is_lazy_sweeping(objspace)) { + gc_sweep_rest(objspace); + } + gc_exit(objspace, gc_enter_event_rest, &lock_lev); } } @@ -9467,18 +9467,18 @@ gc_current_status_fill(rb_objspace_t *objspace, char *buff) { int i = 0; if (is_marking(objspace)) { - buff[i++] = 'M'; - if (is_full_marking(objspace)) buff[i++] = 'F'; + buff[i++] = 'M'; + if (is_full_marking(objspace)) buff[i++] = 'F'; #if GC_ENABLE_INCREMENTAL_MARK - if (is_incremental_marking(objspace)) buff[i++] = 'I'; + if (is_incremental_marking(objspace)) buff[i++] = 'I'; #endif } else if (is_sweeping(objspace)) { - buff[i++] = 'S'; - if (is_lazy_sweeping(objspace)) buff[i++] = 'L'; + buff[i++] = 'S'; + if (is_lazy_sweeping(objspace)) buff[i++] = 'L'; } else { - buff[i++] = 'N'; + buff[i++] = 'N'; } buff[i] = '\0'; } @@ -9502,31 +9502,31 @@ static inline void gc_record(rb_objspace_t *objspace, int direction, const char *event) { if (direction == 0) { /* enter */ - enter_count++; - enter_tick = tick(); - gc_current_status_fill(objspace, last_gc_status); + enter_count++; + enter_tick = tick(); + gc_current_status_fill(objspace, last_gc_status); } else { /* exit */ - tick_t exit_tick = tick(); - char current_gc_status[0x10]; - gc_current_status_fill(objspace, current_gc_status); + tick_t exit_tick = tick(); + char current_gc_status[0x10]; + gc_current_status_fill(objspace, current_gc_status); #if 1 - /* [last mutator time] [gc time] [event] */ - fprintf(stderr, "%"PRItick"\t%"PRItick"\t%s\t[%s->%s|%c]\n", - enter_tick - last_exit_tick, - exit_tick - enter_tick, - event, - last_gc_status, current_gc_status, - (objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) ? '+' : '-'); - last_exit_tick = exit_tick; + /* [last mutator time] [gc time] [event] */ + fprintf(stderr, "%"PRItick"\t%"PRItick"\t%s\t[%s->%s|%c]\n", + enter_tick - last_exit_tick, + exit_tick - enter_tick, + event, + last_gc_status, current_gc_status, + (objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) ? '+' : '-'); + last_exit_tick = exit_tick; #else - /* [enter_tick] [gc time] [event] */ - fprintf(stderr, "%"PRItick"\t%"PRItick"\t%s\t[%s->%s|%c]\n", - enter_tick, - exit_tick - enter_tick, - event, - last_gc_status, current_gc_status, - (objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) ? '+' : '-'); + /* [enter_tick] [gc time] [event] */ + fprintf(stderr, "%"PRItick"\t%"PRItick"\t%s\t[%s->%s|%c]\n", + enter_tick, + exit_tick - enter_tick, + event, + last_gc_status, current_gc_status, + (objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) ? '+' : '-'); #endif } } @@ -9690,20 +9690,20 @@ garbage_collect_with_gvl(rb_objspace_t *objspace, unsigned int reason) { if (dont_gc_val()) return TRUE; if (ruby_thread_has_gvl_p()) { - return garbage_collect(objspace, reason); + return garbage_collect(objspace, reason); } else { - if (ruby_native_thread_p()) { - struct objspace_and_reason oar; - oar.objspace = objspace; - oar.reason = reason; - return (int)(VALUE)rb_thread_call_with_gvl(gc_with_gvl, (void *)&oar); - } - else { - /* no ruby thread */ - fprintf(stderr, "[FATAL] failed to allocate memory\n"); - exit(EXIT_FAILURE); - } + if (ruby_native_thread_p()) { + struct objspace_and_reason oar; + oar.objspace = objspace; + oar.reason = reason; + return (int)(VALUE)rb_thread_call_with_gvl(gc_with_gvl, (void *)&oar); + } + else { + /* no ruby thread */ + fprintf(stderr, "[FATAL] failed to allocate memory\n"); + exit(EXIT_FAILURE); + } } } @@ -11059,44 +11059,44 @@ setup_gc_stat_symbols(void) { if (gc_stat_symbols[0] == 0) { #define S(s) gc_stat_symbols[gc_stat_sym_##s] = ID2SYM(rb_intern_const(#s)) - S(count); + S(count); S(time); - S(heap_allocated_pages); - S(heap_sorted_length); - S(heap_allocatable_pages); - S(heap_available_slots); - S(heap_live_slots); - S(heap_free_slots); - S(heap_final_slots); - S(heap_marked_slots); - S(heap_eden_pages); - S(heap_tomb_pages); - S(total_allocated_pages); - S(total_freed_pages); - S(total_allocated_objects); - S(total_freed_objects); - S(malloc_increase_bytes); - S(malloc_increase_bytes_limit); - S(minor_gc_count); - S(major_gc_count); - S(compact_count); - S(read_barrier_faults); - S(total_moved_objects); - S(remembered_wb_unprotected_objects); - S(remembered_wb_unprotected_objects_limit); - S(old_objects); - S(old_objects_limit); + S(heap_allocated_pages); + S(heap_sorted_length); + S(heap_allocatable_pages); + S(heap_available_slots); + S(heap_live_slots); + S(heap_free_slots); + S(heap_final_slots); + S(heap_marked_slots); + S(heap_eden_pages); + S(heap_tomb_pages); + S(total_allocated_pages); + S(total_freed_pages); + S(total_allocated_objects); + S(total_freed_objects); + S(malloc_increase_bytes); + S(malloc_increase_bytes_limit); + S(minor_gc_count); + S(major_gc_count); + S(compact_count); + S(read_barrier_faults); + S(total_moved_objects); + S(remembered_wb_unprotected_objects); + S(remembered_wb_unprotected_objects_limit); + S(old_objects); + S(old_objects_limit); #if RGENGC_ESTIMATE_OLDMALLOC - S(oldmalloc_increase_bytes); - S(oldmalloc_increase_bytes_limit); + S(oldmalloc_increase_bytes); + S(oldmalloc_increase_bytes_limit); #endif #if RGENGC_PROFILE - S(total_generated_normal_object_count); - S(total_generated_shady_object_count); - S(total_shade_operation_count); - S(total_promoted_count); - S(total_remembered_normal_object_count); - S(total_remembered_shady_object_count); + S(total_generated_normal_object_count); + S(total_generated_shady_object_count); + S(total_shade_operation_count); + S(total_promoted_count); + S(total_remembered_normal_object_count); + S(total_remembered_shady_object_count); #endif /* RGENGC_PROFILE */ #undef S } @@ -11111,20 +11111,20 @@ gc_stat_internal(VALUE hash_or_sym) setup_gc_stat_symbols(); if (RB_TYPE_P(hash_or_sym, T_HASH)) { - hash = hash_or_sym; + hash = hash_or_sym; } else if (SYMBOL_P(hash_or_sym)) { - key = hash_or_sym; + key = hash_or_sym; } else { - rb_raise(rb_eTypeError, "non-hash or symbol argument"); + rb_raise(rb_eTypeError, "non-hash or symbol argument"); } #define SET(name, attr) \ if (key == gc_stat_symbols[gc_stat_sym_##name]) \ - return attr; \ + return attr; \ else if (hash != Qnil) \ - rb_hash_aset(hash, gc_stat_symbols[gc_stat_sym_##name], SIZET2NUM(attr)); + rb_hash_aset(hash, gc_stat_symbols[gc_stat_sym_##name], SIZET2NUM(attr)); SET(count, objspace->profile.count); SET(time, (size_t) (objspace->profile.total_time_ns / (1000 * 1000) /* ns -> ms */)); // TODO: UINT64T2NUM @@ -11171,17 +11171,17 @@ gc_stat_internal(VALUE hash_or_sym) #undef SET if (!NIL_P(key)) { /* matched key should return above */ - rb_raise(rb_eArgError, "unknown key: %"PRIsVALUE, rb_sym2str(key)); + rb_raise(rb_eArgError, "unknown key: %"PRIsVALUE, rb_sym2str(key)); } #if defined(RGENGC_PROFILE) && RGENGC_PROFILE >= 2 if (hash != Qnil) { - gc_count_add_each_types(hash, "generated_normal_object_count_types", objspace->profile.generated_normal_object_count_types); - gc_count_add_each_types(hash, "generated_shady_object_count_types", objspace->profile.generated_shady_object_count_types); - gc_count_add_each_types(hash, "shade_operation_count_types", objspace->profile.shade_operation_count_types); - gc_count_add_each_types(hash, "promoted_types", objspace->profile.promoted_types); - gc_count_add_each_types(hash, "remembered_normal_object_count_types", objspace->profile.remembered_normal_object_count_types); - gc_count_add_each_types(hash, "remembered_shady_object_count_types", objspace->profile.remembered_shady_object_count_types); + gc_count_add_each_types(hash, "generated_normal_object_count_types", objspace->profile.generated_normal_object_count_types); + gc_count_add_each_types(hash, "generated_shady_object_count_types", objspace->profile.generated_shady_object_count_types); + gc_count_add_each_types(hash, "shade_operation_count_types", objspace->profile.shade_operation_count_types); + gc_count_add_each_types(hash, "promoted_types", objspace->profile.promoted_types); + gc_count_add_each_types(hash, "remembered_normal_object_count_types", objspace->profile.remembered_normal_object_count_types); + gc_count_add_each_types(hash, "remembered_shady_object_count_types", objspace->profile.remembered_shady_object_count_types); } #endif @@ -11213,12 +11213,12 @@ size_t rb_gc_stat(VALUE key) { if (SYMBOL_P(key)) { - size_t value = gc_stat_internal(key); - return value; + size_t value = gc_stat_internal(key); + return value; } else { - gc_stat_internal(key); - return 0; + gc_stat_internal(key); + return 0; } } @@ -11478,53 +11478,53 @@ get_envparam_size(const char *name, size_t *default_value, size_t lower_bound) ssize_t val; if (ptr != NULL && *ptr) { - size_t unit = 0; - char *end; + size_t unit = 0; + char *end; #if SIZEOF_SIZE_T == SIZEOF_LONG_LONG - val = strtoll(ptr, &end, 0); + val = strtoll(ptr, &end, 0); #else - val = strtol(ptr, &end, 0); + val = strtol(ptr, &end, 0); #endif - switch (*end) { - case 'k': case 'K': - unit = 1024; - ++end; - break; - case 'm': case 'M': - unit = 1024*1024; - ++end; - break; - case 'g': case 'G': - unit = 1024*1024*1024; - ++end; - break; - } - while (*end && isspace((unsigned char)*end)) end++; - if (*end) { - if (RTEST(ruby_verbose)) fprintf(stderr, "invalid string for %s: %s\n", name, ptr); - return 0; - } - if (unit > 0) { - if (val < -(ssize_t)(SIZE_MAX / 2 / unit) || (ssize_t)(SIZE_MAX / 2 / unit) < val) { - if (RTEST(ruby_verbose)) fprintf(stderr, "%s=%s is ignored because it overflows\n", name, ptr); - return 0; - } - val *= unit; - } - if (val > 0 && (size_t)val > lower_bound) { - if (RTEST(ruby_verbose)) { - fprintf(stderr, "%s=%"PRIdSIZE" (default value: %"PRIuSIZE")\n", name, val, *default_value); - } - *default_value = (size_t)val; - return 1; - } - else { - if (RTEST(ruby_verbose)) { - fprintf(stderr, "%s=%"PRIdSIZE" (default value: %"PRIuSIZE") is ignored because it must be greater than %"PRIuSIZE".\n", - name, val, *default_value, lower_bound); - } - return 0; - } + switch (*end) { + case 'k': case 'K': + unit = 1024; + ++end; + break; + case 'm': case 'M': + unit = 1024*1024; + ++end; + break; + case 'g': case 'G': + unit = 1024*1024*1024; + ++end; + break; + } + while (*end && isspace((unsigned char)*end)) end++; + if (*end) { + if (RTEST(ruby_verbose)) fprintf(stderr, "invalid string for %s: %s\n", name, ptr); + return 0; + } + if (unit > 0) { + if (val < -(ssize_t)(SIZE_MAX / 2 / unit) || (ssize_t)(SIZE_MAX / 2 / unit) < val) { + if (RTEST(ruby_verbose)) fprintf(stderr, "%s=%s is ignored because it overflows\n", name, ptr); + return 0; + } + val *= unit; + } + if (val > 0 && (size_t)val > lower_bound) { + if (RTEST(ruby_verbose)) { + fprintf(stderr, "%s=%"PRIdSIZE" (default value: %"PRIuSIZE")\n", name, val, *default_value); + } + *default_value = (size_t)val; + return 1; + } + else { + if (RTEST(ruby_verbose)) { + fprintf(stderr, "%s=%"PRIdSIZE" (default value: %"PRIuSIZE") is ignored because it must be greater than %"PRIuSIZE".\n", + name, val, *default_value, lower_bound); + } + return 0; + } } return 0; } @@ -11536,32 +11536,32 @@ get_envparam_double(const char *name, double *default_value, double lower_bound, double val; if (ptr != NULL && *ptr) { - char *end; - val = strtod(ptr, &end); - if (!*ptr || *end) { - if (RTEST(ruby_verbose)) fprintf(stderr, "invalid string for %s: %s\n", name, ptr); - return 0; - } + char *end; + val = strtod(ptr, &end); + if (!*ptr || *end) { + if (RTEST(ruby_verbose)) fprintf(stderr, "invalid string for %s: %s\n", name, ptr); + return 0; + } - if (accept_zero && val == 0.0) { - goto accept; - } - else if (val <= lower_bound) { - if (RTEST(ruby_verbose)) { - fprintf(stderr, "%s=%f (default value: %f) is ignored because it must be greater than %f.\n", - name, val, *default_value, lower_bound); - } - } - else if (upper_bound != 0.0 && /* ignore upper_bound if it is 0.0 */ - val > upper_bound) { - if (RTEST(ruby_verbose)) { - fprintf(stderr, "%s=%f (default value: %f) is ignored because it must be lower than %f.\n", - name, val, *default_value, upper_bound); - } - } - else { + if (accept_zero && val == 0.0) { goto accept; - } + } + else if (val <= lower_bound) { + if (RTEST(ruby_verbose)) { + fprintf(stderr, "%s=%f (default value: %f) is ignored because it must be greater than %f.\n", + name, val, *default_value, lower_bound); + } + } + else if (upper_bound != 0.0 && /* ignore upper_bound if it is 0.0 */ + val > upper_bound) { + if (RTEST(ruby_verbose)) { + fprintf(stderr, "%s=%f (default value: %f) is ignored because it must be lower than %f.\n", + name, val, *default_value, upper_bound); + } + } + else { + goto accept; + } } return 0; @@ -11640,26 +11640,26 @@ ruby_gc_set_params(void) rb_objspace_t *objspace = &rb_objspace; /* RUBY_GC_HEAP_FREE_SLOTS */ if (get_envparam_size("RUBY_GC_HEAP_FREE_SLOTS", &gc_params.heap_free_slots, 0)) { - /* ok */ + /* ok */ } /* RUBY_GC_HEAP_INIT_SLOTS */ if (get_envparam_size("RUBY_GC_HEAP_INIT_SLOTS", &gc_params.heap_init_slots, 0)) { - gc_set_initial_pages(); + gc_set_initial_pages(); } get_envparam_double("RUBY_GC_HEAP_GROWTH_FACTOR", &gc_params.growth_factor, 1.0, 0.0, FALSE); get_envparam_size ("RUBY_GC_HEAP_GROWTH_MAX_SLOTS", &gc_params.growth_max_slots, 0); get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_MIN_RATIO", &gc_params.heap_free_slots_min_ratio, - 0.0, 1.0, FALSE); + 0.0, 1.0, FALSE); get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_MAX_RATIO", &gc_params.heap_free_slots_max_ratio, - gc_params.heap_free_slots_min_ratio, 1.0, FALSE); + gc_params.heap_free_slots_min_ratio, 1.0, FALSE); get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_GOAL_RATIO", &gc_params.heap_free_slots_goal_ratio, - gc_params.heap_free_slots_min_ratio, gc_params.heap_free_slots_max_ratio, TRUE); + gc_params.heap_free_slots_min_ratio, gc_params.heap_free_slots_max_ratio, TRUE); get_envparam_double("RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR", &gc_params.oldobject_limit_factor, 0.0, 0.0, TRUE); if (get_envparam_size("RUBY_GC_MALLOC_LIMIT", &gc_params.malloc_limit_min, 0)) { - malloc_limit = gc_params.malloc_limit_min; + malloc_limit = gc_params.malloc_limit_min; } get_envparam_size ("RUBY_GC_MALLOC_LIMIT_MAX", &gc_params.malloc_limit_max, 0); if (!gc_params.malloc_limit_max) { /* ignore max-check if 0 */ @@ -11669,7 +11669,7 @@ ruby_gc_set_params(void) #if RGENGC_ESTIMATE_OLDMALLOC if (get_envparam_size("RUBY_GC_OLDMALLOC_LIMIT", &gc_params.oldmalloc_limit_min, 0)) { - objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min; + objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min; } get_envparam_size ("RUBY_GC_OLDMALLOC_LIMIT_MAX", &gc_params.oldmalloc_limit_max, 0); get_envparam_double("RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR", &gc_params.oldmalloc_limit_growth_factor, 1.0, 0.0, FALSE); @@ -11813,16 +11813,16 @@ static void ruby_memerror(void) { if (ruby_thread_has_gvl_p()) { - rb_memerror(); + rb_memerror(); } else { - if (ruby_native_thread_p()) { - rb_thread_call_with_gvl(ruby_memerror_body, 0); - } - else { - /* no ruby thread */ - fprintf(stderr, "[FATAL] failed to allocate memory\n"); - } + if (ruby_native_thread_p()) { + rb_thread_call_with_gvl(ruby_memerror_body, 0); + } + else { + /* no ruby thread */ + fprintf(stderr, "[FATAL] failed to allocate memory\n"); + } } exit(EXIT_FAILURE); } @@ -11847,16 +11847,16 @@ rb_memerror(void) exc = nomem_error; if (!exc || - rb_ec_raised_p(ec, RAISED_NOMEMORY)) { - fprintf(stderr, "[FATAL] failed to allocate memory\n"); - exit(EXIT_FAILURE); + rb_ec_raised_p(ec, RAISED_NOMEMORY)) { + fprintf(stderr, "[FATAL] failed to allocate memory\n"); + exit(EXIT_FAILURE); } if (rb_ec_raised_p(ec, RAISED_NOMEMORY)) { - rb_ec_raised_clear(ec); + rb_ec_raised_clear(ec); } else { - rb_ec_raised_set(ec, RAISED_NOMEMORY); - exc = ruby_vm_special_exception_copy(exc); + rb_ec_raised_set(ec, RAISED_NOMEMORY); + exc = ruby_vm_special_exception_copy(exc); } ec->errinfo = exc; EC_JUMP_TAG(ec, TAG_RAISE); @@ -11932,9 +11932,9 @@ atomic_sub_nounderflow(size_t *var, size_t sub) if (sub == 0) return; while (1) { - size_t val = *var; - if (val < sub) sub = val; - if (ATOMIC_SIZE_CAS(*var, val, val-sub) == val) break; + size_t val = *var; + if (val < sub) sub = val; + if (ATOMIC_SIZE_CAS(*var, val, val-sub) == val) break; } } @@ -11956,11 +11956,11 @@ static inline bool objspace_malloc_increase_report(rb_objspace_t *objspace, void *mem, size_t new_size, size_t old_size, enum memop_type type) { if (0) fprintf(stderr, "increase - ptr: %p, type: %s, new_size: %"PRIdSIZE", old_size: %"PRIdSIZE"\n", - mem, - type == MEMOP_TYPE_MALLOC ? "malloc" : - type == MEMOP_TYPE_FREE ? "free " : - type == MEMOP_TYPE_REALLOC ? "realloc": "error", - new_size, old_size); + mem, + type == MEMOP_TYPE_MALLOC ? "malloc" : + type == MEMOP_TYPE_FREE ? "free " : + type == MEMOP_TYPE_REALLOC ? "realloc": "error", + new_size, old_size); return false; } @@ -11968,62 +11968,62 @@ static bool objspace_malloc_increase_body(rb_objspace_t *objspace, void *mem, size_t new_size, size_t old_size, enum memop_type type) { if (new_size > old_size) { - ATOMIC_SIZE_ADD(malloc_increase, new_size - old_size); + ATOMIC_SIZE_ADD(malloc_increase, new_size - old_size); #if RGENGC_ESTIMATE_OLDMALLOC - ATOMIC_SIZE_ADD(objspace->rgengc.oldmalloc_increase, new_size - old_size); + ATOMIC_SIZE_ADD(objspace->rgengc.oldmalloc_increase, new_size - old_size); #endif } else { - atomic_sub_nounderflow(&malloc_increase, old_size - new_size); + atomic_sub_nounderflow(&malloc_increase, old_size - new_size); #if RGENGC_ESTIMATE_OLDMALLOC - atomic_sub_nounderflow(&objspace->rgengc.oldmalloc_increase, old_size - new_size); + atomic_sub_nounderflow(&objspace->rgengc.oldmalloc_increase, old_size - new_size); #endif } if (type == MEMOP_TYPE_MALLOC) { retry: - if (malloc_increase > malloc_limit && ruby_native_thread_p() && !dont_gc_val()) { - if (ruby_thread_has_gvl_p() && is_lazy_sweeping(objspace)) { - gc_rest(objspace); /* gc_rest can reduce malloc_increase */ - goto retry; - } - garbage_collect_with_gvl(objspace, GPR_FLAG_MALLOC); - } + if (malloc_increase > malloc_limit && ruby_native_thread_p() && !dont_gc_val()) { + if (ruby_thread_has_gvl_p() && is_lazy_sweeping(objspace)) { + gc_rest(objspace); /* gc_rest can reduce malloc_increase */ + goto retry; + } + garbage_collect_with_gvl(objspace, GPR_FLAG_MALLOC); + } } #if MALLOC_ALLOCATED_SIZE if (new_size >= old_size) { - ATOMIC_SIZE_ADD(objspace->malloc_params.allocated_size, new_size - old_size); + ATOMIC_SIZE_ADD(objspace->malloc_params.allocated_size, new_size - old_size); } else { - size_t dec_size = old_size - new_size; - size_t allocated_size = objspace->malloc_params.allocated_size; + size_t dec_size = old_size - new_size; + size_t allocated_size = objspace->malloc_params.allocated_size; #if MALLOC_ALLOCATED_SIZE_CHECK - if (allocated_size < dec_size) { - rb_bug("objspace_malloc_increase: underflow malloc_params.allocated_size."); - } + if (allocated_size < dec_size) { + rb_bug("objspace_malloc_increase: underflow malloc_params.allocated_size."); + } #endif - atomic_sub_nounderflow(&objspace->malloc_params.allocated_size, dec_size); + atomic_sub_nounderflow(&objspace->malloc_params.allocated_size, dec_size); } switch (type) { case MEMOP_TYPE_MALLOC: - ATOMIC_SIZE_INC(objspace->malloc_params.allocations); - break; + ATOMIC_SIZE_INC(objspace->malloc_params.allocations); + break; case MEMOP_TYPE_FREE: - { - size_t allocations = objspace->malloc_params.allocations; - if (allocations > 0) { - atomic_sub_nounderflow(&objspace->malloc_params.allocations, 1); - } + { + size_t allocations = objspace->malloc_params.allocations; + if (allocations > 0) { + atomic_sub_nounderflow(&objspace->malloc_params.allocations, 1); + } #if MALLOC_ALLOCATED_SIZE_CHECK - else { - GC_ASSERT(objspace->malloc_params.allocations > 0); - } + else { + GC_ASSERT(objspace->malloc_params.allocations > 0); + } #endif - } - break; + } + break; case MEMOP_TYPE_REALLOC: /* ignore */ break; } #endif @@ -12032,8 +12032,8 @@ objspace_malloc_increase_body(rb_objspace_t *objspace, void *mem, size_t new_siz #define objspace_malloc_increase(...) \ for (bool malloc_increase_done = objspace_malloc_increase_report(__VA_ARGS__); \ - !malloc_increase_done; \ - malloc_increase_done = objspace_malloc_increase_body(__VA_ARGS__)) + !malloc_increase_done; \ + malloc_increase_done = objspace_malloc_increase_body(__VA_ARGS__)) struct malloc_obj_info { /* 4 words */ size_t size; @@ -12115,13 +12115,13 @@ objspace_malloc_fixup(rb_objspace_t *objspace, void *mem, size_t size) #else #define TRY_WITH_GC(siz, alloc) do { \ objspace_malloc_gc_stress(objspace); \ - if (!(alloc) && \ + if (!(alloc) && \ (!garbage_collect_with_gvl(objspace, GPR_FLAG_FULL_MARK | \ GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP | \ GPR_FLAG_MALLOC) || \ - !(alloc))) { \ - ruby_memerror(); \ - } \ + !(alloc))) { \ + ruby_memerror(); \ + } \ } while (0) #endif @@ -12347,8 +12347,8 @@ objspace_xfree(rb_objspace_t *objspace, void *ptr, size_t old_size) old_size = objspace_malloc_size(objspace, ptr, old_size); objspace_malloc_increase(objspace, ptr, 0, old_size, MEMOP_TYPE_FREE) { - free(ptr); - RB_DEBUG_COUNTER_INC(heap_xfree); + free(ptr); + RB_DEBUG_COUNTER_INC(heap_xfree); } } @@ -12362,7 +12362,7 @@ void * ruby_xmalloc_body(size_t size) { if ((ssize_t)size < 0) { - negative_size_allocation_error("too large allocation size"); + negative_size_allocation_error("too large allocation size"); } return ruby_xmalloc0(size); } @@ -12371,8 +12371,8 @@ void ruby_malloc_size_overflow(size_t count, size_t elsize) { rb_raise(rb_eArgError, - "malloc: possible integer overflow (%"PRIuSIZE"*%"PRIuSIZE")", - count, elsize); + "malloc: possible integer overflow (%"PRIuSIZE"*%"PRIuSIZE")", + count, elsize); } void * @@ -12404,7 +12404,7 @@ void * ruby_sized_xrealloc(void *ptr, size_t new_size, size_t old_size) { if ((ssize_t)new_size < 0) { - negative_size_allocation_error("too large allocation size"); + negative_size_allocation_error("too large allocation size"); } return objspace_xrealloc(&rb_objspace, ptr, new_size, old_size); @@ -12439,7 +12439,7 @@ void ruby_sized_xfree(void *x, size_t size) { if (x) { - objspace_xfree(&rb_objspace, x, size); + objspace_xfree(&rb_objspace, x, size); } } @@ -12549,7 +12549,7 @@ rb_alloc_tmp_buffer(volatile VALUE *store, long len) long cnt; if (len < 0 || (cnt = (long)roomof(len, sizeof(VALUE))) < 0) { - rb_raise(rb_eArgError, "negative buffer size (or size too big)"); + rb_raise(rb_eArgError, "negative buffer size (or size too big)"); } return rb_alloc_tmp_buffer_with_count(store, len, cnt); @@ -12560,9 +12560,9 @@ rb_free_tmp_buffer(volatile VALUE *store) { rb_imemo_tmpbuf_t *s = (rb_imemo_tmpbuf_t*)ATOMIC_VALUE_EXCHANGE(*store, 0); if (s) { - void *ptr = ATOMIC_PTR_EXCHANGE(s->ptr, 0); - s->cnt = 0; - ruby_xfree(ptr); + void *ptr = ATOMIC_PTR_EXCHANGE(s->ptr, 0); + s->cnt = 0; + ruby_xfree(ptr); } } @@ -12603,10 +12603,10 @@ rb_gc_adjust_memory_usage(ssize_t diff) { rb_objspace_t *objspace = &rb_objspace; if (diff > 0) { - objspace_malloc_increase(objspace, 0, diff, 0, MEMOP_TYPE_REALLOC); + objspace_malloc_increase(objspace, 0, diff, 0, MEMOP_TYPE_REALLOC); } else if (diff < 0) { - objspace_malloc_increase(objspace, 0, 0, -diff, MEMOP_TYPE_REALLOC); + objspace_malloc_increase(objspace, 0, 0, -diff, MEMOP_TYPE_REALLOC); } } @@ -12692,9 +12692,9 @@ wmap_memsize(const void *ptr) static const rb_data_type_t weakmap_type = { "weakmap", { - wmap_mark, - wmap_free, - wmap_memsize, + wmap_mark, + wmap_free, + wmap_memsize, wmap_compact, }, 0, 0, RUBY_TYPED_FREE_IMMEDIATELY @@ -12741,18 +12741,18 @@ wmap_final_func(st_data_t *key, st_data_t *value, st_data_t arg, int existing) if (!existing) return ST_STOP; wmap = (VALUE)arg, ptr = (VALUE *)*value; for (i = j = 1, size = ptr[0]; i <= size; ++i) { - if (ptr[i] != wmap) { - ptr[j++] = ptr[i]; - } + if (ptr[i] != wmap) { + ptr[j++] = ptr[i]; + } } if (j == 1) { - ruby_sized_xfree(ptr, i * sizeof(VALUE)); - return ST_DELETE; + ruby_sized_xfree(ptr, i * sizeof(VALUE)); + return ST_DELETE; } if (j < i) { SIZED_REALLOC_N(ptr, VALUE, j + 1, i); - ptr[0] = j; - *value = (st_data_t)ptr; + ptr[0] = j; + *value = (st_data_t)ptr; } return ST_CONTINUE; } @@ -12774,19 +12774,19 @@ wmap_finalize(RB_BLOCK_CALL_FUNC_ARGLIST(objid, self)) /* obj is original referenced object and/or weak reference. */ orig = (st_data_t)obj; if (st_delete(w->obj2wmap, &orig, &data)) { - rids = (VALUE *)data; - size = *rids++; - for (i = 0; i < size; ++i) { - wmap = (st_data_t)rids[i]; - st_delete(w->wmap2obj, &wmap, NULL); - } - ruby_sized_xfree((VALUE *)data, (size + 1) * sizeof(VALUE)); + rids = (VALUE *)data; + size = *rids++; + for (i = 0; i < size; ++i) { + wmap = (st_data_t)rids[i]; + st_delete(w->wmap2obj, &wmap, NULL); + } + ruby_sized_xfree((VALUE *)data, (size + 1) * sizeof(VALUE)); } wmap = (st_data_t)obj; if (st_delete(w->wmap2obj, &wmap, &orig)) { - wmap = (st_data_t)obj; - st_update(w->obj2wmap, orig, wmap_final_func, wmap); + wmap = (st_data_t)obj; + st_update(w->obj2wmap, orig, wmap_final_func, wmap); } return self; } @@ -12819,11 +12819,11 @@ wmap_inspect_i(st_data_t key, st_data_t val, st_data_t arg) VALUE k = (VALUE)key, v = (VALUE)val; if (RSTRING_PTR(str)[0] == '#') { - rb_str_cat2(str, ", "); + rb_str_cat2(str, ", "); } else { - rb_str_cat2(str, ": "); - RSTRING_PTR(str)[0] = '#'; + rb_str_cat2(str, ": "); + RSTRING_PTR(str)[0] = '#'; } wmap_inspect_append(objspace, str, k); rb_str_cat2(str, " => "); @@ -12843,9 +12843,9 @@ wmap_inspect(VALUE self) TypedData_Get_Struct(self, struct weakmap, &weakmap_type, w); str = rb_sprintf("-<%"PRIsVALUE":%p", c, (void *)self); if (w->wmap2obj) { - args.objspace = &rb_objspace; - args.value = str; - st_foreach(w->wmap2obj, wmap_inspect_i, (st_data_t)&args); + args.objspace = &rb_objspace; + args.value = str; + st_foreach(w->wmap2obj, wmap_inspect_i, (st_data_t)&args); } RSTRING_PTR(str)[0] = '#'; rb_str_cat2(str, ">"); @@ -13001,14 +13001,14 @@ wmap_aset_update(st_data_t *key, st_data_t *val, st_data_t arg, int existing) { VALUE size, *ptr, *optr; if (existing) { - size = (ptr = optr = (VALUE *)*val)[0]; - ++size; + size = (ptr = optr = (VALUE *)*val)[0]; + ++size; SIZED_REALLOC_N(ptr, VALUE, size + 1, size); } else { - optr = 0; - size = 1; - ptr = ruby_xmalloc0(2 * sizeof(VALUE)); + optr = 0; + size = 1; + ptr = ruby_xmalloc0(2 * sizeof(VALUE)); } ptr[0] = size; ptr[size] = (VALUE)arg; @@ -13120,17 +13120,17 @@ current_process_time(struct timespec *ts) #ifdef _WIN32 { - FILETIME creation_time, exit_time, kernel_time, user_time; + FILETIME creation_time, exit_time, kernel_time, user_time; ULARGE_INTEGER ui; if (GetProcessTimes(GetCurrentProcess(), - &creation_time, &exit_time, &kernel_time, &user_time) != 0) { + &creation_time, &exit_time, &kernel_time, &user_time) != 0) { memcpy(&ui, &user_time, sizeof(FILETIME)); #define PER100NSEC (uint64_t)(1000 * 1000 * 10) ts->tv_nsec = (long)(ui.QuadPart % PER100NSEC); ts->tv_sec = (time_t)(ui.QuadPart / PER100NSEC); return true; - } + } } #endif @@ -13154,44 +13154,44 @@ static inline void gc_prof_setup_new_record(rb_objspace_t *objspace, unsigned int reason) { if (objspace->profile.run) { - size_t index = objspace->profile.next_index; - gc_profile_record *record; + size_t index = objspace->profile.next_index; + gc_profile_record *record; - /* create new record */ - objspace->profile.next_index++; + /* create new record */ + objspace->profile.next_index++; - if (!objspace->profile.records) { - objspace->profile.size = GC_PROFILE_RECORD_DEFAULT_SIZE; - objspace->profile.records = malloc(xmalloc2_size(sizeof(gc_profile_record), objspace->profile.size)); - } - if (index >= objspace->profile.size) { - void *ptr; - objspace->profile.size += 1000; - ptr = realloc(objspace->profile.records, xmalloc2_size(sizeof(gc_profile_record), objspace->profile.size)); - if (!ptr) rb_memerror(); - objspace->profile.records = ptr; - } - if (!objspace->profile.records) { - rb_bug("gc_profile malloc or realloc miss"); - } - record = objspace->profile.current_record = &objspace->profile.records[objspace->profile.next_index - 1]; - MEMZERO(record, gc_profile_record, 1); + if (!objspace->profile.records) { + objspace->profile.size = GC_PROFILE_RECORD_DEFAULT_SIZE; + objspace->profile.records = malloc(xmalloc2_size(sizeof(gc_profile_record), objspace->profile.size)); + } + if (index >= objspace->profile.size) { + void *ptr; + objspace->profile.size += 1000; + ptr = realloc(objspace->profile.records, xmalloc2_size(sizeof(gc_profile_record), objspace->profile.size)); + if (!ptr) rb_memerror(); + objspace->profile.records = ptr; + } + if (!objspace->profile.records) { + rb_bug("gc_profile malloc or realloc miss"); + } + record = objspace->profile.current_record = &objspace->profile.records[objspace->profile.next_index - 1]; + MEMZERO(record, gc_profile_record, 1); - /* setup before-GC parameter */ - record->flags = reason | (ruby_gc_stressful ? GPR_FLAG_STRESS : 0); + /* setup before-GC parameter */ + record->flags = reason | (ruby_gc_stressful ? GPR_FLAG_STRESS : 0); #if MALLOC_ALLOCATED_SIZE - record->allocated_size = malloc_allocated_size; + record->allocated_size = malloc_allocated_size; #endif #if GC_PROFILE_MORE_DETAIL && GC_PROFILE_DETAIL_MEMORY #ifdef RUSAGE_SELF - { - struct rusage usage; - if (getrusage(RUSAGE_SELF, &usage) == 0) { - record->maxrss = usage.ru_maxrss; - record->minflt = usage.ru_minflt; - record->majflt = usage.ru_majflt; - } - } + { + struct rusage usage; + if (getrusage(RUSAGE_SELF, &usage) == 0) { + record->maxrss = usage.ru_maxrss; + record->minflt = usage.ru_minflt; + record->majflt = usage.ru_majflt; + } + } #endif #endif } @@ -13201,12 +13201,12 @@ static inline void gc_prof_timer_start(rb_objspace_t *objspace) { if (gc_prof_enabled(objspace)) { - gc_profile_record *record = gc_prof_record(objspace); + gc_profile_record *record = gc_prof_record(objspace); #if GC_PROFILE_MORE_DETAIL - record->prepare_time = objspace->profile.prepare_time; + record->prepare_time = objspace->profile.prepare_time; #endif - record->gc_time = 0; - record->gc_invoke_time = getrusage_time(); + record->gc_time = 0; + record->gc_invoke_time = getrusage_time(); } } @@ -13215,10 +13215,10 @@ elapsed_time_from(double time) { double now = getrusage_time(); if (now > time) { - return now - time; + return now - time; } else { - return 0; + return 0; } } @@ -13226,9 +13226,9 @@ static inline void gc_prof_timer_stop(rb_objspace_t *objspace) { if (gc_prof_enabled(objspace)) { - gc_profile_record *record = gc_prof_record(objspace); - record->gc_time = elapsed_time_from(record->gc_invoke_time); - record->gc_invoke_time -= objspace->profile.invoke_time; + gc_profile_record *record = gc_prof_record(objspace); + record->gc_time = elapsed_time_from(record->gc_invoke_time); + record->gc_invoke_time -= objspace->profile.invoke_time; } } @@ -13240,7 +13240,7 @@ gc_prof_mark_timer_start(rb_objspace_t *objspace) RUBY_DTRACE_GC_HOOK(MARK_BEGIN); #if GC_PROFILE_MORE_DETAIL if (gc_prof_enabled(objspace)) { - gc_prof_record(objspace)->gc_mark_time = getrusage_time(); + gc_prof_record(objspace)->gc_mark_time = getrusage_time(); } #endif } @@ -13252,7 +13252,7 @@ gc_prof_mark_timer_stop(rb_objspace_t *objspace) #if GC_PROFILE_MORE_DETAIL if (gc_prof_enabled(objspace)) { gc_profile_record *record = gc_prof_record(objspace); - record->gc_mark_time = elapsed_time_from(record->gc_mark_time); + record->gc_mark_time = elapsed_time_from(record->gc_mark_time); } #endif } @@ -13262,11 +13262,11 @@ gc_prof_sweep_timer_start(rb_objspace_t *objspace) { RUBY_DTRACE_GC_HOOK(SWEEP_BEGIN); if (gc_prof_enabled(objspace)) { - gc_profile_record *record = gc_prof_record(objspace); + gc_profile_record *record = gc_prof_record(objspace); - if (record->gc_time > 0 || GC_PROFILE_MORE_DETAIL) { - objspace->profile.gc_sweep_start_time = getrusage_time(); - } + if (record->gc_time > 0 || GC_PROFILE_MORE_DETAIL) { + objspace->profile.gc_sweep_start_time = getrusage_time(); + } } } @@ -13276,23 +13276,23 @@ gc_prof_sweep_timer_stop(rb_objspace_t *objspace) RUBY_DTRACE_GC_HOOK(SWEEP_END); if (gc_prof_enabled(objspace)) { - double sweep_time; - gc_profile_record *record = gc_prof_record(objspace); + double sweep_time; + gc_profile_record *record = gc_prof_record(objspace); - if (record->gc_time > 0) { - sweep_time = elapsed_time_from(objspace->profile.gc_sweep_start_time); - /* need to accumulate GC time for lazy sweep after gc() */ - record->gc_time += sweep_time; - } - else if (GC_PROFILE_MORE_DETAIL) { - sweep_time = elapsed_time_from(objspace->profile.gc_sweep_start_time); - } + if (record->gc_time > 0) { + sweep_time = elapsed_time_from(objspace->profile.gc_sweep_start_time); + /* need to accumulate GC time for lazy sweep after gc() */ + record->gc_time += sweep_time; + } + else if (GC_PROFILE_MORE_DETAIL) { + sweep_time = elapsed_time_from(objspace->profile.gc_sweep_start_time); + } #if GC_PROFILE_MORE_DETAIL - record->gc_sweep_time += sweep_time; - if (heap_pages_deferred_final) record->flags |= GPR_FLAG_HAVE_FINALIZE; + record->gc_sweep_time += sweep_time; + if (heap_pages_deferred_final) record->flags |= GPR_FLAG_HAVE_FINALIZE; #endif - if (heap_pages_deferred_final) objspace->profile.latest_gc_info |= GPR_FLAG_HAVE_FINALIZE; + if (heap_pages_deferred_final) objspace->profile.latest_gc_info |= GPR_FLAG_HAVE_FINALIZE; } } @@ -13302,8 +13302,8 @@ gc_prof_set_malloc_info(rb_objspace_t *objspace) #if GC_PROFILE_MORE_DETAIL if (gc_prof_enabled(objspace)) { gc_profile_record *record = gc_prof_record(objspace); - record->allocate_increase = malloc_increase; - record->allocate_limit = malloc_limit; + record->allocate_increase = malloc_increase; + record->allocate_limit = malloc_limit; } #endif } @@ -13312,19 +13312,19 @@ static inline void gc_prof_set_heap_info(rb_objspace_t *objspace) { if (gc_prof_enabled(objspace)) { - gc_profile_record *record = gc_prof_record(objspace); - size_t live = objspace->profile.total_allocated_objects_at_gc_start - objspace->profile.total_freed_objects; - size_t total = objspace->profile.heap_used_at_gc_start * HEAP_PAGE_OBJ_LIMIT; + gc_profile_record *record = gc_prof_record(objspace); + size_t live = objspace->profile.total_allocated_objects_at_gc_start - objspace->profile.total_freed_objects; + size_t total = objspace->profile.heap_used_at_gc_start * HEAP_PAGE_OBJ_LIMIT; #if GC_PROFILE_MORE_DETAIL - record->heap_use_pages = objspace->profile.heap_used_at_gc_start; - record->heap_live_objects = live; - record->heap_free_objects = total - live; + record->heap_use_pages = objspace->profile.heap_used_at_gc_start; + record->heap_live_objects = live; + record->heap_free_objects = total - live; #endif - record->heap_total_objects = total; - record->heap_use_size = live * sizeof(RVALUE); - record->heap_total_size = total * sizeof(RVALUE); + record->heap_total_objects = total; + record->heap_use_size = live * sizeof(RVALUE); + record->heap_total_size = total * sizeof(RVALUE); } } @@ -13410,14 +13410,14 @@ gc_profile_record_get(VALUE _) rb_objspace_t *objspace = (&rb_objspace); if (!objspace->profile.run) { - return Qnil; + return Qnil; } for (i =0; i < objspace->profile.next_index; i++) { - gc_profile_record *record = &objspace->profile.records[i]; + gc_profile_record *record = &objspace->profile.records[i]; - prof = rb_hash_new(); - rb_hash_aset(prof, ID2SYM(rb_intern("GC_FLAGS")), gc_info_decode(0, rb_hash_new(), record->flags)); + prof = rb_hash_new(); + rb_hash_aset(prof, ID2SYM(rb_intern("GC_FLAGS")), gc_info_decode(0, rb_hash_new(), record->flags)); rb_hash_aset(prof, ID2SYM(rb_intern("GC_TIME")), DBL2NUM(record->gc_time)); rb_hash_aset(prof, ID2SYM(rb_intern("GC_INVOKE_TIME")), DBL2NUM(record->gc_invoke_time)); rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_SIZE")), SIZET2NUM(record->heap_use_size)); @@ -13434,18 +13434,18 @@ gc_profile_record_get(VALUE _) rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_LIVE_OBJECTS")), SIZET2NUM(record->heap_live_objects)); rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_FREE_OBJECTS")), SIZET2NUM(record->heap_free_objects)); - rb_hash_aset(prof, ID2SYM(rb_intern("REMOVING_OBJECTS")), SIZET2NUM(record->removing_objects)); - rb_hash_aset(prof, ID2SYM(rb_intern("EMPTY_OBJECTS")), SIZET2NUM(record->empty_objects)); + rb_hash_aset(prof, ID2SYM(rb_intern("REMOVING_OBJECTS")), SIZET2NUM(record->removing_objects)); + rb_hash_aset(prof, ID2SYM(rb_intern("EMPTY_OBJECTS")), SIZET2NUM(record->empty_objects)); - rb_hash_aset(prof, ID2SYM(rb_intern("HAVE_FINALIZE")), RBOOL(record->flags & GPR_FLAG_HAVE_FINALIZE)); + rb_hash_aset(prof, ID2SYM(rb_intern("HAVE_FINALIZE")), RBOOL(record->flags & GPR_FLAG_HAVE_FINALIZE)); #endif #if RGENGC_PROFILE > 0 - rb_hash_aset(prof, ID2SYM(rb_intern("OLD_OBJECTS")), SIZET2NUM(record->old_objects)); - rb_hash_aset(prof, ID2SYM(rb_intern("REMEMBERED_NORMAL_OBJECTS")), SIZET2NUM(record->remembered_normal_objects)); - rb_hash_aset(prof, ID2SYM(rb_intern("REMEMBERED_SHADY_OBJECTS")), SIZET2NUM(record->remembered_shady_objects)); + rb_hash_aset(prof, ID2SYM(rb_intern("OLD_OBJECTS")), SIZET2NUM(record->old_objects)); + rb_hash_aset(prof, ID2SYM(rb_intern("REMEMBERED_NORMAL_OBJECTS")), SIZET2NUM(record->remembered_normal_objects)); + rb_hash_aset(prof, ID2SYM(rb_intern("REMEMBERED_SHADY_OBJECTS")), SIZET2NUM(record->remembered_shady_objects)); #endif - rb_ary_push(gc_profile, prof); + rb_ary_push(gc_profile, prof); } return gc_profile; @@ -13461,8 +13461,8 @@ gc_profile_dump_major_reason(unsigned int flags, char *buff) int i = 0; if (reason == GPR_FLAG_NONE) { - buff[0] = '-'; - buff[1] = 0; + buff[0] = '-'; + buff[1] = 0; } else { #define C(x, s) \ @@ -13471,11 +13471,11 @@ gc_profile_dump_major_reason(unsigned int flags, char *buff) if (i >= MAJOR_REASON_MAX) rb_bug("gc_profile_dump_major_reason: overflow"); \ buff[i] = 0; \ } - C(NOFREE, N); - C(OLDGEN, O); - C(SHADY, S); + C(NOFREE, N); + C(OLDGEN, O); + C(SHADY, S); #if RGENGC_ESTIMATE_OLDMALLOC - C(OLDMALLOC, M); + C(OLDMALLOC, M); #endif #undef C } @@ -13493,88 +13493,88 @@ gc_profile_dump_on(VALUE out, VALUE (*append)(VALUE, VALUE)) #endif if (objspace->profile.run && count /* > 1 */) { - size_t i; - const gc_profile_record *record; + size_t i; + const gc_profile_record *record; - append(out, rb_sprintf("GC %"PRIuSIZE" invokes.\n", objspace->profile.count)); - append(out, rb_str_new_cstr("Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC Time(ms)\n")); + append(out, rb_sprintf("GC %"PRIuSIZE" invokes.\n", objspace->profile.count)); + append(out, rb_str_new_cstr("Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC Time(ms)\n")); - for (i = 0; i < count; i++) { - record = &objspace->profile.records[i]; - append(out, rb_sprintf("%5"PRIuSIZE" %19.3f %20"PRIuSIZE" %20"PRIuSIZE" %20"PRIuSIZE" %30.20f\n", - i+1, record->gc_invoke_time, record->heap_use_size, - record->heap_total_size, record->heap_total_objects, record->gc_time*1000)); - } + for (i = 0; i < count; i++) { + record = &objspace->profile.records[i]; + append(out, rb_sprintf("%5"PRIuSIZE" %19.3f %20"PRIuSIZE" %20"PRIuSIZE" %20"PRIuSIZE" %30.20f\n", + i+1, record->gc_invoke_time, record->heap_use_size, + record->heap_total_size, record->heap_total_objects, record->gc_time*1000)); + } #if GC_PROFILE_MORE_DETAIL const char *str = "\n\n" \ - "More detail.\n" \ - "Prepare Time = Previously GC's rest sweep time\n" - "Index Flags Allocate Inc. Allocate Limit" + "More detail.\n" \ + "Prepare Time = Previously GC's rest sweep time\n" + "Index Flags Allocate Inc. Allocate Limit" #if CALC_EXACT_MALLOC_SIZE - " Allocated Size" + " Allocated Size" #endif - " Use Page Mark Time(ms) Sweep Time(ms) Prepare Time(ms) LivingObj FreeObj RemovedObj EmptyObj" + " Use Page Mark Time(ms) Sweep Time(ms) Prepare Time(ms) LivingObj FreeObj RemovedObj EmptyObj" #if RGENGC_PROFILE - " OldgenObj RemNormObj RemShadObj" + " OldgenObj RemNormObj RemShadObj" #endif #if GC_PROFILE_DETAIL_MEMORY - " MaxRSS(KB) MinorFLT MajorFLT" + " MaxRSS(KB) MinorFLT MajorFLT" #endif "\n"; append(out, rb_str_new_cstr(str)); - for (i = 0; i < count; i++) { - record = &objspace->profile.records[i]; - append(out, rb_sprintf("%5"PRIuSIZE" %4s/%c/%6s%c %13"PRIuSIZE" %15"PRIuSIZE + for (i = 0; i < count; i++) { + record = &objspace->profile.records[i]; + append(out, rb_sprintf("%5"PRIuSIZE" %4s/%c/%6s%c %13"PRIuSIZE" %15"PRIuSIZE #if CALC_EXACT_MALLOC_SIZE - " %15"PRIuSIZE + " %15"PRIuSIZE #endif - " %9"PRIuSIZE" %17.12f %17.12f %17.12f %10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE + " %9"PRIuSIZE" %17.12f %17.12f %17.12f %10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE #if RGENGC_PROFILE - "%10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE + "%10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE #endif #if GC_PROFILE_DETAIL_MEMORY - "%11ld %8ld %8ld" + "%11ld %8ld %8ld" #endif - "\n", - i+1, - gc_profile_dump_major_reason(record->flags, reason_str), - (record->flags & GPR_FLAG_HAVE_FINALIZE) ? 'F' : '.', - (record->flags & GPR_FLAG_NEWOBJ) ? "NEWOBJ" : - (record->flags & GPR_FLAG_MALLOC) ? "MALLOC" : - (record->flags & GPR_FLAG_METHOD) ? "METHOD" : - (record->flags & GPR_FLAG_CAPI) ? "CAPI__" : "??????", - (record->flags & GPR_FLAG_STRESS) ? '!' : ' ', - record->allocate_increase, record->allocate_limit, + "\n", + i+1, + gc_profile_dump_major_reason(record->flags, reason_str), + (record->flags & GPR_FLAG_HAVE_FINALIZE) ? 'F' : '.', + (record->flags & GPR_FLAG_NEWOBJ) ? "NEWOBJ" : + (record->flags & GPR_FLAG_MALLOC) ? "MALLOC" : + (record->flags & GPR_FLAG_METHOD) ? "METHOD" : + (record->flags & GPR_FLAG_CAPI) ? "CAPI__" : "??????", + (record->flags & GPR_FLAG_STRESS) ? '!' : ' ', + record->allocate_increase, record->allocate_limit, #if CALC_EXACT_MALLOC_SIZE - record->allocated_size, + record->allocated_size, #endif - record->heap_use_pages, - record->gc_mark_time*1000, - record->gc_sweep_time*1000, - record->prepare_time*1000, + record->heap_use_pages, + record->gc_mark_time*1000, + record->gc_sweep_time*1000, + record->prepare_time*1000, - record->heap_live_objects, - record->heap_free_objects, - record->removing_objects, - record->empty_objects + record->heap_live_objects, + record->heap_free_objects, + record->removing_objects, + record->empty_objects #if RGENGC_PROFILE - , - record->old_objects, - record->remembered_normal_objects, - record->remembered_shady_objects + , + record->old_objects, + record->remembered_normal_objects, + record->remembered_shady_objects #endif #if GC_PROFILE_DETAIL_MEMORY - , - record->maxrss / 1024, - record->minflt, - record->majflt + , + record->maxrss / 1024, + record->minflt, + record->majflt #endif - )); - } + )); + } #endif } } @@ -13632,12 +13632,12 @@ gc_profile_total_time(VALUE self) rb_objspace_t *objspace = &rb_objspace; if (objspace->profile.run && objspace->profile.next_index > 0) { - size_t i; - size_t count = objspace->profile.next_index; + size_t i; + size_t count = objspace->profile.next_index; - for (i = 0; i < count; i++) { - time += objspace->profile.records[i].gc_time; - } + for (i = 0; i < count; i++) { + time += objspace->profile.records[i].gc_time; + } } return DBL2NUM(time); } @@ -13700,36 +13700,36 @@ type_name(int type, VALUE obj) { switch (type) { #define TYPE_NAME(t) case (t): return #t; - TYPE_NAME(T_NONE); - TYPE_NAME(T_OBJECT); - TYPE_NAME(T_CLASS); - TYPE_NAME(T_MODULE); - TYPE_NAME(T_FLOAT); - TYPE_NAME(T_STRING); - TYPE_NAME(T_REGEXP); - TYPE_NAME(T_ARRAY); - TYPE_NAME(T_HASH); - TYPE_NAME(T_STRUCT); - TYPE_NAME(T_BIGNUM); - TYPE_NAME(T_FILE); - TYPE_NAME(T_MATCH); - TYPE_NAME(T_COMPLEX); - TYPE_NAME(T_RATIONAL); - TYPE_NAME(T_NIL); - TYPE_NAME(T_TRUE); - TYPE_NAME(T_FALSE); - TYPE_NAME(T_SYMBOL); - TYPE_NAME(T_FIXNUM); - TYPE_NAME(T_UNDEF); - TYPE_NAME(T_IMEMO); - TYPE_NAME(T_ICLASS); + TYPE_NAME(T_NONE); + TYPE_NAME(T_OBJECT); + TYPE_NAME(T_CLASS); + TYPE_NAME(T_MODULE); + TYPE_NAME(T_FLOAT); + TYPE_NAME(T_STRING); + TYPE_NAME(T_REGEXP); + TYPE_NAME(T_ARRAY); + TYPE_NAME(T_HASH); + TYPE_NAME(T_STRUCT); + TYPE_NAME(T_BIGNUM); + TYPE_NAME(T_FILE); + TYPE_NAME(T_MATCH); + TYPE_NAME(T_COMPLEX); + TYPE_NAME(T_RATIONAL); + TYPE_NAME(T_NIL); + TYPE_NAME(T_TRUE); + TYPE_NAME(T_FALSE); + TYPE_NAME(T_SYMBOL); + TYPE_NAME(T_FIXNUM); + TYPE_NAME(T_UNDEF); + TYPE_NAME(T_IMEMO); + TYPE_NAME(T_ICLASS); TYPE_NAME(T_MOVED); - TYPE_NAME(T_ZOMBIE); + TYPE_NAME(T_ZOMBIE); case T_DATA: - if (obj && rb_objspace_data_type_name(obj)) { - return rb_objspace_data_type_name(obj); - } - return "T_DATA"; + if (obj && rb_objspace_data_type_name(obj)) { + return rb_objspace_data_type_name(obj); + } + return "T_DATA"; #undef TYPE_NAME } return "unknown"; @@ -13765,12 +13765,12 @@ static void rb_raw_iseq_info(char *const buff, const size_t buff_size, const rb_iseq_t *iseq) { if (buff_size > 0 && ISEQ_BODY(iseq) && ISEQ_BODY(iseq)->location.label && !RB_TYPE_P(ISEQ_BODY(iseq)->location.pathobj, T_MOVED)) { - VALUE path = rb_iseq_path(iseq); + VALUE path = rb_iseq_path(iseq); VALUE n = ISEQ_BODY(iseq)->location.first_lineno; snprintf(buff, buff_size, " %s@%s:%d", RSTRING_PTR(ISEQ_BODY(iseq)->location.label), - RSTRING_PTR(path), - n ? FIX2INT(n) : 0 ); + RSTRING_PTR(path), + n ? FIX2INT(n) : 0 ); } } @@ -13812,7 +13812,7 @@ rb_raw_obj_info_common(char *const buff, const size_t buff_size, const VALUE obj } } else { - const int age = RVALUE_FLAGS_AGE(RBASIC(obj)->flags); + const int age = RVALUE_FLAGS_AGE(RBASIC(obj)->flags); if (is_pointer_to_heap(&rb_objspace, (void *)obj)) { APPEND_F("%p [%d%s%s%s%s%s%s] %s ", @@ -13832,18 +13832,18 @@ rb_raw_obj_info_common(char *const buff, const size_t buff_size, const VALUE obj obj_type_name(obj)); } - if (internal_object_p(obj)) { - /* ignore */ - } - else if (RBASIC(obj)->klass == 0) { + if (internal_object_p(obj)) { + /* ignore */ + } + else if (RBASIC(obj)->klass == 0) { APPEND_S("(temporary internal)"); - } - else if (RTEST(RBASIC(obj)->klass)) { + } + else if (RTEST(RBASIC(obj)->klass)) { VALUE class_path = rb_class_path_cached(RBASIC(obj)->klass); - if (!NIL_P(class_path)) { + if (!NIL_P(class_path)) { APPEND_F("(%s)", RSTRING_PTR(class_path)); - } - } + } + } #if GC_DEBUG APPEND_F("@%s:%d", RANY(obj)->file, RANY(obj)->line); @@ -13858,13 +13858,13 @@ static size_t rb_raw_obj_info_buitin_type(char *const buff, const size_t buff_size, const VALUE obj, size_t pos) { if (LIKELY(pos < buff_size) && !SPECIAL_CONST_P(obj)) { - const enum ruby_value_type type = BUILTIN_TYPE(obj); + const enum ruby_value_type type = BUILTIN_TYPE(obj); - switch (type) { - case T_NODE: - UNEXPECTED_NODE(rb_raw_obj_info); - break; - case T_ARRAY: + switch (type) { + case T_NODE: + UNEXPECTED_NODE(rb_raw_obj_info); + break; + case T_ARRAY: if (ARY_SHARED_P(obj)) { APPEND_S("shared -> "); rb_raw_obj_info(BUFF_ARGS, ARY_SHARED_ROOT(obj)); @@ -13884,8 +13884,8 @@ rb_raw_obj_info_buitin_type(char *const buff, const size_t buff_size, const VALU ARY_EMBED_P(obj) ? -1L : RARRAY(obj)->as.heap.aux.capa, (void *)RARRAY_CONST_PTR_TRANSIENT(obj)); } - break; - case T_STRING: { + break; + case T_STRING: { if (STR_SHARED_P(obj)) { APPEND_F(" [shared] len: %ld", RSTRING_LEN(obj)); } @@ -13895,8 +13895,8 @@ rb_raw_obj_info_buitin_type(char *const buff, const size_t buff_size, const VALU APPEND_F(" len: %ld, capa: %" PRIdSIZE, RSTRING_LEN(obj), rb_str_capacity(obj)); } APPEND_F(" \"%.*s\"", str_len_no_raise(obj), RSTRING_PTR(obj)); - break; - } + break; + } case T_SYMBOL: { VALUE fstr = RSYMBOL(obj)->fstr; ID id = RSYMBOL(obj)->id; @@ -13952,34 +13952,34 @@ rb_raw_obj_info_buitin_type(char *const buff, const size_t buff_size, const VALU } } break; - case T_DATA: { - const struct rb_block *block; - const rb_iseq_t *iseq; - if (rb_obj_is_proc(obj) && - (block = vm_proc_block(obj)) != NULL && - (vm_block_type(block) == block_type_iseq) && - (iseq = vm_block_iseq(block)) != NULL) { + case T_DATA: { + const struct rb_block *block; + const rb_iseq_t *iseq; + if (rb_obj_is_proc(obj) && + (block = vm_proc_block(obj)) != NULL && + (vm_block_type(block) == block_type_iseq) && + (iseq = vm_block_iseq(block)) != NULL) { rb_raw_iseq_info(BUFF_ARGS, iseq); - } + } else if (rb_ractor_p(obj)) { rb_ractor_t *r = (void *)DATA_PTR(obj); if (r) { APPEND_F("r:%d", r->pub.id); } } - else { - const char * const type_name = rb_objspace_data_type_name(obj); - if (type_name) { + else { + const char * const type_name = rb_objspace_data_type_name(obj); + if (type_name) { APPEND_F("%s", type_name); - } - } - break; - } - case T_IMEMO: { + } + } + break; + } + case T_IMEMO: { APPEND_F("<%s> ", rb_imemo_name(imemo_type(obj))); - switch (imemo_type(obj)) { - case imemo_ment: + switch (imemo_type(obj)) { + case imemo_ment: { const rb_method_entry_t *me = &RANY(obj)->as.imemo.ment; @@ -14009,11 +14009,11 @@ rb_raw_obj_info_buitin_type(char *const buff, const size_t buff_size, const VALU break; } - case imemo_iseq: { - const rb_iseq_t *iseq = (const rb_iseq_t *)obj; + case imemo_iseq: { + const rb_iseq_t *iseq = (const rb_iseq_t *)obj; rb_raw_iseq_info(BUFF_ARGS, iseq); - break; - } + break; + } case imemo_callinfo: { const struct rb_callinfo *ci = (const struct rb_callinfo *)obj; @@ -14038,13 +14038,13 @@ rb_raw_obj_info_buitin_type(char *const buff, const size_t buff_size, const VALU (void *)vm_cc_call(cc)); break; } - default: - break; - } - } - default: - break; - } + default: + break; + } + } + default: + break; + } } end: @@ -14193,7 +14193,7 @@ rb_gcdebug_add_stress_to_class(int argc, VALUE *argv, VALUE self) rb_objspace_t *objspace = &rb_objspace; if (!stress_to_class) { - stress_to_class = rb_ary_tmp_new(argc); + stress_to_class = rb_ary_tmp_new(argc); } rb_ary_cat(stress_to_class, argv, argc); return self; @@ -14214,12 +14214,12 @@ rb_gcdebug_remove_stress_to_class(int argc, VALUE *argv, VALUE self) int i; if (stress_to_class) { - for (i = 0; i < argc; ++i) { - rb_ary_delete_same(stress_to_class, argv[i]); - } - if (RARRAY_LEN(stress_to_class) == 0) { - stress_to_class = 0; - } + for (i = 0; i < argc; ++i) { + rb_ary_delete_same(stress_to_class, argv[i]); + } + if (RARRAY_LEN(stress_to_class) == 0) { + stress_to_class = 0; + } } return Qnil; } @@ -14333,23 +14333,23 @@ Init_GC(void) rb_define_module_function(rb_mObjSpace, "count_objects", count_objects, -1); { - VALUE rb_cWeakMap = rb_define_class_under(rb_mObjSpace, "WeakMap", rb_cObject); - rb_define_alloc_func(rb_cWeakMap, wmap_allocate); - rb_define_method(rb_cWeakMap, "[]=", wmap_aset, 2); - rb_define_method(rb_cWeakMap, "[]", wmap_aref, 1); - rb_define_method(rb_cWeakMap, "include?", wmap_has_key, 1); - rb_define_method(rb_cWeakMap, "member?", wmap_has_key, 1); - rb_define_method(rb_cWeakMap, "key?", wmap_has_key, 1); - rb_define_method(rb_cWeakMap, "inspect", wmap_inspect, 0); - rb_define_method(rb_cWeakMap, "each", wmap_each, 0); - rb_define_method(rb_cWeakMap, "each_pair", wmap_each, 0); - rb_define_method(rb_cWeakMap, "each_key", wmap_each_key, 0); - rb_define_method(rb_cWeakMap, "each_value", wmap_each_value, 0); - rb_define_method(rb_cWeakMap, "keys", wmap_keys, 0); - rb_define_method(rb_cWeakMap, "values", wmap_values, 0); - rb_define_method(rb_cWeakMap, "size", wmap_size, 0); - rb_define_method(rb_cWeakMap, "length", wmap_size, 0); - rb_include_module(rb_cWeakMap, rb_mEnumerable); + VALUE rb_cWeakMap = rb_define_class_under(rb_mObjSpace, "WeakMap", rb_cObject); + rb_define_alloc_func(rb_cWeakMap, wmap_allocate); + rb_define_method(rb_cWeakMap, "[]=", wmap_aset, 2); + rb_define_method(rb_cWeakMap, "[]", wmap_aref, 1); + rb_define_method(rb_cWeakMap, "include?", wmap_has_key, 1); + rb_define_method(rb_cWeakMap, "member?", wmap_has_key, 1); + rb_define_method(rb_cWeakMap, "key?", wmap_has_key, 1); + rb_define_method(rb_cWeakMap, "inspect", wmap_inspect, 0); + rb_define_method(rb_cWeakMap, "each", wmap_each, 0); + rb_define_method(rb_cWeakMap, "each_pair", wmap_each, 0); + rb_define_method(rb_cWeakMap, "each_key", wmap_each_key, 0); + rb_define_method(rb_cWeakMap, "each_value", wmap_each_value, 0); + rb_define_method(rb_cWeakMap, "keys", wmap_keys, 0); + rb_define_method(rb_cWeakMap, "values", wmap_values, 0); + rb_define_method(rb_cWeakMap, "size", wmap_size, 0); + rb_define_method(rb_cWeakMap, "length", wmap_size, 0); + rb_include_module(rb_cWeakMap, rb_mEnumerable); } /* internal methods */ @@ -14381,25 +14381,25 @@ Init_GC(void) #endif { - VALUE opts; - /* GC build options */ - rb_define_const(rb_mGC, "OPTS", opts = rb_ary_new()); + VALUE opts; + /* GC build options */ + rb_define_const(rb_mGC, "OPTS", opts = rb_ary_new()); #define OPT(o) if (o) rb_ary_push(opts, rb_fstring_lit(#o)) - OPT(GC_DEBUG); - OPT(USE_RGENGC); - OPT(RGENGC_DEBUG); - OPT(RGENGC_CHECK_MODE); - OPT(RGENGC_PROFILE); - OPT(RGENGC_ESTIMATE_OLDMALLOC); - OPT(GC_PROFILE_MORE_DETAIL); - OPT(GC_ENABLE_LAZY_SWEEP); - OPT(CALC_EXACT_MALLOC_SIZE); - OPT(MALLOC_ALLOCATED_SIZE); - OPT(MALLOC_ALLOCATED_SIZE_CHECK); - OPT(GC_PROFILE_DETAIL_MEMORY); - OPT(GC_COMPACTION_SUPPORTED); + OPT(GC_DEBUG); + OPT(USE_RGENGC); + OPT(RGENGC_DEBUG); + OPT(RGENGC_CHECK_MODE); + OPT(RGENGC_PROFILE); + OPT(RGENGC_ESTIMATE_OLDMALLOC); + OPT(GC_PROFILE_MORE_DETAIL); + OPT(GC_ENABLE_LAZY_SWEEP); + OPT(CALC_EXACT_MALLOC_SIZE); + OPT(MALLOC_ALLOCATED_SIZE); + OPT(MALLOC_ALLOCATED_SIZE_CHECK); + OPT(GC_PROFILE_DETAIL_MEMORY); + OPT(GC_COMPACTION_SUPPORTED); #undef OPT - OBJ_FREEZE(opts); + OBJ_FREEZE(opts); } } diff --git a/gc.h b/gc.h index a1f6e6e49d..3d863fce8a 100644 --- a/gc.h +++ b/gc.h @@ -20,9 +20,9 @@ NOINLINE(void rb_gc_set_stack_end(VALUE **stack_end_p)); #define RB_GC_SAVE_MACHINE_CONTEXT(th) \ do { \ - FLUSH_REGISTER_WINDOWS; \ - setjmp((th)->ec->machine.regs); \ - SET_MACHINE_STACK_END(&(th)->ec->machine.stack_end); \ + FLUSH_REGISTER_WINDOWS; \ + setjmp((th)->ec->machine.regs); \ + SET_MACHINE_STACK_END(&(th)->ec->machine.stack_end); \ } while (0) /* for GC debug */ @@ -44,13 +44,13 @@ static inline void rb_gc_debug_body(const char *mode, const char *msg, int st, void *ptr) { if (st == 0) { - ruby_gc_debug_indent--; + ruby_gc_debug_indent--; } rb_gc_debug_indent(); ruby_debug_printf("%s: %s %s (%p)\n", mode, st ? "->" : "<-", msg, ptr); if (st) { - ruby_gc_debug_indent++; + ruby_gc_debug_indent++; } fflush(stdout); @@ -88,9 +88,9 @@ rb_gc_debug_body(const char *mode, const char *msg, int st, void *ptr) RUBY_EXTERN int ruby_stack_grow_direction; int ruby_get_stack_grow_direction(volatile VALUE *addr); # define stack_growup_p(x) ( \ - (ruby_stack_grow_direction ? \ - ruby_stack_grow_direction : \ - ruby_get_stack_grow_direction(x)) > 0) + (ruby_stack_grow_direction ? \ + ruby_stack_grow_direction : \ + ruby_get_stack_grow_direction(x)) > 0) # define STACK_UPPER(x, a, b) (stack_growup_p(x) ? (a) : (b)) #endif diff --git a/goruby.c b/goruby.c index c90fc97b0a..5d45277207 100644 --- a/goruby.c +++ b/goruby.c @@ -37,21 +37,21 @@ goruby_options(int argc, char **argv) void *ret; if ((isatty(0) && isatty(1) && isatty(2)) && (pipe(rw) == 0)) { - ssize_t n; - infd = dup(0); - if (infd < 0) { - close(rw[0]); - close(rw[1]); - goto no_irb; - } - dup2(rw[0], 0); - close(rw[0]); - n = write(rw[1], cmd, sizeof(cmd) - 1); - close(rw[1]); - ret = n > 0 ? ruby_options(argc, argv) : NULL; - dup2(infd, 0); - close(infd); - return ret; + ssize_t n; + infd = dup(0); + if (infd < 0) { + close(rw[0]); + close(rw[1]); + goto no_irb; + } + dup2(rw[0], 0); + close(rw[0]); + n = write(rw[1], cmd, sizeof(cmd) - 1); + close(rw[1]); + ret = n > 0 ? ruby_options(argc, argv) : NULL; + dup2(infd, 0); + close(infd); + return ret; } no_irb: return ruby_options(argc, argv); @@ -62,7 +62,7 @@ goruby_run_node(void *arg) { int state; if (NIL_P(rb_protect(init_golf, Qtrue, &state))) { - return state == EXIT_SUCCESS ? EXIT_FAILURE : state; + return state == EXIT_SUCCESS ? EXIT_FAILURE : state; } return ruby_run_node(arg); } diff --git a/hash.c b/hash.c index 1c36a22bc0..989bef455c 100644 --- a/hash.c +++ b/hash.c @@ -108,12 +108,12 @@ rb_any_cmp(VALUE a, VALUE b) { if (a == b) return 0; if (RB_TYPE_P(a, T_STRING) && RBASIC(a)->klass == rb_cString && - RB_TYPE_P(b, T_STRING) && RBASIC(b)->klass == rb_cString) { - return rb_str_hash_cmp(a, b); + RB_TYPE_P(b, T_STRING) && RBASIC(b)->klass == rb_cString) { + return rb_str_hash_cmp(a, b); } if (a == Qundef || b == Qundef) return -1; if (SYMBOL_P(a) && SYMBOL_P(b)) { - return a != b; + return a != b; } return !rb_eql(a, b); @@ -156,7 +156,7 @@ any_hash(VALUE a, st_index_t (*other_func)(VALUE)) switch (TYPE(a)) { case T_SYMBOL: - if (STATIC_SYM_P(a)) { + if (STATIC_SYM_P(a)) { hnum = a >> (RUBY_SPECIAL_SHIFT + ID_SCOPE_SHIFT); hnum = rb_hash_start(hnum); } @@ -168,25 +168,25 @@ any_hash(VALUE a, st_index_t (*other_func)(VALUE)) case T_TRUE: case T_FALSE: case T_NIL: - hnum = rb_objid_hash((st_index_t)a); + hnum = rb_objid_hash((st_index_t)a); break; case T_STRING: - hnum = rb_str_hash(a); + hnum = rb_str_hash(a); break; case T_BIGNUM: - hval = rb_big_hash(a); - hnum = FIX2LONG(hval); + hval = rb_big_hash(a); + hnum = FIX2LONG(hval); break; case T_FLOAT: /* prevent pathological behavior: [Bug #10761] */ - hnum = rb_dbl_long_hash(rb_float_value(a)); + hnum = rb_dbl_long_hash(rb_float_value(a)); break; default: - hnum = other_func(a); + hnum = other_func(a); } if ((SIGNED_VALUE)hnum > 0) - hnum &= FIXNUM_MAX; + hnum &= FIXNUM_MAX; else - hnum |= FIXNUM_MIN; + hnum |= FIXNUM_MIN; return (long)hnum; } @@ -1319,7 +1319,7 @@ foreach_safe_i(st_data_t key, st_data_t value, st_data_t args, int error) if (error) return ST_STOP; status = (*arg->func)(key, value, arg->arg); if (status == ST_CONTINUE) { - return ST_CHECK; + return ST_CHECK; } return status; } @@ -1333,7 +1333,7 @@ st_foreach_safe(st_table *table, st_foreach_func *func, st_data_t a) arg.func = (st_foreach_func *)func; arg.arg = a; if (st_foreach_check(table, foreach_safe_i, (st_data_t)&arg, 0)) { - rb_raise(rb_eRuntimeError, "hash modified during iteration"); + rb_raise(rb_eRuntimeError, "hash modified during iteration"); } } @@ -1381,11 +1381,11 @@ hash_foreach_iter(st_data_t key, st_data_t value, st_data_t argp, int error) } switch (status) { case ST_DELETE: - return ST_DELETE; + return ST_DELETE; case ST_CONTINUE: - break; + break; case ST_STOP: - return ST_STOP; + return ST_STOP; } return ST_CHECK; } @@ -1775,12 +1775,12 @@ static void set_proc_default(VALUE hash, VALUE proc) { if (rb_proc_lambda_p(proc)) { - int n = rb_proc_arity(proc); + int n = rb_proc_arity(proc); - if (n != 2 && (n >= 0 || n < -3)) { - if (n < 0) n = -n-1; - rb_raise(rb_eTypeError, "default_proc takes two arguments (2 for %d)", n); - } + if (n != 2 && (n >= 0 || n < -3)) { + if (n < 0) n = -n-1; + rb_raise(rb_eTypeError, "default_proc takes two arguments (2 for %d)", n); + } } FL_SET_RAW(hash, RHASH_PROC_DEFAULT); @@ -1825,14 +1825,14 @@ rb_hash_initialize(int argc, VALUE *argv, VALUE hash) rb_hash_modify(hash); if (rb_block_given_p()) { - rb_check_arity(argc, 0, 0); - ifnone = rb_block_proc(); - SET_PROC_DEFAULT(hash, ifnone); + rb_check_arity(argc, 0, 0); + ifnone = rb_block_proc(); + SET_PROC_DEFAULT(hash, ifnone); } else { - rb_check_arity(argc, 0, 1); - ifnone = argc == 0 ? Qnil : argv[0]; - RHASH_SET_IFNONE(hash, ifnone); + rb_check_arity(argc, 0, 1); + ifnone = argc == 0 ? Qnil : argv[0]; + RHASH_SET_IFNONE(hash, ifnone); } return hash; @@ -1880,42 +1880,42 @@ rb_hash_s_create(int argc, VALUE *argv, VALUE klass) if (argc == 1) { tmp = rb_hash_s_try_convert(Qnil, argv[0]); - if (!NIL_P(tmp)) { - hash = hash_alloc(klass); + if (!NIL_P(tmp)) { + hash = hash_alloc(klass); hash_copy(hash, tmp); - return hash; - } + return hash; + } - tmp = rb_check_array_type(argv[0]); - if (!NIL_P(tmp)) { - long i; + tmp = rb_check_array_type(argv[0]); + if (!NIL_P(tmp)) { + long i; - hash = hash_alloc(klass); - for (i = 0; i < RARRAY_LEN(tmp); ++i) { - VALUE e = RARRAY_AREF(tmp, i); - VALUE v = rb_check_array_type(e); - VALUE key, val = Qnil; + hash = hash_alloc(klass); + for (i = 0; i < RARRAY_LEN(tmp); ++i) { + VALUE e = RARRAY_AREF(tmp, i); + VALUE v = rb_check_array_type(e); + VALUE key, val = Qnil; - if (NIL_P(v)) { - rb_raise(rb_eArgError, "wrong element type %s at %ld (expected array)", - rb_builtin_class_name(e), i); - } - switch (RARRAY_LEN(v)) { - default: - rb_raise(rb_eArgError, "invalid number of elements (%ld for 1..2)", - RARRAY_LEN(v)); - case 2: - val = RARRAY_AREF(v, 1); - case 1: - key = RARRAY_AREF(v, 0); - rb_hash_aset(hash, key, val); - } - } - return hash; - } + if (NIL_P(v)) { + rb_raise(rb_eArgError, "wrong element type %s at %ld (expected array)", + rb_builtin_class_name(e), i); + } + switch (RARRAY_LEN(v)) { + default: + rb_raise(rb_eArgError, "invalid number of elements (%ld for 1..2)", + RARRAY_LEN(v)); + case 2: + val = RARRAY_AREF(v, 1); + case 1: + key = RARRAY_AREF(v, 0); + rb_hash_aset(hash, key, val); + } + } + return hash; + } } if (argc % 2 != 0) { - rb_raise(rb_eArgError, "odd number of arguments for Hash"); + rb_raise(rb_eArgError, "odd number of arguments for Hash"); } hash = hash_alloc(klass); @@ -2038,7 +2038,7 @@ rb_hash_rehash(VALUE hash) st_table *tbl; if (RHASH_ITER_LEV(hash) > 0) { - rb_raise(rb_eRuntimeError, "rehash during iteration"); + rb_raise(rb_eRuntimeError, "rehash during iteration"); } rb_hash_modify_check(hash); if (RHASH_AR_TABLE_P(hash)) { @@ -2074,13 +2074,13 @@ VALUE rb_hash_default_value(VALUE hash, VALUE key) { if (LIKELY(rb_method_basic_definition_p(CLASS_OF(hash), id_default))) { - VALUE ifnone = RHASH_IFNONE(hash); + VALUE ifnone = RHASH_IFNONE(hash); if (!FL_TEST(hash, RHASH_PROC_DEFAULT)) return ifnone; - if (key == Qundef) return Qnil; + if (key == Qundef) return Qnil; return call_default_proc(ifnone, hash, key); } else { - return rb_funcall(hash, id_default, 1, key); + return rb_funcall(hash, id_default, 1, key); } } @@ -2184,7 +2184,7 @@ rb_hash_fetch_m(int argc, VALUE *argv, VALUE hash) block_given = rb_block_given_p(); if (block_given && argc == 2) { - rb_warn("block supersedes default value argument"); + rb_warn("block supersedes default value argument"); } if (hash_stlike_lookup(hash, key, &val)) { @@ -2242,8 +2242,8 @@ rb_hash_default(int argc, VALUE *argv, VALUE hash) rb_check_arity(argc, 0, 1); ifnone = RHASH_IFNONE(hash); if (FL_TEST(hash, RHASH_PROC_DEFAULT)) { - if (argc == 0) return Qnil; - return call_default_proc(ifnone, hash, argv[0]); + if (argc == 0) return Qnil; + return call_default_proc(ifnone, hash, argv[0]); } return ifnone; } @@ -2285,7 +2285,7 @@ static VALUE rb_hash_default_proc(VALUE hash) { if (FL_TEST(hash, RHASH_PROC_DEFAULT)) { - return RHASH_IFNONE(hash); + return RHASH_IFNONE(hash); } return Qnil; } @@ -2311,14 +2311,14 @@ rb_hash_set_default_proc(VALUE hash, VALUE proc) rb_hash_modify_check(hash); if (NIL_P(proc)) { - SET_DEFAULT(hash, proc); - return proc; + SET_DEFAULT(hash, proc); + return proc; } b = rb_check_convert_type_with_id(proc, T_DATA, "Proc", idTo_proc); if (NIL_P(b) || !rb_obj_is_proc(b)) { - rb_raise(rb_eTypeError, - "wrong default_proc type %s (expected Proc)", - rb_obj_classname(proc)); + rb_raise(rb_eTypeError, + "wrong default_proc type %s (expected Proc)", + rb_obj_classname(proc)); } proc = b; SET_PROC_DEFAULT(hash, proc); @@ -2331,8 +2331,8 @@ key_i(VALUE key, VALUE value, VALUE arg) VALUE *args = (VALUE *)arg; if (rb_equal(value, args[0])) { - args[1] = key; - return ST_STOP; + args[1] = key; + return ST_STOP; } return ST_CONTINUE; } @@ -2403,10 +2403,10 @@ rb_hash_delete(VALUE hash, VALUE key) VALUE deleted_value = rb_hash_delete_entry(hash, key); if (deleted_value != Qundef) { /* likely pass */ - return deleted_value; + return deleted_value; } else { - return Qnil; + return Qnil; } } @@ -2446,15 +2446,15 @@ rb_hash_delete_m(VALUE hash, VALUE key) val = rb_hash_delete_entry(hash, key); if (val != Qundef) { - return val; + return val; } else { - if (rb_block_given_p()) { - return rb_yield(key); - } - else { - return Qnil; - } + if (rb_block_given_p()) { + return rb_yield(key); + } + else { + return Qnil; + } } } @@ -2494,13 +2494,13 @@ rb_hash_shift(VALUE hash) rb_hash_modify_check(hash); if (RHASH_AR_TABLE_P(hash)) { - var.key = Qundef; - if (RHASH_ITER_LEV(hash) == 0) { + var.key = Qundef; + if (RHASH_ITER_LEV(hash) == 0) { if (ar_shift(hash, &var.key, &var.val)) { - return rb_assoc_new(var.key, var.val); - } - } - else { + return rb_assoc_new(var.key, var.val); + } + } + else { rb_hash_foreach(hash, shift_i_safe, (VALUE)&var); if (var.key != Qundef) { rb_hash_delete_entry(hash, var.key); @@ -2516,12 +2516,12 @@ rb_hash_shift(VALUE hash) } } else { - rb_hash_foreach(hash, shift_i_safe, (VALUE)&var); - if (var.key != Qundef) { - rb_hash_delete_entry(hash, var.key); - return rb_assoc_new(var.key, var.val); - } - } + rb_hash_foreach(hash, shift_i_safe, (VALUE)&var); + if (var.key != Qundef) { + rb_hash_delete_entry(hash, var.key); + return rb_assoc_new(var.key, var.val); + } + } } return Qnil; } @@ -2530,8 +2530,8 @@ static int delete_if_i(VALUE key, VALUE value, VALUE hash) { if (RTEST(rb_yield_values(2, key, value))) { - rb_hash_modify(hash); - return ST_DELETE; + rb_hash_modify(hash); + return ST_DELETE; } return ST_CONTINUE; } @@ -2628,7 +2628,7 @@ rb_hash_reject(VALUE hash) RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size); result = hash_dup_with_compare_by_id(hash); if (!RHASH_EMPTY_P(hash)) { - rb_hash_foreach(result, delete_if_i, result); + rb_hash_foreach(result, delete_if_i, result); } return result; } @@ -2656,10 +2656,10 @@ rb_hash_slice(int argc, VALUE *argv, VALUE hash) result = copy_compare_by_id(rb_hash_new_with_size(argc), hash); for (i = 0; i < argc; i++) { - key = argv[i]; - value = rb_hash_lookup2(hash, key, Qundef); - if (value != Qundef) - rb_hash_aset(result, key, value); + key = argv[i]; + value = rb_hash_lookup2(hash, key, Qundef); + if (value != Qundef) + rb_hash_aset(result, key, value); } return result; @@ -2712,7 +2712,7 @@ rb_hash_values_at(int argc, VALUE *argv, VALUE hash) long i; for (i=0; i 0) no_new_key(); + if (iter_lev > 0) no_new_key(); ar_alloc_table(hash); } if (RHASH_TYPE(hash) == &identhash || rb_obj_class(key) != rb_cString) { - RHASH_UPDATE_ITER(hash, iter_lev, key, hash_aset, val); + RHASH_UPDATE_ITER(hash, iter_lev, key, hash_aset, val); } else { - RHASH_UPDATE_ITER(hash, iter_lev, key, hash_aset_str, val); + RHASH_UPDATE_ITER(hash, iter_lev, key, hash_aset_str, val); } return val; } @@ -3163,9 +3163,9 @@ rb_hash_each_pair(VALUE hash) { RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size); if (rb_block_pair_yield_optimizable()) - rb_hash_foreach(hash, each_pair_i_fast, 0); + rb_hash_foreach(hash, each_pair_i_fast, 0); else - rb_hash_foreach(hash, each_pair_i, 0); + rb_hash_foreach(hash, each_pair_i, 0); return hash; } @@ -3439,10 +3439,10 @@ inspect_i(VALUE key, VALUE value, VALUE str) str2 = rb_inspect(key); if (RSTRING_LEN(str) > 1) { - rb_str_buf_cat_ascii(str, ", "); + rb_str_buf_cat_ascii(str, ", "); } else { - rb_enc_copy(str, str2); + rb_enc_copy(str, str2); } rb_str_buf_append(str, str2); rb_str_buf_cat_ascii(str, "=>"); @@ -3480,7 +3480,7 @@ static VALUE rb_hash_inspect(VALUE hash) { if (RHASH_EMPTY_P(hash)) - return rb_usascii_str_new2("{}"); + return rb_usascii_str_new2("{}"); return rb_exec_recursive(inspect_hash, hash, 0); } @@ -3555,7 +3555,7 @@ rb_hash_to_h(VALUE hash) return rb_hash_to_h_block(hash); } if (rb_obj_class(hash) != rb_cHash) { - const VALUE flags = RBASIC(hash)->flags; + const VALUE flags = RBASIC(hash)->flags; hash = hash_dup(hash, rb_cHash, flags & RHASH_PROC_DEFAULT); } return hash; @@ -3596,10 +3596,10 @@ rb_hash_keys(VALUE hash) } }); rb_gc_writebarrier_remember(keys); - rb_ary_set_len(keys, size); + rb_ary_set_len(keys, size); } else { - rb_hash_foreach(hash, keys_i, keys); + rb_hash_foreach(hash, keys_i, keys); } return keys; @@ -3644,11 +3644,11 @@ rb_hash_values(VALUE hash) size = st_values(table, ptr, size); }); } - rb_ary_set_len(values, size); + rb_ary_set_len(values, size); } else { - rb_hash_foreach(hash, values_i, values); + rb_hash_foreach(hash, values_i, values); } return values; @@ -3678,8 +3678,8 @@ rb_hash_search_value(VALUE key, VALUE value, VALUE arg) VALUE *data = (VALUE *)arg; if (rb_equal(value, data[1])) { - data[0] = Qtrue; - return ST_STOP; + data[0] = Qtrue; + return ST_STOP; } return ST_CONTINUE; } @@ -3750,23 +3750,23 @@ hash_equal(VALUE hash1, VALUE hash2, int eql) if (hash1 == hash2) return Qtrue; if (!RB_TYPE_P(hash2, T_HASH)) { - if (!rb_respond_to(hash2, idTo_hash)) { - return Qfalse; - } - if (eql) { - if (rb_eql(hash2, hash1)) { - return Qtrue; - } - else { - return Qfalse; - } - } - else { - return rb_equal(hash2, hash1); - } + if (!rb_respond_to(hash2, idTo_hash)) { + return Qfalse; + } + if (eql) { + if (rb_eql(hash2, hash1)) { + return Qtrue; + } + else { + return Qfalse; + } + } + else { + return rb_equal(hash2, hash1); + } } if (RHASH_SIZE(hash1) != RHASH_SIZE(hash2)) - return Qfalse; + return Qfalse; if (!RHASH_TABLE_EMPTY_P(hash1) && !RHASH_TABLE_EMPTY_P(hash2)) { if (RHASH_TYPE(hash1) != RHASH_TYPE(hash2)) { return Qfalse; @@ -3781,7 +3781,7 @@ hash_equal(VALUE hash1, VALUE hash2, int eql) #if 0 if (!(rb_equal(RHASH_IFNONE(hash1), RHASH_IFNONE(hash2)) && FL_TEST(hash1, RHASH_PROC_DEFAULT) == FL_TEST(hash2, RHASH_PROC_DEFAULT))) - return Qfalse; + return Qfalse; #endif return Qtrue; } @@ -3869,7 +3869,7 @@ rb_hash_hash(VALUE hash) st_index_t hval = rb_hash_start(size); hval = rb_hash_uint(hval, (st_index_t)rb_hash_hash); if (size) { - rb_hash_foreach(hash, hash_i, (VALUE)&hval); + rb_hash_foreach(hash, hash_i, (VALUE)&hval); } hval = rb_hash_end(hval); return ST2FIX(hval); @@ -4025,7 +4025,7 @@ rb_hash_update_func_callback(st_data_t *key, st_data_t *value, struct update_arg VALUE newvalue = uf_arg->value; if (existing) { - newvalue = (*uf_arg->func)((VALUE)*key, (VALUE)*value, newvalue); + newvalue = (*uf_arg->func)((VALUE)*key, (VALUE)*value, newvalue); } *value = newvalue; return ST_CONTINUE; @@ -4050,13 +4050,13 @@ rb_hash_update_by(VALUE hash1, VALUE hash2, rb_hash_update_func *func) rb_hash_modify(hash1); hash2 = to_hash(hash2); if (func) { - struct update_func_arg arg; - arg.hash = hash1; - arg.func = func; - rb_hash_foreach(hash2, rb_hash_update_func_i, (VALUE)&arg); + struct update_func_arg arg; + arg.hash = hash1; + arg.func = func; + rb_hash_foreach(hash2, rb_hash_update_func_i, (VALUE)&arg); } else { - rb_hash_foreach(hash2, rb_hash_update_i, hash1); + rb_hash_foreach(hash2, rb_hash_update_i, hash1); } return hash1; } @@ -4151,8 +4151,8 @@ assoc_i(VALUE key, VALUE val, VALUE arg) VALUE *args = (VALUE *)arg; if (RTEST(rb_equal(args[0], key))) { - args[1] = rb_assoc_new(key, val); - return ST_STOP; + args[1] = rb_assoc_new(key, val); + return ST_STOP; } return ST_CONTINUE; } @@ -4183,19 +4183,19 @@ rb_hash_assoc(VALUE hash, VALUE key) orighash = table->type; if (orighash != &identhash) { - VALUE value; - struct reset_hash_type_arg ensure_arg; - struct st_hash_type assochash; + VALUE value; + struct reset_hash_type_arg ensure_arg; + struct st_hash_type assochash; - assochash.compare = assoc_cmp; - assochash.hash = orighash->hash; + assochash.compare = assoc_cmp; + assochash.hash = orighash->hash; table->type = &assochash; - args[0] = hash; - args[1] = key; - ensure_arg.hash = hash; - ensure_arg.orighash = orighash; - value = rb_ensure(lookup2_call, (VALUE)&args, reset_hash_type, (VALUE)&ensure_arg); - if (value != Qundef) return rb_assoc_new(key, value); + args[0] = hash; + args[1] = key; + ensure_arg.hash = hash; + ensure_arg.orighash = orighash; + value = rb_ensure(lookup2_call, (VALUE)&args, reset_hash_type, (VALUE)&ensure_arg); + if (value != Qundef) return rb_assoc_new(key, value); } args[0] = key; @@ -4210,8 +4210,8 @@ rassoc_i(VALUE key, VALUE val, VALUE arg) VALUE *args = (VALUE *)arg; if (RTEST(rb_equal(args[0], val))) { - args[1] = rb_assoc_new(key, val); - return ST_STOP; + args[1] = rb_assoc_new(key, val); + return ST_STOP; } return ST_CONTINUE; } @@ -4291,26 +4291,26 @@ rb_hash_flatten(int argc, VALUE *argv, VALUE hash) rb_check_arity(argc, 0, 1); if (argc) { - int level = NUM2INT(argv[0]); + int level = NUM2INT(argv[0]); - if (level == 0) return rb_hash_to_a(hash); + if (level == 0) return rb_hash_to_a(hash); - ary = rb_ary_new_capa(RHASH_SIZE(hash) * 2); - rb_hash_foreach(hash, flatten_i, ary); - level--; + ary = rb_ary_new_capa(RHASH_SIZE(hash) * 2); + rb_hash_foreach(hash, flatten_i, ary); + level--; - if (level > 0) { - VALUE ary_flatten_level = INT2FIX(level); - rb_funcallv(ary, id_flatten_bang, 1, &ary_flatten_level); - } - else if (level < 0) { - /* flatten recursively */ - rb_funcallv(ary, id_flatten_bang, 0, 0); - } + if (level > 0) { + VALUE ary_flatten_level = INT2FIX(level); + rb_funcallv(ary, id_flatten_bang, 1, &ary_flatten_level); + } + else if (level < 0) { + /* flatten recursively */ + rb_funcallv(ary, id_flatten_bang, 0, 0); + } } else { - ary = rb_ary_new_capa(RHASH_SIZE(hash) * 2); - rb_hash_foreach(hash, flatten_i, ary); + ary = rb_ary_new_capa(RHASH_SIZE(hash) * 2); + rb_hash_foreach(hash, flatten_i, ary); } return ary; @@ -4320,7 +4320,7 @@ static int delete_if_nil(VALUE key, VALUE value, VALUE hash) { if (NIL_P(value)) { - return ST_DELETE; + return ST_DELETE; } return ST_CONTINUE; } @@ -4329,7 +4329,7 @@ static int set_if_not_nil(VALUE key, VALUE value, VALUE hash) { if (!NIL_P(value)) { - rb_hash_aset(hash, key, value); + rb_hash_aset(hash, key, value); } return ST_CONTINUE; } @@ -4349,7 +4349,7 @@ rb_hash_compact(VALUE hash) { VALUE result = rb_hash_new(); if (!RHASH_EMPTY_P(hash)) { - rb_hash_foreach(hash, set_if_not_nil, result); + rb_hash_foreach(hash, set_if_not_nil, result); } return result; } @@ -4372,9 +4372,9 @@ rb_hash_compact_bang(VALUE hash) rb_hash_modify_check(hash); n = RHASH_SIZE(hash); if (n) { - rb_hash_foreach(hash, delete_if_nil, hash); + rb_hash_foreach(hash, delete_if_nil, hash); if (n != RHASH_SIZE(hash)) - return hash; + return hash; } return Qnil; } @@ -4478,8 +4478,8 @@ any_p_i(VALUE key, VALUE value, VALUE arg) { VALUE ret = rb_yield(rb_assoc_new(key, value)); if (RTEST(ret)) { - *(VALUE *)arg = Qtrue; - return ST_STOP; + *(VALUE *)arg = Qtrue; + return ST_STOP; } return ST_CONTINUE; } @@ -4489,8 +4489,8 @@ any_p_i_fast(VALUE key, VALUE value, VALUE arg) { VALUE ret = rb_yield_values(2, key, value); if (RTEST(ret)) { - *(VALUE *)arg = Qtrue; - return ST_STOP; + *(VALUE *)arg = Qtrue; + return ST_STOP; } return ST_CONTINUE; } @@ -4500,8 +4500,8 @@ any_p_i_pattern(VALUE key, VALUE value, VALUE arg) { VALUE ret = rb_funcall(((VALUE *)arg)[1], idEqq, 1, rb_assoc_new(key, value)); if (RTEST(ret)) { - *(VALUE *)arg = Qtrue; - return ST_STOP; + *(VALUE *)arg = Qtrue; + return ST_STOP; } return ST_CONTINUE; } @@ -4547,19 +4547,19 @@ rb_hash_any_p(int argc, VALUE *argv, VALUE hash) if (rb_block_given_p()) { rb_warn("given block not used"); } - args[1] = argv[0]; + args[1] = argv[0]; - rb_hash_foreach(hash, any_p_i_pattern, (VALUE)args); + rb_hash_foreach(hash, any_p_i_pattern, (VALUE)args); } else { - if (!rb_block_given_p()) { - /* yields pairs, never false */ - return Qtrue; - } + if (!rb_block_given_p()) { + /* yields pairs, never false */ + return Qtrue; + } if (rb_block_pair_yield_optimizable()) - rb_hash_foreach(hash, any_p_i_fast, (VALUE)args); - else - rb_hash_foreach(hash, any_p_i, (VALUE)args); + rb_hash_foreach(hash, any_p_i_fast, (VALUE)args); + else + rb_hash_foreach(hash, any_p_i, (VALUE)args); } return args[0]; } @@ -4912,12 +4912,12 @@ get_env_cstr( char *var; rb_encoding *enc = rb_enc_get(str); if (!rb_enc_asciicompat(enc)) { - rb_raise(rb_eArgError, "bad environment variable %s: ASCII incompatible encoding: %s", - name, rb_enc_name(enc)); + rb_raise(rb_eArgError, "bad environment variable %s: ASCII incompatible encoding: %s", + name, rb_enc_name(enc)); } var = RSTRING_PTR(str); if (memchr(var, '\0', RSTRING_LEN(str))) { - rb_raise(rb_eArgError, "bad environment variable %s: contains null byte", name); + rb_raise(rb_eArgError, "bad environment variable %s: contains null byte", name); } return rb_str_fill_terminator(str, 1); /* ASCII compatible */ } @@ -5057,17 +5057,17 @@ env_fetch(int argc, VALUE *argv, VALUE _) key = argv[0]; block_given = rb_block_given_p(); if (block_given && argc == 2) { - rb_warn("block supersedes default value argument"); + rb_warn("block supersedes default value argument"); } nam = env_name(key); env = getenv_with_lock(nam); if (NIL_P(env)) { - if (block_given) return rb_yield(key); - if (argc == 1) { - rb_key_err_raise(rb_sprintf("key not found: \"%"PRIsVALUE"\"", key), envtbl, key); - } - return argv[1]; + if (block_given) return rb_yield(key); + if (argc == 1) { + rb_key_err_raise(rb_sprintf("key not found: \"%"PRIsVALUE"\"", key), envtbl, key); + } + return argv[1]; } return env; } @@ -5079,7 +5079,7 @@ in_origenv(const char *str) { char **env; for (env = origenviron; *env; ++env) { - if (*env == str) return 1; + if (*env == str) return 1; } return 0; } @@ -5094,8 +5094,8 @@ envix(const char *nam) env = GET_ENVIRON(environ); for (i = 0; env[i]; i++) { - if (ENVNMATCH(env[i],nam,len) && env[i][len] == '=') - break; /* memcmp must come first to avoid */ + if (ENVNMATCH(env[i],nam,len) && env[i][len] == '=') + break; /* memcmp must come first to avoid */ } /* potential SEGV's */ FREE_ENVIRON(environ); return i; @@ -5125,16 +5125,16 @@ static int check_envsize(size_t n) { if (_WIN32_WINNT < 0x0600 && rb_w32_osver() < 6) { - /* https://msdn.microsoft.com/en-us/library/windows/desktop/ms682653(v=vs.85).aspx */ - /* Windows Server 2003 and Windows XP: The maximum size of the - * environment block for the process is 32,767 characters. */ - WCHAR* p = GetEnvironmentStringsW(); - if (!p) return -1; /* never happen */ - n += getenvsize(p); - FreeEnvironmentStringsW(p); - if (n >= getenvblocksize()) { - return -1; - } + /* https://msdn.microsoft.com/en-us/library/windows/desktop/ms682653(v=vs.85).aspx */ + /* Windows Server 2003 and Windows XP: The maximum size of the + * environment block for the process is 32,767 characters. */ + WCHAR* p = GetEnvironmentStringsW(); + if (!p) return -1; /* never happen */ + n += getenvsize(p); + FreeEnvironmentStringsW(p); + if (n >= getenvblocksize()) { + return -1; + } } return 0; } @@ -5155,7 +5155,7 @@ static const char * check_envname(const char *name) { if (strchr(name, '=')) { - invalid_envname(name); + invalid_envname(name); } return name; } @@ -5176,26 +5176,26 @@ ruby_setenv(const char *name, const char *value) check_envname(name); len = MultiByteToWideChar(CP_UTF8, 0, name, -1, NULL, 0); if (value) { - int len2; - len2 = MultiByteToWideChar(CP_UTF8, 0, value, -1, NULL, 0); - if (check_envsize((size_t)len + len2)) { /* len and len2 include '\0' */ - goto fail; /* 2 for '=' & '\0' */ - } - wname = ALLOCV_N(WCHAR, buf, len + len2); - wvalue = wname + len; - MultiByteToWideChar(CP_UTF8, 0, name, -1, wname, len); - MultiByteToWideChar(CP_UTF8, 0, value, -1, wvalue, len2); + int len2; + len2 = MultiByteToWideChar(CP_UTF8, 0, value, -1, NULL, 0); + if (check_envsize((size_t)len + len2)) { /* len and len2 include '\0' */ + goto fail; /* 2 for '=' & '\0' */ + } + wname = ALLOCV_N(WCHAR, buf, len + len2); + wvalue = wname + len; + MultiByteToWideChar(CP_UTF8, 0, name, -1, wname, len); + MultiByteToWideChar(CP_UTF8, 0, value, -1, wvalue, len2); #ifndef HAVE__WPUTENV_S - wname[len-1] = L'='; + wname[len-1] = L'='; #endif } else { - wname = ALLOCV_N(WCHAR, buf, len + 1); - MultiByteToWideChar(CP_UTF8, 0, name, -1, wname, len); - wvalue = wname + len; - *wvalue = L'\0'; + wname = ALLOCV_N(WCHAR, buf, len + 1); + MultiByteToWideChar(CP_UTF8, 0, name, -1, wname, len); + wvalue = wname + len; + *wvalue = L'\0'; #ifndef HAVE__WPUTENV_S - wname[len-1] = L'='; + wname[len-1] = L'='; #endif } @@ -5213,13 +5213,13 @@ ruby_setenv(const char *name, const char *value) /* even if putenv() failed, clean up and try to delete the * variable from the system area. */ if (!value || !*value) { - /* putenv() doesn't handle empty value */ - if (!SetEnvironmentVariable(name, value) && - GetLastError() != ERROR_ENVVAR_NOT_FOUND) goto fail; + /* putenv() doesn't handle empty value */ + if (!SetEnvironmentVariable(name, value) && + GetLastError() != ERROR_ENVVAR_NOT_FOUND) goto fail; } if (failed) { fail: - invalid_envname(name); + invalid_envname(name); } #elif defined(HAVE_SETENV) && defined(HAVE_UNSETENV) if (value) { @@ -5289,7 +5289,7 @@ ruby_setenv(const char *name, const char *value) ENV_UNLOCK(); if (ret) { - free(mem_ptr); + free(mem_ptr); rb_sys_fail_str(rb_sprintf("putenv(%s)", name)); } } @@ -5406,7 +5406,7 @@ env_aset(VALUE nm, VALUE val) if (NIL_P(val)) { env_delete(nm); - return Qnil; + return Qnil; } SafeStringValue(nm); SafeStringValue(val); @@ -5512,7 +5512,7 @@ env_each_key(VALUE ehash) RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size); keys = env_keys(FALSE); for (i=0; i 0) { - capa = round_capa(capa); - tbl->capa = (int)capa; - tbl->items = ZALLOC_N(item_t, capa); + capa = round_capa(capa); + tbl->capa = (int)capa; + tbl->items = ZALLOC_N(item_t, capa); } return tbl; } @@ -130,16 +130,16 @@ static int hash_table_index(struct rb_id_table* tbl, id_key_t key) { if (tbl->capa > 0) { - int mask = tbl->capa - 1; - int ix = key & mask; - int d = 1; - while (key != ITEM_GET_KEY(tbl, ix)) { - if (!ITEM_COLLIDED(tbl, ix)) - return -1; - ix = (ix + d) & mask; - d++; - } - return ix; + int mask = tbl->capa - 1; + int ix = key & mask; + int d = 1; + while (key != ITEM_GET_KEY(tbl, ix)) { + if (!ITEM_COLLIDED(tbl, ix)) + return -1; + ix = (ix + d) & mask; + d++; + } + return ix; } return -1; } @@ -152,13 +152,13 @@ hash_table_raw_insert(struct rb_id_table *tbl, id_key_t key, VALUE val) int d = 1; assert(key != 0); while (ITEM_KEY_ISSET(tbl, ix)) { - ITEM_SET_COLLIDED(tbl, ix); - ix = (ix + d) & mask; - d++; + ITEM_SET_COLLIDED(tbl, ix); + ix = (ix + d) & mask; + d++; } tbl->num++; if (!ITEM_COLLIDED(tbl, ix)) { - tbl->used++; + tbl->used++; } ITEM_SET_KEY(tbl, ix, key); tbl->items[ix].val = val; @@ -168,16 +168,16 @@ static int hash_delete_index(struct rb_id_table *tbl, int ix) { if (ix >= 0) { - if (!ITEM_COLLIDED(tbl, ix)) { - tbl->used--; - } - tbl->num--; - ITEM_SET_KEY(tbl, ix, 0); - tbl->items[ix].val = 0; - return TRUE; + if (!ITEM_COLLIDED(tbl, ix)) { + tbl->used--; + } + tbl->num--; + ITEM_SET_KEY(tbl, ix, 0); + tbl->items[ix].val = 0; + return TRUE; } else { - return FALSE; + return FALSE; } } @@ -185,24 +185,24 @@ static void hash_table_extend(struct rb_id_table* tbl) { if (tbl->used + (tbl->used >> 1) >= tbl->capa) { - int new_cap = round_capa(tbl->num + (tbl->num >> 1)); - int i; - item_t* old; - struct rb_id_table tmp_tbl = {0, 0, 0}; - if (new_cap < tbl->capa) { - new_cap = round_capa(tbl->used + (tbl->used >> 1)); - } - tmp_tbl.capa = new_cap; - tmp_tbl.items = ZALLOC_N(item_t, new_cap); - for (i = 0; i < tbl->capa; i++) { - id_key_t key = ITEM_GET_KEY(tbl, i); - if (key != 0) { - hash_table_raw_insert(&tmp_tbl, key, tbl->items[i].val); - } - } - old = tbl->items; - *tbl = tmp_tbl; - xfree(old); + int new_cap = round_capa(tbl->num + (tbl->num >> 1)); + int i; + item_t* old; + struct rb_id_table tmp_tbl = {0, 0, 0}; + if (new_cap < tbl->capa) { + new_cap = round_capa(tbl->used + (tbl->used >> 1)); + } + tmp_tbl.capa = new_cap; + tmp_tbl.items = ZALLOC_N(item_t, new_cap); + for (i = 0; i < tbl->capa; i++) { + id_key_t key = ITEM_GET_KEY(tbl, i); + if (key != 0) { + hash_table_raw_insert(&tmp_tbl, key, tbl->items[i].val); + } + } + old = tbl->items; + *tbl = tmp_tbl; + xfree(old); } } @@ -216,9 +216,9 @@ hash_table_show(struct rb_id_table *tbl) fprintf(stderr, "tbl: %p (capa: %d, num: %d, used: %d)\n", tbl, tbl->capa, tbl->num, tbl->used); for (i=0; i [%d] %s %d\n", i, rb_id2name(key2id(keys[i])), (int)keys[i]); - } + if (ITEM_KEY_ISSET(tbl, i)) { + fprintf(stderr, " -> [%d] %s %d\n", i, rb_id2name(key2id(keys[i])), (int)keys[i]); + } } } #endif @@ -231,10 +231,10 @@ rb_id_table_lookup(struct rb_id_table *tbl, ID id, VALUE *valp) if (index >= 0) { *valp = tbl->items[index].val; - return TRUE; + return TRUE; } else { - return FALSE; + return FALSE; } } @@ -244,11 +244,11 @@ rb_id_table_insert_key(struct rb_id_table *tbl, const id_key_t key, const VALUE const int index = hash_table_index(tbl, key); if (index >= 0) { - tbl->items[index].val = val; + tbl->items[index].val = val; } else { - hash_table_extend(tbl); - hash_table_raw_insert(tbl, key, val); + hash_table_extend(tbl); + hash_table_raw_insert(tbl, key, val); } return TRUE; } @@ -273,16 +273,16 @@ rb_id_table_foreach(struct rb_id_table *tbl, rb_id_table_foreach_func_t *func, v int i, capa = tbl->capa; for (i=0; iitems[i].val, data); - assert(key != 0); + if (ITEM_KEY_ISSET(tbl, i)) { + const id_key_t key = ITEM_GET_KEY(tbl, i); + enum rb_id_table_iterator_result ret = (*func)(key2id(key), tbl->items[i].val, data); + assert(key != 0); - if (ret == ID_TABLE_DELETE) - hash_delete_index(tbl, i); - else if (ret == ID_TABLE_STOP) - return; - } + if (ret == ID_TABLE_DELETE) + hash_delete_index(tbl, i); + else if (ret == ID_TABLE_STOP) + return; + } } } @@ -292,14 +292,14 @@ rb_id_table_foreach_values(struct rb_id_table *tbl, rb_id_table_foreach_values_f int i, capa = tbl->capa; for (i=0; iitems[i].val, data); + if (ITEM_KEY_ISSET(tbl, i)) { + enum rb_id_table_iterator_result ret = (*func)(tbl->items[i].val, data); - if (ret == ID_TABLE_DELETE) - hash_delete_index(tbl, i); - else if (ret == ID_TABLE_STOP) - return; - } + if (ret == ID_TABLE_DELETE) + hash_delete_index(tbl, i); + else if (ret == ID_TABLE_STOP) + return; + } } } diff --git a/include/ruby/ruby.h b/include/ruby/ruby.h index 108127a93c..444940ca3a 100644 --- a/include/ruby/ruby.h +++ b/include/ruby/ruby.h @@ -108,7 +108,7 @@ VALUE rb_get_path_no_checksafe(VALUE); # define rb_varargs_argc_check_runtime(argc, vargc) \ (((argc) <= (vargc)) ? (argc) : \ (rb_fatal("argc(%d) exceeds actual arguments(%d)", \ - argc, vargc), 0)) + argc, vargc), 0)) # define rb_varargs_argc_valid_p(argc, vargc) \ ((argc) == 0 ? (vargc) <= 1 : /* [ruby-core:85266] [Bug #14425] */ \ (argc) == (vargc)) @@ -117,16 +117,16 @@ VALUE rb_get_path_no_checksafe(VALUE); ERRORFUNC((" argument length doesn't match"), int rb_varargs_bad_length(int,int)); # else # define rb_varargs_bad_length(argc, vargc) \ - ((argc)/rb_varargs_argc_valid_p(argc, vargc)) + ((argc)/rb_varargs_argc_valid_p(argc, vargc)) # endif # define rb_varargs_argc_check(argc, vargc) \ __builtin_choose_expr(__builtin_constant_p(argc), \ - (rb_varargs_argc_valid_p(argc, vargc) ? (argc) : \ - rb_varargs_bad_length(argc, vargc)), \ - rb_varargs_argc_check_runtime(argc, vargc)) + (rb_varargs_argc_valid_p(argc, vargc) ? (argc) : \ + rb_varargs_bad_length(argc, vargc)), \ + rb_varargs_argc_check_runtime(argc, vargc)) # else # define rb_varargs_argc_check(argc, vargc) \ - rb_varargs_argc_check_runtime(argc, vargc) + rb_varargs_argc_check_runtime(argc, vargc) # endif #endif /** @endcond */ @@ -277,24 +277,24 @@ int ruby_vsnprintf(char *str, size_t n, char const *fmt, va_list ap); #elif defined(__GNUC__) && defined(HAVE_VA_ARGS_MACRO) && defined(__OPTIMIZE__) # define rb_yield_values(argc, ...) \ __extension__({ \ - const int rb_yield_values_argc = (argc); \ - const VALUE rb_yield_values_args[] = {__VA_ARGS__}; \ - const int rb_yield_values_nargs = \ - (int)(sizeof(rb_yield_values_args) / sizeof(VALUE)); \ - rb_yield_values2( \ - rb_varargs_argc_check(rb_yield_values_argc, rb_yield_values_nargs), \ - rb_yield_values_nargs ? rb_yield_values_args : NULL); \ + const int rb_yield_values_argc = (argc); \ + const VALUE rb_yield_values_args[] = {__VA_ARGS__}; \ + const int rb_yield_values_nargs = \ + (int)(sizeof(rb_yield_values_args) / sizeof(VALUE)); \ + rb_yield_values2( \ + rb_varargs_argc_check(rb_yield_values_argc, rb_yield_values_nargs), \ + rb_yield_values_nargs ? rb_yield_values_args : NULL); \ }) # define rb_funcall(recv, mid, argc, ...) \ __extension__({ \ - const int rb_funcall_argc = (argc); \ - const VALUE rb_funcall_args[] = {__VA_ARGS__}; \ - const int rb_funcall_nargs = \ - (int)(sizeof(rb_funcall_args) / sizeof(VALUE)); \ + const int rb_funcall_argc = (argc); \ + const VALUE rb_funcall_args[] = {__VA_ARGS__}; \ + const int rb_funcall_nargs = \ + (int)(sizeof(rb_funcall_args) / sizeof(VALUE)); \ rb_funcallv(recv, mid, \ - rb_varargs_argc_check(rb_funcall_argc, rb_funcall_nargs), \ - rb_funcall_nargs ? rb_funcall_args : NULL); \ + rb_varargs_argc_check(rb_funcall_argc, rb_funcall_nargs), \ + rb_funcall_nargs ? rb_funcall_args : NULL); \ }) #endif /** @endcond */ diff --git a/include/ruby/thread.h b/include/ruby/thread.h index 299aa2d62e..0b5b1ca0f3 100644 --- a/include/ruby/thread.h +++ b/include/ruby/thread.h @@ -128,7 +128,7 @@ RBIMPL_ATTR_NONNULL((1)) * your code to see if it is actually worth releasing the GVL. */ void *rb_thread_call_without_gvl(void *(*func)(void *), void *data1, - rb_unblock_function_t *ubf, void *data2); + rb_unblock_function_t *ubf, void *data2); RBIMPL_ATTR_NONNULL((1)) /** @@ -152,7 +152,7 @@ RBIMPL_ATTR_NONNULL((1)) * @return What `func` returned, or 0 in case `func` did not return. */ void *rb_thread_call_without_gvl2(void *(*func)(void *), void *data1, - rb_unblock_function_t *ubf, void *data2); + rb_unblock_function_t *ubf, void *data2); /* * XXX: unstable/unapproved - out-of-tree code should NOT not depend diff --git a/include/ruby/util.h b/include/ruby/util.h index b2bc1a09f6..f0ea874322 100644 --- a/include/ruby/util.h +++ b/include/ruby/util.h @@ -124,7 +124,7 @@ unsigned long ruby_scan_hex(const char *str, size_t len, size_t *ret); # define ruby_qsort qsort_r #else void ruby_qsort(void *, const size_t, const size_t, - int (*)(const void *, const void *, void *), void *); + int (*)(const void *, const void *, void *), void *); #endif RBIMPL_ATTR_NONNULL((1)) diff --git a/include/ruby/win32.h b/include/ruby/win32.h index a3f466d627..ea460a5e46 100644 --- a/include/ruby/win32.h +++ b/include/ruby/win32.h @@ -702,10 +702,10 @@ extern char *rb_w32_strerror(int); #endif struct tms { - long tms_utime; - long tms_stime; - long tms_cutime; - long tms_cstime; + long tms_utime; + long tms_stime; + long tms_cutime; + long tms_cstime; }; int rb_w32_times(struct tms *); diff --git a/insns.def b/insns.def index b5dea9c10c..06ca31a850 100644 --- a/insns.def +++ b/insns.def @@ -109,14 +109,14 @@ getblockparam VM_ASSERT(VM_ENV_LOCAL_P(ep)); if (!VM_ENV_FLAGS(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM)) { - val = rb_vm_bh_to_procval(ec, VM_ENV_BLOCK_HANDLER(ep)); - vm_env_write(ep, -(int)idx, val); - VM_ENV_FLAGS_SET(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM); + val = rb_vm_bh_to_procval(ec, VM_ENV_BLOCK_HANDLER(ep)); + vm_env_write(ep, -(int)idx, val); + VM_ENV_FLAGS_SET(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM); } else { - val = *(ep - idx); - RB_DEBUG_COUNTER_INC(lvar_get); - (void)RB_DEBUG_COUNTER_INC_IF(lvar_get_dynamic, level > 0); + val = *(ep - idx); + RB_DEBUG_COUNTER_INC(lvar_get); + (void)RB_DEBUG_COUNTER_INC_IF(lvar_get_dynamic, level > 0); } } @@ -150,35 +150,35 @@ getblockparamproxy VM_ASSERT(VM_ENV_LOCAL_P(ep)); if (!VM_ENV_FLAGS(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM)) { - VALUE block_handler = VM_ENV_BLOCK_HANDLER(ep); + VALUE block_handler = VM_ENV_BLOCK_HANDLER(ep); - if (block_handler) { - switch (vm_block_handler_type(block_handler)) { - case block_handler_type_iseq: - case block_handler_type_ifunc: - val = rb_block_param_proxy; - break; - case block_handler_type_symbol: - val = rb_sym_to_proc(VM_BH_TO_SYMBOL(block_handler)); - goto INSN_LABEL(set); - case block_handler_type_proc: - val = VM_BH_TO_PROC(block_handler); - goto INSN_LABEL(set); - default: - VM_UNREACHABLE(getblockparamproxy); - } - } - else { - val = Qnil; - INSN_LABEL(set): - vm_env_write(ep, -(int)idx, val); - VM_ENV_FLAGS_SET(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM); - } + if (block_handler) { + switch (vm_block_handler_type(block_handler)) { + case block_handler_type_iseq: + case block_handler_type_ifunc: + val = rb_block_param_proxy; + break; + case block_handler_type_symbol: + val = rb_sym_to_proc(VM_BH_TO_SYMBOL(block_handler)); + goto INSN_LABEL(set); + case block_handler_type_proc: + val = VM_BH_TO_PROC(block_handler); + goto INSN_LABEL(set); + default: + VM_UNREACHABLE(getblockparamproxy); + } + } + else { + val = Qnil; + INSN_LABEL(set): + vm_env_write(ep, -(int)idx, val); + VM_ENV_FLAGS_SET(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM); + } } else { - val = *(ep - idx); - RB_DEBUG_COUNTER_INC(lvar_get); - (void)RB_DEBUG_COUNTER_INC_IF(lvar_get_dynamic, level > 0); + val = *(ep - idx); + RB_DEBUG_COUNTER_INC(lvar_get); + (void)RB_DEBUG_COUNTER_INC_IF(lvar_get_dynamic, level > 0); } } @@ -715,8 +715,8 @@ defineclass /* enter scope */ vm_push_frame(ec, class_iseq, VM_FRAME_MAGIC_CLASS | VM_ENV_FLAG_LOCAL, klass, - GET_BLOCK_HANDLER(), - (VALUE)vm_cref_push(ec, klass, NULL, FALSE, FALSE), + GET_BLOCK_HANDLER(), + (VALUE)vm_cref_push(ec, klass, NULL, FALSE, FALSE), ISEQ_BODY(class_iseq)->iseq_encoded, GET_SP(), ISEQ_BODY(class_iseq)->local_table_size, ISEQ_BODY(class_iseq)->stack_max); @@ -920,19 +920,19 @@ leave const VALUE *const bp = vm_base_ptr(GET_CFP()); if (GET_SP() != bp) { vm_stack_consistency_error(ec, GET_CFP(), bp); - } + } } if (vm_pop_frame(ec, GET_CFP(), GET_EP())) { #if OPT_CALL_THREADED_CODE - rb_ec_thread_ptr(ec)->retval = val; - return 0; + rb_ec_thread_ptr(ec)->retval = val; + return 0; #else - return val; + return val; #endif } else { - RESTORE_REGS(); + RESTORE_REGS(); } } @@ -981,8 +981,8 @@ branchif // attr bool leaf = leafness_of_check_ints; /* has rb_threadptr_execute_interrupts() */ { if (RTEST(val)) { - RUBY_VM_CHECK_INTS(ec); - JUMP(dst); + RUBY_VM_CHECK_INTS(ec); + JUMP(dst); } } @@ -996,8 +996,8 @@ branchunless // attr bool leaf = leafness_of_check_ints; /* has rb_threadptr_execute_interrupts() */ { if (!RTEST(val)) { - RUBY_VM_CHECK_INTS(ec); - JUMP(dst); + RUBY_VM_CHECK_INTS(ec); + JUMP(dst); } } @@ -1011,8 +1011,8 @@ branchnil // attr bool leaf = leafness_of_check_ints; /* has rb_threadptr_execute_interrupts() */ { if (NIL_P(val)) { - RUBY_VM_CHECK_INTS(ec); - JUMP(dst); + RUBY_VM_CHECK_INTS(ec); + JUMP(dst); } } @@ -1081,7 +1081,7 @@ opt_case_dispatch OFFSET dst = vm_case_dispatch(hash, else_offset, key); if (dst) { - JUMP(dst); + JUMP(dst); } } @@ -1340,12 +1340,12 @@ opt_aset_with VALUE tmp = vm_opt_aset_with(recv, key, val); if (tmp != Qundef) { - val = tmp; + val = tmp; } else { #ifndef MJIT_HEADER - TOPN(0) = rb_str_resurrect(key); - PUSH(val); + TOPN(0) = rb_str_resurrect(key); + PUSH(val); #endif CALL_SIMPLE_METHOD(); } @@ -1364,7 +1364,7 @@ opt_aref_with if (val == Qundef) { #ifndef MJIT_HEADER - PUSH(rb_str_resurrect(key)); + PUSH(rb_str_resurrect(key)); #endif CALL_SIMPLE_METHOD(); } @@ -1467,9 +1467,9 @@ opt_call_c_function reg_cfp = (funcptr)(ec, reg_cfp); if (reg_cfp == 0) { - VALUE err = ec->errinfo; - ec->errinfo = Qnil; - THROW_EXCEPTION(err); + VALUE err = ec->errinfo; + ec->errinfo = Qnil; + THROW_EXCEPTION(err); } RESTORE_REGS(); diff --git a/io.c b/io.c index 650ea5e377..7149013566 100644 --- a/io.c +++ b/io.c @@ -254,7 +254,7 @@ rb_update_max_fd(int fd) } while (max_fd < afd) { - max_fd = ATOMIC_CAS(max_file_descriptor, max_fd, afd); + max_fd = ATOMIC_CAS(max_file_descriptor, max_fd, afd); } } @@ -299,7 +299,7 @@ rb_fix_detect_o_cloexec(int fd) rb_bug("rb_fix_detect_o_cloexec: fcntl(%d, F_GETFD) failed: %s", fd, strerror(errno)); if (flags & FD_CLOEXEC) - return 1; + return 1; #endif /* fall through if O_CLOEXEC does not work: */ rb_maygvl_fd_fix_cloexec(fd); return 0; @@ -339,13 +339,13 @@ rb_cloexec_open(const char *pathname, int flags, mode_t mode) if (ret < 0) return ret; if (ret <= 2 || o_cloexec_state == 0) { - rb_maygvl_fd_fix_cloexec(ret); + rb_maygvl_fd_fix_cloexec(ret); } else if (o_cloexec_state > 0) { - return ret; + return ret; } else { - o_cloexec_state = rb_fix_detect_o_cloexec(ret); + o_cloexec_state = rb_fix_detect_o_cloexec(ret); } return ret; } @@ -598,19 +598,19 @@ raise_on_write(rb_io_t *fptr, int e, VALUE errinfo) #define NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr) do {\ if (NEED_NEWLINE_DECORATOR_ON_READ(fptr)) {\ - if (((fptr)->mode & FMODE_READABLE) &&\ - !((fptr)->encs.ecflags & ECONV_NEWLINE_DECORATOR_MASK)) {\ - setmode((fptr)->fd, O_BINARY);\ - }\ - else {\ - setmode((fptr)->fd, O_TEXT);\ - }\ + if (((fptr)->mode & FMODE_READABLE) &&\ + !((fptr)->encs.ecflags & ECONV_NEWLINE_DECORATOR_MASK)) {\ + setmode((fptr)->fd, O_BINARY);\ + }\ + else {\ + setmode((fptr)->fd, O_TEXT);\ + }\ }\ } while(0) #define SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags) do {\ if ((enc2) && ((ecflags) & ECONV_DEFAULT_NEWLINE_DECORATOR)) {\ - (ecflags) |= ECONV_UNIVERSAL_NEWLINE_DECORATOR;\ + (ecflags) |= ECONV_UNIVERSAL_NEWLINE_DECORATOR;\ }\ } while(0) @@ -630,28 +630,28 @@ io_unread(rb_io_t *fptr) rb_io_check_closed(fptr); if (fptr->rbuf.len == 0 || fptr->mode & FMODE_DUPLEX) { - return; + return; } errno = 0; if (!rb_w32_fd_is_text(fptr->fd)) { - r = lseek(fptr->fd, -fptr->rbuf.len, SEEK_CUR); - if (r < 0 && errno) { - if (errno == ESPIPE) - fptr->mode |= FMODE_DUPLEX; - return; - } + r = lseek(fptr->fd, -fptr->rbuf.len, SEEK_CUR); + if (r < 0 && errno) { + if (errno == ESPIPE) + fptr->mode |= FMODE_DUPLEX; + return; + } - fptr->rbuf.off = 0; - fptr->rbuf.len = 0; - return; + fptr->rbuf.off = 0; + fptr->rbuf.len = 0; + return; } pos = lseek(fptr->fd, 0, SEEK_CUR); if (pos < 0 && errno) { - if (errno == ESPIPE) - fptr->mode |= FMODE_DUPLEX; - return; + if (errno == ESPIPE) + fptr->mode |= FMODE_DUPLEX; + return; } /* add extra offset for removed '\r' in rbuf */ @@ -660,36 +660,36 @@ io_unread(rb_io_t *fptr) /* if the end of rbuf is '\r', rbuf doesn't have '\r' within rbuf.len */ if (*(fptr->rbuf.ptr + fptr->rbuf.capa - 1) == '\r') { - newlines++; + newlines++; } for (i = 0; i < fptr->rbuf.len; i++) { - if (*p == '\n') newlines++; - if (extra_max == newlines) break; - p++; + if (*p == '\n') newlines++; + if (extra_max == newlines) break; + p++; } buf = ALLOC_N(char, fptr->rbuf.len + newlines); while (newlines >= 0) { - r = lseek(fptr->fd, pos - fptr->rbuf.len - newlines, SEEK_SET); - if (newlines == 0) break; - if (r < 0) { - newlines--; - continue; - } - read_size = _read(fptr->fd, buf, fptr->rbuf.len + newlines); - if (read_size < 0) { - int e = errno; - free(buf); - rb_syserr_fail_path(e, fptr->pathv); - } - if (read_size == fptr->rbuf.len) { - lseek(fptr->fd, r, SEEK_SET); - break; - } - else { - newlines--; - } + r = lseek(fptr->fd, pos - fptr->rbuf.len - newlines, SEEK_SET); + if (newlines == 0) break; + if (r < 0) { + newlines--; + continue; + } + read_size = _read(fptr->fd, buf, fptr->rbuf.len + newlines); + if (read_size < 0) { + int e = errno; + free(buf); + rb_syserr_fail_path(e, fptr->pathv); + } + if (read_size == fptr->rbuf.len) { + lseek(fptr->fd, r, SEEK_SET); + break; + } + else { + newlines--; + } } free(buf); fptr->rbuf.off = 0; @@ -710,7 +710,7 @@ set_binary_mode_with_seek_cur(rb_io_t *fptr) if (!rb_w32_fd_is_text(fptr->fd)) return O_BINARY; if (fptr->rbuf.len == 0 || fptr->mode & FMODE_DUPLEX) { - return setmode(fptr->fd, O_BINARY); + return setmode(fptr->fd, O_BINARY); } flush_before_seek(fptr); return setmode(fptr->fd, O_BINARY); @@ -779,7 +779,7 @@ void rb_io_check_initialized(rb_io_t *fptr) { if (!fptr) { - rb_raise(rb_eIOError, "uninitialized stream"); + rb_raise(rb_eIOError, "uninitialized stream"); } } @@ -827,10 +827,10 @@ rb_io_set_write_io(VALUE io, VALUE w) VALUE write_io; rb_io_t *fptr = rb_io_get_fptr(io); if (!RTEST(w)) { - w = 0; + w = 0; } else { - GetWriteIO(w); + GetWriteIO(w); } write_io = fptr->tied_io_for_writing; fptr->tied_io_for_writing = w; @@ -889,17 +889,17 @@ io_ungetbyte(VALUE str, rb_io_t *fptr) fptr->rbuf.off = 0; fptr->rbuf.len = 0; #if SIZEOF_LONG > SIZEOF_INT - if (len > INT_MAX) - rb_raise(rb_eIOError, "ungetbyte failed"); + if (len > INT_MAX) + rb_raise(rb_eIOError, "ungetbyte failed"); #endif - if (len > min_capa) - fptr->rbuf.capa = (int)len; - else - fptr->rbuf.capa = min_capa; + if (len > min_capa) + fptr->rbuf.capa = (int)len; + else + fptr->rbuf.capa = min_capa; fptr->rbuf.ptr = ALLOC_N(char, fptr->rbuf.capa); } if (fptr->rbuf.capa < len + fptr->rbuf.len) { - rb_raise(rb_eIOError, "ungetbyte failed"); + rb_raise(rb_eIOError, "ungetbyte failed"); } if (fptr->rbuf.off < len) { MEMMOVE(fptr->rbuf.ptr+fptr->rbuf.capa-fptr->rbuf.len, @@ -936,15 +936,15 @@ rb_io_check_char_readable(rb_io_t *fptr) { rb_io_check_closed(fptr); if (!(fptr->mode & FMODE_READABLE)) { - rb_raise(rb_eIOError, "not opened for reading"); + rb_raise(rb_eIOError, "not opened for reading"); } if (fptr->wbuf.len) { if (io_fflush(fptr) < 0) rb_sys_fail_on_write(fptr); } if (fptr->tied_io_for_writing) { - rb_io_t *wfptr; - GetOpenFile(fptr->tied_io_for_writing, wfptr); + rb_io_t *wfptr; + GetOpenFile(fptr->tied_io_for_writing, wfptr); if (io_fflush(wfptr) < 0) rb_sys_fail_on_write(wfptr); } @@ -955,7 +955,7 @@ rb_io_check_byte_readable(rb_io_t *fptr) { rb_io_check_char_readable(fptr); if (READ_CHAR_PENDING(fptr)) { - rb_raise(rb_eIOError, "byte oriented read for character buffered IO"); + rb_raise(rb_eIOError, "byte oriented read for character buffered IO"); } } @@ -969,7 +969,7 @@ static rb_encoding* io_read_encoding(rb_io_t *fptr) { if (fptr->encs.enc) { - return fptr->encs.enc; + return fptr->encs.enc; } return rb_default_external_encoding(); } @@ -978,7 +978,7 @@ static rb_encoding* io_input_encoding(rb_io_t *fptr) { if (fptr->encs.enc2) { - return fptr->encs.enc2; + return fptr->encs.enc2; } return io_read_encoding(fptr); } @@ -988,7 +988,7 @@ rb_io_check_writable(rb_io_t *fptr) { rb_io_check_closed(fptr); if (!(fptr->mode & FMODE_WRITABLE)) { - rb_raise(rb_eIOError, "not opened for writing"); + rb_raise(rb_eIOError, "not opened for writing"); } if (fptr->rbuf.len) { io_unread(fptr); @@ -1017,8 +1017,8 @@ int rb_gc_for_fd(int err) { if (err == EMFILE || err == ENFILE || err == ENOMEM) { - rb_gc(); - return 1; + rb_gc(); + return 1; } return 0; } @@ -1030,13 +1030,13 @@ ruby_dup(int orig) fd = rb_cloexec_dup(orig); if (fd < 0) { - int e = errno; - if (rb_gc_for_fd(e)) { - fd = rb_cloexec_dup(orig); - } - if (fd < 0) { - rb_syserr_fail(e, 0); - } + int e = errno; + if (rb_gc_for_fd(e)) { + fd = rb_cloexec_dup(orig); + } + if (fd < 0) { + rb_syserr_fail(e, 0); + } } rb_update_max_fd(fd); return fd; @@ -1200,14 +1200,14 @@ io_flush_buffer_sync(void *arg) ssize_t r = write(fptr->fd, fptr->wbuf.ptr+fptr->wbuf.off, (size_t)l); if (fptr->wbuf.len <= r) { - fptr->wbuf.off = 0; - fptr->wbuf.len = 0; - return 0; + fptr->wbuf.off = 0; + fptr->wbuf.len = 0; + return 0; } if (0 <= r) { - fptr->wbuf.off += (int)r; - fptr->wbuf.len -= (int)r; - errno = EAGAIN; + fptr->wbuf.off += (int)r; + fptr->wbuf.len -= (int)r; + errno = EAGAIN; } return (VALUE)-1; } @@ -1725,7 +1725,7 @@ do_writeconv(VALUE str, rb_io_t *fptr, int *converted) { if (NEED_WRITECONV(fptr)) { VALUE common_encoding = Qnil; - SET_BINARY_MODE(fptr); + SET_BINARY_MODE(fptr); make_writeconv(fptr); @@ -1749,27 +1749,27 @@ do_writeconv(VALUE str, rb_io_t *fptr, int *converted) if (!NIL_P(common_encoding)) { str = rb_str_encode(str, common_encoding, fptr->writeconv_pre_ecflags, fptr->writeconv_pre_ecopts); - *converted = 1; + *converted = 1; } if (fptr->writeconv) { str = rb_econv_str_convert(fptr->writeconv, str, ECONV_PARTIAL_INPUT); - *converted = 1; + *converted = 1; } } #if RUBY_CRLF_ENVIRONMENT #define fmode (fptr->mode) else if (MODE_BTMODE(DEFAULT_TEXTMODE,0,1)) { - if ((fptr->mode & FMODE_READABLE) && - !(fptr->encs.ecflags & ECONV_NEWLINE_DECORATOR_MASK)) { - setmode(fptr->fd, O_BINARY); - } - else { - setmode(fptr->fd, O_TEXT); - } - if (!rb_enc_asciicompat(rb_enc_get(str))) { - rb_raise(rb_eArgError, "ASCII incompatible string written for text mode IO without encoding conversion: %s", - rb_enc_name(rb_enc_get(str))); + if ((fptr->mode & FMODE_READABLE) && + !(fptr->encs.ecflags & ECONV_NEWLINE_DECORATOR_MASK)) { + setmode(fptr->fd, O_BINARY); + } + else { + setmode(fptr->fd, O_TEXT); + } + if (!rb_enc_asciicompat(rb_enc_get(str))) { + rb_raise(rb_eArgError, "ASCII incompatible string written for text mode IO without encoding conversion: %s", + rb_enc_name(rb_enc_get(str))); } } #undef fmode @@ -2152,7 +2152,7 @@ nogvl_fsync(void *ptr) #ifdef _WIN32 if (GetFileType((HANDLE)rb_w32_get_osfhandle(fptr->fd)) != FILE_TYPE_DISK) - return 0; + return 0; #endif return (VALUE)fsync(fptr->fd); } @@ -2319,7 +2319,7 @@ rb_io_seek_m(int argc, VALUE *argv, VALUE io) int whence = SEEK_SET; if (rb_scan_args(argc, argv, "11", &offset, &ptrname) == 2) { - whence = interpret_seek_whence(ptrname); + whence = interpret_seek_whence(ptrname); } return rb_io_seek(io, offset, whence); @@ -2390,11 +2390,11 @@ rb_io_rewind(VALUE io) GetOpenFile(io, fptr); if (io_seek(fptr, 0L, 0) < 0 && errno) rb_sys_fail_path(fptr->pathv); if (io == ARGF.current_file) { - ARGF.lineno -= fptr->lineno; + ARGF.lineno -= fptr->lineno; } fptr->lineno = 0; if (fptr->readconv) { - clear_readconv(fptr); + clear_readconv(fptr); } return INT2FIX(0); @@ -2501,7 +2501,7 @@ rb_io_eof(VALUE io) READ_CHECK(fptr); #if RUBY_CRLF_ENVIRONMENT if (!NEED_READCONV(fptr) && NEED_NEWLINE_DECORATOR_ON_READ(fptr)) { - return RBOOL(eof(fptr->fd));; + return RBOOL(eof(fptr->fd));; } #endif return RBOOL(io_fillbuf(fptr) < 0); @@ -2568,10 +2568,10 @@ rb_io_set_sync(VALUE io, VALUE sync) io = GetWriteIO(io); GetOpenFile(io, fptr); if (RTEST(sync)) { - fptr->mode |= FMODE_SYNC; + fptr->mode |= FMODE_SYNC; } else { - fptr->mode &= ~FMODE_SYNC; + fptr->mode &= ~FMODE_SYNC; } return sync; } @@ -2605,7 +2605,7 @@ rb_io_fsync(VALUE io) if (io_fflush(fptr) < 0) rb_sys_fail_on_write(fptr); if ((int)rb_thread_io_blocking_region(nogvl_fsync, fptr, fptr->fd) < 0) - rb_sys_fail_path(fptr->pathv); + rb_sys_fail_path(fptr->pathv); return INT2FIX(0); } #else @@ -2627,7 +2627,7 @@ nogvl_fdatasync(void *ptr) #ifdef _WIN32 if (GetFileType((HANDLE)rb_w32_get_osfhandle(fptr->fd)) != FILE_TYPE_DISK) - return 0; + return 0; #endif return (VALUE)fdatasync(fptr->fd); } @@ -2655,7 +2655,7 @@ rb_io_fdatasync(VALUE io) rb_sys_fail_on_write(fptr); if ((int)rb_thread_io_blocking_region(nogvl_fdatasync, fptr, fptr->fd) == 0) - return INT2FIX(0); + return INT2FIX(0); /* fall back */ return rb_io_fsync(io); @@ -2733,7 +2733,7 @@ rb_io_pid(VALUE io) GetOpenFile(io, fptr); if (!fptr->pid) - return Qnil; + return Qnil; return PIDT2NUM(fptr->pid); } @@ -2764,16 +2764,16 @@ rb_io_inspect(VALUE obj) rb_str_cat2(result, ":"); if (NIL_P(fptr->pathv)) { if (fptr->fd < 0) { - rb_str_cat(result, closed+1, strlen(closed)-1); + rb_str_cat(result, closed+1, strlen(closed)-1); } else { - rb_str_catf(result, "fd %d", fptr->fd); + rb_str_catf(result, "fd %d", fptr->fd); } } else { - rb_str_append(result, fptr->pathv); + rb_str_append(result, fptr->pathv); if (fptr->fd < 0) { - rb_str_cat(result, closed, strlen(closed)); + rb_str_cat(result, closed, strlen(closed)); } } return rb_str_cat2(result, ">"); @@ -2887,22 +2887,22 @@ remain_size(rb_io_t *fptr) if (fstat(fptr->fd, &st) == 0 && S_ISREG(st.st_mode) #if defined(__HAIKU__) - && (st.st_dev > 3) + && (st.st_dev > 3) #endif - ) + ) { if (io_fflush(fptr) < 0) rb_sys_fail_on_write(fptr); - pos = lseek(fptr->fd, 0, SEEK_CUR); - if (st.st_size >= pos && pos >= 0) { - siz += st.st_size - pos; - if (siz > LONG_MAX) { - rb_raise(rb_eIOError, "file too big for single read"); - } - } + pos = lseek(fptr->fd, 0, SEEK_CUR); + if (st.st_size >= pos && pos >= 0) { + siz += st.st_size - pos; + if (siz > LONG_MAX) { + rb_raise(rb_eIOError, "file too big for single read"); + } + } } else { - siz += BUFSIZ; + siz += BUFSIZ; } return (long)siz; } @@ -2937,7 +2937,7 @@ make_readconv(rb_io_t *fptr, int size) rb_exc_raise(rb_econv_open_exc(sname, dname, ecflags)); fptr->cbuf.off = 0; fptr->cbuf.len = 0; - if (size < IO_CBUF_CAPA_MIN) size = IO_CBUF_CAPA_MIN; + if (size < IO_CBUF_CAPA_MIN) size = IO_CBUF_CAPA_MIN; fptr->cbuf.capa = size; fptr->cbuf.ptr = ALLOC_N(char, fptr->cbuf.capa); } @@ -2994,27 +2994,27 @@ fill_cbuf(rb_io_t *fptr, int ec_flags) if (res == econv_finished) { return MORE_CHAR_FINISHED; - } + } if (res == econv_source_buffer_empty) { if (fptr->rbuf.len == 0) { - READ_CHECK(fptr); + READ_CHECK(fptr); if (io_fillbuf(fptr) < 0) { - if (!fptr->readconv) { - return MORE_CHAR_FINISHED; - } + if (!fptr->readconv) { + return MORE_CHAR_FINISHED; + } ds = dp = (unsigned char *)fptr->cbuf.ptr + fptr->cbuf.off + fptr->cbuf.len; de = (unsigned char *)fptr->cbuf.ptr + fptr->cbuf.capa; res = rb_econv_convert(fptr->readconv, NULL, NULL, &dp, de, 0); fptr->cbuf.len += (int)(dp - ds); rb_econv_check_error(fptr->readconv); - break; + break; } } } } if (cbuf_len0 != fptr->cbuf.len) - return MORE_CHAR_SUSPENDED; + return MORE_CHAR_SUSPENDED; return MORE_CHAR_FINISHED; } @@ -3034,14 +3034,14 @@ io_shift_cbuf(rb_io_t *fptr, int len, VALUE *strp) { VALUE str = Qnil; if (strp) { - str = *strp; - if (NIL_P(str)) { - *strp = str = rb_str_new(fptr->cbuf.ptr+fptr->cbuf.off, len); - } - else { - rb_str_cat(str, fptr->cbuf.ptr+fptr->cbuf.off, len); - } - rb_enc_associate(str, fptr->encs.enc); + str = *strp; + if (NIL_P(str)) { + *strp = str = rb_str_new(fptr->cbuf.ptr+fptr->cbuf.off, len); + } + else { + rb_str_cat(str, fptr->cbuf.ptr+fptr->cbuf.off, len); + } + rb_enc_associate(str, fptr->encs.enc); } fptr->cbuf.off += len; fptr->cbuf.len -= len; @@ -3062,17 +3062,17 @@ io_setstrbuf(VALUE *str, long len) len = (len + 1) & ~1L; /* round up for wide char */ #endif if (NIL_P(*str)) { - *str = rb_str_new(0, len); - return TRUE; + *str = rb_str_new(0, len); + return TRUE; } else { - VALUE s = StringValue(*str); - long clen = RSTRING_LEN(s); - if (clen >= len) { - rb_str_modify(s); - return FALSE; - } - len -= clen; + VALUE s = StringValue(*str); + long clen = RSTRING_LEN(s); + if (clen >= len) { + rb_str_modify(s); + return FALSE; + } + len -= clen; } rb_str_modify_expand(*str, len); return FALSE; @@ -3083,7 +3083,7 @@ static void io_shrink_read_string(VALUE str, long n) { if (rb_str_capacity(str) - n > MAX_REALLOC_GAP) { - rb_str_resize(str, n); + rb_str_resize(str, n); } } @@ -3091,9 +3091,9 @@ static void io_set_read_length(VALUE str, long n, int shrinkable) { if (RSTRING_LEN(str) != n) { - rb_str_modify(str); - rb_str_set_len(str, n); - if (shrinkable) io_shrink_read_string(str, n); + rb_str_modify(str); + rb_str_set_len(str, n); + if (shrinkable) io_shrink_read_string(str, n); } } @@ -3108,28 +3108,28 @@ read_all(rb_io_t *fptr, long siz, VALUE str) int shrinkable; if (NEED_READCONV(fptr)) { - int first = !NIL_P(str); - SET_BINARY_MODE(fptr); - shrinkable = io_setstrbuf(&str,0); + int first = !NIL_P(str); + SET_BINARY_MODE(fptr); + shrinkable = io_setstrbuf(&str,0); make_readconv(fptr, 0); while (1) { VALUE v; if (fptr->cbuf.len) { - if (first) rb_str_set_len(str, first = 0); + if (first) rb_str_set_len(str, first = 0); io_shift_cbuf(fptr, fptr->cbuf.len, &str); } v = fill_cbuf(fptr, 0); if (v != MORE_CHAR_SUSPENDED && v != MORE_CHAR_FINISHED) { if (fptr->cbuf.len) { - if (first) rb_str_set_len(str, first = 0); + if (first) rb_str_set_len(str, first = 0); io_shift_cbuf(fptr, fptr->cbuf.len, &str); } rb_exc_raise(v); } if (v == MORE_CHAR_FINISHED) { clear_readconv(fptr); - if (first) rb_str_set_len(str, first = 0); - if (shrinkable) io_shrink_read_string(str, RSTRING_LEN(str)); + if (first) rb_str_set_len(str, first = 0); + if (shrinkable) io_shrink_read_string(str, RSTRING_LEN(str)); return io_enc_str(str, fptr); } } @@ -3145,19 +3145,19 @@ read_all(rb_io_t *fptr, long siz, VALUE str) if (siz == 0) siz = BUFSIZ; shrinkable = io_setstrbuf(&str, siz); for (;;) { - READ_CHECK(fptr); - n = io_fread(str, bytes, siz - bytes, fptr); - if (n == 0 && bytes == 0) { - rb_str_set_len(str, 0); - break; - } - bytes += n; - rb_str_set_len(str, bytes); - if (cr != ENC_CODERANGE_BROKEN) - pos += rb_str_coderange_scan_restartable(RSTRING_PTR(str) + pos, RSTRING_PTR(str) + bytes, enc, &cr); - if (bytes < siz) break; - siz += BUFSIZ; - rb_str_modify_expand(str, BUFSIZ); + READ_CHECK(fptr); + n = io_fread(str, bytes, siz - bytes, fptr); + if (n == 0 && bytes == 0) { + rb_str_set_len(str, 0); + break; + } + bytes += n; + rb_str_set_len(str, bytes); + if (cr != ENC_CODERANGE_BROKEN) + pos += rb_str_coderange_scan_restartable(RSTRING_PTR(str) + pos, RSTRING_PTR(str) + bytes, enc, &cr); + if (bytes < siz) break; + siz += BUFSIZ; + rb_str_modify_expand(str, BUFSIZ); } if (shrinkable) io_shrink_read_string(str, RSTRING_LEN(str)); str = io_enc_str(str, fptr); @@ -3169,7 +3169,7 @@ void rb_io_set_nonblock(rb_io_t *fptr) { if (rb_fd_set_nonblock(fptr->fd) != 0) { - rb_sys_fail_path(fptr->pathv); + rb_sys_fail_path(fptr->pathv); } } @@ -3211,7 +3211,7 @@ io_getpartial(int argc, VALUE *argv, VALUE io, int no_exception, int nonblock) rb_scan_args(argc, argv, "11", &length, &str); if ((len = NUM2LONG(length)) < 0) { - rb_raise(rb_eArgError, "negative length %ld given", len); + rb_raise(rb_eArgError, "negative length %ld given", len); } shrinkable = io_setstrbuf(&str, len); @@ -3220,8 +3220,8 @@ io_getpartial(int argc, VALUE *argv, VALUE io, int no_exception, int nonblock) rb_io_check_byte_readable(fptr); if (len == 0) { - io_set_read_length(str, 0, shrinkable); - return str; + io_set_read_length(str, 0, shrinkable); + return str; } if (!nonblock) @@ -3232,7 +3232,7 @@ io_getpartial(int argc, VALUE *argv, VALUE io, int no_exception, int nonblock) if (nonblock) { rb_io_set_nonblock(fptr); } - io_setstrbuf(&str, len); + io_setstrbuf(&str, len); iis.th = rb_thread_current(); iis.fptr = fptr; iis.nonblock = nonblock; @@ -3240,15 +3240,15 @@ io_getpartial(int argc, VALUE *argv, VALUE io, int no_exception, int nonblock) iis.capa = len; n = read_internal_locktmp(str, &iis); if (n < 0) { - int e = errno; + int e = errno; if (!nonblock && fptr_wait_readable(fptr)) goto again; - if (nonblock && (io_again_p(e))) { + if (nonblock && (io_again_p(e))) { if (no_exception) return sym_wait_readable; else - rb_readwrite_syserr_fail(RB_IO_WAIT_READABLE, - e, "read would block"); + rb_readwrite_syserr_fail(RB_IO_WAIT_READABLE, + e, "read would block"); } rb_syserr_fail_path(e, fptr->pathv); } @@ -3383,7 +3383,7 @@ io_read_nonblock(rb_execution_context_t *ec, VALUE io, VALUE length, VALUE str, int shrinkable; if ((len = NUM2LONG(length)) < 0) { - rb_raise(rb_eArgError, "negative length %ld given", len); + rb_raise(rb_eArgError, "negative length %ld given", len); } shrinkable = io_setstrbuf(&str, len); @@ -3393,25 +3393,25 @@ io_read_nonblock(rb_execution_context_t *ec, VALUE io, VALUE length, VALUE str, rb_io_check_byte_readable(fptr); if (len == 0) { - io_set_read_length(str, 0, shrinkable); - return str; + io_set_read_length(str, 0, shrinkable); + return str; } n = read_buffered_data(RSTRING_PTR(str), len, fptr); if (n <= 0) { - rb_io_set_nonblock(fptr); - shrinkable |= io_setstrbuf(&str, len); + rb_io_set_nonblock(fptr); + shrinkable |= io_setstrbuf(&str, len); iis.fptr = fptr; iis.nonblock = 1; iis.buf = RSTRING_PTR(str); iis.capa = len; n = read_internal_locktmp(str, &iis); if (n < 0) { - int e = errno; - if (io_again_p(e)) { + int e = errno; + if (io_again_p(e)) { if (!ex) return sym_wait_readable; - rb_readwrite_syserr_fail(RB_IO_WAIT_READABLE, - e, "read would block"); + rb_readwrite_syserr_fail(RB_IO_WAIT_READABLE, + e, "read would block"); } rb_syserr_fail_path(e, fptr->pathv); } @@ -3420,7 +3420,7 @@ io_read_nonblock(rb_execution_context_t *ec, VALUE io, VALUE length, VALUE str, if (n == 0) { if (!ex) return Qnil; - rb_eof_error(); + rb_eof_error(); } return str; @@ -3434,7 +3434,7 @@ io_write_nonblock(rb_execution_context_t *ec, VALUE io, VALUE str, VALUE ex) long n; if (!RB_TYPE_P(str, T_STRING)) - str = rb_obj_as_string(str); + str = rb_obj_as_string(str); rb_bool_expected(ex, "exception", TRUE); io = GetWriteIO(io); @@ -3449,16 +3449,16 @@ io_write_nonblock(rb_execution_context_t *ec, VALUE io, VALUE str, VALUE ex) RB_GC_GUARD(str); if (n < 0) { - int e = errno; - if (io_again_p(e)) { + int e = errno; + if (io_again_p(e)) { if (!ex) { - return sym_wait_writable; - } - else { - rb_readwrite_syserr_fail(RB_IO_WAIT_WRITABLE, e, "write would block"); - } - } - rb_syserr_fail_path(e, fptr->pathv); + return sym_wait_writable; + } + else { + rb_readwrite_syserr_fail(RB_IO_WAIT_WRITABLE, e, "write would block"); + } + } + rb_syserr_fail_path(e, fptr->pathv); } return LONG2FIX(n); @@ -3549,13 +3549,13 @@ io_read(int argc, VALUE *argv, VALUE io) rb_scan_args(argc, argv, "02", &length, &str); if (NIL_P(length)) { - GetOpenFile(io, fptr); - rb_io_check_char_readable(fptr); - return read_all(fptr, remain_size(fptr), str); + GetOpenFile(io, fptr); + rb_io_check_char_readable(fptr); + return read_all(fptr, remain_size(fptr), str); } len = NUM2LONG(length); if (len < 0) { - rb_raise(rb_eArgError, "negative length %ld given", len); + rb_raise(rb_eArgError, "negative length %ld given", len); } shrinkable = io_setstrbuf(&str,len); @@ -3563,8 +3563,8 @@ io_read(int argc, VALUE *argv, VALUE io) GetOpenFile(io, fptr); rb_io_check_byte_readable(fptr); if (len == 0) { - io_set_read_length(str, 0, shrinkable); - return str; + io_set_read_length(str, 0, shrinkable); + return str; } READ_CHECK(fptr); @@ -3575,7 +3575,7 @@ io_read(int argc, VALUE *argv, VALUE io) io_set_read_length(str, n, shrinkable); #if RUBY_CRLF_ENVIRONMENT if (previous_mode == O_TEXT) { - setmode(fptr->fd, O_TEXT); + setmode(fptr->fd, O_TEXT); } #endif if (n == 0) return Qnil; @@ -3588,7 +3588,7 @@ rscheck(const char *rsptr, long rslen, VALUE rs) { if (!rs) return; if (RSTRING_PTR(rs) != rsptr && RSTRING_LEN(rs) != rslen) - rb_raise(rb_eRuntimeError, "rs modified"); + rb_raise(rb_eRuntimeError, "rs modified"); } static int @@ -3598,7 +3598,7 @@ appendline(rb_io_t *fptr, int delim, VALUE *strp, long *lp) long limit = *lp; if (NEED_READCONV(fptr)) { - SET_BINARY_MODE(fptr); + SET_BINARY_MODE(fptr); make_readconv(fptr, 0); do { const char *p, *e; @@ -3609,7 +3609,7 @@ appendline(rb_io_t *fptr, int delim, VALUE *strp, long *lp) searchlen = (int)limit; e = memchr(p, delim, searchlen); if (e) { - int len = (int)(e-p+1); + int len = (int)(e-p+1); if (NIL_P(str)) *strp = str = rb_str_new(p, len); else @@ -3642,32 +3642,32 @@ appendline(rb_io_t *fptr, int delim, VALUE *strp, long *lp) NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr); do { - long pending = READ_DATA_PENDING_COUNT(fptr); - if (pending > 0) { - const char *p = READ_DATA_PENDING_PTR(fptr); - const char *e; - long last; + long pending = READ_DATA_PENDING_COUNT(fptr); + if (pending > 0) { + const char *p = READ_DATA_PENDING_PTR(fptr); + const char *e; + long last; - if (limit > 0 && pending > limit) pending = limit; - e = memchr(p, delim, pending); - if (e) pending = e - p + 1; - if (!NIL_P(str)) { - last = RSTRING_LEN(str); - rb_str_resize(str, last + pending); - } - else { + if (limit > 0 && pending > limit) pending = limit; + e = memchr(p, delim, pending); + if (e) pending = e - p + 1; + if (!NIL_P(str)) { + last = RSTRING_LEN(str); + rb_str_resize(str, last + pending); + } + else { last = 0; - *strp = str = rb_str_buf_new(pending); - rb_str_set_len(str, pending); - } - read_buffered_data(RSTRING_PTR(str) + last, pending, fptr); /* must not fail */ - limit -= pending; - *lp = limit; - if (e) return delim; - if (limit == 0) - return (unsigned char)RSTRING_PTR(str)[RSTRING_LEN(str)-1]; - } - READ_CHECK(fptr); + *strp = str = rb_str_buf_new(pending); + rb_str_set_len(str, pending); + } + read_buffered_data(RSTRING_PTR(str) + last, pending, fptr); /* must not fail */ + limit -= pending; + *lp = limit; + if (e) return delim; + if (limit == 0) + return (unsigned char)RSTRING_PTR(str)[RSTRING_LEN(str)-1]; + } + READ_CHECK(fptr); } while (io_fillbuf(fptr) >= 0); *lp = limit; return EOF; @@ -3677,47 +3677,47 @@ static inline int swallow(rb_io_t *fptr, int term) { if (NEED_READCONV(fptr)) { - rb_encoding *enc = io_read_encoding(fptr); - int needconv = rb_enc_mbminlen(enc) != 1; - SET_BINARY_MODE(fptr); - make_readconv(fptr, 0); - do { - size_t cnt; - while ((cnt = READ_CHAR_PENDING_COUNT(fptr)) > 0) { - const char *p = READ_CHAR_PENDING_PTR(fptr); - int i; - if (!needconv) { - if (*p != term) return TRUE; - i = (int)cnt; - while (--i && *++p == term); - } - else { - const char *e = p + cnt; - if (rb_enc_ascget(p, e, &i, enc) != term) return TRUE; - while ((p += i) < e && rb_enc_ascget(p, e, &i, enc) == term); - i = (int)(e - p); - } - io_shift_cbuf(fptr, (int)cnt - i, NULL); - } - } while (more_char(fptr) != MORE_CHAR_FINISHED); - return FALSE; + rb_encoding *enc = io_read_encoding(fptr); + int needconv = rb_enc_mbminlen(enc) != 1; + SET_BINARY_MODE(fptr); + make_readconv(fptr, 0); + do { + size_t cnt; + while ((cnt = READ_CHAR_PENDING_COUNT(fptr)) > 0) { + const char *p = READ_CHAR_PENDING_PTR(fptr); + int i; + if (!needconv) { + if (*p != term) return TRUE; + i = (int)cnt; + while (--i && *++p == term); + } + else { + const char *e = p + cnt; + if (rb_enc_ascget(p, e, &i, enc) != term) return TRUE; + while ((p += i) < e && rb_enc_ascget(p, e, &i, enc) == term); + i = (int)(e - p); + } + io_shift_cbuf(fptr, (int)cnt - i, NULL); + } + } while (more_char(fptr) != MORE_CHAR_FINISHED); + return FALSE; } NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr); do { - size_t cnt; - while ((cnt = READ_DATA_PENDING_COUNT(fptr)) > 0) { - char buf[1024]; - const char *p = READ_DATA_PENDING_PTR(fptr); - int i; - if (cnt > sizeof buf) cnt = sizeof buf; - if (*p != term) return TRUE; - i = (int)cnt; - while (--i && *++p == term); - if (!read_buffered_data(buf, cnt - i, fptr)) /* must not fail */ - rb_sys_fail_path(fptr->pathv); - } - READ_CHECK(fptr); + size_t cnt; + while ((cnt = READ_DATA_PENDING_COUNT(fptr)) > 0) { + char buf[1024]; + const char *p = READ_DATA_PENDING_PTR(fptr); + int i; + if (cnt > sizeof buf) cnt = sizeof buf; + if (*p != term) return TRUE; + i = (int)cnt; + while (--i && *++p == term); + if (!read_buffered_data(buf, cnt - i, fptr)) /* must not fail */ + rb_sys_fail_path(fptr->pathv); + } + READ_CHECK(fptr); } while (io_fillbuf(fptr) == 0); return FALSE; } @@ -3731,43 +3731,43 @@ rb_io_getline_fast(rb_io_t *fptr, rb_encoding *enc, int chomp) int cr = 0; do { - int pending = READ_DATA_PENDING_COUNT(fptr); + int pending = READ_DATA_PENDING_COUNT(fptr); - if (pending > 0) { - const char *p = READ_DATA_PENDING_PTR(fptr); - const char *e; - int chomplen = 0; + if (pending > 0) { + const char *p = READ_DATA_PENDING_PTR(fptr); + const char *e; + int chomplen = 0; - e = memchr(p, '\n', pending); - if (e) { + e = memchr(p, '\n', pending); + if (e) { pending = (int)(e - p + 1); - if (chomp) { - chomplen = (pending > 1 && *(e-1) == '\r') + 1; - } - } - if (NIL_P(str)) { - str = rb_str_new(p, pending - chomplen); - fptr->rbuf.off += pending; - fptr->rbuf.len -= pending; - } - else { - rb_str_resize(str, len + pending - chomplen); - read_buffered_data(RSTRING_PTR(str)+len, pending - chomplen, fptr); - fptr->rbuf.off += chomplen; - fptr->rbuf.len -= chomplen; + if (chomp) { + chomplen = (pending > 1 && *(e-1) == '\r') + 1; + } + } + if (NIL_P(str)) { + str = rb_str_new(p, pending - chomplen); + fptr->rbuf.off += pending; + fptr->rbuf.len -= pending; + } + else { + rb_str_resize(str, len + pending - chomplen); + read_buffered_data(RSTRING_PTR(str)+len, pending - chomplen, fptr); + fptr->rbuf.off += chomplen; + fptr->rbuf.len -= chomplen; if (pending == 1 && chomplen == 1 && len > 0) { if (RSTRING_PTR(str)[len-1] == '\r') { rb_str_resize(str, --len); break; } } - } - len += pending - chomplen; - if (cr != ENC_CODERANGE_BROKEN) - pos += rb_str_coderange_scan_restartable(RSTRING_PTR(str) + pos, RSTRING_PTR(str) + len, enc, &cr); - if (e) break; - } - READ_CHECK(fptr); + } + len += pending - chomplen; + if (cr != ENC_CODERANGE_BROKEN) + pos += rb_str_coderange_scan_restartable(RSTRING_PTR(str) + pos, RSTRING_PTR(str) + len, enc, &cr); + if (e) break; + } + READ_CHECK(fptr); } while (io_fillbuf(fptr) >= 0); if (NIL_P(str)) return Qnil; @@ -3790,13 +3790,13 @@ extract_getline_opts(VALUE opts, struct getline_arg *args) { int chomp = FALSE; if (!NIL_P(opts)) { - static ID kwds[1]; - VALUE vchomp; - if (!kwds[0]) { - kwds[0] = rb_intern_const("chomp"); - } - rb_get_kwargs(opts, kwds, 0, -2, &vchomp); - chomp = (vchomp != Qundef) && RTEST(vchomp); + static ID kwds[1]; + VALUE vchomp; + if (!kwds[0]) { + kwds[0] = rb_intern_const("chomp"); + } + rb_get_kwargs(opts, kwds, 0, -2, &vchomp); + chomp = (vchomp != Qundef) && RTEST(vchomp); } args->chomp = chomp; } @@ -3817,7 +3817,7 @@ extract_getline_args(int argc, VALUE *argv, struct getline_arg *args) } } else if (2 <= argc) { - rs = argv[0], lim = argv[1]; + rs = argv[0], lim = argv[1]; if (!NIL_P(rs)) StringValue(rs); } @@ -3832,25 +3832,25 @@ check_getline_args(VALUE *rsp, long *limit, VALUE io) VALUE rs = *rsp; if (!NIL_P(rs)) { - rb_encoding *enc_rs, *enc_io; + rb_encoding *enc_rs, *enc_io; - GetOpenFile(io, fptr); - enc_rs = rb_enc_get(rs); - enc_io = io_read_encoding(fptr); - if (enc_io != enc_rs && - (!is_ascii_string(rs) || - (RSTRING_LEN(rs) > 0 && !rb_enc_asciicompat(enc_io)))) { + GetOpenFile(io, fptr); + enc_rs = rb_enc_get(rs); + enc_io = io_read_encoding(fptr); + if (enc_io != enc_rs && + (!is_ascii_string(rs) || + (RSTRING_LEN(rs) > 0 && !rb_enc_asciicompat(enc_io)))) { if (rs == rb_default_rs) { rs = rb_enc_str_new(0, 0, enc_io); rb_str_buf_cat_ascii(rs, "\n"); - *rsp = rs; + *rsp = rs; } else { rb_raise(rb_eArgError, "encoding mismatch: %s IO with %s RS", rb_enc_name(enc_io), rb_enc_name(enc_rs)); } - } + } } } @@ -3873,76 +3873,76 @@ rb_io_getline_0(VALUE rs, long limit, int chomp, rb_io_t *fptr) rb_io_check_char_readable(fptr); if (NIL_P(rs) && limit < 0) { - str = read_all(fptr, 0, Qnil); - if (RSTRING_LEN(str) == 0) return Qnil; - if (chomp) rb_str_chomp_string(str, rb_default_rs); + str = read_all(fptr, 0, Qnil); + if (RSTRING_LEN(str) == 0) return Qnil; + if (chomp) rb_str_chomp_string(str, rb_default_rs); } else if (limit == 0) { - return rb_enc_str_new(0, 0, io_read_encoding(fptr)); + return rb_enc_str_new(0, 0, io_read_encoding(fptr)); } else if (rs == rb_default_rs && limit < 0 && !NEED_READCONV(fptr) && rb_enc_asciicompat(enc = io_read_encoding(fptr))) { - NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr); - return rb_io_getline_fast(fptr, enc, chomp); + NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr); + return rb_io_getline_fast(fptr, enc, chomp); } else { - int c, newline = -1; - const char *rsptr = 0; - long rslen = 0; - int rspara = 0; + int c, newline = -1; + const char *rsptr = 0; + long rslen = 0; + int rspara = 0; int extra_limit = 16; - int chomp_cr = chomp; + int chomp_cr = chomp; - SET_BINARY_MODE(fptr); + SET_BINARY_MODE(fptr); enc = io_read_encoding(fptr); - if (!NIL_P(rs)) { - rslen = RSTRING_LEN(rs); - if (rslen == 0) { - rsptr = "\n\n"; - rslen = 2; - rspara = 1; - swallow(fptr, '\n'); - rs = 0; - if (!rb_enc_asciicompat(enc)) { - rs = rb_usascii_str_new(rsptr, rslen); - rs = rb_str_encode(rs, rb_enc_from_encoding(enc), 0, Qnil); - OBJ_FREEZE(rs); - rsptr = RSTRING_PTR(rs); - rslen = RSTRING_LEN(rs); - } - } - else { - rsptr = RSTRING_PTR(rs); - } - newline = (unsigned char)rsptr[rslen - 1]; - chomp_cr = chomp && rslen == 1 && newline == '\n'; - } + if (!NIL_P(rs)) { + rslen = RSTRING_LEN(rs); + if (rslen == 0) { + rsptr = "\n\n"; + rslen = 2; + rspara = 1; + swallow(fptr, '\n'); + rs = 0; + if (!rb_enc_asciicompat(enc)) { + rs = rb_usascii_str_new(rsptr, rslen); + rs = rb_str_encode(rs, rb_enc_from_encoding(enc), 0, Qnil); + OBJ_FREEZE(rs); + rsptr = RSTRING_PTR(rs); + rslen = RSTRING_LEN(rs); + } + } + else { + rsptr = RSTRING_PTR(rs); + } + newline = (unsigned char)rsptr[rslen - 1]; + chomp_cr = chomp && rslen == 1 && newline == '\n'; + } - /* MS - Optimization */ - while ((c = appendline(fptr, newline, &str, &limit)) != EOF) { + /* MS - Optimization */ + while ((c = appendline(fptr, newline, &str, &limit)) != EOF) { const char *s, *p, *pp, *e; - if (c == newline) { - if (RSTRING_LEN(str) < rslen) continue; - s = RSTRING_PTR(str); + if (c == newline) { + if (RSTRING_LEN(str) < rslen) continue; + s = RSTRING_PTR(str); e = RSTRING_END(str); - p = e - rslen; - pp = rb_enc_left_char_head(s, p, e, enc); - if (pp != p) continue; - if (!rspara) rscheck(rsptr, rslen, rs); - if (memcmp(p, rsptr, rslen) == 0) { - if (chomp) { - if (chomp_cr && p > s && *(p-1) == '\r') --p; - rb_str_set_len(str, p - s); - } - break; - } - } - if (limit == 0) { - s = RSTRING_PTR(str); - p = RSTRING_END(str); - pp = rb_enc_left_char_head(s, p-1, p, enc); + p = e - rslen; + pp = rb_enc_left_char_head(s, p, e, enc); + if (pp != p) continue; + if (!rspara) rscheck(rsptr, rslen, rs); + if (memcmp(p, rsptr, rslen) == 0) { + if (chomp) { + if (chomp_cr && p > s && *(p-1) == '\r') --p; + rb_str_set_len(str, p - s); + } + break; + } + } + if (limit == 0) { + s = RSTRING_PTR(str); + p = RSTRING_END(str); + pp = rb_enc_left_char_head(s, p-1, p, enc); if (extra_limit && MBCLEN_NEEDMORE_P(rb_enc_precise_mbclen(pp, p, enc))) { /* relax the limit while incomplete character. @@ -3954,17 +3954,17 @@ rb_io_getline_0(VALUE rs, long limit, int chomp, rb_io_t *fptr) nolimit = 1; break; } - } - } + } + } - if (rspara && c != EOF) - swallow(fptr, '\n'); - if (!NIL_P(str)) + if (rspara && c != EOF) + swallow(fptr, '\n'); + if (!NIL_P(str)) str = io_enc_str(str, fptr); } if (!NIL_P(str) && !nolimit) { - fptr->lineno++; + fptr->lineno++; } return str; @@ -3981,13 +3981,13 @@ rb_io_getline_1(VALUE rs, long limit, int chomp, VALUE io) old_lineno = fptr->lineno; str = rb_io_getline_0(rs, limit, chomp, fptr); if (!NIL_P(str) && (new_lineno = fptr->lineno) != old_lineno) { - if (io == ARGF.current_file) { - ARGF.lineno += new_lineno - old_lineno; - ARGF.last_lineno = ARGF.lineno; - } - else { - ARGF.last_lineno = new_lineno; - } + if (io == ARGF.current_file) { + ARGF.lineno += new_lineno - old_lineno; + ARGF.last_lineno = ARGF.lineno; + } + else { + ARGF.last_lineno = new_lineno; + } } return str; @@ -4157,7 +4157,7 @@ rb_io_readline(int argc, VALUE *argv, VALUE io) VALUE line = rb_io_gets_m(argc, argv, io); if (NIL_P(line)) { - rb_eof_error(); + rb_eof_error(); } return line; } @@ -4245,10 +4245,10 @@ io_readlines(const struct getline_arg *arg, VALUE io) VALUE line, ary; if (arg->limit == 0) - rb_raise(rb_eArgError, "invalid limit: 0 for readlines"); + rb_raise(rb_eArgError, "invalid limit: 0 for readlines"); ary = rb_ary_new(); while (!NIL_P(line = rb_io_getline_1(arg->rs, arg->limit, arg->chomp, io))) { - rb_ary_push(ary, line); + rb_ary_push(ary, line); } return ary; } @@ -4373,9 +4373,9 @@ rb_io_each_line(int argc, VALUE *argv, VALUE io) RETURN_ENUMERATOR(io, argc, argv); prepare_getline_args(argc, argv, &args, io); if (args.limit == 0) - rb_raise(rb_eArgError, "invalid limit: 0 for each_line"); + rb_raise(rb_eArgError, "invalid limit: 0 for each_line"); while (!NIL_P(str = rb_io_getline_1(args.rs, args.limit, args.chomp, io))) { - rb_yield(str); + rb_yield(str); } return io; } @@ -4408,14 +4408,14 @@ rb_io_each_byte(VALUE io) GetOpenFile(io, fptr); do { - while (fptr->rbuf.len > 0) { - char *p = fptr->rbuf.ptr + fptr->rbuf.off++; - fptr->rbuf.len--; - rb_yield(INT2FIX(*p & 0xff)); - rb_io_check_byte_readable(fptr); - errno = 0; - } - READ_CHECK(fptr); + while (fptr->rbuf.len > 0) { + char *p = fptr->rbuf.ptr + fptr->rbuf.off++; + fptr->rbuf.len--; + rb_yield(INT2FIX(*p & 0xff)); + rb_io_check_byte_readable(fptr); + errno = 0; + } + READ_CHECK(fptr); } while (io_fillbuf(fptr) >= 0); return io; } @@ -4427,17 +4427,17 @@ io_getc(rb_io_t *fptr, rb_encoding *enc) VALUE str; if (NEED_READCONV(fptr)) { - rb_encoding *read_enc = io_read_encoding(fptr); + rb_encoding *read_enc = io_read_encoding(fptr); - str = Qnil; - SET_BINARY_MODE(fptr); + str = Qnil; + SET_BINARY_MODE(fptr); make_readconv(fptr, 0); while (1) { if (fptr->cbuf.len) { - r = rb_enc_precise_mbclen(fptr->cbuf.ptr+fptr->cbuf.off, - fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len, - read_enc); + r = rb_enc_precise_mbclen(fptr->cbuf.ptr+fptr->cbuf.off, + fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len, + read_enc); if (!MBCLEN_NEEDMORE_P(r)) break; if (fptr->cbuf.len == fptr->cbuf.capa) { @@ -4447,16 +4447,16 @@ io_getc(rb_io_t *fptr, rb_encoding *enc) if (more_char(fptr) == MORE_CHAR_FINISHED) { if (fptr->cbuf.len == 0) { - clear_readconv(fptr); - return Qnil; - } + clear_readconv(fptr); + return Qnil; + } /* return an unit of an incomplete character just before EOF */ - str = rb_enc_str_new(fptr->cbuf.ptr+fptr->cbuf.off, 1, read_enc); - fptr->cbuf.off += 1; - fptr->cbuf.len -= 1; + str = rb_enc_str_new(fptr->cbuf.ptr+fptr->cbuf.off, 1, read_enc); + fptr->cbuf.off += 1; + fptr->cbuf.len -= 1; if (fptr->cbuf.len == 0) clear_readconv(fptr); - ENC_CODERANGE_SET(str, ENC_CODERANGE_BROKEN); - return str; + ENC_CODERANGE_SET(str, ENC_CODERANGE_BROKEN); + return str; } } if (MBCLEN_INVALID_P(r)) { @@ -4464,62 +4464,62 @@ io_getc(rb_io_t *fptr, rb_encoding *enc) fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len, read_enc); io_shift_cbuf(fptr, r, &str); - cr = ENC_CODERANGE_BROKEN; - } - else { - io_shift_cbuf(fptr, MBCLEN_CHARFOUND_LEN(r), &str); - cr = ENC_CODERANGE_VALID; - if (MBCLEN_CHARFOUND_LEN(r) == 1 && rb_enc_asciicompat(read_enc) && - ISASCII(RSTRING_PTR(str)[0])) { - cr = ENC_CODERANGE_7BIT; - } - } - str = io_enc_str(str, fptr); - ENC_CODERANGE_SET(str, cr); - return str; + cr = ENC_CODERANGE_BROKEN; + } + else { + io_shift_cbuf(fptr, MBCLEN_CHARFOUND_LEN(r), &str); + cr = ENC_CODERANGE_VALID; + if (MBCLEN_CHARFOUND_LEN(r) == 1 && rb_enc_asciicompat(read_enc) && + ISASCII(RSTRING_PTR(str)[0])) { + cr = ENC_CODERANGE_7BIT; + } + } + str = io_enc_str(str, fptr); + ENC_CODERANGE_SET(str, cr); + return str; } NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr); if (io_fillbuf(fptr) < 0) { - return Qnil; + return Qnil; } if (rb_enc_asciicompat(enc) && ISASCII(fptr->rbuf.ptr[fptr->rbuf.off])) { - str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, 1); - fptr->rbuf.off += 1; - fptr->rbuf.len -= 1; - cr = ENC_CODERANGE_7BIT; + str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, 1); + fptr->rbuf.off += 1; + fptr->rbuf.len -= 1; + cr = ENC_CODERANGE_7BIT; } else { - r = rb_enc_precise_mbclen(fptr->rbuf.ptr+fptr->rbuf.off, fptr->rbuf.ptr+fptr->rbuf.off+fptr->rbuf.len, enc); - if (MBCLEN_CHARFOUND_P(r) && - (n = MBCLEN_CHARFOUND_LEN(r)) <= fptr->rbuf.len) { - str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, n); - fptr->rbuf.off += n; - fptr->rbuf.len -= n; - cr = ENC_CODERANGE_VALID; - } - else if (MBCLEN_NEEDMORE_P(r)) { - str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, fptr->rbuf.len); - fptr->rbuf.len = 0; - getc_needmore: - if (io_fillbuf(fptr) != -1) { - rb_str_cat(str, fptr->rbuf.ptr+fptr->rbuf.off, 1); - fptr->rbuf.off++; - fptr->rbuf.len--; - r = rb_enc_precise_mbclen(RSTRING_PTR(str), RSTRING_PTR(str)+RSTRING_LEN(str), enc); - if (MBCLEN_NEEDMORE_P(r)) { - goto getc_needmore; - } - else if (MBCLEN_CHARFOUND_P(r)) { - cr = ENC_CODERANGE_VALID; - } - } - } - else { - str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, 1); - fptr->rbuf.off++; - fptr->rbuf.len--; - } + r = rb_enc_precise_mbclen(fptr->rbuf.ptr+fptr->rbuf.off, fptr->rbuf.ptr+fptr->rbuf.off+fptr->rbuf.len, enc); + if (MBCLEN_CHARFOUND_P(r) && + (n = MBCLEN_CHARFOUND_LEN(r)) <= fptr->rbuf.len) { + str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, n); + fptr->rbuf.off += n; + fptr->rbuf.len -= n; + cr = ENC_CODERANGE_VALID; + } + else if (MBCLEN_NEEDMORE_P(r)) { + str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, fptr->rbuf.len); + fptr->rbuf.len = 0; + getc_needmore: + if (io_fillbuf(fptr) != -1) { + rb_str_cat(str, fptr->rbuf.ptr+fptr->rbuf.off, 1); + fptr->rbuf.off++; + fptr->rbuf.len--; + r = rb_enc_precise_mbclen(RSTRING_PTR(str), RSTRING_PTR(str)+RSTRING_LEN(str), enc); + if (MBCLEN_NEEDMORE_P(r)) { + goto getc_needmore; + } + else if (MBCLEN_CHARFOUND_P(r)) { + cr = ENC_CODERANGE_VALID; + } + } + } + else { + str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, 1); + fptr->rbuf.off++; + fptr->rbuf.len--; + } } if (!cr) cr = ENC_CODERANGE_BROKEN; str = io_enc_str(str, fptr); @@ -4598,87 +4598,87 @@ rb_io_each_codepoint(VALUE io) READ_CHECK(fptr); if (NEED_READCONV(fptr)) { - SET_BINARY_MODE(fptr); - r = 1; /* no invalid char yet */ - for (;;) { - make_readconv(fptr, 0); - for (;;) { - if (fptr->cbuf.len) { - if (fptr->encs.enc) - r = rb_enc_precise_mbclen(fptr->cbuf.ptr+fptr->cbuf.off, - fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len, - fptr->encs.enc); - else - r = ONIGENC_CONSTRUCT_MBCLEN_CHARFOUND(1); - if (!MBCLEN_NEEDMORE_P(r)) - break; - if (fptr->cbuf.len == fptr->cbuf.capa) { - rb_raise(rb_eIOError, "too long character"); - } - } - if (more_char(fptr) == MORE_CHAR_FINISHED) { + SET_BINARY_MODE(fptr); + r = 1; /* no invalid char yet */ + for (;;) { + make_readconv(fptr, 0); + for (;;) { + if (fptr->cbuf.len) { + if (fptr->encs.enc) + r = rb_enc_precise_mbclen(fptr->cbuf.ptr+fptr->cbuf.off, + fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len, + fptr->encs.enc); + else + r = ONIGENC_CONSTRUCT_MBCLEN_CHARFOUND(1); + if (!MBCLEN_NEEDMORE_P(r)) + break; + if (fptr->cbuf.len == fptr->cbuf.capa) { + rb_raise(rb_eIOError, "too long character"); + } + } + if (more_char(fptr) == MORE_CHAR_FINISHED) { clear_readconv(fptr); - if (!MBCLEN_CHARFOUND_P(r)) { - enc = fptr->encs.enc; - goto invalid; - } - return io; - } - } - if (MBCLEN_INVALID_P(r)) { - enc = fptr->encs.enc; - goto invalid; - } - n = MBCLEN_CHARFOUND_LEN(r); - if (fptr->encs.enc) { - c = rb_enc_codepoint(fptr->cbuf.ptr+fptr->cbuf.off, - fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len, - fptr->encs.enc); - } - else { - c = (unsigned char)fptr->cbuf.ptr[fptr->cbuf.off]; - } - fptr->cbuf.off += n; - fptr->cbuf.len -= n; - rb_yield(UINT2NUM(c)); + if (!MBCLEN_CHARFOUND_P(r)) { + enc = fptr->encs.enc; + goto invalid; + } + return io; + } + } + if (MBCLEN_INVALID_P(r)) { + enc = fptr->encs.enc; + goto invalid; + } + n = MBCLEN_CHARFOUND_LEN(r); + if (fptr->encs.enc) { + c = rb_enc_codepoint(fptr->cbuf.ptr+fptr->cbuf.off, + fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len, + fptr->encs.enc); + } + else { + c = (unsigned char)fptr->cbuf.ptr[fptr->cbuf.off]; + } + fptr->cbuf.off += n; + fptr->cbuf.len -= n; + rb_yield(UINT2NUM(c)); rb_io_check_byte_readable(fptr); - } + } } NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr); enc = io_input_encoding(fptr); while (io_fillbuf(fptr) >= 0) { - r = rb_enc_precise_mbclen(fptr->rbuf.ptr+fptr->rbuf.off, - fptr->rbuf.ptr+fptr->rbuf.off+fptr->rbuf.len, enc); - if (MBCLEN_CHARFOUND_P(r) && - (n = MBCLEN_CHARFOUND_LEN(r)) <= fptr->rbuf.len) { - c = rb_enc_codepoint(fptr->rbuf.ptr+fptr->rbuf.off, - fptr->rbuf.ptr+fptr->rbuf.off+fptr->rbuf.len, enc); - fptr->rbuf.off += n; - fptr->rbuf.len -= n; - rb_yield(UINT2NUM(c)); - } - else if (MBCLEN_INVALID_P(r)) { + r = rb_enc_precise_mbclen(fptr->rbuf.ptr+fptr->rbuf.off, + fptr->rbuf.ptr+fptr->rbuf.off+fptr->rbuf.len, enc); + if (MBCLEN_CHARFOUND_P(r) && + (n = MBCLEN_CHARFOUND_LEN(r)) <= fptr->rbuf.len) { + c = rb_enc_codepoint(fptr->rbuf.ptr+fptr->rbuf.off, + fptr->rbuf.ptr+fptr->rbuf.off+fptr->rbuf.len, enc); + fptr->rbuf.off += n; + fptr->rbuf.len -= n; + rb_yield(UINT2NUM(c)); + } + else if (MBCLEN_INVALID_P(r)) { goto invalid; - } - else if (MBCLEN_NEEDMORE_P(r)) { - char cbuf[8], *p = cbuf; - int more = MBCLEN_NEEDMORE_LEN(r); - if (more > numberof(cbuf)) goto invalid; - more += n = fptr->rbuf.len; - if (more > numberof(cbuf)) goto invalid; - while ((n = (int)read_buffered_data(p, more, fptr)) > 0 && - (p += n, (more -= n) > 0)) { - if (io_fillbuf(fptr) < 0) goto invalid; - if ((n = fptr->rbuf.len) > more) n = more; - } - r = rb_enc_precise_mbclen(cbuf, p, enc); - if (!MBCLEN_CHARFOUND_P(r)) goto invalid; - c = rb_enc_codepoint(cbuf, p, enc); - rb_yield(UINT2NUM(c)); - } - else { - continue; - } + } + else if (MBCLEN_NEEDMORE_P(r)) { + char cbuf[8], *p = cbuf; + int more = MBCLEN_NEEDMORE_LEN(r); + if (more > numberof(cbuf)) goto invalid; + more += n = fptr->rbuf.len; + if (more > numberof(cbuf)) goto invalid; + while ((n = (int)read_buffered_data(p, more, fptr)) > 0 && + (p += n, (more -= n) > 0)) { + if (io_fillbuf(fptr) < 0) goto invalid; + if ((n = fptr->rbuf.len) > more) n = more; + } + r = rb_enc_precise_mbclen(cbuf, p, enc); + if (!MBCLEN_CHARFOUND_P(r)) goto invalid; + c = rb_enc_codepoint(cbuf, p, enc); + rb_yield(UINT2NUM(c)); + } + else { + continue; + } rb_io_check_byte_readable(fptr); } return io; @@ -4744,7 +4744,7 @@ rb_io_readchar(VALUE io) VALUE c = rb_io_getc(io); if (NIL_P(c)) { - rb_eof_error(); + rb_eof_error(); } return c; } @@ -4785,7 +4785,7 @@ rb_io_getbyte(VALUE io) } } if (io_fillbuf(fptr) < 0) { - return Qnil; + return Qnil; } fptr->rbuf.off++; fptr->rbuf.len--; @@ -4817,7 +4817,7 @@ rb_io_readbyte(VALUE io) VALUE c = rb_io_getbyte(io); if (NIL_P(c)) { - rb_eof_error(); + rb_eof_error(); } return c; } @@ -4931,20 +4931,20 @@ rb_io_ungetc(VALUE io, VALUE c) GetOpenFile(io, fptr); rb_io_check_char_readable(fptr); if (FIXNUM_P(c)) { - c = rb_enc_uint_chr(FIX2UINT(c), io_read_encoding(fptr)); + c = rb_enc_uint_chr(FIX2UINT(c), io_read_encoding(fptr)); } else if (RB_BIGNUM_TYPE_P(c)) { - c = rb_enc_uint_chr(NUM2UINT(c), io_read_encoding(fptr)); + c = rb_enc_uint_chr(NUM2UINT(c), io_read_encoding(fptr)); } else { - SafeStringValue(c); + SafeStringValue(c); } if (NEED_READCONV(fptr)) { - SET_BINARY_MODE(fptr); + SET_BINARY_MODE(fptr); len = RSTRING_LEN(c); #if SIZEOF_LONG > SIZEOF_INT - if (len > INT_MAX) - rb_raise(rb_eIOError, "ungetc failed"); + if (len > INT_MAX) + rb_raise(rb_eIOError, "ungetc failed"); #endif make_readconv(fptr, (int)len); if (fptr->cbuf.capa - fptr->cbuf.len < len) @@ -4960,7 +4960,7 @@ rb_io_ungetc(VALUE io, VALUE c) MEMMOVE(fptr->cbuf.ptr+fptr->cbuf.off, RSTRING_PTR(c), char, len); } else { - NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr); + NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr); io_ungetbyte(c, fptr); } return Qnil; @@ -5310,10 +5310,10 @@ static void rb_io_fptr_cleanup(rb_io_t *fptr, int noraise) { if (fptr->finalize) { - (*fptr->finalize)(fptr, noraise); + (*fptr->finalize)(fptr, noraise); } else { - fptr_finalize(fptr, noraise); + fptr_finalize(fptr, noraise); } } @@ -5487,9 +5487,9 @@ ignore_closed_stream(VALUE io, VALUE exc) enum {mesg_len = sizeof(closed_stream)-1}; VALUE mesg = rb_attr_get(exc, idMesg); if (!RB_TYPE_P(mesg, T_STRING) || - RSTRING_LEN(mesg) != mesg_len || - memcmp(RSTRING_PTR(mesg), closed_stream, mesg_len)) { - rb_exc_raise(exc); + RSTRING_LEN(mesg) != mesg_len || + memcmp(RSTRING_PTR(mesg), closed_stream, mesg_len)) { + rb_exc_raise(exc); } return io; } @@ -5500,7 +5500,7 @@ io_close(VALUE io) VALUE closed = rb_check_funcall(io, rb_intern("closed?"), 0, 0); if (closed != Qundef && RTEST(closed)) return io; rb_rescue2(io_call_close, io, ignore_closed_stream, io, - rb_eIOError, (VALUE)0); + rb_eIOError, (VALUE)0); return io; } @@ -5579,21 +5579,21 @@ rb_io_close_read(VALUE io) write_io = GetWriteIO(io); if (io != write_io) { - rb_io_t *wfptr; - wfptr = rb_io_get_fptr(rb_io_taint_check(write_io)); - wfptr->pid = fptr->pid; - fptr->pid = 0; + rb_io_t *wfptr; + wfptr = rb_io_get_fptr(rb_io_taint_check(write_io)); + wfptr->pid = fptr->pid; + fptr->pid = 0; RFILE(io)->fptr = wfptr; - /* bind to write_io temporarily to get rid of memory/fd leak */ - fptr->tied_io_for_writing = 0; - RFILE(write_io)->fptr = fptr; - rb_io_fptr_cleanup(fptr, FALSE); - /* should not finalize fptr because another thread may be reading it */ + /* bind to write_io temporarily to get rid of memory/fd leak */ + fptr->tied_io_for_writing = 0; + RFILE(write_io)->fptr = fptr; + rb_io_fptr_cleanup(fptr, FALSE); + /* should not finalize fptr because another thread may be reading it */ return Qnil; } if ((fptr->mode & (FMODE_DUPLEX|FMODE_WRITABLE)) == FMODE_WRITABLE) { - rb_raise(rb_eIOError, "closing non-duplex IO for reading"); + rb_raise(rb_eIOError, "closing non-duplex IO for reading"); } return rb_io_close(io); } @@ -5628,17 +5628,17 @@ rb_io_close_write(VALUE io) rb_sys_fail_path(fptr->pathv); fptr->mode &= ~FMODE_WRITABLE; if (!(fptr->mode & FMODE_READABLE)) - return rb_io_close(write_io); + return rb_io_close(write_io); return Qnil; } if ((fptr->mode & (FMODE_DUPLEX|FMODE_READABLE)) == FMODE_READABLE) { - rb_raise(rb_eIOError, "closing non-duplex IO for writing"); + rb_raise(rb_eIOError, "closing non-duplex IO for writing"); } if (io != write_io) { - fptr = rb_io_get_fptr(rb_io_taint_check(io)); - fptr->tied_io_for_writing = 0; + fptr = rb_io_get_fptr(rb_io_taint_check(io)); + fptr->tied_io_for_writing = 0; } rb_io_close(write_io); return Qnil; @@ -5664,16 +5664,16 @@ rb_io_sysseek(int argc, VALUE *argv, VALUE io) off_t pos; if (rb_scan_args(argc, argv, "11", &offset, &ptrname) == 2) { - whence = interpret_seek_whence(ptrname); + whence = interpret_seek_whence(ptrname); } pos = NUM2OFFT(offset); GetOpenFile(io, fptr); if ((fptr->mode & FMODE_READABLE) && (READ_DATA_BUFFERED(fptr) || READ_CHAR_PENDING(fptr))) { - rb_raise(rb_eIOError, "sysseek for buffered IO"); + rb_raise(rb_eIOError, "sysseek for buffered IO"); } if ((fptr->mode & FMODE_WRITABLE) && fptr->wbuf.len) { - rb_warn("sysseek for buffered IO"); + rb_warn("sysseek for buffered IO"); } errno = 0; pos = lseek(fptr->fd, pos, whence); @@ -5709,14 +5709,14 @@ rb_io_syswrite(VALUE io, VALUE str) const char *ptr; if (!RB_TYPE_P(str, T_STRING)) - str = rb_obj_as_string(str); + str = rb_obj_as_string(str); io = GetWriteIO(io); GetOpenFile(io, fptr); rb_io_check_writable(fptr); if (fptr->wbuf.len) { - rb_warn("syswrite for buffered IO"); + rb_warn("syswrite for buffered IO"); } tmp = rb_str_tmp_frozen_acquire(str); @@ -5863,11 +5863,11 @@ rb_io_pread(int argc, VALUE *argv, VALUE io) n = (ssize_t)rb_ensure(pread_internal_call, (VALUE)&arg, rb_str_unlocktmp, str); if (n < 0) { - rb_sys_fail_path(fptr->pathv); + rb_sys_fail_path(fptr->pathv); } io_set_read_length(str, n, shrinkable); if (n == 0 && arg.count > 0) { - rb_eof_error(); + rb_eof_error(); } return str; @@ -5919,7 +5919,7 @@ rb_io_pwrite(VALUE io, VALUE str, VALUE offset) VALUE tmp; if (!RB_TYPE_P(str, T_STRING)) - str = rb_obj_as_string(str); + str = rb_obj_as_string(str); arg.offset = NUM2OFFT(offset); @@ -5957,10 +5957,10 @@ rb_io_binmode(VALUE io) fptr->writeconv_pre_ecflags &= ~ECONV_NEWLINE_DECORATOR_MASK; #ifdef O_BINARY if (!fptr->readconv) { - SET_BINARY_MODE_WITH_SEEK_CUR(fptr); + SET_BINARY_MODE_WITH_SEEK_CUR(fptr); } else { - setmode(fptr->fd, O_BINARY); + setmode(fptr->fd, O_BINARY); } #endif return io; @@ -6043,23 +6043,23 @@ static const char* rb_io_fmode_modestr(int fmode) { if (fmode & FMODE_APPEND) { - if ((fmode & FMODE_READWRITE) == FMODE_READWRITE) { - return MODE_BTMODE("a+", "ab+", "at+"); - } - return MODE_BTMODE("a", "ab", "at"); + if ((fmode & FMODE_READWRITE) == FMODE_READWRITE) { + return MODE_BTMODE("a+", "ab+", "at+"); + } + return MODE_BTMODE("a", "ab", "at"); } switch (fmode & FMODE_READWRITE) { default: - rb_raise(rb_eArgError, "invalid access fmode 0x%x", fmode); + rb_raise(rb_eArgError, "invalid access fmode 0x%x", fmode); case FMODE_READABLE: - return MODE_BTMODE("r", "rb", "rt"); + return MODE_BTMODE("r", "rb", "rt"); case FMODE_WRITABLE: - return MODE_BTXMODE("w", "wb", "wt", "wx", "wbx", "wtx"); + return MODE_BTXMODE("w", "wb", "wt", "wx", "wbx", "wtx"); case FMODE_READWRITE: - if (fmode & FMODE_CREATE) { + if (fmode & FMODE_CREATE) { return MODE_BTXMODE("w+", "wb+", "wt+", "w+x", "wb+x", "wt+x"); - } - return MODE_BTMODE("r+", "rb+", "rt+"); + } + return MODE_BTMODE("r+", "rb+", "rt+"); } } @@ -6082,27 +6082,27 @@ rb_io_modestr_fmode(const char *modestr) switch (*m++) { case 'r': - fmode |= FMODE_READABLE; - break; + fmode |= FMODE_READABLE; + break; case 'w': - fmode |= FMODE_WRITABLE | FMODE_TRUNC | FMODE_CREATE; - break; + fmode |= FMODE_WRITABLE | FMODE_TRUNC | FMODE_CREATE; + break; case 'a': - fmode |= FMODE_WRITABLE | FMODE_APPEND | FMODE_CREATE; - break; + fmode |= FMODE_WRITABLE | FMODE_APPEND | FMODE_CREATE; + break; default: goto error; } while (*m) { switch (*m++) { - case 'b': + case 'b': fmode |= FMODE_BINMODE; break; - case 't': + case 't': fmode |= FMODE_TEXTMODE; break; - case '+': + case '+': fmode |= FMODE_READWRITE; break; case 'x': @@ -6110,12 +6110,12 @@ rb_io_modestr_fmode(const char *modestr) goto error; fmode |= FMODE_EXCL; break; - default: + default: goto error; - case ':': - p = strchr(m, ':'); - if (io_encname_bom_p(m, p ? (long)(p - m) : (long)strlen(m))) - fmode |= FMODE_SETENC_BY_BOM; + case ':': + p = strchr(m, ':'); + if (io_encname_bom_p(m, p ? (long)(p - m) : (long)strlen(m))) + fmode |= FMODE_SETENC_BY_BOM; goto finished; } } @@ -6138,31 +6138,31 @@ rb_io_oflags_fmode(int oflags) switch (oflags & O_ACCMODE) { case O_RDONLY: - fmode = FMODE_READABLE; - break; + fmode = FMODE_READABLE; + break; case O_WRONLY: - fmode = FMODE_WRITABLE; - break; + fmode = FMODE_WRITABLE; + break; case O_RDWR: - fmode = FMODE_READWRITE; - break; + fmode = FMODE_READWRITE; + break; } if (oflags & O_APPEND) { - fmode |= FMODE_APPEND; + fmode |= FMODE_APPEND; } if (oflags & O_TRUNC) { - fmode |= FMODE_TRUNC; + fmode |= FMODE_TRUNC; } if (oflags & O_CREAT) { - fmode |= FMODE_CREATE; + fmode |= FMODE_CREATE; } if (oflags & O_EXCL) { fmode |= FMODE_EXCL; } #ifdef O_BINARY if (oflags & O_BINARY) { - fmode |= FMODE_BINMODE; + fmode |= FMODE_BINMODE; } #endif @@ -6227,25 +6227,25 @@ rb_io_oflags_modestr(int oflags) } accmode = oflags & (O_RDONLY|O_WRONLY|O_RDWR); if (oflags & O_APPEND) { - if (accmode == O_WRONLY) { - return MODE_BINARY("a", "ab"); - } - if (accmode == O_RDWR) { - return MODE_BINARY("a+", "ab+"); - } + if (accmode == O_WRONLY) { + return MODE_BINARY("a", "ab"); + } + if (accmode == O_RDWR) { + return MODE_BINARY("a+", "ab+"); + } } switch (accmode) { default: - rb_raise(rb_eArgError, "invalid access oflags 0x%x", oflags); + rb_raise(rb_eArgError, "invalid access oflags 0x%x", oflags); case O_RDONLY: - return MODE_BINARY("r", "rb"); + return MODE_BINARY("r", "rb"); case O_WRONLY: - return MODE_BINARY("w", "wb"); + return MODE_BINARY("w", "wb"); case O_RDWR: - if (oflags & O_TRUNC) { - return MODE_BINARY("w+", "wb+"); - } - return MODE_BINARY("r+", "rb+"); + if (oflags & O_TRUNC) { + return MODE_BINARY("w+", "wb+"); + } + return MODE_BINARY("r+", "rb+"); } } @@ -6260,25 +6260,25 @@ rb_io_ext_int_to_encs(rb_encoding *ext, rb_encoding *intern, rb_encoding **enc, int default_ext = 0; if (ext == NULL) { - ext = rb_default_external_encoding(); - default_ext = 1; + ext = rb_default_external_encoding(); + default_ext = 1; } if (ext == rb_ascii8bit_encoding()) { - /* If external is ASCII-8BIT, no transcoding */ - intern = NULL; + /* If external is ASCII-8BIT, no transcoding */ + intern = NULL; } else if (intern == NULL) { - intern = rb_default_internal_encoding(); + intern = rb_default_internal_encoding(); } if (intern == NULL || intern == (rb_encoding *)Qnil || - (!(fmode & FMODE_SETENC_BY_BOM) && (intern == ext))) { - /* No internal encoding => use external + no transcoding */ - *enc = (default_ext && intern != ext) ? NULL : ext; - *enc2 = NULL; + (!(fmode & FMODE_SETENC_BY_BOM) && (intern == ext))) { + /* No internal encoding => use external + no transcoding */ + *enc = (default_ext && intern != ext) ? NULL : ext; + *enc2 = NULL; } else { - *enc = intern; - *enc2 = ext; + *enc = intern; + *enc2 = ext; } } @@ -6290,7 +6290,7 @@ unsupported_encoding(const char *name, rb_encoding *enc) static void parse_mode_enc(const char *estr, rb_encoding *estr_enc, - rb_encoding **enc_p, rb_encoding **enc2_p, int *fmode_p) + rb_encoding **enc_p, rb_encoding **enc2_p, int *fmode_p) { const char *p; char encname[ENCODING_MAXNAMELEN+1]; @@ -6304,53 +6304,53 @@ parse_mode_enc(const char *estr, rb_encoding *estr_enc, p = strrchr(estr, ':'); len = p ? (p++ - estr) : (long)strlen(estr); if ((fmode & FMODE_SETENC_BY_BOM) || io_encname_bom_p(estr, len)) { - estr += bom_prefix_len; - len -= bom_prefix_len; - if (!STRNCASECMP(estr, utf_prefix, utf_prefix_len)) { - fmode |= FMODE_SETENC_BY_BOM; - } - else { - rb_enc_warn(estr_enc, "BOM with non-UTF encoding %s is nonsense", estr); - fmode &= ~FMODE_SETENC_BY_BOM; - } + estr += bom_prefix_len; + len -= bom_prefix_len; + if (!STRNCASECMP(estr, utf_prefix, utf_prefix_len)) { + fmode |= FMODE_SETENC_BY_BOM; + } + else { + rb_enc_warn(estr_enc, "BOM with non-UTF encoding %s is nonsense", estr); + fmode &= ~FMODE_SETENC_BY_BOM; + } } if (len == 0 || len > ENCODING_MAXNAMELEN) { - idx = -1; + idx = -1; } else { - if (p) { - memcpy(encname, estr, len); - encname[len] = '\0'; - estr = encname; - } - idx = rb_enc_find_index(estr); + if (p) { + memcpy(encname, estr, len); + encname[len] = '\0'; + estr = encname; + } + idx = rb_enc_find_index(estr); } if (fmode_p) *fmode_p = fmode; if (idx >= 0) - ext_enc = rb_enc_from_index(idx); + ext_enc = rb_enc_from_index(idx); else { - if (idx != -2) - unsupported_encoding(estr, estr_enc); - ext_enc = NULL; + if (idx != -2) + unsupported_encoding(estr, estr_enc); + ext_enc = NULL; } int_enc = NULL; if (p) { - if (*p == '-' && *(p+1) == '\0') { - /* Special case - "-" => no transcoding */ - int_enc = (rb_encoding *)Qnil; - } - else { - idx2 = rb_enc_find_index(p); - if (idx2 < 0) - unsupported_encoding(p, estr_enc); - else if (!(fmode & FMODE_SETENC_BY_BOM) && (idx2 == idx)) { - int_enc = (rb_encoding *)Qnil; - } - else - int_enc = rb_enc_from_index(idx2); - } + if (*p == '-' && *(p+1) == '\0') { + /* Special case - "-" => no transcoding */ + int_enc = (rb_encoding *)Qnil; + } + else { + idx2 = rb_enc_find_index(p); + if (idx2 < 0) + unsupported_encoding(p, estr_enc); + else if (!(fmode & FMODE_SETENC_BY_BOM) && (idx2 == idx)) { + int_enc = (rb_encoding *)Qnil; + } + else + int_enc = rb_enc_from_index(idx2); + } } rb_io_ext_int_to_encs(ext_enc, int_enc, enc_p, enc2_p, fmode); @@ -6365,62 +6365,62 @@ rb_io_extract_encoding_option(VALUE opt, rb_encoding **enc_p, rb_encoding **enc2 rb_encoding *intencoding = NULL; if (!NIL_P(opt)) { - VALUE v; - v = rb_hash_lookup2(opt, sym_encoding, Qnil); - if (v != Qnil) encoding = v; - v = rb_hash_lookup2(opt, sym_extenc, Qundef); - if (v != Qnil) extenc = v; - v = rb_hash_lookup2(opt, sym_intenc, Qundef); - if (v != Qundef) intenc = v; + VALUE v; + v = rb_hash_lookup2(opt, sym_encoding, Qnil); + if (v != Qnil) encoding = v; + v = rb_hash_lookup2(opt, sym_extenc, Qundef); + if (v != Qnil) extenc = v; + v = rb_hash_lookup2(opt, sym_intenc, Qundef); + if (v != Qundef) intenc = v; } if ((extenc != Qundef || intenc != Qundef) && !NIL_P(encoding)) { - if (!NIL_P(ruby_verbose)) { - int idx = rb_to_encoding_index(encoding); - if (idx >= 0) encoding = rb_enc_from_encoding(rb_enc_from_index(idx)); - rb_warn("Ignoring encoding parameter '%"PRIsVALUE"': %s_encoding is used", - encoding, extenc == Qundef ? "internal" : "external"); - } - encoding = Qnil; + if (!NIL_P(ruby_verbose)) { + int idx = rb_to_encoding_index(encoding); + if (idx >= 0) encoding = rb_enc_from_encoding(rb_enc_from_index(idx)); + rb_warn("Ignoring encoding parameter '%"PRIsVALUE"': %s_encoding is used", + encoding, extenc == Qundef ? "internal" : "external"); + } + encoding = Qnil; } if (extenc != Qundef && !NIL_P(extenc)) { - extencoding = rb_to_encoding(extenc); + extencoding = rb_to_encoding(extenc); } if (intenc != Qundef) { - if (NIL_P(intenc)) { - /* internal_encoding: nil => no transcoding */ - intencoding = (rb_encoding *)Qnil; - } - else if (!NIL_P(tmp = rb_check_string_type(intenc))) { - char *p = StringValueCStr(tmp); + if (NIL_P(intenc)) { + /* internal_encoding: nil => no transcoding */ + intencoding = (rb_encoding *)Qnil; + } + else if (!NIL_P(tmp = rb_check_string_type(intenc))) { + char *p = StringValueCStr(tmp); - if (*p == '-' && *(p+1) == '\0') { - /* Special case - "-" => no transcoding */ - intencoding = (rb_encoding *)Qnil; - } - else { - intencoding = rb_to_encoding(intenc); - } - } - else { - intencoding = rb_to_encoding(intenc); - } - if (extencoding == intencoding) { - intencoding = (rb_encoding *)Qnil; - } + if (*p == '-' && *(p+1) == '\0') { + /* Special case - "-" => no transcoding */ + intencoding = (rb_encoding *)Qnil; + } + else { + intencoding = rb_to_encoding(intenc); + } + } + else { + intencoding = rb_to_encoding(intenc); + } + if (extencoding == intencoding) { + intencoding = (rb_encoding *)Qnil; + } } if (!NIL_P(encoding)) { - extracted = 1; - if (!NIL_P(tmp = rb_check_string_type(encoding))) { - parse_mode_enc(StringValueCStr(tmp), rb_enc_get(tmp), - enc_p, enc2_p, fmode_p); - } - else { - rb_io_ext_int_to_encs(rb_to_encoding(encoding), NULL, enc_p, enc2_p, 0); - } + extracted = 1; + if (!NIL_P(tmp = rb_check_string_type(encoding))) { + parse_mode_enc(StringValueCStr(tmp), rb_enc_get(tmp), + enc_p, enc2_p, fmode_p); + } + else { + rb_io_ext_int_to_encs(rb_to_encoding(encoding), NULL, enc_p, enc2_p, 0); + } } else if (extenc != Qundef || intenc != Qundef) { extracted = 1; - rb_io_ext_int_to_encs(extencoding, intencoding, enc_p, enc2_p, 0); + rb_io_ext_int_to_encs(extencoding, intencoding, enc_p, enc2_p, 0); } return extracted; } @@ -6439,17 +6439,17 @@ validate_enc_binmode(int *fmode_p, int ecflags, rb_encoding *enc, rb_encoding *e rb_raise(rb_eArgError, "ASCII incompatible encoding needs binmode"); if ((fmode & FMODE_BINMODE) && (ecflags & ECONV_NEWLINE_DECORATOR_MASK)) { - rb_raise(rb_eArgError, "newline decorator with binary mode"); + rb_raise(rb_eArgError, "newline decorator with binary mode"); } if (!(fmode & FMODE_BINMODE) && - (DEFAULT_TEXTMODE || (ecflags & ECONV_NEWLINE_DECORATOR_MASK))) { - fmode |= FMODE_TEXTMODE; - *fmode_p = fmode; + (DEFAULT_TEXTMODE || (ecflags & ECONV_NEWLINE_DECORATOR_MASK))) { + fmode |= FMODE_TEXTMODE; + *fmode_p = fmode; } #if !DEFAULT_TEXTMODE else if (!(ecflags & ECONV_NEWLINE_DECORATOR_MASK)) { - fmode &= ~FMODE_TEXTMODE; - *fmode_p = fmode; + fmode &= ~FMODE_TEXTMODE; + *fmode_p = fmode; } #endif } @@ -6458,28 +6458,28 @@ static void extract_binmode(VALUE opthash, int *fmode) { if (!NIL_P(opthash)) { - VALUE v; - v = rb_hash_aref(opthash, sym_textmode); - if (!NIL_P(v)) { - if (*fmode & FMODE_TEXTMODE) - rb_raise(rb_eArgError, "textmode specified twice"); - if (*fmode & FMODE_BINMODE) - rb_raise(rb_eArgError, "both textmode and binmode specified"); - if (RTEST(v)) - *fmode |= FMODE_TEXTMODE; - } - v = rb_hash_aref(opthash, sym_binmode); - if (!NIL_P(v)) { - if (*fmode & FMODE_BINMODE) - rb_raise(rb_eArgError, "binmode specified twice"); - if (*fmode & FMODE_TEXTMODE) - rb_raise(rb_eArgError, "both textmode and binmode specified"); - if (RTEST(v)) - *fmode |= FMODE_BINMODE; - } + VALUE v; + v = rb_hash_aref(opthash, sym_textmode); + if (!NIL_P(v)) { + if (*fmode & FMODE_TEXTMODE) + rb_raise(rb_eArgError, "textmode specified twice"); + if (*fmode & FMODE_BINMODE) + rb_raise(rb_eArgError, "both textmode and binmode specified"); + if (RTEST(v)) + *fmode |= FMODE_TEXTMODE; + } + v = rb_hash_aref(opthash, sym_binmode); + if (!NIL_P(v)) { + if (*fmode & FMODE_BINMODE) + rb_raise(rb_eArgError, "binmode specified twice"); + if (*fmode & FMODE_TEXTMODE) + rb_raise(rb_eArgError, "both textmode and binmode specified"); + if (RTEST(v)) + *fmode |= FMODE_BINMODE; + } - if ((*fmode & FMODE_BINMODE) && (*fmode & FMODE_TEXTMODE)) - rb_raise(rb_eArgError, "both textmode and binmode specified"); + if ((*fmode & FMODE_BINMODE) && (*fmode & FMODE_TEXTMODE)) + rb_raise(rb_eArgError, "both textmode and binmode specified"); } } @@ -6522,24 +6522,24 @@ rb_io_extract_modeenc(VALUE *vmode_p, VALUE *vperm_p, VALUE opthash, has_enc = 1; parse_mode_enc(p+1, rb_enc_get(vmode), &enc, &enc2, &fmode); } - else { - rb_encoding *e; + else { + rb_encoding *e; - e = (fmode & FMODE_BINMODE) ? rb_ascii8bit_encoding() : NULL; - rb_io_ext_int_to_encs(e, NULL, &enc, &enc2, fmode); - } + e = (fmode & FMODE_BINMODE) ? rb_ascii8bit_encoding() : NULL; + rb_io_ext_int_to_encs(e, NULL, &enc, &enc2, fmode); + } } if (NIL_P(opthash)) { - ecflags = (fmode & FMODE_READABLE) ? - MODE_BTMODE(ECONV_DEFAULT_NEWLINE_DECORATOR, - 0, ECONV_UNIVERSAL_NEWLINE_DECORATOR) : 0; + ecflags = (fmode & FMODE_READABLE) ? + MODE_BTMODE(ECONV_DEFAULT_NEWLINE_DECORATOR, + 0, ECONV_UNIVERSAL_NEWLINE_DECORATOR) : 0; #ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE - ecflags |= (fmode & FMODE_WRITABLE) ? - MODE_BTMODE(TEXTMODE_NEWLINE_DECORATOR_ON_WRITE, - 0, TEXTMODE_NEWLINE_DECORATOR_ON_WRITE) : 0; + ecflags |= (fmode & FMODE_WRITABLE) ? + MODE_BTMODE(TEXTMODE_NEWLINE_DECORATOR_ON_WRITE, + 0, TEXTMODE_NEWLINE_DECORATOR_ON_WRITE) : 0; #endif - SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags); + SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags); ecopts = Qnil; if (fmode & FMODE_BINMODE) { #ifdef O_BINARY @@ -6555,57 +6555,57 @@ rb_io_extract_modeenc(VALUE *vmode_p, VALUE *vperm_p, VALUE opthash, #endif } else { - VALUE v; - if (!has_vmode) { - v = rb_hash_aref(opthash, sym_mode); - if (!NIL_P(v)) { - if (!NIL_P(vmode)) { - rb_raise(rb_eArgError, "mode specified twice"); - } - has_vmode = 1; - vmode = v; - goto vmode_handle; - } - } - v = rb_hash_aref(opthash, sym_flags); - if (!NIL_P(v)) { - v = rb_to_int(v); - oflags |= NUM2INT(v); - vmode = INT2NUM(oflags); - fmode = rb_io_oflags_fmode(oflags); - } - extract_binmode(opthash, &fmode); - if (fmode & FMODE_BINMODE) { + VALUE v; + if (!has_vmode) { + v = rb_hash_aref(opthash, sym_mode); + if (!NIL_P(v)) { + if (!NIL_P(vmode)) { + rb_raise(rb_eArgError, "mode specified twice"); + } + has_vmode = 1; + vmode = v; + goto vmode_handle; + } + } + v = rb_hash_aref(opthash, sym_flags); + if (!NIL_P(v)) { + v = rb_to_int(v); + oflags |= NUM2INT(v); + vmode = INT2NUM(oflags); + fmode = rb_io_oflags_fmode(oflags); + } + extract_binmode(opthash, &fmode); + if (fmode & FMODE_BINMODE) { #ifdef O_BINARY oflags |= O_BINARY; #endif - if (!has_enc) - rb_io_ext_int_to_encs(rb_ascii8bit_encoding(), NULL, &enc, &enc2, fmode); - } + if (!has_enc) + rb_io_ext_int_to_encs(rb_ascii8bit_encoding(), NULL, &enc, &enc2, fmode); + } #if DEFAULT_TEXTMODE - else if (NIL_P(vmode)) { - fmode |= DEFAULT_TEXTMODE; - } + else if (NIL_P(vmode)) { + fmode |= DEFAULT_TEXTMODE; + } #endif - v = rb_hash_aref(opthash, sym_perm); - if (!NIL_P(v)) { - if (vperm_p) { - if (!NIL_P(*vperm_p)) { - rb_raise(rb_eArgError, "perm specified twice"); - } - *vperm_p = v; - } - else { - /* perm no use, just ignore */ - } - } - ecflags = (fmode & FMODE_READABLE) ? - MODE_BTMODE(ECONV_DEFAULT_NEWLINE_DECORATOR, - 0, ECONV_UNIVERSAL_NEWLINE_DECORATOR) : 0; + v = rb_hash_aref(opthash, sym_perm); + if (!NIL_P(v)) { + if (vperm_p) { + if (!NIL_P(*vperm_p)) { + rb_raise(rb_eArgError, "perm specified twice"); + } + *vperm_p = v; + } + else { + /* perm no use, just ignore */ + } + } + ecflags = (fmode & FMODE_READABLE) ? + MODE_BTMODE(ECONV_DEFAULT_NEWLINE_DECORATOR, + 0, ECONV_UNIVERSAL_NEWLINE_DECORATOR) : 0; #ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE - ecflags |= (fmode & FMODE_WRITABLE) ? - MODE_BTMODE(TEXTMODE_NEWLINE_DECORATOR_ON_WRITE, - 0, TEXTMODE_NEWLINE_DECORATOR_ON_WRITE) : 0; + ecflags |= (fmode & FMODE_WRITABLE) ? + MODE_BTMODE(TEXTMODE_NEWLINE_DECORATOR_ON_WRITE, + 0, TEXTMODE_NEWLINE_DECORATOR_ON_WRITE) : 0; #endif if (rb_io_extract_encoding_option(opthash, &enc, &enc2, &fmode)) { @@ -6613,8 +6613,8 @@ rb_io_extract_modeenc(VALUE *vmode_p, VALUE *vperm_p, VALUE opthash, rb_raise(rb_eArgError, "encoding specified twice"); } } - SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags); - ecflags = rb_econv_prepare_options(opthash, &ecopts, ecflags); + SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags); + ecflags = rb_econv_prepare_options(opthash, &ecopts, ecflags); } validate_enc_binmode(&fmode, ecflags, enc, enc2); @@ -6666,13 +6666,13 @@ rb_sysopen(VALUE fname, int oflags, mode_t perm) fd = rb_sysopen_internal(&data); if (fd < 0) { - int e = errno; - if (rb_gc_for_fd(e)) { - fd = rb_sysopen_internal(&data); - } - if (fd < 0) { - rb_syserr_fail_path(e, fname); - } + int e = errno; + if (rb_gc_for_fd(e)) { + fd = rb_sysopen_internal(&data); + } + if (fd < 0) { + rb_syserr_fail_path(e, fname); + } } return fd; } @@ -6687,32 +6687,32 @@ rb_fdopen(int fd, const char *modestr) #endif file = fdopen(fd, modestr); if (!file) { - int e = errno; + int e = errno; #if defined(__sun) - if (e == 0) { - rb_gc(); - errno = 0; - file = fdopen(fd, modestr); - } - else + if (e == 0) { + rb_gc(); + errno = 0; + file = fdopen(fd, modestr); + } + else #endif - if (rb_gc_for_fd(e)) { - file = fdopen(fd, modestr); - } - if (!file) { + if (rb_gc_for_fd(e)) { + file = fdopen(fd, modestr); + } + if (!file) { #ifdef _WIN32 - if (e == 0) e = EINVAL; + if (e == 0) e = EINVAL; #elif defined(__sun) - if (e == 0) e = EMFILE; + if (e == 0) e = EMFILE; #endif - rb_syserr_fail(e, 0); - } + rb_syserr_fail(e, 0); + } } /* xxx: should be _IONBF? A buffer in FILE may have trouble. */ #ifdef USE_SETVBUF if (setvbuf(file, NULL, _IOFBF, 0) != 0) - rb_warn("setvbuf() can't be honoured (fd=%d)", fd); + rb_warn("setvbuf() can't be honoured (fd=%d)", fd); #endif return file; } @@ -6740,53 +6740,53 @@ io_strip_bom(VALUE io) if (NIL_P(b1 = rb_io_getbyte(io))) return 0; switch (b1) { case INT2FIX(0xEF): - if (NIL_P(b2 = rb_io_getbyte(io))) break; - if (b2 == INT2FIX(0xBB) && !NIL_P(b3 = rb_io_getbyte(io))) { - if (b3 == INT2FIX(0xBF)) { - return rb_utf8_encindex(); - } - rb_io_ungetbyte(io, b3); - } - rb_io_ungetbyte(io, b2); - break; + if (NIL_P(b2 = rb_io_getbyte(io))) break; + if (b2 == INT2FIX(0xBB) && !NIL_P(b3 = rb_io_getbyte(io))) { + if (b3 == INT2FIX(0xBF)) { + return rb_utf8_encindex(); + } + rb_io_ungetbyte(io, b3); + } + rb_io_ungetbyte(io, b2); + break; case INT2FIX(0xFE): - if (NIL_P(b2 = rb_io_getbyte(io))) break; - if (b2 == INT2FIX(0xFF)) { - return ENCINDEX_UTF_16BE; - } - rb_io_ungetbyte(io, b2); - break; + if (NIL_P(b2 = rb_io_getbyte(io))) break; + if (b2 == INT2FIX(0xFF)) { + return ENCINDEX_UTF_16BE; + } + rb_io_ungetbyte(io, b2); + break; case INT2FIX(0xFF): - if (NIL_P(b2 = rb_io_getbyte(io))) break; - if (b2 == INT2FIX(0xFE)) { - b3 = rb_io_getbyte(io); - if (b3 == INT2FIX(0) && !NIL_P(b4 = rb_io_getbyte(io))) { - if (b4 == INT2FIX(0)) { - return ENCINDEX_UTF_32LE; - } - rb_io_ungetbyte(io, b4); - } + if (NIL_P(b2 = rb_io_getbyte(io))) break; + if (b2 == INT2FIX(0xFE)) { + b3 = rb_io_getbyte(io); + if (b3 == INT2FIX(0) && !NIL_P(b4 = rb_io_getbyte(io))) { + if (b4 == INT2FIX(0)) { + return ENCINDEX_UTF_32LE; + } + rb_io_ungetbyte(io, b4); + } rb_io_ungetbyte(io, b3); return ENCINDEX_UTF_16LE; - } - rb_io_ungetbyte(io, b2); - break; + } + rb_io_ungetbyte(io, b2); + break; case INT2FIX(0): - if (NIL_P(b2 = rb_io_getbyte(io))) break; - if (b2 == INT2FIX(0) && !NIL_P(b3 = rb_io_getbyte(io))) { - if (b3 == INT2FIX(0xFE) && !NIL_P(b4 = rb_io_getbyte(io))) { - if (b4 == INT2FIX(0xFF)) { - return ENCINDEX_UTF_32BE; - } - rb_io_ungetbyte(io, b4); - } - rb_io_ungetbyte(io, b3); - } - rb_io_ungetbyte(io, b2); - break; + if (NIL_P(b2 = rb_io_getbyte(io))) break; + if (b2 == INT2FIX(0) && !NIL_P(b3 = rb_io_getbyte(io))) { + if (b3 == INT2FIX(0xFE) && !NIL_P(b4 = rb_io_getbyte(io))) { + if (b4 == INT2FIX(0xFF)) { + return ENCINDEX_UTF_32BE; + } + rb_io_ungetbyte(io, b4); + } + rb_io_ungetbyte(io, b3); + } + rb_io_ungetbyte(io, b2); + break; } rb_io_ungetbyte(io, b1); return 0; @@ -6806,27 +6806,27 @@ io_set_encoding_by_bom(VALUE io) rb_io_internal_encoding(io), Qnil); } else { - fptr->encs.enc2 = NULL; + fptr->encs.enc2 = NULL; } return extenc; } static VALUE rb_file_open_generic(VALUE io, VALUE filename, int oflags, int fmode, - const convconfig_t *convconfig, mode_t perm) + const convconfig_t *convconfig, mode_t perm) { VALUE pathv; rb_io_t *fptr; convconfig_t cc; if (!convconfig) { - /* Set to default encodings */ - rb_io_ext_int_to_encs(NULL, NULL, &cc.enc, &cc.enc2, fmode); + /* Set to default encodings */ + rb_io_ext_int_to_encs(NULL, NULL, &cc.enc, &cc.enc2, fmode); cc.ecflags = 0; cc.ecopts = Qnil; convconfig = &cc; } validate_enc_binmode(&fmode, convconfig->ecflags, - convconfig->enc, convconfig->enc2); + convconfig->enc, convconfig->enc2); MakeOpenFile(io, fptr); fptr->mode = fmode; @@ -6855,16 +6855,16 @@ rb_file_open_internal(VALUE io, VALUE filename, const char *modestr) if (p) { parse_mode_enc(p+1, rb_usascii_encoding(), - &convconfig.enc, &convconfig.enc2, &fmode); + &convconfig.enc, &convconfig.enc2, &fmode); convconfig.ecflags = 0; convconfig.ecopts = Qnil; } else { - rb_encoding *e; - /* Set to default encodings */ + rb_encoding *e; + /* Set to default encodings */ - e = (fmode & FMODE_BINMODE) ? rb_ascii8bit_encoding() : NULL; - rb_io_ext_int_to_encs(e, NULL, &convconfig.enc, &convconfig.enc2, fmode); + e = (fmode & FMODE_BINMODE) ? rb_ascii8bit_encoding() : NULL; + rb_io_ext_int_to_encs(e, NULL, &convconfig.enc, &convconfig.enc2, fmode); convconfig.ecflags = 0; convconfig.ecopts = Qnil; } @@ -6913,12 +6913,12 @@ pipe_del_fptr(rb_io_t *fptr) struct pipe_list *tmp; while ((tmp = *prev) != 0) { - if (tmp->fptr == fptr) { - *prev = tmp->next; - free(tmp); - return; - } - prev = &tmp->next; + if (tmp->fptr == fptr) { + *prev = tmp->next; + free(tmp); + return; + } + prev = &tmp->next; } } @@ -6930,9 +6930,9 @@ pipe_atexit(void) struct pipe_list *tmp; while (list) { - tmp = list->next; - rb_io_fptr_finalize(list->fptr); - list = tmp; + tmp = list->next; + rb_io_fptr_finalize(list->fptr); + list = tmp; } } #endif @@ -6968,14 +6968,14 @@ fptr_copy_finalizer(rb_io_t *fptr, const rb_io_t *orig) #if defined(__CYGWIN__) || !defined(HAVE_WORKING_FORK) if (old_finalize != pipe_finalize) { - struct pipe_list *list; - for (list = pipe_list; list; list = list->next) { - if (list->fptr == fptr) break; - } - if (!list) pipe_add_fptr(fptr); + struct pipe_list *list; + for (list = pipe_list; list; list = list->next) { + if (list->fptr == fptr) break; + } + if (!list) pipe_add_fptr(fptr); } else { - pipe_del_fptr(fptr); + pipe_del_fptr(fptr); } #endif } @@ -7126,15 +7126,15 @@ rb_close_before_exec(int lowfd, int maxhint, VALUE noclose_fds) if (!NIL_P(noclose_fds) && RTEST(rb_hash_lookup(noclose_fds, INT2FIX(fd)))) /* async-signal-safe */ continue; - ret = fcntl(fd, F_GETFD); /* async-signal-safe */ - if (ret != -1 && !(ret & FD_CLOEXEC)) { + ret = fcntl(fd, F_GETFD); /* async-signal-safe */ + if (ret != -1 && !(ret & FD_CLOEXEC)) { fcntl(fd, F_SETFD, ret|FD_CLOEXEC); /* async-signal-safe */ } # define CONTIGUOUS_CLOSED_FDS 20 if (ret != -1) { - if (max < fd + CONTIGUOUS_CLOSED_FDS) - max = fd + CONTIGUOUS_CLOSED_FDS; - } + if (max < fd + CONTIGUOUS_CLOSED_FDS) + max = fd + CONTIGUOUS_CLOSED_FDS; + } } #endif } @@ -7164,7 +7164,7 @@ char *rb_execarg_commandline(const struct rb_execarg *eargp, VALUE *prog); #ifndef __EMSCRIPTEN__ static VALUE pipe_open(VALUE execarg_obj, const char *modestr, int fmode, - const convconfig_t *convconfig) + const convconfig_t *convconfig) { struct rb_execarg *eargp = NIL_P(execarg_obj) ? NULL : rb_execarg_get(execarg_obj); VALUE prog = eargp ? (eargp->use_shell ? eargp->invoke.sh.shell_script : eargp->invoke.cmd.command_name) : Qfalse ; @@ -7185,12 +7185,12 @@ pipe_open(VALUE execarg_obj, const char *modestr, int fmode, #if defined(HAVE_SPAWNV) # if defined(HAVE_SPAWNVE) # define DO_SPAWN(cmd, args, envp) ((args) ? \ - spawnve(P_NOWAIT, (cmd), (args), (envp)) : \ - spawne(P_NOWAIT, (cmd), (envp))) + spawnve(P_NOWAIT, (cmd), (args), (envp)) : \ + spawne(P_NOWAIT, (cmd), (envp))) # else # define DO_SPAWN(cmd, args, envp) ((args) ? \ - spawnv(P_NOWAIT, (cmd), (args)) : \ - spawn(P_NOWAIT, (cmd))) + spawnv(P_NOWAIT, (cmd), (args)) : \ + spawn(P_NOWAIT, (cmd))) # endif # if !defined(HAVE_WORKING_FORK) char **args = NULL; @@ -7237,19 +7237,19 @@ pipe_open(VALUE execarg_obj, const char *modestr, int fmode, rb_execarg_addopt(execarg_obj, INT2FIX(0), INT2FIX(arg.write_pair[0])); rb_execarg_addopt(execarg_obj, INT2FIX(1), INT2FIX(arg.pair[1])); } - break; + break; case FMODE_READABLE: if (rb_pipe(arg.pair) < 0) rb_sys_fail_str(prog); if (eargp) rb_execarg_addopt(execarg_obj, INT2FIX(1), INT2FIX(arg.pair[1])); - break; + break; case FMODE_WRITABLE: if (rb_pipe(arg.pair) < 0) rb_sys_fail_str(prog); if (eargp) rb_execarg_addopt(execarg_obj, INT2FIX(0), INT2FIX(arg.pair[0])); - break; + break; default: rb_sys_fail_str(prog); } @@ -7265,59 +7265,59 @@ pipe_open(VALUE execarg_obj, const char *modestr, int fmode, } # if defined(HAVE_WORKING_FORK) - pid = rb_fork_async_signal_safe(&status, popen_exec, &arg, arg.eargp->redirect_fds, errmsg, sizeof(errmsg)); + pid = rb_fork_async_signal_safe(&status, popen_exec, &arg, arg.eargp->redirect_fds, errmsg, sizeof(errmsg)); # else - rb_execarg_run_options(eargp, sargp, NULL, 0); + rb_execarg_run_options(eargp, sargp, NULL, 0); # if defined(HAVE_SPAWNVE) - if (eargp->envp_str) envp = (char **)RSTRING_PTR(eargp->envp_str); + if (eargp->envp_str) envp = (char **)RSTRING_PTR(eargp->envp_str); # endif while ((pid = DO_SPAWN(cmd, args, envp)) < 0) { - /* exec failed */ - switch (e = errno) { - case EAGAIN: + /* exec failed */ + switch (e = errno) { + case EAGAIN: # if EWOULDBLOCK != EAGAIN - case EWOULDBLOCK: + case EWOULDBLOCK: # endif - rb_thread_sleep(1); - continue; - } - break; - } - if (eargp) - rb_execarg_run_options(sargp, NULL, NULL, 0); + rb_thread_sleep(1); + continue; + } + break; + } + if (eargp) + rb_execarg_run_options(sargp, NULL, NULL, 0); # endif rb_execarg_parent_end(execarg_obj); } else { # if defined(HAVE_WORKING_FORK) - pid = rb_call_proc__fork(); - if (pid == 0) { /* child */ - popen_redirect(&arg); - rb_io_synchronized(RFILE(orig_stdout)->fptr); - rb_io_synchronized(RFILE(orig_stderr)->fptr); - return Qnil; - } + pid = rb_call_proc__fork(); + if (pid == 0) { /* child */ + popen_redirect(&arg); + rb_io_synchronized(RFILE(orig_stdout)->fptr); + rb_io_synchronized(RFILE(orig_stderr)->fptr); + return Qnil; + } # else - rb_notimplement(); + rb_notimplement(); # endif } /* parent */ if (pid < 0) { # if defined(HAVE_WORKING_FORK) - e = errno; + e = errno; # endif - close(arg.pair[0]); - close(arg.pair[1]); + close(arg.pair[0]); + close(arg.pair[1]); if ((fmode & (FMODE_READABLE|FMODE_WRITABLE)) == (FMODE_READABLE|FMODE_WRITABLE)) { close(arg.write_pair[0]); close(arg.write_pair[1]); } # if defined(HAVE_WORKING_FORK) if (errmsg[0]) - rb_syserr_fail(e, errmsg); + rb_syserr_fail(e, errmsg); # endif - rb_syserr_fail_str(e, prog); + rb_syserr_fail_str(e, prog); } if ((fmode & FMODE_READABLE) && (fmode & FMODE_WRITABLE)) { close(arg.pair[1]); @@ -7336,14 +7336,14 @@ pipe_open(VALUE execarg_obj, const char *modestr, int fmode, #else cmd = rb_execarg_commandline(eargp, &prog); if (!NIL_P(execarg_obj)) { - rb_execarg_parent_start(execarg_obj); - rb_execarg_run_options(eargp, sargp, NULL, 0); + rb_execarg_parent_start(execarg_obj); + rb_execarg_run_options(eargp, sargp, NULL, 0); } fp = popen(cmd, modestr); e = errno; if (eargp) { rb_execarg_parent_end(execarg_obj); - rb_execarg_run_options(sargp, NULL, NULL, 0); + rb_execarg_run_options(sargp, NULL, NULL, 0); } if (!fp) rb_syserr_fail_path(e, prog); fd = fileno(fp); @@ -7357,19 +7357,19 @@ pipe_open(VALUE execarg_obj, const char *modestr, int fmode, if (convconfig) { fptr->encs = *convconfig; #if RUBY_CRLF_ENVIRONMENT - if (fptr->encs.ecflags & ECONV_DEFAULT_NEWLINE_DECORATOR) { - fptr->encs.ecflags |= ECONV_UNIVERSAL_NEWLINE_DECORATOR; - } + if (fptr->encs.ecflags & ECONV_DEFAULT_NEWLINE_DECORATOR) { + fptr->encs.ecflags |= ECONV_UNIVERSAL_NEWLINE_DECORATOR; + } #endif } else { - if (NEED_NEWLINE_DECORATOR_ON_READ(fptr)) { - fptr->encs.ecflags |= ECONV_UNIVERSAL_NEWLINE_DECORATOR; - } + if (NEED_NEWLINE_DECORATOR_ON_READ(fptr)) { + fptr->encs.ecflags |= ECONV_UNIVERSAL_NEWLINE_DECORATOR; + } #ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE - if (NEED_NEWLINE_DECORATOR_ON_WRITE(fptr)) { - fptr->encs.ecflags |= TEXTMODE_NEWLINE_DECORATOR_ON_WRITE; - } + if (NEED_NEWLINE_DECORATOR_ON_WRITE(fptr)) { + fptr->encs.ecflags |= TEXTMODE_NEWLINE_DECORATOR_ON_WRITE; + } #endif } fptr->pid = pid; @@ -7393,7 +7393,7 @@ pipe_open(VALUE execarg_obj, const char *modestr, int fmode, #else static VALUE pipe_open(VALUE execarg_obj, const char *modestr, int fmode, - const convconfig_t *convconfig) + const convconfig_t *convconfig) { rb_raise(rb_eNotImpError, "popen() is not available"); } @@ -7404,10 +7404,10 @@ is_popen_fork(VALUE prog) { if (RSTRING_LEN(prog) == 1 && RSTRING_PTR(prog)[0] == '-') { #if !defined(HAVE_WORKING_FORK) - rb_raise(rb_eNotImpError, - "fork() function is unimplemented on this machine"); + rb_raise(rb_eNotImpError, + "fork() function is unimplemented on this machine"); #else - return TRUE; + return TRUE; #endif } return FALSE; @@ -7415,7 +7415,7 @@ is_popen_fork(VALUE prog) static VALUE pipe_open_s(VALUE prog, const char *modestr, int fmode, - const convconfig_t *convconfig) + const convconfig_t *convconfig) { int argc = 1; VALUE *argv = &prog; @@ -7431,7 +7431,7 @@ pipe_close(VALUE io) { rb_io_t *fptr = io_close_fptr(io); if (fptr) { - fptr_waitpid(fptr, rb_thread_to_be_killed(rb_thread_current())); + fptr_waitpid(fptr, rb_thread_to_be_killed(rb_thread_current())); } return Qnil; } @@ -7605,15 +7605,15 @@ rb_io_s_popen(int argc, VALUE *argv, VALUE klass) if (argc > 1 && !NIL_P(env = rb_check_hash_type(argv[0]))) --argc, ++argv; switch (argc) { case 2: - pmode = argv[1]; + pmode = argv[1]; case 1: - pname = argv[0]; - break; + pname = argv[0]; + break; default: - { - int ex = !NIL_P(opt); - rb_error_arity(argc + ex, 1 + ex, 2 + ex); - } + { + int ex = !NIL_P(opt); + rb_error_arity(argc + ex, 1 + ex, 2 + ex); + } } return popen_finish(rb_io_popen(pname, pmode, env, opt), klass); } @@ -7628,26 +7628,26 @@ rb_io_popen(VALUE pname, VALUE pmode, VALUE env, VALUE opt) tmp = rb_check_array_type(pname); if (!NIL_P(tmp)) { - long len = RARRAY_LEN(tmp); + long len = RARRAY_LEN(tmp); #if SIZEOF_LONG > SIZEOF_INT - if (len > INT_MAX) { - rb_raise(rb_eArgError, "too many arguments"); - } + if (len > INT_MAX) { + rb_raise(rb_eArgError, "too many arguments"); + } #endif execarg_obj = rb_execarg_new((int)len, RARRAY_CONST_PTR(tmp), FALSE, FALSE); - RB_GC_GUARD(tmp); + RB_GC_GUARD(tmp); } else { - SafeStringValue(pname); - execarg_obj = Qnil; - if (!is_popen_fork(pname)) + SafeStringValue(pname); + execarg_obj = Qnil; + if (!is_popen_fork(pname)) execarg_obj = rb_execarg_new(1, &pname, TRUE, FALSE); } if (!NIL_P(execarg_obj)) { - if (!NIL_P(opt)) - opt = rb_execarg_extract_options(execarg_obj, opt); - if (!NIL_P(env)) - rb_execarg_setenv(execarg_obj, env); + if (!NIL_P(opt)) + opt = rb_execarg_extract_options(execarg_obj, opt); + if (!NIL_P(env)) + rb_execarg_setenv(execarg_obj, env); } rb_io_extract_modeenc(&pmode, 0, opt, &oflags, &fmode, &convconfig); modestr = rb_io_oflags_modestr(oflags); @@ -7659,18 +7659,18 @@ static VALUE popen_finish(VALUE port, VALUE klass) { if (NIL_P(port)) { - /* child */ - if (rb_block_given_p()) { - rb_yield(Qnil); + /* child */ + if (rb_block_given_p()) { + rb_yield(Qnil); rb_io_flush(rb_ractor_stdout()); rb_io_flush(rb_ractor_stderr()); - _exit(0); - } - return Qnil; + _exit(0); + } + return Qnil; } RBASIC_SET_CLASS(port, klass); if (rb_block_given_p()) { - return rb_ensure(rb_yield, port, pipe_close, port); + return rb_ensure(rb_yield, port, pipe_close, port); } return port; } @@ -7749,7 +7749,7 @@ rb_io_s_open(int argc, VALUE *argv, VALUE klass) VALUE io = rb_class_new_instance_kw(argc, argv, klass, RB_PASS_CALLED_KEYWORDS); if (rb_block_given_p()) { - return rb_ensure(rb_yield, io, io_close, io); + return rb_ensure(rb_yield, io, io_close, io); } return io; @@ -7789,8 +7789,8 @@ rb_io_s_sysopen(int argc, VALUE *argv, VALUE _) else if (!NIL_P(intmode = rb_check_to_integer(vmode, "to_int"))) oflags = NUM2INT(intmode); else { - SafeStringValue(vmode); - oflags = rb_io_modestr_oflags(StringValueCStr(vmode)); + SafeStringValue(vmode); + oflags = rb_io_modestr_oflags(StringValueCStr(vmode)); } if (NIL_P(vperm)) perm = 0666; else perm = NUM2MODET(vperm); @@ -7920,32 +7920,32 @@ rb_f_open(int argc, VALUE *argv, VALUE _) int redirect = FALSE; if (argc >= 1) { - CONST_ID(to_open, "to_open"); - if (rb_respond_to(argv[0], to_open)) { - redirect = TRUE; - } - else { - VALUE tmp = argv[0]; - FilePathValue(tmp); - if (NIL_P(tmp)) { - redirect = TRUE; - } - else { + CONST_ID(to_open, "to_open"); + if (rb_respond_to(argv[0], to_open)) { + redirect = TRUE; + } + else { + VALUE tmp = argv[0]; + FilePathValue(tmp); + if (NIL_P(tmp)) { + redirect = TRUE; + } + else { VALUE cmd = check_pipe_command(tmp); if (!NIL_P(cmd)) { - argv[0] = cmd; - return rb_io_s_popen(argc, argv, rb_cIO); - } - } - } + argv[0] = cmd; + return rb_io_s_popen(argc, argv, rb_cIO); + } + } + } } if (redirect) { VALUE io = rb_funcallv_kw(argv[0], to_open, argc-1, argv+1, RB_PASS_CALLED_KEYWORDS); - if (rb_block_given_p()) { - return rb_ensure(rb_yield, io, io_close, io); - } - return io; + if (rb_block_given_p()) { + return rb_ensure(rb_yield, io, io_close, io); + } + return io; } return rb_io_s_open(argc, argv, rb_cFile); } @@ -7966,15 +7966,15 @@ rb_io_open(VALUE io, VALUE filename, VALUE vmode, VALUE vperm, VALUE opt) static VALUE rb_io_open_generic(VALUE klass, VALUE filename, int oflags, int fmode, - const convconfig_t *convconfig, mode_t perm) + const convconfig_t *convconfig, mode_t perm) { VALUE cmd; if (klass == rb_cIO && !NIL_P(cmd = check_pipe_command(filename))) { - return pipe_open_s(cmd, rb_io_oflags_modestr(oflags), fmode, convconfig); + return pipe_open_s(cmd, rb_io_oflags_modestr(oflags), fmode, convconfig); } else { - return rb_file_open_generic(io_alloc(klass), filename, - oflags, fmode, convconfig, perm); + return rb_file_open_generic(io_alloc(klass), filename, + oflags, fmode, convconfig, perm); } } @@ -7994,11 +7994,11 @@ io_reopen(VALUE io, VALUE nfile) if ((fptr->stdio_file == stdin && !(orig->mode & FMODE_READABLE)) || (fptr->stdio_file == stdout && !(orig->mode & FMODE_WRITABLE)) || (fptr->stdio_file == stderr && !(orig->mode & FMODE_WRITABLE))) { - rb_raise(rb_eArgError, - "%s can't change access mode from \"%s\" to \"%s\"", - PREP_STDIO_NAME(fptr), rb_io_fmode_modestr(fptr->mode), - rb_io_fmode_modestr(orig->mode)); - } + rb_raise(rb_eArgError, + "%s can't change access mode from \"%s\" to \"%s\"", + PREP_STDIO_NAME(fptr), rb_io_fmode_modestr(fptr->mode), + rb_io_fmode_modestr(orig->mode)); + } } if (fptr->mode & FMODE_WRITABLE) { if (io_fflush(fptr) < 0) @@ -8008,7 +8008,7 @@ io_reopen(VALUE io, VALUE nfile) flush_before_seek(fptr); } if (orig->mode & FMODE_READABLE) { - pos = io_tell(orig); + pos = io_tell(orig); } if (orig->mode & FMODE_WRITABLE) { if (io_fflush(orig) < 0) @@ -8026,13 +8026,13 @@ io_reopen(VALUE io, VALUE nfile) fd = fptr->fd; fd2 = orig->fd; if (fd != fd2) { - if (IS_PREP_STDIO(fptr) || fd <= 2 || !fptr->stdio_file) { - /* need to keep FILE objects of stdin, stdout and stderr */ - if (rb_cloexec_dup2(fd2, fd) < 0) - rb_sys_fail_path(orig->pathv); + if (IS_PREP_STDIO(fptr) || fd <= 2 || !fptr->stdio_file) { + /* need to keep FILE objects of stdin, stdout and stderr */ + if (rb_cloexec_dup2(fd2, fd) < 0) + rb_sys_fail_path(orig->pathv); rb_update_max_fd(fd); - } - else { + } + else { fclose(fptr->stdio_file); fptr->stdio_file = 0; fptr->fd = -1; @@ -8040,20 +8040,20 @@ io_reopen(VALUE io, VALUE nfile) rb_sys_fail_path(orig->pathv); rb_update_max_fd(fd); fptr->fd = fd; - } - rb_thread_fd_close(fd); - if ((orig->mode & FMODE_READABLE) && pos >= 0) { - if (io_seek(fptr, pos, SEEK_SET) < 0 && errno) { - rb_sys_fail_path(fptr->pathv); - } - if (io_seek(orig, pos, SEEK_SET) < 0 && errno) { - rb_sys_fail_path(orig->pathv); - } - } + } + rb_thread_fd_close(fd); + if ((orig->mode & FMODE_READABLE) && pos >= 0) { + if (io_seek(fptr, pos, SEEK_SET) < 0 && errno) { + rb_sys_fail_path(fptr->pathv); + } + if (io_seek(orig, pos, SEEK_SET) < 0 && errno) { + rb_sys_fail_path(orig->pathv); + } + } } if (fptr->mode & FMODE_BINMODE) { - rb_io_binmode(io); + rb_io_binmode(io); } RBASIC_SET_CLASS(io, rb_obj_class(nfile)); @@ -8067,8 +8067,8 @@ static int rb_freopen(VALUE fname, const char *mode, FILE *fp) { if (!freopen(RSTRING_PTR(fname), mode, fp)) { - RB_GC_GUARD(fname); - return errno; + RB_GC_GUARD(fname); + return errno; } return 0; } @@ -8116,44 +8116,44 @@ rb_io_reopen(int argc, VALUE *argv, VALUE file) rb_io_t *fptr; if (rb_scan_args(argc, argv, "11:", &fname, &nmode, &opt) == 1) { - VALUE tmp = rb_io_check_io(fname); - if (!NIL_P(tmp)) { - return io_reopen(file, tmp); - } + VALUE tmp = rb_io_check_io(fname); + if (!NIL_P(tmp)) { + return io_reopen(file, tmp); + } } FilePathValue(fname); rb_io_taint_check(file); fptr = RFILE(file)->fptr; if (!fptr) { - fptr = RFILE(file)->fptr = ZALLOC(rb_io_t); + fptr = RFILE(file)->fptr = ZALLOC(rb_io_t); } if (!NIL_P(nmode) || !NIL_P(opt)) { - int fmode; - convconfig_t convconfig; + int fmode; + convconfig_t convconfig; - rb_io_extract_modeenc(&nmode, 0, opt, &oflags, &fmode, &convconfig); - if (IS_PREP_STDIO(fptr) && + rb_io_extract_modeenc(&nmode, 0, opt, &oflags, &fmode, &convconfig); + if (IS_PREP_STDIO(fptr) && ((fptr->mode & FMODE_READWRITE) & (fmode & FMODE_READWRITE)) != (fptr->mode & FMODE_READWRITE)) { - rb_raise(rb_eArgError, - "%s can't change access mode from \"%s\" to \"%s\"", - PREP_STDIO_NAME(fptr), rb_io_fmode_modestr(fptr->mode), - rb_io_fmode_modestr(fmode)); - } - fptr->mode = fmode; - fptr->encs = convconfig; + rb_raise(rb_eArgError, + "%s can't change access mode from \"%s\" to \"%s\"", + PREP_STDIO_NAME(fptr), rb_io_fmode_modestr(fptr->mode), + rb_io_fmode_modestr(fmode)); + } + fptr->mode = fmode; + fptr->encs = convconfig; } else { - oflags = rb_io_fmode_oflags(fptr->mode); + oflags = rb_io_fmode_oflags(fptr->mode); } fptr->pathv = fname; if (fptr->fd < 0) { fptr->fd = rb_sysopen(fptr->pathv, oflags, 0666); - fptr->stdio_file = 0; - return file; + fptr->stdio_file = 0; + return file; } if (fptr->mode & FMODE_WRITABLE) { @@ -8163,9 +8163,9 @@ rb_io_reopen(int argc, VALUE *argv, VALUE file) fptr->rbuf.off = fptr->rbuf.len = 0; if (fptr->stdio_file) { - int e = rb_freopen(rb_str_encode_ospath(fptr->pathv), - rb_io_oflags_modestr(oflags), - fptr->stdio_file); + int e = rb_freopen(rb_str_encode_ospath(fptr->pathv), + rb_io_oflags_modestr(oflags), + fptr->stdio_file); if (e) rb_syserr_fail_path(e, fptr->pathv); fptr->fd = fileno(fptr->stdio_file); rb_fd_fix_cloexec(fptr->fd); @@ -8183,14 +8183,14 @@ rb_io_reopen(int argc, VALUE *argv, VALUE file) } } else { - int tmpfd = rb_sysopen(fptr->pathv, oflags, 0666); - int err = 0; - if (rb_cloexec_dup2(tmpfd, fptr->fd) < 0) - err = errno; - (void)close(tmpfd); - if (err) { - rb_syserr_fail_path(err, fptr->pathv); - } + int tmpfd = rb_sysopen(fptr->pathv, oflags, 0666); + int err = 0; + if (rb_cloexec_dup2(tmpfd, fptr->fd) < 0) + err = errno; + (void)close(tmpfd); + if (err) { + rb_syserr_fail_path(err, fptr->pathv); + } } return file; @@ -8226,7 +8226,7 @@ rb_io_init_copy(VALUE dest, VALUE io) if (0 <= pos) io_seek(fptr, pos, SEEK_SET); if (fptr->mode & FMODE_BINMODE) { - rb_io_binmode(dest); + rb_io_binmode(dest); } write_io = GetWriteIO(io); @@ -8298,12 +8298,12 @@ rb_f_printf(int argc, VALUE *argv, VALUE _) if (argc == 0) return Qnil; if (RB_TYPE_P(argv[0], T_STRING)) { - out = rb_ractor_stdout(); + out = rb_ractor_stdout(); } else { - out = argv[0]; - argv++; - argc--; + out = argv[0]; + argv++; + argc--; } rb_io_write(out, rb_f_sprintf(argc, argv)); @@ -8383,21 +8383,21 @@ rb_io_print(int argc, const VALUE *argv, VALUE out) /* if no argument given, print `$_' */ if (argc == 0) { - argc = 1; - line = rb_lastline_get(); - argv = &line; + argc = 1; + line = rb_lastline_get(); + argv = &line; } if (argc > 1 && !NIL_P(rb_output_fs)) { rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "$, is set to non-nil value"); } for (i=0; i0) { - rb_io_write(out, rb_output_fs); - } - rb_io_write(out, argv[i]); + if (!NIL_P(rb_output_fs) && i>0) { + rb_io_write(out, rb_output_fs); + } + rb_io_write(out, argv[i]); } if (argc > 0 && !NIL_P(rb_output_rs)) { - rb_io_write(out, rb_output_rs); + rb_io_write(out, rb_output_rs); } return Qnil; @@ -8484,11 +8484,11 @@ rb_io_putc(VALUE io, VALUE ch) { VALUE str; if (RB_TYPE_P(ch, T_STRING)) { - str = rb_str_substr(ch, 0, 1); + str = rb_str_substr(ch, 0, 1); } else { - char c = NUM2CHR(ch); - str = rb_str_new(&c, 1); + char c = NUM2CHR(ch); + str = rb_str_new(&c, 1); } rb_io_write(io, str); return ch; @@ -8518,7 +8518,7 @@ rb_f_putc(VALUE recv, VALUE ch) { VALUE r_stdout = rb_ractor_stdout(); if (recv == r_stdout) { - return rb_io_putc(recv, ch); + return rb_io_putc(recv, ch); } return forward(r_stdout, rb_intern("putc"), 1, &ch); } @@ -8534,7 +8534,7 @@ rb_str_end_with_asciichar(VALUE str, int c) if (len == 0) return 0; if ((n = rb_enc_mbminlen(enc)) == 1) { - return ptr[len - 1] == c; + return ptr[len - 1] == c; } return rb_enc_ascget(ptr + ((len - 1) / n) * n, ptr + len, &n, enc) == c; } @@ -8546,15 +8546,15 @@ io_puts_ary(VALUE ary, VALUE out, int recur) long i; if (recur) { - tmp = rb_str_new2("[...]"); - rb_io_puts(1, &tmp, out); - return Qtrue; + tmp = rb_str_new2("[...]"); + rb_io_puts(1, &tmp, out); + return Qtrue; } ary = rb_check_array_type(ary); if (NIL_P(ary)) return Qfalse; for (i=0; i 0) return; - } + if (isatty(fileno(stderr))) { + if (rb_w32_write_console(rb_str_new(mesg, len), fileno(stderr)) > 0) return; + } #endif - if (fwrite(mesg, sizeof(char), (size_t)len, stderr) < (size_t)len) { - /* failed to write to stderr, what can we do? */ - return; - } + if (fwrite(mesg, sizeof(char), (size_t)len, stderr) < (size_t)len) { + /* failed to write to stderr, what can we do? */ + return; + } } else { - rb_io_write(out, rb_str_new(mesg, len)); + rb_io_write(out, rb_str_new(mesg, len)); } } @@ -8803,20 +8803,20 @@ rb_write_error_str(VALUE mesg) VALUE out = rb_ractor_stderr(); /* a stopgap measure for the time being */ if (rb_stderr_to_original_p(out)) { - size_t len = (size_t)RSTRING_LEN(mesg); + size_t len = (size_t)RSTRING_LEN(mesg); #ifdef _WIN32 - if (isatty(fileno(stderr))) { - if (rb_w32_write_console(mesg, fileno(stderr)) > 0) return; - } + if (isatty(fileno(stderr))) { + if (rb_w32_write_console(mesg, fileno(stderr)) > 0) return; + } #endif - if (fwrite(RSTRING_PTR(mesg), sizeof(char), len, stderr) < len) { - RB_GC_GUARD(mesg); - return; - } + if (fwrite(RSTRING_PTR(mesg), sizeof(char), len, stderr) < len) { + RB_GC_GUARD(mesg); + return; + } } else { - /* may unlock GVL, and */ - rb_io_write(out, mesg); + /* may unlock GVL, and */ + rb_io_write(out, mesg); } } @@ -8824,7 +8824,7 @@ int rb_stderr_tty_p(void) { if (rb_stderr_to_original_p(rb_ractor_stderr())) - return isatty(fileno(stderr)); + return isatty(fileno(stderr)); return 0; } @@ -8832,9 +8832,9 @@ static void must_respond_to(ID mid, VALUE val, ID id) { if (!rb_respond_to(val, mid)) { - rb_raise(rb_eTypeError, "%"PRIsVALUE" must have %"PRIsVALUE" method, %"PRIsVALUE" given", - rb_id2str(id), rb_id2str(mid), - rb_obj_class(val)); + rb_raise(rb_eTypeError, "%"PRIsVALUE" must have %"PRIsVALUE" method, %"PRIsVALUE" given", + rb_id2str(id), rb_id2str(mid), + rb_obj_class(val)); } } @@ -8888,8 +8888,8 @@ prep_io(int fd, int fmode, VALUE klass, const char *path) fp->mode = fmode; if (!io_check_tty(fp)) { #ifdef __CYGWIN__ - fp->mode |= FMODE_BINMODE; - setmode(fd, O_BINARY); + fp->mode |= FMODE_BINMODE; + setmode(fd, O_BINARY); #endif } if (path) fp->pathv = rb_obj_freeze(rb_str_new_cstr(path)); @@ -8918,7 +8918,7 @@ prep_stdio(FILE *f, int fmode, VALUE klass, const char *path) #ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE fptr->encs.ecflags |= TEXTMODE_NEWLINE_DECORATOR_ON_WRITE; if (fmode & FMODE_READABLE) { - fptr->encs.ecflags |= ECONV_UNIVERSAL_NEWLINE_DECORATOR; + fptr->encs.ecflags |= ECONV_UNIVERSAL_NEWLINE_DECORATOR; } #endif fptr->stdio_file = f; @@ -9071,7 +9071,7 @@ rb_io_initialize(int argc, VALUE *argv, VALUE io) fd = NUM2INT(fnum); if (rb_reserved_fd_p(fd)) { - rb_raise(rb_eArgError, "The given fd is not accessible because RubyVM reserves it"); + rb_raise(rb_eArgError, "The given fd is not accessible because RubyVM reserves it"); } #if defined(HAVE_FCNTL) && defined(F_GETFL) oflags = fcntl(fd, F_GETFL); @@ -9083,15 +9083,15 @@ rb_io_initialize(int argc, VALUE *argv, VALUE io) #if defined(HAVE_FCNTL) && defined(F_GETFL) ofmode = rb_io_oflags_fmode(oflags); if (NIL_P(vmode)) { - fmode = ofmode; + fmode = ofmode; } else if ((~ofmode & fmode) & FMODE_READWRITE) { - VALUE error = INT2FIX(EINVAL); - rb_exc_raise(rb_class_new_instance(1, &error, rb_eSystemCallError)); + VALUE error = INT2FIX(EINVAL); + rb_exc_raise(rb_class_new_instance(1, &error, rb_eSystemCallError)); } #endif if (!NIL_P(opt) && rb_hash_aref(opt, sym_autoclose) == Qfalse) { - fmode |= FMODE_PREP; + fmode |= FMODE_PREP; } MakeOpenFile(io, fp); fp->self = io; @@ -9101,11 +9101,11 @@ rb_io_initialize(int argc, VALUE *argv, VALUE io) clear_codeconv(fp); io_check_tty(fp); if (fileno(stdin) == fd) - fp->stdio_file = stdin; + fp->stdio_file = stdin; else if (fileno(stdout) == fd) - fp->stdio_file = stdout; + fp->stdio_file = stdout; else if (fileno(stderr) == fd) - fp->stdio_file = stderr; + fp->stdio_file = stderr; if (fmode & FMODE_SETENC_BY_BOM) io_set_encoding_by_bom(io); return io; @@ -9199,15 +9199,15 @@ static VALUE rb_file_initialize(int argc, VALUE *argv, VALUE io) { if (RFILE(io)->fptr) { - rb_raise(rb_eRuntimeError, "reinitializing File"); + rb_raise(rb_eRuntimeError, "reinitializing File"); } if (0 < argc && argc < 3) { - VALUE fd = rb_check_to_int(argv[0]); + VALUE fd = rb_check_to_int(argv[0]); - if (!NIL_P(fd)) { - argv[0] = fd; - return rb_io_initialize(argc, argv, io); - } + if (!NIL_P(fd)) { + argv[0] = fd; + return rb_io_initialize(argc, argv, io); + } } rb_open_file(argc, argv, io); @@ -9219,10 +9219,10 @@ static VALUE rb_io_s_new(int argc, VALUE *argv, VALUE klass) { if (rb_block_given_p()) { - VALUE cname = rb_obj_as_string(klass); + VALUE cname = rb_obj_as_string(klass); - rb_warn("%"PRIsVALUE"::new() does not take block; use %"PRIsVALUE"::open() instead", - cname, cname); + rb_warn("%"PRIsVALUE"::new() does not take block; use %"PRIsVALUE"::open() instead", + cname, cname); } return rb_class_new_instance_kw(argc, argv, klass, RB_PASS_CALLED_KEYWORDS); } @@ -9283,9 +9283,9 @@ rb_io_set_autoclose(VALUE io, VALUE autoclose) rb_io_t *fptr; GetOpenFile(io, fptr); if (!RTEST(autoclose)) - fptr->mode |= FMODE_PREP; + fptr->mode |= FMODE_PREP; else - fptr->mode &= ~FMODE_PREP; + fptr->mode &= ~FMODE_PREP; return autoclose; } @@ -9622,7 +9622,7 @@ argf_forward(int argc, VALUE *argv, VALUE argf) (ARGF.current_file == rb_stdin && !RB_TYPE_P(ARGF.current_file, T_FILE)) #define ARGF_FORWARD(argc, argv) do {\ if (ARGF_GENERIC_INPUT_P())\ - return argf_forward((argc), (argv), argf);\ + return argf_forward((argc), (argv), argf);\ } while (0) #define NEXT_ARGF_FORWARD(argc, argv) do {\ if (!next_argv()) return Qnil;\ @@ -9635,7 +9635,7 @@ argf_close(VALUE argf) VALUE file = ARGF.current_file; if (file == rb_stdin) return; if (RB_TYPE_P(file, T_FILE)) { - rb_io_set_write_io(file, Qnil); + rb_io_set_write_io(file, Qnil); } io_close(file); ARGF.init_p = -1; @@ -9658,163 +9658,163 @@ argf_next_argv(VALUE argf) } if (ARGF.init_p == 0) { - if (!NIL_P(ARGF.argv) && RARRAY_LEN(ARGF.argv) > 0) { - ARGF.next_p = 1; - } - else { - ARGF.next_p = -1; - } - ARGF.init_p = 1; + if (!NIL_P(ARGF.argv) && RARRAY_LEN(ARGF.argv) > 0) { + ARGF.next_p = 1; + } + else { + ARGF.next_p = -1; + } + ARGF.init_p = 1; } else { - if (NIL_P(ARGF.argv)) { - ARGF.next_p = -1; - } - else if (ARGF.next_p == -1 && RARRAY_LEN(ARGF.argv) > 0) { - ARGF.next_p = 1; - } + if (NIL_P(ARGF.argv)) { + ARGF.next_p = -1; + } + else if (ARGF.next_p == -1 && RARRAY_LEN(ARGF.argv) > 0) { + ARGF.next_p = 1; + } } if (ARGF.next_p == 1) { - if (ARGF.init_p == 1) argf_close(argf); + if (ARGF.init_p == 1) argf_close(argf); retry: - if (RARRAY_LEN(ARGF.argv) > 0) { - VALUE filename = rb_ary_shift(ARGF.argv); - FilePathValue(filename); - ARGF.filename = filename; - filename = rb_str_encode_ospath(filename); - fn = StringValueCStr(filename); - if (RSTRING_LEN(filename) == 1 && fn[0] == '-') { - ARGF.current_file = rb_stdin; - if (ARGF.inplace) { - rb_warn("Can't do inplace edit for stdio; skipping"); - goto retry; - } - } - else { - VALUE write_io = Qnil; - int fr = rb_sysopen(filename, O_RDONLY, 0); + if (RARRAY_LEN(ARGF.argv) > 0) { + VALUE filename = rb_ary_shift(ARGF.argv); + FilePathValue(filename); + ARGF.filename = filename; + filename = rb_str_encode_ospath(filename); + fn = StringValueCStr(filename); + if (RSTRING_LEN(filename) == 1 && fn[0] == '-') { + ARGF.current_file = rb_stdin; + if (ARGF.inplace) { + rb_warn("Can't do inplace edit for stdio; skipping"); + goto retry; + } + } + else { + VALUE write_io = Qnil; + int fr = rb_sysopen(filename, O_RDONLY, 0); - if (ARGF.inplace) { - struct stat st; + if (ARGF.inplace) { + struct stat st; #ifndef NO_SAFE_RENAME - struct stat st2; + struct stat st2; #endif - VALUE str; - int fw; + VALUE str; + int fw; - if (RB_TYPE_P(r_stdout, T_FILE) && r_stdout != orig_stdout) { - rb_io_close(r_stdout); - } - fstat(fr, &st); - str = filename; - if (!NIL_P(ARGF.inplace)) { - VALUE suffix = ARGF.inplace; - str = rb_str_dup(str); - if (NIL_P(rb_str_cat_conv_enc_opts(str, RSTRING_LEN(str), - RSTRING_PTR(suffix), RSTRING_LEN(suffix), - rb_enc_get(suffix), 0, Qnil))) { - rb_str_append(str, suffix); - } + if (RB_TYPE_P(r_stdout, T_FILE) && r_stdout != orig_stdout) { + rb_io_close(r_stdout); + } + fstat(fr, &st); + str = filename; + if (!NIL_P(ARGF.inplace)) { + VALUE suffix = ARGF.inplace; + str = rb_str_dup(str); + if (NIL_P(rb_str_cat_conv_enc_opts(str, RSTRING_LEN(str), + RSTRING_PTR(suffix), RSTRING_LEN(suffix), + rb_enc_get(suffix), 0, Qnil))) { + rb_str_append(str, suffix); + } #ifdef NO_SAFE_RENAME - (void)close(fr); - (void)unlink(RSTRING_PTR(str)); - if (rename(fn, RSTRING_PTR(str)) < 0) { - rb_warn("Can't rename %"PRIsVALUE" to %"PRIsVALUE": %s, skipping file", - filename, str, strerror(errno)); - goto retry; - } - fr = rb_sysopen(str, O_RDONLY, 0); + (void)close(fr); + (void)unlink(RSTRING_PTR(str)); + if (rename(fn, RSTRING_PTR(str)) < 0) { + rb_warn("Can't rename %"PRIsVALUE" to %"PRIsVALUE": %s, skipping file", + filename, str, strerror(errno)); + goto retry; + } + fr = rb_sysopen(str, O_RDONLY, 0); #else - if (rename(fn, RSTRING_PTR(str)) < 0) { - rb_warn("Can't rename %"PRIsVALUE" to %"PRIsVALUE": %s, skipping file", - filename, str, strerror(errno)); - close(fr); - goto retry; - } + if (rename(fn, RSTRING_PTR(str)) < 0) { + rb_warn("Can't rename %"PRIsVALUE" to %"PRIsVALUE": %s, skipping file", + filename, str, strerror(errno)); + close(fr); + goto retry; + } #endif - } - else { + } + else { #ifdef NO_SAFE_RENAME - rb_fatal("Can't do inplace edit without backup"); + rb_fatal("Can't do inplace edit without backup"); #else - if (unlink(fn) < 0) { - rb_warn("Can't remove %"PRIsVALUE": %s, skipping file", - filename, strerror(errno)); - close(fr); - goto retry; - } + if (unlink(fn) < 0) { + rb_warn("Can't remove %"PRIsVALUE": %s, skipping file", + filename, strerror(errno)); + close(fr); + goto retry; + } #endif - } - fw = rb_sysopen(filename, O_WRONLY|O_CREAT|O_TRUNC, 0666); + } + fw = rb_sysopen(filename, O_WRONLY|O_CREAT|O_TRUNC, 0666); #ifndef NO_SAFE_RENAME - fstat(fw, &st2); + fstat(fw, &st2); #ifdef HAVE_FCHMOD - fchmod(fw, st.st_mode); + fchmod(fw, st.st_mode); #else - chmod(fn, st.st_mode); + chmod(fn, st.st_mode); #endif - if (st.st_uid!=st2.st_uid || st.st_gid!=st2.st_gid) { - int err; + if (st.st_uid!=st2.st_uid || st.st_gid!=st2.st_gid) { + int err; #ifdef HAVE_FCHOWN - err = fchown(fw, st.st_uid, st.st_gid); + err = fchown(fw, st.st_uid, st.st_gid); #else - err = chown(fn, st.st_uid, st.st_gid); + err = chown(fn, st.st_uid, st.st_gid); #endif - if (err && getuid() == 0 && st2.st_uid == 0) { - const char *wkfn = RSTRING_PTR(filename); - rb_warn("Can't set owner/group of %"PRIsVALUE" to same as %"PRIsVALUE": %s, skipping file", - filename, str, strerror(errno)); - (void)close(fr); - (void)close(fw); - (void)unlink(wkfn); - goto retry; - } - } + if (err && getuid() == 0 && st2.st_uid == 0) { + const char *wkfn = RSTRING_PTR(filename); + rb_warn("Can't set owner/group of %"PRIsVALUE" to same as %"PRIsVALUE": %s, skipping file", + filename, str, strerror(errno)); + (void)close(fr); + (void)close(fw); + (void)unlink(wkfn); + goto retry; + } + } #endif - write_io = prep_io(fw, FMODE_WRITABLE, rb_cFile, fn); - rb_ractor_stdout_set(write_io); - if (stdout_binmode) rb_io_binmode(rb_stdout); - } - fmode = FMODE_READABLE; - if (!ARGF.binmode) { - fmode |= DEFAULT_TEXTMODE; - } - ARGF.current_file = prep_io(fr, fmode, rb_cFile, fn); - if (!NIL_P(write_io)) { - rb_io_set_write_io(ARGF.current_file, write_io); - } - RB_GC_GUARD(filename); - } - if (ARGF.binmode) rb_io_ascii8bit_binmode(ARGF.current_file); - GetOpenFile(ARGF.current_file, fptr); - if (ARGF.encs.enc) { - fptr->encs = ARGF.encs; + write_io = prep_io(fw, FMODE_WRITABLE, rb_cFile, fn); + rb_ractor_stdout_set(write_io); + if (stdout_binmode) rb_io_binmode(rb_stdout); + } + fmode = FMODE_READABLE; + if (!ARGF.binmode) { + fmode |= DEFAULT_TEXTMODE; + } + ARGF.current_file = prep_io(fr, fmode, rb_cFile, fn); + if (!NIL_P(write_io)) { + rb_io_set_write_io(ARGF.current_file, write_io); + } + RB_GC_GUARD(filename); + } + if (ARGF.binmode) rb_io_ascii8bit_binmode(ARGF.current_file); + GetOpenFile(ARGF.current_file, fptr); + if (ARGF.encs.enc) { + fptr->encs = ARGF.encs; clear_codeconv(fptr); - } - else { - fptr->encs.ecflags &= ~ECONV_NEWLINE_DECORATOR_MASK; - if (!ARGF.binmode) { - fptr->encs.ecflags |= ECONV_DEFAULT_NEWLINE_DECORATOR; + } + else { + fptr->encs.ecflags &= ~ECONV_NEWLINE_DECORATOR_MASK; + if (!ARGF.binmode) { + fptr->encs.ecflags |= ECONV_DEFAULT_NEWLINE_DECORATOR; #ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE - fptr->encs.ecflags |= TEXTMODE_NEWLINE_DECORATOR_ON_WRITE; + fptr->encs.ecflags |= TEXTMODE_NEWLINE_DECORATOR_ON_WRITE; #endif - } - } - ARGF.next_p = 0; - } - else { - ARGF.next_p = 1; - return FALSE; - } + } + } + ARGF.next_p = 0; + } + else { + ARGF.next_p = 1; + return FALSE; + } } else if (ARGF.next_p == -1) { - ARGF.current_file = rb_stdin; - ARGF.filename = rb_str_new2("-"); - if (ARGF.inplace) { - rb_warn("Can't do inplace edit for stdio"); - rb_ractor_stdout_set(orig_stdout); - } + ARGF.current_file = rb_stdin; + ARGF.filename = rb_str_new2("-"); + if (ARGF.inplace) { + rb_warn("Can't do inplace edit for stdio"); + rb_ractor_stdout_set(orig_stdout); + } } if (ARGF.init_p == -1) ARGF.init_p = 1; return TRUE; @@ -9829,24 +9829,24 @@ argf_getline(int argc, VALUE *argv, VALUE argf) retry: if (!next_argv()) return Qnil; if (ARGF_GENERIC_INPUT_P()) { - line = forward_current(idGets, argc, argv); + line = forward_current(idGets, argc, argv); } else { - if (argc == 0 && rb_rs == rb_default_rs) { - line = rb_io_gets(ARGF.current_file); - } - else { - line = rb_io_getline(argc, argv, ARGF.current_file); - } - if (NIL_P(line) && ARGF.next_p != -1) { - argf_close(argf); - ARGF.next_p = 1; - goto retry; - } + if (argc == 0 && rb_rs == rb_default_rs) { + line = rb_io_gets(ARGF.current_file); + } + else { + line = rb_io_getline(argc, argv, ARGF.current_file); + } + if (NIL_P(line) && ARGF.next_p != -1) { + argf_close(argf); + ARGF.next_p = 1; + goto retry; + } } if (!NIL_P(line)) { - ARGF.lineno = ++lineno; - ARGF.last_lineno = ARGF.lineno; + ARGF.lineno = ++lineno; + ARGF.last_lineno = ARGF.lineno; } return line; } @@ -9911,7 +9911,7 @@ static VALUE rb_f_gets(int argc, VALUE *argv, VALUE recv) { if (recv == argf) { - return argf_gets(argc, argv, argf); + return argf_gets(argc, argv, argf); } return forward(argf, idGets, argc, argv); } @@ -9951,21 +9951,21 @@ rb_gets(void) VALUE line; if (rb_rs != rb_default_rs) { - return rb_f_gets(0, 0, argf); + return rb_f_gets(0, 0, argf); } retry: if (!next_argv()) return Qnil; line = rb_io_gets(ARGF.current_file); if (NIL_P(line) && ARGF.next_p != -1) { - rb_io_close(ARGF.current_file); - ARGF.next_p = 1; - goto retry; + rb_io_close(ARGF.current_file); + ARGF.next_p = 1; + goto retry; } rb_lastline_set(line); if (!NIL_P(line)) { - ARGF.lineno++; - ARGF.last_lineno = ARGF.lineno; + ARGF.lineno++; + ARGF.last_lineno = ARGF.lineno; } return line; @@ -9992,7 +9992,7 @@ static VALUE rb_f_readline(int argc, VALUE *argv, VALUE recv) { if (recv == argf) { - return argf_readline(argc, argv, argf); + return argf_readline(argc, argv, argf); } return forward(argf, rb_intern("readline"), argc, argv); } @@ -10024,7 +10024,7 @@ argf_readline(int argc, VALUE *argv, VALUE argf) ARGF_FORWARD(argc, argv); line = argf_gets(argc, argv, argf); if (NIL_P(line)) { - rb_eof_error(); + rb_eof_error(); } return line; @@ -10095,7 +10095,7 @@ static VALUE rb_f_readlines(int argc, VALUE *argv, VALUE recv) { if (recv == argf) { - return argf_readlines(argc, argv, argf); + return argf_readlines(argc, argv, argf); } return forward(argf, rb_intern("readlines"), argc, argv); } @@ -10124,17 +10124,17 @@ argf_readlines(int argc, VALUE *argv, VALUE argf) ary = rb_ary_new(); while (next_argv()) { - if (ARGF_GENERIC_INPUT_P()) { - lines = forward_current(rb_intern("readlines"), argc, argv); - } - else { - lines = rb_io_readlines(argc, argv, ARGF.current_file); - argf_close(argf); - } - ARGF.next_p = 1; - rb_ary_concat(ary, lines); - ARGF.lineno = lineno + RARRAY_LEN(ary); - ARGF.last_lineno = ARGF.lineno; + if (ARGF_GENERIC_INPUT_P()) { + lines = forward_current(rb_intern("readlines"), argc, argv); + } + else { + lines = rb_io_readlines(argc, argv, ARGF.current_file); + argf_close(argf); + } + ARGF.next_p = 1; + rb_ary_concat(ary, lines); + ARGF.lineno = lineno + RARRAY_LEN(ary); + ARGF.last_lineno = ARGF.lineno; } ARGF.init_p = 0; return ary; @@ -10199,63 +10199,63 @@ select_internal(VALUE read, VALUE write, VALUE except, struct timeval *tp, rb_fd struct timeval timerec; if (!NIL_P(read)) { - Check_Type(read, T_ARRAY); - for (i=0; ifd, &fds[0]); - if (READ_DATA_PENDING(fptr) || READ_CHAR_PENDING(fptr)) { /* check for buffered data */ - pending++; - rb_fd_set(fptr->fd, &fds[3]); - } - if (max < fptr->fd) max = fptr->fd; - } - if (pending) { /* no blocking if there's buffered data */ - timerec.tv_sec = timerec.tv_usec = 0; - tp = &timerec; - } - rp = &fds[0]; + Check_Type(read, T_ARRAY); + for (i=0; ifd, &fds[0]); + if (READ_DATA_PENDING(fptr) || READ_CHAR_PENDING(fptr)) { /* check for buffered data */ + pending++; + rb_fd_set(fptr->fd, &fds[3]); + } + if (max < fptr->fd) max = fptr->fd; + } + if (pending) { /* no blocking if there's buffered data */ + timerec.tv_sec = timerec.tv_usec = 0; + tp = &timerec; + } + rp = &fds[0]; } else - rp = 0; + rp = 0; if (!NIL_P(write)) { - Check_Type(write, T_ARRAY); - for (i=0; ifd, &fds[1]); - if (max < fptr->fd) max = fptr->fd; - } - wp = &fds[1]; + GetOpenFile(write_io, fptr); + rb_fd_set(fptr->fd, &fds[1]); + if (max < fptr->fd) max = fptr->fd; + } + wp = &fds[1]; } else - wp = 0; + wp = 0; if (!NIL_P(except)) { - Check_Type(except, T_ARRAY); - for (i=0; ifd, &fds[2]); - if (max < fptr->fd) max = fptr->fd; + GetOpenFile(io, fptr); + rb_fd_set(fptr->fd, &fds[2]); + if (max < fptr->fd) max = fptr->fd; if (io != write_io) { GetOpenFile(write_io, fptr); rb_fd_set(fptr->fd, &fds[2]); if (max < fptr->fd) max = fptr->fd; } - } - ep = &fds[2]; + } + ep = &fds[2]; } else { - ep = 0; + ep = 0; } max++; n = rb_thread_fd_select(max, rp, wp, ep, tp); if (n < 0) { - rb_sys_fail(0); + rb_sys_fail(0); } if (!pending && n == 0) return Qnil; /* returns nil on timeout */ @@ -10265,48 +10265,48 @@ select_internal(VALUE read, VALUE write, VALUE except, struct timeval *tp, rb_fd rb_ary_push(res, ep?rb_ary_new():rb_ary_new2(0)); if (rp) { - list = RARRAY_AREF(res, 0); - for (i=0; i< RARRAY_LEN(read); i++) { - VALUE obj = rb_ary_entry(read, i); - VALUE io = rb_io_get_io(obj); - GetOpenFile(io, fptr); - if (rb_fd_isset(fptr->fd, &fds[0]) || - rb_fd_isset(fptr->fd, &fds[3])) { - rb_ary_push(list, obj); - } - } + list = RARRAY_AREF(res, 0); + for (i=0; i< RARRAY_LEN(read); i++) { + VALUE obj = rb_ary_entry(read, i); + VALUE io = rb_io_get_io(obj); + GetOpenFile(io, fptr); + if (rb_fd_isset(fptr->fd, &fds[0]) || + rb_fd_isset(fptr->fd, &fds[3])) { + rb_ary_push(list, obj); + } + } } if (wp) { - list = RARRAY_AREF(res, 1); - for (i=0; i< RARRAY_LEN(write); i++) { - VALUE obj = rb_ary_entry(write, i); - VALUE io = rb_io_get_io(obj); - VALUE write_io = GetWriteIO(io); - GetOpenFile(write_io, fptr); - if (rb_fd_isset(fptr->fd, &fds[1])) { - rb_ary_push(list, obj); - } - } + list = RARRAY_AREF(res, 1); + for (i=0; i< RARRAY_LEN(write); i++) { + VALUE obj = rb_ary_entry(write, i); + VALUE io = rb_io_get_io(obj); + VALUE write_io = GetWriteIO(io); + GetOpenFile(write_io, fptr); + if (rb_fd_isset(fptr->fd, &fds[1])) { + rb_ary_push(list, obj); + } + } } if (ep) { - list = RARRAY_AREF(res, 2); - for (i=0; i< RARRAY_LEN(except); i++) { - VALUE obj = rb_ary_entry(except, i); - VALUE io = rb_io_get_io(obj); - VALUE write_io = GetWriteIO(io); - GetOpenFile(io, fptr); - if (rb_fd_isset(fptr->fd, &fds[2])) { - rb_ary_push(list, obj); - } - else if (io != write_io) { - GetOpenFile(write_io, fptr); - if (rb_fd_isset(fptr->fd, &fds[2])) { - rb_ary_push(list, obj); - } - } - } + list = RARRAY_AREF(res, 2); + for (i=0; i< RARRAY_LEN(except); i++) { + VALUE obj = rb_ary_entry(except, i); + VALUE io = rb_io_get_io(obj); + VALUE write_io = GetWriteIO(io); + GetOpenFile(io, fptr); + if (rb_fd_isset(fptr->fd, &fds[2])) { + rb_ary_push(list, obj); + } + else if (io != write_io) { + GetOpenFile(write_io, fptr); + if (rb_fd_isset(fptr->fd, &fds[2])) { + rb_ary_push(list, obj); + } + } + } } return res; /* returns an empty array on interrupt */ @@ -10333,7 +10333,7 @@ select_end(VALUE arg) int i; for (i = 0; i < numberof(p->fdsets); ++i) - rb_fd_term(&p->fdsets[i]); + rb_fd_term(&p->fdsets[i]); return Qnil; } @@ -10360,32 +10360,32 @@ io_advise_sym_to_const(VALUE sym) { #ifdef POSIX_FADV_NORMAL if (sym == sym_normal) - return INT2NUM(POSIX_FADV_NORMAL); + return INT2NUM(POSIX_FADV_NORMAL); #endif #ifdef POSIX_FADV_RANDOM if (sym == sym_random) - return INT2NUM(POSIX_FADV_RANDOM); + return INT2NUM(POSIX_FADV_RANDOM); #endif #ifdef POSIX_FADV_SEQUENTIAL if (sym == sym_sequential) - return INT2NUM(POSIX_FADV_SEQUENTIAL); + return INT2NUM(POSIX_FADV_SEQUENTIAL); #endif #ifdef POSIX_FADV_WILLNEED if (sym == sym_willneed) - return INT2NUM(POSIX_FADV_WILLNEED); + return INT2NUM(POSIX_FADV_WILLNEED); #endif #ifdef POSIX_FADV_DONTNEED if (sym == sym_dontneed) - return INT2NUM(POSIX_FADV_DONTNEED); + return INT2NUM(POSIX_FADV_DONTNEED); #endif #ifdef POSIX_FADV_NOREUSE if (sym == sym_noreuse) - return INT2NUM(POSIX_FADV_NOREUSE); + return INT2NUM(POSIX_FADV_NOREUSE); #endif return Qnil; @@ -10405,7 +10405,7 @@ do_io_advise(rb_io_t *fptr, VALUE advice, off_t offset, off_t len) * silently ignore it. Because IO::advise is only hint. */ if (NIL_P(num_adv)) - return Qnil; + return Qnil; ias.fd = fptr->fd; ias.advice = NUM2INT(num_adv); @@ -10414,14 +10414,14 @@ do_io_advise(rb_io_t *fptr, VALUE advice, off_t offset, off_t len) rv = (int)rb_thread_io_blocking_region(io_advise_internal, &ias, fptr->fd); if (rv && rv != ENOSYS) { - /* posix_fadvise(2) doesn't set errno. On success it returns 0; otherwise - it returns the error code. */ - VALUE message = rb_sprintf("%"PRIsVALUE" " - "(%"PRI_OFFT_PREFIX"d, " - "%"PRI_OFFT_PREFIX"d, " - "%"PRIsVALUE")", - fptr->pathv, offset, len, advice); - rb_syserr_fail_str(rv, message); + /* posix_fadvise(2) doesn't set errno. On success it returns 0; otherwise + it returns the error code. */ + VALUE message = rb_sprintf("%"PRIsVALUE" " + "(%"PRI_OFFT_PREFIX"d, " + "%"PRI_OFFT_PREFIX"d, " + "%"PRIsVALUE")", + fptr->pathv, offset, len, advice); + rb_syserr_fail_str(rv, message); } return Qnil; @@ -10433,15 +10433,15 @@ static void advice_arg_check(VALUE advice) { if (!SYMBOL_P(advice)) - rb_raise(rb_eTypeError, "advice must be a Symbol"); + rb_raise(rb_eTypeError, "advice must be a Symbol"); if (advice != sym_normal && - advice != sym_sequential && - advice != sym_random && - advice != sym_willneed && - advice != sym_dontneed && - advice != sym_noreuse) { - rb_raise(rb_eNotImpError, "Unsupported advice: %+"PRIsVALUE, advice); + advice != sym_sequential && + advice != sym_random && + advice != sym_willneed && + advice != sym_dontneed && + advice != sym_noreuse) { + rb_raise(rb_eNotImpError, "Unsupported advice: %+"PRIsVALUE, advice); } } @@ -10661,15 +10661,15 @@ rb_f_select(int argc, VALUE *argv, VALUE obj) rb_scan_args(argc, argv, "13", &args.read, &args.write, &args.except, &timeout); if (NIL_P(timeout)) { - args.timeout = 0; + args.timeout = 0; } else { - timerec = rb_time_interval(timeout); - args.timeout = &timerec; + timerec = rb_time_interval(timeout); + args.timeout = &timerec; } for (i = 0; i < numberof(args.fdsets); ++i) - rb_fd_init(&args.fdsets[i]); + rb_fd_init(&args.fdsets[i]); return rb_ensure(select_call, (VALUE)&args, select_end, (VALUE)&args); } @@ -10721,15 +10721,15 @@ linux_iocparm_len(ioctl_req_t cmd) long len; if ((cmd & 0xFFFF0000) == 0) { - /* legacy and unstructured ioctl number. */ - return DEFAULT_IOCTL_NARG_LEN; + /* legacy and unstructured ioctl number. */ + return DEFAULT_IOCTL_NARG_LEN; } len = _IOC_SIZE(cmd); /* paranoia check for silly drivers which don't keep ioctl convention */ if (len < DEFAULT_IOCTL_NARG_LEN) - len = DEFAULT_IOCTL_NARG_LEN; + len = DEFAULT_IOCTL_NARG_LEN; return len; } @@ -10775,113 +10775,113 @@ fcntl_narg_len(ioctl_req_t cmd) switch (cmd) { #ifdef F_DUPFD case F_DUPFD: - len = sizeof(fcntl_arg_t); - break; + len = sizeof(fcntl_arg_t); + break; #endif #ifdef F_DUP2FD /* bsd specific */ case F_DUP2FD: - len = sizeof(int); - break; + len = sizeof(int); + break; #endif #ifdef F_DUPFD_CLOEXEC /* linux specific */ case F_DUPFD_CLOEXEC: - len = sizeof(fcntl_arg_t); - break; + len = sizeof(fcntl_arg_t); + break; #endif #ifdef F_GETFD case F_GETFD: - len = 1; - break; + len = 1; + break; #endif #ifdef F_SETFD case F_SETFD: - len = sizeof(fcntl_arg_t); - break; + len = sizeof(fcntl_arg_t); + break; #endif #ifdef F_GETFL case F_GETFL: - len = 1; - break; + len = 1; + break; #endif #ifdef F_SETFL case F_SETFL: - len = sizeof(fcntl_arg_t); - break; + len = sizeof(fcntl_arg_t); + break; #endif #ifdef F_GETOWN case F_GETOWN: - len = 1; - break; + len = 1; + break; #endif #ifdef F_SETOWN case F_SETOWN: - len = sizeof(fcntl_arg_t); - break; + len = sizeof(fcntl_arg_t); + break; #endif #ifdef F_GETOWN_EX /* linux specific */ case F_GETOWN_EX: - len = sizeof(struct f_owner_ex); - break; + len = sizeof(struct f_owner_ex); + break; #endif #ifdef F_SETOWN_EX /* linux specific */ case F_SETOWN_EX: - len = sizeof(struct f_owner_ex); - break; + len = sizeof(struct f_owner_ex); + break; #endif #ifdef F_GETLK case F_GETLK: - len = sizeof(struct flock); - break; + len = sizeof(struct flock); + break; #endif #ifdef F_SETLK case F_SETLK: - len = sizeof(struct flock); - break; + len = sizeof(struct flock); + break; #endif #ifdef F_SETLKW case F_SETLKW: - len = sizeof(struct flock); - break; + len = sizeof(struct flock); + break; #endif #ifdef F_READAHEAD /* bsd specific */ case F_READAHEAD: - len = sizeof(int); - break; + len = sizeof(int); + break; #endif #ifdef F_RDAHEAD /* Darwin specific */ case F_RDAHEAD: - len = sizeof(int); - break; + len = sizeof(int); + break; #endif #ifdef F_GETSIG /* linux specific */ case F_GETSIG: - len = 1; - break; + len = 1; + break; #endif #ifdef F_SETSIG /* linux specific */ case F_SETSIG: - len = sizeof(fcntl_arg_t); - break; + len = sizeof(fcntl_arg_t); + break; #endif #ifdef F_GETLEASE /* linux specific */ case F_GETLEASE: - len = 1; - break; + len = 1; + break; #endif #ifdef F_SETLEASE /* linux specific */ case F_SETLEASE: - len = sizeof(fcntl_arg_t); - break; + len = sizeof(fcntl_arg_t); + break; #endif #ifdef F_NOTIFY /* linux specific */ case F_NOTIFY: - len = sizeof(fcntl_arg_t); - break; + len = sizeof(fcntl_arg_t); + break; #endif default: - len = 256; - break; + len = 256; + break; } return len; @@ -10903,40 +10903,40 @@ setup_narg(ioctl_req_t cmd, VALUE *argp, long (*narg_len)(ioctl_req_t)) VALUE arg = *argp; if (!RTEST(arg)) { - narg = 0; + narg = 0; } else if (FIXNUM_P(arg)) { - narg = FIX2LONG(arg); + narg = FIX2LONG(arg); } else if (arg == Qtrue) { - narg = 1; + narg = 1; } else { - VALUE tmp = rb_check_string_type(arg); + VALUE tmp = rb_check_string_type(arg); - if (NIL_P(tmp)) { - narg = NUM2LONG(arg); - } - else { - char *ptr; - long len, slen; + if (NIL_P(tmp)) { + narg = NUM2LONG(arg); + } + else { + char *ptr; + long len, slen; - *argp = arg = tmp; - len = narg_len(cmd); - rb_str_modify(arg); + *argp = arg = tmp; + len = narg_len(cmd); + rb_str_modify(arg); - slen = RSTRING_LEN(arg); - /* expand for data + sentinel. */ - if (slen < len+1) { - rb_str_resize(arg, len+1); - MEMZERO(RSTRING_PTR(arg)+slen, char, len-slen); - slen = len+1; - } - /* a little sanity check here */ - ptr = RSTRING_PTR(arg); - ptr[slen - 1] = NARG_SENTINEL; - narg = (long)(SIGNED_VALUE)ptr; - } + slen = RSTRING_LEN(arg); + /* expand for data + sentinel. */ + if (slen < len+1) { + rb_str_resize(arg, len+1); + MEMZERO(RSTRING_PTR(arg)+slen, char, len-slen); + slen = len+1; + } + /* a little sanity check here */ + ptr = RSTRING_PTR(arg); + ptr[slen - 1] = NARG_SENTINEL; + narg = (long)(SIGNED_VALUE)ptr; + } } return narg; @@ -10947,12 +10947,12 @@ finish_narg(int retval, VALUE arg, const rb_io_t *fptr) { if (retval < 0) rb_sys_fail_path(fptr->pathv); if (RB_TYPE_P(arg, T_STRING)) { - char *ptr; - long slen; - RSTRING_GETMEM(arg, ptr, slen); - if (ptr[slen-1] != NARG_SENTINEL) - rb_raise(rb_eArgError, "return value overflowed string"); - ptr[slen-1] = '\0'; + char *ptr; + long slen; + RSTRING_GETMEM(arg, ptr, slen); + if (ptr[slen-1] != NARG_SENTINEL) + rb_raise(rb_eArgError, "return value overflowed string"); + ptr[slen-1] = '\0'; } return INT2NUM(retval); @@ -11017,7 +11017,7 @@ nogvl_fcntl(void *ptr) #if defined(F_DUPFD) if (arg->cmd == F_DUPFD) - return (VALUE)rb_cloexec_fcntl_dupfd(arg->fd, (int)arg->narg); + return (VALUE)rb_cloexec_fcntl_dupfd(arg->fd, (int)arg->narg); #endif return (VALUE)fcntl(arg->fd, arg->cmd, arg->narg); } @@ -11034,15 +11034,15 @@ do_fcntl(int fd, int cmd, long narg) retval = (int)rb_thread_io_blocking_region(nogvl_fcntl, &arg, fd); if (retval != -1) { - switch (cmd) { + switch (cmd) { #if defined(F_DUPFD) - case F_DUPFD: + case F_DUPFD: #endif #if defined(F_DUPFD_CLOEXEC) - case F_DUPFD_CLOEXEC: + case F_DUPFD_CLOEXEC: #endif - rb_update_max_fd(retval); - } + rb_update_max_fd(retval); + } } return retval; @@ -11160,52 +11160,52 @@ rb_f_syscall(int argc, VALUE *argv, VALUE _) } if (argc == 0) - rb_raise(rb_eArgError, "too few arguments for syscall"); + rb_raise(rb_eArgError, "too few arguments for syscall"); if (argc > numberof(arg)) - rb_raise(rb_eArgError, "too many arguments for syscall"); + rb_raise(rb_eArgError, "too many arguments for syscall"); num = NUM2SYSCALLID(argv[0]); ++argv; for (i = argc - 1; i--; ) { - VALUE v = rb_check_string_type(argv[i]); + VALUE v = rb_check_string_type(argv[i]); - if (!NIL_P(v)) { - SafeStringValue(v); - rb_str_modify(v); - arg[i] = (VALUE)StringValueCStr(v); - } - else { - arg[i] = (VALUE)NUM2LONG(argv[i]); - } + if (!NIL_P(v)) { + SafeStringValue(v); + rb_str_modify(v); + arg[i] = (VALUE)StringValueCStr(v); + } + else { + arg[i] = (VALUE)NUM2LONG(argv[i]); + } } switch (argc) { case 1: - retval = SYSCALL(num); - break; + retval = SYSCALL(num); + break; case 2: - retval = SYSCALL(num, arg[0]); - break; + retval = SYSCALL(num, arg[0]); + break; case 3: - retval = SYSCALL(num, arg[0],arg[1]); - break; + retval = SYSCALL(num, arg[0],arg[1]); + break; case 4: - retval = SYSCALL(num, arg[0],arg[1],arg[2]); - break; + retval = SYSCALL(num, arg[0],arg[1],arg[2]); + break; case 5: - retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3]); - break; + retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3]); + break; case 6: - retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4]); - break; + retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4]); + break; case 7: - retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4],arg[5]); - break; + retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4],arg[5]); + break; case 8: - retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6]); - break; + retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6]); + break; } if (retval == -1) - rb_sys_fail(0); + rb_sys_fail(0); return RETVAL2NUM(retval); #undef SYSCALL #undef NUM2SYSCALLID @@ -11237,51 +11237,51 @@ io_encoding_set(rb_io_t *fptr, VALUE v1, VALUE v2, VALUE opt) VALUE ecopts, tmp; if (!NIL_P(v2)) { - enc2 = find_encoding(v1); - tmp = rb_check_string_type(v2); - if (!NIL_P(tmp)) { - if (RSTRING_LEN(tmp) == 1 && RSTRING_PTR(tmp)[0] == '-') { - /* Special case - "-" => no transcoding */ - enc = enc2; - enc2 = NULL; - } - else - enc = find_encoding(v2); - if (enc == enc2) { - /* Special case - "-" => no transcoding */ - enc2 = NULL; - } - } - else { - enc = find_encoding(v2); - if (enc == enc2) { - /* Special case - "-" => no transcoding */ - enc2 = NULL; - } - } - SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags); - ecflags = rb_econv_prepare_options(opt, &ecopts, ecflags); + enc2 = find_encoding(v1); + tmp = rb_check_string_type(v2); + if (!NIL_P(tmp)) { + if (RSTRING_LEN(tmp) == 1 && RSTRING_PTR(tmp)[0] == '-') { + /* Special case - "-" => no transcoding */ + enc = enc2; + enc2 = NULL; + } + else + enc = find_encoding(v2); + if (enc == enc2) { + /* Special case - "-" => no transcoding */ + enc2 = NULL; + } + } + else { + enc = find_encoding(v2); + if (enc == enc2) { + /* Special case - "-" => no transcoding */ + enc2 = NULL; + } + } + SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags); + ecflags = rb_econv_prepare_options(opt, &ecopts, ecflags); } else { - if (NIL_P(v1)) { - /* Set to default encodings */ - rb_io_ext_int_to_encs(NULL, NULL, &enc, &enc2, 0); - SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags); + if (NIL_P(v1)) { + /* Set to default encodings */ + rb_io_ext_int_to_encs(NULL, NULL, &enc, &enc2, 0); + SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags); ecopts = Qnil; - } - else { - tmp = rb_check_string_type(v1); - if (!NIL_P(tmp) && rb_enc_asciicompat(enc = rb_enc_get(tmp))) { + } + else { + tmp = rb_check_string_type(v1); + if (!NIL_P(tmp) && rb_enc_asciicompat(enc = rb_enc_get(tmp))) { parse_mode_enc(RSTRING_PTR(tmp), enc, &enc, &enc2, NULL); - SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags); + SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags); ecflags = rb_econv_prepare_options(opt, &ecopts, ecflags); - } - else { - rb_io_ext_int_to_encs(find_encoding(v1), NULL, &enc, &enc2, 0); - SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags); + } + else { + rb_io_ext_int_to_encs(find_encoding(v1), NULL, &enc, &enc2, 0); + SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags); ecopts = Qnil; - } - } + } + } } validate_enc_binmode(&fptr->mode, ecflags, enc, enc2); fptr->encs.enc = enc; @@ -11413,9 +11413,9 @@ rb_io_s_pipe(int argc, VALUE *argv, VALUE klass) args[2] = INT2FIX(O_RDONLY); r = rb_protect(io_new_instance, (VALUE)args, &state); if (state) { - close(pipes[0]); - close(pipes[1]); - rb_jump_tag(state); + close(pipes[0]); + close(pipes[1]); + rb_jump_tag(state); } GetOpenFile(r, fptr); @@ -11425,18 +11425,18 @@ rb_io_s_pipe(int argc, VALUE *argv, VALUE klass) ies_args.opt = opt; rb_protect(io_encoding_set_v, (VALUE)&ies_args, &state); if (state) { - close(pipes[1]); + close(pipes[1]); io_close(r); - rb_jump_tag(state); + rb_jump_tag(state); } args[1] = INT2NUM(pipes[1]); args[2] = INT2FIX(O_WRONLY); w = rb_protect(io_new_instance, (VALUE)args, &state); if (state) { - close(pipes[1]); - if (!NIL_P(r)) rb_io_close(r); - rb_jump_tag(state); + close(pipes[1]); + if (!NIL_P(r)) rb_io_close(r); + rb_jump_tag(state); } GetOpenFile(w, fptr2); rb_io_synchronized(fptr2); @@ -11450,30 +11450,30 @@ rb_io_s_pipe(int argc, VALUE *argv, VALUE klass) #if DEFAULT_TEXTMODE if ((fptr->mode & FMODE_TEXTMODE) && (fmode & FMODE_BINMODE)) { - fptr->mode &= ~FMODE_TEXTMODE; - setmode(fptr->fd, O_BINARY); + fptr->mode &= ~FMODE_TEXTMODE; + setmode(fptr->fd, O_BINARY); } #if RUBY_CRLF_ENVIRONMENT if (fptr->encs.ecflags & ECONV_DEFAULT_NEWLINE_DECORATOR) { - fptr->encs.ecflags |= ECONV_UNIVERSAL_NEWLINE_DECORATOR; + fptr->encs.ecflags |= ECONV_UNIVERSAL_NEWLINE_DECORATOR; } #endif #endif fptr->mode |= fmode; #if DEFAULT_TEXTMODE if ((fptr2->mode & FMODE_TEXTMODE) && (fmode & FMODE_BINMODE)) { - fptr2->mode &= ~FMODE_TEXTMODE; - setmode(fptr2->fd, O_BINARY); + fptr2->mode &= ~FMODE_TEXTMODE; + setmode(fptr2->fd, O_BINARY); } #endif fptr2->mode |= fmode; ret = rb_assoc_new(r, w); if (rb_block_given_p()) { - VALUE rw[2]; - rw[0] = r; - rw[1] = w; - return rb_ensure(rb_yield, ret, pipe_pair_close, (VALUE)rw); + VALUE rw[2]; + rw[0] = r; + rw[1] = w; + return rb_ensure(rb_yield, ret, pipe_pair_close, (VALUE)rw); } return ret; } @@ -11497,15 +11497,15 @@ open_key_args(VALUE klass, int argc, VALUE *argv, VALUE opt, struct foreach_arg arg->argc = argc; arg->argv = argv; if (NIL_P(opt)) { - vmode = INT2NUM(O_RDONLY); - vperm = INT2FIX(0666); + vmode = INT2NUM(O_RDONLY); + vperm = INT2FIX(0666); } else if (!NIL_P(v = rb_hash_aref(opt, sym_open_args))) { - int n; + int n; - v = rb_to_array_type(v); - n = RARRAY_LENINT(v); - rb_check_arity(n, 0, 3); /* rb_io_open */ + v = rb_to_array_type(v); + n = RARRAY_LENINT(v); + rb_check_arity(n, 0, 3); /* rb_io_open */ rb_scan_args_kw(RB_SCAN_ARGS_LAST_HASH_KEYWORDS, n, RARRAY_CONST_PTR(v), "02:", &vmode, &vperm, &opt); } arg->io = rb_io_open(klass, path, vmode, vperm, opt); @@ -11518,8 +11518,8 @@ io_s_foreach(VALUE v) VALUE str; while (!NIL_P(str = rb_io_getline_1(arg->rs, arg->limit, arg->chomp, arg->io))) { - rb_lastline_set(str); - rb_yield(str); + rb_lastline_set(str); + rb_yield(str); } rb_lastline_set(Qnil); return Qnil; @@ -11812,17 +11812,17 @@ rb_io_s_read(int argc, VALUE *argv, VALUE io) open_key_args(io, argc, argv, opt, &arg); if (NIL_P(arg.io)) return Qnil; if (!NIL_P(offset)) { - struct seek_arg sarg; - int state = 0; - sarg.io = arg.io; - sarg.offset = offset; - sarg.mode = SEEK_SET; - rb_protect(seek_before_access, (VALUE)&sarg, &state); - if (state) { - rb_io_close(arg.io); - rb_jump_tag(state); - } - if (arg.argc == 2) arg.argc = 1; + struct seek_arg sarg; + int state = 0; + sarg.io = arg.io; + sarg.offset = offset; + sarg.mode = SEEK_SET; + rb_protect(seek_before_access, (VALUE)&sarg, &state); + if (state) { + rb_io_close(arg.io); + rb_jump_tag(state); + } + if (arg.argc == 2) arg.argc = 1; } return rb_ensure(io_s_read, (VALUE)&arg, rb_io_close, arg.io); } @@ -11847,10 +11847,10 @@ rb_io_s_binread(int argc, VALUE *argv, VALUE io) VALUE offset; struct foreach_arg arg; enum { - fmode = FMODE_READABLE|FMODE_BINMODE, - oflags = O_RDONLY + fmode = FMODE_READABLE|FMODE_BINMODE, + oflags = O_RDONLY #ifdef O_BINARY - |O_BINARY + |O_BINARY #endif }; convconfig_t convconfig = {NULL, NULL, 0, Qnil}; @@ -11863,16 +11863,16 @@ rb_io_s_binread(int argc, VALUE *argv, VALUE io) arg.argv = argv+1; arg.argc = (argc > 1) ? 1 : 0; if (!NIL_P(offset)) { - struct seek_arg sarg; - int state = 0; - sarg.io = arg.io; - sarg.offset = offset; - sarg.mode = SEEK_SET; - rb_protect(seek_before_access, (VALUE)&sarg, &state); - if (state) { - rb_io_close(arg.io); - rb_jump_tag(state); - } + struct seek_arg sarg; + int state = 0; + sarg.io = arg.io; + sarg.offset = offset; + sarg.mode = SEEK_SET; + rb_protect(seek_before_access, (VALUE)&sarg, &state); + if (state) { + rb_io_close(arg.io); + rb_jump_tag(state); + } } return rb_ensure(io_s_read, (VALUE)&arg, rb_io_close, arg.io); } @@ -12062,13 +12062,13 @@ maygvl_copy_stream_continue_p(int has_gvl, struct copy_stream_struct *stp) #if defined(ERESTART) case ERESTART: #endif - if (rb_thread_interrupted(stp->th)) { + if (rb_thread_interrupted(stp->th)) { if (has_gvl) rb_thread_execute_interrupts(stp->th); else rb_thread_call_with_gvl(exec_interrupts, (void *)stp->th); } - return TRUE; + return TRUE; } return FALSE; } @@ -12181,7 +12181,7 @@ nogvl_copy_stream_wait_write(struct copy_stream_struct *stp) int ret; do { - ret = nogvl_wait_for(stp->th, stp->dst_fptr, RB_WAITFD_OUT); + ret = nogvl_wait_for(stp->th, stp->dst_fptr, RB_WAITFD_OUT); } while (ret < 0 && maygvl_copy_stream_continue_p(0, stp)); if (ret < 0) { @@ -12217,16 +12217,16 @@ nogvl_copy_file_range(struct copy_stream_struct *stp) src_size = stp->src_stat.st_size; src_offset = stp->src_offset; if (src_offset >= (off_t)0) { - src_offset_ptr = &src_offset; + src_offset_ptr = &src_offset; } else { - src_offset_ptr = NULL; /* if src_offset_ptr is NULL, then bytes are read from in_fd starting from the file offset */ + src_offset_ptr = NULL; /* if src_offset_ptr is NULL, then bytes are read from in_fd starting from the file offset */ } copy_length = stp->copy_length; if (copy_length < (off_t)0) { if (src_offset < (off_t)0) { - off_t current_offset; + off_t current_offset; errno = 0; current_offset = lseek(stp->src_fptr->fd, 0, SEEK_CUR); if (current_offset < (off_t)0 && errno) { @@ -12235,10 +12235,10 @@ nogvl_copy_file_range(struct copy_stream_struct *stp) return (int)current_offset; } copy_length = src_size - current_offset; - } - else { + } + else { copy_length = src_size - src_offset; - } + } } retry_copy_file_range: @@ -12257,39 +12257,39 @@ nogvl_copy_file_range(struct copy_stream_struct *stp) } } if (ss < 0) { - if (maygvl_copy_stream_continue_p(0, stp)) { + if (maygvl_copy_stream_continue_p(0, stp)) { goto retry_copy_file_range; - } + } switch (errno) { - case EINVAL: - case EPERM: /* copy_file_range(2) doesn't exist (may happen in - docker container) */ + case EINVAL: + case EPERM: /* copy_file_range(2) doesn't exist (may happen in + docker container) */ #ifdef ENOSYS - case ENOSYS: + case ENOSYS: #endif #ifdef EXDEV - case EXDEV: /* in_fd and out_fd are not on the same filesystem */ + case EXDEV: /* in_fd and out_fd are not on the same filesystem */ #endif return 0; - case EAGAIN: + case EAGAIN: #if EWOULDBLOCK != EAGAIN - case EWOULDBLOCK: + case EWOULDBLOCK: #endif { int ret = nogvl_copy_stream_wait_write(stp); if (ret < 0) return ret; } goto retry_copy_file_range; - case EBADF: - { - int e = errno; - int flags = fcntl(stp->dst_fptr->fd, F_GETFL); + case EBADF: + { + int e = errno; + int flags = fcntl(stp->dst_fptr->fd, F_GETFL); - if (flags != -1 && flags & O_APPEND) { - return 0; - } - errno = e; - } + if (flags != -1 && flags & O_APPEND) { + return 0; + } + errno = e; + } } stp->syserr = "copy_file_range"; stp->error_no = errno; @@ -12413,10 +12413,10 @@ simple_sendfile(int out_fd, int in_fd, off_t *offset, off_t count) # endif if (r != 0 && sbytes == 0) return r; if (offset) { - *offset += sbytes; + *offset += sbytes; } else { - lseek(in_fd, sbytes, SEEK_CUR); + lseek(in_fd, sbytes, SEEK_CUR); } return (ssize_t)sbytes; } @@ -12441,7 +12441,7 @@ nogvl_copy_stream_sendfile(struct copy_stream_struct *stp) src_size = stp->src_stat.st_size; #ifndef __linux__ if ((stp->dst_stat.st_mode & S_IFMT) != S_IFSOCK) - return 0; + return 0; #endif src_offset = stp->src_offset; @@ -12485,22 +12485,22 @@ nogvl_copy_stream_sendfile(struct copy_stream_struct *stp) } } if (ss < 0) { - if (maygvl_copy_stream_continue_p(0, stp)) - goto retry_sendfile; + if (maygvl_copy_stream_continue_p(0, stp)) + goto retry_sendfile; switch (errno) { - case EINVAL: + case EINVAL: #ifdef ENOSYS - case ENOSYS: + case ENOSYS: #endif #ifdef EOPNOTSUP - /* some RedHat kernels may return EOPNOTSUP on an NFS mount. - see also: [Feature #16965] */ - case EOPNOTSUP: + /* some RedHat kernels may return EOPNOTSUP on an NFS mount. + see also: [Feature #16965] */ + case EOPNOTSUP: #endif return 0; - case EAGAIN: + case EAGAIN: #if EWOULDBLOCK != EAGAIN - case EWOULDBLOCK: + case EWOULDBLOCK: #endif { int ret; @@ -12557,12 +12557,12 @@ maygvl_copy_stream_read(int has_gvl, struct copy_stream_struct *stp, char *buf, return 0; } if (ss < 0) { - if (maygvl_copy_stream_continue_p(has_gvl, stp)) - goto retry_read; + if (maygvl_copy_stream_continue_p(has_gvl, stp)) + goto retry_read; switch (errno) { - case EAGAIN: + case EAGAIN: #if EWOULDBLOCK != EAGAIN - case EWOULDBLOCK: + case EWOULDBLOCK: #endif { int ret = maygvl_copy_stream_wait_read(has_gvl, stp); @@ -12570,7 +12570,7 @@ maygvl_copy_stream_read(int has_gvl, struct copy_stream_struct *stp, char *buf, } goto retry_read; #ifdef ENOSYS - case ENOSYS: + case ENOSYS: stp->notimp = "pread"; return ss; #endif @@ -12626,7 +12626,7 @@ nogvl_copy_stream_read_write(struct copy_stream_struct *stp) if (use_pread && stp->close_src) { off_t r; - errno = 0; + errno = 0; r = lseek(stp->src_fptr->fd, src_offset, SEEK_SET); if (r < (off_t)0 && errno) { stp->syserr = "lseek"; @@ -12675,7 +12675,7 @@ nogvl_copy_stream_func(void *arg) #ifdef USE_COPY_FILE_RANGE ret = nogvl_copy_file_range(stp); if (ret != 0) - goto finish; /* error or success */ + goto finish; /* error or success */ #endif #ifdef HAVE_FCOPYFILE @@ -12710,9 +12710,9 @@ copy_stream_fallback_body(VALUE arg) ID read_method = id_readpartial; if (!stp->src_fptr) { - if (!rb_respond_to(stp->src, read_method)) { - read_method = id_read; - } + if (!rb_respond_to(stp->src, read_method)) { + read_method = id_read; + } } while (1) { @@ -12722,10 +12722,10 @@ copy_stream_fallback_body(VALUE arg) l = buflen; } else { - if (rest == 0) { - rb_str_resize(buf, 0); - break; - } + if (rest == 0) { + rb_str_resize(buf, 0); + break; + } l = buflen < rest ? buflen : (long)rest; } if (!stp->src_fptr) { @@ -12750,9 +12750,9 @@ copy_stream_fallback_body(VALUE arg) numwrote = NUM2LONG(n); stp->total += numwrote; rest -= numwrote; - if (read_method == id_read && RSTRING_LEN(buf) == 0) { - break; - } + if (read_method == id_read && RSTRING_LEN(buf) == 0) { + break; + } } return Qnil; @@ -12762,7 +12762,7 @@ static VALUE copy_stream_fallback(struct copy_stream_struct *stp) { if (!stp->src_fptr && stp->src_offset >= (off_t)0) { - rb_raise(rb_eArgError, "cannot specify src_offset for non-IO"); + rb_raise(rb_eArgError, "cannot specify src_offset for non-IO"); } rb_rescue2(copy_stream_fallback_body, (VALUE)stp, (VALUE (*) (VALUE, VALUE))0, (VALUE)0, @@ -12777,37 +12777,37 @@ copy_stream_body(VALUE arg) VALUE src_io = stp->src, dst_io = stp->dst; const int common_oflags = 0 #ifdef O_NOCTTY - | O_NOCTTY + | O_NOCTTY #endif - ; + ; stp->th = rb_thread_current(); stp->total = 0; if (src_io == argf || - !(RB_TYPE_P(src_io, T_FILE) || - RB_TYPE_P(src_io, T_STRING) || - rb_respond_to(src_io, rb_intern("to_path")))) { + !(RB_TYPE_P(src_io, T_FILE) || + RB_TYPE_P(src_io, T_STRING) || + rb_respond_to(src_io, rb_intern("to_path")))) { stp->src_fptr = NULL; } else { int stat_ret; - VALUE tmp_io = rb_io_check_io(src_io); - if (!NIL_P(tmp_io)) { - src_io = tmp_io; - } - else if (!RB_TYPE_P(src_io, T_FILE)) { - VALUE args[2]; - FilePathValue(src_io); - args[0] = src_io; - args[1] = INT2NUM(O_RDONLY|common_oflags); - src_io = rb_class_new_instance(2, args, rb_cFile); - stp->src = src_io; - stp->close_src = 1; - } - RB_IO_POINTER(src_io, stp->src_fptr); - rb_io_check_byte_readable(stp->src_fptr); + VALUE tmp_io = rb_io_check_io(src_io); + if (!NIL_P(tmp_io)) { + src_io = tmp_io; + } + else if (!RB_TYPE_P(src_io, T_FILE)) { + VALUE args[2]; + FilePathValue(src_io); + args[0] = src_io; + args[1] = INT2NUM(O_RDONLY|common_oflags); + src_io = rb_class_new_instance(2, args, rb_cFile); + stp->src = src_io; + stp->close_src = 1; + } + RB_IO_POINTER(src_io, stp->src_fptr); + rb_io_check_byte_readable(stp->src_fptr); stat_ret = fstat(stp->src_fptr->fd, &stp->src_stat); if (stat_ret < 0) { @@ -12818,33 +12818,33 @@ copy_stream_body(VALUE arg) } if (dst_io == argf || - !(RB_TYPE_P(dst_io, T_FILE) || - RB_TYPE_P(dst_io, T_STRING) || - rb_respond_to(dst_io, rb_intern("to_path")))) { - stp->dst_fptr = NULL; + !(RB_TYPE_P(dst_io, T_FILE) || + RB_TYPE_P(dst_io, T_STRING) || + rb_respond_to(dst_io, rb_intern("to_path")))) { + stp->dst_fptr = NULL; } else { int stat_ret; VALUE tmp_io = rb_io_check_io(dst_io); - if (!NIL_P(tmp_io)) { - dst_io = GetWriteIO(tmp_io); - } - else if (!RB_TYPE_P(dst_io, T_FILE)) { - VALUE args[3]; - FilePathValue(dst_io); - args[0] = dst_io; - args[1] = INT2NUM(O_WRONLY|O_CREAT|O_TRUNC|common_oflags); - args[2] = INT2FIX(0666); - dst_io = rb_class_new_instance(3, args, rb_cFile); - stp->dst = dst_io; - stp->close_dst = 1; - } - else { - dst_io = GetWriteIO(dst_io); - stp->dst = dst_io; - } - RB_IO_POINTER(dst_io, stp->dst_fptr); - rb_io_check_writable(stp->dst_fptr); + if (!NIL_P(tmp_io)) { + dst_io = GetWriteIO(tmp_io); + } + else if (!RB_TYPE_P(dst_io, T_FILE)) { + VALUE args[3]; + FilePathValue(dst_io); + args[0] = dst_io; + args[1] = INT2NUM(O_WRONLY|O_CREAT|O_TRUNC|common_oflags); + args[2] = INT2FIX(0666); + dst_io = rb_class_new_instance(3, args, rb_cFile); + stp->dst = dst_io; + stp->close_dst = 1; + } + else { + dst_io = GetWriteIO(dst_io); + stp->dst = dst_io; + } + RB_IO_POINTER(dst_io, stp->dst_fptr); + rb_io_check_writable(stp->dst_fptr); stat_ret = fstat(stp->dst_fptr->fd, &stp->dst_stat); if (stat_ret < 0) { @@ -12856,10 +12856,10 @@ copy_stream_body(VALUE arg) #ifdef O_BINARY if (stp->src_fptr) - SET_BINARY_MODE_WITH_SEEK_CUR(stp->src_fptr); + SET_BINARY_MODE_WITH_SEEK_CUR(stp->src_fptr); #endif if (stp->dst_fptr) - io_ascii8bit_binmode(stp->dst_fptr); + io_ascii8bit_binmode(stp->dst_fptr); if (stp->src_offset < (off_t)0 && stp->src_fptr && stp->src_fptr->rbuf.len) { size_t len = stp->src_fptr->rbuf.len; @@ -12875,7 +12875,7 @@ copy_stream_body(VALUE arg) rb_sys_fail_on_write(stp->dst_fptr); } else /* others such as StringIO */ - rb_io_write(dst_io, str); + rb_io_write(dst_io, str); rb_str_resize(str, 0); stp->total += len; if (stp->copy_length >= (off_t)0) @@ -12883,7 +12883,7 @@ copy_stream_body(VALUE arg) } if (stp->dst_fptr && io_fflush(stp->dst_fptr) < 0) { - rb_raise(rb_eIOError, "flush failed"); + rb_raise(rb_eIOError, "flush failed"); } if (stp->copy_length == 0) @@ -12918,7 +12918,7 @@ copy_stream_finalize(VALUE arg) rb_syserr_fail(stp->error_no, stp->syserr); } if (stp->notimp) { - rb_raise(rb_eNotImpError, "%s() not implemented", stp->notimp); + rb_raise(rb_eNotImpError, "%s() not implemented", stp->notimp); } return Qnil; } @@ -13022,12 +13022,12 @@ rb_io_external_encoding(VALUE io) rb_io_t *fptr = RFILE(rb_io_taint_check(io))->fptr; if (fptr->encs.enc2) { - return rb_enc_from_encoding(fptr->encs.enc2); + return rb_enc_from_encoding(fptr->encs.enc2); } if (fptr->mode & FMODE_WRITABLE) { - if (fptr->encs.enc) - return rb_enc_from_encoding(fptr->encs.enc); - return Qnil; + if (fptr->encs.enc) + return rb_enc_from_encoding(fptr->encs.enc); + return Qnil; } return rb_enc_from_encoding(io_read_encoding(fptr)); } @@ -13141,7 +13141,7 @@ static VALUE argf_external_encoding(VALUE argf) { if (!RTEST(ARGF.current_file)) { - return rb_enc_from_encoding(rb_default_external_encoding()); + return rb_enc_from_encoding(rb_default_external_encoding()); } return rb_io_external_encoding(rb_io_check_io(ARGF.current_file)); } @@ -13163,7 +13163,7 @@ static VALUE argf_internal_encoding(VALUE argf) { if (!RTEST(ARGF.current_file)) { - return rb_enc_from_encoding(rb_default_external_encoding()); + return rb_enc_from_encoding(rb_default_external_encoding()); } return rb_io_internal_encoding(rb_io_check_io(ARGF.current_file)); } @@ -13205,7 +13205,7 @@ argf_set_encoding(int argc, VALUE *argv, VALUE argf) rb_io_t *fptr; if (!next_argv()) { - rb_raise(rb_eArgError, "no stream to set encoding"); + rb_raise(rb_eArgError, "no stream to set encoding"); } rb_io_set_encoding(argc, argv, ARGF.current_file); GetOpenFile(ARGF.current_file, fptr); @@ -13229,7 +13229,7 @@ static VALUE argf_tell(VALUE argf) { if (!next_argv()) { - rb_raise(rb_eArgError, "no stream to tell"); + rb_raise(rb_eArgError, "no stream to tell"); } ARGF_FORWARD(0, 0); return rb_io_tell(ARGF.current_file); @@ -13246,7 +13246,7 @@ static VALUE argf_seek_m(int argc, VALUE *argv, VALUE argf) { if (!next_argv()) { - rb_raise(rb_eArgError, "no stream to seek"); + rb_raise(rb_eArgError, "no stream to seek"); } ARGF_FORWARD(argc, argv); return rb_io_seek_m(argc, argv, ARGF.current_file); @@ -13267,7 +13267,7 @@ static VALUE argf_set_pos(VALUE argf, VALUE offset) { if (!next_argv()) { - rb_raise(rb_eArgError, "no stream to set position"); + rb_raise(rb_eArgError, "no stream to set position"); } ARGF_FORWARD(1, &offset); return rb_io_set_pos(ARGF.current_file, offset); @@ -13292,13 +13292,13 @@ argf_rewind(VALUE argf) int old_lineno; if (!next_argv()) { - rb_raise(rb_eArgError, "no stream to rewind"); + rb_raise(rb_eArgError, "no stream to rewind"); } ARGF_FORWARD(0, 0); old_lineno = RFILE(ARGF.current_file)->fptr->lineno; ret = rb_io_rewind(ARGF.current_file); if (!global_argf_p(argf)) { - ARGF.last_lineno = ARGF.lineno -= old_lineno; + ARGF.last_lineno = ARGF.lineno -= old_lineno; } return ret; } @@ -13317,7 +13317,7 @@ static VALUE argf_fileno(VALUE argf) { if (!next_argv()) { - rb_raise(rb_eArgError, "no stream"); + rb_raise(rb_eArgError, "no stream"); } ARGF_FORWARD(0, 0); return rb_io_fileno(ARGF.current_file); @@ -13366,12 +13366,12 @@ argf_eof(VALUE argf) { next_argv(); if (RTEST(ARGF.current_file)) { - if (ARGF.init_p == 0) return Qtrue; - next_argv(); - ARGF_FORWARD(0, 0); - if (rb_io_eof(ARGF.current_file)) { - return Qtrue; - } + if (ARGF.init_p == 0) return Qtrue; + next_argv(); + ARGF_FORWARD(0, 0); + if (rb_io_eof(ARGF.current_file)) { + return Qtrue; + } } return Qfalse; } @@ -13432,39 +13432,39 @@ argf_read(int argc, VALUE *argv, VALUE argf) rb_scan_args(argc, argv, "02", &length, &str); if (!NIL_P(length)) { - len = NUM2LONG(argv[0]); + len = NUM2LONG(argv[0]); } if (!NIL_P(str)) { - StringValue(str); - rb_str_resize(str,0); - argv[1] = Qnil; + StringValue(str); + rb_str_resize(str,0); + argv[1] = Qnil; } retry: if (!next_argv()) { - return str; + return str; } if (ARGF_GENERIC_INPUT_P()) { - tmp = argf_forward(argc, argv, argf); + tmp = argf_forward(argc, argv, argf); } else { - tmp = io_read(argc, argv, ARGF.current_file); + tmp = io_read(argc, argv, ARGF.current_file); } if (NIL_P(str)) str = tmp; else if (!NIL_P(tmp)) rb_str_append(str, tmp); if (NIL_P(tmp) || NIL_P(length)) { - if (ARGF.next_p != -1) { - argf_close(argf); - ARGF.next_p = 1; - goto retry; - } + if (ARGF.next_p != -1) { + argf_close(argf); + ARGF.next_p = 1; + goto retry; + } } else if (argc >= 1) { - long slen = RSTRING_LEN(str); - if (slen < len) { + long slen = RSTRING_LEN(str); + if (slen < len) { argv[0] = LONG2NUM(len - slen); - goto retry; - } + goto retry; + } } return str; } @@ -13547,18 +13547,18 @@ argf_getpartial(int argc, VALUE *argv, VALUE argf, VALUE opts, int nonblock) no_exception = no_exception_p(opts); if (!next_argv()) { - if (!NIL_P(str)) { - rb_str_resize(str, 0); - } + if (!NIL_P(str)) { + rb_str_resize(str, 0); + } rb_eof_error(); } if (ARGF_GENERIC_INPUT_P()) { VALUE (*const rescue_does_nothing)(VALUE, VALUE) = 0; - struct argf_call_arg arg; - arg.argc = argc; - arg.argv = argv; - arg.argf = argf; - tmp = rb_rescue2(argf_forward_call, (VALUE)&arg, + struct argf_call_arg arg; + arg.argc = argc; + arg.argv = argv; + arg.argf = argf; + tmp = rb_rescue2(argf_forward_call, (VALUE)&arg, rescue_does_nothing, Qnil, rb_eEOFError, (VALUE)0); } else { @@ -13572,7 +13572,7 @@ argf_getpartial(int argc, VALUE *argv, VALUE argf, VALUE opts, int nonblock) ARGF.next_p = 1; if (RARRAY_LEN(ARGF.argv) == 0) { return io_nonblock_eof(no_exception); - } + } if (NIL_P(str)) str = rb_str_new(NULL, 0); return str; @@ -13611,15 +13611,15 @@ argf_getc(VALUE argf) retry: if (!next_argv()) return Qnil; if (ARGF_GENERIC_INPUT_P()) { - ch = forward_current(rb_intern("getc"), 0, 0); + ch = forward_current(rb_intern("getc"), 0, 0); } else { - ch = rb_io_getc(ARGF.current_file); + ch = rb_io_getc(ARGF.current_file); } if (NIL_P(ch) && ARGF.next_p != -1) { - argf_close(argf); - ARGF.next_p = 1; - goto retry; + argf_close(argf); + ARGF.next_p = 1; + goto retry; } return ch; @@ -13651,15 +13651,15 @@ argf_getbyte(VALUE argf) retry: if (!next_argv()) return Qnil; if (!RB_TYPE_P(ARGF.current_file, T_FILE)) { - ch = forward_current(rb_intern("getbyte"), 0, 0); + ch = forward_current(rb_intern("getbyte"), 0, 0); } else { - ch = rb_io_getbyte(ARGF.current_file); + ch = rb_io_getbyte(ARGF.current_file); } if (NIL_P(ch) && ARGF.next_p != -1) { - argf_close(argf); - ARGF.next_p = 1; - goto retry; + argf_close(argf); + ARGF.next_p = 1; + goto retry; } return ch; @@ -13691,15 +13691,15 @@ argf_readchar(VALUE argf) retry: if (!next_argv()) rb_eof_error(); if (!RB_TYPE_P(ARGF.current_file, T_FILE)) { - ch = forward_current(rb_intern("getc"), 0, 0); + ch = forward_current(rb_intern("getc"), 0, 0); } else { - ch = rb_io_getc(ARGF.current_file); + ch = rb_io_getc(ARGF.current_file); } if (NIL_P(ch) && ARGF.next_p != -1) { - argf_close(argf); - ARGF.next_p = 1; - goto retry; + argf_close(argf); + ARGF.next_p = 1; + goto retry; } return ch; @@ -13731,7 +13731,7 @@ argf_readbyte(VALUE argf) NEXT_ARGF_FORWARD(0, 0); c = argf_getbyte(argf); if (NIL_P(c)) { - rb_eof_error(); + rb_eof_error(); } return c; } @@ -13744,7 +13744,7 @@ argf_block_call_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, argf)) const VALUE current = ARGF.current_file; rb_yield_values2(argc, argv); if (ARGF.init_p == -1 || current != ARGF.current_file) { - rb_iter_break_value(Qundef); + rb_iter_break_value(Qundef); } return Qnil; } @@ -13764,7 +13764,7 @@ static VALUE argf_block_call_line_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, argf)) { if (!global_argf_p(argf)) { - ARGF.last_lineno = ++ARGF.lineno; + ARGF.last_lineno = ++ARGF.lineno; } return argf_block_call_i(i, argf, argc, argv, blockarg); } @@ -13821,7 +13821,7 @@ argf_each_line(int argc, VALUE *argv, VALUE argf) { RETURN_ENUMERATOR(argf, argc, argv); FOREACH_ARGF() { - argf_block_call_line(rb_intern("each_line"), argc, argv, argf); + argf_block_call_line(rb_intern("each_line"), argc, argv, argf); } return argf; } @@ -13852,7 +13852,7 @@ argf_each_byte(VALUE argf) { RETURN_ENUMERATOR(argf, 0, 0); FOREACH_ARGF() { - argf_block_call(rb_intern("each_byte"), 0, 0, argf); + argf_block_call(rb_intern("each_byte"), 0, 0, argf); } return argf; } @@ -13878,7 +13878,7 @@ argf_each_char(VALUE argf) { RETURN_ENUMERATOR(argf, 0, 0); FOREACH_ARGF() { - argf_block_call(rb_intern("each_char"), 0, 0, argf); + argf_block_call(rb_intern("each_char"), 0, 0, argf); } return argf; } @@ -13904,7 +13904,7 @@ argf_each_codepoint(VALUE argf) { RETURN_ENUMERATOR(argf, 0, 0); FOREACH_ARGF() { - argf_block_call(rb_intern("each_codepoint"), 0, 0, argf); + argf_block_call(rb_intern("each_codepoint"), 0, 0, argf); } return argf; } @@ -14027,8 +14027,8 @@ static VALUE argf_skip(VALUE argf) { if (ARGF.init_p && ARGF.next_p == 0) { - argf_close(argf); - ARGF.next_p = 1; + argf_close(argf); + ARGF.next_p = 1; } return argf; } @@ -14056,7 +14056,7 @@ argf_close_m(VALUE argf) next_argv(); argf_close(argf); if (ARGF.next_p != -1) { - ARGF.next_p = 1; + ARGF.next_p = 1; } ARGF.lineno = 0; return argf; @@ -14135,13 +14135,13 @@ static VALUE argf_inplace_mode_set(VALUE argf, VALUE val) { if (!RTEST(val)) { - ARGF.inplace = Qfalse; + ARGF.inplace = Qfalse; } else if (StringValueCStr(val), !RSTRING_LEN(val)) { - ARGF.inplace = Qnil; + ARGF.inplace = Qnil; } else { - ARGF.inplace = rb_str_new_frozen(val); + ARGF.inplace = rb_str_new_frozen(val); } return argf; } @@ -14201,7 +14201,7 @@ static VALUE argf_write_io(VALUE argf) { if (!RTEST(ARGF.current_file)) { - rb_raise(rb_eIOError, "not opened for writing"); + rb_raise(rb_eIOError, "not opened for writing"); } return GetWriteIO(ARGF.current_file); } @@ -14231,41 +14231,41 @@ rb_readwrite_syserr_fail(enum rb_io_wait_readwrite waiting, int n, const char *m arg = mesg ? rb_str_new2(mesg) : Qnil; switch (waiting) { case RB_IO_WAIT_WRITABLE: - switch (n) { - case EAGAIN: + switch (n) { + case EAGAIN: c = rb_eEAGAINWaitWritable; - break; + break; #if EAGAIN != EWOULDBLOCK - case EWOULDBLOCK: + case EWOULDBLOCK: c = rb_eEWOULDBLOCKWaitWritable; - break; + break; #endif - case EINPROGRESS: + case EINPROGRESS: c = rb_eEINPROGRESSWaitWritable; - break; - default: + break; + default: rb_mod_syserr_fail_str(rb_mWaitWritable, n, arg); - } + } break; case RB_IO_WAIT_READABLE: - switch (n) { - case EAGAIN: + switch (n) { + case EAGAIN: c = rb_eEAGAINWaitReadable; - break; + break; #if EAGAIN != EWOULDBLOCK - case EWOULDBLOCK: + case EWOULDBLOCK: c = rb_eEWOULDBLOCKWaitReadable; - break; + break; #endif - case EINPROGRESS: + case EINPROGRESS: c = rb_eEINPROGRESSWaitReadable; - break; - default: + break; + default: rb_mod_syserr_fail_str(rb_mWaitReadable, n, arg); - } + } break; default: - rb_bug("invalid read/write type passed to rb_readwrite_sys_fail: %d", waiting); + rb_bug("invalid read/write type passed to rb_readwrite_sys_fail: %d", waiting); } rb_exc_raise(rb_class_new_instance(1, &arg, c)); } @@ -14900,11 +14900,11 @@ Init_IO(void) #include static struct __cygwin_perfile pf[] = { - {"", O_RDONLY | O_BINARY}, - {"", O_WRONLY | O_BINARY}, - {"", O_RDWR | O_BINARY}, - {"", O_APPEND | O_BINARY}, - {NULL, 0} + {"", O_RDONLY | O_BINARY}, + {"", O_WRONLY | O_BINARY}, + {"", O_RDWR | O_BINARY}, + {"", O_APPEND | O_BINARY}, + {NULL, 0} }; cygwin_internal(CW_PERFILE, pf); #endif diff --git a/iseq.c b/iseq.c index 0369830bdd..f49312156b 100644 --- a/iseq.c +++ b/iseq.c @@ -60,19 +60,19 @@ static inline VALUE obj_resurrect(VALUE obj) { if (hidden_obj_p(obj)) { - switch (BUILTIN_TYPE(obj)) { - case T_STRING: - obj = rb_str_resurrect(obj); - break; - case T_ARRAY: - obj = rb_ary_resurrect(obj); - break; + switch (BUILTIN_TYPE(obj)) { + case T_STRING: + obj = rb_str_resurrect(obj); + break; + case T_ARRAY: + obj = rb_ary_resurrect(obj); + break; case T_HASH: obj = rb_hash_resurrect(obj); break; default: - break; - } + break; + } } return obj; } @@ -93,12 +93,12 @@ static void compile_data_free(struct iseq_compile_data *compile_data) { if (compile_data) { - free_arena(compile_data->node.storage_head); - free_arena(compile_data->insn.storage_head); - if (compile_data->ivar_cache_table) { - rb_id_table_free(compile_data->ivar_cache_table); - } - ruby_xfree(compile_data); + free_arena(compile_data->node.storage_head); + free_arena(compile_data->insn.storage_head); + if (compile_data->ivar_cache_table) { + rb_id_table_free(compile_data->ivar_cache_table); + } + ruby_xfree(compile_data); } } @@ -174,36 +174,36 @@ rb_iseq_free(const rb_iseq_t *iseq) if (iseq && ISEQ_BODY(iseq)) { iseq_clear_ic_references(iseq); struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq); - mjit_free_iseq(iseq); /* Notify MJIT */ + mjit_free_iseq(iseq); /* Notify MJIT */ #if YJIT_BUILD rb_yjit_iseq_free(body->yjit_payload); #endif - ruby_xfree((void *)body->iseq_encoded); - ruby_xfree((void *)body->insns_info.body); - if (body->insns_info.positions) ruby_xfree((void *)body->insns_info.positions); + ruby_xfree((void *)body->iseq_encoded); + ruby_xfree((void *)body->insns_info.body); + if (body->insns_info.positions) ruby_xfree((void *)body->insns_info.positions); #if VM_INSN_INFO_TABLE_IMPL == 2 - if (body->insns_info.succ_index_table) ruby_xfree(body->insns_info.succ_index_table); + if (body->insns_info.succ_index_table) ruby_xfree(body->insns_info.succ_index_table); #endif if (LIKELY(body->local_table != rb_iseq_shared_exc_local_tbl)) ruby_xfree((void *)body->local_table); - ruby_xfree((void *)body->is_entries); + ruby_xfree((void *)body->is_entries); if (body->call_data) { ruby_xfree(body->call_data); - } - ruby_xfree((void *)body->catch_table); - ruby_xfree((void *)body->param.opt_table); + } + ruby_xfree((void *)body->catch_table); + ruby_xfree((void *)body->param.opt_table); if (ISEQ_MBITS_BUFLEN(body->iseq_size) > 1 && body->mark_bits.list) { ruby_xfree((void *)body->mark_bits.list); } - if (body->param.keyword != NULL) { - ruby_xfree((void *)body->param.keyword->default_values); - ruby_xfree((void *)body->param.keyword); - } - compile_data_free(ISEQ_COMPILE_DATA(iseq)); + if (body->param.keyword != NULL) { + ruby_xfree((void *)body->param.keyword->default_values); + ruby_xfree((void *)body->param.keyword); + } + compile_data_free(ISEQ_COMPILE_DATA(iseq)); if (body->outer_variables) rb_id_table_free(body->outer_variables); - ruby_xfree(body); + ruby_xfree(body); } if (iseq && ISEQ_EXECUTABLE_P(iseq) && iseq->aux.exec.local_hooks) { @@ -497,31 +497,31 @@ rb_iseq_mark(const rb_iseq_t *iseq) } } - if (body->param.flags.has_kw && ISEQ_COMPILE_DATA(iseq) == NULL) { - const struct rb_iseq_param_keyword *const keyword = body->param.keyword; - int i, j; + if (body->param.flags.has_kw && ISEQ_COMPILE_DATA(iseq) == NULL) { + const struct rb_iseq_param_keyword *const keyword = body->param.keyword; + int i, j; - i = keyword->required_num; + i = keyword->required_num; - for (j = 0; i < keyword->num; i++, j++) { - VALUE obj = keyword->default_values[j]; - if (!SPECIAL_CONST_P(obj)) { + for (j = 0; i < keyword->num; i++, j++) { + VALUE obj = keyword->default_values[j]; + if (!SPECIAL_CONST_P(obj)) { rb_gc_mark_movable(obj); - } - } - } + } + } + } - if (body->catch_table) { - const struct iseq_catch_table *table = body->catch_table; - unsigned int i; - for (i = 0; i < table->size; i++) { - const struct iseq_catch_table_entry *entry; - entry = UNALIGNED_MEMBER_PTR(table, entries[i]); - if (entry->iseq) { + if (body->catch_table) { + const struct iseq_catch_table *table = body->catch_table; + unsigned int i; + for (i = 0; i < table->size; i++) { + const struct iseq_catch_table_entry *entry; + entry = UNALIGNED_MEMBER_PTR(table, entries[i]); + if (entry->iseq) { rb_gc_mark_movable((VALUE)entry->iseq); - } - } - } + } + } + } #if USE_MJIT mjit_mark_cc_entries(body); @@ -532,10 +532,10 @@ rb_iseq_mark(const rb_iseq_t *iseq) } if (FL_TEST_RAW((VALUE)iseq, ISEQ_NOT_LOADED_YET)) { - rb_gc_mark(iseq->aux.loader.obj); + rb_gc_mark(iseq->aux.loader.obj); } else if (FL_TEST_RAW((VALUE)iseq, ISEQ_USE_COMPILE_DATA)) { - const struct iseq_compile_data *const compile_data = ISEQ_COMPILE_DATA(iseq); + const struct iseq_compile_data *const compile_data = ISEQ_COMPILE_DATA(iseq); rb_iseq_mark_insn_storage(compile_data->insn.storage_head); @@ -600,15 +600,15 @@ rb_iseq_memsize(const rb_iseq_t *iseq) compile_data = ISEQ_COMPILE_DATA(iseq); if (compile_data) { - struct iseq_compile_data_storage *cur; + struct iseq_compile_data_storage *cur; - size += sizeof(struct iseq_compile_data); + size += sizeof(struct iseq_compile_data); - cur = compile_data->node.storage_head; - while (cur) { - size += cur->size + offsetof(struct iseq_compile_data_storage, buff); - cur = cur->next; - } + cur = compile_data->node.storage_head; + while (cur) { + size += cur->size + offsetof(struct iseq_compile_data_storage, buff); + cur = cur->next; + } } return size; @@ -638,13 +638,13 @@ rb_iseq_pathobj_new(VALUE path, VALUE realpath) VM_ASSERT(NIL_P(realpath) || RB_TYPE_P(realpath, T_STRING)); if (path == realpath || - (!NIL_P(realpath) && rb_str_cmp(path, realpath) == 0)) { - pathobj = rb_fstring(path); + (!NIL_P(realpath) && rb_str_cmp(path, realpath) == 0)) { + pathobj = rb_fstring(path); } else { - if (!NIL_P(realpath)) realpath = rb_fstring(realpath); - pathobj = rb_ary_new_from_args(2, rb_fstring(path), realpath); - rb_obj_freeze(pathobj); + if (!NIL_P(realpath)) realpath = rb_fstring(realpath); + pathobj = rb_ary_new_from_args(2, rb_fstring(path), realpath); + rb_obj_freeze(pathobj); } return pathobj; } @@ -653,7 +653,7 @@ void rb_iseq_pathobj_set(const rb_iseq_t *iseq, VALUE path, VALUE realpath) { RB_OBJ_WRITE(iseq, &ISEQ_BODY(iseq)->location.pathobj, - rb_iseq_pathobj_new(path, realpath)); + rb_iseq_pathobj_new(path, realpath)); } static rb_iseq_location_t * @@ -667,13 +667,13 @@ iseq_location_setup(rb_iseq_t *iseq, VALUE name, VALUE path, VALUE realpath, VAL loc->first_lineno = first_lineno; if (code_location) { loc->node_id = node_id; - loc->code_location = *code_location; + loc->code_location = *code_location; } else { - loc->code_location.beg_pos.lineno = 0; - loc->code_location.beg_pos.column = 0; - loc->code_location.end_pos.lineno = -1; - loc->code_location.end_pos.column = -1; + loc->code_location.beg_pos.lineno = 0; + loc->code_location.beg_pos.column = 0; + loc->code_location.end_pos.lineno = -1; + loc->code_location.end_pos.column = -1; } return loc; @@ -687,21 +687,21 @@ set_relation(rb_iseq_t *iseq, const rb_iseq_t *piseq) /* set class nest stack */ if (type == ISEQ_TYPE_TOP) { - body->local_iseq = iseq; + body->local_iseq = iseq; } else if (type == ISEQ_TYPE_METHOD || type == ISEQ_TYPE_CLASS) { - body->local_iseq = iseq; + body->local_iseq = iseq; } else if (piseq) { body->local_iseq = ISEQ_BODY(piseq)->local_iseq; } if (piseq) { - body->parent_iseq = piseq; + body->parent_iseq = piseq; } if (type == ISEQ_TYPE_MAIN) { - body->local_iseq = iseq; + body->local_iseq = iseq; } } @@ -723,7 +723,7 @@ new_arena(void) static VALUE prepare_iseq_build(rb_iseq_t *iseq, VALUE name, VALUE path, VALUE realpath, VALUE first_lineno, const rb_code_location_t *code_location, const int node_id, - const rb_iseq_t *parent, int isolated_depth, enum iseq_type type, + const rb_iseq_t *parent, int isolated_depth, enum iseq_type type, VALUE script_lines, const rb_compile_option_t *option) { VALUE coverage = Qfalse; @@ -731,7 +731,7 @@ prepare_iseq_build(rb_iseq_t *iseq, struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq); if (parent && (type == ISEQ_TYPE_MAIN || type == ISEQ_TYPE_TOP)) - err_info = Qfalse; + err_info = Qfalse; body->type = type; set_relation(iseq, parent); @@ -765,11 +765,11 @@ prepare_iseq_build(rb_iseq_t *iseq, if (option->coverage_enabled) { - VALUE coverages = rb_get_coverages(); - if (RTEST(coverages)) { - coverage = rb_hash_lookup(coverages, rb_iseq_path(iseq)); - if (NIL_P(coverage)) coverage = Qfalse; - } + VALUE coverages = rb_get_coverages(); + if (RTEST(coverages)) { + coverage = rb_hash_lookup(coverages, rb_iseq_path(iseq)); + if (NIL_P(coverage)) coverage = Qfalse; + } } ISEQ_COVERAGE_SET(iseq, coverage); if (coverage && ISEQ_BRANCH_COVERAGE(iseq)) @@ -834,10 +834,10 @@ finish_iseq_build(rb_iseq_t *iseq) #endif if (RTEST(err)) { - VALUE path = pathobj_path(body->location.pathobj); - if (err == Qtrue) err = rb_exc_new_cstr(rb_eSyntaxError, "compile error"); - rb_funcallv(err, rb_intern("set_backtrace"), 1, &path); - rb_exc_raise(err); + VALUE path = pathobj_path(body->location.pathobj); + if (err == Qtrue) err = rb_exc_new_cstr(rb_eSyntaxError, "compile error"); + rb_funcallv(err, rb_intern("set_backtrace"), 1, &path); + rb_exc_raise(err); } RB_DEBUG_COUNTER_INC(iseq_num); @@ -900,22 +900,22 @@ static void make_compile_option(rb_compile_option_t *option, VALUE opt) { if (NIL_P(opt)) { - *option = COMPILE_OPTION_DEFAULT; + *option = COMPILE_OPTION_DEFAULT; } else if (opt == Qfalse) { - *option = COMPILE_OPTION_FALSE; + *option = COMPILE_OPTION_FALSE; } else if (opt == Qtrue) { - int i; - for (i = 0; i < (int)(sizeof(rb_compile_option_t) / sizeof(int)); ++i) - ((int *)option)[i] = 1; + int i; + for (i = 0; i < (int)(sizeof(rb_compile_option_t) / sizeof(int)); ++i) + ((int *)option)[i] = 1; } else if (RB_TYPE_P(opt, T_HASH)) { - *option = COMPILE_OPTION_DEFAULT; - set_compile_option_from_hash(option, opt); + *option = COMPILE_OPTION_DEFAULT; + set_compile_option_from_hash(option, opt); } else { - rb_raise(rb_eTypeError, "Compile option must be Hash/true/false/nil"); + rb_raise(rb_eTypeError, "Compile option must be Hash/true/false/nil"); } } @@ -928,17 +928,17 @@ make_compile_option_value(rb_compile_option_t *option) #define SET_COMPILE_OPTION_NUM(o, h, mem) \ rb_hash_aset((h), ID2SYM(rb_intern(#mem)), INT2NUM((o)->mem)) { - SET_COMPILE_OPTION(option, opt, inline_const_cache); - SET_COMPILE_OPTION(option, opt, peephole_optimization); - SET_COMPILE_OPTION(option, opt, tailcall_optimization); - SET_COMPILE_OPTION(option, opt, specialized_instruction); - SET_COMPILE_OPTION(option, opt, operands_unification); - SET_COMPILE_OPTION(option, opt, instructions_unification); - SET_COMPILE_OPTION(option, opt, stack_caching); - SET_COMPILE_OPTION(option, opt, frozen_string_literal); - SET_COMPILE_OPTION(option, opt, debug_frozen_string_literal); - SET_COMPILE_OPTION(option, opt, coverage_enabled); - SET_COMPILE_OPTION_NUM(option, opt, debug_level); + SET_COMPILE_OPTION(option, opt, inline_const_cache); + SET_COMPILE_OPTION(option, opt, peephole_optimization); + SET_COMPILE_OPTION(option, opt, tailcall_optimization); + SET_COMPILE_OPTION(option, opt, specialized_instruction); + SET_COMPILE_OPTION(option, opt, operands_unification); + SET_COMPILE_OPTION(option, opt, instructions_unification); + SET_COMPILE_OPTION(option, opt, stack_caching); + SET_COMPILE_OPTION(option, opt, frozen_string_literal); + SET_COMPILE_OPTION(option, opt, debug_frozen_string_literal); + SET_COMPILE_OPTION(option, opt, coverage_enabled); + SET_COMPILE_OPTION_NUM(option, opt, debug_level); } #undef SET_COMPILE_OPTION #undef SET_COMPILE_OPTION_NUM @@ -947,7 +947,7 @@ make_compile_option_value(rb_compile_option_t *option) rb_iseq_t * rb_iseq_new(const rb_ast_body_t *ast, VALUE name, VALUE path, VALUE realpath, - const rb_iseq_t *parent, enum iseq_type type) + const rb_iseq_t *parent, enum iseq_type type) { return rb_iseq_new_with_opt(ast, name, path, realpath, INT2FIX(0), parent, 0, type, &COMPILE_OPTION_DEFAULT); @@ -987,8 +987,8 @@ rb_iseq_t * rb_iseq_new_main(const rb_ast_body_t *ast, VALUE path, VALUE realpath, const rb_iseq_t *parent, int opt) { return rb_iseq_new_with_opt(ast, rb_fstring_lit("
"), - path, realpath, INT2FIX(0), - parent, 0, ISEQ_TYPE_MAIN, opt ? &COMPILE_OPTION_DEFAULT : &COMPILE_OPTION_FALSE); + path, realpath, INT2FIX(0), + parent, 0, ISEQ_TYPE_MAIN, opt ? &COMPILE_OPTION_DEFAULT : &COMPILE_OPTION_FALSE); } rb_iseq_t * @@ -1002,11 +1002,11 @@ static inline rb_iseq_t * iseq_translate(rb_iseq_t *iseq) { if (rb_respond_to(rb_cISeq, rb_intern("translate"))) { - VALUE v1 = iseqw_new(iseq); - VALUE v2 = rb_funcall(rb_cISeq, rb_intern("translate"), 1, v1); - if (v1 != v2 && CLASS_OF(v2) == rb_cISeq) { - iseq = (rb_iseq_t *)iseqw_check(v2); - } + VALUE v1 = iseqw_new(iseq); + VALUE v2 = rb_funcall(rb_cISeq, rb_intern("translate"), 1, v1); + if (v1 != v2 && CLASS_OF(v2) == rb_cISeq) { + iseq = (rb_iseq_t *)iseqw_check(v2); + } } return iseq; @@ -1014,7 +1014,7 @@ iseq_translate(rb_iseq_t *iseq) rb_iseq_t * rb_iseq_new_with_opt(const rb_ast_body_t *ast, VALUE name, VALUE path, VALUE realpath, - VALUE first_lineno, const rb_iseq_t *parent, int isolated_depth, + VALUE first_lineno, const rb_iseq_t *parent, int isolated_depth, enum iseq_type type, const rb_compile_option_t *option) { const NODE *node = ast ? ast->root : 0; @@ -1073,7 +1073,7 @@ rb_iseq_load_iseq(VALUE fname) VALUE iseqv = rb_check_funcall(rb_cISeq, rb_intern("load_iseq"), 1, &fname); if (!SPECIAL_CONST_P(iseqv) && RBASIC_CLASS(iseqv) == rb_cISeq) { - return iseqw_check(iseqv); + return iseqw_check(iseqv); } return NULL; @@ -1156,17 +1156,17 @@ iseq_load(VALUE data, const rb_iseq_t *parent, VALUE opt) iseq_type = iseq_type_from_sym(type); if (iseq_type == (enum iseq_type)-1) { - rb_raise(rb_eTypeError, "unsupported type: :%"PRIsVALUE, rb_sym2str(type)); + rb_raise(rb_eTypeError, "unsupported type: :%"PRIsVALUE, rb_sym2str(type)); } node_id = rb_hash_aref(misc, ID2SYM(rb_intern("node_id"))); code_location = rb_hash_aref(misc, ID2SYM(rb_intern("code_location"))); if (RB_TYPE_P(code_location, T_ARRAY) && RARRAY_LEN(code_location) == 4) { - tmp_loc.beg_pos.lineno = NUM2INT(rb_ary_entry(code_location, 0)); - tmp_loc.beg_pos.column = NUM2INT(rb_ary_entry(code_location, 1)); - tmp_loc.end_pos.lineno = NUM2INT(rb_ary_entry(code_location, 2)); - tmp_loc.end_pos.column = NUM2INT(rb_ary_entry(code_location, 3)); + tmp_loc.beg_pos.lineno = NUM2INT(rb_ary_entry(code_location, 0)); + tmp_loc.beg_pos.column = NUM2INT(rb_ary_entry(code_location, 1)); + tmp_loc.end_pos.lineno = NUM2INT(rb_ary_entry(code_location, 2)); + tmp_loc.end_pos.column = NUM2INT(rb_ary_entry(code_location, 3)); } make_compile_option(&option, opt); @@ -1218,29 +1218,29 @@ rb_iseq_compile_with_option(VALUE src, VALUE file, VALUE realpath, VALUE line, V ln = NUM2INT(line); StringValueCStr(file); if (RB_TYPE_P(src, T_FILE)) { - parse = rb_parser_compile_file_path; + parse = rb_parser_compile_file_path; } else { - parse = rb_parser_compile_string_path; - StringValue(src); + parse = rb_parser_compile_string_path; + StringValue(src); } { - const VALUE parser = rb_parser_new(); + const VALUE parser = rb_parser_new(); const rb_iseq_t *outer_scope = rb_iseq_new(NULL, name, name, Qnil, 0, ISEQ_TYPE_TOP); VALUE outer_scope_v = (VALUE)outer_scope; rb_parser_set_context(parser, outer_scope, FALSE); RB_GC_GUARD(outer_scope_v); - ast = (*parse)(parser, file, src, ln); + ast = (*parse)(parser, file, src, ln); } if (!ast->body.root) { - rb_ast_dispose(ast); - rb_exc_raise(GET_EC()->errinfo); + rb_ast_dispose(ast); + rb_exc_raise(GET_EC()->errinfo); } else { - iseq = rb_iseq_new_with_opt(&ast->body, name, file, realpath, line, - NULL, 0, ISEQ_TYPE_TOP, &option); - rb_ast_dispose(ast); + iseq = rb_iseq_new_with_opt(&ast->body, name, file, realpath, line, + NULL, 0, ISEQ_TYPE_TOP, &option); + rb_ast_dispose(ast); } return iseq; @@ -1294,10 +1294,10 @@ rb_iseq_method_name(const rb_iseq_t *iseq) struct rb_iseq_constant_body *const body = ISEQ_BODY(ISEQ_BODY(iseq)->local_iseq); if (body->type == ISEQ_TYPE_METHOD) { - return body->location.base_label; + return body->location.base_label; } else { - return Qnil; + return Qnil; } } @@ -1333,10 +1333,10 @@ remove_coverage_i(void *vstart, void *vend, size_t stride, void *data) void *ptr = asan_poisoned_object_p(v); asan_unpoison_object(v, false); - if (rb_obj_is_iseq(v)) { + if (rb_obj_is_iseq(v)) { rb_iseq_t *iseq = (rb_iseq_t *)v; ISEQ_COVERAGE_SET(iseq, Qnil); - } + } asan_poison_object_if(ptr, v); } @@ -1500,16 +1500,16 @@ iseqw_s_compile_file(int argc, VALUE *argv, VALUE self) rb_io_close(f); if (!ast->body.root) { - rb_ast_dispose(ast); - rb_exc_raise(exc); + rb_ast_dispose(ast); + rb_exc_raise(exc); } make_compile_option(&option, opt); ret = iseqw_new(rb_iseq_new_with_opt(&ast->body, rb_fstring_lit("
"), - file, - rb_realpath_internal(Qnil, file, 1), - line, NULL, 0, ISEQ_TYPE_TOP, &option)); + file, + rb_realpath_internal(Qnil, file, 1), + line, NULL, 0, ISEQ_TYPE_TOP, &option)); rb_ast_dispose(ast); return ret; } @@ -1574,11 +1574,11 @@ iseqw_check(VALUE iseqw) rb_iseq_t *iseq = DATA_PTR(iseqw); if (!ISEQ_BODY(iseq)) { - rb_ibf_load_iseq_complete(iseq); + rb_ibf_load_iseq_complete(iseq); } if (!ISEQ_BODY(iseq)->location.label) { - rb_raise(rb_eTypeError, "uninitialized InstructionSequence"); + rb_raise(rb_eTypeError, "uninitialized InstructionSequence"); } return iseq; } @@ -1615,13 +1615,13 @@ iseqw_inspect(VALUE self) VALUE klass = rb_class_name(rb_obj_class(self)); if (!body->location.label) { - return rb_sprintf("#<%"PRIsVALUE": uninitialized>", klass); + return rb_sprintf("#<%"PRIsVALUE": uninitialized>", klass); } else { - return rb_sprintf("<%"PRIsVALUE":%"PRIsVALUE"@%"PRIsVALUE":%d>", - klass, - body->location.label, rb_iseq_path(iseq), - FIX2INT(rb_iseq_first_lineno(iseq))); + return rb_sprintf("<%"PRIsVALUE":%"PRIsVALUE"@%"PRIsVALUE":%d>", + klass, + body->location.label, rb_iseq_path(iseq), + FIX2INT(rb_iseq_first_lineno(iseq))); } } @@ -1848,38 +1848,38 @@ get_insn_info_binary_search(const rb_iseq_t *iseq, size_t pos) const int debug = 0; if (debug) { - printf("size: %"PRIuSIZE"\n", size); - printf("insns_info[%"PRIuSIZE"]: position: %d, line: %d, pos: %"PRIuSIZE"\n", - (size_t)0, positions[0], insns_info[0].line_no, pos); + printf("size: %"PRIuSIZE"\n", size); + printf("insns_info[%"PRIuSIZE"]: position: %d, line: %d, pos: %"PRIuSIZE"\n", + (size_t)0, positions[0], insns_info[0].line_no, pos); } if (size == 0) { - return NULL; + return NULL; } else if (size == 1) { - return &insns_info[0]; + return &insns_info[0]; } else { - size_t l = 1, r = size - 1; - while (l <= r) { - size_t m = l + (r - l) / 2; - if (positions[m] == pos) { - return &insns_info[m]; - } - if (positions[m] < pos) { - l = m + 1; - } - else { - r = m - 1; - } - } - if (l >= size) { - return &insns_info[size-1]; - } - if (positions[l] > pos) { - return &insns_info[l-1]; - } - return &insns_info[l]; + size_t l = 1, r = size - 1; + while (l <= r) { + size_t m = l + (r - l) / 2; + if (positions[m] == pos) { + return &insns_info[m]; + } + if (positions[m] < pos) { + l = m + 1; + } + else { + r = m - 1; + } + } + if (l >= size) { + return &insns_info[size-1]; + } + if (positions[l] > pos) { + return &insns_info[l-1]; + } + return &insns_info[l]; } } @@ -1913,16 +1913,16 @@ get_insn_info_succinct_bitvector(const rb_iseq_t *iseq, size_t pos) } if (size == 0) { - return NULL; + return NULL; } else if (size == 1) { - return &insns_info[0]; + return &insns_info[0]; } else { - int index; - VM_ASSERT(body->insns_info.succ_index_table != NULL); - index = succ_index_lookup(body->insns_info.succ_index_table, (int)pos); - return &insns_info[index-1]; + int index; + VM_ASSERT(body->insns_info.succ_index_table != NULL); + index = succ_index_lookup(body->insns_info.succ_index_table, (int)pos); + return &insns_info[index-1]; } } @@ -1944,29 +1944,29 @@ get_insn_info_linear_search(const rb_iseq_t *iseq, size_t pos) const int debug = 0; if (debug) { - printf("size: %"PRIuSIZE"\n", size); - printf("insns_info[%"PRIuSIZE"]: position: %d, line: %d, pos: %"PRIuSIZE"\n", - i, positions[i], insns_info[i].line_no, pos); + printf("size: %"PRIuSIZE"\n", size); + printf("insns_info[%"PRIuSIZE"]: position: %d, line: %d, pos: %"PRIuSIZE"\n", + i, positions[i], insns_info[i].line_no, pos); } if (size == 0) { - return NULL; + return NULL; } else if (size == 1) { - return &insns_info[0]; + return &insns_info[0]; } else { - for (i=1; i pos) { - return &insns_info[i-1]; - } - } + if (positions[i] == pos) { + return &insns_info[i]; + } + if (positions[i] > pos) { + return &insns_info[i-1]; + } + } } return &insns_info[i-1]; } @@ -1987,9 +1987,9 @@ validate_get_insn_info(const rb_iseq_t *iseq) const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq); size_t i; for (i = 0; i < body->iseq_size; i++) { - if (get_insn_info_linear_search(iseq, i) != get_insn_info(iseq, i)) { - rb_bug("validate_get_insn_info: get_insn_info_linear_search(iseq, %"PRIuSIZE") != get_insn_info(iseq, %"PRIuSIZE")", i, i); - } + if (get_insn_info_linear_search(iseq, i) != get_insn_info(iseq, i)) { + rb_bug("validate_get_insn_info: get_insn_info_linear_search(iseq, %"PRIuSIZE") != get_insn_info(iseq, %"PRIuSIZE")", i, i); + } } } #endif @@ -2000,10 +2000,10 @@ rb_iseq_line_no(const rb_iseq_t *iseq, size_t pos) const struct iseq_insn_info_entry *entry = get_insn_info(iseq, pos); if (entry) { - return entry->line_no; + return entry->line_no; } else { - return 0; + return 0; } } @@ -2014,10 +2014,10 @@ rb_iseq_node_id(const rb_iseq_t *iseq, size_t pos) const struct iseq_insn_info_entry *entry = get_insn_info(iseq, pos); if (entry) { - return entry->node_id; + return entry->node_id; } else { - return 0; + return 0; } } #endif @@ -2027,10 +2027,10 @@ rb_iseq_event_flags(const rb_iseq_t *iseq, size_t pos) { const struct iseq_insn_info_entry *entry = get_insn_info(iseq, pos); if (entry) { - return entry->events; + return entry->events; } else { - return 0; + return 0; } } @@ -2062,13 +2062,13 @@ local_var_name(const rb_iseq_t *diseq, VALUE level, VALUE op) lid = ISEQ_BODY(diseq)->local_table[idx]; name = rb_id2str(lid); if (!name) { - name = rb_str_new_cstr("?"); + name = rb_str_new_cstr("?"); } else if (!rb_str_symname_p(name)) { - name = rb_str_inspect(name); + name = rb_str_inspect(name); } else { - name = rb_str_dup(name); + name = rb_str_dup(name); } rb_str_catf(name, "@%d", idx); return name; @@ -2079,8 +2079,8 @@ VALUE rb_dump_literal(VALUE lit); VALUE rb_insn_operand_intern(const rb_iseq_t *iseq, - VALUE insn, int op_no, VALUE op, - int len, size_t pos, const VALUE *pnop, VALUE child) + VALUE insn, int op_no, VALUE op, + int len, size_t pos, const VALUE *pnop, VALUE child) { const char *types = insn_op_types(insn); char type = types[op_no]; @@ -2088,157 +2088,157 @@ rb_insn_operand_intern(const rb_iseq_t *iseq, switch (type) { case TS_OFFSET: /* LONG */ - ret = rb_sprintf("%"PRIdVALUE, (VALUE)(pos + len + op)); - break; + ret = rb_sprintf("%"PRIdVALUE, (VALUE)(pos + len + op)); + break; case TS_NUM: /* ULONG */ - if (insn == BIN(defined) && op_no == 0) { - enum defined_type deftype = (enum defined_type)op; - switch (deftype) { - case DEFINED_FUNC: - ret = rb_fstring_lit("func"); - break; - case DEFINED_REF: - ret = rb_fstring_lit("ref"); - break; - case DEFINED_CONST_FROM: - ret = rb_fstring_lit("constant-from"); - break; - default: - ret = rb_iseq_defined_string(deftype); - break; - } - if (ret) break; - } - else if (insn == BIN(checktype) && op_no == 0) { - const char *type_str = rb_type_str((enum ruby_value_type)op); - if (type_str) { - ret = rb_str_new_cstr(type_str); break; - } - } - ret = rb_sprintf("%"PRIuVALUE, op); - break; + if (insn == BIN(defined) && op_no == 0) { + enum defined_type deftype = (enum defined_type)op; + switch (deftype) { + case DEFINED_FUNC: + ret = rb_fstring_lit("func"); + break; + case DEFINED_REF: + ret = rb_fstring_lit("ref"); + break; + case DEFINED_CONST_FROM: + ret = rb_fstring_lit("constant-from"); + break; + default: + ret = rb_iseq_defined_string(deftype); + break; + } + if (ret) break; + } + else if (insn == BIN(checktype) && op_no == 0) { + const char *type_str = rb_type_str((enum ruby_value_type)op); + if (type_str) { + ret = rb_str_new_cstr(type_str); break; + } + } + ret = rb_sprintf("%"PRIuVALUE, op); + break; case TS_LINDEX:{ - int level; - if (types[op_no+1] == TS_NUM && pnop) { - ret = local_var_name(iseq, *pnop, op - VM_ENV_DATA_SIZE); - } - else if ((level = rb_insn_unified_local_var_level(insn)) >= 0) { - ret = local_var_name(iseq, (VALUE)level, op - VM_ENV_DATA_SIZE); - } - else { - ret = rb_inspect(INT2FIX(op)); - } - break; + int level; + if (types[op_no+1] == TS_NUM && pnop) { + ret = local_var_name(iseq, *pnop, op - VM_ENV_DATA_SIZE); + } + else if ((level = rb_insn_unified_local_var_level(insn)) >= 0) { + ret = local_var_name(iseq, (VALUE)level, op - VM_ENV_DATA_SIZE); + } + else { + ret = rb_inspect(INT2FIX(op)); + } + break; } case TS_ID: /* ID (symbol) */ - ret = rb_inspect(ID2SYM(op)); - break; + ret = rb_inspect(ID2SYM(op)); + break; case TS_VALUE: /* VALUE */ - op = obj_resurrect(op); - if (insn == BIN(defined) && op_no == 1 && FIXNUM_P(op)) { - /* should be DEFINED_REF */ - int type = NUM2INT(op); - if (type) { - if (type & 1) { - ret = rb_sprintf(":$%c", (type >> 1)); - } - else { - ret = rb_sprintf(":$%d", (type >> 1)); - } - break; - } - } - ret = rb_dump_literal(op); - if (CLASS_OF(op) == rb_cISeq) { - if (child) { - rb_ary_push(child, op); - } - } - break; + op = obj_resurrect(op); + if (insn == BIN(defined) && op_no == 1 && FIXNUM_P(op)) { + /* should be DEFINED_REF */ + int type = NUM2INT(op); + if (type) { + if (type & 1) { + ret = rb_sprintf(":$%c", (type >> 1)); + } + else { + ret = rb_sprintf(":$%d", (type >> 1)); + } + break; + } + } + ret = rb_dump_literal(op); + if (CLASS_OF(op) == rb_cISeq) { + if (child) { + rb_ary_push(child, op); + } + } + break; case TS_ISEQ: /* iseq */ - { - if (op) { - const rb_iseq_t *iseq = rb_iseq_check((rb_iseq_t *)op); + { + if (op) { + const rb_iseq_t *iseq = rb_iseq_check((rb_iseq_t *)op); ret = ISEQ_BODY(iseq)->location.label; - if (child) { - rb_ary_push(child, (VALUE)iseq); - } - } - else { - ret = rb_str_new2("nil"); - } - break; - } + if (child) { + rb_ary_push(child, (VALUE)iseq); + } + } + else { + ret = rb_str_new2("nil"); + } + break; + } case TS_IC: case TS_IVC: case TS_ICVARC: case TS_ISE: ret = rb_sprintf("", (union iseq_inline_storage_entry *)op - ISEQ_BODY(iseq)->is_entries); - break; + break; case TS_CALLDATA: - { + { struct rb_call_data *cd = (struct rb_call_data *)op; const struct rb_callinfo *ci = cd->ci; - VALUE ary = rb_ary_new(); + VALUE ary = rb_ary_new(); ID mid = vm_ci_mid(ci); if (mid) { - rb_ary_push(ary, rb_sprintf("mid:%"PRIsVALUE, rb_id2str(mid))); - } + rb_ary_push(ary, rb_sprintf("mid:%"PRIsVALUE, rb_id2str(mid))); + } - rb_ary_push(ary, rb_sprintf("argc:%d", vm_ci_argc(ci))); + rb_ary_push(ary, rb_sprintf("argc:%d", vm_ci_argc(ci))); if (vm_ci_flag(ci) & VM_CALL_KWARG) { const struct rb_callinfo_kwarg *kw_args = vm_ci_kwarg(ci); VALUE kw_ary = rb_ary_new_from_values(kw_args->keyword_len, kw_args->keywords); rb_ary_push(ary, rb_sprintf("kw:[%"PRIsVALUE"]", rb_ary_join(kw_ary, rb_str_new2(",")))); - } + } if (vm_ci_flag(ci)) { - VALUE flags = rb_ary_new(); + VALUE flags = rb_ary_new(); # define CALL_FLAG(n) if (vm_ci_flag(ci) & VM_CALL_##n) rb_ary_push(flags, rb_str_new2(#n)) - CALL_FLAG(ARGS_SPLAT); - CALL_FLAG(ARGS_BLOCKARG); - CALL_FLAG(FCALL); - CALL_FLAG(VCALL); - CALL_FLAG(ARGS_SIMPLE); - CALL_FLAG(BLOCKISEQ); - CALL_FLAG(TAILCALL); - CALL_FLAG(SUPER); - CALL_FLAG(ZSUPER); - CALL_FLAG(KWARG); - CALL_FLAG(KW_SPLAT); + CALL_FLAG(ARGS_SPLAT); + CALL_FLAG(ARGS_BLOCKARG); + CALL_FLAG(FCALL); + CALL_FLAG(VCALL); + CALL_FLAG(ARGS_SIMPLE); + CALL_FLAG(BLOCKISEQ); + CALL_FLAG(TAILCALL); + CALL_FLAG(SUPER); + CALL_FLAG(ZSUPER); + CALL_FLAG(KWARG); + CALL_FLAG(KW_SPLAT); CALL_FLAG(KW_SPLAT_MUT); - CALL_FLAG(OPT_SEND); /* maybe not reachable */ - rb_ary_push(ary, rb_ary_join(flags, rb_str_new2("|"))); - } + CALL_FLAG(OPT_SEND); /* maybe not reachable */ + rb_ary_push(ary, rb_ary_join(flags, rb_str_new2("|"))); + } ret = rb_sprintf("", rb_ary_join(ary, rb_str_new2(", "))); } - break; + break; case TS_CDHASH: - ret = rb_str_new2(""); - break; + ret = rb_str_new2(""); + break; case TS_FUNCPTR: - { + { #ifdef HAVE_DLADDR - Dl_info info; - if (dladdr((void *)op, &info) && info.dli_sname) { - ret = rb_str_new_cstr(info.dli_sname); - break; - } + Dl_info info; + if (dladdr((void *)op, &info) && info.dli_sname) { + ret = rb_str_new_cstr(info.dli_sname); + break; + } #endif - ret = rb_str_new2(""); - } - break; + ret = rb_str_new2(""); + } + break; case TS_BUILTIN: { @@ -2249,7 +2249,7 @@ rb_insn_operand_intern(const rb_iseq_t *iseq, break; default: - rb_bug("unknown operand type: %c", type); + rb_bug("unknown operand type: %c", type); } return ret; } @@ -2269,7 +2269,7 @@ right_strip(VALUE str) */ int rb_iseq_disasm_insn(VALUE ret, const VALUE *code, size_t pos, - const rb_iseq_t *iseq, VALUE child) + const rb_iseq_t *iseq, VALUE child) { VALUE insn = code[pos]; int len = insn_len(insn); @@ -2280,60 +2280,60 @@ rb_iseq_disasm_insn(VALUE ret, const VALUE *code, size_t pos, insn_name_buff = insn_name(insn); if (1) { - extern const int rb_vm_max_insn_name_size; - rb_str_catf(str, "%04"PRIuSIZE" %-*s ", pos, rb_vm_max_insn_name_size, insn_name_buff); + extern const int rb_vm_max_insn_name_size; + rb_str_catf(str, "%04"PRIuSIZE" %-*s ", pos, rb_vm_max_insn_name_size, insn_name_buff); } else { - rb_str_catf(str, "%04"PRIuSIZE" %-28.*s ", pos, - (int)strcspn(insn_name_buff, "_"), insn_name_buff); + rb_str_catf(str, "%04"PRIuSIZE" %-28.*s ", pos, + (int)strcspn(insn_name_buff, "_"), insn_name_buff); } for (j = 0; types[j]; j++) { - VALUE opstr = rb_insn_operand_intern(iseq, insn, j, code[pos + j + 1], - len, pos, &code[pos + j + 2], - child); - rb_str_concat(str, opstr); + VALUE opstr = rb_insn_operand_intern(iseq, insn, j, code[pos + j + 1], + len, pos, &code[pos + j + 2], + child); + rb_str_concat(str, opstr); - if (types[j + 1]) { - rb_str_cat2(str, ", "); - } + if (types[j + 1]) { + rb_str_cat2(str, ", "); + } } { - unsigned int line_no = rb_iseq_line_no(iseq, pos); - unsigned int prev = pos == 0 ? 0 : rb_iseq_line_no(iseq, pos - 1); - if (line_no && line_no != prev) { - long slen = RSTRING_LEN(str); - slen = (slen > 70) ? 0 : (70 - slen); - str = rb_str_catf(str, "%*s(%4d)", (int)slen, "", line_no); - } + unsigned int line_no = rb_iseq_line_no(iseq, pos); + unsigned int prev = pos == 0 ? 0 : rb_iseq_line_no(iseq, pos - 1); + if (line_no && line_no != prev) { + long slen = RSTRING_LEN(str); + slen = (slen > 70) ? 0 : (70 - slen); + str = rb_str_catf(str, "%*s(%4d)", (int)slen, "", line_no); + } } { - rb_event_flag_t events = rb_iseq_event_flags(iseq, pos); - if (events) { + rb_event_flag_t events = rb_iseq_event_flags(iseq, pos); + if (events) { str = rb_str_catf(str, "[%s%s%s%s%s%s%s%s%s%s%s]", - events & RUBY_EVENT_LINE ? "Li" : "", - events & RUBY_EVENT_CLASS ? "Cl" : "", - events & RUBY_EVENT_END ? "En" : "", - events & RUBY_EVENT_CALL ? "Ca" : "", - events & RUBY_EVENT_RETURN ? "Re" : "", - events & RUBY_EVENT_C_CALL ? "Cc" : "", - events & RUBY_EVENT_C_RETURN ? "Cr" : "", - events & RUBY_EVENT_B_CALL ? "Bc" : "", + events & RUBY_EVENT_LINE ? "Li" : "", + events & RUBY_EVENT_CLASS ? "Cl" : "", + events & RUBY_EVENT_END ? "En" : "", + events & RUBY_EVENT_CALL ? "Ca" : "", + events & RUBY_EVENT_RETURN ? "Re" : "", + events & RUBY_EVENT_C_CALL ? "Cc" : "", + events & RUBY_EVENT_C_RETURN ? "Cr" : "", + events & RUBY_EVENT_B_CALL ? "Bc" : "", events & RUBY_EVENT_B_RETURN ? "Br" : "", events & RUBY_EVENT_COVERAGE_LINE ? "Cli" : "", events & RUBY_EVENT_COVERAGE_BRANCH ? "Cbr" : ""); - } + } } right_strip(str); if (ret) { - rb_str_cat2(str, "\n"); - rb_str_concat(ret, str); + rb_str_cat2(str, "\n"); + rb_str_concat(ret, str); } else { - printf("%.*s\n", (int)RSTRING_LEN(str), RSTRING_PTR(str)); + printf("%.*s\n", (int)RSTRING_LEN(str), RSTRING_PTR(str)); } return len; } @@ -2343,20 +2343,20 @@ catch_type(int type) { switch (type) { case CATCH_TYPE_RESCUE: - return "rescue"; + return "rescue"; case CATCH_TYPE_ENSURE: - return "ensure"; + return "ensure"; case CATCH_TYPE_RETRY: - return "retry"; + return "retry"; case CATCH_TYPE_BREAK: - return "break"; + return "break"; case CATCH_TYPE_REDO: - return "redo"; + return "redo"; case CATCH_TYPE_NEXT: - return "next"; + return "next"; default: - rb_bug("unknown catch type: %d", type); - return 0; + rb_bug("unknown catch type: %d", type); + return 0; } } @@ -2365,17 +2365,17 @@ iseq_inspect(const rb_iseq_t *iseq) { const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq); if (!body->location.label) { - return rb_sprintf("#"); + return rb_sprintf("#"); } else { - const rb_code_location_t *loc = &body->location.code_location; - return rb_sprintf("#", - body->location.label, rb_iseq_path(iseq), - loc->beg_pos.lineno, - loc->beg_pos.lineno, - loc->beg_pos.column, - loc->end_pos.lineno, - loc->end_pos.column); + const rb_code_location_t *loc = &body->location.code_location; + return rb_sprintf("#", + body->location.label, rb_iseq_path(iseq), + loc->beg_pos.lineno, + loc->beg_pos.lineno, + loc->beg_pos.column, + loc->end_pos.lineno, + loc->end_pos.column); } } @@ -2413,111 +2413,111 @@ rb_iseq_disasm_recursive(const rb_iseq_t *iseq, VALUE indent) rb_str_append(str, iseq_inspect(iseq)); rb_str_catf(str, " (catch: %s)", body->catch_except_p ? "TRUE" : "FALSE"); if ((l = RSTRING_LEN(str) - indent_len) < header_minlen) { - rb_str_modify_expand(str, header_minlen - l); - memset(RSTRING_END(str), '=', header_minlen - l); + rb_str_modify_expand(str, header_minlen - l); + memset(RSTRING_END(str), '=', header_minlen - l); } rb_str_cat2(str, "\n"); /* show catch table information */ if (body->catch_table) { - rb_str_cat(str, indent_str, indent_len); - rb_str_cat2(str, "== catch table\n"); + rb_str_cat(str, indent_str, indent_len); + rb_str_cat2(str, "== catch table\n"); } if (body->catch_table) { - rb_str_cat_cstr(indent, "| "); - indent_str = RSTRING_PTR(indent); - for (i = 0; i < body->catch_table->size; i++) { - const struct iseq_catch_table_entry *entry = - UNALIGNED_MEMBER_PTR(body->catch_table, entries[i]); - rb_str_cat(str, indent_str, indent_len); - rb_str_catf(str, - "| catch type: %-6s st: %04d ed: %04d sp: %04d cont: %04d\n", - catch_type((int)entry->type), (int)entry->start, - (int)entry->end, (int)entry->sp, (int)entry->cont); - if (entry->iseq && !(done_iseq && st_is_member(done_iseq, (st_data_t)entry->iseq))) { - rb_str_concat(str, rb_iseq_disasm_recursive(rb_iseq_check(entry->iseq), indent)); - if (!done_iseq) { + rb_str_cat_cstr(indent, "| "); + indent_str = RSTRING_PTR(indent); + for (i = 0; i < body->catch_table->size; i++) { + const struct iseq_catch_table_entry *entry = + UNALIGNED_MEMBER_PTR(body->catch_table, entries[i]); + rb_str_cat(str, indent_str, indent_len); + rb_str_catf(str, + "| catch type: %-6s st: %04d ed: %04d sp: %04d cont: %04d\n", + catch_type((int)entry->type), (int)entry->start, + (int)entry->end, (int)entry->sp, (int)entry->cont); + if (entry->iseq && !(done_iseq && st_is_member(done_iseq, (st_data_t)entry->iseq))) { + rb_str_concat(str, rb_iseq_disasm_recursive(rb_iseq_check(entry->iseq), indent)); + if (!done_iseq) { done_iseq = st_init_numtable(); done_iseq_wrapper = TypedData_Wrap_Struct(0, &tmp_set, done_iseq); } - st_insert(done_iseq, (st_data_t)entry->iseq, (st_data_t)0); - indent_str = RSTRING_PTR(indent); - } - } - rb_str_resize(indent, indent_len); - indent_str = RSTRING_PTR(indent); + st_insert(done_iseq, (st_data_t)entry->iseq, (st_data_t)0); + indent_str = RSTRING_PTR(indent); + } + } + rb_str_resize(indent, indent_len); + indent_str = RSTRING_PTR(indent); } if (body->catch_table) { - rb_str_cat(str, indent_str, indent_len); - rb_str_cat2(str, "|-------------------------------------" - "-----------------------------------\n"); + rb_str_cat(str, indent_str, indent_len); + rb_str_cat2(str, "|-------------------------------------" + "-----------------------------------\n"); } /* show local table information */ if (body->local_table) { - const struct rb_iseq_param_keyword *const keyword = body->param.keyword; - rb_str_cat(str, indent_str, indent_len); - rb_str_catf(str, - "local table (size: %d, argc: %d " - "[opts: %d, rest: %d, post: %d, block: %d, kw: %d@%d, kwrest: %d])\n", - body->local_table_size, - body->param.lead_num, - body->param.opt_num, - body->param.flags.has_rest ? body->param.rest_start : -1, - body->param.post_num, - body->param.flags.has_block ? body->param.block_start : -1, - body->param.flags.has_kw ? keyword->num : -1, - body->param.flags.has_kw ? keyword->required_num : -1, - body->param.flags.has_kwrest ? keyword->rest_start : -1); + const struct rb_iseq_param_keyword *const keyword = body->param.keyword; + rb_str_cat(str, indent_str, indent_len); + rb_str_catf(str, + "local table (size: %d, argc: %d " + "[opts: %d, rest: %d, post: %d, block: %d, kw: %d@%d, kwrest: %d])\n", + body->local_table_size, + body->param.lead_num, + body->param.opt_num, + body->param.flags.has_rest ? body->param.rest_start : -1, + body->param.post_num, + body->param.flags.has_block ? body->param.block_start : -1, + body->param.flags.has_kw ? keyword->num : -1, + body->param.flags.has_kw ? keyword->required_num : -1, + body->param.flags.has_kwrest ? keyword->rest_start : -1); - for (i = body->local_table_size; i > 0;) { - int li = body->local_table_size - --i - 1; - long width; - VALUE name = local_var_name(iseq, 0, i); + for (i = body->local_table_size; i > 0;) { + int li = body->local_table_size - --i - 1; + long width; + VALUE name = local_var_name(iseq, 0, i); char argi[0x100]; char opti[0x100]; opti[0] = '\0'; - if (body->param.flags.has_opt) { - int argc = body->param.lead_num; - int opts = body->param.opt_num; - if (li >= argc && li < argc + opts) { - snprintf(opti, sizeof(opti), "Opt=%"PRIdVALUE, - body->param.opt_table[li - argc]); - } - } + if (body->param.flags.has_opt) { + int argc = body->param.lead_num; + int opts = body->param.opt_num; + if (li >= argc && li < argc + opts) { + snprintf(opti, sizeof(opti), "Opt=%"PRIdVALUE, + body->param.opt_table[li - argc]); + } + } - snprintf(argi, sizeof(argi), "%s%s%s%s%s%s", /* arg, opts, rest, post, kwrest, block */ - body->param.lead_num > li ? "Arg" : "", - opti, - (body->param.flags.has_rest && body->param.rest_start == li) ? "Rest" : "", - (body->param.flags.has_post && body->param.post_start <= li && li < body->param.post_start + body->param.post_num) ? "Post" : "", - (body->param.flags.has_kwrest && keyword->rest_start == li) ? "Kwrest" : "", - (body->param.flags.has_block && body->param.block_start == li) ? "Block" : ""); + snprintf(argi, sizeof(argi), "%s%s%s%s%s%s", /* arg, opts, rest, post, kwrest, block */ + body->param.lead_num > li ? "Arg" : "", + opti, + (body->param.flags.has_rest && body->param.rest_start == li) ? "Rest" : "", + (body->param.flags.has_post && body->param.post_start <= li && li < body->param.post_start + body->param.post_num) ? "Post" : "", + (body->param.flags.has_kwrest && keyword->rest_start == li) ? "Kwrest" : "", + (body->param.flags.has_block && body->param.block_start == li) ? "Block" : ""); - rb_str_cat(str, indent_str, indent_len); - rb_str_catf(str, "[%2d] ", i + 1); - width = RSTRING_LEN(str) + 11; - rb_str_append(str, name); - if (*argi) rb_str_catf(str, "<%s>", argi); - if ((width -= RSTRING_LEN(str)) > 0) rb_str_catf(str, "%*s", (int)width, ""); - } - rb_str_cat_cstr(right_strip(str), "\n"); + rb_str_cat(str, indent_str, indent_len); + rb_str_catf(str, "[%2d] ", i + 1); + width = RSTRING_LEN(str) + 11; + rb_str_append(str, name); + if (*argi) rb_str_catf(str, "<%s>", argi); + if ((width -= RSTRING_LEN(str)) > 0) rb_str_catf(str, "%*s", (int)width, ""); + } + rb_str_cat_cstr(right_strip(str), "\n"); } /* show each line */ code = rb_iseq_original_iseq(iseq); for (n = 0; n < size;) { - rb_str_cat(str, indent_str, indent_len); - n += rb_iseq_disasm_insn(str, code, n, iseq, child); + rb_str_cat(str, indent_str, indent_len); + n += rb_iseq_disasm_insn(str, code, n, iseq, child); } for (l = 0; l < RARRAY_LEN(child); l++) { - VALUE isv = rb_ary_entry(child, l); - if (done_iseq && st_is_member(done_iseq, (st_data_t)isv)) continue; - rb_str_cat_cstr(str, "\n"); - rb_str_concat(str, rb_iseq_disasm_recursive(rb_iseq_check((rb_iseq_t *)isv), indent)); - indent_str = RSTRING_PTR(indent); + VALUE isv = rb_ary_entry(child, l); + if (done_iseq && st_is_member(done_iseq, (st_data_t)isv)) continue; + rb_str_cat_cstr(str, "\n"); + rb_str_concat(str, rb_iseq_disasm_recursive(rb_iseq_check((rb_iseq_t *)isv), indent)); + indent_str = RSTRING_PTR(indent); } RB_GC_GUARD(done_iseq_wrapper); @@ -2658,10 +2658,10 @@ iseqw_trace_points(VALUE self) VALUE ary = rb_ary_new(); for (i=0; iinsns_info.size; i++) { - const struct iseq_insn_info_entry *entry = &body->insns_info.body[i]; - if (entry->events) { - push_event_info(iseq, entry->events, entry->line_no, ary); - } + const struct iseq_insn_info_entry *entry = &body->insns_info.body[i]; + if (entry->events) { + push_event_info(iseq, entry->events, entry->line_no, ary); + } } return ary; } @@ -2788,8 +2788,8 @@ ruby_node_name(int node) switch (node) { #include "node_name.inc" default: - rb_bug("unknown node: %d", node); - return 0; + rb_bug("unknown node: %d", node); + return 0; } } @@ -2813,7 +2813,7 @@ exception_type2symbol(VALUE type) case CATCH_TYPE_REDO: CONST_ID(id, "redo"); break; case CATCH_TYPE_NEXT: CONST_ID(id, "next"); break; default: - rb_bug("unknown exception type: %d", (int)type); + rb_bug("unknown exception type: %d", (int)type); } return ID2SYM(id); } @@ -2914,170 +2914,170 @@ iseq_data_to_ary(const rb_iseq_t *iseq) /* locals */ for (i=0; ilocal_table_size; i++) { - ID lid = iseq_body->local_table[i]; - if (lid) { - if (rb_id2str(lid)) { - rb_ary_push(locals, ID2SYM(lid)); - } - else { /* hidden variable from id_internal() */ - rb_ary_push(locals, ULONG2NUM(iseq_body->local_table_size-i+1)); - } - } - else { - rb_ary_push(locals, ID2SYM(rb_intern("#arg_rest"))); - } + ID lid = iseq_body->local_table[i]; + if (lid) { + if (rb_id2str(lid)) { + rb_ary_push(locals, ID2SYM(lid)); + } + else { /* hidden variable from id_internal() */ + rb_ary_push(locals, ULONG2NUM(iseq_body->local_table_size-i+1)); + } + } + else { + rb_ary_push(locals, ID2SYM(rb_intern("#arg_rest"))); + } } /* params */ { - const struct rb_iseq_param_keyword *const keyword = iseq_body->param.keyword; - int j; + const struct rb_iseq_param_keyword *const keyword = iseq_body->param.keyword; + int j; - if (iseq_body->param.flags.has_opt) { - int len = iseq_body->param.opt_num + 1; - VALUE arg_opt_labels = rb_ary_new2(len); + if (iseq_body->param.flags.has_opt) { + int len = iseq_body->param.opt_num + 1; + VALUE arg_opt_labels = rb_ary_new2(len); - for (j = 0; j < len; j++) { - VALUE l = register_label(labels_table, iseq_body->param.opt_table[j]); - rb_ary_push(arg_opt_labels, l); - } - rb_hash_aset(params, ID2SYM(rb_intern("opt")), arg_opt_labels); + for (j = 0; j < len; j++) { + VALUE l = register_label(labels_table, iseq_body->param.opt_table[j]); + rb_ary_push(arg_opt_labels, l); + } + rb_hash_aset(params, ID2SYM(rb_intern("opt")), arg_opt_labels); } - /* commit */ - if (iseq_body->param.flags.has_lead) rb_hash_aset(params, ID2SYM(rb_intern("lead_num")), INT2FIX(iseq_body->param.lead_num)); - if (iseq_body->param.flags.has_post) rb_hash_aset(params, ID2SYM(rb_intern("post_num")), INT2FIX(iseq_body->param.post_num)); - if (iseq_body->param.flags.has_post) rb_hash_aset(params, ID2SYM(rb_intern("post_start")), INT2FIX(iseq_body->param.post_start)); - if (iseq_body->param.flags.has_rest) rb_hash_aset(params, ID2SYM(rb_intern("rest_start")), INT2FIX(iseq_body->param.rest_start)); - if (iseq_body->param.flags.has_block) rb_hash_aset(params, ID2SYM(rb_intern("block_start")), INT2FIX(iseq_body->param.block_start)); - if (iseq_body->param.flags.has_kw) { - VALUE keywords = rb_ary_new(); - int i, j; - for (i=0; irequired_num; i++) { - rb_ary_push(keywords, ID2SYM(keyword->table[i])); - } - for (j=0; inum; i++, j++) { - VALUE key = rb_ary_new_from_args(1, ID2SYM(keyword->table[i])); - if (keyword->default_values[j] != Qundef) { - rb_ary_push(key, keyword->default_values[j]); - } - rb_ary_push(keywords, key); - } + /* commit */ + if (iseq_body->param.flags.has_lead) rb_hash_aset(params, ID2SYM(rb_intern("lead_num")), INT2FIX(iseq_body->param.lead_num)); + if (iseq_body->param.flags.has_post) rb_hash_aset(params, ID2SYM(rb_intern("post_num")), INT2FIX(iseq_body->param.post_num)); + if (iseq_body->param.flags.has_post) rb_hash_aset(params, ID2SYM(rb_intern("post_start")), INT2FIX(iseq_body->param.post_start)); + if (iseq_body->param.flags.has_rest) rb_hash_aset(params, ID2SYM(rb_intern("rest_start")), INT2FIX(iseq_body->param.rest_start)); + if (iseq_body->param.flags.has_block) rb_hash_aset(params, ID2SYM(rb_intern("block_start")), INT2FIX(iseq_body->param.block_start)); + if (iseq_body->param.flags.has_kw) { + VALUE keywords = rb_ary_new(); + int i, j; + for (i=0; irequired_num; i++) { + rb_ary_push(keywords, ID2SYM(keyword->table[i])); + } + for (j=0; inum; i++, j++) { + VALUE key = rb_ary_new_from_args(1, ID2SYM(keyword->table[i])); + if (keyword->default_values[j] != Qundef) { + rb_ary_push(key, keyword->default_values[j]); + } + rb_ary_push(keywords, key); + } - rb_hash_aset(params, ID2SYM(rb_intern("kwbits")), - INT2FIX(keyword->bits_start)); - rb_hash_aset(params, ID2SYM(rb_intern("keyword")), keywords); - } - if (iseq_body->param.flags.has_kwrest) rb_hash_aset(params, ID2SYM(rb_intern("kwrest")), INT2FIX(keyword->rest_start)); - if (iseq_body->param.flags.ambiguous_param0) rb_hash_aset(params, ID2SYM(rb_intern("ambiguous_param0")), Qtrue); + rb_hash_aset(params, ID2SYM(rb_intern("kwbits")), + INT2FIX(keyword->bits_start)); + rb_hash_aset(params, ID2SYM(rb_intern("keyword")), keywords); + } + if (iseq_body->param.flags.has_kwrest) rb_hash_aset(params, ID2SYM(rb_intern("kwrest")), INT2FIX(keyword->rest_start)); + if (iseq_body->param.flags.ambiguous_param0) rb_hash_aset(params, ID2SYM(rb_intern("ambiguous_param0")), Qtrue); } /* body */ iseq_original = rb_iseq_original_iseq((rb_iseq_t *)iseq); for (seq = iseq_original; seq < iseq_original + iseq_body->iseq_size; ) { - VALUE insn = *seq++; - int j, len = insn_len(insn); - VALUE *nseq = seq + len - 1; - VALUE ary = rb_ary_new2(len); + VALUE insn = *seq++; + int j, len = insn_len(insn); + VALUE *nseq = seq + len - 1; + VALUE ary = rb_ary_new2(len); rb_ary_push(ary, ID2SYM(insn_syms[insn%numberof(insn_syms)])); - for (j=0; jci; - VALUE e = rb_hash_new(); + VALUE e = rb_hash_new(); int argc = vm_ci_argc(ci); ID mid = vm_ci_mid(ci); - rb_hash_aset(e, ID2SYM(rb_intern("mid")), mid ? ID2SYM(mid) : Qnil); - rb_hash_aset(e, ID2SYM(rb_intern("flag")), UINT2NUM(vm_ci_flag(ci))); + rb_hash_aset(e, ID2SYM(rb_intern("mid")), mid ? ID2SYM(mid) : Qnil); + rb_hash_aset(e, ID2SYM(rb_intern("flag")), UINT2NUM(vm_ci_flag(ci))); if (vm_ci_flag(ci) & VM_CALL_KWARG) { const struct rb_callinfo_kwarg *kwarg = vm_ci_kwarg(ci); int i; - VALUE kw = rb_ary_new2((long)kwarg->keyword_len); + VALUE kw = rb_ary_new2((long)kwarg->keyword_len); - argc -= kwarg->keyword_len; + argc -= kwarg->keyword_len; for (i = 0; i < kwarg->keyword_len; i++) { - rb_ary_push(kw, kwarg->keywords[i]); - } - rb_hash_aset(e, ID2SYM(rb_intern("kw_arg")), kw); - } + rb_ary_push(kw, kwarg->keywords[i]); + } + rb_hash_aset(e, ID2SYM(rb_intern("kw_arg")), kw); + } - rb_hash_aset(e, ID2SYM(rb_intern("orig_argc")), - INT2FIX(argc)); - rb_ary_push(ary, e); - } - break; - case TS_ID: - rb_ary_push(ary, ID2SYM(*seq)); - break; - case TS_CDHASH: - { - VALUE hash = *seq; - VALUE val = rb_ary_new(); - int i; + rb_hash_aset(e, ID2SYM(rb_intern("orig_argc")), + INT2FIX(argc)); + rb_ary_push(ary, e); + } + break; + case TS_ID: + rb_ary_push(ary, ID2SYM(*seq)); + break; + case TS_CDHASH: + { + VALUE hash = *seq; + VALUE val = rb_ary_new(); + int i; - rb_hash_foreach(hash, cdhash_each, val); + rb_hash_foreach(hash, cdhash_each, val); - for (i=0; icatch_table) for (i=0; icatch_table->size; i++) { - VALUE ary = rb_ary_new(); - const struct iseq_catch_table_entry *entry = - UNALIGNED_MEMBER_PTR(iseq_body->catch_table, entries[i]); - rb_ary_push(ary, exception_type2symbol(entry->type)); - if (entry->iseq) { - rb_ary_push(ary, iseq_data_to_ary(rb_iseq_check(entry->iseq))); - } - else { - rb_ary_push(ary, Qnil); - } - rb_ary_push(ary, register_label(labels_table, entry->start)); - rb_ary_push(ary, register_label(labels_table, entry->end)); - rb_ary_push(ary, register_label(labels_table, entry->cont)); - rb_ary_push(ary, UINT2NUM(entry->sp)); - rb_ary_push(exception, ary); + VALUE ary = rb_ary_new(); + const struct iseq_catch_table_entry *entry = + UNALIGNED_MEMBER_PTR(iseq_body->catch_table, entries[i]); + rb_ary_push(ary, exception_type2symbol(entry->type)); + if (entry->iseq) { + rb_ary_push(ary, iseq_data_to_ary(rb_iseq_check(entry->iseq))); + } + else { + rb_ary_push(ary, Qnil); + } + rb_ary_push(ary, register_label(labels_table, entry->start)); + rb_ary_push(ary, register_label(labels_table, entry->end)); + rb_ary_push(ary, register_label(labels_table, entry->cont)); + rb_ary_push(ary, UINT2NUM(entry->sp)); + rb_ary_push(exception, ary); } /* make body with labels and insert line number */ @@ -3129,41 +3129,41 @@ iseq_data_to_ary(const rb_iseq_t *iseq) #endif for (l=0, pos=0; lnode_id)); #endif - if (prev_insn_info != info) { - int line = info->line_no; - rb_event_flag_t events = info->events; + if (prev_insn_info != info) { + int line = info->line_no; + rb_event_flag_t events = info->events; - if (line > 0 && last_line != line) { - rb_ary_push(body, INT2FIX(line)); - last_line = line; - } + if (line > 0 && last_line != line) { + rb_ary_push(body, INT2FIX(line)); + last_line = line; + } #define CHECK_EVENT(ev) if (events & ev) rb_ary_push(body, ID2SYM(rb_intern(#ev))); - CHECK_EVENT(RUBY_EVENT_LINE); - CHECK_EVENT(RUBY_EVENT_CLASS); - CHECK_EVENT(RUBY_EVENT_END); - CHECK_EVENT(RUBY_EVENT_CALL); - CHECK_EVENT(RUBY_EVENT_RETURN); - CHECK_EVENT(RUBY_EVENT_B_CALL); - CHECK_EVENT(RUBY_EVENT_B_RETURN); + CHECK_EVENT(RUBY_EVENT_LINE); + CHECK_EVENT(RUBY_EVENT_CLASS); + CHECK_EVENT(RUBY_EVENT_END); + CHECK_EVENT(RUBY_EVENT_CALL); + CHECK_EVENT(RUBY_EVENT_RETURN); + CHECK_EVENT(RUBY_EVENT_B_CALL); + CHECK_EVENT(RUBY_EVENT_B_RETURN); #undef CHECK_EVENT - prev_insn_info = info; - } + prev_insn_info = info; + } - rb_ary_push(body, ary); - pos += RARRAY_LENINT(ary); /* reject too huge data */ + rb_ary_push(body, ary); + pos += RARRAY_LENINT(ary); /* reject too huge data */ } RB_GC_GUARD(nbody); RB_GC_GUARD(labels_wrapper); @@ -3173,11 +3173,11 @@ iseq_data_to_ary(const rb_iseq_t *iseq) rb_hash_aset(misc, ID2SYM(rb_intern("stack_max")), INT2FIX(iseq_body->stack_max)); rb_hash_aset(misc, ID2SYM(rb_intern("node_id")), INT2FIX(iseq_body->location.node_id)); rb_hash_aset(misc, ID2SYM(rb_intern("code_location")), - rb_ary_new_from_args(4, - INT2FIX(iseq_body->location.code_location.beg_pos.lineno), - INT2FIX(iseq_body->location.code_location.beg_pos.column), - INT2FIX(iseq_body->location.code_location.end_pos.lineno), - INT2FIX(iseq_body->location.code_location.end_pos.column))); + rb_ary_new_from_args(4, + INT2FIX(iseq_body->location.code_location.beg_pos.lineno), + INT2FIX(iseq_body->location.code_location.beg_pos.column), + INT2FIX(iseq_body->location.code_location.end_pos.lineno), + INT2FIX(iseq_body->location.code_location.end_pos.column))); #ifdef USE_ISEQ_NODE_ID rb_hash_aset(misc, ID2SYM(rb_intern("node_ids")), node_ids); #endif @@ -3215,81 +3215,81 @@ rb_iseq_parameters(const rb_iseq_t *iseq, int is_proc) #define PARAM_TYPE(type) rb_ary_push(a = rb_ary_new2(2), ID2SYM(type)) #define PARAM_ID(i) body->local_table[(i)] #define PARAM(i, type) ( \ - PARAM_TYPE(type), \ - rb_id2str(PARAM_ID(i)) ? \ - rb_ary_push(a, ID2SYM(PARAM_ID(i))) : \ - a) + PARAM_TYPE(type), \ + rb_id2str(PARAM_ID(i)) ? \ + rb_ary_push(a, ID2SYM(PARAM_ID(i))) : \ + a) CONST_ID(req, "req"); CONST_ID(opt, "opt"); if (is_proc) { - for (i = 0; i < body->param.lead_num; i++) { - PARAM_TYPE(opt); - rb_ary_push(a, rb_id2str(PARAM_ID(i)) ? ID2SYM(PARAM_ID(i)) : Qnil); - rb_ary_push(args, a); - } + for (i = 0; i < body->param.lead_num; i++) { + PARAM_TYPE(opt); + rb_ary_push(a, rb_id2str(PARAM_ID(i)) ? ID2SYM(PARAM_ID(i)) : Qnil); + rb_ary_push(args, a); + } } else { - for (i = 0; i < body->param.lead_num; i++) { - rb_ary_push(args, PARAM(i, req)); - } + for (i = 0; i < body->param.lead_num; i++) { + rb_ary_push(args, PARAM(i, req)); + } } r = body->param.lead_num + body->param.opt_num; for (; i < r; i++) { - PARAM_TYPE(opt); - if (rb_id2str(PARAM_ID(i))) { - rb_ary_push(a, ID2SYM(PARAM_ID(i))); - } - rb_ary_push(args, a); + PARAM_TYPE(opt); + if (rb_id2str(PARAM_ID(i))) { + rb_ary_push(a, ID2SYM(PARAM_ID(i))); + } + rb_ary_push(args, a); } if (body->param.flags.has_rest) { - CONST_ID(rest, "rest"); - rb_ary_push(args, PARAM(body->param.rest_start, rest)); + CONST_ID(rest, "rest"); + rb_ary_push(args, PARAM(body->param.rest_start, rest)); } r = body->param.post_start + body->param.post_num; if (is_proc) { - for (i = body->param.post_start; i < r; i++) { - PARAM_TYPE(opt); - rb_ary_push(a, rb_id2str(PARAM_ID(i)) ? ID2SYM(PARAM_ID(i)) : Qnil); - rb_ary_push(args, a); - } + for (i = body->param.post_start; i < r; i++) { + PARAM_TYPE(opt); + rb_ary_push(a, rb_id2str(PARAM_ID(i)) ? ID2SYM(PARAM_ID(i)) : Qnil); + rb_ary_push(args, a); + } } else { - for (i = body->param.post_start; i < r; i++) { - rb_ary_push(args, PARAM(i, req)); - } + for (i = body->param.post_start; i < r; i++) { + rb_ary_push(args, PARAM(i, req)); + } } if (body->param.flags.accepts_no_kwarg) { - ID nokey; - CONST_ID(nokey, "nokey"); - PARAM_TYPE(nokey); - rb_ary_push(args, a); + ID nokey; + CONST_ID(nokey, "nokey"); + PARAM_TYPE(nokey); + rb_ary_push(args, a); } if (body->param.flags.has_kw) { - i = 0; - if (keyword->required_num > 0) { - ID keyreq; - CONST_ID(keyreq, "keyreq"); - for (; i < keyword->required_num; i++) { - PARAM_TYPE(keyreq); - if (rb_id2str(keyword->table[i])) { - rb_ary_push(a, ID2SYM(keyword->table[i])); - } - rb_ary_push(args, a); - } - } - CONST_ID(key, "key"); - for (; i < keyword->num; i++) { - PARAM_TYPE(key); - if (rb_id2str(keyword->table[i])) { - rb_ary_push(a, ID2SYM(keyword->table[i])); - } - rb_ary_push(args, a); - } + i = 0; + if (keyword->required_num > 0) { + ID keyreq; + CONST_ID(keyreq, "keyreq"); + for (; i < keyword->required_num; i++) { + PARAM_TYPE(keyreq); + if (rb_id2str(keyword->table[i])) { + rb_ary_push(a, ID2SYM(keyword->table[i])); + } + rb_ary_push(args, a); + } + } + CONST_ID(key, "key"); + for (; i < keyword->num; i++) { + PARAM_TYPE(key); + if (rb_id2str(keyword->table[i])) { + rb_ary_push(a, ID2SYM(keyword->table[i])); + } + rb_ary_push(args, a); + } } if (body->param.flags.has_kwrest || body->param.flags.ruby2_keywords) { ID param; - CONST_ID(keyrest, "keyrest"); + CONST_ID(keyrest, "keyrest"); PARAM_TYPE(keyrest); if (body->param.flags.has_kwrest && rb_id2str(param = PARAM_ID(keyword->rest_start))) { @@ -3298,11 +3298,11 @@ rb_iseq_parameters(const rb_iseq_t *iseq, int is_proc) else if (body->param.flags.ruby2_keywords) { rb_ary_push(a, ID2SYM(idPow)); } - rb_ary_push(args, a); + rb_ary_push(args, a); } if (body->param.flags.has_block) { - CONST_ID(block, "block"); - rb_ary_push(args, PARAM(body->param.block_start, block)); + CONST_ID(block, "block"); + rb_ary_push(args, PARAM(body->param.block_start, block)); } return args; } @@ -3311,20 +3311,20 @@ VALUE rb_iseq_defined_string(enum defined_type type) { static const char expr_names[][18] = { - "nil", - "instance-variable", - "local-variable", - "global-variable", - "class variable", - "constant", - "method", - "yield", - "super", - "self", - "true", - "false", - "assignment", - "expression", + "nil", + "instance-variable", + "local-variable", + "global-variable", + "class variable", + "constant", + "method", + "yield", + "super", + "self", + "true", + "false", + "assignment", + "expression", }; const char *estr; @@ -3594,17 +3594,17 @@ void rb_iseq_trace_set(const rb_iseq_t *iseq, rb_event_flag_t turnon_events) { if (iseq->aux.exec.global_trace_events == turnon_events) { - return; + return; } if (!ISEQ_EXECUTABLE_P(iseq)) { - /* this is building ISeq */ - return; + /* this is building ISeq */ + return; } else { unsigned int pc; const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq); - VALUE *iseq_encoded = (VALUE *)body->iseq_encoded; + VALUE *iseq_encoded = (VALUE *)body->iseq_encoded; rb_event_flag_t enabled_events; rb_event_flag_t local_events = iseq->aux.exec.local_hooks ? iseq->aux.exec.local_hooks->events : 0; ((rb_iseq_t *)iseq)->aux.exec.global_trace_events = turnon_events; @@ -3613,7 +3613,7 @@ rb_iseq_trace_set(const rb_iseq_t *iseq, rb_event_flag_t turnon_events) for (pc=0; pciseq_size;) { rb_event_flag_t pc_events = rb_iseq_event_flags(iseq, pc); pc += encoded_iseq_trace_instrument(&iseq_encoded[pc], pc_events & enabled_events, true); - } + } } } @@ -3653,9 +3653,9 @@ trace_set_i(void *vstart, void *vend, size_t stride, void *data) void *ptr = asan_poisoned_object_p(v); asan_unpoison_object(v, false); - if (rb_obj_is_iseq(v)) { - rb_iseq_trace_set(rb_iseq_check((rb_iseq_t *)v), turnon_events); - } + if (rb_obj_is_iseq(v)) { + rb_iseq_trace_set(rb_iseq_check((rb_iseq_t *)v), turnon_events); + } else if (imemo_type_p(v, imemo_callcache) && rb_vm_call_ivar_attrset_p(((const struct rb_callcache *)v)->call_)) { rb_vm_cc_general((struct rb_callcache *)v); } @@ -3770,9 +3770,9 @@ iseqw_s_load_from_binary_extra_data(VALUE self, VALUE str) struct succ_index_table { uint64_t imm_part[IMMEDIATE_TABLE_SIZE / 9]; struct succ_dict_block { - unsigned int rank; - uint64_t small_block_ranks; /* 9 bits * 7 = 63 bits */ - uint64_t bits[512/64]; + unsigned int rank; + uint64_t small_block_ranks; /* 9 bits * 7 = 63 bits */ + uint64_t bits[512/64]; } succ_part[FLEX_ARY_LEN]; }; @@ -3794,27 +3794,27 @@ succ_index_table_create(int max_pos, int *data, int size) r = 0; for (j = 0; j < imm_size; j++) { - for (i = 0; i < 9; i++) { - if (r < size && data[r] == j * 9 + i) r++; - imm_block_rank_set(sd->imm_part[j], i, r); - } + for (i = 0; i < 9; i++) { + if (r < size && data[r] == j * 9 + i) r++; + imm_block_rank_set(sd->imm_part[j], i, r); + } } for (k = 0; k < succ_size; k++) { - struct succ_dict_block *sd_block = &sd->succ_part[k]; - int small_rank = 0; - sd_block->rank = r; - for (j = 0; j < 8; j++) { - uint64_t bits = 0; - if (j) small_block_rank_set(sd_block->small_block_ranks, j, small_rank); - for (i = 0; i < 64; i++) { - if (r < size && data[r] == k * 512 + j * 64 + i + IMMEDIATE_TABLE_SIZE) { - bits |= ((uint64_t)1) << i; - r++; - } - } - sd_block->bits[j] = bits; - small_rank += rb_popcount64(bits); - } + struct succ_dict_block *sd_block = &sd->succ_part[k]; + int small_rank = 0; + sd_block->rank = r; + for (j = 0; j < 8; j++) { + uint64_t bits = 0; + if (j) small_block_rank_set(sd_block->small_block_ranks, j, small_rank); + for (i = 0; i < 64; i++) { + if (r < size && data[r] == k * 512 + j * 64 + i + IMMEDIATE_TABLE_SIZE) { + bits |= ((uint64_t)1) << i; + r++; + } + } + sd_block->bits[j] = bits; + small_rank += rb_popcount64(bits); + } } return sd; } @@ -3828,20 +3828,20 @@ succ_index_table_invert(int max_pos, struct succ_index_table *sd, int size) int i, j, k, r = -1; p = positions; for (j = 0; j < imm_size; j++) { - for (i = 0; i < 9; i++) { - int nr = imm_block_rank_get(sd->imm_part[j], i); - if (r != nr) *p++ = j * 9 + i; - r = nr; - } + for (i = 0; i < 9; i++) { + int nr = imm_block_rank_get(sd->imm_part[j], i); + if (r != nr) *p++ = j * 9 + i; + r = nr; + } } for (k = 0; k < succ_size; k++) { - for (j = 0; j < 8; j++) { - for (i = 0; i < 64; i++) { - if (sd->succ_part[k].bits[j] & (((uint64_t)1) << i)) { - *p++ = k * 512 + j * 64 + i + IMMEDIATE_TABLE_SIZE; - } - } - } + for (j = 0; j < 8; j++) { + for (i = 0; i < 64; i++) { + if (sd->succ_part[k].bits[j] & (((uint64_t)1) << i)) { + *p++ = k * 512 + j * 64 + i + IMMEDIATE_TABLE_SIZE; + } + } + } } return positions; } @@ -3850,19 +3850,19 @@ static int succ_index_lookup(const struct succ_index_table *sd, int x) { if (x < IMMEDIATE_TABLE_SIZE) { - const int i = x / 9; - const int j = x % 9; - return imm_block_rank_get(sd->imm_part[i], j); + const int i = x / 9; + const int j = x % 9; + return imm_block_rank_get(sd->imm_part[i], j); } else { - const int block_index = (x - IMMEDIATE_TABLE_SIZE) / 512; - const struct succ_dict_block *block = &sd->succ_part[block_index]; - const int block_bit_index = (x - IMMEDIATE_TABLE_SIZE) % 512; - const int small_block_index = block_bit_index / 64; - const int small_block_popcount = small_block_rank_get(block->small_block_ranks, small_block_index); - const int popcnt = rb_popcount64(block->bits[small_block_index] << (63 - block_bit_index % 64)); + const int block_index = (x - IMMEDIATE_TABLE_SIZE) / 512; + const struct succ_dict_block *block = &sd->succ_part[block_index]; + const int block_bit_index = (x - IMMEDIATE_TABLE_SIZE) % 512; + const int small_block_index = block_bit_index / 64; + const int small_block_popcount = small_block_rank_get(block->small_block_ranks, small_block_index); + const int popcnt = rb_popcount64(block->bits[small_block_index] << (63 - block_bit_index % 64)); - return block->rank + small_block_popcount + popcnt; + return block->rank + small_block_popcount + popcnt; } } #endif diff --git a/iseq.h b/iseq.h index 4c6d9f6597..63991d95ff 100644 --- a/iseq.h +++ b/iseq.h @@ -76,14 +76,14 @@ ISEQ_ORIGINAL_ISEQ_ALLOC(const rb_iseq_t *iseq, long size) } #define ISEQ_TRACE_EVENTS (RUBY_EVENT_LINE | \ - RUBY_EVENT_CLASS | \ - RUBY_EVENT_END | \ - RUBY_EVENT_CALL | \ - RUBY_EVENT_RETURN| \ + RUBY_EVENT_CLASS | \ + RUBY_EVENT_END | \ + RUBY_EVENT_CALL | \ + RUBY_EVENT_RETURN| \ RUBY_EVENT_C_CALL| \ RUBY_EVENT_C_RETURN| \ - RUBY_EVENT_B_CALL| \ - RUBY_EVENT_B_RETURN| \ + RUBY_EVENT_B_CALL| \ + RUBY_EVENT_B_RETURN| \ RUBY_EVENT_COVERAGE_LINE| \ RUBY_EVENT_COVERAGE_BRANCH) @@ -132,10 +132,10 @@ static inline struct iseq_compile_data * ISEQ_COMPILE_DATA(const rb_iseq_t *iseq) { if (iseq->flags & ISEQ_USE_COMPILE_DATA) { - return iseq->aux.compile_data; + return iseq->aux.compile_data; } else { - return NULL; + return NULL; } } @@ -182,8 +182,8 @@ VALUE rb_iseq_compile_node(rb_iseq_t *iseq, const NODE *node); VALUE rb_iseq_compile_callback(rb_iseq_t *iseq, const struct rb_iseq_new_with_callback_callback_func * ifunc); VALUE *rb_iseq_original_iseq(const rb_iseq_t *iseq); void rb_iseq_build_from_ary(rb_iseq_t *iseq, VALUE misc, - VALUE locals, VALUE args, - VALUE exception, VALUE body); + VALUE locals, VALUE args, + VALUE exception, VALUE body); void rb_iseq_mark_insn_storage(struct iseq_compile_data_storage *arena); /* iseq.c */ @@ -243,12 +243,12 @@ struct iseq_insn_info_entry { struct iseq_catch_table_entry { enum catch_type { - CATCH_TYPE_RESCUE = INT2FIX(1), - CATCH_TYPE_ENSURE = INT2FIX(2), - CATCH_TYPE_RETRY = INT2FIX(3), - CATCH_TYPE_BREAK = INT2FIX(4), - CATCH_TYPE_REDO = INT2FIX(5), - CATCH_TYPE_NEXT = INT2FIX(6) + CATCH_TYPE_RESCUE = INT2FIX(1), + CATCH_TYPE_ENSURE = INT2FIX(2), + CATCH_TYPE_RETRY = INT2FIX(3), + CATCH_TYPE_BREAK = INT2FIX(4), + CATCH_TYPE_REDO = INT2FIX(5), + CATCH_TYPE_NEXT = INT2FIX(6) } type; /* @@ -280,12 +280,12 @@ static inline int iseq_catch_table_bytes(int n) { enum { - catch_table_entry_size = sizeof(struct iseq_catch_table_entry), - catch_table_entries_max = (INT_MAX - offsetof(struct iseq_catch_table, entries)) / catch_table_entry_size + catch_table_entry_size = sizeof(struct iseq_catch_table_entry), + catch_table_entries_max = (INT_MAX - offsetof(struct iseq_catch_table, entries)) / catch_table_entry_size }; if (n > catch_table_entries_max) rb_fatal("too large iseq_catch_table - %d", n); return (int)(offsetof(struct iseq_catch_table, entries) + - n * catch_table_entry_size); + n * catch_table_entry_size); } #define INITIAL_ISEQ_COMPILE_DATA_STORAGE_BUFF_SIZE (512) diff --git a/load.c b/load.c index a66940e0b7..e3daea7d7b 100644 --- a/load.c +++ b/load.c @@ -56,37 +56,37 @@ rb_construct_expanded_load_path(rb_vm_t *vm, enum expand_type type, int *has_rel ary = rb_ary_tmp_new(RARRAY_LEN(load_path)); for (i = 0; i < RARRAY_LEN(load_path); ++i) { - VALUE path, as_str, expanded_path; - int is_string, non_cache; - char *as_cstr; - as_str = path = RARRAY_AREF(load_path, i); - is_string = RB_TYPE_P(path, T_STRING) ? 1 : 0; - non_cache = !is_string ? 1 : 0; + VALUE path, as_str, expanded_path; + int is_string, non_cache; + char *as_cstr; + as_str = path = RARRAY_AREF(load_path, i); + is_string = RB_TYPE_P(path, T_STRING) ? 1 : 0; + non_cache = !is_string ? 1 : 0; as_str = rb_get_path_check_to_string(path); - as_cstr = RSTRING_PTR(as_str); + as_cstr = RSTRING_PTR(as_str); - if (!non_cache) { - if ((type == EXPAND_RELATIVE && - rb_is_absolute_path(as_cstr)) || - (type == EXPAND_HOME && - (!as_cstr[0] || as_cstr[0] != '~')) || - (type == EXPAND_NON_CACHE)) { - /* Use cached expanded path. */ - rb_ary_push(ary, RARRAY_AREF(expanded_load_path, i)); - continue; - } - } - if (!*has_relative && !rb_is_absolute_path(as_cstr)) - *has_relative = 1; - if (!*has_non_cache && non_cache) - *has_non_cache = 1; - /* Freeze only string object. We expand other objects every time. */ - if (is_string) - rb_str_freeze(path); + if (!non_cache) { + if ((type == EXPAND_RELATIVE && + rb_is_absolute_path(as_cstr)) || + (type == EXPAND_HOME && + (!as_cstr[0] || as_cstr[0] != '~')) || + (type == EXPAND_NON_CACHE)) { + /* Use cached expanded path. */ + rb_ary_push(ary, RARRAY_AREF(expanded_load_path, i)); + continue; + } + } + if (!*has_relative && !rb_is_absolute_path(as_cstr)) + *has_relative = 1; + if (!*has_non_cache && non_cache) + *has_non_cache = 1; + /* Freeze only string object. We expand other objects every time. */ + if (is_string) + rb_str_freeze(path); as_str = rb_get_path_check_convert(as_str); - expanded_path = rb_check_realpath(Qnil, as_str, NULL); - if (NIL_P(expanded_path)) expanded_path = as_str; - rb_ary_push(ary, rb_fstring(expanded_path)); + expanded_path = rb_check_realpath(Qnil, as_str, NULL); + if (NIL_P(expanded_path)) expanded_path = as_str; + rb_ary_push(ary, rb_fstring(expanded_path)); } rb_obj_freeze(ary); vm->expanded_load_path = ary; @@ -99,41 +99,41 @@ get_expanded_load_path(rb_vm_t *vm) const VALUE non_cache = Qtrue; if (!rb_ary_shared_with_p(vm->load_path_snapshot, vm->load_path)) { - /* The load path was modified. Rebuild the expanded load path. */ - int has_relative = 0, has_non_cache = 0; - rb_construct_expanded_load_path(vm, EXPAND_ALL, &has_relative, &has_non_cache); - if (has_relative) { - vm->load_path_check_cache = rb_dir_getwd_ospath(); - } - else if (has_non_cache) { - /* Non string object. */ - vm->load_path_check_cache = non_cache; - } - else { - vm->load_path_check_cache = 0; - } + /* The load path was modified. Rebuild the expanded load path. */ + int has_relative = 0, has_non_cache = 0; + rb_construct_expanded_load_path(vm, EXPAND_ALL, &has_relative, &has_non_cache); + if (has_relative) { + vm->load_path_check_cache = rb_dir_getwd_ospath(); + } + else if (has_non_cache) { + /* Non string object. */ + vm->load_path_check_cache = non_cache; + } + else { + vm->load_path_check_cache = 0; + } } else if (vm->load_path_check_cache == non_cache) { - int has_relative = 1, has_non_cache = 1; - /* Expand only non-cacheable objects. */ - rb_construct_expanded_load_path(vm, EXPAND_NON_CACHE, - &has_relative, &has_non_cache); + int has_relative = 1, has_non_cache = 1; + /* Expand only non-cacheable objects. */ + rb_construct_expanded_load_path(vm, EXPAND_NON_CACHE, + &has_relative, &has_non_cache); } else if (vm->load_path_check_cache) { - int has_relative = 1, has_non_cache = 1; - VALUE cwd = rb_dir_getwd_ospath(); - if (!rb_str_equal(vm->load_path_check_cache, cwd)) { - /* Current working directory or filesystem encoding was changed. - Expand relative load path and non-cacheable objects again. */ - vm->load_path_check_cache = cwd; - rb_construct_expanded_load_path(vm, EXPAND_RELATIVE, - &has_relative, &has_non_cache); - } - else { - /* Expand only tilde (User HOME) and non-cacheable objects. */ - rb_construct_expanded_load_path(vm, EXPAND_HOME, - &has_relative, &has_non_cache); - } + int has_relative = 1, has_non_cache = 1; + VALUE cwd = rb_dir_getwd_ospath(); + if (!rb_str_equal(vm->load_path_check_cache, cwd)) { + /* Current working directory or filesystem encoding was changed. + Expand relative load path and non-cacheable objects again. */ + vm->load_path_check_cache = cwd; + rb_construct_expanded_load_path(vm, EXPAND_RELATIVE, + &has_relative, &has_non_cache); + } + else { + /* Expand only tilde (User HOME) and non-cacheable objects. */ + rb_construct_expanded_load_path(vm, EXPAND_HOME, + &has_relative, &has_non_cache); + } } return vm->expanded_load_path; } @@ -311,10 +311,10 @@ features_index_add(rb_vm_t *vm, VALUE feature, VALUE offset) feature_end = feature_str + RSTRING_LEN(feature); for (ext = feature_end; ext > feature_str; ext--) - if (*ext == '.' || *ext == '/') - break; + if (*ext == '.' || *ext == '/') + break; if (*ext != '.') - ext = NULL; + ext = NULL; else rb = IS_RBEXT(ext); /* Now `ext` points to the only string matching %r{^\.[^./]*$} that is @@ -322,20 +322,20 @@ features_index_add(rb_vm_t *vm, VALUE feature, VALUE offset) p = ext ? ext : feature_end; while (1) { - p--; - while (p >= feature_str && *p != '/') - p--; - if (p < feature_str) - break; - /* Now *p == '/'. We reach this point for every '/' in `feature`. */ - features_index_add_single(vm, p + 1, feature_end - p - 1, offset, false); - if (ext) { - features_index_add_single(vm, p + 1, ext - p - 1, offset, rb); - } + p--; + while (p >= feature_str && *p != '/') + p--; + if (p < feature_str) + break; + /* Now *p == '/'. We reach this point for every '/' in `feature`. */ + features_index_add_single(vm, p + 1, feature_end - p - 1, offset, false); + if (ext) { + features_index_add_single(vm, p + 1, ext - p - 1, offset, rb); + } } features_index_add_single(vm, feature_str, feature_end - feature_str, offset, false); if (ext) { - features_index_add_single(vm, feature_str, ext - feature_str, offset, rb); + features_index_add_single(vm, feature_str, ext - feature_str, offset, rb); } } @@ -356,23 +356,23 @@ get_loaded_features_index(rb_vm_t *vm) int i; if (!rb_ary_shared_with_p(vm->loaded_features_snapshot, vm->loaded_features)) { - /* The sharing was broken; something (other than us in rb_provide_feature()) - modified loaded_features. Rebuild the index. */ - st_foreach(vm->loaded_features_index, loaded_features_index_clear_i, 0); + /* The sharing was broken; something (other than us in rb_provide_feature()) + modified loaded_features. Rebuild the index. */ + st_foreach(vm->loaded_features_index, loaded_features_index_clear_i, 0); VALUE realpaths = vm->loaded_features_realpaths; rb_hash_clear(realpaths); - features = vm->loaded_features; - for (i = 0; i < RARRAY_LEN(features); i++) { - VALUE entry, as_str; - as_str = entry = rb_ary_entry(features, i); - StringValue(as_str); - as_str = rb_fstring(rb_str_freeze(as_str)); - if (as_str != entry) - rb_ary_store(features, i, as_str); - features_index_add(vm, as_str, INT2FIX(i)); - } - reset_loaded_features_snapshot(vm); + features = vm->loaded_features; + for (i = 0; i < RARRAY_LEN(features); i++) { + VALUE entry, as_str; + as_str = entry = rb_ary_entry(features, i); + StringValue(as_str); + as_str = rb_fstring(rb_str_freeze(as_str)); + if (as_str != entry) + rb_ary_store(features, i, as_str); + features_index_add(vm, as_str, INT2FIX(i)); + } + reset_loaded_features_snapshot(vm); features = rb_ary_dup(vm->loaded_features_snapshot); long j = RARRAY_LEN(features); @@ -399,7 +399,7 @@ get_loaded_features_index(rb_vm_t *vm) */ static VALUE loaded_feature_path(const char *name, long vlen, const char *feature, long len, - int type, VALUE load_path) + int type, VALUE load_path) { long i; long plen; @@ -407,36 +407,36 @@ loaded_feature_path(const char *name, long vlen, const char *feature, long len, if (vlen < len+1) return 0; if (strchr(feature, '.') && !strncmp(name+(vlen-len), feature, len)) { - plen = vlen - len; + plen = vlen - len; } else { - for (e = name + vlen; name != e && *e != '.' && *e != '/'; --e); - if (*e != '.' || - e-name < len || - strncmp(e-len, feature, len)) - return 0; - plen = e - name - len; + for (e = name + vlen; name != e && *e != '.' && *e != '/'; --e); + if (*e != '.' || + e-name < len || + strncmp(e-len, feature, len)) + return 0; + plen = e - name - len; } if (plen > 0 && name[plen-1] != '/') { - return 0; + return 0; } if (type == 's' ? !IS_DLEXT(&name[plen+len]) : - type == 'r' ? !IS_RBEXT(&name[plen+len]) : - 0) { - return 0; + type == 'r' ? !IS_RBEXT(&name[plen+len]) : + 0) { + return 0; } /* Now name == "#{prefix}/#{feature}#{ext}" where ext is acceptable (possibly empty) and prefix is some string of length plen. */ if (plen > 0) --plen; /* exclude '.' */ for (i = 0; i < RARRAY_LEN(load_path); ++i) { - VALUE p = RARRAY_AREF(load_path, i); - const char *s = StringValuePtr(p); - long n = RSTRING_LEN(p); + VALUE p = RARRAY_AREF(load_path, i); + const char *s = StringValuePtr(p); + long n = RSTRING_LEN(p); - if (n != plen) continue; - if (n && strncmp(name, s, n)) continue; - return p; + if (n != plen) continue; + if (n && strncmp(name, s, n)) continue; + return p; } return 0; } @@ -455,7 +455,7 @@ loaded_feature_path_i(st_data_t v, st_data_t b, st_data_t f) const char *s = (const char *)v; struct loaded_feature_searching *fp = (struct loaded_feature_searching *)f; VALUE p = loaded_feature_path(s, strlen(s), fp->name, fp->len, - fp->type, fp->load_path); + fp->type, fp->load_path); if (!p) return ST_CONTINUE; fp->result = s; return ST_STOP; @@ -474,14 +474,14 @@ rb_feature_p(rb_vm_t *vm, const char *feature, const char *ext, int rb, int expa if (fn) *fn = 0; if (ext) { - elen = strlen(ext); - len = strlen(feature) - elen; - type = rb ? 'r' : 's'; + elen = strlen(ext); + len = strlen(feature) - elen; + type = rb ? 'r' : 's'; } else { - len = strlen(feature); - elen = 0; - type = 0; + len = strlen(feature); + elen = 0; + type = 0; } features = get_loaded_features(vm); features_index = get_loaded_features_index(vm); @@ -515,89 +515,89 @@ rb_feature_p(rb_vm_t *vm, const char *feature, const char *ext, int rb, int expa */ if (st_lookup(features_index, key, &data) && !NIL_P(this_feature_index = (VALUE)data)) { for (size_t i = 0; ; i++) { - long index; + long index; if (FIXNUM_P(this_feature_index)) { - if (i > 0) break; + if (i > 0) break; index = FIX2LONG(this_feature_index); - } + } else { feature_indexes_t feature_indexes = (feature_indexes_t)this_feature_index; if (i >= rb_darray_size(feature_indexes)) break; index = rb_darray_get(feature_indexes, i); } - v = RARRAY_AREF(features, index); - f = StringValuePtr(v); - if ((n = RSTRING_LEN(v)) < len) continue; - if (strncmp(f, feature, len) != 0) { - if (expanded) continue; - if (!load_path) load_path = get_expanded_load_path(vm); - if (!(p = loaded_feature_path(f, n, feature, len, type, load_path))) - continue; - expanded = 1; - f += RSTRING_LEN(p) + 1; - } - if (!*(e = f + len)) { - if (ext) continue; - return 'u'; - } - if (*e != '.') continue; - if ((!rb || !ext) && (IS_SOEXT(e) || IS_DLEXT(e))) { - return 's'; - } - if ((rb || !ext) && (IS_RBEXT(e))) { - return 'r'; - } - } + v = RARRAY_AREF(features, index); + f = StringValuePtr(v); + if ((n = RSTRING_LEN(v)) < len) continue; + if (strncmp(f, feature, len) != 0) { + if (expanded) continue; + if (!load_path) load_path = get_expanded_load_path(vm); + if (!(p = loaded_feature_path(f, n, feature, len, type, load_path))) + continue; + expanded = 1; + f += RSTRING_LEN(p) + 1; + } + if (!*(e = f + len)) { + if (ext) continue; + return 'u'; + } + if (*e != '.') continue; + if ((!rb || !ext) && (IS_SOEXT(e) || IS_DLEXT(e))) { + return 's'; + } + if ((rb || !ext) && (IS_RBEXT(e))) { + return 'r'; + } + } } loading_tbl = get_loading_table(vm); f = 0; if (!expanded) { - struct loaded_feature_searching fs; - fs.name = feature; - fs.len = len; - fs.type = type; - fs.load_path = load_path ? load_path : get_expanded_load_path(vm); - fs.result = 0; - st_foreach(loading_tbl, loaded_feature_path_i, (st_data_t)&fs); - if ((f = fs.result) != 0) { - if (fn) *fn = f; - goto loading; - } + struct loaded_feature_searching fs; + fs.name = feature; + fs.len = len; + fs.type = type; + fs.load_path = load_path ? load_path : get_expanded_load_path(vm); + fs.result = 0; + st_foreach(loading_tbl, loaded_feature_path_i, (st_data_t)&fs); + if ((f = fs.result) != 0) { + if (fn) *fn = f; + goto loading; + } } if (st_get_key(loading_tbl, (st_data_t)feature, &data)) { - if (fn) *fn = (const char*)data; + if (fn) *fn = (const char*)data; goto loading; } else { - VALUE bufstr; - char *buf; - static const char so_ext[][4] = { - ".so", ".o", - }; + VALUE bufstr; + char *buf; + static const char so_ext[][4] = { + ".so", ".o", + }; - if (ext && *ext) return 0; - bufstr = rb_str_tmp_new(len + DLEXT_MAXLEN); - buf = RSTRING_PTR(bufstr); - MEMCPY(buf, feature, char, len); - for (i = 0; (e = loadable_ext[i]) != 0; i++) { - strlcpy(buf + len, e, DLEXT_MAXLEN + 1); - if (st_get_key(loading_tbl, (st_data_t)buf, &data)) { - rb_str_resize(bufstr, 0); - if (fn) *fn = (const char*)data; - return i ? 's' : 'r'; - } - } - for (i = 0; i < numberof(so_ext); i++) { - strlcpy(buf + len, so_ext[i], DLEXT_MAXLEN + 1); - if (st_get_key(loading_tbl, (st_data_t)buf, &data)) { - rb_str_resize(bufstr, 0); - if (fn) *fn = (const char*)data; - return 's'; - } - } - rb_str_resize(bufstr, 0); + if (ext && *ext) return 0; + bufstr = rb_str_tmp_new(len + DLEXT_MAXLEN); + buf = RSTRING_PTR(bufstr); + MEMCPY(buf, feature, char, len); + for (i = 0; (e = loadable_ext[i]) != 0; i++) { + strlcpy(buf + len, e, DLEXT_MAXLEN + 1); + if (st_get_key(loading_tbl, (st_data_t)buf, &data)) { + rb_str_resize(bufstr, 0); + if (fn) *fn = (const char*)data; + return i ? 's' : 'r'; + } + } + for (i = 0; i < numberof(so_ext); i++) { + strlcpy(buf + len, so_ext[i], DLEXT_MAXLEN + 1); + if (st_get_key(loading_tbl, (st_data_t)buf, &data)) { + rb_str_resize(bufstr, 0); + if (fn) *fn = (const char*)data; + return 's'; + } + } + rb_str_resize(bufstr, 0); } return 0; @@ -619,22 +619,22 @@ feature_provided(rb_vm_t *vm, const char *feature, const char **loading) VALUE fullpath = 0; if (*feature == '.' && - (feature[1] == '/' || strncmp(feature+1, "./", 2) == 0)) { - fullpath = rb_file_expand_path_fast(rb_get_path(rb_str_new2(feature)), Qnil); - feature = RSTRING_PTR(fullpath); + (feature[1] == '/' || strncmp(feature+1, "./", 2) == 0)) { + fullpath = rb_file_expand_path_fast(rb_get_path(rb_str_new2(feature)), Qnil); + feature = RSTRING_PTR(fullpath); } if (ext && !strchr(ext, '/')) { - if (IS_RBEXT(ext)) { - if (rb_feature_p(vm, feature, ext, TRUE, FALSE, loading)) return TRUE; - return FALSE; - } - else if (IS_SOEXT(ext) || IS_DLEXT(ext)) { - if (rb_feature_p(vm, feature, ext, FALSE, FALSE, loading)) return TRUE; - return FALSE; - } + if (IS_RBEXT(ext)) { + if (rb_feature_p(vm, feature, ext, TRUE, FALSE, loading)) return TRUE; + return FALSE; + } + else if (IS_SOEXT(ext) || IS_DLEXT(ext)) { + if (rb_feature_p(vm, feature, ext, FALSE, FALSE, loading)) return TRUE; + return FALSE; + } } if (rb_feature_p(vm, feature, 0, TRUE, FALSE, loading)) - return TRUE; + return TRUE; RB_GC_GUARD(fullpath); return FALSE; } @@ -652,8 +652,8 @@ rb_provide_feature(rb_vm_t *vm, VALUE feature) features = get_loaded_features(vm); if (OBJ_FROZEN(features)) { - rb_raise(rb_eRuntimeError, - "$LOADED_FEATURES is frozen; cannot append feature"); + rb_raise(rb_eRuntimeError, + "$LOADED_FEATURES is frozen; cannot append feature"); } rb_str_freeze(feature); @@ -822,9 +822,9 @@ rb_f_load(int argc, VALUE *argv, VALUE _) path = rb_find_file(fname); if (!path) { - if (!rb_file_load_ok(RSTRING_PTR(fname))) - load_failed(orig_fname); - path = fname; + if (!rb_file_load_ok(RSTRING_PTR(fname))) + load_failed(orig_fname); + path = fname; } rb_load_internal(path, wrap); @@ -840,29 +840,29 @@ load_lock(rb_vm_t *vm, const char *ftptr, bool warn) st_table *loading_tbl = get_loading_table(vm); if (!st_lookup(loading_tbl, (st_data_t)ftptr, &data)) { - /* partial state */ - ftptr = ruby_strdup(ftptr); - data = (st_data_t)rb_thread_shield_new(); - st_insert(loading_tbl, (st_data_t)ftptr, data); - return (char *)ftptr; + /* partial state */ + ftptr = ruby_strdup(ftptr); + data = (st_data_t)rb_thread_shield_new(); + st_insert(loading_tbl, (st_data_t)ftptr, data); + return (char *)ftptr; } else if (imemo_type_p(data, imemo_memo)) { - struct MEMO *memo = MEMO_CAST(data); + struct MEMO *memo = MEMO_CAST(data); void (*init)(void) = memo->u3.func; - data = (st_data_t)rb_thread_shield_new(); - st_insert(loading_tbl, (st_data_t)ftptr, data); - (*init)(); - return (char *)""; + data = (st_data_t)rb_thread_shield_new(); + st_insert(loading_tbl, (st_data_t)ftptr, data); + (*init)(); + return (char *)""; } if (warn) { - VALUE warning = rb_warning_string("loading in progress, circular require considered harmful - %s", ftptr); - rb_backtrace_each(rb_str_append, warning); - rb_warning("%"PRIsVALUE, warning); + VALUE warning = rb_warning_string("loading in progress, circular require considered harmful - %s", ftptr); + rb_backtrace_each(rb_str_append, warning); + rb_warning("%"PRIsVALUE, warning); } switch (rb_thread_shield_wait((VALUE)data)) { case Qfalse: case Qnil: - return 0; + return 0; } return (char *)ftptr; } @@ -873,13 +873,13 @@ release_thread_shield(st_data_t *key, st_data_t *value, st_data_t done, int exis VALUE thread_shield = (VALUE)*value; if (!existing) return ST_STOP; if (done) { - rb_thread_shield_destroy(thread_shield); - /* Delete the entry even if there are waiting threads, because they - * won't load the file and won't delete the entry. */ + rb_thread_shield_destroy(thread_shield); + /* Delete the entry even if there are waiting threads, because they + * won't load the file and won't delete the entry. */ } else if (rb_thread_shield_release(thread_shield)) { - /* still in-use */ - return ST_CONTINUE; + /* still in-use */ + return ST_CONTINUE; } xfree((char *)*key); return ST_DELETE; @@ -889,10 +889,10 @@ static void load_unlock(rb_vm_t *vm, const char *ftptr, int done) { if (ftptr) { - st_data_t key = (st_data_t)ftptr; - st_table *loading_tbl = get_loading_table(vm); + st_data_t key = (st_data_t)ftptr; + st_table *loading_tbl = get_loading_table(vm); - st_update(loading_tbl, key, release_thread_shield, done); + st_update(loading_tbl, key, release_thread_shield, done); } } @@ -955,7 +955,7 @@ rb_f_require_relative(VALUE obj, VALUE fname) { VALUE base = rb_current_realfilepath(); if (NIL_P(base)) { - rb_loaderror("cannot infer basepath"); + rb_loaderror("cannot infer basepath"); } base = rb_file_dirname(base); return rb_require_string(rb_file_absolute_path(fname, base)); @@ -974,70 +974,70 @@ search_required(rb_vm_t *vm, VALUE fname, volatile VALUE *path, feature_func rb_ *path = 0; ext = strrchr(ftptr = RSTRING_PTR(fname), '.'); if (ext && !strchr(ext, '/')) { - if (IS_RBEXT(ext)) { - if (rb_feature_p(vm, ftptr, ext, TRUE, FALSE, &loading)) { - if (loading) *path = rb_filesystem_str_new_cstr(loading); - return 'r'; - } + if (IS_RBEXT(ext)) { + if (rb_feature_p(vm, ftptr, ext, TRUE, FALSE, &loading)) { + if (loading) *path = rb_filesystem_str_new_cstr(loading); + return 'r'; + } if ((tmp = rb_find_file(fname)) != 0) { - ext = strrchr(ftptr = RSTRING_PTR(tmp), '.'); - if (!rb_feature_p(vm, ftptr, ext, TRUE, TRUE, &loading) || loading) - *path = tmp; - return 'r'; - } - return 0; - } - else if (IS_SOEXT(ext)) { - if (rb_feature_p(vm, ftptr, ext, FALSE, FALSE, &loading)) { - if (loading) *path = rb_filesystem_str_new_cstr(loading); - return 's'; - } - tmp = rb_str_subseq(fname, 0, ext - RSTRING_PTR(fname)); - rb_str_cat2(tmp, DLEXT); - OBJ_FREEZE(tmp); + ext = strrchr(ftptr = RSTRING_PTR(tmp), '.'); + if (!rb_feature_p(vm, ftptr, ext, TRUE, TRUE, &loading) || loading) + *path = tmp; + return 'r'; + } + return 0; + } + else if (IS_SOEXT(ext)) { + if (rb_feature_p(vm, ftptr, ext, FALSE, FALSE, &loading)) { + if (loading) *path = rb_filesystem_str_new_cstr(loading); + return 's'; + } + tmp = rb_str_subseq(fname, 0, ext - RSTRING_PTR(fname)); + rb_str_cat2(tmp, DLEXT); + OBJ_FREEZE(tmp); if ((tmp = rb_find_file(tmp)) != 0) { - ext = strrchr(ftptr = RSTRING_PTR(tmp), '.'); - if (!rb_feature_p(vm, ftptr, ext, FALSE, TRUE, &loading) || loading) - *path = tmp; - return 's'; - } - } - else if (IS_DLEXT(ext)) { - if (rb_feature_p(vm, ftptr, ext, FALSE, FALSE, &loading)) { - if (loading) *path = rb_filesystem_str_new_cstr(loading); - return 's'; - } + ext = strrchr(ftptr = RSTRING_PTR(tmp), '.'); + if (!rb_feature_p(vm, ftptr, ext, FALSE, TRUE, &loading) || loading) + *path = tmp; + return 's'; + } + } + else if (IS_DLEXT(ext)) { + if (rb_feature_p(vm, ftptr, ext, FALSE, FALSE, &loading)) { + if (loading) *path = rb_filesystem_str_new_cstr(loading); + return 's'; + } if ((tmp = rb_find_file(fname)) != 0) { - ext = strrchr(ftptr = RSTRING_PTR(tmp), '.'); - if (!rb_feature_p(vm, ftptr, ext, FALSE, TRUE, &loading) || loading) - *path = tmp; - return 's'; - } - } + ext = strrchr(ftptr = RSTRING_PTR(tmp), '.'); + if (!rb_feature_p(vm, ftptr, ext, FALSE, TRUE, &loading) || loading) + *path = tmp; + return 's'; + } + } } else if ((ft = rb_feature_p(vm, ftptr, 0, FALSE, FALSE, &loading)) == 'r') { - if (loading) *path = rb_filesystem_str_new_cstr(loading); - return 'r'; + if (loading) *path = rb_filesystem_str_new_cstr(loading); + return 'r'; } tmp = fname; type = rb_find_file_ext(&tmp, ft == 's' ? ruby_ext : loadable_ext); switch (type) { case 0: - if (ft) - goto statically_linked; - ftptr = RSTRING_PTR(tmp); - return rb_feature_p(vm, ftptr, 0, FALSE, TRUE, 0); + if (ft) + goto statically_linked; + ftptr = RSTRING_PTR(tmp); + return rb_feature_p(vm, ftptr, 0, FALSE, TRUE, 0); default: - if (ft) { + if (ft) { goto statically_linked; - } + } /* fall through */ case 1: - ext = strrchr(ftptr = RSTRING_PTR(tmp), '.'); - if (rb_feature_p(vm, ftptr, ext, !--type, TRUE, &loading) && !loading) - break; - *path = tmp; + ext = strrchr(ftptr = RSTRING_PTR(tmp), '.'); + if (rb_feature_p(vm, ftptr, ext, !--type, TRUE, &loading) && !loading) + break; + *path = tmp; } return type ? 's' : 'r'; @@ -1145,42 +1145,42 @@ require_internal(rb_execution_context_t *ec, VALUE fname, int exception, bool wa ec->errinfo = Qnil; /* ensure */ th->top_wrapper = 0; if ((state = EC_EXEC_TAG()) == TAG_NONE) { - long handle; - int found; + long handle; + int found; - RUBY_DTRACE_HOOK(FIND_REQUIRE_ENTRY, RSTRING_PTR(fname)); + RUBY_DTRACE_HOOK(FIND_REQUIRE_ENTRY, RSTRING_PTR(fname)); found = search_required(th->vm, path, &saved_path, rb_feature_p); - RUBY_DTRACE_HOOK(FIND_REQUIRE_RETURN, RSTRING_PTR(fname)); + RUBY_DTRACE_HOOK(FIND_REQUIRE_RETURN, RSTRING_PTR(fname)); path = saved_path; - if (found) { + if (found) { if (!path || !(ftptr = load_lock(th->vm, RSTRING_PTR(path), warn))) { - result = 0; - } - else if (!*ftptr) { - result = TAG_RETURN; - } + result = 0; + } + else if (!*ftptr) { + result = TAG_RETURN; + } else if (RTEST(rb_hash_aref(realpaths, realpath = rb_realpath_internal(Qnil, path, 1)))) { result = 0; } - else { - switch (found) { - case 'r': + else { + switch (found) { + case 'r': load_iseq_eval(ec, path); - break; + break; - case 's': + case 's': reset_ext_config = true; ext_config_push(th, &prev_ext_config); - handle = (long)rb_vm_call_cfunc(rb_vm_top_self(), load_ext, - path, VM_BLOCK_HANDLER_NONE, path); - rb_ary_push(ruby_dln_librefs, LONG2NUM(handle)); - break; - } + handle = (long)rb_vm_call_cfunc(rb_vm_top_self(), load_ext, + path, VM_BLOCK_HANDLER_NONE, path); + rb_ary_push(ruby_dln_librefs, LONG2NUM(handle)); + break; + } result = TAG_RETURN; - } - } + } + } } EC_POP_TAG(); @@ -1206,9 +1206,9 @@ require_internal(rb_execution_context_t *ec, VALUE fname, int exception, bool wa else if (state == TAG_RETURN) { return TAG_RAISE; } - RB_GC_GUARD(fname); - /* never TAG_RETURN */ - return state; + RB_GC_GUARD(fname); + /* never TAG_RETURN */ + return state; } if (!NIL_P(ec->errinfo)) { if (!exception) return TAG_RAISE; @@ -1264,7 +1264,7 @@ rb_require_string(VALUE fname) EC_JUMP_TAG(ec, result); } if (result < 0) { - load_failed(fname); + load_failed(fname); } return RBOOL(result); @@ -1281,12 +1281,12 @@ register_init_ext(st_data_t *key, st_data_t *value, st_data_t init, int existing { const char *name = (char *)*key; if (existing) { - /* already registered */ - rb_warn("%s is already registered", name); + /* already registered */ + rb_warn("%s is already registered", name); } else { - *value = (st_data_t)MEMO_NEW(0, 0, init); - *key = (st_data_t)ruby_strdup(name); + *value = (st_data_t)MEMO_NEW(0, 0, init); + *key = (st_data_t)ruby_strdup(name); } return ST_CONTINUE; } @@ -1298,7 +1298,7 @@ ruby_init_ext(const char *name, void (*init)(void)) st_table *loading_tbl = get_loading_table(vm); if (feature_provided(vm, name, 0)) - return; + return; st_update(loading_tbl, (st_data_t)name, register_init_ext, (st_data_t)init); } @@ -1364,7 +1364,7 @@ rb_mod_autoload_p(int argc, VALUE *argv, VALUE mod) ID id = rb_check_id(&sym); if (!id) { - return Qnil; + return Qnil; } return rb_autoload_at_p(mod, id, recur); } @@ -1389,7 +1389,7 @@ rb_f_autoload(VALUE obj, VALUE sym, VALUE file) { VALUE klass = rb_class_real(rb_vm_cbase()); if (!klass) { - rb_raise(rb_eTypeError, "Can not set autoload on singleton class"); + rb_raise(rb_eTypeError, "Can not set autoload on singleton class"); } return rb_mod_autoload(klass, sym, file); } @@ -1411,7 +1411,7 @@ rb_f_autoload_p(int argc, VALUE *argv, VALUE obj) /* use rb_vm_cbase() as same as rb_f_autoload. */ VALUE klass = rb_vm_cbase(); if (NIL_P(klass)) { - return Qnil; + return Qnil; } return rb_mod_autoload_p(argc, argv, klass); } diff --git a/localeinit.c b/localeinit.c index 050b22350a..cea2e309f5 100644 --- a/localeinit.c +++ b/localeinit.c @@ -46,11 +46,11 @@ locale_charmap(VALUE (*conv)(const char *)) codeset = nl_langinfo_codeset(); # endif if (!codeset) { - UINT codepage = ruby_w32_codepage[0]; - if (!codepage) codepage = GetConsoleCP(); - if (!codepage) codepage = GetACP(); - CP_FORMAT(cp, codepage); - codeset = cp; + UINT codepage = ruby_w32_codepage[0]; + if (!codepage) codepage = GetConsoleCP(); + if (!codepage) codepage = GetACP(); + CP_FORMAT(cp, codepage); + codeset = cp; } #elif defined HAVE_LANGINFO_H codeset = nl_langinfo(CODESET); diff --git a/marshal.c b/marshal.c index 8267658f5c..3bca956a09 100644 --- a/marshal.c +++ b/marshal.c @@ -54,8 +54,8 @@ shortlen(size_t len, BDIGIT *ds) num = ds[len-1]; while (num) { - num = SHORTDN(num); - offset++; + num = SHORTDN(num); + offset++; } return (len - 1)*SIZEOF_BDIGIT/2 + offset; } @@ -184,20 +184,20 @@ check_dump_arg(VALUE ret, struct dump_arg *arg, const char *name) { if (!arg->symbols) { rb_raise(rb_eRuntimeError, "Marshal.dump reentered at %s", - name); + name); } return ret; } static VALUE check_userdump_arg(VALUE obj, ID sym, int argc, const VALUE *argv, - struct dump_arg *arg, const char *name) + struct dump_arg *arg, const char *name) { VALUE ret = rb_funcallv(obj, sym, argc, argv); VALUE klass = CLASS_OF(obj); if (CLASS_OF(ret) == klass) { rb_raise(rb_eRuntimeError, "%"PRIsVALUE"#%s returned same class instance", - klass, name); + klass, name); } return check_dump_arg(ret, arg, name); } @@ -246,13 +246,13 @@ must_not_be_anonymous(const char *type, VALUE path) char *n = RSTRING_PTR(path); if (!rb_enc_asciicompat(rb_enc_get(path))) { - /* cannot occur? */ - rb_raise(rb_eTypeError, "can't dump non-ascii %s name % "PRIsVALUE, - type, path); + /* cannot occur? */ + rb_raise(rb_eTypeError, "can't dump non-ascii %s name % "PRIsVALUE, + type, path); } if (n[0] == '#') { - rb_raise(rb_eTypeError, "can't dump anonymous %s % "PRIsVALUE, - type, path); + rb_raise(rb_eTypeError, "can't dump anonymous %s % "PRIsVALUE, + type, path); } return path; } @@ -264,7 +264,7 @@ class2path(VALUE klass) must_not_be_anonymous((RB_TYPE_P(klass, T_CLASS) ? "class" : "module"), path); if (rb_path_to_class(path) != rb_class_real(klass)) { - rb_raise(rb_eTypeError, "% "PRIsVALUE" can't be referred to", path); + rb_raise(rb_eTypeError, "% "PRIsVALUE" can't be referred to", path); } return path; } @@ -280,8 +280,8 @@ w_nbyte(const char *s, long n, struct dump_arg *arg) VALUE buf = arg->str; rb_str_buf_cat(buf, s, n); if (arg->dest && RSTRING_LEN(buf) >= BUFSIZ) { - rb_io_write(arg->dest, buf); - rb_str_resize(buf, 0); + rb_io_write(arg->dest, buf); + rb_str_resize(buf, 0); } } @@ -325,7 +325,7 @@ ruby_marshal_write_long(long x, char *buf) #if SIZEOF_LONG > 4 if (!(RSHIFT(x, 31) == 0 || RSHIFT(x, 31) == -1)) { - /* big long does not fit in 4 bytes */ + /* big long does not fit in 4 bytes */ return -1; } #endif @@ -343,16 +343,16 @@ ruby_marshal_write_long(long x, char *buf) return 1; } for (i=1;i<(int)sizeof(long)+1;i++) { - buf[i] = (char)(x & 0xff); - x = RSHIFT(x,8); - if (x == 0) { - buf[0] = i; - break; - } - if (x == -1) { - buf[0] = -i; - break; - } + buf[i] = (char)(x & 0xff); + x = RSHIFT(x,8); + if (x == 0) { + buf[0] = i; + break; + } + if (x == -1) { + buf[0] = -i; + break; + } } return i+1; } @@ -375,13 +375,13 @@ load_mantissa(double d, const char *buf, long len) { if (!len) return d; if (--len > 0 && !*buf++) { /* binary mantissa mark */ - int e, s = d < 0, dig = 0; - unsigned long m; + int e, s = d < 0, dig = 0; + unsigned long m; - modf(ldexp(frexp(fabs(d), &e), DECIMAL_MANT), &d); - do { - m = 0; - switch (len) { + modf(ldexp(frexp(fabs(d), &e), DECIMAL_MANT), &d); + do { + m = 0; + switch (len) { default: m = *buf++ & 0xff; /* fall through */ #if MANT_BITS > 24 case 3: m = (m << 8) | (*buf++ & 0xff); /* fall through */ @@ -390,14 +390,14 @@ load_mantissa(double d, const char *buf, long len) case 2: m = (m << 8) | (*buf++ & 0xff); /* fall through */ #endif #if MANT_BITS > 8 - case 1: m = (m << 8) | (*buf++ & 0xff); + case 1: m = (m << 8) | (*buf++ & 0xff); #endif - } - dig -= len < MANT_BITS / 8 ? 8 * (unsigned)len : MANT_BITS; - d += ldexp((double)m, dig); - } while ((len -= MANT_BITS / 8) > 0); - d = ldexp(d, e - DECIMAL_MANT); - if (s) d = -d; + } + dig -= len < MANT_BITS / 8 ? 8 * (unsigned)len : MANT_BITS; + d += ldexp((double)m, dig); + } while ((len -= MANT_BITS / 8) > 0); + d = ldexp(d, e - DECIMAL_MANT); + if (s) d = -d; } return d; } @@ -417,49 +417,49 @@ w_float(double d, struct dump_arg *arg) char buf[FLOAT_DIG + (DECIMAL_MANT + 7) / 8 + 10]; if (isinf(d)) { - if (d < 0) w_cstr("-inf", arg); - else w_cstr("inf", arg); + if (d < 0) w_cstr("-inf", arg); + else w_cstr("inf", arg); } else if (isnan(d)) { - w_cstr("nan", arg); + w_cstr("nan", arg); } else if (d == 0.0) { if (signbit(d)) w_cstr("-0", arg); else w_cstr("0", arg); } else { - int decpt, sign, digs, len = 0; - char *e, *p = ruby_dtoa(d, 0, 0, &decpt, &sign, &e); - if (sign) buf[len++] = '-'; - digs = (int)(e - p); - if (decpt < -3 || decpt > digs) { - buf[len++] = p[0]; - if (--digs > 0) buf[len++] = '.'; - memcpy(buf + len, p + 1, digs); - len += digs; - len += snprintf(buf + len, sizeof(buf) - len, "e%d", decpt - 1); - } - else if (decpt > 0) { - memcpy(buf + len, p, decpt); - len += decpt; - if ((digs -= decpt) > 0) { - buf[len++] = '.'; - memcpy(buf + len, p + decpt, digs); - len += digs; - } - } - else { - buf[len++] = '0'; - buf[len++] = '.'; - if (decpt) { - memset(buf + len, '0', -decpt); - len -= decpt; - } - memcpy(buf + len, p, digs); - len += digs; - } - xfree(p); - w_bytes(buf, len, arg); + int decpt, sign, digs, len = 0; + char *e, *p = ruby_dtoa(d, 0, 0, &decpt, &sign, &e); + if (sign) buf[len++] = '-'; + digs = (int)(e - p); + if (decpt < -3 || decpt > digs) { + buf[len++] = p[0]; + if (--digs > 0) buf[len++] = '.'; + memcpy(buf + len, p + 1, digs); + len += digs; + len += snprintf(buf + len, sizeof(buf) - len, "e%d", decpt - 1); + } + else if (decpt > 0) { + memcpy(buf + len, p, decpt); + len += decpt; + if ((digs -= decpt) > 0) { + buf[len++] = '.'; + memcpy(buf + len, p + decpt, digs); + len += digs; + } + } + else { + buf[len++] = '0'; + buf[len++] = '.'; + if (decpt) { + memset(buf + len, '0', -decpt); + len -= decpt; + } + memcpy(buf + len, p, digs); + len += digs; + } + xfree(p); + w_bytes(buf, len, arg); } } @@ -470,33 +470,33 @@ w_symbol(VALUE sym, struct dump_arg *arg) VALUE encname; if (st_lookup(arg->symbols, sym, &num)) { - w_byte(TYPE_SYMLINK, arg); - w_long((long)num, arg); + w_byte(TYPE_SYMLINK, arg); + w_long((long)num, arg); } else { - const VALUE orig_sym = sym; - sym = rb_sym2str(sym); - if (!sym) { - rb_raise(rb_eTypeError, "can't dump anonymous ID %"PRIdVALUE, sym); - } - encname = encoding_name(sym, arg); - if (NIL_P(encname) || - is_ascii_string(sym)) { - encname = Qnil; - } - else { - w_byte(TYPE_IVAR, arg); - } - w_byte(TYPE_SYMBOL, arg); - w_bytes(RSTRING_PTR(sym), RSTRING_LEN(sym), arg); - st_add_direct(arg->symbols, orig_sym, arg->symbols->num_entries); - if (!NIL_P(encname)) { - struct dump_call_arg c_arg; - c_arg.limit = 1; - c_arg.arg = arg; - w_long(1L, arg); - w_encoding(encname, &c_arg); - } + const VALUE orig_sym = sym; + sym = rb_sym2str(sym); + if (!sym) { + rb_raise(rb_eTypeError, "can't dump anonymous ID %"PRIdVALUE, sym); + } + encname = encoding_name(sym, arg); + if (NIL_P(encname) || + is_ascii_string(sym)) { + encname = Qnil; + } + else { + w_byte(TYPE_IVAR, arg); + } + w_byte(TYPE_SYMBOL, arg); + w_bytes(RSTRING_PTR(sym), RSTRING_LEN(sym), arg); + st_add_direct(arg->symbols, orig_sym, arg->symbols->num_entries); + if (!NIL_P(encname)) { + struct dump_call_arg c_arg; + c_arg.limit = 1; + c_arg.arg = arg; + w_long(1L, arg); + w_encoding(encname, &c_arg); + } } } @@ -526,12 +526,12 @@ static void w_extended(VALUE klass, struct dump_arg *arg, int check) { if (check && FL_TEST(klass, FL_SINGLETON)) { - VALUE origin = RCLASS_ORIGIN(klass); - if (SINGLETON_DUMP_UNABLE_P(klass) || - (origin != klass && SINGLETON_DUMP_UNABLE_P(origin))) { - rb_raise(rb_eTypeError, "singleton can't be dumped"); - } - klass = RCLASS_SUPER(klass); + VALUE origin = RCLASS_ORIGIN(klass); + if (SINGLETON_DUMP_UNABLE_P(klass) || + (origin != klass && SINGLETON_DUMP_UNABLE_P(origin))) { + rb_raise(rb_eTypeError, "singleton can't be dumped"); + } + klass = RCLASS_SUPER(klass); } while (BUILTIN_TYPE(klass) == T_ICLASS) { if (!FL_TEST(klass, RICLASS_IS_ORIGIN) || @@ -552,7 +552,7 @@ w_class(char type, VALUE obj, struct dump_arg *arg, int check) VALUE klass; if (arg->compat_tbl && - st_lookup(arg->compat_tbl, (st_data_t)obj, &real_obj)) { + st_lookup(arg->compat_tbl, (st_data_t)obj, &real_obj)) { obj = (VALUE)real_obj; } klass = CLASS_OF(obj); @@ -570,8 +570,8 @@ w_uclass(VALUE obj, VALUE super, struct dump_arg *arg) w_extended(klass, arg, TRUE); klass = rb_class_real(klass); if (klass != super) { - w_byte(TYPE_UCLASS, arg); - w_unique(class2path(klass), arg); + w_byte(TYPE_UCLASS, arg); + w_unique(class2path(klass), arg); } } @@ -682,7 +682,7 @@ w_encoding(VALUE encname, struct dump_call_arg *arg) case Qfalse: case Qtrue: w_symbol(ID2SYM(s_encoding_short), arg->arg); - w_object(encname, arg->arg, limit); + w_object(encname, arg->arg, limit); return 1; case Qnil: return 0; @@ -702,14 +702,14 @@ has_ivars(VALUE obj, VALUE encname, VALUE *ivobj) case T_OBJECT: case T_CLASS: case T_MODULE: - break; /* counted elsewhere */ + break; /* counted elsewhere */ case T_HASH: if (rb_hash_ruby2_keywords_p(obj)) ++num; /* fall through */ default: generic: - rb_ivar_foreach(obj, obj_count_ivars, (st_data_t)&num); - if (num) *ivobj = obj; + rb_ivar_foreach(obj, obj_count_ivars, (st_data_t)&num); + if (num) *ivobj = obj; } return num; @@ -736,7 +736,7 @@ w_ivar(st_index_t num, VALUE ivobj, VALUE encname, struct dump_call_arg *arg) int limit = arg->limit; if (limit >= 0) ++limit; w_symbol(ID2SYM(s_ruby2_keywords_flag), arg->arg); - w_object(Qtrue, arg->arg, limit); + w_object(Qtrue, arg->arg, limit); num--; } if (ivobj != Qundef && num) { @@ -764,7 +764,7 @@ w_object(VALUE obj, struct dump_arg *arg, int limit) VALUE encname = Qnil; if (limit == 0) { - rb_raise(rb_eArgError, "exceed depth limit"); + rb_raise(rb_eArgError, "exceed depth limit"); } if (limit > 0) limit--; @@ -773,88 +773,88 @@ w_object(VALUE obj, struct dump_arg *arg, int limit) c_arg.obj = obj; if (st_lookup(arg->data, obj, &num)) { - w_byte(TYPE_LINK, arg); - w_long((long)num, arg); - return; + w_byte(TYPE_LINK, arg); + w_long((long)num, arg); + return; } if (NIL_P(obj)) { - w_byte(TYPE_NIL, arg); + w_byte(TYPE_NIL, arg); } else if (obj == Qtrue) { - w_byte(TYPE_TRUE, arg); + w_byte(TYPE_TRUE, arg); } else if (obj == Qfalse) { - w_byte(TYPE_FALSE, arg); + w_byte(TYPE_FALSE, arg); } else if (FIXNUM_P(obj)) { #if SIZEOF_LONG <= 4 - w_byte(TYPE_FIXNUM, arg); - w_long(FIX2INT(obj), arg); + w_byte(TYPE_FIXNUM, arg); + w_long(FIX2INT(obj), arg); #else - if (RSHIFT((long)obj, 31) == 0 || RSHIFT((long)obj, 31) == -1) { - w_byte(TYPE_FIXNUM, arg); - w_long(FIX2LONG(obj), arg); - } - else { - w_object(rb_int2big(FIX2LONG(obj)), arg, limit); - } + if (RSHIFT((long)obj, 31) == 0 || RSHIFT((long)obj, 31) == -1) { + w_byte(TYPE_FIXNUM, arg); + w_long(FIX2LONG(obj), arg); + } + else { + w_object(rb_int2big(FIX2LONG(obj)), arg, limit); + } #endif } else if (SYMBOL_P(obj)) { - w_symbol(obj, arg); + w_symbol(obj, arg); } else if (FLONUM_P(obj)) { - st_add_direct(arg->data, obj, arg->data->num_entries); - w_byte(TYPE_FLOAT, arg); - w_float(RFLOAT_VALUE(obj), arg); + st_add_direct(arg->data, obj, arg->data->num_entries); + w_byte(TYPE_FLOAT, arg); + w_float(RFLOAT_VALUE(obj), arg); } else { - VALUE v; + VALUE v; - if (!RBASIC_CLASS(obj)) { - rb_raise(rb_eTypeError, "can't dump internal %s", - rb_builtin_type_name(BUILTIN_TYPE(obj))); - } + if (!RBASIC_CLASS(obj)) { + rb_raise(rb_eTypeError, "can't dump internal %s", + rb_builtin_type_name(BUILTIN_TYPE(obj))); + } - if (rb_obj_respond_to(obj, s_mdump, TRUE)) { - st_add_direct(arg->data, obj, arg->data->num_entries); - - v = dump_funcall(arg, obj, s_mdump, 0, 0); - w_class(TYPE_USRMARSHAL, obj, arg, FALSE); - w_object(v, arg, limit); - return; - } - if (rb_obj_respond_to(obj, s_dump, TRUE)) { - VALUE ivobj2 = Qundef; - st_index_t hasiv2; - VALUE encname2; - - v = INT2NUM(limit); - v = dump_funcall(arg, obj, s_dump, 1, &v); - if (!RB_TYPE_P(v, T_STRING)) { - rb_raise(rb_eTypeError, "_dump() must return string"); - } - hasiv = has_ivars(obj, (encname = encoding_name(obj, arg)), &ivobj); - hasiv2 = has_ivars(v, (encname2 = encoding_name(v, arg)), &ivobj2); - if (hasiv2) { - hasiv = hasiv2; - ivobj = ivobj2; - encname = encname2; - } - if (hasiv) w_byte(TYPE_IVAR, arg); - w_class(TYPE_USERDEF, obj, arg, FALSE); - w_bytes(RSTRING_PTR(v), RSTRING_LEN(v), arg); - if (hasiv) { - w_ivar(hasiv, ivobj, encname, &c_arg); - } + if (rb_obj_respond_to(obj, s_mdump, TRUE)) { st_add_direct(arg->data, obj, arg->data->num_entries); - return; - } + + v = dump_funcall(arg, obj, s_mdump, 0, 0); + w_class(TYPE_USRMARSHAL, obj, arg, FALSE); + w_object(v, arg, limit); + return; + } + if (rb_obj_respond_to(obj, s_dump, TRUE)) { + VALUE ivobj2 = Qundef; + st_index_t hasiv2; + VALUE encname2; + + v = INT2NUM(limit); + v = dump_funcall(arg, obj, s_dump, 1, &v); + if (!RB_TYPE_P(v, T_STRING)) { + rb_raise(rb_eTypeError, "_dump() must return string"); + } + hasiv = has_ivars(obj, (encname = encoding_name(obj, arg)), &ivobj); + hasiv2 = has_ivars(v, (encname2 = encoding_name(v, arg)), &ivobj2); + if (hasiv2) { + hasiv = hasiv2; + ivobj = ivobj2; + encname = encname2; + } + if (hasiv) w_byte(TYPE_IVAR, arg); + w_class(TYPE_USERDEF, obj, arg, FALSE); + w_bytes(RSTRING_PTR(v), RSTRING_LEN(v), arg); + if (hasiv) { + w_ivar(hasiv, ivobj, encname, &c_arg); + } + st_add_direct(arg->data, obj, arg->data->num_entries); + return; + } st_add_direct(arg->data, obj, arg->data->num_entries); - hasiv = has_ivars(obj, (encname = encoding_name(obj, arg)), &ivobj); + hasiv = has_ivars(obj, (encname = encoding_name(obj, arg)), &ivobj); { st_data_t compat_data; rb_alloc_func_t allocator = rb_get_alloc_func(RBASIC(obj)->klass); @@ -868,79 +868,79 @@ w_object(VALUE obj, struct dump_arg *arg, int limit) arg->compat_tbl = rb_init_identtable(); } st_insert(arg->compat_tbl, (st_data_t)obj, (st_data_t)real_obj); - if (obj != real_obj && ivobj == Qundef) hasiv = 0; + if (obj != real_obj && ivobj == Qundef) hasiv = 0; } } - if (hasiv) w_byte(TYPE_IVAR, arg); + if (hasiv) w_byte(TYPE_IVAR, arg); - switch (BUILTIN_TYPE(obj)) { - case T_CLASS: - if (FL_TEST(obj, FL_SINGLETON)) { - rb_raise(rb_eTypeError, "singleton class can't be dumped"); - } - w_byte(TYPE_CLASS, arg); - { - VALUE path = class2path(obj); - w_bytes(RSTRING_PTR(path), RSTRING_LEN(path), arg); - RB_GC_GUARD(path); - } - break; + switch (BUILTIN_TYPE(obj)) { + case T_CLASS: + if (FL_TEST(obj, FL_SINGLETON)) { + rb_raise(rb_eTypeError, "singleton class can't be dumped"); + } + w_byte(TYPE_CLASS, arg); + { + VALUE path = class2path(obj); + w_bytes(RSTRING_PTR(path), RSTRING_LEN(path), arg); + RB_GC_GUARD(path); + } + break; - case T_MODULE: - w_byte(TYPE_MODULE, arg); - { - VALUE path = class2path(obj); - w_bytes(RSTRING_PTR(path), RSTRING_LEN(path), arg); - RB_GC_GUARD(path); - } - break; + case T_MODULE: + w_byte(TYPE_MODULE, arg); + { + VALUE path = class2path(obj); + w_bytes(RSTRING_PTR(path), RSTRING_LEN(path), arg); + RB_GC_GUARD(path); + } + break; - case T_FLOAT: - w_byte(TYPE_FLOAT, arg); - w_float(RFLOAT_VALUE(obj), arg); - break; + case T_FLOAT: + w_byte(TYPE_FLOAT, arg); + w_float(RFLOAT_VALUE(obj), arg); + break; - case T_BIGNUM: - w_byte(TYPE_BIGNUM, arg); - { - char sign = BIGNUM_SIGN(obj) ? '+' : '-'; - size_t len = BIGNUM_LEN(obj); - size_t slen; + case T_BIGNUM: + w_byte(TYPE_BIGNUM, arg); + { + char sign = BIGNUM_SIGN(obj) ? '+' : '-'; + size_t len = BIGNUM_LEN(obj); + size_t slen; size_t j; - BDIGIT *d = BIGNUM_DIGITS(obj); + BDIGIT *d = BIGNUM_DIGITS(obj); slen = SHORTLEN(len); if (LONG_MAX < slen) { rb_raise(rb_eTypeError, "too big Bignum can't be dumped"); } - w_byte(sign, arg); - w_long((long)slen, arg); + w_byte(sign, arg); + w_long((long)slen, arg); for (j = 0; j < len; j++) { #if SIZEOF_BDIGIT > SIZEOF_SHORT - BDIGIT num = *d; - int i; + BDIGIT num = *d; + int i; - for (i=0; idata); arg->data = 0; if (arg->compat_tbl) { - st_free_table(arg->compat_tbl); - arg->compat_tbl = 0; + st_free_table(arg->compat_tbl); + arg->compat_tbl = 0; } if (arg->encodings) { - st_free_table(arg->encodings); - arg->encodings = 0; + st_free_table(arg->encodings); + arg->encodings = 0; } } @@ -1104,14 +1104,14 @@ marshal_dump(int argc, VALUE *argv, VALUE _) port = Qnil; rb_scan_args(argc, argv, "12", &obj, &a1, &a2); if (argc == 3) { - if (!NIL_P(a2)) limit = NUM2INT(a2); - if (NIL_P(a1)) io_needed(); - port = a1; + if (!NIL_P(a2)) limit = NUM2INT(a2); + if (NIL_P(a1)) io_needed(); + port = a1; } else if (argc == 2) { - if (FIXNUM_P(a1)) limit = FIX2INT(a1); - else if (NIL_P(a1)) io_needed(); - else port = a1; + if (FIXNUM_P(a1)) limit = FIX2INT(a1); + else if (NIL_P(a1)) io_needed(); + else port = a1; } return rb_marshal_dump_limited(obj, port, limit); } @@ -1130,14 +1130,14 @@ rb_marshal_dump_limited(VALUE obj, VALUE port, int limit) arg->encodings = 0; arg->str = rb_str_buf_new(0); if (!NIL_P(port)) { - if (!rb_respond_to(port, s_write)) { - io_needed(); - } - arg->dest = port; - dump_check_funcall(arg, port, s_binmode, 0, 0); + if (!rb_respond_to(port, s_write)) { + io_needed(); + } + arg->dest = port; + dump_check_funcall(arg, port, s_binmode, 0, 0); } else { - port = arg->str; + port = arg->str; } w_byte(MARSHAL_MAJOR, arg); @@ -1145,8 +1145,8 @@ rb_marshal_dump_limited(VALUE obj, VALUE port, int limit) w_object(obj, arg, limit); if (arg->dest) { - rb_io_write(arg->dest, arg->str); - rb_str_resize(arg->str, 0); + rb_io_write(arg->dest, arg->str); + rb_str_resize(arg->str, 0); } clear_dump_arg(arg); RB_GC_GUARD(wrapper); @@ -1173,7 +1173,7 @@ check_load_arg(VALUE ret, struct load_arg *arg, const char *name) { if (!arg->symbols) { rb_raise(rb_eRuntimeError, "Marshal.load reentered at %s", - name); + name); } return ret; } @@ -1237,15 +1237,15 @@ static unsigned char r_byte1_buffered(struct load_arg *arg) { if (arg->buflen == 0) { - long readable = arg->readable < BUFSIZ ? arg->readable : BUFSIZ; - VALUE str, n = LONG2NUM(readable); + long readable = arg->readable < BUFSIZ ? arg->readable : BUFSIZ; + VALUE str, n = LONG2NUM(readable); - str = load_funcall(arg, arg->src, s_read, 1, &n); - if (NIL_P(str)) too_short(); - StringValue(str); - memcpy(arg->buf, RSTRING_PTR(str), RSTRING_LEN(str)); - arg->offset = 0; - arg->buflen = RSTRING_LEN(str); + str = load_funcall(arg, arg->src, s_read, 1, &n); + if (NIL_P(str)) too_short(); + StringValue(str); + memcpy(arg->buf, RSTRING_PTR(str), RSTRING_LEN(str)); + arg->offset = 0; + arg->buflen = RSTRING_LEN(str); } arg->buflen--; return arg->buf[arg->offset++]; @@ -1257,22 +1257,22 @@ r_byte(struct load_arg *arg) int c; if (RB_TYPE_P(arg->src, T_STRING)) { - if (RSTRING_LEN(arg->src) > arg->offset) { - c = (unsigned char)RSTRING_PTR(arg->src)[arg->offset++]; - } - else { - too_short(); - } + if (RSTRING_LEN(arg->src) > arg->offset) { + c = (unsigned char)RSTRING_PTR(arg->src)[arg->offset++]; + } + else { + too_short(); + } } else { - if (arg->readable >0 || arg->buflen > 0) { - c = r_byte1_buffered(arg); - } - else { - VALUE v = load_funcall(arg, arg->src, s_getbyte, 0, 0); - if (NIL_P(v)) rb_eof_error(); - c = (unsigned char)NUM2CHR(v); - } + if (arg->readable >0 || arg->buflen > 0) { + c = r_byte1_buffered(arg); + } + else { + VALUE v = load_funcall(arg, arg->src, s_getbyte, 0, 0); + if (NIL_P(v)) rb_eof_error(); + c = (unsigned char)NUM2CHR(v); + } } return c; } @@ -1283,7 +1283,7 @@ static void long_toobig(int size) { rb_raise(rb_eTypeError, "long too big for this architecture (size " - STRINGIZE(SIZEOF_LONG)", given %d)", size); + STRINGIZE(SIZEOF_LONG)", given %d)", size); } static long @@ -1295,26 +1295,26 @@ r_long(struct load_arg *arg) if (c == 0) return 0; if (c > 0) { - if (4 < c && c < 128) { - return c - 5; - } - if (c > (int)sizeof(long)) long_toobig(c); - x = 0; - for (i=0;i (int)sizeof(long)) long_toobig(c); + x = 0; + for (i=0;i (int)sizeof(long)) long_toobig(c); - x = -1; - for (i=0;i (int)sizeof(long)) long_toobig(c); + x = -1; + for (i=0;ibuflen) { - str = rb_str_new(arg->buf+arg->offset, len); - arg->offset += len; - arg->buflen -= len; + str = rb_str_new(arg->buf+arg->offset, len); + arg->offset += len; + arg->buflen -= len; } else { - long buflen = arg->buflen; - long readable = arg->readable + 1; - long tmp_len, read_len, need_len = len - buflen; - VALUE tmp, n; + long buflen = arg->buflen; + long readable = arg->readable + 1; + long tmp_len, read_len, need_len = len - buflen; + VALUE tmp, n; - readable = readable < BUFSIZ ? readable : BUFSIZ; - read_len = need_len > readable ? need_len : readable; - n = LONG2NUM(read_len); - tmp = load_funcall(arg, arg->src, s_read, 1, &n); - if (NIL_P(tmp)) too_short(); - StringValue(tmp); + readable = readable < BUFSIZ ? readable : BUFSIZ; + read_len = need_len > readable ? need_len : readable; + n = LONG2NUM(read_len); + tmp = load_funcall(arg, arg->src, s_read, 1, &n); + if (NIL_P(tmp)) too_short(); + StringValue(tmp); - tmp_len = RSTRING_LEN(tmp); + tmp_len = RSTRING_LEN(tmp); - if (tmp_len < need_len) too_short(); + if (tmp_len < need_len) too_short(); - str = rb_str_new(arg->buf+arg->offset, buflen); - rb_str_cat(str, RSTRING_PTR(tmp), need_len); + str = rb_str_new(arg->buf+arg->offset, buflen); + rb_str_cat(str, RSTRING_PTR(tmp), need_len); - if (tmp_len > need_len) { - buflen = tmp_len - need_len; - memcpy(arg->buf, RSTRING_PTR(tmp)+need_len, buflen); - arg->buflen = buflen; - } - else { - arg->buflen = 0; - } - arg->offset = 0; + if (tmp_len > need_len) { + buflen = tmp_len - need_len; + memcpy(arg->buf, RSTRING_PTR(tmp)+need_len, buflen); + arg->buflen = buflen; + } + else { + arg->buflen = 0; + } + arg->offset = 0; } return str; @@ -1398,21 +1398,21 @@ r_bytes0(long len, struct load_arg *arg) if (len == 0) return rb_str_new(0, 0); if (RB_TYPE_P(arg->src, T_STRING)) { - if (RSTRING_LEN(arg->src) - arg->offset >= len) { - str = rb_str_new(RSTRING_PTR(arg->src)+arg->offset, len); - arg->offset += len; - } - else { - too_short(); - } + if (RSTRING_LEN(arg->src) - arg->offset >= len) { + str = rb_str_new(RSTRING_PTR(arg->src)+arg->offset, len); + arg->offset += len; + } + else { + too_short(); + } } else { - if (arg->readable > 0 || arg->buflen > 0) { - str = r_bytes1_buffered(len, arg); - } - else { - str = r_bytes1(len, arg); - } + if (arg->readable > 0 || arg->buflen > 0) { + str = r_bytes1_buffered(len, arg); + } + else { + str = r_bytes1(len, arg); + } } return str; } @@ -1434,13 +1434,13 @@ sym2encidx(VALUE sym, VALUE val) RSTRING_GETMEM(sym, p, l); if (l <= 0) return -1; if (name_equal(name_encoding, sizeof(name_encoding), p, l)) { - int idx = rb_enc_find_index(StringValueCStr(val)); - return idx; + int idx = rb_enc_find_index(StringValueCStr(val)); + return idx; } if (name_equal(name_s_encoding_short, rb_strlen_lit(name_s_encoding_short), p, l)) { - if (val == Qfalse) return rb_usascii_encindex(); - else if (val == Qtrue) return rb_utf8_encindex(); - /* bogus ignore */ + if (val == Qfalse) return rb_usascii_encindex(); + else if (val == Qtrue) return rb_utf8_encindex(); + /* bogus ignore */ } return -1; } @@ -1468,7 +1468,7 @@ r_symlink(struct load_arg *arg) long num = r_long(arg); if (!st_lookup(arg->symbols, num, &sym)) { - rb_raise(rb_eArgError, "bad symbol"); + rb_raise(rb_eArgError, "bad symbol"); } return (VALUE)sym; } @@ -1484,11 +1484,11 @@ r_symreal(struct load_arg *arg, int ivar) if (rb_enc_str_asciionly_p(s)) rb_enc_associate_index(s, ENCINDEX_US_ASCII); st_insert(arg->symbols, (st_data_t)n, (st_data_t)s); if (ivar) { - long num = r_long(arg); - while (num-- > 0) { - sym = r_symbol(arg); - idx = sym2encidx(sym, r_object(arg)); - } + long num = r_long(arg); + while (num-- > 0) { + sym = r_symbol(arg); + idx = sym2encidx(sym, r_object(arg)); + } } if (idx > 0) { rb_enc_associate_index(s, idx); @@ -1509,17 +1509,17 @@ r_symbol(struct load_arg *arg) again: switch ((type = r_byte(arg))) { default: - rb_raise(rb_eArgError, "dump format error for symbol(0x%x)", type); + rb_raise(rb_eArgError, "dump format error for symbol(0x%x)", type); case TYPE_IVAR: - ivar = 1; - goto again; + ivar = 1; + goto again; case TYPE_SYMBOL: - return r_symreal(arg, ivar); + return r_symreal(arg, ivar); case TYPE_SYMLINK: - if (ivar) { - rb_raise(rb_eArgError, "dump format error (symlink with encoding)"); - } - return r_symlink(arg); + if (ivar) { + rb_raise(rb_eArgError, "dump format error (symlink with encoding)"); + } + return r_symlink(arg); } } @@ -1569,7 +1569,7 @@ static VALUE r_post_proc(VALUE v, struct load_arg *arg) { if (arg->proc) { - v = load_funcall(arg, arg->proc, s_call, 1, &v); + v = load_funcall(arg, arg->proc, s_call, 1, &v); } return v; } @@ -1579,21 +1579,21 @@ r_leave(VALUE v, struct load_arg *arg, bool partial) { v = r_fixup_compat(v, arg); if (!partial) { - st_data_t data; - st_data_t key = (st_data_t)v; - st_delete(arg->partial_objects, &key, &data); - if (arg->freeze) { - if (RB_TYPE_P(v, T_MODULE) || RB_TYPE_P(v, T_CLASS)) { - // noop - } - else if (RB_TYPE_P(v, T_STRING)) { - v = rb_str_to_interned_str(v); - } - else { - OBJ_FREEZE(v); - } + st_data_t data; + st_data_t key = (st_data_t)v; + st_delete(arg->partial_objects, &key, &data); + if (arg->freeze) { + if (RB_TYPE_P(v, T_MODULE) || RB_TYPE_P(v, T_CLASS)) { + // noop + } + else if (RB_TYPE_P(v, T_STRING)) { + v = rb_str_to_interned_str(v); + } + else { + OBJ_FREEZE(v); + } } - v = r_post_proc(v, arg); + v = r_post_proc(v, arg); } return v; } @@ -1605,7 +1605,7 @@ copy_ivar_i(st_data_t key, st_data_t val, st_data_t arg) ID vid = (ID)key; if (!rb_ivar_defined(obj, vid)) - rb_ivar_set(obj, vid, value); + rb_ivar_set(obj, vid, value); return ST_CONTINUE; } @@ -1623,20 +1623,20 @@ r_ivar(VALUE obj, int *has_encoding, struct load_arg *arg) len = r_long(arg); if (len > 0) { - do { - VALUE sym = r_symbol(arg); - VALUE val = r_object(arg); - int idx = sym2encidx(sym, val); - if (idx >= 0) { + do { + VALUE sym = r_symbol(arg); + VALUE val = r_object(arg); + int idx = sym2encidx(sym, val); + if (idx >= 0) { if (rb_enc_capable(obj)) { rb_enc_associate_index(obj, idx); } else { rb_raise(rb_eArgError, "%"PRIsVALUE" is not enc_capable", obj); } - if (has_encoding) *has_encoding = TRUE; - } - else if (symname_equal_lit(sym, name_s_ruby2_keywords_flag)) { + if (has_encoding) *has_encoding = TRUE; + } + else if (symname_equal_lit(sym, name_s_ruby2_keywords_flag)) { if (RB_TYPE_P(obj, T_HASH)) { rb_hash_ruby2_keywords(obj); } @@ -1646,8 +1646,8 @@ r_ivar(VALUE obj, int *has_encoding, struct load_arg *arg) } else { rb_ivar_set(obj, rb_intern_str(sym), val); - } - } while (--len > 0); + } + } while (--len > 0); } } @@ -1657,7 +1657,7 @@ path2class(VALUE path) VALUE v = rb_path_to_class(path); if (!RB_TYPE_P(v, T_CLASS)) { - rb_raise(rb_eArgError, "%"PRIsVALUE" does not refer to class", path); + rb_raise(rb_eArgError, "%"PRIsVALUE" does not refer to class", path); } return v; } @@ -1668,7 +1668,7 @@ static VALUE must_be_module(VALUE v, VALUE path) { if (!RB_TYPE_P(v, T_MODULE)) { - rb_raise(rb_eArgError, "%"PRIsVALUE" does not refer to module", path); + rb_raise(rb_eArgError, "%"PRIsVALUE" does not refer to module", path); } return v; } @@ -1684,7 +1684,7 @@ obj_alloc_by_klass(VALUE klass, struct load_arg *arg, VALUE *oldclass) marshal_compat_t *compat = (marshal_compat_t*)data; VALUE real_obj = rb_obj_alloc(klass); VALUE obj = rb_obj_alloc(compat->oldclass); - if (oldclass) *oldclass = compat->oldclass; + if (oldclass) *oldclass = compat->oldclass; if (!arg->compat_tbl) { arg->compat_tbl = rb_init_identtable(); @@ -1707,17 +1707,17 @@ append_extmod(VALUE obj, VALUE extmod) { long i = RARRAY_LEN(extmod); while (i > 0) { - VALUE m = RARRAY_AREF(extmod, --i); - rb_extend_object(obj, m); + VALUE m = RARRAY_AREF(extmod, --i); + rb_extend_object(obj, m); } return obj; } #define prohibit_ivar(type, str) do { \ - if (!ivp || !*ivp) break; \ - rb_raise(rb_eTypeError, \ - "can't override instance variable of "type" `%"PRIsVALUE"'", \ - (str)); \ + if (!ivp || !*ivp) break; \ + rb_raise(rb_eTypeError, \ + "can't override instance variable of "type" `%"PRIsVALUE"'", \ + (str)); \ } while (0) static VALUE r_object_for(struct load_arg *arg, bool partial, int *ivp, VALUE extmod, int type); @@ -1739,437 +1739,437 @@ r_object_for(struct load_arg *arg, bool partial, int *ivp, VALUE extmod, int typ switch (type) { case TYPE_LINK: - id = r_long(arg); - if (!st_lookup(arg->data, (st_data_t)id, &link)) { - rb_raise(rb_eArgError, "dump format error (unlinked)"); - } - v = (VALUE)link; - if (!st_lookup(arg->partial_objects, (st_data_t)v, &link)) { - v = r_post_proc(v, arg); - } - break; + id = r_long(arg); + if (!st_lookup(arg->data, (st_data_t)id, &link)) { + rb_raise(rb_eArgError, "dump format error (unlinked)"); + } + v = (VALUE)link; + if (!st_lookup(arg->partial_objects, (st_data_t)v, &link)) { + v = r_post_proc(v, arg); + } + break; case TYPE_IVAR: { - int ivar = TRUE; + int ivar = TRUE; - v = r_object0(arg, true, &ivar, extmod); - if (ivar) r_ivar(v, NULL, arg); - v = r_leave(v, arg, partial); - } - break; + v = r_object0(arg, true, &ivar, extmod); + if (ivar) r_ivar(v, NULL, arg); + v = r_leave(v, arg, partial); + } + break; case TYPE_EXTENDED: - { - VALUE path = r_unique(arg); - VALUE m = rb_path_to_class(path); - if (NIL_P(extmod)) extmod = rb_ary_tmp_new(0); + { + VALUE path = r_unique(arg); + VALUE m = rb_path_to_class(path); + if (NIL_P(extmod)) extmod = rb_ary_tmp_new(0); - if (RB_TYPE_P(m, T_CLASS)) { /* prepended */ - VALUE c; + if (RB_TYPE_P(m, T_CLASS)) { /* prepended */ + VALUE c; - v = r_object0(arg, true, 0, Qnil); - c = CLASS_OF(v); - if (c != m || FL_TEST(c, FL_SINGLETON)) { - rb_raise(rb_eArgError, - "prepended class %"PRIsVALUE" differs from class %"PRIsVALUE, - path, rb_class_name(c)); - } - c = rb_singleton_class(v); - while (RARRAY_LEN(extmod) > 0) { - m = rb_ary_pop(extmod); - rb_prepend_module(c, m); - } - } - else { - must_be_module(m, path); - rb_ary_push(extmod, m); + v = r_object0(arg, true, 0, Qnil); + c = CLASS_OF(v); + if (c != m || FL_TEST(c, FL_SINGLETON)) { + rb_raise(rb_eArgError, + "prepended class %"PRIsVALUE" differs from class %"PRIsVALUE, + path, rb_class_name(c)); + } + c = rb_singleton_class(v); + while (RARRAY_LEN(extmod) > 0) { + m = rb_ary_pop(extmod); + rb_prepend_module(c, m); + } + } + else { + must_be_module(m, path); + rb_ary_push(extmod, m); - v = r_object0(arg, true, 0, extmod); - while (RARRAY_LEN(extmod) > 0) { - m = rb_ary_pop(extmod); - rb_extend_object(v, m); - } - } - } - break; + v = r_object0(arg, true, 0, extmod); + while (RARRAY_LEN(extmod) > 0) { + m = rb_ary_pop(extmod); + rb_extend_object(v, m); + } + } + } + break; case TYPE_UCLASS: - { - VALUE c = path2class(r_unique(arg)); + { + VALUE c = path2class(r_unique(arg)); - if (FL_TEST(c, FL_SINGLETON)) { - rb_raise(rb_eTypeError, "singleton can't be loaded"); - } - type = r_byte(arg); - if ((c == rb_cHash) && - /* Hack for compare_by_identify */ - (type == TYPE_HASH || type == TYPE_HASH_DEF)) { - hash_new_with_size = rb_ident_hash_new_with_size; - goto type_hash; - } - v = r_object_for(arg, partial, 0, extmod, type); - if (rb_special_const_p(v) || RB_TYPE_P(v, T_OBJECT) || RB_TYPE_P(v, T_CLASS)) { + if (FL_TEST(c, FL_SINGLETON)) { + rb_raise(rb_eTypeError, "singleton can't be loaded"); + } + type = r_byte(arg); + if ((c == rb_cHash) && + /* Hack for compare_by_identify */ + (type == TYPE_HASH || type == TYPE_HASH_DEF)) { + hash_new_with_size = rb_ident_hash_new_with_size; + goto type_hash; + } + v = r_object_for(arg, partial, 0, extmod, type); + if (rb_special_const_p(v) || RB_TYPE_P(v, T_OBJECT) || RB_TYPE_P(v, T_CLASS)) { goto format_error; - } - if (RB_TYPE_P(v, T_MODULE) || !RTEST(rb_class_inherited_p(c, RBASIC(v)->klass))) { - VALUE tmp = rb_obj_alloc(c); + } + if (RB_TYPE_P(v, T_MODULE) || !RTEST(rb_class_inherited_p(c, RBASIC(v)->klass))) { + VALUE tmp = rb_obj_alloc(c); - if (TYPE(v) != TYPE(tmp)) goto format_error; - } - RBASIC_SET_CLASS(v, c); - } - break; + if (TYPE(v) != TYPE(tmp)) goto format_error; + } + RBASIC_SET_CLASS(v, c); + } + break; format_error: rb_raise(rb_eArgError, "dump format error (user class)"); case TYPE_NIL: - v = Qnil; - v = r_leave(v, arg, false); - break; + v = Qnil; + v = r_leave(v, arg, false); + break; case TYPE_TRUE: - v = Qtrue; - v = r_leave(v, arg, false); - break; + v = Qtrue; + v = r_leave(v, arg, false); + break; case TYPE_FALSE: - v = Qfalse; - v = r_leave(v, arg, false); - break; + v = Qfalse; + v = r_leave(v, arg, false); + break; case TYPE_FIXNUM: - { - long i = r_long(arg); - v = LONG2FIX(i); - } - v = r_leave(v, arg, false); - break; + { + long i = r_long(arg); + v = LONG2FIX(i); + } + v = r_leave(v, arg, false); + break; case TYPE_FLOAT: - { - double d; - VALUE str = r_bytes(arg); - const char *ptr = RSTRING_PTR(str); + { + double d; + VALUE str = r_bytes(arg); + const char *ptr = RSTRING_PTR(str); - if (strcmp(ptr, "nan") == 0) { - d = nan(""); - } - else if (strcmp(ptr, "inf") == 0) { - d = HUGE_VAL; - } - else if (strcmp(ptr, "-inf") == 0) { - d = -HUGE_VAL; - } - else { - char *e; - d = strtod(ptr, &e); - d = load_mantissa(d, e, RSTRING_LEN(str) - (e - ptr)); - } - v = DBL2NUM(d); - v = r_entry(v, arg); + if (strcmp(ptr, "nan") == 0) { + d = nan(""); + } + else if (strcmp(ptr, "inf") == 0) { + d = HUGE_VAL; + } + else if (strcmp(ptr, "-inf") == 0) { + d = -HUGE_VAL; + } + else { + char *e; + d = strtod(ptr, &e); + d = load_mantissa(d, e, RSTRING_LEN(str) - (e - ptr)); + } + v = DBL2NUM(d); + v = r_entry(v, arg); v = r_leave(v, arg, false); - } - break; + } + break; case TYPE_BIGNUM: - { - long len; - VALUE data; + { + long len; + VALUE data; int sign; - sign = r_byte(arg); - len = r_long(arg); - data = r_bytes0(len * 2, arg); + sign = r_byte(arg); + len = r_long(arg); + data = r_bytes0(len * 2, arg); v = rb_integer_unpack(RSTRING_PTR(data), len, 2, 0, INTEGER_PACK_LITTLE_ENDIAN | (sign == '-' ? INTEGER_PACK_NEGATIVE : 0)); - rb_str_resize(data, 0L); - v = r_entry(v, arg); + rb_str_resize(data, 0L); + v = r_entry(v, arg); v = r_leave(v, arg, false); - } - break; + } + break; case TYPE_STRING: - v = r_entry(r_string(arg), arg); - v = r_leave(v, arg, partial); - break; + v = r_entry(r_string(arg), arg); + v = r_leave(v, arg, partial); + break; case TYPE_REGEXP: - { - VALUE str = r_bytes(arg); - int options = r_byte(arg); - int has_encoding = FALSE; - st_index_t idx = r_prepare(arg); + { + VALUE str = r_bytes(arg); + int options = r_byte(arg); + int has_encoding = FALSE; + st_index_t idx = r_prepare(arg); - if (ivp) { - r_ivar(str, &has_encoding, arg); - *ivp = FALSE; - } - if (!has_encoding) { - /* 1.8 compatibility; remove escapes undefined in 1.8 */ - char *ptr = RSTRING_PTR(str), *dst = ptr, *src = ptr; - long len = RSTRING_LEN(str); - long bs = 0; - for (; len-- > 0; *dst++ = *src++) { - switch (*src) { - case '\\': bs++; break; - case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': - case 'm': case 'o': case 'p': case 'q': case 'u': case 'y': - case 'E': case 'F': case 'H': case 'I': case 'J': case 'K': - case 'L': case 'N': case 'O': case 'P': case 'Q': case 'R': - case 'S': case 'T': case 'U': case 'V': case 'X': case 'Y': - if (bs & 1) --dst; + if (ivp) { + r_ivar(str, &has_encoding, arg); + *ivp = FALSE; + } + if (!has_encoding) { + /* 1.8 compatibility; remove escapes undefined in 1.8 */ + char *ptr = RSTRING_PTR(str), *dst = ptr, *src = ptr; + long len = RSTRING_LEN(str); + long bs = 0; + for (; len-- > 0; *dst++ = *src++) { + switch (*src) { + case '\\': bs++; break; + case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': + case 'm': case 'o': case 'p': case 'q': case 'u': case 'y': + case 'E': case 'F': case 'H': case 'I': case 'J': case 'K': + case 'L': case 'N': case 'O': case 'P': case 'Q': case 'R': + case 'S': case 'T': case 'U': case 'V': case 'X': case 'Y': + if (bs & 1) --dst; /* fall through */ - default: bs = 0; break; - } - } - rb_str_set_len(str, dst - ptr); - } - v = r_entry0(rb_reg_new_str(str, options), idx, arg); - v = r_leave(v, arg, partial); - } - break; + default: bs = 0; break; + } + } + rb_str_set_len(str, dst - ptr); + } + v = r_entry0(rb_reg_new_str(str, options), idx, arg); + v = r_leave(v, arg, partial); + } + break; case TYPE_ARRAY: - { - long len = r_long(arg); + { + long len = r_long(arg); - v = rb_ary_new2(len); - v = r_entry(v, arg); - arg->readable += len - 1; - while (len--) { - rb_ary_push(v, r_object(arg)); - arg->readable--; - } + v = rb_ary_new2(len); + v = r_entry(v, arg); + arg->readable += len - 1; + while (len--) { + rb_ary_push(v, r_object(arg)); + arg->readable--; + } v = r_leave(v, arg, partial); - arg->readable++; - } - break; + arg->readable++; + } + break; case TYPE_HASH: case TYPE_HASH_DEF: type_hash: - { - long len = r_long(arg); + { + long len = r_long(arg); - v = hash_new_with_size(len); - v = r_entry(v, arg); - arg->readable += (len - 1) * 2; - while (len--) { - VALUE key = r_object(arg); - VALUE value = r_object(arg); - rb_hash_aset(v, key, value); - arg->readable -= 2; - } - arg->readable += 2; - if (type == TYPE_HASH_DEF) { - RHASH_SET_IFNONE(v, r_object(arg)); - } + v = hash_new_with_size(len); + v = r_entry(v, arg); + arg->readable += (len - 1) * 2; + while (len--) { + VALUE key = r_object(arg); + VALUE value = r_object(arg); + rb_hash_aset(v, key, value); + arg->readable -= 2; + } + arg->readable += 2; + if (type == TYPE_HASH_DEF) { + RHASH_SET_IFNONE(v, r_object(arg)); + } v = r_leave(v, arg, partial); - } - break; + } + break; case TYPE_STRUCT: - { - VALUE mem, values; - long i; - VALUE slot; - st_index_t idx = r_prepare(arg); - VALUE klass = path2class(r_unique(arg)); - long len = r_long(arg); + { + VALUE mem, values; + long i; + VALUE slot; + st_index_t idx = r_prepare(arg); + VALUE klass = path2class(r_unique(arg)); + long len = r_long(arg); v = rb_obj_alloc(klass); - if (!RB_TYPE_P(v, T_STRUCT)) { - rb_raise(rb_eTypeError, "class %"PRIsVALUE" not a struct", rb_class_name(klass)); - } - mem = rb_struct_s_members(klass); + if (!RB_TYPE_P(v, T_STRUCT)) { + rb_raise(rb_eTypeError, "class %"PRIsVALUE" not a struct", rb_class_name(klass)); + } + mem = rb_struct_s_members(klass); if (RARRAY_LEN(mem) != len) { rb_raise(rb_eTypeError, "struct %"PRIsVALUE" not compatible (struct size differs)", rb_class_name(klass)); } - arg->readable += (len - 1) * 2; - v = r_entry0(v, idx, arg); - values = rb_ary_new2(len); - { - VALUE keywords = Qfalse; - if (RTEST(rb_struct_s_keyword_init(klass))) { - keywords = rb_hash_new(); - rb_ary_push(values, keywords); - } + arg->readable += (len - 1) * 2; + v = r_entry0(v, idx, arg); + values = rb_ary_new2(len); + { + VALUE keywords = Qfalse; + if (RTEST(rb_struct_s_keyword_init(klass))) { + keywords = rb_hash_new(); + rb_ary_push(values, keywords); + } - for (i=0; ireadable -= 2; - } - } + if (!rb_str_equal(n, slot)) { + rb_raise(rb_eTypeError, "struct %"PRIsVALUE" not compatible (:%"PRIsVALUE" for :%"PRIsVALUE")", + rb_class_name(klass), + slot, n); + } + if (keywords) { + rb_hash_aset(keywords, RARRAY_AREF(mem, i), r_object(arg)); + } + else { + rb_ary_push(values, r_object(arg)); + } + arg->readable -= 2; + } + } rb_struct_initialize(v, values); v = r_leave(v, arg, partial); - arg->readable += 2; - } - break; + arg->readable += 2; + } + break; case TYPE_USERDEF: { - VALUE name = r_unique(arg); - VALUE klass = path2class(name); - VALUE data; - st_data_t d; + VALUE name = r_unique(arg); + VALUE klass = path2class(name); + VALUE data; + st_data_t d; - if (!rb_obj_respond_to(klass, s_load, TRUE)) { - rb_raise(rb_eTypeError, "class %"PRIsVALUE" needs to have method `_load'", - name); - } - data = r_string(arg); - if (ivp) { - r_ivar(data, NULL, arg); - *ivp = FALSE; - } - v = load_funcall(arg, klass, s_load, 1, &data); - v = r_entry(v, arg); - if (st_lookup(compat_allocator_tbl, (st_data_t)rb_get_alloc_func(klass), &d)) { - marshal_compat_t *compat = (marshal_compat_t*)d; - v = compat->loader(klass, v); - } - if (!partial) v = r_post_proc(v, arg); - } + if (!rb_obj_respond_to(klass, s_load, TRUE)) { + rb_raise(rb_eTypeError, "class %"PRIsVALUE" needs to have method `_load'", + name); + } + data = r_string(arg); + if (ivp) { + r_ivar(data, NULL, arg); + *ivp = FALSE; + } + v = load_funcall(arg, klass, s_load, 1, &data); + v = r_entry(v, arg); + if (st_lookup(compat_allocator_tbl, (st_data_t)rb_get_alloc_func(klass), &d)) { + marshal_compat_t *compat = (marshal_compat_t*)d; + v = compat->loader(klass, v); + } + if (!partial) v = r_post_proc(v, arg); + } break; case TYPE_USRMARSHAL: { - VALUE name = r_unique(arg); - VALUE klass = path2class(name); - VALUE oldclass = 0; - VALUE data; + VALUE name = r_unique(arg); + VALUE klass = path2class(name); + VALUE oldclass = 0; + VALUE data; - v = obj_alloc_by_klass(klass, arg, &oldclass); + v = obj_alloc_by_klass(klass, arg, &oldclass); if (!NIL_P(extmod)) { - /* for the case marshal_load is overridden */ - append_extmod(v, extmod); + /* for the case marshal_load is overridden */ + append_extmod(v, extmod); } - if (!rb_obj_respond_to(v, s_mload, TRUE)) { - rb_raise(rb_eTypeError, "instance of %"PRIsVALUE" needs to have method `marshal_load'", - name); - } - v = r_entry(v, arg); - data = r_object(arg); - load_funcall(arg, v, s_mload, 1, &data); - v = r_fixup_compat(v, arg); - v = r_copy_ivar(v, data); - v = r_post_proc(v, arg); - if (!NIL_P(extmod)) { - if (oldclass) append_extmod(v, extmod); - rb_ary_clear(extmod); - } - } + if (!rb_obj_respond_to(v, s_mload, TRUE)) { + rb_raise(rb_eTypeError, "instance of %"PRIsVALUE" needs to have method `marshal_load'", + name); + } + v = r_entry(v, arg); + data = r_object(arg); + load_funcall(arg, v, s_mload, 1, &data); + v = r_fixup_compat(v, arg); + v = r_copy_ivar(v, data); + v = r_post_proc(v, arg); + if (!NIL_P(extmod)) { + if (oldclass) append_extmod(v, extmod); + rb_ary_clear(extmod); + } + } break; case TYPE_OBJECT: - { - st_index_t idx = r_prepare(arg); + { + st_index_t idx = r_prepare(arg); v = obj_alloc_by_path(r_unique(arg), arg); - if (!RB_TYPE_P(v, T_OBJECT)) { - rb_raise(rb_eArgError, "dump format error"); - } - v = r_entry0(v, idx, arg); - r_ivar(v, NULL, arg); - v = r_leave(v, arg, partial); - } - break; + if (!RB_TYPE_P(v, T_OBJECT)) { + rb_raise(rb_eArgError, "dump format error"); + } + v = r_entry0(v, idx, arg); + r_ivar(v, NULL, arg); + v = r_leave(v, arg, partial); + } + break; case TYPE_DATA: - { - VALUE name = r_unique(arg); - VALUE klass = path2class(name); - VALUE oldclass = 0; - VALUE r; + { + VALUE name = r_unique(arg); + VALUE klass = path2class(name); + VALUE oldclass = 0; + VALUE r; - v = obj_alloc_by_klass(klass, arg, &oldclass); - if (!RB_TYPE_P(v, T_DATA)) { - rb_raise(rb_eArgError, "dump format error"); - } - v = r_entry(v, arg); - if (!rb_obj_respond_to(v, s_load_data, TRUE)) { - rb_raise(rb_eTypeError, - "class %"PRIsVALUE" needs to have instance method `_load_data'", - name); - } - r = r_object0(arg, partial, 0, extmod); - load_funcall(arg, v, s_load_data, 1, &r); - v = r_leave(v, arg, partial); - } - break; + v = obj_alloc_by_klass(klass, arg, &oldclass); + if (!RB_TYPE_P(v, T_DATA)) { + rb_raise(rb_eArgError, "dump format error"); + } + v = r_entry(v, arg); + if (!rb_obj_respond_to(v, s_load_data, TRUE)) { + rb_raise(rb_eTypeError, + "class %"PRIsVALUE" needs to have instance method `_load_data'", + name); + } + r = r_object0(arg, partial, 0, extmod); + load_funcall(arg, v, s_load_data, 1, &r); + v = r_leave(v, arg, partial); + } + break; case TYPE_MODULE_OLD: { - VALUE str = r_bytes(arg); + VALUE str = r_bytes(arg); - v = rb_path_to_class(str); - prohibit_ivar("class/module", str); - v = r_entry(v, arg); + v = rb_path_to_class(str); + prohibit_ivar("class/module", str); + v = r_entry(v, arg); v = r_leave(v, arg, partial); - } - break; + } + break; case TYPE_CLASS: { - VALUE str = r_bytes(arg); + VALUE str = r_bytes(arg); - v = path2class(str); - prohibit_ivar("class", str); - v = r_entry(v, arg); + v = path2class(str); + prohibit_ivar("class", str); + v = r_entry(v, arg); v = r_leave(v, arg, partial); - } - break; + } + break; case TYPE_MODULE: { - VALUE str = r_bytes(arg); + VALUE str = r_bytes(arg); - v = path2module(str); - prohibit_ivar("module", str); - v = r_entry(v, arg); + v = path2module(str); + prohibit_ivar("module", str); + v = r_entry(v, arg); v = r_leave(v, arg, partial); - } - break; + } + break; case TYPE_SYMBOL: - if (ivp) { - v = r_symreal(arg, *ivp); - *ivp = FALSE; - } - else { - v = r_symreal(arg, 0); - } - v = rb_str_intern(v); - v = r_leave(v, arg, partial); - break; + if (ivp) { + v = r_symreal(arg, *ivp); + *ivp = FALSE; + } + else { + v = r_symreal(arg, 0); + } + v = rb_str_intern(v); + v = r_leave(v, arg, partial); + break; case TYPE_SYMLINK: - v = rb_str_intern(r_symlink(arg)); - break; + v = rb_str_intern(r_symlink(arg)); + break; default: - rb_raise(rb_eArgError, "dump format error(0x%x)", type); - break; + rb_raise(rb_eArgError, "dump format error(0x%x)", type); + break; } if (v == Qundef) { - rb_raise(rb_eArgError, "dump format error (bad link)"); + rb_raise(rb_eArgError, "dump format error (bad link)"); } return v; @@ -2185,8 +2185,8 @@ static void clear_load_arg(struct load_arg *arg) { if (arg->buf) { - xfree(arg->buf); - arg->buf = 0; + xfree(arg->buf); + arg->buf = 0; } arg->buflen = 0; arg->offset = 0; @@ -2199,8 +2199,8 @@ clear_load_arg(struct load_arg *arg) st_free_table(arg->partial_objects); arg->partial_objects = 0; if (arg->compat_tbl) { - st_free_table(arg->compat_tbl); - arg->compat_tbl = 0; + st_free_table(arg->compat_tbl); + arg->compat_tbl = 0; } } @@ -2214,13 +2214,13 @@ rb_marshal_load_with_proc(VALUE port, VALUE proc, bool freeze) v = rb_check_string_type(port); if (!NIL_P(v)) { - port = v; + port = v; } else if (rb_respond_to(port, s_getbyte) && rb_respond_to(port, s_read)) { - rb_check_funcall(port, s_binmode, 0, 0); + rb_check_funcall(port, s_binmode, 0, 0); } else { - io_needed(); + io_needed(); } wrapper = TypedData_Make_Struct(0, struct load_arg, &load_arg_data, arg); arg->src = port; @@ -2234,22 +2234,22 @@ rb_marshal_load_with_proc(VALUE port, VALUE proc, bool freeze) arg->freeze = freeze; if (NIL_P(v)) - arg->buf = xmalloc(BUFSIZ); + arg->buf = xmalloc(BUFSIZ); else - arg->buf = 0; + arg->buf = 0; major = r_byte(arg); minor = r_byte(arg); if (major != MARSHAL_MAJOR || minor > MARSHAL_MINOR) { - clear_load_arg(arg); - rb_raise(rb_eTypeError, "incompatible marshal file format (can't be read)\n\ + clear_load_arg(arg); + rb_raise(rb_eTypeError, "incompatible marshal file format (can't be read)\n\ \tformat version %d.%d required; %d.%d given", - MARSHAL_MAJOR, MARSHAL_MINOR, major, minor); + MARSHAL_MAJOR, MARSHAL_MINOR, major, minor); } if (RTEST(ruby_verbose) && minor != MARSHAL_MINOR) { - rb_warn("incompatible marshal file format (can be read)\n\ + rb_warn("incompatible marshal file format (can be read)\n\ \tformat version %d.%d required; %d.%d given", - MARSHAL_MAJOR, MARSHAL_MINOR, major, minor); + MARSHAL_MAJOR, MARSHAL_MINOR, major, minor); } if (!NIL_P(proc)) arg->proc = proc; @@ -2414,7 +2414,7 @@ compat_allocator_table(void) #undef RUBY_UNTYPED_DATA_WARNING #define RUBY_UNTYPED_DATA_WARNING 0 compat_allocator_tbl_wrapper = - Data_Wrap_Struct(0, mark_marshal_compat_t, 0, compat_allocator_tbl); + Data_Wrap_Struct(0, mark_marshal_compat_t, 0, compat_allocator_tbl); rb_gc_register_mark_object(compat_allocator_tbl_wrapper); return compat_allocator_tbl; } diff --git a/math.c b/math.c index 4996718b10..67bf8b7b63 100644 --- a/math.c +++ b/math.c @@ -65,23 +65,23 @@ math_atan2(VALUE unused_obj, VALUE y, VALUE x) dx = Get_Double(x); dy = Get_Double(y); if (dx == 0.0 && dy == 0.0) { - if (!signbit(dx)) - return DBL2NUM(dy); + if (!signbit(dx)) + return DBL2NUM(dy); if (!signbit(dy)) - return DBL2NUM(M_PI); - return DBL2NUM(-M_PI); + return DBL2NUM(M_PI); + return DBL2NUM(-M_PI); } #ifndef ATAN2_INF_C99 if (isinf(dx) && isinf(dy)) { - /* optimization for FLONUM */ - if (dx < 0.0) { - const double dz = (3.0 * M_PI / 4.0); - return (dy < 0.0) ? DBL2NUM(-dz) : DBL2NUM(dz); - } - else { - const double dz = (M_PI / 4.0); - return (dy < 0.0) ? DBL2NUM(-dz) : DBL2NUM(dz); - } + /* optimization for FLONUM */ + if (dx < 0.0) { + const double dz = (3.0 * M_PI / 4.0); + return (dy < 0.0) ? DBL2NUM(-dz) : DBL2NUM(dz); + } + else { + const double dz = (M_PI / 4.0); + return (dy < 0.0) ? DBL2NUM(-dz) : DBL2NUM(dz); + } } #endif return DBL2NUM(atan2(dy, dx)); @@ -520,7 +520,7 @@ rb_math_log(int argc, const VALUE *argv) rb_scan_args(argc, argv, "11", &x, &base); d = math_log1(x); if (argc == 2) { - d /= math_log1(base); + d /= math_log1(base); } return DBL2NUM(d); } @@ -536,7 +536,7 @@ get_double_rshift(VALUE x, size_t *pnumbits) x = rb_big_rshift(x, SIZET2NUM(numbits)); } else { - numbits = 0; + numbits = 0; } *pnumbits = numbits; return Get_Double(x); @@ -681,13 +681,13 @@ rb_math_sqrt(VALUE x) double d; if (RB_TYPE_P(x, T_COMPLEX)) { - VALUE neg = f_signbit(RCOMPLEX(x)->imag); - double re = Get_Double(RCOMPLEX(x)->real), im; - d = Get_Double(rb_complex_abs(x)); - im = sqrt((d - re) / 2.0); - re = sqrt((d + re) / 2.0); - if (neg) im = -im; - return rb_complex_new(DBL2NUM(re), DBL2NUM(im)); + VALUE neg = f_signbit(RCOMPLEX(x)->imag); + double re = Get_Double(RCOMPLEX(x)->real), im; + d = Get_Double(rb_complex_abs(x)); + im = sqrt((d - re) / 2.0); + re = sqrt((d + re) / 2.0); + if (neg) im = -im; + return rb_complex_new(DBL2NUM(re), DBL2NUM(im)); } d = Get_Double(x); domain_check_min(d, 0.0, "sqrt"); @@ -727,7 +727,7 @@ math_cbrt(VALUE unused_obj, VALUE x) double r = cbrt(f); #if defined __GLIBC__ if (isfinite(r) && !(f == 0.0 && r == 0.0)) { - r = (2.0 * r + (f / r / r)) / 3.0; + r = (2.0 * r + (f / r / r)) / 3.0; } #endif return DBL2NUM(r); @@ -945,17 +945,17 @@ math_gamma(VALUE unused_obj, VALUE x) d = Get_Double(x); /* check for domain error */ if (isinf(d)) { - if (signbit(d)) domain_error("gamma"); - return DBL2NUM(HUGE_VAL); + if (signbit(d)) domain_error("gamma"); + return DBL2NUM(HUGE_VAL); } if (d == 0.0) { - return signbit(d) ? DBL2NUM(-HUGE_VAL) : DBL2NUM(HUGE_VAL); + return signbit(d) ? DBL2NUM(-HUGE_VAL) : DBL2NUM(HUGE_VAL); } if (d == floor(d)) { - domain_check_min(d, 0.0, "gamma"); - if (1.0 <= d && d <= (double)NFACT_TABLE) { - return DBL2NUM(fact_table[(int)d - 1]); - } + domain_check_min(d, 0.0, "gamma"); + if (1.0 <= d && d <= (double)NFACT_TABLE) { + return DBL2NUM(fact_table[(int)d - 1]); + } } return DBL2NUM(tgamma(d)); } @@ -1007,12 +1007,12 @@ math_lgamma(VALUE unused_obj, VALUE x) d = Get_Double(x); /* check for domain error */ if (isinf(d)) { - if (signbit(d)) domain_error("lgamma"); - return rb_assoc_new(DBL2NUM(HUGE_VAL), INT2FIX(1)); + if (signbit(d)) domain_error("lgamma"); + return rb_assoc_new(DBL2NUM(HUGE_VAL), INT2FIX(1)); } if (d == 0.0) { - VALUE vsign = signbit(d) ? INT2FIX(-1) : INT2FIX(+1); - return rb_assoc_new(DBL2NUM(HUGE_VAL), vsign); + VALUE vsign = signbit(d) ? INT2FIX(-1) : INT2FIX(+1); + return rb_assoc_new(DBL2NUM(HUGE_VAL), vsign); } v = DBL2NUM(lgamma_r(d, &sign)); return rb_assoc_new(v, INT2FIX(sign)); diff --git a/memory_view.c b/memory_view.c index 935b8d983f..3fb79202f9 100644 --- a/memory_view.c +++ b/memory_view.c @@ -61,9 +61,9 @@ exported_object_registry_free(void *ptr) const rb_data_type_t rb_memory_view_exported_object_registry_data_type = { "memory_view/exported_object_registry", { - exported_object_registry_mark, - exported_object_registry_free, - 0, + exported_object_registry_mark, + exported_object_registry_free, + 0, }, 0, 0, RUBY_TYPED_FREE_IMMEDIATELY }; @@ -120,9 +120,9 @@ static ID id_memory_view; static const rb_data_type_t memory_view_entry_data_type = { "memory_view/entry", { - 0, - 0, - 0, + 0, + 0, + 0, }, 0, 0, RUBY_TYPED_FREE_IMMEDIATELY }; diff --git a/mjit_instruction.rb b/mjit_instruction.rb new file mode 100644 index 0000000000..04f0db3b0a --- /dev/null +++ b/mjit_instruction.rb @@ -0,0 +1,1034 @@ +module RubyVM::MJIT + Instruction = Struct.new(:expr) + + INSTRUCTIONS = { + nop: Instruction.new( + expr: <<-EXPR, +{ + /* none */ +} + EXPR + ), + getlocal: Instruction.new( + expr: <<-EXPR, +{ + val = *(vm_get_ep(GET_EP(), level) - idx); + RB_DEBUG_COUNTER_INC(lvar_get); + (void)RB_DEBUG_COUNTER_INC_IF(lvar_get_dynamic, level > 0); +} + EXPR + ), + setlocal: Instruction.new( + expr: <<-EXPR, +{ + vm_env_write(vm_get_ep(GET_EP(), level), -(int)idx, val); + RB_DEBUG_COUNTER_INC(lvar_set); + (void)RB_DEBUG_COUNTER_INC_IF(lvar_set_dynamic, level > 0); +} + EXPR + ), + getblockparam: Instruction.new( + expr: <<-EXPR, +{ + const VALUE *ep = vm_get_ep(GET_EP(), level); + VM_ASSERT(VM_ENV_LOCAL_P(ep)); + + if (!VM_ENV_FLAGS(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM)) { + val = rb_vm_bh_to_procval(ec, VM_ENV_BLOCK_HANDLER(ep)); + vm_env_write(ep, -(int)idx, val); + VM_ENV_FLAGS_SET(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM); + } + else { + val = *(ep - idx); + RB_DEBUG_COUNTER_INC(lvar_get); + (void)RB_DEBUG_COUNTER_INC_IF(lvar_get_dynamic, level > 0); + } +} + EXPR + ), + setblockparam: Instruction.new( + expr: <<-EXPR, +{ + const VALUE *ep = vm_get_ep(GET_EP(), level); + VM_ASSERT(VM_ENV_LOCAL_P(ep)); + + vm_env_write(ep, -(int)idx, val); + RB_DEBUG_COUNTER_INC(lvar_set); + (void)RB_DEBUG_COUNTER_INC_IF(lvar_set_dynamic, level > 0); + + VM_ENV_FLAGS_SET(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM); +} + EXPR + ), + getblockparamproxy: Instruction.new( + expr: <<-EXPR, +{ + const VALUE *ep = vm_get_ep(GET_EP(), level); + VM_ASSERT(VM_ENV_LOCAL_P(ep)); + + if (!VM_ENV_FLAGS(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM)) { + VALUE block_handler = VM_ENV_BLOCK_HANDLER(ep); + + if (block_handler) { + switch (vm_block_handler_type(block_handler)) { + case block_handler_type_iseq: + case block_handler_type_ifunc: + val = rb_block_param_proxy; + break; + case block_handler_type_symbol: + val = rb_sym_to_proc(VM_BH_TO_SYMBOL(block_handler)); + goto INSN_LABEL(set); + case block_handler_type_proc: + val = VM_BH_TO_PROC(block_handler); + goto INSN_LABEL(set); + default: + VM_UNREACHABLE(getblockparamproxy); + } + } + else { + val = Qnil; + INSN_LABEL(set): + vm_env_write(ep, -(int)idx, val); + VM_ENV_FLAGS_SET(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM); + } + } + else { + val = *(ep - idx); + RB_DEBUG_COUNTER_INC(lvar_get); + (void)RB_DEBUG_COUNTER_INC_IF(lvar_get_dynamic, level > 0); + } +} + EXPR + ), + getspecial: Instruction.new( + expr: <<-EXPR, +{ + val = vm_getspecial(ec, GET_LEP(), key, type); +} + EXPR + ), + setspecial: Instruction.new( + expr: <<-EXPR, +{ + lep_svar_set(ec, GET_LEP(), key, obj); +} + EXPR + ), + getinstancevariable: Instruction.new( + expr: <<-EXPR, +{ + val = vm_getinstancevariable(GET_ISEQ(), GET_SELF(), id, ic); +} + EXPR + ), + setinstancevariable: Instruction.new( + expr: <<-EXPR, +{ + vm_setinstancevariable(GET_ISEQ(), GET_SELF(), id, val, ic); +} + EXPR + ), + getclassvariable: Instruction.new( + expr: <<-EXPR, +{ + rb_control_frame_t *cfp = GET_CFP(); + val = vm_getclassvariable(GET_ISEQ(), cfp, id, ic); +} + EXPR + ), + setclassvariable: Instruction.new( + expr: <<-EXPR, +{ + vm_ensure_not_refinement_module(GET_SELF()); + vm_setclassvariable(GET_ISEQ(), GET_CFP(), id, val, ic); +} + EXPR + ), + getconstant: Instruction.new( + expr: <<-EXPR, +{ + val = vm_get_ev_const(ec, klass, id, allow_nil == Qtrue, 0); +} + EXPR + ), + setconstant: Instruction.new( + expr: <<-EXPR, +{ + vm_check_if_namespace(cbase); + vm_ensure_not_refinement_module(GET_SELF()); + rb_const_set(cbase, id, val); +} + EXPR + ), + getglobal: Instruction.new( + expr: <<-EXPR, +{ + val = rb_gvar_get(gid); +} + EXPR + ), + setglobal: Instruction.new( + expr: <<-EXPR, +{ + rb_gvar_set(gid, val); +} + EXPR + ), + putnil: Instruction.new( + expr: <<-EXPR, +{ + val = Qnil; +} + EXPR + ), + putself: Instruction.new( + expr: <<-EXPR, +{ + val = GET_SELF(); +} + EXPR + ), + putobject: Instruction.new( + expr: <<-EXPR, +{ + /* */ +} + EXPR + ), + putspecialobject: Instruction.new( + expr: <<-EXPR, +{ + enum vm_special_object_type type; + + type = (enum vm_special_object_type)value_type; + val = vm_get_special_object(GET_EP(), type); +} + EXPR + ), + putstring: Instruction.new( + expr: <<-EXPR, +{ + val = rb_ec_str_resurrect(ec, str); +} + EXPR + ), + concatstrings: Instruction.new( + expr: <<-EXPR, +{ + val = rb_str_concat_literals(num, STACK_ADDR_FROM_TOP(num)); +} + EXPR + ), + anytostring: Instruction.new( + expr: <<-EXPR, +{ + val = rb_obj_as_string_result(str, val); +} + EXPR + ), + toregexp: Instruction.new( + expr: <<-EXPR, +{ + const VALUE ary = rb_ary_tmp_new_from_values(0, cnt, STACK_ADDR_FROM_TOP(cnt)); + val = rb_reg_new_ary(ary, (int)opt); + rb_ary_clear(ary); +} + EXPR + ), + intern: Instruction.new( + expr: <<-EXPR, +{ + sym = rb_str_intern(str); +} + EXPR + ), + newarray: Instruction.new( + expr: <<-EXPR, +{ + val = rb_ec_ary_new_from_values(ec, num, STACK_ADDR_FROM_TOP(num)); +} + EXPR + ), + newarraykwsplat: Instruction.new( + expr: <<-EXPR, +{ + if (RHASH_EMPTY_P(*STACK_ADDR_FROM_TOP(1))) { + val = rb_ary_new4(num-1, STACK_ADDR_FROM_TOP(num)); + } + else { + val = rb_ary_new4(num, STACK_ADDR_FROM_TOP(num)); + } +} + EXPR + ), + duparray: Instruction.new( + expr: <<-EXPR, +{ + RUBY_DTRACE_CREATE_HOOK(ARRAY, RARRAY_LEN(ary)); + val = rb_ary_resurrect(ary); +} + EXPR + ), + duphash: Instruction.new( + expr: <<-EXPR, +{ + RUBY_DTRACE_CREATE_HOOK(HASH, RHASH_SIZE(hash) << 1); + val = rb_hash_resurrect(hash); +} + EXPR + ), + expandarray: Instruction.new( + expr: <<-EXPR, +{ + vm_expandarray(GET_SP(), ary, num, (int)flag); +} + EXPR + ), + concatarray: Instruction.new( + expr: <<-EXPR, +{ + ary = vm_concat_array(ary1, ary2); +} + EXPR + ), + splatarray: Instruction.new( + expr: <<-EXPR, +{ + obj = vm_splat_array(flag, ary); +} + EXPR + ), + newhash: Instruction.new( + expr: <<-EXPR, +{ + RUBY_DTRACE_CREATE_HOOK(HASH, num); + + if (num) { + val = rb_hash_new_with_size(num / 2); + rb_hash_bulk_insert(num, STACK_ADDR_FROM_TOP(num), val); + } + else { + val = rb_hash_new(); + } +} + EXPR + ), + newrange: Instruction.new( + expr: <<-EXPR, +{ + val = rb_range_new(low, high, (int)flag); +} + EXPR + ), + pop: Instruction.new( + expr: <<-EXPR, +{ + (void)val; + /* none */ +} + EXPR + ), + dup: Instruction.new( + expr: <<-EXPR, +{ + val1 = val2 = val; +} + EXPR + ), + dupn: Instruction.new( + expr: <<-EXPR, +{ + void *dst = GET_SP(); + void *src = STACK_ADDR_FROM_TOP(n); + + MEMCPY(dst, src, VALUE, n); +} + EXPR + ), + swap: Instruction.new( + expr: <<-EXPR, +{ + /* none */ +} + EXPR + ), + topn: Instruction.new( + expr: <<-EXPR, +{ + val = TOPN(n); +} + EXPR + ), + setn: Instruction.new( + expr: <<-EXPR, +{ + TOPN(n) = val; +} + EXPR + ), + adjuststack: Instruction.new( + expr: <<-EXPR, +{ + /* none */ +} + EXPR + ), + defined: Instruction.new( + expr: <<-EXPR, +{ + val = Qnil; + if (vm_defined(ec, GET_CFP(), op_type, obj, v)) { + val = pushval; + } +} + EXPR + ), + checkmatch: Instruction.new( + expr: <<-EXPR, +{ + result = vm_check_match(ec, target, pattern, flag); +} + EXPR + ), + checkkeyword: Instruction.new( + expr: <<-EXPR, +{ + ret = vm_check_keyword(kw_bits_index, keyword_index, GET_EP()); +} + EXPR + ), + checktype: Instruction.new( + expr: <<-EXPR, +{ + ret = RBOOL(TYPE(val) == (int)type); +} + EXPR + ), + defineclass: Instruction.new( + expr: <<-EXPR, +{ + VALUE klass = vm_find_or_create_class_by_id(id, flags, cbase, super); + + rb_iseq_check(class_iseq); + + /* enter scope */ + vm_push_frame(ec, class_iseq, VM_FRAME_MAGIC_CLASS | VM_ENV_FLAG_LOCAL, klass, + GET_BLOCK_HANDLER(), + (VALUE)vm_cref_push(ec, klass, NULL, FALSE, FALSE), + ISEQ_BODY(class_iseq)->iseq_encoded, GET_SP(), + ISEQ_BODY(class_iseq)->local_table_size, + ISEQ_BODY(class_iseq)->stack_max); + RESTORE_REGS(); + NEXT_INSN(); +} + EXPR + ), + definemethod: Instruction.new( + expr: <<-EXPR, +{ + vm_define_method(ec, Qnil, id, (VALUE)iseq, FALSE); +} + EXPR + ), + definesmethod: Instruction.new( + expr: <<-EXPR, +{ + vm_define_method(ec, obj, id, (VALUE)iseq, TRUE); +} + EXPR + ), + send: Instruction.new( + expr: <<-EXPR, +{ + VALUE bh = vm_caller_setup_arg_block(ec, GET_CFP(), cd->ci, blockiseq, false); + val = vm_sendish(ec, GET_CFP(), cd, bh, mexp_search_method); + + if (val == Qundef) { + RESTORE_REGS(); + NEXT_INSN(); + } +} + EXPR + ), + opt_send_without_block: Instruction.new( + expr: <<-EXPR, +{ + VALUE bh = VM_BLOCK_HANDLER_NONE; + val = vm_sendish(ec, GET_CFP(), cd, bh, mexp_search_method); + + if (val == Qundef) { + RESTORE_REGS(); + NEXT_INSN(); + } +} + EXPR + ), + objtostring: Instruction.new( + expr: <<-EXPR, +{ + val = vm_objtostring(GET_ISEQ(), recv, cd); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_str_freeze: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_str_freeze(str, BOP_FREEZE, idFreeze); + + if (val == Qundef) { + PUSH(rb_str_resurrect(str)); + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_nil_p: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_nil_p(GET_ISEQ(), cd, recv); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_str_uminus: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_str_freeze(str, BOP_UMINUS, idUMinus); + + if (val == Qundef) { + PUSH(rb_str_resurrect(str)); + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_newarray_max: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_newarray_max(ec, num, STACK_ADDR_FROM_TOP(num)); +} + EXPR + ), + opt_newarray_min: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_newarray_min(ec, num, STACK_ADDR_FROM_TOP(num)); +} + EXPR + ), + invokesuper: Instruction.new( + expr: <<-EXPR, +{ + VALUE bh = vm_caller_setup_arg_block(ec, GET_CFP(), cd->ci, blockiseq, true); + val = vm_sendish(ec, GET_CFP(), cd, bh, mexp_search_super); + + if (val == Qundef) { + RESTORE_REGS(); + NEXT_INSN(); + } +} + EXPR + ), + invokeblock: Instruction.new( + expr: <<-EXPR, +{ + VALUE bh = VM_BLOCK_HANDLER_NONE; + val = vm_sendish(ec, GET_CFP(), cd, bh, mexp_search_invokeblock); + + if (val == Qundef) { + RESTORE_REGS(); + NEXT_INSN(); + } +} + EXPR + ), + leave: Instruction.new( + expr: <<-EXPR, +{ + if (OPT_CHECKED_RUN) { + const VALUE *const bp = vm_base_ptr(GET_CFP()); + if (GET_SP() != bp) { + vm_stack_consistency_error(ec, GET_CFP(), bp); + } + } + + if (vm_pop_frame(ec, GET_CFP(), GET_EP())) { +#if OPT_CALL_THREADED_CODE + rb_ec_thread_ptr(ec)->retval = val; + return 0; +#else + return val; +#endif + } + else { + RESTORE_REGS(); + } +} + EXPR + ), + throw: Instruction.new( + expr: <<-EXPR, +{ + val = vm_throw(ec, GET_CFP(), throw_state, throwobj); + THROW_EXCEPTION(val); + /* unreachable */ +} + EXPR + ), + jump: Instruction.new( + expr: <<-EXPR, +{ + RUBY_VM_CHECK_INTS(ec); + JUMP(dst); +} + EXPR + ), + branchif: Instruction.new( + expr: <<-EXPR, +{ + if (RTEST(val)) { + RUBY_VM_CHECK_INTS(ec); + JUMP(dst); + } +} + EXPR + ), + branchunless: Instruction.new( + expr: <<-EXPR, +{ + if (!RTEST(val)) { + RUBY_VM_CHECK_INTS(ec); + JUMP(dst); + } +} + EXPR + ), + branchnil: Instruction.new( + expr: <<-EXPR, +{ + if (NIL_P(val)) { + RUBY_VM_CHECK_INTS(ec); + JUMP(dst); + } +} + EXPR + ), + opt_getinlinecache: Instruction.new( + expr: <<-EXPR, +{ + struct iseq_inline_constant_cache_entry *ice = ic->entry; + + // If there isn't an entry, then we're going to walk through the ISEQ + // starting at this instruction until we get to the associated + // opt_setinlinecache and associate this inline cache with every getconstant + // listed in between. We're doing this here instead of when the instructions + // are first compiled because it's possible to turn off inline caches and we + // want this to work in either case. + if (!ice) { + vm_ic_compile(GET_CFP(), ic); + } + + if (ice && vm_ic_hit_p(ice, GET_EP())) { + val = ice->value; + JUMP(dst); + } + else { + ruby_vm_constant_cache_misses++; + val = Qnil; + } +} + EXPR + ), + opt_setinlinecache: Instruction.new( + expr: <<-EXPR, +{ + vm_ic_update(GET_ISEQ(), ic, val, GET_EP()); +} + EXPR + ), + once: Instruction.new( + expr: <<-EXPR, +{ + val = vm_once_dispatch(ec, iseq, ise); +} + EXPR + ), + opt_case_dispatch: Instruction.new( + expr: <<-EXPR, +{ + OFFSET dst = vm_case_dispatch(hash, else_offset, key); + + if (dst) { + JUMP(dst); + } +} + EXPR + ), + opt_plus: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_plus(recv, obj); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_minus: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_minus(recv, obj); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_mult: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_mult(recv, obj); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_div: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_div(recv, obj); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_mod: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_mod(recv, obj); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_eq: Instruction.new( + expr: <<-EXPR, +{ + val = opt_equality(GET_ISEQ(), recv, obj, cd); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_neq: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_neq(GET_ISEQ(), cd, cd_eq, recv, obj); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_lt: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_lt(recv, obj); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_le: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_le(recv, obj); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_gt: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_gt(recv, obj); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_ge: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_ge(recv, obj); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_ltlt: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_ltlt(recv, obj); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_and: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_and(recv, obj); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_or: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_or(recv, obj); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_aref: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_aref(recv, obj); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_aset: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_aset(recv, obj, set); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_aset_with: Instruction.new( + expr: <<-EXPR, +{ + VALUE tmp = vm_opt_aset_with(recv, key, val); + + if (tmp != Qundef) { + val = tmp; + } + else { +#ifndef MJIT_HEADER + TOPN(0) = rb_str_resurrect(key); + PUSH(val); +#endif + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_aref_with: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_aref_with(recv, key); + + if (val == Qundef) { +#ifndef MJIT_HEADER + PUSH(rb_str_resurrect(key)); +#endif + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_length: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_length(recv, BOP_LENGTH); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_size: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_length(recv, BOP_SIZE); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_empty_p: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_empty_p(recv); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_succ: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_succ(recv); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_not: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_not(GET_ISEQ(), cd, recv); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + opt_regexpmatch2: Instruction.new( + expr: <<-EXPR, +{ + val = vm_opt_regexpmatch2(obj2, obj1); + + if (val == Qundef) { + CALL_SIMPLE_METHOD(); + } +} + EXPR + ), + invokebuiltin: Instruction.new( + expr: <<-EXPR, +{ + val = vm_invoke_builtin(ec, reg_cfp, bf, STACK_ADDR_FROM_TOP(bf->argc)); +} + EXPR + ), + opt_invokebuiltin_delegate: Instruction.new( + expr: <<-EXPR, +{ + val = vm_invoke_builtin_delegate(ec, reg_cfp, bf, (unsigned int)index); +} + EXPR + ), + opt_invokebuiltin_delegate_leave: Instruction.new( + expr: <<-EXPR, +{ + val = vm_invoke_builtin_delegate(ec, reg_cfp, bf, (unsigned int)index); + + /* leave fastpath */ + /* TracePoint/return fallbacks this insn to opt_invokebuiltin_delegate */ + if (vm_pop_frame(ec, GET_CFP(), GET_EP())) { +#if OPT_CALL_THREADED_CODE + rb_ec_thread_ptr(ec)->retval = val; + return 0; +#else + return val; +#endif + } + else { + RESTORE_REGS(); + } +} + EXPR + ), + getlocal_WC_0: Instruction.new( + expr: <<-EXPR, +{ + val = *(vm_get_ep(GET_EP(), level) - idx); + RB_DEBUG_COUNTER_INC(lvar_get); + (void)RB_DEBUG_COUNTER_INC_IF(lvar_get_dynamic, level > 0); +} + EXPR + ), + getlocal_WC_1: Instruction.new( + expr: <<-EXPR, +{ + val = *(vm_get_ep(GET_EP(), level) - idx); + RB_DEBUG_COUNTER_INC(lvar_get); + (void)RB_DEBUG_COUNTER_INC_IF(lvar_get_dynamic, level > 0); +} + EXPR + ), + setlocal_WC_0: Instruction.new( + expr: <<-EXPR, +{ + vm_env_write(vm_get_ep(GET_EP(), level), -(int)idx, val); + RB_DEBUG_COUNTER_INC(lvar_set); + (void)RB_DEBUG_COUNTER_INC_IF(lvar_set_dynamic, level > 0); +} + EXPR + ), + setlocal_WC_1: Instruction.new( + expr: <<-EXPR, +{ + vm_env_write(vm_get_ep(GET_EP(), level), -(int)idx, val); + RB_DEBUG_COUNTER_INC(lvar_set); + (void)RB_DEBUG_COUNTER_INC_IF(lvar_set_dynamic, level > 0); +} + EXPR + ), + putobject_INT2FIX_0_: Instruction.new( + expr: <<-EXPR, +{ + /* */ +} + EXPR + ), + putobject_INT2FIX_1_: Instruction.new( + expr: <<-EXPR, +{ + /* */ +} + EXPR + ), + } +end diff --git a/node.c b/node.c index d8c1da95ef..a10d5122c3 100644 --- a/node.c +++ b/node.c @@ -29,10 +29,10 @@ #define A_LIT(lit) AR(rb_dump_literal(lit)) #define A_NODE_HEADER(node, term) \ rb_str_catf(buf, "@ %s (id: %d, line: %d, location: (%d,%d)-(%d,%d))%s"term, \ - ruby_node_name(nd_type(node)), nd_node_id(node), nd_line(node), \ - nd_first_lineno(node), nd_first_column(node), \ - nd_last_lineno(node), nd_last_column(node), \ - (node->flags & NODE_FL_NEWLINE ? "*" : "")) + ruby_node_name(nd_type(node)), nd_node_id(node), nd_line(node), \ + nd_first_lineno(node), nd_first_column(node), \ + nd_last_lineno(node), nd_last_column(node), \ + (node->flags & NODE_FL_NEWLINE ? "*" : "")) #define A_FIELD_HEADER(len, name, term) \ rb_str_catf(buf, "+- %.*s:"term, (len), (name)) #define D_FIELD_HEADER(len, name, term) (A_INDENT, A_FIELD_HEADER(len, name, term)) @@ -45,20 +45,20 @@ #define COMPOUND_FIELD1(name, ann) \ COMPOUND_FIELD(FIELD_NAME_LEN(name, ann), \ - FIELD_NAME_DESC(name, ann)) + FIELD_NAME_DESC(name, ann)) #define FIELD_NAME_DESC(name, ann) name " (" ann ")" #define FIELD_NAME_LEN(name, ann) (int)( \ - comment ? \ - rb_strlen_lit(FIELD_NAME_DESC(name, ann)) : \ - rb_strlen_lit(name)) + comment ? \ + rb_strlen_lit(FIELD_NAME_DESC(name, ann)) : \ + rb_strlen_lit(name)) #define SIMPLE_FIELD(len, name) \ FIELD_BLOCK(D_FIELD_HEADER((len), (name), " "), A("\n")) #define FIELD_BLOCK(init, reset) \ for (init, field_flag = 1; \ - field_flag; /* should be optimized away */ \ - reset, field_flag = 0) + field_flag; /* should be optimized away */ \ + reset, field_flag = 0) #define SIMPLE_FIELD1(name, ann) SIMPLE_FIELD(FIELD_NAME_LEN(name, ann), FIELD_NAME_DESC(name, ann)) #define F_CUSTOM1(name, ann) SIMPLE_FIELD1(#name, ann) @@ -74,7 +74,7 @@ #define ANN(ann) \ if (comment) { \ - A_INDENT; A("| # " ann "\n"); \ + A_INDENT; A("| # " ann "\n"); \ } #define LAST_NODE (next_indent = " ") @@ -108,16 +108,16 @@ static void add_id(VALUE buf, ID id) { if (id == 0) { - A("(null)"); + A("(null)"); } else { - VALUE str = rb_id2str(id); - if (str) { - A(":"); AR(str); - } - else { + VALUE str = rb_id2str(id); + if (str) { + A(":"); AR(str); + } + else { rb_str_catf(buf, "(internal variable: 0x%"PRIsVALUE")", id); - } + } } } @@ -137,8 +137,8 @@ dump_array(VALUE buf, VALUE indent, int comment, const NODE *node) F_LONG(nd_alen, "length"); F_NODE(nd_head, "element"); while (node->nd_next && nd_type_p(node->nd_next, NODE_LIST)) { - node = node->nd_next; - F_NODE(nd_head, "element"); + node = node->nd_next; + F_NODE(nd_head, "element"); } LAST_NODE; F_NODE(nd_next, "next element"); @@ -153,8 +153,8 @@ dump_node(VALUE buf, VALUE indent, int comment, const NODE * node) enum node_type type; if (!node) { - D_NULL_NODE; - return; + D_NULL_NODE; + return; } D_NODE_HEADER(node); @@ -162,63 +162,63 @@ dump_node(VALUE buf, VALUE indent, int comment, const NODE * node) type = nd_type(node); switch (type) { case NODE_BLOCK: - ANN("statement sequence"); - ANN("format: [nd_head]; ...; [nd_next]"); - ANN("example: foo; bar"); - i = 0; - do { - A_INDENT; - rb_str_catf(buf, "+- nd_head (%s%d):\n", - comment ? "statement #" : "", ++i); - if (!node->nd_next) LAST_NODE; - D_INDENT; - dump_node(buf, indent, comment, node->nd_head); - D_DEDENT; - } while (node->nd_next && - nd_type_p(node->nd_next, NODE_BLOCK) && - (node = node->nd_next, 1)); - if (node->nd_next) { - LAST_NODE; - F_NODE(nd_next, "next block"); - } - return; + ANN("statement sequence"); + ANN("format: [nd_head]; ...; [nd_next]"); + ANN("example: foo; bar"); + i = 0; + do { + A_INDENT; + rb_str_catf(buf, "+- nd_head (%s%d):\n", + comment ? "statement #" : "", ++i); + if (!node->nd_next) LAST_NODE; + D_INDENT; + dump_node(buf, indent, comment, node->nd_head); + D_DEDENT; + } while (node->nd_next && + nd_type_p(node->nd_next, NODE_BLOCK) && + (node = node->nd_next, 1)); + if (node->nd_next) { + LAST_NODE; + F_NODE(nd_next, "next block"); + } + return; case NODE_IF: - ANN("if statement"); - ANN("format: if [nd_cond] then [nd_body] else [nd_else] end"); - ANN("example: if x == 1 then foo else bar end"); - F_NODE(nd_cond, "condition expr"); - F_NODE(nd_body, "then clause"); - LAST_NODE; - F_NODE(nd_else, "else clause"); - return; + ANN("if statement"); + ANN("format: if [nd_cond] then [nd_body] else [nd_else] end"); + ANN("example: if x == 1 then foo else bar end"); + F_NODE(nd_cond, "condition expr"); + F_NODE(nd_body, "then clause"); + LAST_NODE; + F_NODE(nd_else, "else clause"); + return; case NODE_UNLESS: - ANN("unless statement"); - ANN("format: unless [nd_cond] then [nd_body] else [nd_else] end"); - ANN("example: unless x == 1 then foo else bar end"); - F_NODE(nd_cond, "condition expr"); - F_NODE(nd_body, "then clause"); - LAST_NODE; - F_NODE(nd_else, "else clause"); - return; + ANN("unless statement"); + ANN("format: unless [nd_cond] then [nd_body] else [nd_else] end"); + ANN("example: unless x == 1 then foo else bar end"); + F_NODE(nd_cond, "condition expr"); + F_NODE(nd_body, "then clause"); + LAST_NODE; + F_NODE(nd_else, "else clause"); + return; case NODE_CASE: - ANN("case statement"); - ANN("format: case [nd_head]; [nd_body]; end"); - ANN("example: case x; when 1; foo; when 2; bar; else baz; end"); - F_NODE(nd_head, "case expr"); - LAST_NODE; - F_NODE(nd_body, "when clauses"); - return; + ANN("case statement"); + ANN("format: case [nd_head]; [nd_body]; end"); + ANN("example: case x; when 1; foo; when 2; bar; else baz; end"); + F_NODE(nd_head, "case expr"); + LAST_NODE; + F_NODE(nd_body, "when clauses"); + return; case NODE_CASE2: - ANN("case statement with no head"); - ANN("format: case; [nd_body]; end"); - ANN("example: case; when 1; foo; when 2; bar; else baz; end"); - F_NODE(nd_head, "case expr"); - LAST_NODE; - F_NODE(nd_body, "when clauses"); - return; + ANN("case statement with no head"); + ANN("format: case; [nd_body]; end"); + ANN("example: case; when 1; foo; when 2; bar; else baz; end"); + F_NODE(nd_head, "case expr"); + LAST_NODE; + F_NODE(nd_body, "when clauses"); + return; case NODE_CASE3: ANN("case statement (pattern matching)"); ANN("format: case [nd_head]; [nd_body]; end"); @@ -229,14 +229,14 @@ dump_node(VALUE buf, VALUE indent, int comment, const NODE * node) return; case NODE_WHEN: - ANN("when clause"); - ANN("format: when [nd_head]; [nd_body]; (when or else) [nd_next]"); - ANN("example: case x; when 1; foo; when 2; bar; else baz; end"); - F_NODE(nd_head, "when value"); - F_NODE(nd_body, "when body"); - LAST_NODE; - F_NODE(nd_next, "next when clause"); - return; + ANN("when clause"); + ANN("format: when [nd_head]; [nd_body]; (when or else) [nd_next]"); + ANN("example: case x; when 1; foo; when 2; bar; else baz; end"); + F_NODE(nd_head, "when value"); + F_NODE(nd_body, "when body"); + LAST_NODE; + F_NODE(nd_next, "next when clause"); + return; case NODE_IN: ANN("in clause"); @@ -249,278 +249,278 @@ dump_node(VALUE buf, VALUE indent, int comment, const NODE * node) return; case NODE_WHILE: - ANN("while statement"); - ANN("format: while [nd_cond]; [nd_body]; end"); - ANN("example: while x == 1; foo; end"); - goto loop; + ANN("while statement"); + ANN("format: while [nd_cond]; [nd_body]; end"); + ANN("example: while x == 1; foo; end"); + goto loop; case NODE_UNTIL: - ANN("until statement"); - ANN("format: until [nd_cond]; [nd_body]; end"); - ANN("example: until x == 1; foo; end"); + ANN("until statement"); + ANN("format: until [nd_cond]; [nd_body]; end"); + ANN("example: until x == 1; foo; end"); loop: - F_CUSTOM1(nd_state, "begin-end-while?") { - A_INT((int)node->nd_state); - A((node->nd_state == 1) ? " (while-end)" : " (begin-end-while)"); - } - F_NODE(nd_cond, "condition"); - LAST_NODE; - F_NODE(nd_body, "body"); - return; + F_CUSTOM1(nd_state, "begin-end-while?") { + A_INT((int)node->nd_state); + A((node->nd_state == 1) ? " (while-end)" : " (begin-end-while)"); + } + F_NODE(nd_cond, "condition"); + LAST_NODE; + F_NODE(nd_body, "body"); + return; case NODE_ITER: - ANN("method call with block"); - ANN("format: [nd_iter] { [nd_body] }"); - ANN("example: 3.times { foo }"); - goto iter; + ANN("method call with block"); + ANN("format: [nd_iter] { [nd_body] }"); + ANN("example: 3.times { foo }"); + goto iter; case NODE_FOR: - ANN("for statement"); - ANN("format: for * in [nd_iter] do [nd_body] end"); - ANN("example: for i in 1..3 do foo end"); + ANN("for statement"); + ANN("format: for * in [nd_iter] do [nd_body] end"); + ANN("example: for i in 1..3 do foo end"); iter: - F_NODE(nd_iter, "iteration receiver"); - LAST_NODE; - F_NODE(nd_body, "body"); - return; + F_NODE(nd_iter, "iteration receiver"); + LAST_NODE; + F_NODE(nd_body, "body"); + return; case NODE_FOR_MASGN: - ANN("vars of for statement with masgn"); - ANN("format: for [nd_var] in ... do ... end"); - ANN("example: for x, y in 1..3 do foo end"); - LAST_NODE; - F_NODE(nd_var, "var"); - return; + ANN("vars of for statement with masgn"); + ANN("format: for [nd_var] in ... do ... end"); + ANN("example: for x, y in 1..3 do foo end"); + LAST_NODE; + F_NODE(nd_var, "var"); + return; case NODE_BREAK: - ANN("break statement"); - ANN("format: break [nd_stts]"); - ANN("example: break 1"); - goto jump; + ANN("break statement"); + ANN("format: break [nd_stts]"); + ANN("example: break 1"); + goto jump; case NODE_NEXT: - ANN("next statement"); - ANN("format: next [nd_stts]"); - ANN("example: next 1"); - goto jump; + ANN("next statement"); + ANN("format: next [nd_stts]"); + ANN("example: next 1"); + goto jump; case NODE_RETURN: - ANN("return statement"); - ANN("format: return [nd_stts]"); - ANN("example: return 1"); + ANN("return statement"); + ANN("format: return [nd_stts]"); + ANN("example: return 1"); jump: - LAST_NODE; - F_NODE(nd_stts, "value"); - return; + LAST_NODE; + F_NODE(nd_stts, "value"); + return; case NODE_REDO: - ANN("redo statement"); - ANN("format: redo"); - ANN("example: redo"); - return; + ANN("redo statement"); + ANN("format: redo"); + ANN("example: redo"); + return; case NODE_RETRY: - ANN("retry statement"); - ANN("format: retry"); - ANN("example: retry"); - return; + ANN("retry statement"); + ANN("format: retry"); + ANN("example: retry"); + return; case NODE_BEGIN: - ANN("begin statement"); - ANN("format: begin; [nd_body]; end"); - ANN("example: begin; 1; end"); - LAST_NODE; - F_NODE(nd_body, "body"); - return; + ANN("begin statement"); + ANN("format: begin; [nd_body]; end"); + ANN("example: begin; 1; end"); + LAST_NODE; + F_NODE(nd_body, "body"); + return; case NODE_RESCUE: - ANN("rescue clause"); - ANN("format: begin; [nd_body]; (rescue) [nd_resq]; else [nd_else]; end"); - ANN("example: begin; foo; rescue; bar; else; baz; end"); - F_NODE(nd_head, "body"); - F_NODE(nd_resq, "rescue clause list"); - LAST_NODE; - F_NODE(nd_else, "rescue else clause"); - return; + ANN("rescue clause"); + ANN("format: begin; [nd_body]; (rescue) [nd_resq]; else [nd_else]; end"); + ANN("example: begin; foo; rescue; bar; else; baz; end"); + F_NODE(nd_head, "body"); + F_NODE(nd_resq, "rescue clause list"); + LAST_NODE; + F_NODE(nd_else, "rescue else clause"); + return; case NODE_RESBODY: - ANN("rescue clause (cont'd)"); - ANN("format: rescue [nd_args]; [nd_body]; (rescue) [nd_head]"); - ANN("example: begin; foo; rescue; bar; else; baz; end"); - F_NODE(nd_args, "rescue exceptions"); - F_NODE(nd_body, "rescue clause"); - LAST_NODE; - F_NODE(nd_head, "next rescue clause"); - return; + ANN("rescue clause (cont'd)"); + ANN("format: rescue [nd_args]; [nd_body]; (rescue) [nd_head]"); + ANN("example: begin; foo; rescue; bar; else; baz; end"); + F_NODE(nd_args, "rescue exceptions"); + F_NODE(nd_body, "rescue clause"); + LAST_NODE; + F_NODE(nd_head, "next rescue clause"); + return; case NODE_ENSURE: - ANN("ensure clause"); - ANN("format: begin; [nd_head]; ensure; [nd_ensr]; end"); - ANN("example: begin; foo; ensure; bar; end"); - F_NODE(nd_head, "body"); - LAST_NODE; - F_NODE(nd_ensr, "ensure clause"); - return; + ANN("ensure clause"); + ANN("format: begin; [nd_head]; ensure; [nd_ensr]; end"); + ANN("example: begin; foo; ensure; bar; end"); + F_NODE(nd_head, "body"); + LAST_NODE; + F_NODE(nd_ensr, "ensure clause"); + return; case NODE_AND: - ANN("&& operator"); - ANN("format: [nd_1st] && [nd_2nd]"); - ANN("example: foo && bar"); - goto andor; + ANN("&& operator"); + ANN("format: [nd_1st] && [nd_2nd]"); + ANN("example: foo && bar"); + goto andor; case NODE_OR: - ANN("|| operator"); - ANN("format: [nd_1st] || [nd_2nd]"); - ANN("example: foo || bar"); + ANN("|| operator"); + ANN("format: [nd_1st] || [nd_2nd]"); + ANN("example: foo || bar"); andor: - while (1) { - F_NODE(nd_1st, "left expr"); - if (!node->nd_2nd || !nd_type_p(node->nd_2nd, type)) - break; - node = node->nd_2nd; - } - LAST_NODE; - F_NODE(nd_2nd, "right expr"); - return; + while (1) { + F_NODE(nd_1st, "left expr"); + if (!node->nd_2nd || !nd_type_p(node->nd_2nd, type)) + break; + node = node->nd_2nd; + } + LAST_NODE; + F_NODE(nd_2nd, "right expr"); + return; case NODE_MASGN: - ANN("multiple assignment"); - ANN("format: [nd_head], [nd_args] = [nd_value]"); - ANN("example: a, b = foo"); - F_NODE(nd_value, "rhsn"); - F_NODE(nd_head, "lhsn"); - if (NODE_NAMED_REST_P(node->nd_args)) { - LAST_NODE; - F_NODE(nd_args, "splatn"); - } - else { - F_MSG(nd_args, "splatn", "NODE_SPECIAL_NO_NAME_REST (rest argument without name)"); - } - return; + ANN("multiple assignment"); + ANN("format: [nd_head], [nd_args] = [nd_value]"); + ANN("example: a, b = foo"); + F_NODE(nd_value, "rhsn"); + F_NODE(nd_head, "lhsn"); + if (NODE_NAMED_REST_P(node->nd_args)) { + LAST_NODE; + F_NODE(nd_args, "splatn"); + } + else { + F_MSG(nd_args, "splatn", "NODE_SPECIAL_NO_NAME_REST (rest argument without name)"); + } + return; case NODE_LASGN: - ANN("local variable assignment"); - ANN("format: [nd_vid](lvar) = [nd_value]"); - ANN("example: x = foo"); - F_ID(nd_vid, "local variable"); - if (NODE_REQUIRED_KEYWORD_P(node)) { - F_MSG(nd_value, "rvalue", "NODE_SPECIAL_REQUIRED_KEYWORD (required keyword argument)"); - } - else { - LAST_NODE; - F_NODE(nd_value, "rvalue"); - } - return; + ANN("local variable assignment"); + ANN("format: [nd_vid](lvar) = [nd_value]"); + ANN("example: x = foo"); + F_ID(nd_vid, "local variable"); + if (NODE_REQUIRED_KEYWORD_P(node)) { + F_MSG(nd_value, "rvalue", "NODE_SPECIAL_REQUIRED_KEYWORD (required keyword argument)"); + } + else { + LAST_NODE; + F_NODE(nd_value, "rvalue"); + } + return; case NODE_DASGN: - ANN("dynamic variable assignment"); - ANN("format: [nd_vid](dvar) = [nd_value]"); - ANN("example: x = nil; 1.times { x = foo }"); - ANN("example: 1.times { x = foo }"); - F_ID(nd_vid, "local variable"); - if (NODE_REQUIRED_KEYWORD_P(node)) { - F_MSG(nd_value, "rvalue", "NODE_SPECIAL_REQUIRED_KEYWORD (required keyword argument)"); - } - else { - LAST_NODE; - F_NODE(nd_value, "rvalue"); - } - return; + ANN("dynamic variable assignment"); + ANN("format: [nd_vid](dvar) = [nd_value]"); + ANN("example: x = nil; 1.times { x = foo }"); + ANN("example: 1.times { x = foo }"); + F_ID(nd_vid, "local variable"); + if (NODE_REQUIRED_KEYWORD_P(node)) { + F_MSG(nd_value, "rvalue", "NODE_SPECIAL_REQUIRED_KEYWORD (required keyword argument)"); + } + else { + LAST_NODE; + F_NODE(nd_value, "rvalue"); + } + return; case NODE_IASGN: - ANN("instance variable assignment"); - ANN("format: [nd_vid](ivar) = [nd_value]"); - ANN("example: @x = foo"); - F_ID(nd_vid, "instance variable"); - LAST_NODE; - F_NODE(nd_value, "rvalue"); - return; + ANN("instance variable assignment"); + ANN("format: [nd_vid](ivar) = [nd_value]"); + ANN("example: @x = foo"); + F_ID(nd_vid, "instance variable"); + LAST_NODE; + F_NODE(nd_value, "rvalue"); + return; case NODE_CVASGN: - ANN("class variable assignment"); - ANN("format: [nd_vid](cvar) = [nd_value]"); - ANN("example: @@x = foo"); - F_ID(nd_vid, "class variable"); - LAST_NODE; - F_NODE(nd_value, "rvalue"); - return; + ANN("class variable assignment"); + ANN("format: [nd_vid](cvar) = [nd_value]"); + ANN("example: @@x = foo"); + F_ID(nd_vid, "class variable"); + LAST_NODE; + F_NODE(nd_value, "rvalue"); + return; case NODE_GASGN: - ANN("global variable assignment"); - ANN("format: [nd_entry](gvar) = [nd_value]"); - ANN("example: $x = foo"); - F_GENTRY(nd_entry, "global variable"); - LAST_NODE; - F_NODE(nd_value, "rvalue"); - return; + ANN("global variable assignment"); + ANN("format: [nd_entry](gvar) = [nd_value]"); + ANN("example: $x = foo"); + F_GENTRY(nd_entry, "global variable"); + LAST_NODE; + F_NODE(nd_value, "rvalue"); + return; case NODE_CDECL: - ANN("constant declaration"); - ANN("format: [nd_else]::[nd_vid](constant) = [nd_value]"); - ANN("example: X = foo"); - if (node->nd_vid) { - F_ID(nd_vid, "constant"); - F_MSG(nd_else, "extension", "not used"); - } - else { - F_MSG(nd_vid, "constant", "0 (see extension field)"); - F_NODE(nd_else, "extension"); - } - LAST_NODE; - F_NODE(nd_value, "rvalue"); - return; + ANN("constant declaration"); + ANN("format: [nd_else]::[nd_vid](constant) = [nd_value]"); + ANN("example: X = foo"); + if (node->nd_vid) { + F_ID(nd_vid, "constant"); + F_MSG(nd_else, "extension", "not used"); + } + else { + F_MSG(nd_vid, "constant", "0 (see extension field)"); + F_NODE(nd_else, "extension"); + } + LAST_NODE; + F_NODE(nd_value, "rvalue"); + return; case NODE_OP_ASGN1: - ANN("array assignment with operator"); - ANN("format: [nd_recv] [ [nd_args->nd_head] ] [nd_mid]= [nd_args->nd_body]"); - ANN("example: ary[1] += foo"); - F_NODE(nd_recv, "receiver"); - F_ID(nd_mid, "operator"); - F_NODE(nd_args->nd_head, "index"); - LAST_NODE; - F_NODE(nd_args->nd_body, "rvalue"); - return; + ANN("array assignment with operator"); + ANN("format: [nd_recv] [ [nd_args->nd_head] ] [nd_mid]= [nd_args->nd_body]"); + ANN("example: ary[1] += foo"); + F_NODE(nd_recv, "receiver"); + F_ID(nd_mid, "operator"); + F_NODE(nd_args->nd_head, "index"); + LAST_NODE; + F_NODE(nd_args->nd_body, "rvalue"); + return; case NODE_OP_ASGN2: - ANN("attr assignment with operator"); - ANN("format: [nd_recv].[attr] [nd_next->nd_mid]= [nd_value]"); - ANN(" where [attr]: [nd_next->nd_vid]"); - ANN("example: struct.field += foo"); - F_NODE(nd_recv, "receiver"); - F_CUSTOM1(nd_next->nd_vid, "attr") { - if (node->nd_next->nd_aid) A("? "); - A_ID(node->nd_next->nd_vid); - } - F_ID(nd_next->nd_mid, "operator"); - LAST_NODE; - F_NODE(nd_value, "rvalue"); - return; + ANN("attr assignment with operator"); + ANN("format: [nd_recv].[attr] [nd_next->nd_mid]= [nd_value]"); + ANN(" where [attr]: [nd_next->nd_vid]"); + ANN("example: struct.field += foo"); + F_NODE(nd_recv, "receiver"); + F_CUSTOM1(nd_next->nd_vid, "attr") { + if (node->nd_next->nd_aid) A("? "); + A_ID(node->nd_next->nd_vid); + } + F_ID(nd_next->nd_mid, "operator"); + LAST_NODE; + F_NODE(nd_value, "rvalue"); + return; case NODE_OP_ASGN_AND: - ANN("assignment with && operator"); - ANN("format: [nd_head] &&= [nd_value]"); - ANN("example: foo &&= bar"); - goto asgn_andor; + ANN("assignment with && operator"); + ANN("format: [nd_head] &&= [nd_value]"); + ANN("example: foo &&= bar"); + goto asgn_andor; case NODE_OP_ASGN_OR: - ANN("assignment with || operator"); - ANN("format: [nd_head] ||= [nd_value]"); - ANN("example: foo ||= bar"); + ANN("assignment with || operator"); + ANN("format: [nd_head] ||= [nd_value]"); + ANN("example: foo ||= bar"); asgn_andor: - F_NODE(nd_head, "variable"); - LAST_NODE; - F_NODE(nd_value, "rvalue"); - return; + F_NODE(nd_head, "variable"); + LAST_NODE; + F_NODE(nd_value, "rvalue"); + return; case NODE_OP_CDECL: - ANN("constant declaration with operator"); - ANN("format: [nd_head](constant) [nd_aid]= [nd_value]"); - ANN("example: A::B ||= 1"); - F_NODE(nd_head, "constant"); - F_ID(nd_aid, "operator"); - LAST_NODE; - F_NODE(nd_value, "rvalue"); - return; + ANN("constant declaration with operator"); + ANN("format: [nd_head](constant) [nd_aid]= [nd_value]"); + ANN("example: A::B ||= 1"); + F_NODE(nd_head, "constant"); + F_ID(nd_aid, "operator"); + LAST_NODE; + F_NODE(nd_value, "rvalue"); + return; case NODE_CALL: - ANN("method invocation"); - ANN("format: [nd_recv].[nd_mid]([nd_args])"); - ANN("example: obj.foo(1)"); - F_ID(nd_mid, "method id"); - F_NODE(nd_recv, "receiver"); - LAST_NODE; - F_NODE(nd_args, "arguments"); - return; + ANN("method invocation"); + ANN("format: [nd_recv].[nd_mid]([nd_args])"); + ANN("example: obj.foo(1)"); + F_ID(nd_mid, "method id"); + F_NODE(nd_recv, "receiver"); + LAST_NODE; + F_NODE(nd_args, "arguments"); + return; case NODE_OPCALL: ANN("method invocation"); @@ -533,490 +533,490 @@ dump_node(VALUE buf, VALUE indent, int comment, const NODE * node) return; case NODE_FCALL: - ANN("function call"); - ANN("format: [nd_mid]([nd_args])"); - ANN("example: foo(1)"); - F_ID(nd_mid, "method id"); - LAST_NODE; - F_NODE(nd_args, "arguments"); - return; + ANN("function call"); + ANN("format: [nd_mid]([nd_args])"); + ANN("example: foo(1)"); + F_ID(nd_mid, "method id"); + LAST_NODE; + F_NODE(nd_args, "arguments"); + return; case NODE_VCALL: - ANN("function call with no argument"); - ANN("format: [nd_mid]"); - ANN("example: foo"); - F_ID(nd_mid, "method id"); - return; + ANN("function call with no argument"); + ANN("format: [nd_mid]"); + ANN("example: foo"); + F_ID(nd_mid, "method id"); + return; case NODE_QCALL: - ANN("safe method invocation"); - ANN("format: [nd_recv]&.[nd_mid]([nd_args])"); - ANN("example: obj&.foo(1)"); - F_ID(nd_mid, "method id"); - F_NODE(nd_recv, "receiver"); - LAST_NODE; - F_NODE(nd_args, "arguments"); - return; + ANN("safe method invocation"); + ANN("format: [nd_recv]&.[nd_mid]([nd_args])"); + ANN("example: obj&.foo(1)"); + F_ID(nd_mid, "method id"); + F_NODE(nd_recv, "receiver"); + LAST_NODE; + F_NODE(nd_args, "arguments"); + return; case NODE_SUPER: - ANN("super invocation"); - ANN("format: super [nd_args]"); - ANN("example: super 1"); - LAST_NODE; - F_NODE(nd_args, "arguments"); - return; + ANN("super invocation"); + ANN("format: super [nd_args]"); + ANN("example: super 1"); + LAST_NODE; + F_NODE(nd_args, "arguments"); + return; case NODE_ZSUPER: - ANN("super invocation with no argument"); - ANN("format: super"); - ANN("example: super"); - return; + ANN("super invocation with no argument"); + ANN("format: super"); + ANN("example: super"); + return; case NODE_LIST: - ANN("list constructor"); - ANN("format: [ [nd_head], [nd_next].. ] (length: [nd_alen])"); - ANN("example: [1, 2, 3]"); - goto ary; + ANN("list constructor"); + ANN("format: [ [nd_head], [nd_next].. ] (length: [nd_alen])"); + ANN("example: [1, 2, 3]"); + goto ary; case NODE_VALUES: - ANN("return arguments"); - ANN("format: [ [nd_head], [nd_next].. ] (length: [nd_alen])"); - ANN("example: return 1, 2, 3"); + ANN("return arguments"); + ANN("format: [ [nd_head], [nd_next].. ] (length: [nd_alen])"); + ANN("example: return 1, 2, 3"); ary: - dump_array(buf, indent, comment, node); - return; + dump_array(buf, indent, comment, node); + return; case NODE_ZLIST: - ANN("empty list constructor"); - ANN("format: []"); - ANN("example: []"); - return; + ANN("empty list constructor"); + ANN("format: []"); + ANN("example: []"); + return; case NODE_HASH: if (!node->nd_brace) { - ANN("keyword arguments"); - ANN("format: nd_head"); - ANN("example: a: 1, b: 2"); - } - else { - ANN("hash constructor"); - ANN("format: { [nd_head] }"); - ANN("example: { 1 => 2, 3 => 4 }"); - } + ANN("keyword arguments"); + ANN("format: nd_head"); + ANN("example: a: 1, b: 2"); + } + else { + ANN("hash constructor"); + ANN("format: { [nd_head] }"); + ANN("example: { 1 => 2, 3 => 4 }"); + } F_CUSTOM1(nd_brace, "keyword arguments or hash literal") { switch (node->nd_brace) { - case 0: A("0 (keyword argument)"); break; - case 1: A("1 (hash literal)"); break; - } - } - LAST_NODE; - F_NODE(nd_head, "contents"); - return; + case 0: A("0 (keyword argument)"); break; + case 1: A("1 (hash literal)"); break; + } + } + LAST_NODE; + F_NODE(nd_head, "contents"); + return; case NODE_YIELD: - ANN("yield invocation"); - ANN("format: yield [nd_head]"); - ANN("example: yield 1"); - LAST_NODE; - F_NODE(nd_head, "arguments"); - return; + ANN("yield invocation"); + ANN("format: yield [nd_head]"); + ANN("example: yield 1"); + LAST_NODE; + F_NODE(nd_head, "arguments"); + return; case NODE_LVAR: - ANN("local variable reference"); - ANN("format: [nd_vid](lvar)"); - ANN("example: x"); - F_ID(nd_vid, "local variable"); - return; + ANN("local variable reference"); + ANN("format: [nd_vid](lvar)"); + ANN("example: x"); + F_ID(nd_vid, "local variable"); + return; case NODE_DVAR: - ANN("dynamic variable reference"); - ANN("format: [nd_vid](dvar)"); - ANN("example: 1.times { x = 1; x }"); - F_ID(nd_vid, "local variable"); - return; + ANN("dynamic variable reference"); + ANN("format: [nd_vid](dvar)"); + ANN("example: 1.times { x = 1; x }"); + F_ID(nd_vid, "local variable"); + return; case NODE_IVAR: - ANN("instance variable reference"); - ANN("format: [nd_vid](ivar)"); - ANN("example: @x"); - F_ID(nd_vid, "instance variable"); - return; + ANN("instance variable reference"); + ANN("format: [nd_vid](ivar)"); + ANN("example: @x"); + F_ID(nd_vid, "instance variable"); + return; case NODE_CONST: - ANN("constant reference"); - ANN("format: [nd_vid](constant)"); - ANN("example: X"); - F_ID(nd_vid, "constant"); - return; + ANN("constant reference"); + ANN("format: [nd_vid](constant)"); + ANN("example: X"); + F_ID(nd_vid, "constant"); + return; case NODE_CVAR: - ANN("class variable reference"); - ANN("format: [nd_vid](cvar)"); - ANN("example: @@x"); - F_ID(nd_vid, "class variable"); - return; + ANN("class variable reference"); + ANN("format: [nd_vid](cvar)"); + ANN("example: @@x"); + F_ID(nd_vid, "class variable"); + return; case NODE_GVAR: - ANN("global variable reference"); - ANN("format: [nd_entry](gvar)"); - ANN("example: $x"); - F_GENTRY(nd_entry, "global variable"); - return; + ANN("global variable reference"); + ANN("format: [nd_entry](gvar)"); + ANN("example: $x"); + F_GENTRY(nd_entry, "global variable"); + return; case NODE_NTH_REF: - ANN("nth special variable reference"); - ANN("format: $[nd_nth]"); - ANN("example: $1, $2, .."); - F_CUSTOM1(nd_nth, "variable") { A("$"); A_LONG(node->nd_nth); } - return; + ANN("nth special variable reference"); + ANN("format: $[nd_nth]"); + ANN("example: $1, $2, .."); + F_CUSTOM1(nd_nth, "variable") { A("$"); A_LONG(node->nd_nth); } + return; case NODE_BACK_REF: - ANN("back special variable reference"); - ANN("format: $[nd_nth]"); - ANN("example: $&, $`, $', $+"); - F_CUSTOM1(nd_nth, "variable") { - char name[3] = "$ "; - name[1] = (char)node->nd_nth; - A(name); - } - return; + ANN("back special variable reference"); + ANN("format: $[nd_nth]"); + ANN("example: $&, $`, $', $+"); + F_CUSTOM1(nd_nth, "variable") { + char name[3] = "$ "; + name[1] = (char)node->nd_nth; + A(name); + } + return; case NODE_MATCH: - ANN("match expression (against $_ implicitly)"); + ANN("match expression (against $_ implicitly)"); ANN("format: [nd_lit] (in condition)"); - ANN("example: if /foo/; foo; end"); - F_LIT(nd_lit, "regexp"); - return; + ANN("example: if /foo/; foo; end"); + F_LIT(nd_lit, "regexp"); + return; case NODE_MATCH2: - ANN("match expression (regexp first)"); + ANN("match expression (regexp first)"); ANN("format: [nd_recv] =~ [nd_value]"); - ANN("example: /foo/ =~ 'foo'"); - F_NODE(nd_recv, "regexp (receiver)"); - if (!node->nd_args) LAST_NODE; - F_NODE(nd_value, "string (argument)"); - if (node->nd_args) { - LAST_NODE; - F_NODE(nd_args, "named captures"); - } - return; + ANN("example: /foo/ =~ 'foo'"); + F_NODE(nd_recv, "regexp (receiver)"); + if (!node->nd_args) LAST_NODE; + F_NODE(nd_value, "string (argument)"); + if (node->nd_args) { + LAST_NODE; + F_NODE(nd_args, "named captures"); + } + return; case NODE_MATCH3: - ANN("match expression (regexp second)"); + ANN("match expression (regexp second)"); ANN("format: [nd_recv] =~ [nd_value]"); - ANN("example: 'foo' =~ /foo/"); - F_NODE(nd_recv, "string (receiver)"); - LAST_NODE; - F_NODE(nd_value, "regexp (argument)"); - return; + ANN("example: 'foo' =~ /foo/"); + F_NODE(nd_recv, "string (receiver)"); + LAST_NODE; + F_NODE(nd_value, "regexp (argument)"); + return; case NODE_LIT: - ANN("literal"); - ANN("format: [nd_lit]"); - ANN("example: 1, /foo/"); - goto lit; + ANN("literal"); + ANN("format: [nd_lit]"); + ANN("example: 1, /foo/"); + goto lit; case NODE_STR: - ANN("string literal"); - ANN("format: [nd_lit]"); - ANN("example: 'foo'"); - goto lit; + ANN("string literal"); + ANN("format: [nd_lit]"); + ANN("example: 'foo'"); + goto lit; case NODE_XSTR: - ANN("xstring literal"); - ANN("format: [nd_lit]"); - ANN("example: `foo`"); + ANN("xstring literal"); + ANN("format: [nd_lit]"); + ANN("example: `foo`"); lit: - F_LIT(nd_lit, "literal"); - return; + F_LIT(nd_lit, "literal"); + return; case NODE_ONCE: - ANN("once evaluation"); - ANN("format: [nd_body]"); - ANN("example: /foo#{ bar }baz/o"); - LAST_NODE; - F_NODE(nd_body, "body"); - return; + ANN("once evaluation"); + ANN("format: [nd_body]"); + ANN("example: /foo#{ bar }baz/o"); + LAST_NODE; + F_NODE(nd_body, "body"); + return; case NODE_DSTR: - ANN("string literal with interpolation"); - ANN("format: [nd_lit]"); - ANN("example: \"foo#{ bar }baz\""); - goto dlit; + ANN("string literal with interpolation"); + ANN("format: [nd_lit]"); + ANN("example: \"foo#{ bar }baz\""); + goto dlit; case NODE_DXSTR: - ANN("xstring literal with interpolation"); - ANN("format: [nd_lit]"); - ANN("example: `foo#{ bar }baz`"); - goto dlit; + ANN("xstring literal with interpolation"); + ANN("format: [nd_lit]"); + ANN("example: `foo#{ bar }baz`"); + goto dlit; case NODE_DREGX: - ANN("regexp literal with interpolation"); - ANN("format: [nd_lit]"); - ANN("example: /foo#{ bar }baz/"); - goto dlit; + ANN("regexp literal with interpolation"); + ANN("format: [nd_lit]"); + ANN("example: /foo#{ bar }baz/"); + goto dlit; case NODE_DSYM: - ANN("symbol literal with interpolation"); - ANN("format: [nd_lit]"); - ANN("example: :\"foo#{ bar }baz\""); + ANN("symbol literal with interpolation"); + ANN("format: [nd_lit]"); + ANN("example: :\"foo#{ bar }baz\""); dlit: - F_LIT(nd_lit, "preceding string"); - if (!node->nd_next) return; - F_NODE(nd_next->nd_head, "interpolation"); - LAST_NODE; - F_NODE(nd_next->nd_next, "tailing strings"); - return; + F_LIT(nd_lit, "preceding string"); + if (!node->nd_next) return; + F_NODE(nd_next->nd_head, "interpolation"); + LAST_NODE; + F_NODE(nd_next->nd_next, "tailing strings"); + return; case NODE_EVSTR: - ANN("interpolation expression"); - ANN("format: \"..#{ [nd_lit] }..\""); - ANN("example: \"foo#{ bar }baz\""); - LAST_NODE; - F_NODE(nd_body, "body"); - return; + ANN("interpolation expression"); + ANN("format: \"..#{ [nd_lit] }..\""); + ANN("example: \"foo#{ bar }baz\""); + LAST_NODE; + F_NODE(nd_body, "body"); + return; case NODE_ARGSCAT: - ANN("splat argument following arguments"); - ANN("format: ..(*[nd_head], [nd_body..])"); - ANN("example: foo(*ary, post_arg1, post_arg2)"); - F_NODE(nd_head, "preceding array"); - LAST_NODE; - F_NODE(nd_body, "following array"); - return; + ANN("splat argument following arguments"); + ANN("format: ..(*[nd_head], [nd_body..])"); + ANN("example: foo(*ary, post_arg1, post_arg2)"); + F_NODE(nd_head, "preceding array"); + LAST_NODE; + F_NODE(nd_body, "following array"); + return; case NODE_ARGSPUSH: - ANN("splat argument following one argument"); - ANN("format: ..(*[nd_head], [nd_body])"); - ANN("example: foo(*ary, post_arg)"); - F_NODE(nd_head, "preceding array"); - LAST_NODE; - F_NODE(nd_body, "following element"); - return; + ANN("splat argument following one argument"); + ANN("format: ..(*[nd_head], [nd_body])"); + ANN("example: foo(*ary, post_arg)"); + F_NODE(nd_head, "preceding array"); + LAST_NODE; + F_NODE(nd_body, "following element"); + return; case NODE_SPLAT: - ANN("splat argument"); - ANN("format: *[nd_head]"); - ANN("example: foo(*ary)"); - LAST_NODE; - F_NODE(nd_head, "splat'ed array"); - return; + ANN("splat argument"); + ANN("format: *[nd_head]"); + ANN("example: foo(*ary)"); + LAST_NODE; + F_NODE(nd_head, "splat'ed array"); + return; case NODE_BLOCK_PASS: - ANN("arguments with block argument"); - ANN("format: ..([nd_head], &[nd_body])"); - ANN("example: foo(x, &blk)"); - F_NODE(nd_head, "other arguments"); - LAST_NODE; - F_NODE(nd_body, "block argument"); - return; + ANN("arguments with block argument"); + ANN("format: ..([nd_head], &[nd_body])"); + ANN("example: foo(x, &blk)"); + F_NODE(nd_head, "other arguments"); + LAST_NODE; + F_NODE(nd_body, "block argument"); + return; case NODE_DEFN: - ANN("method definition"); - ANN("format: def [nd_mid] [nd_defn]; end"); - ANN("example: def foo; bar; end"); - F_ID(nd_mid, "method name"); - LAST_NODE; - F_NODE(nd_defn, "method definition"); - return; + ANN("method definition"); + ANN("format: def [nd_mid] [nd_defn]; end"); + ANN("example: def foo; bar; end"); + F_ID(nd_mid, "method name"); + LAST_NODE; + F_NODE(nd_defn, "method definition"); + return; case NODE_DEFS: - ANN("singleton method definition"); - ANN("format: def [nd_recv].[nd_mid] [nd_defn]; end"); - ANN("example: def obj.foo; bar; end"); - F_NODE(nd_recv, "receiver"); - F_ID(nd_mid, "method name"); - LAST_NODE; - F_NODE(nd_defn, "method definition"); - return; + ANN("singleton method definition"); + ANN("format: def [nd_recv].[nd_mid] [nd_defn]; end"); + ANN("example: def obj.foo; bar; end"); + F_NODE(nd_recv, "receiver"); + F_ID(nd_mid, "method name"); + LAST_NODE; + F_NODE(nd_defn, "method definition"); + return; case NODE_ALIAS: - ANN("method alias statement"); - ANN("format: alias [nd_1st] [nd_2nd]"); - ANN("example: alias bar foo"); - F_NODE(nd_1st, "new name"); - LAST_NODE; - F_NODE(nd_2nd, "old name"); - return; + ANN("method alias statement"); + ANN("format: alias [nd_1st] [nd_2nd]"); + ANN("example: alias bar foo"); + F_NODE(nd_1st, "new name"); + LAST_NODE; + F_NODE(nd_2nd, "old name"); + return; case NODE_VALIAS: - ANN("global variable alias statement"); - ANN("format: alias [nd_alias](gvar) [nd_orig](gvar)"); - ANN("example: alias $y $x"); - F_ID(nd_alias, "new name"); - F_ID(nd_orig, "old name"); - return; + ANN("global variable alias statement"); + ANN("format: alias [nd_alias](gvar) [nd_orig](gvar)"); + ANN("example: alias $y $x"); + F_ID(nd_alias, "new name"); + F_ID(nd_orig, "old name"); + return; case NODE_UNDEF: - ANN("method undef statement"); - ANN("format: undef [nd_undef]"); - ANN("example: undef foo"); - LAST_NODE; - F_NODE(nd_undef, "old name"); - return; + ANN("method undef statement"); + ANN("format: undef [nd_undef]"); + ANN("example: undef foo"); + LAST_NODE; + F_NODE(nd_undef, "old name"); + return; case NODE_CLASS: - ANN("class definition"); - ANN("format: class [nd_cpath] < [nd_super]; [nd_body]; end"); - ANN("example: class C2 < C; ..; end"); - F_NODE(nd_cpath, "class path"); - F_NODE(nd_super, "superclass"); - LAST_NODE; - F_NODE(nd_body, "class definition"); - return; + ANN("class definition"); + ANN("format: class [nd_cpath] < [nd_super]; [nd_body]; end"); + ANN("example: class C2 < C; ..; end"); + F_NODE(nd_cpath, "class path"); + F_NODE(nd_super, "superclass"); + LAST_NODE; + F_NODE(nd_body, "class definition"); + return; case NODE_MODULE: - ANN("module definition"); - ANN("format: module [nd_cpath]; [nd_body]; end"); - ANN("example: module M; ..; end"); - F_NODE(nd_cpath, "module path"); - LAST_NODE; - F_NODE(nd_body, "module definition"); - return; + ANN("module definition"); + ANN("format: module [nd_cpath]; [nd_body]; end"); + ANN("example: module M; ..; end"); + F_NODE(nd_cpath, "module path"); + LAST_NODE; + F_NODE(nd_body, "module definition"); + return; case NODE_SCLASS: - ANN("singleton class definition"); - ANN("format: class << [nd_recv]; [nd_body]; end"); - ANN("example: class << obj; ..; end"); - F_NODE(nd_recv, "receiver"); - LAST_NODE; - F_NODE(nd_body, "singleton class definition"); - return; + ANN("singleton class definition"); + ANN("format: class << [nd_recv]; [nd_body]; end"); + ANN("example: class << obj; ..; end"); + F_NODE(nd_recv, "receiver"); + LAST_NODE; + F_NODE(nd_body, "singleton class definition"); + return; case NODE_COLON2: - ANN("scoped constant reference"); - ANN("format: [nd_head]::[nd_mid]"); - ANN("example: M::C"); - F_ID(nd_mid, "constant name"); - LAST_NODE; - F_NODE(nd_head, "receiver"); - return; + ANN("scoped constant reference"); + ANN("format: [nd_head]::[nd_mid]"); + ANN("example: M::C"); + F_ID(nd_mid, "constant name"); + LAST_NODE; + F_NODE(nd_head, "receiver"); + return; case NODE_COLON3: - ANN("top-level constant reference"); - ANN("format: ::[nd_mid]"); - ANN("example: ::Object"); - F_ID(nd_mid, "constant name"); - return; + ANN("top-level constant reference"); + ANN("format: ::[nd_mid]"); + ANN("example: ::Object"); + F_ID(nd_mid, "constant name"); + return; case NODE_DOT2: - ANN("range constructor (incl.)"); - ANN("format: [nd_beg]..[nd_end]"); - ANN("example: 1..5"); - goto dot; + ANN("range constructor (incl.)"); + ANN("format: [nd_beg]..[nd_end]"); + ANN("example: 1..5"); + goto dot; case NODE_DOT3: - ANN("range constructor (excl.)"); - ANN("format: [nd_beg]...[nd_end]"); - ANN("example: 1...5"); - goto dot; + ANN("range constructor (excl.)"); + ANN("format: [nd_beg]...[nd_end]"); + ANN("example: 1...5"); + goto dot; case NODE_FLIP2: - ANN("flip-flop condition (incl.)"); - ANN("format: [nd_beg]..[nd_end]"); - ANN("example: if (x==1)..(x==5); foo; end"); - goto dot; + ANN("flip-flop condition (incl.)"); + ANN("format: [nd_beg]..[nd_end]"); + ANN("example: if (x==1)..(x==5); foo; end"); + goto dot; case NODE_FLIP3: - ANN("flip-flop condition (excl.)"); - ANN("format: [nd_beg]...[nd_end]"); - ANN("example: if (x==1)...(x==5); foo; end"); + ANN("flip-flop condition (excl.)"); + ANN("format: [nd_beg]...[nd_end]"); + ANN("example: if (x==1)...(x==5); foo; end"); dot: - F_NODE(nd_beg, "begin"); - LAST_NODE; - F_NODE(nd_end, "end"); - return; + F_NODE(nd_beg, "begin"); + LAST_NODE; + F_NODE(nd_end, "end"); + return; case NODE_SELF: - ANN("self"); - ANN("format: self"); - ANN("example: self"); - return; + ANN("self"); + ANN("format: self"); + ANN("example: self"); + return; case NODE_NIL: - ANN("nil"); - ANN("format: nil"); - ANN("example: nil"); - return; + ANN("nil"); + ANN("format: nil"); + ANN("example: nil"); + return; case NODE_TRUE: - ANN("true"); - ANN("format: true"); - ANN("example: true"); - return; + ANN("true"); + ANN("format: true"); + ANN("example: true"); + return; case NODE_FALSE: - ANN("false"); - ANN("format: false"); - ANN("example: false"); - return; + ANN("false"); + ANN("format: false"); + ANN("example: false"); + return; case NODE_ERRINFO: - ANN("virtual reference to $!"); - ANN("format: rescue => id"); - ANN("example: rescue => id"); - return; + ANN("virtual reference to $!"); + ANN("format: rescue => id"); + ANN("example: rescue => id"); + return; case NODE_DEFINED: - ANN("defined? expression"); - ANN("format: defined?([nd_head])"); - ANN("example: defined?(foo)"); - F_NODE(nd_head, "expr"); - return; + ANN("defined? expression"); + ANN("format: defined?([nd_head])"); + ANN("example: defined?(foo)"); + F_NODE(nd_head, "expr"); + return; case NODE_POSTEXE: - ANN("post-execution"); - ANN("format: END { [nd_body] }"); - ANN("example: END { foo }"); - LAST_NODE; - F_NODE(nd_body, "END clause"); - return; + ANN("post-execution"); + ANN("format: END { [nd_body] }"); + ANN("example: END { foo }"); + LAST_NODE; + F_NODE(nd_body, "END clause"); + return; case NODE_ATTRASGN: - ANN("attr assignment"); - ANN("format: [nd_recv].[nd_mid] = [nd_args]"); - ANN("example: struct.field = foo"); - F_NODE(nd_recv, "receiver"); - F_ID(nd_mid, "method name"); - LAST_NODE; - F_NODE(nd_args, "arguments"); - return; + ANN("attr assignment"); + ANN("format: [nd_recv].[nd_mid] = [nd_args]"); + ANN("example: struct.field = foo"); + F_NODE(nd_recv, "receiver"); + F_ID(nd_mid, "method name"); + LAST_NODE; + F_NODE(nd_args, "arguments"); + return; case NODE_LAMBDA: - ANN("lambda expression"); - ANN("format: -> [nd_body]"); - ANN("example: -> { foo }"); - LAST_NODE; - F_NODE(nd_body, "lambda clause"); - return; + ANN("lambda expression"); + ANN("format: -> [nd_body]"); + ANN("example: -> { foo }"); + LAST_NODE; + F_NODE(nd_body, "lambda clause"); + return; case NODE_OPT_ARG: - ANN("optional arguments"); - ANN("format: def method_name([nd_body=some], [nd_next..])"); - ANN("example: def foo(a, b=1, c); end"); - F_NODE(nd_body, "body"); - LAST_NODE; - F_NODE(nd_next, "next"); - return; + ANN("optional arguments"); + ANN("format: def method_name([nd_body=some], [nd_next..])"); + ANN("example: def foo(a, b=1, c); end"); + F_NODE(nd_body, "body"); + LAST_NODE; + F_NODE(nd_next, "next"); + return; case NODE_KW_ARG: - ANN("keyword arguments"); - ANN("format: def method_name([nd_body=some], [nd_next..])"); - ANN("example: def foo(a:1, b:2); end"); - F_NODE(nd_body, "body"); - LAST_NODE; - F_NODE(nd_next, "next"); - return; + ANN("keyword arguments"); + ANN("format: def method_name([nd_body=some], [nd_next..])"); + ANN("example: def foo(a:1, b:2); end"); + F_NODE(nd_body, "body"); + LAST_NODE; + F_NODE(nd_next, "next"); + return; case NODE_POSTARG: - ANN("post arguments"); - ANN("format: *[nd_1st], [nd_2nd..] = .."); - ANN("example: a, *rest, z = foo"); - if (NODE_NAMED_REST_P(node->nd_1st)) { - F_NODE(nd_1st, "rest argument"); - } - else { - F_MSG(nd_1st, "rest argument", "NODE_SPECIAL_NO_NAME_REST (rest argument without name)"); - } - LAST_NODE; - F_NODE(nd_2nd, "post arguments"); - return; + ANN("post arguments"); + ANN("format: *[nd_1st], [nd_2nd..] = .."); + ANN("example: a, *rest, z = foo"); + if (NODE_NAMED_REST_P(node->nd_1st)) { + F_NODE(nd_1st, "rest argument"); + } + else { + F_MSG(nd_1st, "rest argument", "NODE_SPECIAL_NO_NAME_REST (rest argument without name)"); + } + LAST_NODE; + F_NODE(nd_2nd, "post arguments"); + return; case NODE_ARGS: - ANN("method parameters"); - ANN("format: def method_name(.., [nd_ainfo->nd_optargs], *[nd_ainfo->rest_arg], [nd_ainfo->first_post_arg], .., [nd_ainfo->kw_args], **[nd_ainfo->kw_rest_arg], &[nd_ainfo->block_arg])"); - ANN("example: def foo(a, b, opt1=1, opt2=2, *rest, y, z, kw: 1, **kwrest, &blk); end"); - F_INT(nd_ainfo->pre_args_num, "count of mandatory (pre-)arguments"); - F_NODE(nd_ainfo->pre_init, "initialization of (pre-)arguments"); - F_INT(nd_ainfo->post_args_num, "count of mandatory post-arguments"); - F_NODE(nd_ainfo->post_init, "initialization of post-arguments"); - F_ID(nd_ainfo->first_post_arg, "first post argument"); + ANN("method parameters"); + ANN("format: def method_name(.., [nd_ainfo->nd_optargs], *[nd_ainfo->rest_arg], [nd_ainfo->first_post_arg], .., [nd_ainfo->kw_args], **[nd_ainfo->kw_rest_arg], &[nd_ainfo->block_arg])"); + ANN("example: def foo(a, b, opt1=1, opt2=2, *rest, y, z, kw: 1, **kwrest, &blk); end"); + F_INT(nd_ainfo->pre_args_num, "count of mandatory (pre-)arguments"); + F_NODE(nd_ainfo->pre_init, "initialization of (pre-)arguments"); + F_INT(nd_ainfo->post_args_num, "count of mandatory post-arguments"); + F_NODE(nd_ainfo->post_init, "initialization of post-arguments"); + F_ID(nd_ainfo->first_post_arg, "first post argument"); F_CUSTOM1(nd_ainfo->rest_arg, "rest argument") { if (node->nd_ainfo->rest_arg == NODE_SPECIAL_EXCESSIVE_COMMA) { A("1 (excessed comma)"); @@ -1025,29 +1025,29 @@ dump_node(VALUE buf, VALUE indent, int comment, const NODE * node) A_ID(node->nd_ainfo->rest_arg); } } - F_ID(nd_ainfo->block_arg, "block argument"); - F_NODE(nd_ainfo->opt_args, "optional arguments"); - F_NODE(nd_ainfo->kw_args, "keyword arguments"); - LAST_NODE; - F_NODE(nd_ainfo->kw_rest_arg, "keyword rest argument"); - return; + F_ID(nd_ainfo->block_arg, "block argument"); + F_NODE(nd_ainfo->opt_args, "optional arguments"); + F_NODE(nd_ainfo->kw_args, "keyword arguments"); + LAST_NODE; + F_NODE(nd_ainfo->kw_rest_arg, "keyword rest argument"); + return; case NODE_SCOPE: - ANN("new scope"); - ANN("format: [nd_tbl]: local table, [nd_args]: arguments, [nd_body]: body"); - F_CUSTOM1(nd_tbl, "local table") { - rb_ast_id_table_t *tbl = node->nd_tbl; - int i; - int size = tbl ? tbl->size : 0; - if (size == 0) A("(empty)"); - for (i = 0; i < size; i++) { - A_ID(tbl->ids[i]); if (i < size - 1) A(","); - } - } - F_NODE(nd_args, "arguments"); - LAST_NODE; - F_NODE(nd_body, "body"); - return; + ANN("new scope"); + ANN("format: [nd_tbl]: local table, [nd_args]: arguments, [nd_body]: body"); + F_CUSTOM1(nd_tbl, "local table") { + rb_ast_id_table_t *tbl = node->nd_tbl; + int i; + int size = tbl ? tbl->size : 0; + if (size == 0) A("(empty)"); + for (i = 0; i < size; i++) { + A_ID(tbl->ids[i]); if (i < size - 1) A(","); + } + } + F_NODE(nd_args, "arguments"); + LAST_NODE; + F_NODE(nd_body, "body"); + return; case NODE_ARYPTN: ANN("array pattern"); @@ -1101,7 +1101,7 @@ dump_node(VALUE buf, VALUE indent, int comment, const NODE * node) case NODE_ARGS_AUX: case NODE_LAST: - break; + break; } rb_bug("dump_node: unknown node: %s", ruby_node_name(nd_type(node))); @@ -1111,10 +1111,10 @@ VALUE rb_parser_dump_tree(const NODE *node, int comment) { VALUE buf = rb_str_new_cstr( - "###########################################################\n" - "## Do NOT use this node dump for any purpose other than ##\n" - "## debug and research. Compatibility is not guaranteed. ##\n" - "###########################################################\n\n" + "###########################################################\n" + "## Do NOT use this node dump for any purpose other than ##\n" + "## debug and research. Compatibility is not guaranteed. ##\n" + "###########################################################\n\n" ); dump_node(buf, rb_str_new_cstr("# "), comment, node); return buf; @@ -1192,9 +1192,9 @@ node_buffer_list_free(node_buffer_list_t * nb) node_buffer_elem_t *nbe = nb->head; while (nbe != nb->last) { - void *buf = nbe; - nbe = nbe->next; - xfree(buf); + void *buf = nbe; + nbe = nbe->next; + xfree(buf); } } @@ -1224,14 +1224,14 @@ static NODE * ast_newnode_in_bucket(node_buffer_list_t *nb) { if (nb->idx >= nb->len) { - long n = nb->len * 2; - node_buffer_elem_t *nbe; + long n = nb->len * 2; + node_buffer_elem_t *nbe; nbe = rb_xmalloc_mul_add(n, sizeof(NODE), offsetof(node_buffer_elem_t, buf)); nbe->len = n; - nb->idx = 0; - nb->len = n; - nbe->next = nb->head; - nb->head = nbe; + nb->idx = 0; + nb->len = n; + nbe->next = nb->head; + nb->head = nbe; } return &nb->head->buf[nb->idx++]; } @@ -1428,8 +1428,8 @@ void rb_ast_free(rb_ast_t *ast) { if (ast->node_buffer) { - rb_node_buffer_free(ast->node_buffer); - ast->node_buffer = 0; + rb_node_buffer_free(ast->node_buffer); + ast->node_buffer = 0; } } diff --git a/node.h b/node.h index ebe82b85be..d97c333ab5 100644 --- a/node.h +++ b/node.h @@ -155,25 +155,25 @@ typedef struct rb_ast_id_table { typedef struct RNode { VALUE flags; union { - struct RNode *node; - ID id; - VALUE value; - rb_ast_id_table_t *tbl; + struct RNode *node; + ID id; + VALUE value; + rb_ast_id_table_t *tbl; } u1; union { - struct RNode *node; - ID id; - long argc; - VALUE value; + struct RNode *node; + ID id; + long argc; + VALUE value; } u2; union { - struct RNode *node; - ID id; - long state; - struct rb_args_info *args; - struct rb_ary_pattern_info *apinfo; - struct rb_fnd_pattern_info *fpinfo; - VALUE value; + struct RNode *node; + ID id; + long state; + struct rb_args_info *args; + struct rb_ary_pattern_info *apinfo; + struct rb_fnd_pattern_info *fpinfo; + VALUE value; } u3; rb_code_location_t nd_loc; int node_id; diff --git a/numeric.c b/numeric.c index 1b1c8d99b9..4f927f00fb 100644 --- a/numeric.c +++ b/numeric.c @@ -95,12 +95,12 @@ round(double x) double f; if (x > 0.0) { - f = floor(x); - x = f + (x - f >= 0.5); + f = floor(x); + x = f + (x - f >= 0.5); } else if (x < 0.0) { - f = ceil(x); - x = f - (f - x >= 0.5); + f = ceil(x); + x = f - (f - x >= 0.5); } return x; } @@ -114,12 +114,12 @@ round_half_up(double x, double s) f = round(xs); if (s == 1.0) return f; if (x > 0) { - if ((double)((f + 0.5) / s) <= x) f += 1; - x = f; + if ((double)((f + 0.5) / s) <= x) f += 1; + x = f; } else { - if ((double)((f - 0.5) / s) >= x) f -= 1; - x = f; + if ((double)((f - 0.5) / s) >= x) f -= 1; + x = f; } return x; } @@ -131,12 +131,12 @@ round_half_down(double x, double s) f = round(xs); if (x > 0) { - if ((double)((f - 0.5) / s) >= x) f -= 1; - x = f; + if ((double)((f - 0.5) / s) >= x) f -= 1; + x = f; } else { - if ((double)((f + 0.5) / s) <= x) f += 1; - x = f; + if ((double)((f + 0.5) / s) <= x) f += 1; + x = f; } return x; } @@ -147,26 +147,26 @@ round_half_even(double x, double s) double f, d, xs = x * s; if (x > 0.0) { - f = floor(xs); - d = xs - f; - if (d > 0.5) - d = 1.0; - else if (d == 0.5 || ((double)((f + 0.5) / s) <= x)) - d = fmod(f, 2.0); - else - d = 0.0; - x = f + d; + f = floor(xs); + d = xs - f; + if (d > 0.5) + d = 1.0; + else if (d == 0.5 || ((double)((f + 0.5) / s) <= x)) + d = fmod(f, 2.0); + else + d = 0.0; + x = f + d; } else if (x < 0.0) { - f = ceil(xs); - d = f - xs; - if (d > 0.5) - d = 1.0; - else if (d == 0.5 || ((double)((f - 0.5) / s) >= x)) - d = fmod(-f, 2.0); - else - d = 0.0; - x = f - d; + f = ceil(xs); + d = f - xs; + if (d > 0.5) + d = 1.0; + else if (d == 0.5 || ((double)((f - 0.5) / s) >= x)) + d = fmod(-f, 2.0); + else + d = 0.0; + x = f - d; } return x; } @@ -211,36 +211,36 @@ rb_num_get_rounding_option(VALUE opts) const char *s; if (!NIL_P(opts)) { - if (!round_kwds[0]) { - round_kwds[0] = rb_intern_const("half"); - } - if (!rb_get_kwargs(opts, round_kwds, 0, 1, &rounding)) goto noopt; - if (SYMBOL_P(rounding)) { - str = rb_sym2str(rounding); - } - else if (NIL_P(rounding)) { - goto noopt; - } - else if (!RB_TYPE_P(str = rounding, T_STRING)) { - str = rb_check_string_type(rounding); - if (NIL_P(str)) goto invalid; - } + if (!round_kwds[0]) { + round_kwds[0] = rb_intern_const("half"); + } + if (!rb_get_kwargs(opts, round_kwds, 0, 1, &rounding)) goto noopt; + if (SYMBOL_P(rounding)) { + str = rb_sym2str(rounding); + } + else if (NIL_P(rounding)) { + goto noopt; + } + else if (!RB_TYPE_P(str = rounding, T_STRING)) { + str = rb_check_string_type(rounding); + if (NIL_P(str)) goto invalid; + } rb_must_asciicompat(str); - s = RSTRING_PTR(str); - switch (RSTRING_LEN(str)) { - case 2: - if (rb_memcicmp(s, "up", 2) == 0) - return RUBY_NUM_ROUND_HALF_UP; - break; - case 4: - if (rb_memcicmp(s, "even", 4) == 0) - return RUBY_NUM_ROUND_HALF_EVEN; - if (strncasecmp(s, "down", 4) == 0) - return RUBY_NUM_ROUND_HALF_DOWN; - break; - } + s = RSTRING_PTR(str); + switch (RSTRING_LEN(str)) { + case 2: + if (rb_memcicmp(s, "up", 2) == 0) + return RUBY_NUM_ROUND_HALF_UP; + break; + case 4: + if (rb_memcicmp(s, "even", 4) == 0) + return RUBY_NUM_ROUND_HALF_EVEN; + if (strncasecmp(s, "down", 4) == 0) + return RUBY_NUM_ROUND_HALF_DOWN; + break; + } invalid: - rb_raise(rb_eArgError, "invalid rounding mode: % "PRIsVALUE, rounding); + rb_raise(rb_eArgError, "invalid rounding mode: % "PRIsVALUE, rounding); } noopt: return RUBY_NUM_ROUND_DEFAULT; @@ -254,25 +254,25 @@ rb_num_to_uint(VALUE val, unsigned int *ret) #define NUMERR_NEGATIVE 2 #define NUMERR_TOOLARGE 3 if (FIXNUM_P(val)) { - long v = FIX2LONG(val); + long v = FIX2LONG(val); #if SIZEOF_INT < SIZEOF_LONG - if (v > (long)UINT_MAX) return NUMERR_TOOLARGE; + if (v > (long)UINT_MAX) return NUMERR_TOOLARGE; #endif - if (v < 0) return NUMERR_NEGATIVE; - *ret = (unsigned int)v; - return 0; + if (v < 0) return NUMERR_NEGATIVE; + *ret = (unsigned int)v; + return 0; } if (RB_BIGNUM_TYPE_P(val)) { - if (BIGNUM_NEGATIVE_P(val)) return NUMERR_NEGATIVE; + if (BIGNUM_NEGATIVE_P(val)) return NUMERR_NEGATIVE; #if SIZEOF_INT < SIZEOF_LONG - /* long is 64bit */ - return NUMERR_TOOLARGE; + /* long is 64bit */ + return NUMERR_TOOLARGE; #else - /* long is 32bit */ - if (rb_absint_size(val, NULL) > sizeof(int)) return NUMERR_TOOLARGE; - *ret = (unsigned int)rb_big2ulong((VALUE)val); - return 0; + /* long is 32bit */ + if (rb_absint_size(val, NULL) > sizeof(int)) return NUMERR_TOOLARGE; + *ret = (unsigned int)rb_big2ulong((VALUE)val); + return 0; #endif } return NUMERR_TYPE; @@ -284,10 +284,10 @@ static inline int int_pos_p(VALUE num) { if (FIXNUM_P(num)) { - return FIXNUM_POSITIVE_P(num); + return FIXNUM_POSITIVE_P(num); } else if (RB_BIGNUM_TYPE_P(num)) { - return BIGNUM_POSITIVE_P(num); + return BIGNUM_POSITIVE_P(num); } rb_raise(rb_eTypeError, "not an Integer"); } @@ -296,10 +296,10 @@ static inline int int_neg_p(VALUE num) { if (FIXNUM_P(num)) { - return FIXNUM_NEGATIVE_P(num); + return FIXNUM_NEGATIVE_P(num); } else if (RB_BIGNUM_TYPE_P(num)) { - return BIGNUM_NEGATIVE_P(num); + return BIGNUM_NEGATIVE_P(num); } rb_raise(rb_eTypeError, "not an Integer"); } @@ -327,19 +327,19 @@ num_funcall_op_0(VALUE x, VALUE arg, int recursive) { ID func = (ID)arg; if (recursive) { - const char *name = rb_id2name(func); - if (ISALNUM(name[0])) { - rb_name_error(func, "%"PRIsVALUE".%"PRIsVALUE, - x, ID2SYM(func)); - } - else if (name[0] && name[1] == '@' && !name[2]) { - rb_name_error(func, "%c%"PRIsVALUE, - name[0], x); - } - else { - rb_name_error(func, "%"PRIsVALUE"%"PRIsVALUE, - ID2SYM(func), x); - } + const char *name = rb_id2name(func); + if (ISALNUM(name[0])) { + rb_name_error(func, "%"PRIsVALUE".%"PRIsVALUE, + x, ID2SYM(func)); + } + else if (name[0] && name[1] == '@' && !name[2]) { + rb_name_error(func, "%c%"PRIsVALUE, + name[0], x); + } + else { + rb_name_error(func, "%"PRIsVALUE"%"PRIsVALUE, + ID2SYM(func), x); + } } return rb_funcallv(x, func, 0, 0); } @@ -357,12 +357,12 @@ num_funcall_op_1_recursion(VALUE x, ID func, VALUE y) { const char *name = rb_id2name(func); if (ISALNUM(name[0])) { - rb_name_error(func, "%"PRIsVALUE".%"PRIsVALUE"(%"PRIsVALUE")", - x, ID2SYM(func), y); + rb_name_error(func, "%"PRIsVALUE".%"PRIsVALUE"(%"PRIsVALUE")", + x, ID2SYM(func), y); } else { - rb_name_error(func, "%"PRIsVALUE"%"PRIsVALUE"%"PRIsVALUE, - x, ID2SYM(func), y); + rb_name_error(func, "%"PRIsVALUE"%"PRIsVALUE"%"PRIsVALUE, + x, ID2SYM(func), y); } } @@ -372,7 +372,7 @@ num_funcall_op_1(VALUE y, VALUE arg, int recursive) ID func = (ID)((VALUE *)arg)[0]; VALUE x = ((VALUE *)arg)[1]; if (recursive) { - num_funcall_op_1_recursion(x, func, y); + num_funcall_op_1_recursion(x, func, y); } return rb_funcall(x, func, 1, y); } @@ -425,7 +425,7 @@ static VALUE num_coerce(VALUE x, VALUE y) { if (CLASS_OF(x) == CLASS_OF(y)) - return rb_assoc_new(y, x); + return rb_assoc_new(y, x); x = rb_Float(x); y = rb_Float(y); return rb_assoc_new(y, x); @@ -436,13 +436,13 @@ static void coerce_failed(VALUE x, VALUE y) { if (SPECIAL_CONST_P(y) || SYMBOL_P(y) || RB_FLOAT_TYPE_P(y)) { - y = rb_inspect(y); + y = rb_inspect(y); } else { - y = rb_obj_class(y); + y = rb_obj_class(y); } rb_raise(rb_eTypeError, "%"PRIsVALUE" can't be coerced into %"PRIsVALUE, - y, rb_obj_class(x)); + y, rb_obj_class(x)); } static int @@ -450,16 +450,16 @@ do_coerce(VALUE *x, VALUE *y, int err) { VALUE ary = rb_check_funcall(*y, id_coerce, 1, x); if (ary == Qundef) { - if (err) { - coerce_failed(*x, *y); - } - return FALSE; + if (err) { + coerce_failed(*x, *y); + } + return FALSE; } if (!err && NIL_P(ary)) { - return FALSE; + return FALSE; } if (!RB_TYPE_P(ary, T_ARRAY) || RARRAY_LEN(ary) != 2) { - rb_raise(rb_eTypeError, "coerce must return [x, y]"); + rb_raise(rb_eTypeError, "coerce must return [x, y]"); } *x = RARRAY_AREF(ary, 0); @@ -478,7 +478,7 @@ VALUE rb_num_coerce_cmp(VALUE x, VALUE y, ID func) { if (do_coerce(&x, &y, FALSE)) - return rb_funcall(x, func, 1, y); + return rb_funcall(x, func, 1, y); return Qnil; } @@ -495,8 +495,8 @@ rb_num_coerce_relop(VALUE x, VALUE y, ID func) VALUE x0 = x, y0 = y; if (!do_coerce(&x, &y, FALSE)) { - rb_cmperr(x0, y0); - UNREACHABLE_RETURN(Qnil); + rb_cmperr(x0, y0); + UNREACHABLE_RETURN(Qnil); } return ensure_cmp(rb_funcall(x, func, 1, y), x0, y0); } @@ -518,9 +518,9 @@ num_sadded(VALUE x, VALUE name) /* ruby_frame = ruby_frame->prev; */ /* pop frame for "singleton_method_added" */ rb_remove_method_id(rb_singleton_class(x), mid); rb_raise(rb_eTypeError, - "can't define singleton method \"%"PRIsVALUE"\" for %"PRIsVALUE, - rb_id2str(mid), - rb_obj_class(x)); + "can't define singleton method \"%"PRIsVALUE"\" for %"PRIsVALUE, + rb_id2str(mid), + rb_obj_class(x)); UNREACHABLE_RETURN(Qnil); } @@ -697,7 +697,7 @@ num_modulo(VALUE x, VALUE y) { VALUE q = num_funcall1(x, id_div, y); return rb_funcall(x, '-', 1, - rb_funcall(y, '*', 1, q)); + rb_funcall(y, '*', 1, q)); } /* @@ -737,16 +737,16 @@ num_remainder(VALUE x, VALUE y) VALUE z = num_funcall1(x, '%', y); if ((!rb_equal(z, INT2FIX(0))) && - ((rb_num_negative_int_p(x) && - rb_num_positive_int_p(y)) || - (rb_num_positive_int_p(x) && - rb_num_negative_int_p(y)))) { + ((rb_num_negative_int_p(x) && + rb_num_positive_int_p(y)) || + (rb_num_positive_int_p(x) && + rb_num_negative_int_p(y)))) { if (RB_FLOAT_TYPE_P(y)) { if (isinf(RFLOAT_VALUE(y))) { return x; } } - return rb_funcall(z, '-', 1, y); + return rb_funcall(z, '-', 1, y); } return z; } @@ -803,7 +803,7 @@ static VALUE num_abs(VALUE num) { if (rb_num_negative_int_p(num)) { - return num_funcall0(num, idUMinus); + return num_funcall0(num, idUMinus); } return num; } @@ -863,7 +863,7 @@ static VALUE num_nonzero_p(VALUE num) { if (RTEST(num_funcall0(num, rb_intern("zero?")))) { - return Qnil; + return Qnil; } return num; } @@ -907,12 +907,12 @@ num_positive_p(VALUE num) const ID mid = '>'; if (FIXNUM_P(num)) { - if (method_basic_p(rb_cInteger)) - return RBOOL((SIGNED_VALUE)num > (SIGNED_VALUE)INT2FIX(0)); + if (method_basic_p(rb_cInteger)) + return RBOOL((SIGNED_VALUE)num > (SIGNED_VALUE)INT2FIX(0)); } else if (RB_BIGNUM_TYPE_P(num)) { - if (method_basic_p(rb_cInteger)) - return RBOOL(BIGNUM_POSITIVE_P(num) && !rb_bigzero_p(num)); + if (method_basic_p(rb_cInteger)) + return RBOOL(BIGNUM_POSITIVE_P(num) && !rb_bigzero_p(num)); } return rb_num_compare_with_zero(num, mid); } @@ -1062,12 +1062,12 @@ flo_to_s(VALUE flt) int sign, decpt, digs; if (isinf(value)) { - static const char minf[] = "-Infinity"; - const int pos = (value > 0); /* skip "-" */ - return rb_usascii_str_new(minf+pos, strlen(minf)-pos); + static const char minf[] = "-Infinity"; + const int pos = (value > 0); /* skip "-" */ + return rb_usascii_str_new(minf+pos, strlen(minf)-pos); } else if (isnan(value)) - return rb_usascii_str_new2("NaN"); + return rb_usascii_str_new2("NaN"); p = ruby_dtoa(value, 0, 0, &decpt, &sign, &e); s = sign ? rb_usascii_str_new_cstr("-") : rb_usascii_str_new(0, 0); @@ -1075,35 +1075,35 @@ flo_to_s(VALUE flt) memcpy(buf, p, digs); xfree(p); if (decpt > 0) { - if (decpt < digs) { - memmove(buf + decpt + 1, buf + decpt, digs - decpt); - buf[decpt] = '.'; - rb_str_cat(s, buf, digs + 1); - } - else if (decpt <= DBL_DIG) { - long len; - char *ptr; - rb_str_cat(s, buf, digs); - rb_str_resize(s, (len = RSTRING_LEN(s)) + decpt - digs + 2); - ptr = RSTRING_PTR(s) + len; - if (decpt > digs) { - memset(ptr, '0', decpt - digs); - ptr += decpt - digs; - } - memcpy(ptr, ".0", 2); - } - else { - goto exp; - } + if (decpt < digs) { + memmove(buf + decpt + 1, buf + decpt, digs - decpt); + buf[decpt] = '.'; + rb_str_cat(s, buf, digs + 1); + } + else if (decpt <= DBL_DIG) { + long len; + char *ptr; + rb_str_cat(s, buf, digs); + rb_str_resize(s, (len = RSTRING_LEN(s)) + decpt - digs + 2); + ptr = RSTRING_PTR(s) + len; + if (decpt > digs) { + memset(ptr, '0', decpt - digs); + ptr += decpt - digs; + } + memcpy(ptr, ".0", 2); + } + else { + goto exp; + } } else if (decpt > -4) { - long len; - char *ptr; - rb_str_cat(s, "0.", 2); - rb_str_resize(s, (len = RSTRING_LEN(s)) - decpt + digs); - ptr = RSTRING_PTR(s); - memset(ptr += len, '0', -decpt); - memcpy(ptr -= decpt, buf, digs); + long len; + char *ptr; + rb_str_cat(s, "0.", 2); + rb_str_resize(s, (len = RSTRING_LEN(s)) - decpt + digs); + ptr = RSTRING_PTR(s); + memset(ptr += len, '0', -decpt); + memcpy(ptr -= decpt, buf, digs); } else { goto exp; @@ -1171,16 +1171,16 @@ VALUE rb_float_plus(VALUE x, VALUE y) { if (FIXNUM_P(y)) { - return DBL2NUM(RFLOAT_VALUE(x) + (double)FIX2LONG(y)); + return DBL2NUM(RFLOAT_VALUE(x) + (double)FIX2LONG(y)); } else if (RB_BIGNUM_TYPE_P(y)) { - return DBL2NUM(RFLOAT_VALUE(x) + rb_big2dbl(y)); + return DBL2NUM(RFLOAT_VALUE(x) + rb_big2dbl(y)); } else if (RB_FLOAT_TYPE_P(y)) { - return DBL2NUM(RFLOAT_VALUE(x) + RFLOAT_VALUE(y)); + return DBL2NUM(RFLOAT_VALUE(x) + RFLOAT_VALUE(y)); } else { - return rb_num_coerce_bin(x, y, '+'); + return rb_num_coerce_bin(x, y, '+'); } } @@ -1202,16 +1202,16 @@ VALUE rb_float_minus(VALUE x, VALUE y) { if (FIXNUM_P(y)) { - return DBL2NUM(RFLOAT_VALUE(x) - (double)FIX2LONG(y)); + return DBL2NUM(RFLOAT_VALUE(x) - (double)FIX2LONG(y)); } else if (RB_BIGNUM_TYPE_P(y)) { - return DBL2NUM(RFLOAT_VALUE(x) - rb_big2dbl(y)); + return DBL2NUM(RFLOAT_VALUE(x) - rb_big2dbl(y)); } else if (RB_FLOAT_TYPE_P(y)) { - return DBL2NUM(RFLOAT_VALUE(x) - RFLOAT_VALUE(y)); + return DBL2NUM(RFLOAT_VALUE(x) - RFLOAT_VALUE(y)); } else { - return rb_num_coerce_bin(x, y, '-'); + return rb_num_coerce_bin(x, y, '-'); } } @@ -1232,16 +1232,16 @@ VALUE rb_float_mul(VALUE x, VALUE y) { if (FIXNUM_P(y)) { - return DBL2NUM(RFLOAT_VALUE(x) * (double)FIX2LONG(y)); + return DBL2NUM(RFLOAT_VALUE(x) * (double)FIX2LONG(y)); } else if (RB_BIGNUM_TYPE_P(y)) { - return DBL2NUM(RFLOAT_VALUE(x) * rb_big2dbl(y)); + return DBL2NUM(RFLOAT_VALUE(x) * rb_big2dbl(y)); } else if (RB_FLOAT_TYPE_P(y)) { - return DBL2NUM(RFLOAT_VALUE(x) * RFLOAT_VALUE(y)); + return DBL2NUM(RFLOAT_VALUE(x) * RFLOAT_VALUE(y)); } else { - return rb_num_coerce_bin(x, y, '*'); + return rb_num_coerce_bin(x, y, '*'); } } @@ -1300,7 +1300,7 @@ rb_float_div(VALUE x, VALUE y) den = RFLOAT_VALUE(y); } else { - return rb_num_coerce_bin(x, y, '/'); + return rb_num_coerce_bin(x, y, '/'); } ret = double_div_double(num, den); @@ -1335,28 +1335,28 @@ flodivmod(double x, double y, double *divp, double *modp) double div, mod; if (isnan(y)) { - /* y is NaN so all results are NaN */ - if (modp) *modp = y; - if (divp) *divp = y; - return; + /* y is NaN so all results are NaN */ + if (modp) *modp = y; + if (divp) *divp = y; + return; } if (y == 0.0) rb_num_zerodiv(); if ((x == 0.0) || (isinf(y) && !isinf(x))) mod = x; else { #ifdef HAVE_FMOD - mod = fmod(x, y); + mod = fmod(x, y); #else - double z; + double z; - modf(x/y, &z); - mod = x - z * y; + modf(x/y, &z); + mod = x - z * y; #endif } if (isinf(x) && !isinf(y)) - div = x; + div = x; else { - div = (x - mod) / y; + div = (x - mod) / y; if (modp && divp) div = round(div); } if (y*mod < 0) { @@ -1417,16 +1417,16 @@ flo_mod(VALUE x, VALUE y) double fy; if (FIXNUM_P(y)) { - fy = (double)FIX2LONG(y); + fy = (double)FIX2LONG(y); } else if (RB_BIGNUM_TYPE_P(y)) { - fy = rb_big2dbl(y); + fy = rb_big2dbl(y); } else if (RB_FLOAT_TYPE_P(y)) { - fy = RFLOAT_VALUE(y); + fy = RFLOAT_VALUE(y); } else { - return rb_num_coerce_bin(x, y, '%'); + return rb_num_coerce_bin(x, y, '%'); } return DBL2NUM(ruby_float_mod(RFLOAT_VALUE(x), fy)); } @@ -1435,7 +1435,7 @@ static VALUE dbl2ival(double d) { if (FIXABLE(d)) { - return LONG2FIX((long)d); + return LONG2FIX((long)d); } return rb_dbl2big(d); } @@ -1473,16 +1473,16 @@ flo_divmod(VALUE x, VALUE y) volatile VALUE a, b; if (FIXNUM_P(y)) { - fy = (double)FIX2LONG(y); + fy = (double)FIX2LONG(y); } else if (RB_BIGNUM_TYPE_P(y)) { - fy = rb_big2dbl(y); + fy = rb_big2dbl(y); } else if (RB_FLOAT_TYPE_P(y)) { - fy = RFLOAT_VALUE(y); + fy = RFLOAT_VALUE(y); } else { - return rb_num_coerce_bin(x, y, id_divmod); + return rb_num_coerce_bin(x, y, id_divmod); } flodivmod(RFLOAT_VALUE(x), fy, &div, &mod); a = dbl2ival(div); @@ -1510,25 +1510,25 @@ rb_float_pow(VALUE x, VALUE y) { double dx, dy; if (y == INT2FIX(2)) { - dx = RFLOAT_VALUE(x); + dx = RFLOAT_VALUE(x); return DBL2NUM(dx * dx); } else if (FIXNUM_P(y)) { - dx = RFLOAT_VALUE(x); - dy = (double)FIX2LONG(y); + dx = RFLOAT_VALUE(x); + dy = (double)FIX2LONG(y); } else if (RB_BIGNUM_TYPE_P(y)) { - dx = RFLOAT_VALUE(x); - dy = rb_big2dbl(y); + dx = RFLOAT_VALUE(x); + dy = rb_big2dbl(y); } else if (RB_FLOAT_TYPE_P(y)) { - dx = RFLOAT_VALUE(x); - dy = RFLOAT_VALUE(y); - if (dx < 0 && dy != round(dy)) + dx = RFLOAT_VALUE(x); + dy = RFLOAT_VALUE(y); + if (dx < 0 && dy != round(dy)) return rb_dbl_complex_new_polar_pi(pow(-dx, dy), dy); } else { - return rb_num_coerce_bin(x, y, idPow); + return rb_num_coerce_bin(x, y, idPow); } return DBL2NUM(pow(dx, dy)); } @@ -1560,7 +1560,7 @@ num_eql(VALUE x, VALUE y) if (TYPE(x) != TYPE(y)) return Qfalse; if (RB_BIGNUM_TYPE_P(x)) { - return rb_big_eql(x, y); + return rb_big_eql(x, y); } return rb_equal(x, y); @@ -1618,13 +1618,13 @@ rb_float_equal(VALUE x, VALUE y) return rb_integer_float_eq(y, x); } else if (RB_FLOAT_TYPE_P(y)) { - b = RFLOAT_VALUE(y); + b = RFLOAT_VALUE(y); #if MSC_VERSION_BEFORE(1300) - if (isnan(b)) return Qfalse; + if (isnan(b)) return Qfalse; #endif } else { - return num_equal(x, y); + return num_equal(x, y); } a = RFLOAT_VALUE(x); #if MSC_VERSION_BEFORE(1300) @@ -1710,19 +1710,19 @@ flo_cmp(VALUE x, VALUE y) return rel; } else if (RB_FLOAT_TYPE_P(y)) { - b = RFLOAT_VALUE(y); + b = RFLOAT_VALUE(y); } else { - if (isinf(a) && (i = rb_check_funcall(y, rb_intern("infinite?"), 0, 0)) != Qundef) { - if (RTEST(i)) { - int j = rb_cmpint(i, x, y); - j = (a > 0.0) ? (j > 0 ? 0 : +1) : (j < 0 ? 0 : -1); - return INT2FIX(j); - } - if (a > 0.0) return INT2FIX(1); - return INT2FIX(-1); - } - return rb_num_coerce_cmp(x, y, id_cmp); + if (isinf(a) && (i = rb_check_funcall(y, rb_intern("infinite?"), 0, 0)) != Qundef) { + if (RTEST(i)) { + int j = rb_cmpint(i, x, y); + j = (a > 0.0) ? (j > 0 ? 0 : +1) : (j < 0 ? 0 : -1); + return INT2FIX(j); + } + if (a > 0.0) return INT2FIX(1); + return INT2FIX(-1); + } + return rb_num_coerce_cmp(x, y, id_cmp); } return rb_dbl_cmp(a, b); } @@ -1761,13 +1761,13 @@ rb_float_gt(VALUE x, VALUE y) return Qfalse; } else if (RB_FLOAT_TYPE_P(y)) { - b = RFLOAT_VALUE(y); + b = RFLOAT_VALUE(y); #if MSC_VERSION_BEFORE(1300) - if (isnan(b)) return Qfalse; + if (isnan(b)) return Qfalse; #endif } else { - return rb_num_coerce_relop(x, y, '>'); + return rb_num_coerce_relop(x, y, '>'); } #if MSC_VERSION_BEFORE(1300) if (isnan(a)) return Qfalse; @@ -1804,13 +1804,13 @@ flo_ge(VALUE x, VALUE y) return Qfalse; } else if (RB_FLOAT_TYPE_P(y)) { - b = RFLOAT_VALUE(y); + b = RFLOAT_VALUE(y); #if MSC_VERSION_BEFORE(1300) - if (isnan(b)) return Qfalse; + if (isnan(b)) return Qfalse; #endif } else { - return rb_num_coerce_relop(x, y, idGE); + return rb_num_coerce_relop(x, y, idGE); } #if MSC_VERSION_BEFORE(1300) if (isnan(a)) return Qfalse; @@ -1846,13 +1846,13 @@ flo_lt(VALUE x, VALUE y) return Qfalse; } else if (RB_FLOAT_TYPE_P(y)) { - b = RFLOAT_VALUE(y); + b = RFLOAT_VALUE(y); #if MSC_VERSION_BEFORE(1300) - if (isnan(b)) return Qfalse; + if (isnan(b)) return Qfalse; #endif } else { - return rb_num_coerce_relop(x, y, '<'); + return rb_num_coerce_relop(x, y, '<'); } #if MSC_VERSION_BEFORE(1300) if (isnan(a)) return Qfalse; @@ -1889,13 +1889,13 @@ flo_le(VALUE x, VALUE y) return Qfalse; } else if (RB_FLOAT_TYPE_P(y)) { - b = RFLOAT_VALUE(y); + b = RFLOAT_VALUE(y); #if MSC_VERSION_BEFORE(1300) - if (isnan(b)) return Qfalse; + if (isnan(b)) return Qfalse; #endif } else { - return rb_num_coerce_relop(x, y, idLE); + return rb_num_coerce_relop(x, y, idLE); } #if MSC_VERSION_BEFORE(1300) if (isnan(a)) return Qfalse; @@ -1925,10 +1925,10 @@ MJIT_FUNC_EXPORTED VALUE rb_float_eql(VALUE x, VALUE y) { if (RB_FLOAT_TYPE_P(y)) { - double a = RFLOAT_VALUE(x); - double b = RFLOAT_VALUE(y); + double a = RFLOAT_VALUE(x); + double b = RFLOAT_VALUE(y); #if MSC_VERSION_BEFORE(1300) - if (isnan(a) || isnan(b)) return Qfalse; + if (isnan(a) || isnan(b)) return Qfalse; #endif return RBOOL(a == b); } @@ -1993,7 +1993,7 @@ rb_flo_is_infinite_p(VALUE num) double value = RFLOAT_VALUE(num); if (isinf(value)) { - return INT2FIX( value < 0 ? -1 : 1 ); + return INT2FIX( value < 0 ? -1 : 1 ); } return Qnil; @@ -2131,16 +2131,16 @@ rb_float_floor(VALUE num, int ndigits) double number; number = RFLOAT_VALUE(num); if (number == 0.0) { - return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0); + return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0); } if (ndigits > 0) { - int binexp; + int binexp; double f, mul, res; - frexp(number, &binexp); - if (float_round_overflow(ndigits, binexp)) return num; - if (number > 0.0 && float_round_underflow(ndigits, binexp)) - return DBL2NUM(0.0); - f = pow(10, ndigits); + frexp(number, &binexp); + if (float_round_overflow(ndigits, binexp)) return num; + if (number > 0.0 && float_round_underflow(ndigits, binexp)) + return DBL2NUM(0.0); + f = pow(10, ndigits); mul = floor(number * f); res = (mul + 1) / f; if (res > number) @@ -2148,9 +2148,9 @@ rb_float_floor(VALUE num, int ndigits) return DBL2NUM(res); } else { - num = dbl2ival(floor(number)); - if (ndigits < 0) num = rb_int_floor(num, ndigits); - return num; + num = dbl2ival(floor(number)); + if (ndigits < 0) num = rb_int_floor(num, ndigits); + return num; } } @@ -2158,7 +2158,7 @@ static int flo_ndigits(int argc, VALUE *argv) { if (rb_check_arity(argc, 0, 1)) { - return NUM2INT(argv[0]); + return NUM2INT(argv[0]); } return 0; } @@ -2256,22 +2256,22 @@ rb_float_ceil(VALUE num, int ndigits) number = RFLOAT_VALUE(num); if (number == 0.0) { - return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0); + return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0); } if (ndigits > 0) { - int binexp; - frexp(number, &binexp); - if (float_round_overflow(ndigits, binexp)) return num; - if (number < 0.0 && float_round_underflow(ndigits, binexp)) - return DBL2NUM(0.0); - f = pow(10, ndigits); - f = ceil(number * f) / f; - return DBL2NUM(f); + int binexp; + frexp(number, &binexp); + if (float_round_overflow(ndigits, binexp)) return num; + if (number < 0.0 && float_round_underflow(ndigits, binexp)) + return DBL2NUM(0.0); + f = pow(10, ndigits); + f = ceil(number * f) / f; + return DBL2NUM(f); } else { - num = dbl2ival(ceil(number)); - if (ndigits < 0) num = rb_int_ceil(num, ndigits); - return num; + num = dbl2ival(ceil(number)); + if (ndigits < 0) num = rb_int_ceil(num, ndigits); + return num; } } @@ -2282,13 +2282,13 @@ int_round_zero_p(VALUE num, int ndigits) /* If 10**N / 2 > num, then return 0 */ /* We have log_256(10) > 0.415241 and log_256(1/2) = -0.125, so */ if (FIXNUM_P(num)) { - bytes = sizeof(long); + bytes = sizeof(long); } else if (RB_BIGNUM_TYPE_P(num)) { - bytes = rb_big_size(num); + bytes = rb_big_size(num); } else { - bytes = NUM2LONG(rb_funcall(num, idSize, 0)); + bytes = NUM2LONG(rb_funcall(num, idSize, 0)); } return (-0.415241 * ndigits - 0.125 > bytes); } @@ -2298,7 +2298,7 @@ int_round_half_even(SIGNED_VALUE x, SIGNED_VALUE y) { SIGNED_VALUE z = +(x + y / 2) / y; if ((z * y - x) * 2 == y) { - z &= ~1; + z &= ~1; } return z * y; } @@ -2342,29 +2342,29 @@ rb_int_round(VALUE num, int ndigits, enum ruby_num_rounding_mode mode) VALUE n, f, h, r; if (int_round_zero_p(num, ndigits)) { - return INT2FIX(0); + return INT2FIX(0); } f = int_pow(10, -ndigits); if (FIXNUM_P(num) && FIXNUM_P(f)) { - SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f); - int neg = x < 0; - if (neg) x = -x; - x = ROUND_CALL(mode, int_round, (x, y)); - if (neg) x = -x; - return LONG2NUM(x); + SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f); + int neg = x < 0; + if (neg) x = -x; + x = ROUND_CALL(mode, int_round, (x, y)); + if (neg) x = -x; + return LONG2NUM(x); } if (RB_FLOAT_TYPE_P(f)) { - /* then int_pow overflow */ - return INT2FIX(0); + /* then int_pow overflow */ + return INT2FIX(0); } h = rb_int_idiv(f, INT2FIX(2)); r = rb_int_modulo(num, f); n = rb_int_minus(num, r); r = rb_int_cmp(r, h); if (FIXNUM_POSITIVE_P(r) || - (FIXNUM_ZERO_P(r) && ROUND_CALL(mode, int_half_p, (num, n, f)))) { - n = rb_int_plus(n, f); + (FIXNUM_ZERO_P(r) && ROUND_CALL(mode, int_half_p, (num, n, f)))) { + n = rb_int_plus(n, f); } return n; } @@ -2375,19 +2375,19 @@ rb_int_floor(VALUE num, int ndigits) VALUE f; if (int_round_zero_p(num, ndigits)) - return INT2FIX(0); + return INT2FIX(0); f = int_pow(10, -ndigits); if (FIXNUM_P(num) && FIXNUM_P(f)) { - SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f); - int neg = x < 0; - if (neg) x = -x + y - 1; - x = x / y * y; - if (neg) x = -x; - return LONG2NUM(x); + SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f); + int neg = x < 0; + if (neg) x = -x + y - 1; + x = x / y * y; + if (neg) x = -x; + return LONG2NUM(x); } if (RB_FLOAT_TYPE_P(f)) { - /* then int_pow overflow */ - return INT2FIX(0); + /* then int_pow overflow */ + return INT2FIX(0); } return rb_int_minus(num, rb_int_modulo(num, f)); } @@ -2398,20 +2398,20 @@ rb_int_ceil(VALUE num, int ndigits) VALUE f; if (int_round_zero_p(num, ndigits)) - return INT2FIX(0); + return INT2FIX(0); f = int_pow(10, -ndigits); if (FIXNUM_P(num) && FIXNUM_P(f)) { - SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f); - int neg = x < 0; - if (neg) x = -x; - else x += y - 1; - x = (x / y) * y; - if (neg) x = -x; - return LONG2NUM(x); + SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f); + int neg = x < 0; + if (neg) x = -x; + else x += y - 1; + x = (x / y) * y; + if (neg) x = -x; + return LONG2NUM(x); } if (RB_FLOAT_TYPE_P(f)) { - /* then int_pow overflow */ - return INT2FIX(0); + /* then int_pow overflow */ + return INT2FIX(0); } return rb_int_plus(num, rb_int_minus(f, rb_int_modulo(num, f))); } @@ -2423,26 +2423,26 @@ rb_int_truncate(VALUE num, int ndigits) VALUE m; if (int_round_zero_p(num, ndigits)) - return INT2FIX(0); + return INT2FIX(0); f = int_pow(10, -ndigits); if (FIXNUM_P(num) && FIXNUM_P(f)) { - SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f); - int neg = x < 0; - if (neg) x = -x; - x = x / y * y; - if (neg) x = -x; - return LONG2NUM(x); + SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f); + int neg = x < 0; + if (neg) x = -x; + x = x / y * y; + if (neg) x = -x; + return LONG2NUM(x); } if (RB_FLOAT_TYPE_P(f)) { - /* then int_pow overflow */ - return INT2FIX(0); + /* then int_pow overflow */ + return INT2FIX(0); } m = rb_int_modulo(num, f); if (int_neg_p(num)) { - return rb_int_plus(num, rb_int_minus(f, m)); + return rb_int_plus(num, rb_int_minus(f, m)); } else { - return rb_int_minus(num, m); + return rb_int_minus(num, m); } } @@ -2510,32 +2510,32 @@ flo_round(int argc, VALUE *argv, VALUE num) enum ruby_num_rounding_mode mode; if (rb_scan_args(argc, argv, "01:", &nd, &opt)) { - ndigits = NUM2INT(nd); + ndigits = NUM2INT(nd); } mode = rb_num_get_rounding_option(opt); number = RFLOAT_VALUE(num); if (number == 0.0) { - return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0); + return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0); } if (ndigits < 0) { - return rb_int_round(flo_to_i(num), ndigits, mode); + return rb_int_round(flo_to_i(num), ndigits, mode); } if (ndigits == 0) { - x = ROUND_CALL(mode, round, (number, 1.0)); - return dbl2ival(x); + x = ROUND_CALL(mode, round, (number, 1.0)); + return dbl2ival(x); } if (isfinite(number)) { - int binexp; - frexp(number, &binexp); - if (float_round_overflow(ndigits, binexp)) return num; - if (float_round_underflow(ndigits, binexp)) return DBL2NUM(0); + int binexp; + frexp(number, &binexp); + if (float_round_overflow(ndigits, binexp)) return num; + if (float_round_underflow(ndigits, binexp)) return DBL2NUM(0); if (ndigits > 14) { /* In this case, pow(10, ndigits) may not be accurate. */ return rb_flo_round_by_rational(argc, argv, num); } - f = pow(10, ndigits); - x = ROUND_CALL(mode, round, (number, f)); - return DBL2NUM(x / f); + f = pow(10, ndigits); + x = ROUND_CALL(mode, round, (number, f)); + return DBL2NUM(x / f); } return num; } @@ -2553,17 +2553,17 @@ float_round_overflow(int ndigits, int binexp) If ndigits + exp <= 0, the result is 0 or "1e#{exp}", so if ndigits + exp < 0, the result is 0. We have: - 2 ** (binexp-1) <= |number| < 2 ** binexp - 10 ** ((binexp-1)/log_2(10)) <= |number| < 10 ** (binexp/log_2(10)) - If binexp >= 0, and since log_2(10) = 3.322259: - 10 ** (binexp/4 - 1) < |number| < 10 ** (binexp/3) - floor(binexp/4) <= exp <= ceil(binexp/3) - If binexp <= 0, swap the /4 and the /3 - So if ndigits + floor(binexp/(4 or 3)) >= float_dig, the result is number - If ndigits + ceil(binexp/(3 or 4)) < 0 the result is 0 + 2 ** (binexp-1) <= |number| < 2 ** binexp + 10 ** ((binexp-1)/log_2(10)) <= |number| < 10 ** (binexp/log_2(10)) + If binexp >= 0, and since log_2(10) = 3.322259: + 10 ** (binexp/4 - 1) < |number| < 10 ** (binexp/3) + floor(binexp/4) <= exp <= ceil(binexp/3) + If binexp <= 0, swap the /4 and the /3 + So if ndigits + floor(binexp/(4 or 3)) >= float_dig, the result is number + If ndigits + ceil(binexp/(3 or 4)) < 0 the result is 0 */ if (ndigits >= float_dig - (binexp > 0 ? binexp / 4 : binexp / 3 - 1)) { - return TRUE; + return TRUE; } return FALSE; } @@ -2572,7 +2572,7 @@ static int float_round_underflow(int ndigits, int binexp) { if (ndigits < - (binexp > 0 ? binexp / 3 + 1 : binexp / 4)) { - return TRUE; + return TRUE; } return FALSE; } @@ -2644,9 +2644,9 @@ static VALUE flo_truncate(int argc, VALUE *argv, VALUE num) { if (signbit(RFLOAT_VALUE(num))) - return flo_ceil(argc, argv, num); + return flo_ceil(argc, argv, num); else - return flo_floor(argc, argv, num); + return flo_floor(argc, argv, num); } /* @@ -2727,17 +2727,17 @@ ruby_float_step_size(double beg, double end, double unit, int excl) return HUGE_VAL; } if (isinf(unit)) { - return unit > 0 ? beg <= end : beg >= end; + return unit > 0 ? beg <= end : beg >= end; } n= (end - beg)/unit; err = (fabs(beg) + fabs(end) + fabs(end-beg)) / fabs(unit) * epsilon; if (err>0.5) err=0.5; if (excl) { - if (n<=0) return 0; - if (n<1) - n = 0; - else - n = floor(n - err); + if (n<=0) return 0; + if (n<1) + n = 0; + else + n = floor(n - err); d = +((n + 1) * unit) + beg; if (beg < end) { if (d < end) @@ -2749,8 +2749,8 @@ ruby_float_step_size(double beg, double end, double unit, int excl) } } else { - if (n<0) return 0; - n = floor(n + err); + if (n<0) return 0; + n = floor(n + err); d = +((n + 1) * unit) + beg; if (beg < end) { if (d <= end) @@ -2769,28 +2769,28 @@ ruby_float_step(VALUE from, VALUE to, VALUE step, int excl, int allow_endless) { if (RB_FLOAT_TYPE_P(from) || RB_FLOAT_TYPE_P(to) || RB_FLOAT_TYPE_P(step)) { double unit = NUM2DBL(step); - double beg = NUM2DBL(from); + double beg = NUM2DBL(from); double end = (allow_endless && NIL_P(to)) ? (unit < 0 ? -1 : 1)*HUGE_VAL : NUM2DBL(to); - double n = ruby_float_step_size(beg, end, unit, excl); - long i; + double n = ruby_float_step_size(beg, end, unit, excl); + long i; - if (isinf(unit)) { - /* if unit is infinity, i*unit+beg is NaN */ - if (n) rb_yield(DBL2NUM(beg)); - } - else if (unit == 0) { - VALUE val = DBL2NUM(beg); - for (;;) - rb_yield(val); - } - else { - for (i=0; i= 0 ? end < d : d < end) d = end; - rb_yield(DBL2NUM(d)); - } - } - return TRUE; + if (isinf(unit)) { + /* if unit is infinity, i*unit+beg is NaN */ + if (n) rb_yield(DBL2NUM(beg)); + } + else if (unit == 0) { + VALUE val = DBL2NUM(beg); + for (;;) + rb_yield(val); + } + else { + for (i=0; i= 0 ? end < d : d < end) d = end; + rb_yield(DBL2NUM(d)); + } + } + return TRUE; } return FALSE; } @@ -2799,45 +2799,45 @@ VALUE ruby_num_interval_step_size(VALUE from, VALUE to, VALUE step, int excl) { if (FIXNUM_P(from) && FIXNUM_P(to) && FIXNUM_P(step)) { - long delta, diff; + long delta, diff; - diff = FIX2LONG(step); - if (diff == 0) { - return DBL2NUM(HUGE_VAL); - } - delta = FIX2LONG(to) - FIX2LONG(from); - if (diff < 0) { - diff = -diff; - delta = -delta; - } - if (excl) { - delta--; - } - if (delta < 0) { - return INT2FIX(0); - } - return ULONG2NUM(delta / diff + 1UL); + diff = FIX2LONG(step); + if (diff == 0) { + return DBL2NUM(HUGE_VAL); + } + delta = FIX2LONG(to) - FIX2LONG(from); + if (diff < 0) { + diff = -diff; + delta = -delta; + } + if (excl) { + delta--; + } + if (delta < 0) { + return INT2FIX(0); + } + return ULONG2NUM(delta / diff + 1UL); } else if (RB_FLOAT_TYPE_P(from) || RB_FLOAT_TYPE_P(to) || RB_FLOAT_TYPE_P(step)) { - double n = ruby_float_step_size(NUM2DBL(from), NUM2DBL(to), NUM2DBL(step), excl); + double n = ruby_float_step_size(NUM2DBL(from), NUM2DBL(to), NUM2DBL(step), excl); - if (isinf(n)) return DBL2NUM(n); - if (POSFIXABLE(n)) return LONG2FIX((long)n); - return rb_dbl2big(n); + if (isinf(n)) return DBL2NUM(n); + if (POSFIXABLE(n)) return LONG2FIX((long)n); + return rb_dbl2big(n); } else { - VALUE result; - ID cmp = '>'; - switch (rb_cmpint(rb_num_coerce_cmp(step, INT2FIX(0), id_cmp), step, INT2FIX(0))) { - case 0: return DBL2NUM(HUGE_VAL); - case -1: cmp = '<'; break; - } - if (RTEST(rb_funcall(from, cmp, 1, to))) return INT2FIX(0); - result = rb_funcall(rb_funcall(to, '-', 1, from), id_div, 1, step); - if (!excl || RTEST(rb_funcall(rb_funcall(from, '+', 1, rb_funcall(result, '*', 1, step)), cmp, 1, to))) { - result = rb_funcall(result, '+', 1, INT2FIX(1)); - } - return result; + VALUE result; + ID cmp = '>'; + switch (rb_cmpint(rb_num_coerce_cmp(step, INT2FIX(0), id_cmp), step, INT2FIX(0))) { + case 0: return DBL2NUM(HUGE_VAL); + case -1: cmp = '<'; break; + } + if (RTEST(rb_funcall(from, cmp, 1, to))) return INT2FIX(0); + result = rb_funcall(rb_funcall(to, '-', 1, from), id_div, 1, step); + if (!excl || RTEST(rb_funcall(rb_funcall(from, '+', 1, rb_funcall(result, '*', 1, step)), cmp, 1, to))) { + result = rb_funcall(result, '+', 1, INT2FIX(1)); + } + return result; } } @@ -2849,17 +2849,17 @@ num_step_negative_p(VALUE num) VALUE r; if (FIXNUM_P(num)) { - if (method_basic_p(rb_cInteger)) - return (SIGNED_VALUE)num < 0; + if (method_basic_p(rb_cInteger)) + return (SIGNED_VALUE)num < 0; } else if (RB_BIGNUM_TYPE_P(num)) { - if (method_basic_p(rb_cInteger)) - return BIGNUM_NEGATIVE_P(num); + if (method_basic_p(rb_cInteger)) + return BIGNUM_NEGATIVE_P(num); } r = rb_check_funcall(num, '>', 1, &zero); if (r == Qundef) { - coerce_failed(num, INT2FIX(0)); + coerce_failed(num, INT2FIX(0)); } return !RTEST(r); } @@ -2871,19 +2871,19 @@ num_step_extract_args(int argc, const VALUE *argv, VALUE *to, VALUE *step, VALUE argc = rb_scan_args(argc, argv, "02:", to, step, &hash); if (!NIL_P(hash)) { - ID keys[2]; - VALUE values[2]; - keys[0] = id_to; - keys[1] = id_by; - rb_get_kwargs(hash, keys, 0, 2, values); - if (values[0] != Qundef) { - if (argc > 0) rb_raise(rb_eArgError, "to is given twice"); - *to = values[0]; - } - if (values[1] != Qundef) { - if (argc > 1) rb_raise(rb_eArgError, "step is given twice"); - *by = values[1]; - } + ID keys[2]; + VALUE values[2]; + keys[0] = id_to; + keys[1] = id_by; + rb_get_kwargs(hash, keys, 0, 2, values); + if (values[0] != Qundef) { + if (argc > 0) rb_raise(rb_eArgError, "to is given twice"); + *to = values[0]; + } + if (values[1] != Qundef) { + if (argc > 1) rb_raise(rb_eArgError, "step is given twice"); + *by = values[1]; + } } return argc; @@ -2906,7 +2906,7 @@ num_step_check_fix_args(int argc, VALUE *to, VALUE *step, VALUE by, int fix_nil, rb_raise(rb_eArgError, "step can't be 0"); } if (NIL_P(*step)) { - *step = INT2FIX(1); + *step = INT2FIX(1); } desc = num_step_negative_p(*step); if (fix_nil && NIL_P(*to)) { @@ -3061,48 +3061,48 @@ num_step(int argc, VALUE *argv, VALUE from) desc = num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE); if (rb_equal(step, INT2FIX(0))) { - inf = 1; + inf = 1; } else if (RB_FLOAT_TYPE_P(to)) { - double f = RFLOAT_VALUE(to); - inf = isinf(f) && (signbit(f) ? desc : !desc); + double f = RFLOAT_VALUE(to); + inf = isinf(f) && (signbit(f) ? desc : !desc); } else inf = 0; if (FIXNUM_P(from) && (inf || FIXNUM_P(to)) && FIXNUM_P(step)) { - long i = FIX2LONG(from); - long diff = FIX2LONG(step); + long i = FIX2LONG(from); + long diff = FIX2LONG(step); - if (inf) { - for (;; i += diff) - rb_yield(LONG2FIX(i)); - } - else { - long end = FIX2LONG(to); + if (inf) { + for (;; i += diff) + rb_yield(LONG2FIX(i)); + } + else { + long end = FIX2LONG(to); - if (desc) { - for (; i >= end; i += diff) - rb_yield(LONG2FIX(i)); - } - else { - for (; i <= end; i += diff) - rb_yield(LONG2FIX(i)); - } - } + if (desc) { + for (; i >= end; i += diff) + rb_yield(LONG2FIX(i)); + } + else { + for (; i <= end; i += diff) + rb_yield(LONG2FIX(i)); + } + } } else if (!ruby_float_step(from, to, step, FALSE, FALSE)) { - VALUE i = from; + VALUE i = from; - if (inf) { - for (;; i = rb_funcall(i, '+', 1, step)) - rb_yield(i); - } - else { - ID cmp = desc ? '<' : '>'; + if (inf) { + for (;; i = rb_funcall(i, '+', 1, step)) + rb_yield(i); + } + else { + ID cmp = desc ? '<' : '>'; - for (; !RTEST(rb_funcall(i, cmp, 1, to)); i = rb_funcall(i, '+', 1, step)) - rb_yield(i); - } + for (; !RTEST(rb_funcall(i, cmp, 1, to)); i = rb_funcall(i, '+', 1, step)) + rb_yield(i); + } } return from; } @@ -3121,7 +3121,7 @@ out_of_range_float(char (*pbuf)[24], VALUE val) #define FLOAT_OUT_OF_RANGE(val, type) do { \ char buf[24]; \ rb_raise(rb_eRangeError, "float %s out of range of "type, \ - out_of_range_float(&buf, (val))); \ + out_of_range_float(&buf, (val))); \ } while (0) #define LONG_MIN_MINUS_ONE ((double)LONG_MIN-1) @@ -3137,26 +3137,26 @@ rb_num2long(VALUE val) { again: if (NIL_P(val)) { - rb_raise(rb_eTypeError, "no implicit conversion from nil to integer"); + rb_raise(rb_eTypeError, "no implicit conversion from nil to integer"); } if (FIXNUM_P(val)) return FIX2LONG(val); else if (RB_FLOAT_TYPE_P(val)) { - if (RFLOAT_VALUE(val) < LONG_MAX_PLUS_ONE - && LONG_MIN_MINUS_ONE_IS_LESS_THAN(RFLOAT_VALUE(val))) { - return (long)RFLOAT_VALUE(val); - } - else { - FLOAT_OUT_OF_RANGE(val, "integer"); - } + if (RFLOAT_VALUE(val) < LONG_MAX_PLUS_ONE + && LONG_MIN_MINUS_ONE_IS_LESS_THAN(RFLOAT_VALUE(val))) { + return (long)RFLOAT_VALUE(val); + } + else { + FLOAT_OUT_OF_RANGE(val, "integer"); + } } else if (RB_BIGNUM_TYPE_P(val)) { - return rb_big2long(val); + return rb_big2long(val); } else { - val = rb_to_int(val); - goto again; + val = rb_to_int(val); + goto again; } } @@ -3175,17 +3175,17 @@ rb_num2ulong_internal(VALUE val, int *wrap_p) return (unsigned long)l; } else if (RB_FLOAT_TYPE_P(val)) { - double d = RFLOAT_VALUE(val); - if (d < ULONG_MAX_PLUS_ONE && LONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) { - if (wrap_p) - *wrap_p = d <= -1.0; /* NUM2ULONG(v) uses v.to_int conceptually. */ - if (0 <= d) - return (unsigned long)d; - return (unsigned long)(long)d; - } - else { - FLOAT_OUT_OF_RANGE(val, "integer"); - } + double d = RFLOAT_VALUE(val); + if (d < ULONG_MAX_PLUS_ONE && LONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) { + if (wrap_p) + *wrap_p = d <= -1.0; /* NUM2ULONG(v) uses v.to_int conceptually. */ + if (0 <= d) + return (unsigned long)d; + return (unsigned long)(long)d; + } + else { + FLOAT_OUT_OF_RANGE(val, "integer"); + } } else if (RB_BIGNUM_TYPE_P(val)) { { @@ -3211,7 +3211,7 @@ void rb_out_of_int(SIGNED_VALUE num) { rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to `int'", - num, num < 0 ? "small" : "big"); + num, num < 0 ? "small" : "big"); } #if SIZEOF_INT < SIZEOF_LONG @@ -3219,7 +3219,7 @@ static void check_int(long num) { if ((long)(int)num != num) { - rb_out_of_int(num); + rb_out_of_int(num); } } @@ -3227,14 +3227,14 @@ static void check_uint(unsigned long num, int sign) { if (sign) { - /* minus */ - if (num < (unsigned long)INT_MIN) - rb_raise(rb_eRangeError, "integer %ld too small to convert to `unsigned int'", (long)num); + /* minus */ + if (num < (unsigned long)INT_MIN) + rb_raise(rb_eRangeError, "integer %ld too small to convert to `unsigned int'", (long)num); } else { - /* plus */ - if (UINT_MAX < num) - rb_raise(rb_eRangeError, "integer %lu too big to convert to `unsigned int'", num); + /* plus */ + if (UINT_MAX < num) + rb_raise(rb_eRangeError, "integer %lu too big to convert to `unsigned int'", num); } } @@ -3272,7 +3272,7 @@ rb_fix2uint(VALUE val) unsigned long num; if (!FIXNUM_P(val)) { - return rb_num2uint(val); + return rb_num2uint(val); } num = FIX2ULONG(val); @@ -3310,14 +3310,14 @@ static void rb_out_of_short(SIGNED_VALUE num) { rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to `short'", - num, num < 0 ? "small" : "big"); + num, num < 0 ? "small" : "big"); } static void check_short(long num) { if ((long)(short)num != num) { - rb_out_of_short(num); + rb_out_of_short(num); } } @@ -3325,14 +3325,14 @@ static void check_ushort(unsigned long num, int sign) { if (sign) { - /* minus */ - if (num < (unsigned long)SHRT_MIN) - rb_raise(rb_eRangeError, "integer %ld too small to convert to `unsigned short'", (long)num); + /* minus */ + if (num < (unsigned long)SHRT_MIN) + rb_raise(rb_eRangeError, "integer %ld too small to convert to `unsigned short'", (long)num); } else { - /* plus */ - if (USHRT_MAX < num) - rb_raise(rb_eRangeError, "integer %lu too big to convert to `unsigned short'", num); + /* plus */ + if (USHRT_MAX < num) + rb_raise(rb_eRangeError, "integer %lu too big to convert to `unsigned short'", num); } } @@ -3370,7 +3370,7 @@ rb_fix2ushort(VALUE val) unsigned long num; if (!FIXNUM_P(val)) { - return rb_num2ushort(val); + return rb_num2ushort(val); } num = FIX2ULONG(val); @@ -3387,7 +3387,7 @@ rb_num2fix(VALUE val) v = rb_num2long(val); if (!FIXABLE(v)) - rb_raise(rb_eRangeError, "integer %ld out of range of fixnum", v); + rb_raise(rb_eRangeError, "integer %ld out of range of fixnum", v); return LONG2FIX(v); } @@ -3408,28 +3408,28 @@ LONG_LONG rb_num2ll(VALUE val) { if (NIL_P(val)) { - rb_raise(rb_eTypeError, "no implicit conversion from nil"); + rb_raise(rb_eTypeError, "no implicit conversion from nil"); } if (FIXNUM_P(val)) return (LONG_LONG)FIX2LONG(val); else if (RB_FLOAT_TYPE_P(val)) { - double d = RFLOAT_VALUE(val); - if (d < LLONG_MAX_PLUS_ONE && (LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d))) { - return (LONG_LONG)d; - } - else { - FLOAT_OUT_OF_RANGE(val, "long long"); - } + double d = RFLOAT_VALUE(val); + if (d < LLONG_MAX_PLUS_ONE && (LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d))) { + return (LONG_LONG)d; + } + else { + FLOAT_OUT_OF_RANGE(val, "long long"); + } } else if (RB_BIGNUM_TYPE_P(val)) { - return rb_big2ll(val); + return rb_big2ll(val); } else if (RB_TYPE_P(val, T_STRING)) { - rb_raise(rb_eTypeError, "no implicit conversion from string"); + rb_raise(rb_eTypeError, "no implicit conversion from string"); } else if (RB_TYPE_P(val, T_TRUE) || RB_TYPE_P(val, T_FALSE)) { - rb_raise(rb_eTypeError, "no implicit conversion from boolean"); + rb_raise(rb_eTypeError, "no implicit conversion from boolean"); } val = rb_to_int(val); @@ -3440,30 +3440,30 @@ unsigned LONG_LONG rb_num2ull(VALUE val) { if (NIL_P(val)) { - rb_raise(rb_eTypeError, "no implicit conversion from nil"); + rb_raise(rb_eTypeError, "no implicit conversion from nil"); } else if (FIXNUM_P(val)) { - return (LONG_LONG)FIX2LONG(val); /* this is FIX2LONG, intended */ + return (LONG_LONG)FIX2LONG(val); /* this is FIX2LONG, intended */ } else if (RB_FLOAT_TYPE_P(val)) { - double d = RFLOAT_VALUE(val); - if (d < ULLONG_MAX_PLUS_ONE && LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) { - if (0 <= d) - return (unsigned LONG_LONG)d; - return (unsigned LONG_LONG)(LONG_LONG)d; - } - else { - FLOAT_OUT_OF_RANGE(val, "unsigned long long"); - } + double d = RFLOAT_VALUE(val); + if (d < ULLONG_MAX_PLUS_ONE && LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) { + if (0 <= d) + return (unsigned LONG_LONG)d; + return (unsigned LONG_LONG)(LONG_LONG)d; + } + else { + FLOAT_OUT_OF_RANGE(val, "unsigned long long"); + } } else if (RB_BIGNUM_TYPE_P(val)) { - return rb_big2ull(val); + return rb_big2ull(val); } else if (RB_TYPE_P(val, T_STRING)) { - rb_raise(rb_eTypeError, "no implicit conversion from string"); + rb_raise(rb_eTypeError, "no implicit conversion from string"); } else if (RB_TYPE_P(val, T_TRUE) || RB_TYPE_P(val, T_FALSE)) { - rb_raise(rb_eTypeError, "no implicit conversion from boolean"); + rb_raise(rb_eTypeError, "no implicit conversion from boolean"); } val = rb_to_int(val); @@ -3574,7 +3574,7 @@ rb_int_odd_p(VALUE num) } else { assert(RB_BIGNUM_TYPE_P(num)); - return rb_big_odd_p(num); + return rb_big_odd_p(num); } } @@ -3586,7 +3586,7 @@ int_even_p(VALUE num) } else { assert(RB_BIGNUM_TYPE_P(num)); - return rb_big_even_p(num); + return rb_big_even_p(num); } } @@ -3704,11 +3704,11 @@ VALUE rb_int_succ(VALUE num) { if (FIXNUM_P(num)) { - long i = FIX2LONG(num) + 1; - return LONG2NUM(i); + long i = FIX2LONG(num) + 1; + return LONG2NUM(i); } if (RB_BIGNUM_TYPE_P(num)) { - return rb_big_plus(num, INT2FIX(1)); + return rb_big_plus(num, INT2FIX(1)); } return num_funcall1(num, '+', INT2FIX(1)); } @@ -3732,11 +3732,11 @@ static VALUE rb_int_pred(VALUE num) { if (FIXNUM_P(num)) { - long i = FIX2LONG(num) - 1; - return LONG2NUM(i); + long i = FIX2LONG(num) - 1; + return LONG2NUM(i); } if (RB_BIGNUM_TYPE_P(num)) { - return rb_big_minus(num, INT2FIX(1)); + return rb_big_minus(num, INT2FIX(1)); } return num_funcall1(num, '-', INT2FIX(1)); } @@ -3750,17 +3750,17 @@ rb_enc_uint_chr(unsigned int code, rb_encoding *enc) VALUE str; switch (n = rb_enc_codelen(code, enc)) { case ONIGERR_INVALID_CODE_POINT_VALUE: - rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc)); - break; + rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc)); + break; case ONIGERR_TOO_BIG_WIDE_CHAR_VALUE: case 0: - rb_raise(rb_eRangeError, "%u out of char range", code); - break; + rb_raise(rb_eRangeError, "%u out of char range", code); + break; } str = rb_enc_str_new(0, n, enc); rb_enc_mbcput(code, RSTRING_PTR(str), enc); if (rb_enc_precise_mbclen(RSTRING_PTR(str), RSTRING_END(str), enc) != n) { - rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc)); + rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc)); } return str; } @@ -3794,30 +3794,30 @@ int_chr(int argc, VALUE *argv, VALUE num) if (rb_num_to_uint(num, &i) == 0) { } else if (FIXNUM_P(num)) { - rb_raise(rb_eRangeError, "%ld out of char range", FIX2LONG(num)); + rb_raise(rb_eRangeError, "%ld out of char range", FIX2LONG(num)); } else { - rb_raise(rb_eRangeError, "bignum out of char range"); + rb_raise(rb_eRangeError, "bignum out of char range"); } switch (argc) { case 0: - if (0xff < i) { - enc = rb_default_internal_encoding(); - if (!enc) { - rb_raise(rb_eRangeError, "%u out of char range", i); - } - goto decode; - } - c = (char)i; - if (i < 0x80) { - return rb_usascii_str_new(&c, 1); - } - else { - return rb_str_new(&c, 1); - } + if (0xff < i) { + enc = rb_default_internal_encoding(); + if (!enc) { + rb_raise(rb_eRangeError, "%u out of char range", i); + } + goto decode; + } + c = (char)i; + if (i < 0x80) { + return rb_usascii_str_new(&c, 1); + } + else { + return rb_str_new(&c, 1); + } case 1: - break; + break; default: rb_error_arity(argc, 0, 1); } @@ -3841,11 +3841,11 @@ VALUE rb_int_uminus(VALUE num) { if (FIXNUM_P(num)) { - return fix_uminus(num); + return fix_uminus(num); } else { assert(RB_BIGNUM_TYPE_P(num)); - return rb_big_uminus(num); + return rb_big_uminus(num); } } @@ -3858,13 +3858,13 @@ rb_fix2str(VALUE x, int base) int neg = 0; if (base < 2 || 36 < base) { - rb_raise(rb_eArgError, "invalid radix %d", base); + rb_raise(rb_eArgError, "invalid radix %d", base); } #if SIZEOF_LONG < SIZEOF_VOIDP # if SIZEOF_VOIDP == SIZEOF_LONG_LONG if ((val >= 0 && (x & 0xFFFFFFFF00000000ull)) || - (val < 0 && (x & 0xFFFFFFFF00000000ull) != 0xFFFFFFFF00000000ull)) { - rb_bug("Unnormalized Fixnum value %p", (void *)x); + (val < 0 && (x & 0xFFFFFFFF00000000ull) != 0xFFFFFFFF00000000ull)) { + rb_bug("Unnormalized Fixnum value %p", (void *)x); } # else /* should do something like above code, but currently ruby does not know */ @@ -3872,20 +3872,20 @@ rb_fix2str(VALUE x, int base) # endif #endif if (val == 0) { - return rb_usascii_str_new2("0"); + return rb_usascii_str_new2("0"); } if (val < 0) { - u = 1 + (unsigned long)(-(val + 1)); /* u = -val avoiding overflow */ - neg = 1; + u = 1 + (unsigned long)(-(val + 1)); /* u = -val avoiding overflow */ + neg = 1; } else { - u = val; + u = val; } do { - *--b = ruby_digitmap[(int)(u % base)]; + *--b = ruby_digitmap[(int)(u % base)]; } while (u /= base); if (neg) { - *--b = '-'; + *--b = '-'; } return rb_usascii_str_new(b, e - b); @@ -3930,9 +3930,9 @@ rb_int_to_s(int argc, VALUE *argv, VALUE x) int base; if (rb_check_arity(argc, 0, 1)) - base = NUM2INT(argv[0]); + base = NUM2INT(argv[0]); else - base = 10; + base = 10; return rb_int2str(x, base); } @@ -3940,10 +3940,10 @@ VALUE rb_int2str(VALUE x, int base) { if (FIXNUM_P(x)) { - return rb_fix2str(x, base); + return rb_fix2str(x, base); } else if (RB_BIGNUM_TYPE_P(x)) { - return rb_big2str(x, base); + return rb_big2str(x, base); } return rb_any_to_s(x); @@ -3953,19 +3953,19 @@ static VALUE fix_plus(VALUE x, VALUE y) { if (FIXNUM_P(y)) { - return rb_fix_plus_fix(x, y); + return rb_fix_plus_fix(x, y); } else if (RB_BIGNUM_TYPE_P(y)) { - return rb_big_plus(y, x); + return rb_big_plus(y, x); } else if (RB_FLOAT_TYPE_P(y)) { - return DBL2NUM((double)FIX2LONG(x) + RFLOAT_VALUE(y)); + return DBL2NUM((double)FIX2LONG(x) + RFLOAT_VALUE(y)); } else if (RB_TYPE_P(y, T_COMPLEX)) { - return rb_complex_plus(y, x); + return rb_complex_plus(y, x); } else { - return rb_num_coerce_bin(x, y, '+'); + return rb_num_coerce_bin(x, y, '+'); } } @@ -3994,10 +3994,10 @@ VALUE rb_int_plus(VALUE x, VALUE y) { if (FIXNUM_P(x)) { - return fix_plus(x, y); + return fix_plus(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { - return rb_big_plus(x, y); + return rb_big_plus(x, y); } return rb_num_coerce_bin(x, y, '+'); } @@ -4006,17 +4006,17 @@ static VALUE fix_minus(VALUE x, VALUE y) { if (FIXNUM_P(y)) { - return rb_fix_minus_fix(x, y); + return rb_fix_minus_fix(x, y); } else if (RB_BIGNUM_TYPE_P(y)) { - x = rb_int2big(FIX2LONG(x)); - return rb_big_minus(x, y); + x = rb_int2big(FIX2LONG(x)); + return rb_big_minus(x, y); } else if (RB_FLOAT_TYPE_P(y)) { - return DBL2NUM((double)FIX2LONG(x) - RFLOAT_VALUE(y)); + return DBL2NUM((double)FIX2LONG(x) - RFLOAT_VALUE(y)); } else { - return rb_num_coerce_bin(x, y, '-'); + return rb_num_coerce_bin(x, y, '-'); } } @@ -4039,10 +4039,10 @@ VALUE rb_int_minus(VALUE x, VALUE y) { if (FIXNUM_P(x)) { - return fix_minus(x, y); + return fix_minus(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { - return rb_big_minus(x, y); + return rb_big_minus(x, y); } return rb_num_coerce_bin(x, y, '-'); } @@ -4056,23 +4056,23 @@ static VALUE fix_mul(VALUE x, VALUE y) { if (FIXNUM_P(y)) { - return rb_fix_mul_fix(x, y); + return rb_fix_mul_fix(x, y); } else if (RB_BIGNUM_TYPE_P(y)) { - switch (x) { - case INT2FIX(0): return x; - case INT2FIX(1): return y; - } - return rb_big_mul(y, x); + switch (x) { + case INT2FIX(0): return x; + case INT2FIX(1): return y; + } + return rb_big_mul(y, x); } else if (RB_FLOAT_TYPE_P(y)) { - return DBL2NUM((double)FIX2LONG(x) * RFLOAT_VALUE(y)); + return DBL2NUM((double)FIX2LONG(x) * RFLOAT_VALUE(y)); } else if (RB_TYPE_P(y, T_COMPLEX)) { - return rb_complex_mul(y, x); + return rb_complex_mul(y, x); } else { - return rb_num_coerce_bin(x, y, '*'); + return rb_num_coerce_bin(x, y, '*'); } } @@ -4094,10 +4094,10 @@ VALUE rb_int_mul(VALUE x, VALUE y) { if (FIXNUM_P(x)) { - return fix_mul(x, y); + return fix_mul(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { - return rb_big_mul(x, y); + return rb_big_mul(x, y); } return rb_num_coerce_bin(x, y, '*'); } @@ -4123,11 +4123,11 @@ double rb_int_fdiv_double(VALUE x, VALUE y) { if (RB_INTEGER_TYPE_P(y) && !FIXNUM_ZERO_P(y)) { - VALUE gcd = rb_gcd(x, y); - if (!FIXNUM_ZERO_P(gcd)) { - x = rb_int_idiv(x, gcd); - y = rb_int_idiv(y, gcd); - } + VALUE gcd = rb_gcd(x, y); + if (!FIXNUM_ZERO_P(gcd)) { + x = rb_int_idiv(x, gcd); + y = rb_int_idiv(y, gcd); + } } if (FIXNUM_P(x)) { return fix_fdiv_double(x, y); @@ -4169,30 +4169,30 @@ static VALUE fix_divide(VALUE x, VALUE y, ID op) { if (FIXNUM_P(y)) { - if (FIXNUM_ZERO_P(y)) rb_num_zerodiv(); - return rb_fix_div_fix(x, y); + if (FIXNUM_ZERO_P(y)) rb_num_zerodiv(); + return rb_fix_div_fix(x, y); } else if (RB_BIGNUM_TYPE_P(y)) { - x = rb_int2big(FIX2LONG(x)); - return rb_big_div(x, y); + x = rb_int2big(FIX2LONG(x)); + return rb_big_div(x, y); } else if (RB_FLOAT_TYPE_P(y)) { - if (op == '/') { + if (op == '/') { double d = FIX2LONG(x); return rb_flo_div_flo(DBL2NUM(d), y); - } - else { + } + else { VALUE v; - if (RFLOAT_VALUE(y) == 0) rb_num_zerodiv(); + if (RFLOAT_VALUE(y) == 0) rb_num_zerodiv(); v = fix_divide(x, y, '/'); return flo_floor(0, 0, v); - } + } } else { - if (RB_TYPE_P(y, T_RATIONAL) && - op == '/' && FIX2LONG(x) == 1) - return rb_rational_reciprocal(y); - return rb_num_coerce_bin(x, y, op); + if (RB_TYPE_P(y, T_RATIONAL) && + op == '/' && FIX2LONG(x) == 1) + return rb_rational_reciprocal(y); + return rb_num_coerce_bin(x, y, op); } } @@ -4225,10 +4225,10 @@ VALUE rb_int_div(VALUE x, VALUE y) { if (FIXNUM_P(x)) { - return fix_div(x, y); + return fix_div(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { - return rb_big_div(x, y); + return rb_big_div(x, y); } return Qnil; } @@ -4261,10 +4261,10 @@ VALUE rb_int_idiv(VALUE x, VALUE y) { if (FIXNUM_P(x)) { - return fix_idiv(x, y); + return fix_idiv(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { - return rb_big_idiv(x, y); + return rb_big_idiv(x, y); } return num_div(x, y); } @@ -4273,18 +4273,18 @@ static VALUE fix_mod(VALUE x, VALUE y) { if (FIXNUM_P(y)) { - if (FIXNUM_ZERO_P(y)) rb_num_zerodiv(); - return rb_fix_mod_fix(x, y); + if (FIXNUM_ZERO_P(y)) rb_num_zerodiv(); + return rb_fix_mod_fix(x, y); } else if (RB_BIGNUM_TYPE_P(y)) { - x = rb_int2big(FIX2LONG(x)); - return rb_big_modulo(x, y); + x = rb_int2big(FIX2LONG(x)); + return rb_big_modulo(x, y); } else if (RB_FLOAT_TYPE_P(y)) { - return DBL2NUM(ruby_float_mod((double)FIX2LONG(x), RFLOAT_VALUE(y))); + return DBL2NUM(ruby_float_mod((double)FIX2LONG(x), RFLOAT_VALUE(y))); } else { - return rb_num_coerce_bin(x, y, '%'); + return rb_num_coerce_bin(x, y, '%'); } } @@ -4322,10 +4322,10 @@ VALUE rb_int_modulo(VALUE x, VALUE y) { if (FIXNUM_P(x)) { - return fix_mod(x, y); + return fix_mod(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { - return rb_big_modulo(x, y); + return rb_big_modulo(x, y); } return num_modulo(x, y); } @@ -4357,10 +4357,10 @@ static VALUE int_remainder(VALUE x, VALUE y) { if (FIXNUM_P(x)) { - return num_remainder(x, y); + return num_remainder(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { - return rb_big_remainder(x, y); + return rb_big_remainder(x, y); } return Qnil; } @@ -4369,28 +4369,28 @@ static VALUE fix_divmod(VALUE x, VALUE y) { if (FIXNUM_P(y)) { - VALUE div, mod; - if (FIXNUM_ZERO_P(y)) rb_num_zerodiv(); - rb_fix_divmod_fix(x, y, &div, &mod); - return rb_assoc_new(div, mod); + VALUE div, mod; + if (FIXNUM_ZERO_P(y)) rb_num_zerodiv(); + rb_fix_divmod_fix(x, y, &div, &mod); + return rb_assoc_new(div, mod); } else if (RB_BIGNUM_TYPE_P(y)) { - x = rb_int2big(FIX2LONG(x)); - return rb_big_divmod(x, y); + x = rb_int2big(FIX2LONG(x)); + return rb_big_divmod(x, y); } else if (RB_FLOAT_TYPE_P(y)) { - { - double div, mod; - volatile VALUE a, b; + { + double div, mod; + volatile VALUE a, b; - flodivmod((double)FIX2LONG(x), RFLOAT_VALUE(y), &div, &mod); - a = dbl2ival(div); - b = DBL2NUM(mod); - return rb_assoc_new(a, b); - } + flodivmod((double)FIX2LONG(x), RFLOAT_VALUE(y), &div, &mod); + a = dbl2ival(div); + b = DBL2NUM(mod); + return rb_assoc_new(a, b); + } } else { - return rb_num_coerce_bin(x, y, id_divmod); + return rb_num_coerce_bin(x, y, id_divmod); } } @@ -4423,10 +4423,10 @@ VALUE rb_int_divmod(VALUE x, VALUE y) { if (FIXNUM_P(x)) { - return fix_divmod(x, y); + return fix_divmod(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { - return rb_big_divmod(x, y); + return rb_big_divmod(x, y); } return Qnil; } @@ -4457,24 +4457,24 @@ int_pow(long x, unsigned long y) if (y == 1) return LONG2NUM(x); if (neg) x = -x; if (y & 1) - z = x; + z = x; else - neg = 0; + neg = 0; y &= ~1; do { - while (y % 2 == 0) { - if (!FIT_SQRT_LONG(x)) { + while (y % 2 == 0) { + if (!FIT_SQRT_LONG(x)) { goto bignum; - } - x = x * x; - y >>= 1; - } - { + } + x = x * x; + y >>= 1; + } + { if (MUL_OVERFLOW_FIXNUM_P(x, z)) { - goto bignum; - } - z = x * z; - } + goto bignum; + } + z = x * z; + } } while (--y); if (neg) z = -z; return LONG2NUM(z); @@ -4520,37 +4520,37 @@ fix_pow(VALUE x, VALUE y) long a = FIX2LONG(x); if (FIXNUM_P(y)) { - long b = FIX2LONG(y); + long b = FIX2LONG(y); - if (a == 1) return INT2FIX(1); + if (a == 1) return INT2FIX(1); if (a == -1) return INT2FIX(b % 2 ? -1 : 1); if (b < 0) return fix_pow_inverted(x, fix_uminus(y)); - if (b == 0) return INT2FIX(1); - if (b == 1) return x; - if (a == 0) return INT2FIX(0); - return int_pow(a, b); + if (b == 0) return INT2FIX(1); + if (b == 1) return x; + if (a == 0) return INT2FIX(0); + return int_pow(a, b); } else if (RB_BIGNUM_TYPE_P(y)) { - if (a == 1) return INT2FIX(1); + if (a == 1) return INT2FIX(1); if (a == -1) return INT2FIX(int_even_p(y) ? 1 : -1); if (BIGNUM_NEGATIVE_P(y)) return fix_pow_inverted(x, rb_big_uminus(y)); - if (a == 0) return INT2FIX(0); - x = rb_int2big(FIX2LONG(x)); - return rb_big_pow(x, y); + if (a == 0) return INT2FIX(0); + x = rb_int2big(FIX2LONG(x)); + return rb_big_pow(x, y); } else if (RB_FLOAT_TYPE_P(y)) { - double dy = RFLOAT_VALUE(y); - if (dy == 0.0) return DBL2NUM(1.0); - if (a == 0) { - return DBL2NUM(dy < 0 ? HUGE_VAL : 0.0); - } - if (a == 1) return DBL2NUM(1.0); + double dy = RFLOAT_VALUE(y); + if (dy == 0.0) return DBL2NUM(1.0); + if (a == 0) { + return DBL2NUM(dy < 0 ? HUGE_VAL : 0.0); + } + if (a == 1) return DBL2NUM(1.0); if (a < 0 && dy != round(dy)) return rb_dbl_complex_new_polar_pi(pow(-(double)a, dy), dy); return DBL2NUM(pow((double)a, dy)); } else { - return rb_num_coerce_bin(x, y, idPow); + return rb_num_coerce_bin(x, y, idPow); } } @@ -4573,10 +4573,10 @@ VALUE rb_int_pow(VALUE x, VALUE y) { if (FIXNUM_P(x)) { - return fix_pow(x, y); + return fix_pow(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { - return rb_big_pow(x, y); + return rb_big_pow(x, y); } return Qnil; } @@ -4605,13 +4605,13 @@ fix_equal(VALUE x, VALUE y) if (x == y) return Qtrue; if (FIXNUM_P(y)) return Qfalse; else if (RB_BIGNUM_TYPE_P(y)) { - return rb_big_eq(y, x); + return rb_big_eq(y, x); } else if (RB_FLOAT_TYPE_P(y)) { return rb_integer_float_eq(x, y); } else { - return num_equal(x, y); + return num_equal(x, y); } } @@ -4634,10 +4634,10 @@ VALUE rb_int_equal(VALUE x, VALUE y) { if (FIXNUM_P(x)) { - return fix_equal(x, y); + return fix_equal(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { - return rb_big_eq(x, y); + return rb_big_eq(x, y); } return Qnil; } @@ -4647,22 +4647,22 @@ fix_cmp(VALUE x, VALUE y) { if (x == y) return INT2FIX(0); if (FIXNUM_P(y)) { - if (FIX2LONG(x) > FIX2LONG(y)) return INT2FIX(1); - return INT2FIX(-1); + if (FIX2LONG(x) > FIX2LONG(y)) return INT2FIX(1); + return INT2FIX(-1); } else if (RB_BIGNUM_TYPE_P(y)) { - VALUE cmp = rb_big_cmp(y, x); - switch (cmp) { - case INT2FIX(+1): return INT2FIX(-1); - case INT2FIX(-1): return INT2FIX(+1); - } - return cmp; + VALUE cmp = rb_big_cmp(y, x); + switch (cmp) { + case INT2FIX(+1): return INT2FIX(-1); + case INT2FIX(-1): return INT2FIX(+1); + } + return cmp; } else if (RB_FLOAT_TYPE_P(y)) { - return rb_integer_float_cmp(x, y); + return rb_integer_float_cmp(x, y); } else { - return rb_num_coerce_cmp(x, y, id_cmp); + return rb_num_coerce_cmp(x, y, id_cmp); } } @@ -4696,13 +4696,13 @@ VALUE rb_int_cmp(VALUE x, VALUE y) { if (FIXNUM_P(x)) { - return fix_cmp(x, y); + return fix_cmp(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { - return rb_big_cmp(x, y); + return rb_big_cmp(x, y); } else { - rb_raise(rb_eNotImpError, "need to define `<=>' in %s", rb_obj_classname(x)); + rb_raise(rb_eNotImpError, "need to define `<=>' in %s", rb_obj_classname(x)); } } @@ -4713,13 +4713,13 @@ fix_gt(VALUE x, VALUE y) return RBOOL(FIX2LONG(x) > FIX2LONG(y)); } else if (RB_BIGNUM_TYPE_P(y)) { - return RBOOL(rb_big_cmp(y, x) == INT2FIX(-1)); + return RBOOL(rb_big_cmp(y, x) == INT2FIX(-1)); } else if (RB_FLOAT_TYPE_P(y)) { return RBOOL(rb_integer_float_cmp(x, y) == INT2FIX(1)); } else { - return rb_num_coerce_relop(x, y, '>'); + return rb_num_coerce_relop(x, y, '>'); } } @@ -4743,10 +4743,10 @@ VALUE rb_int_gt(VALUE x, VALUE y) { if (FIXNUM_P(x)) { - return fix_gt(x, y); + return fix_gt(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { - return rb_big_gt(x, y); + return rb_big_gt(x, y); } return Qnil; } @@ -4758,14 +4758,14 @@ fix_ge(VALUE x, VALUE y) return RBOOL(FIX2LONG(x) >= FIX2LONG(y)); } else if (RB_BIGNUM_TYPE_P(y)) { - return RBOOL(rb_big_cmp(y, x) != INT2FIX(+1)); + return RBOOL(rb_big_cmp(y, x) != INT2FIX(+1)); } else if (RB_FLOAT_TYPE_P(y)) { - VALUE rel = rb_integer_float_cmp(x, y); - return RBOOL(rel == INT2FIX(1) || rel == INT2FIX(0)); + VALUE rel = rb_integer_float_cmp(x, y); + return RBOOL(rel == INT2FIX(1) || rel == INT2FIX(0)); } else { - return rb_num_coerce_relop(x, y, idGE); + return rb_num_coerce_relop(x, y, idGE); } } @@ -4790,10 +4790,10 @@ VALUE rb_int_ge(VALUE x, VALUE y) { if (FIXNUM_P(x)) { - return fix_ge(x, y); + return fix_ge(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { - return rb_big_ge(x, y); + return rb_big_ge(x, y); } return Qnil; } @@ -4805,13 +4805,13 @@ fix_lt(VALUE x, VALUE y) return RBOOL(FIX2LONG(x) < FIX2LONG(y)); } else if (RB_BIGNUM_TYPE_P(y)) { - return RBOOL(rb_big_cmp(y, x) == INT2FIX(+1)); + return RBOOL(rb_big_cmp(y, x) == INT2FIX(+1)); } else if (RB_FLOAT_TYPE_P(y)) { return RBOOL(rb_integer_float_cmp(x, y) == INT2FIX(-1)); } else { - return rb_num_coerce_relop(x, y, '<'); + return rb_num_coerce_relop(x, y, '<'); } } @@ -4835,10 +4835,10 @@ static VALUE int_lt(VALUE x, VALUE y) { if (FIXNUM_P(x)) { - return fix_lt(x, y); + return fix_lt(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { - return rb_big_lt(x, y); + return rb_big_lt(x, y); } return Qnil; } @@ -4850,14 +4850,14 @@ fix_le(VALUE x, VALUE y) return RBOOL(FIX2LONG(x) <= FIX2LONG(y)); } else if (RB_BIGNUM_TYPE_P(y)) { - return RBOOL(rb_big_cmp(y, x) != INT2FIX(-1)); + return RBOOL(rb_big_cmp(y, x) != INT2FIX(-1)); } else if (RB_FLOAT_TYPE_P(y)) { - VALUE rel = rb_integer_float_cmp(x, y); - return RBOOL(rel == INT2FIX(-1) || rel == INT2FIX(0)); + VALUE rel = rb_integer_float_cmp(x, y); + return RBOOL(rel == INT2FIX(-1) || rel == INT2FIX(0)); } else { - return rb_num_coerce_relop(x, y, idLE); + return rb_num_coerce_relop(x, y, idLE); } } @@ -4882,10 +4882,10 @@ static VALUE int_le(VALUE x, VALUE y) { if (FIXNUM_P(x)) { - return fix_le(x, y); + return fix_le(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { - return rb_big_le(x, y); + return rb_big_le(x, y); } return Qnil; } @@ -4900,10 +4900,10 @@ VALUE rb_int_comp(VALUE num) { if (FIXNUM_P(num)) { - return fix_comp(num); + return fix_comp(num); } else if (RB_BIGNUM_TYPE_P(num)) { - return rb_big_comp(num); + return rb_big_comp(num); } return Qnil; } @@ -4914,7 +4914,7 @@ num_funcall_bit_1(VALUE y, VALUE arg, int recursive) ID func = (ID)((VALUE *)arg)[0]; VALUE x = ((VALUE *)arg)[1]; if (recursive) { - num_funcall_op_1_recursion(x, func, y); + num_funcall_op_1_recursion(x, func, y); } return rb_check_funcall(x, func, 1, &y); } @@ -4929,10 +4929,10 @@ rb_num_coerce_bit(VALUE x, VALUE y, ID func) args[2] = y; do_coerce(&args[1], &args[2], TRUE); ret = rb_exec_recursive_paired(num_funcall_bit_1, - args[2], args[1], (VALUE)args); + args[2], args[1], (VALUE)args); if (ret == Qundef) { - /* show the original object, not coerced object */ - coerce_failed(x, y); + /* show the original object, not coerced object */ + coerce_failed(x, y); } return ret; } @@ -4941,12 +4941,12 @@ static VALUE fix_and(VALUE x, VALUE y) { if (FIXNUM_P(y)) { - long val = FIX2LONG(x) & FIX2LONG(y); - return LONG2NUM(val); + long val = FIX2LONG(x) & FIX2LONG(y); + return LONG2NUM(val); } if (RB_BIGNUM_TYPE_P(y)) { - return rb_big_and(y, x); + return rb_big_and(y, x); } return rb_num_coerce_bit(x, y, '&'); @@ -4971,10 +4971,10 @@ VALUE rb_int_and(VALUE x, VALUE y) { if (FIXNUM_P(x)) { - return fix_and(x, y); + return fix_and(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { - return rb_big_and(x, y); + return rb_big_and(x, y); } return Qnil; } @@ -4983,12 +4983,12 @@ static VALUE fix_or(VALUE x, VALUE y) { if (FIXNUM_P(y)) { - long val = FIX2LONG(x) | FIX2LONG(y); - return LONG2NUM(val); + long val = FIX2LONG(x) | FIX2LONG(y); + return LONG2NUM(val); } if (RB_BIGNUM_TYPE_P(y)) { - return rb_big_or(y, x); + return rb_big_or(y, x); } return rb_num_coerce_bit(x, y, '|'); @@ -5013,10 +5013,10 @@ static VALUE int_or(VALUE x, VALUE y) { if (FIXNUM_P(x)) { - return fix_or(x, y); + return fix_or(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { - return rb_big_or(x, y); + return rb_big_or(x, y); } return Qnil; } @@ -5025,12 +5025,12 @@ static VALUE fix_xor(VALUE x, VALUE y) { if (FIXNUM_P(y)) { - long val = FIX2LONG(x) ^ FIX2LONG(y); - return LONG2NUM(val); + long val = FIX2LONG(x) ^ FIX2LONG(y); + return LONG2NUM(val); } if (RB_BIGNUM_TYPE_P(y)) { - return rb_big_xor(y, x); + return rb_big_xor(y, x); } return rb_num_coerce_bit(x, y, '^'); @@ -5055,10 +5055,10 @@ static VALUE int_xor(VALUE x, VALUE y) { if (FIXNUM_P(x)) { - return fix_xor(x, y); + return fix_xor(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { - return rb_big_xor(x, y); + return rb_big_xor(x, y); } return Qnil; } @@ -5071,10 +5071,10 @@ rb_fix_lshift(VALUE x, VALUE y) val = NUM2LONG(x); if (!val) return (rb_to_int(y), INT2FIX(0)); if (!FIXNUM_P(y)) - return rb_big_lshift(rb_int2big(val), y); + return rb_big_lshift(rb_int2big(val), y); width = FIX2LONG(y); if (width < 0) - return fix_rshift(val, (unsigned long)-width); + return fix_rshift(val, (unsigned long)-width); return fix_lshift(val, width); } @@ -5082,8 +5082,8 @@ static VALUE fix_lshift(long val, unsigned long width) { if (width > (SIZEOF_LONG*CHAR_BIT-1) - || ((unsigned long)val)>>(SIZEOF_LONG*CHAR_BIT-1-width) > 0) { - return rb_big_lshift(rb_int2big(val), ULONG2NUM(width)); + || ((unsigned long)val)>>(SIZEOF_LONG*CHAR_BIT-1-width) > 0) { + return rb_big_lshift(rb_int2big(val), ULONG2NUM(width)); } val = val << width; return LONG2NUM(val); @@ -5110,10 +5110,10 @@ VALUE rb_int_lshift(VALUE x, VALUE y) { if (FIXNUM_P(x)) { - return rb_fix_lshift(x, y); + return rb_fix_lshift(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { - return rb_big_lshift(x, y); + return rb_big_lshift(x, y); } return Qnil; } @@ -5126,11 +5126,11 @@ rb_fix_rshift(VALUE x, VALUE y) val = FIX2LONG(x); if (!val) return (rb_to_int(y), INT2FIX(0)); if (!FIXNUM_P(y)) - return rb_big_rshift(rb_int2big(val), y); + return rb_big_rshift(rb_int2big(val), y); i = FIX2LONG(y); if (i == 0) return x; if (i < 0) - return fix_lshift(val, (unsigned long)-i); + return fix_lshift(val, (unsigned long)-i); return fix_rshift(val, i); } @@ -5138,8 +5138,8 @@ static VALUE fix_rshift(long val, unsigned long i) { if (i >= sizeof(long)*CHAR_BIT-1) { - if (val < 0) return INT2FIX(-1); - return INT2FIX(0); + if (val < 0) return INT2FIX(-1); + return INT2FIX(0); } val = RSHIFT(val, i); return LONG2FIX(val); @@ -5166,10 +5166,10 @@ static VALUE rb_int_rshift(VALUE x, VALUE y) { if (FIXNUM_P(x)) { - return rb_fix_rshift(x, y); + return rb_fix_rshift(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { - return rb_big_rshift(x, y); + return rb_big_rshift(x, y); } return Qnil; } @@ -5182,22 +5182,22 @@ rb_fix_aref(VALUE fix, VALUE idx) idx = rb_to_int(idx); if (!FIXNUM_P(idx)) { - idx = rb_big_norm(idx); - if (!FIXNUM_P(idx)) { - if (!BIGNUM_SIGN(idx) || val >= 0) - return INT2FIX(0); - return INT2FIX(1); - } + idx = rb_big_norm(idx); + if (!FIXNUM_P(idx)) { + if (!BIGNUM_SIGN(idx) || val >= 0) + return INT2FIX(0); + return INT2FIX(1); + } } i = FIX2LONG(idx); if (i < 0) return INT2FIX(0); if (SIZEOF_LONG*CHAR_BIT-1 <= i) { - if (val < 0) return INT2FIX(1); - return INT2FIX(0); + if (val < 0) return INT2FIX(1); + return INT2FIX(0); } if (val & (1L<', 1, to))) { - rb_yield(i); - i = rb_funcall(i, '+', 1, INT2FIX(1)); - } - ensure_cmp(c, i, to); + while (!(c = rb_funcall(i, '>', 1, to))) { + rb_yield(i); + i = rb_funcall(i, '+', 1, INT2FIX(1)); + } + ensure_cmp(c, i, to); } return from; } @@ -5638,21 +5638,21 @@ int_downto(VALUE from, VALUE to) { RETURN_SIZED_ENUMERATOR(from, 1, &to, int_downto_size); if (FIXNUM_P(from) && FIXNUM_P(to)) { - long i, end; + long i, end; - end = FIX2LONG(to); - for (i=FIX2LONG(from); i >= end; i--) { - rb_yield(LONG2FIX(i)); - } + end = FIX2LONG(to); + for (i=FIX2LONG(from); i >= end; i--) { + rb_yield(LONG2FIX(i)); + } } else { - VALUE i = from, c; + VALUE i = from, c; - while (!(c = rb_funcall(i, '<', 1, to))) { - rb_yield(i); - i = rb_funcall(i, '-', 1, INT2FIX(1)); - } - if (NIL_P(c)) rb_cmperr(i, to); + while (!(c = rb_funcall(i, '<', 1, to))) { + rb_yield(i); + i = rb_funcall(i, '-', 1, INT2FIX(1)); + } + if (NIL_P(c)) rb_cmperr(i, to); } return from; } @@ -5661,10 +5661,10 @@ static VALUE int_dotimes_size(VALUE num, VALUE args, VALUE eobj) { if (FIXNUM_P(num)) { - if (NUM2LONG(num) <= 0) return INT2FIX(0); + if (NUM2LONG(num) <= 0) return INT2FIX(0); } else { - if (RTEST(rb_funcall(num, '<', 1, INT2FIX(0)))) return INT2FIX(0); + if (RTEST(rb_funcall(num, '<', 1, INT2FIX(0)))) return INT2FIX(0); } return num; } @@ -5690,21 +5690,21 @@ int_dotimes(VALUE num) RETURN_SIZED_ENUMERATOR(num, 0, 0, int_dotimes_size); if (FIXNUM_P(num)) { - long i, end; + long i, end; - end = FIX2LONG(num); - for (i=0; i= 0) { - return num; + return num; } return rb_int_round(num, ndigits, mode); } @@ -5806,7 +5806,7 @@ int_floor(int argc, VALUE* argv, VALUE num) if (!rb_check_arity(argc, 0, 1)) return num; ndigits = NUM2INT(argv[0]); if (ndigits >= 0) { - return num; + return num; } return rb_int_floor(num, ndigits); } @@ -5843,7 +5843,7 @@ int_ceil(int argc, VALUE* argv, VALUE num) if (!rb_check_arity(argc, 0, 1)) return num; ndigits = NUM2INT(argv[0]); if (ndigits >= 0) { - return num; + return num; } return rb_int_ceil(num, ndigits); } @@ -5879,7 +5879,7 @@ int_truncate(int argc, VALUE* argv, VALUE num) if (!rb_check_arity(argc, 0, 1)) return num; ndigits = NUM2INT(argv[0]); if (ndigits >= 0) { - return num; + return num; } return rb_int_truncate(num, ndigits); } @@ -5889,12 +5889,12 @@ rettype \ prefix##_isqrt(argtype n) \ { \ if (!argtype##_IN_DOUBLE_P(n)) { \ - unsigned int b = bit_length(n); \ - argtype t; \ - rettype x = (rettype)(n >> (b/2+1)); \ - x |= ((rettype)1LU << (b-1)/2); \ - while ((t = n/x) < (argtype)x) x = (rettype)((x + t) >> 1); \ - return x; \ + unsigned int b = bit_length(n); \ + argtype t; \ + rettype x = (rettype)(n >> (b/2+1)); \ + x |= ((rettype)1LU << (b-1)/2); \ + while ((t = n/x) < (argtype)x) x = (rettype)((x + t) >> 1); \ + return x; \ } \ return (rettype)sqrt(argtype##_TO_DOUBLE(n)); \ } @@ -5963,29 +5963,29 @@ rb_int_s_isqrt(VALUE self, VALUE num) unsigned long n, sq; num = rb_to_int(num); if (FIXNUM_P(num)) { - if (FIXNUM_NEGATIVE_P(num)) { - domain_error("isqrt"); - } - n = FIX2ULONG(num); - sq = rb_ulong_isqrt(n); - return LONG2FIX(sq); + if (FIXNUM_NEGATIVE_P(num)) { + domain_error("isqrt"); + } + n = FIX2ULONG(num); + sq = rb_ulong_isqrt(n); + return LONG2FIX(sq); } else { - size_t biglen; - if (RBIGNUM_NEGATIVE_P(num)) { - domain_error("isqrt"); - } - biglen = BIGNUM_LEN(num); - if (biglen == 0) return INT2FIX(0); + size_t biglen; + if (RBIGNUM_NEGATIVE_P(num)) { + domain_error("isqrt"); + } + biglen = BIGNUM_LEN(num); + if (biglen == 0) return INT2FIX(0); #if SIZEOF_BDIGIT <= SIZEOF_LONG - /* short-circuit */ - if (biglen == 1) { - n = BIGNUM_DIGITS(num)[0]; - sq = rb_ulong_isqrt(n); - return ULONG2NUM(sq); - } + /* short-circuit */ + if (biglen == 1) { + n = BIGNUM_DIGITS(num)[0]; + sq = rb_ulong_isqrt(n); + return ULONG2NUM(sq); + } #endif - return rb_big_isqrt(num); + return rb_big_isqrt(num); } } diff --git a/object.c b/object.c index 4baf7ffc56..3a8a07736a 100644 --- a/object.c +++ b/object.c @@ -82,7 +82,7 @@ VALUE rb_obj_hide(VALUE obj) { if (!SPECIAL_CONST_P(obj)) { - RBASIC_CLEAR_CLASS(obj); + RBASIC_CLEAR_CLASS(obj); } return obj; } @@ -91,7 +91,7 @@ VALUE rb_obj_reveal(VALUE obj, VALUE klass) { if (!SPECIAL_CONST_P(obj)) { - RBASIC_SET_CLASS(obj, klass); + RBASIC_SET_CLASS(obj, klass); } return obj; } @@ -124,7 +124,7 @@ rb_equal(VALUE obj1, VALUE obj2) if (obj1 == obj2) return Qtrue; result = rb_equal_opt(obj1, obj2); if (result == Qundef) { - result = rb_funcall(obj1, id_eq, 1, obj2); + result = rb_funcall(obj1, id_eq, 1, obj2); } return RBOOL(RTEST(result)); } @@ -137,7 +137,7 @@ rb_eql(VALUE obj1, VALUE obj2) if (obj1 == obj2) return Qtrue; result = rb_eql_opt(obj1, obj2); if (result == Qundef) { - result = rb_funcall(obj1, id_eql, 1, obj2); + result = rb_funcall(obj1, id_eql, 1, obj2); } return RBOOL(RTEST(result)); } @@ -229,7 +229,7 @@ rb_class_real(VALUE cl) { while (cl && ((RBASIC(cl)->flags & FL_SINGLETON) || BUILTIN_TYPE(cl) == T_ICLASS)) { - cl = RCLASS_SUPER(cl); + cl = RCLASS_SUPER(cl); } return cl; } @@ -288,7 +288,7 @@ init_copy(VALUE dest, VALUE obj) rb_copy_generic_ivar(dest, obj); rb_gc_copy_finalizer(dest, obj); if (RB_TYPE_P(obj, T_OBJECT)) { - rb_obj_copy_ivar(dest, obj); + rb_obj_copy_ivar(dest, obj); } } @@ -305,10 +305,10 @@ special_object_p(VALUE obj) case T_SYMBOL: case T_RATIONAL: case T_COMPLEX: - /* not a comprehensive list */ - return TRUE; + /* not a comprehensive list */ + return TRUE; default: - return FALSE; + return FALSE; } } @@ -332,7 +332,7 @@ rb_obj_clone2(rb_execution_context_t *ec, VALUE obj, VALUE freeze) { VALUE kwfreeze = obj_freeze_opt(freeze); if (!special_object_p(obj)) - return mutable_obj_clone(obj, kwfreeze); + return mutable_obj_clone(obj, kwfreeze); return immutable_obj_clone(obj, kwfreeze); } @@ -352,11 +352,11 @@ rb_get_freeze_opt(int argc, VALUE *argv) VALUE kwfreeze = Qnil; if (!keyword_ids[0]) { - CONST_ID(keyword_ids[0], "freeze"); + CONST_ID(keyword_ids[0], "freeze"); } rb_scan_args(argc, argv, "0:", &opt); if (!NIL_P(opt)) { - rb_get_kwargs(opt, keyword_ids, 0, 1, &kwfreeze); + rb_get_kwargs(opt, keyword_ids, 0, 1, &kwfreeze); if (kwfreeze != Qundef) kwfreeze = obj_freeze_opt(kwfreeze); } @@ -367,8 +367,8 @@ static VALUE immutable_obj_clone(VALUE obj, VALUE kwfreeze) { if (kwfreeze == Qfalse) - rb_raise(rb_eArgError, "can't unfreeze %"PRIsVALUE, - rb_obj_class(obj)); + rb_raise(rb_eArgError, "can't unfreeze %"PRIsVALUE, + rb_obj_class(obj)); return obj; } @@ -383,7 +383,7 @@ mutable_obj_clone(VALUE obj, VALUE kwfreeze) singleton = rb_singleton_class_clone_and_attach(obj, clone); RBASIC_SET_CLASS(clone, singleton); if (FL_TEST(singleton, FL_SINGLETON)) { - rb_singleton_class_attached(singleton, clone); + rb_singleton_class_attached(singleton, clone); } init_copy(clone, obj); @@ -391,7 +391,7 @@ mutable_obj_clone(VALUE obj, VALUE kwfreeze) switch (kwfreeze) { case Qnil: rb_funcall(clone, id_init_clone, 1, obj); - RBASIC(clone)->flags |= RBASIC(obj)->flags & FL_FREEZE; + RBASIC(clone)->flags |= RBASIC(obj)->flags & FL_FREEZE; break; case Qtrue: { @@ -483,7 +483,7 @@ rb_obj_dup(VALUE obj) VALUE dup; if (special_object_p(obj)) { - return obj; + return obj; } dup = rb_obj_alloc(rb_obj_class(obj)); init_copy(dup, obj); @@ -535,7 +535,7 @@ rb_obj_init_copy(VALUE obj, VALUE orig) if (obj == orig) return obj; rb_check_frozen(obj); if (TYPE(obj) != TYPE(orig) || rb_obj_class(obj) != rb_obj_class(orig)) { - rb_raise(rb_eTypeError, "initialize_copy should take same class object"); + rb_raise(rb_eTypeError, "initialize_copy should take same class object"); } return obj; } @@ -607,12 +607,12 @@ rb_inspect(VALUE obj) rb_encoding *enc = rb_default_internal_encoding(); if (enc == NULL) enc = rb_default_external_encoding(); if (!rb_enc_asciicompat(enc)) { - if (!rb_enc_str_asciionly_p(str)) - return rb_str_escape(str); - return str; + if (!rb_enc_str_asciionly_p(str)) + return rb_str_escape(str); + return str; } if (rb_enc_get(str) != enc && !rb_enc_str_asciionly_p(str)) - return rb_str_escape(str); + return rb_str_escape(str); return str; } @@ -627,14 +627,14 @@ inspect_i(st_data_t k, st_data_t v, st_data_t a) if (CLASS_OF(value) == 0) return ST_CONTINUE; if (!rb_is_instance_id(id)) return ST_CONTINUE; if (RSTRING_PTR(str)[0] == '-') { /* first element */ - RSTRING_PTR(str)[0] = '#'; - rb_str_cat2(str, " "); + RSTRING_PTR(str)[0] = '#'; + rb_str_cat2(str, " "); } else { - rb_str_cat2(str, ", "); + rb_str_cat2(str, ", "); } rb_str_catf(str, "%"PRIsVALUE"=%+"PRIsVALUE, - rb_id2str(id), value); + rb_id2str(id), value); return ST_CONTINUE; } @@ -643,10 +643,10 @@ static VALUE inspect_obj(VALUE obj, VALUE str, int recur) { if (recur) { - rb_str_cat2(str, " ..."); + rb_str_cat2(str, " ..."); } else { - rb_ivar_foreach(obj, inspect_i, str); + rb_ivar_foreach(obj, inspect_i, str); } rb_str_cat2(str, ">"); RSTRING_PTR(str)[0] = '#'; @@ -685,14 +685,14 @@ static VALUE rb_obj_inspect(VALUE obj) { if (rb_ivar_count(obj) > 0) { - VALUE str; - VALUE c = rb_class_name(CLASS_OF(obj)); + VALUE str; + VALUE c = rb_class_name(CLASS_OF(obj)); - str = rb_sprintf("-<%"PRIsVALUE":%p", c, (void*)obj); - return rb_exec_recursive(inspect_obj, obj, str); + str = rb_sprintf("-<%"PRIsVALUE":%p", c, (void*)obj); + return rb_exec_recursive(inspect_obj, obj, str); } else { - return rb_any_to_s(obj); + return rb_any_to_s(obj); } } @@ -703,10 +703,10 @@ class_or_module_required(VALUE c) case T_MODULE: case T_CLASS: case T_ICLASS: - break; + break; default: - rb_raise(rb_eTypeError, "class or module required"); + rb_raise(rb_eTypeError, "class or module required"); } return c; } @@ -1185,10 +1185,10 @@ VALUE rb_obj_freeze(VALUE obj) { if (!OBJ_FROZEN(obj)) { - OBJ_FREEZE(obj); - if (SPECIAL_CONST_P(obj)) { - rb_bug("special consts should be frozen."); - } + OBJ_FREEZE(obj); + if (SPECIAL_CONST_P(obj)) { + rb_bug("special consts should be frozen."); + } } return obj; } @@ -1490,7 +1490,7 @@ static VALUE rb_obj_cmp(VALUE obj1, VALUE obj2) { if (rb_equal(obj1, obj2)) - return INT2FIX(0); + return INT2FIX(0); return Qnil; } @@ -1538,30 +1538,30 @@ rb_mod_to_s(VALUE klass) VALUE refined_class, defined_at; if (FL_TEST(klass, FL_SINGLETON)) { - VALUE s = rb_usascii_str_new2("#"); + if (CLASS_OR_MODULE_P(v)) { + rb_str_append(s, rb_inspect(v)); + } + else { + rb_str_append(s, rb_any_to_s(v)); + } + rb_str_cat2(s, ">"); - return s; + return s; } refined_class = rb_refinement_module_get_refined_class(klass); if (!NIL_P(refined_class)) { - VALUE s = rb_usascii_str_new2("#"); - return s; + rb_str_concat(s, rb_inspect(refined_class)); + rb_str_cat2(s, "@"); + CONST_ID(id_defined_at, "__defined_at__"); + defined_at = rb_attr_get(klass, id_defined_at); + rb_str_concat(s, rb_inspect(defined_at)); + rb_str_cat2(s, ">"); + return s; } return rb_class_name(klass); } @@ -1684,7 +1684,7 @@ static VALUE rb_mod_ge(VALUE mod, VALUE arg) { if (!CLASS_OR_MODULE_P(arg)) { - rb_raise(rb_eTypeError, "compared with non class/module"); + rb_raise(rb_eTypeError, "compared with non class/module"); } return rb_class_inherited_p(arg, mod); @@ -1729,13 +1729,13 @@ rb_mod_cmp(VALUE mod, VALUE arg) if (mod == arg) return INT2FIX(0); if (!CLASS_OR_MODULE_P(arg)) { - return Qnil; + return Qnil; } cmp = rb_class_inherited_p(mod, arg); if (NIL_P(cmp)) return Qnil; if (cmp) { - return INT2FIX(-1); + return INT2FIX(-1); } return INT2FIX(1); } @@ -1778,7 +1778,7 @@ static VALUE rb_mod_initialize_exec(VALUE module) { if (rb_block_given_p()) { - rb_mod_module_exec(1, &module, module); + rb_mod_module_exec(1, &module, module); } return Qnil; } @@ -1831,17 +1831,17 @@ rb_class_initialize(int argc, VALUE *argv, VALUE klass) VALUE super; if (RCLASS_SUPER(klass) != 0 || klass == rb_cBasicObject) { - rb_raise(rb_eTypeError, "already initialized class"); + rb_raise(rb_eTypeError, "already initialized class"); } if (rb_check_arity(argc, 0, 1) == 0) { - super = rb_cObject; + super = rb_cObject; } else { super = argv[0]; - rb_check_inheritable(super); - if (super != rb_cBasicObject && !RCLASS_SUPER(super)) { - rb_raise(rb_eTypeError, "can't inherit uninitialized class"); - } + rb_check_inheritable(super); + if (super != rb_cBasicObject && !RCLASS_SUPER(super)) { + rb_raise(rb_eTypeError, "can't inherit uninitialized class"); + } } RCLASS_SET_SUPER(klass, super); rb_make_metaclass(klass, RBASIC(super)->klass); @@ -1856,7 +1856,7 @@ void rb_undefined_alloc(VALUE klass) { rb_raise(rb_eTypeError, "allocator undefined for %"PRIsVALUE, - klass); + klass); } static rb_alloc_func_t class_get_alloc_func(VALUE klass); @@ -1908,14 +1908,14 @@ class_get_alloc_func(VALUE klass) rb_alloc_func_t allocator; if (RCLASS_SUPER(klass) == 0 && klass != rb_cBasicObject) { - rb_raise(rb_eTypeError, "can't instantiate uninitialized class"); + rb_raise(rb_eTypeError, "can't instantiate uninitialized class"); } if (FL_TEST(klass, FL_SINGLETON)) { - rb_raise(rb_eTypeError, "can't create instance of singleton class"); + rb_raise(rb_eTypeError, "can't create instance of singleton class"); } allocator = rb_get_alloc_func(klass); if (!allocator) { - rb_undefined_alloc(klass); + rb_undefined_alloc(klass); } return allocator; } @@ -1930,7 +1930,7 @@ class_call_alloc_func(rb_alloc_func_t allocator, VALUE klass) obj = (*allocator)(klass); if (rb_obj_class(obj) != rb_class_real(klass)) { - rb_raise(rb_eTypeError, "wrong instance allocation"); + rb_raise(rb_eTypeError, "wrong instance allocation"); } return obj; } @@ -2023,8 +2023,8 @@ rb_class_superclass(VALUE klass) VALUE super = RCLASS_SUPER(klass); if (!super) { - if (klass == rb_cBasicObject) return Qnil; - rb_raise(rb_eTypeError, "uninitialized class"); + if (klass == rb_cBasicObject) return Qnil; + rb_raise(rb_eTypeError, "uninitialized class"); } else { super = RCLASS_SUPERCLASSES(klass)[RCLASS_SUPERCLASS_DEPTH(klass) - 1]; RUBY_ASSERT(RB_TYPE_P(klass, T_CLASS)); @@ -2051,15 +2051,15 @@ static const char bad_attr_name[] = "invalid attribute name `%1$s'"; check_setter_id(obj, &(name), rb_is_##type##_id, rb_is_##type##_name, message, strlen(message)) static ID check_setter_id(VALUE obj, VALUE *pname, - int (*valid_id_p)(ID), int (*valid_name_p)(VALUE), - const char *message, size_t message_len) + int (*valid_id_p)(ID), int (*valid_name_p)(VALUE), + const char *message, size_t message_len) { ID id = rb_check_id(pname); VALUE name = *pname; if (id ? !valid_id_p(id) : !valid_name_p(name)) { - rb_name_err_raise_str(rb_fstring_new(message, message_len), - obj, name); + rb_name_err_raise_str(rb_fstring_new(message, message_len), + obj, name); } return id; } @@ -2105,9 +2105,9 @@ rb_mod_attr_reader(int argc, VALUE *argv, VALUE klass) VALUE names = rb_ary_new2(argc); for (i=0; i= pend || p[1] != ':') goto wrong_name; - p += 2; - pbeg = p; - } + if (p < pend && p[0] == ':') { + if (p + 2 >= pend || p[1] != ':') goto wrong_name; + p += 2; + pbeg = p; + } - if (!RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) { - rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module", - QUOTE(name)); - } + if (!RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) { + rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module", + QUOTE(name)); + } - if (!id) { - part = rb_str_subseq(name, beglen, len); - OBJ_FREEZE(part); - if (!rb_is_const_name(part)) { - name = part; - goto wrong_name; - } - else if (!rb_method_basic_definition_p(CLASS_OF(mod), id_const_missing)) { - part = rb_str_intern(part); - mod = rb_const_missing(mod, part); - continue; - } - else { - rb_mod_const_missing(mod, part); - } - } - if (!rb_is_const_id(id)) { - name = ID2SYM(id); - goto wrong_name; - } + if (!id) { + part = rb_str_subseq(name, beglen, len); + OBJ_FREEZE(part); + if (!rb_is_const_name(part)) { + name = part; + goto wrong_name; + } + else if (!rb_method_basic_definition_p(CLASS_OF(mod), id_const_missing)) { + part = rb_str_intern(part); + mod = rb_const_missing(mod, part); + continue; + } + else { + rb_mod_const_missing(mod, part); + } + } + if (!rb_is_const_id(id)) { + name = ID2SYM(id); + goto wrong_name; + } #if 0 mod = rb_const_get_0(mod, id, beglen > 0 || !RTEST(recur), RTEST(recur), FALSE); #else @@ -2428,17 +2428,17 @@ rb_mod_const_defined(int argc, VALUE *argv, VALUE mod) recur = (argc == 1) ? Qtrue : argv[1]; if (SYMBOL_P(name)) { - if (!rb_is_const_sym(name)) goto wrong_name; - id = rb_check_id(&name); - if (!id) return Qfalse; - return RTEST(recur) ? rb_const_defined(mod, id) : rb_const_defined_at(mod, id); + if (!rb_is_const_sym(name)) goto wrong_name; + id = rb_check_id(&name); + if (!id) return Qfalse; + return RTEST(recur) ? rb_const_defined(mod, id) : rb_const_defined_at(mod, id); } path = StringValuePtr(name); enc = rb_enc_get(name); if (!rb_enc_asciicompat(enc)) { - rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)"); + rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)"); } pbeg = p = path; @@ -2449,54 +2449,54 @@ rb_mod_const_defined(int argc, VALUE *argv, VALUE mod) } if (p + 2 < pend && p[0] == ':' && p[1] == ':') { - mod = rb_cObject; - p += 2; - pbeg = p; + mod = rb_cObject; + p += 2; + pbeg = p; } while (p < pend) { - VALUE part; - long len, beglen; + VALUE part; + long len, beglen; - while (p < pend && *p != ':') p++; + while (p < pend && *p != ':') p++; - if (pbeg == p) goto wrong_name; + if (pbeg == p) goto wrong_name; - id = rb_check_id_cstr(pbeg, len = p-pbeg, enc); - beglen = pbeg-path; + id = rb_check_id_cstr(pbeg, len = p-pbeg, enc); + beglen = pbeg-path; - if (p < pend && p[0] == ':') { - if (p + 2 >= pend || p[1] != ':') goto wrong_name; - p += 2; - pbeg = p; - } + if (p < pend && p[0] == ':') { + if (p + 2 >= pend || p[1] != ':') goto wrong_name; + p += 2; + pbeg = p; + } - if (!id) { - part = rb_str_subseq(name, beglen, len); - OBJ_FREEZE(part); - if (!rb_is_const_name(part)) { - name = part; - goto wrong_name; - } - else { - return Qfalse; - } - } - if (!rb_is_const_id(id)) { - name = ID2SYM(id); - goto wrong_name; - } + if (!id) { + part = rb_str_subseq(name, beglen, len); + OBJ_FREEZE(part); + if (!rb_is_const_name(part)) { + name = part; + goto wrong_name; + } + else { + return Qfalse; + } + } + if (!rb_is_const_id(id)) { + name = ID2SYM(id); + goto wrong_name; + } #if 0 mod = rb_const_search(mod, id, beglen > 0 || !RTEST(recur), RTEST(recur), FALSE); if (mod == Qundef) return Qfalse; #else if (!RTEST(recur)) { - if (!rb_const_defined_at(mod, id)) - return Qfalse; + if (!rb_const_defined_at(mod, id)) + return Qfalse; if (p == pend) return Qtrue; - mod = rb_const_get_at(mod, id); - } + mod = rb_const_get_at(mod, id); + } else if (beglen == 0) { if (!rb_const_defined(mod, id)) return Qfalse; @@ -2511,10 +2511,10 @@ rb_mod_const_defined(int argc, VALUE *argv, VALUE mod) } #endif - if (p < pend && !RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) { - rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module", - QUOTE(name)); - } + if (p < pend && !RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) { + rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module", + QUOTE(name)); + } } return Qtrue; @@ -2705,7 +2705,7 @@ rb_obj_ivar_get(VALUE obj, VALUE iv) ID id = id_for_var(obj, iv, instance); if (!id) { - return Qnil; + return Qnil; } return rb_ivar_get(obj, id); } @@ -2767,7 +2767,7 @@ rb_obj_ivar_defined(VALUE obj, VALUE iv) ID id = id_for_var(obj, iv, instance); if (!id) { - return Qfalse; + return Qfalse; } return rb_ivar_defined(obj, id); } @@ -2794,8 +2794,8 @@ rb_mod_cvar_get(VALUE obj, VALUE iv) ID id = id_for_var(obj, iv, class); if (!id) { - rb_name_err_raise("uninitialized class variable %1$s in %2$s", - obj, iv); + rb_name_err_raise("uninitialized class variable %1$s in %2$s", + obj, iv); } return rb_cvar_get(obj, id); } @@ -2851,7 +2851,7 @@ rb_mod_cvar_defined(VALUE obj, VALUE iv) ID id = id_for_var(obj, iv, class); if (!id) { - return Qfalse; + return Qfalse; } return rb_cvar_defined(obj, id); } @@ -2903,14 +2903,14 @@ conv_method_index(const char *method) static const char prefix[] = "to_"; if (strncmp(prefix, method, sizeof(prefix)-1) == 0) { - const char *const meth = &method[sizeof(prefix)-1]; - int i; - for (i=0; i < numberof(conv_method_names); i++) { - if (conv_method_names[i].method[0] == meth[0] && - strcmp(conv_method_names[i].method, meth) == 0) { - return i; - } - } + const char *const meth = &method[sizeof(prefix)-1]; + int i; + for (i=0; i < numberof(conv_method_names); i++) { + if (conv_method_names[i].method[0] == meth[0] && + strcmp(conv_method_names[i].method, meth) == 0) { + return i; + } + } } return numberof(conv_method_names); } @@ -2920,22 +2920,22 @@ convert_type_with_id(VALUE val, const char *tname, ID method, int raise, int ind { VALUE r = rb_check_funcall(val, method, 0, 0); if (r == Qundef) { - if (raise) { - const char *msg = - ((index < 0 ? conv_method_index(rb_id2name(method)) : index) - < IMPLICIT_CONVERSIONS) ? - "no implicit conversion of" : "can't convert"; - const char *cname = NIL_P(val) ? "nil" : - val == Qtrue ? "true" : - val == Qfalse ? "false" : - NULL; - if (cname) - rb_raise(rb_eTypeError, "%s %s into %s", msg, cname, tname); - rb_raise(rb_eTypeError, "%s %"PRIsVALUE" into %s", msg, - rb_obj_class(val), - tname); - } - return Qnil; + if (raise) { + const char *msg = + ((index < 0 ? conv_method_index(rb_id2name(method)) : index) + < IMPLICIT_CONVERSIONS) ? + "no implicit conversion of" : "can't convert"; + const char *cname = NIL_P(val) ? "nil" : + val == Qtrue ? "true" : + val == Qfalse ? "false" : + NULL; + if (cname) + rb_raise(rb_eTypeError, "%s %s into %s", msg, cname, tname); + rb_raise(rb_eTypeError, "%s %"PRIsVALUE" into %s", msg, + rb_obj_class(val), + tname); + } + return Qnil; } return r; } @@ -2945,7 +2945,7 @@ convert_type(VALUE val, const char *tname, const char *method, int raise) { int i = conv_method_index(method); ID m = i < numberof(conv_method_names) ? - conv_method_names[i].id : rb_intern(method); + conv_method_names[i].id : rb_intern(method); return convert_type_with_id(val, tname, m, raise, i); } @@ -2956,8 +2956,8 @@ conversion_mismatch(VALUE val, const char *tname, const char *method, VALUE resu { VALUE cname = rb_obj_class(val); rb_raise(rb_eTypeError, - "can't convert %"PRIsVALUE" to %s (%"PRIsVALUE"#%s gives %"PRIsVALUE")", - cname, tname, cname, method, rb_obj_class(result)); + "can't convert %"PRIsVALUE" to %s (%"PRIsVALUE"#%s gives %"PRIsVALUE")", + cname, tname, cname, method, rb_obj_class(result)); } VALUE @@ -2968,7 +2968,7 @@ rb_convert_type(VALUE val, int type, const char *tname, const char *method) if (TYPE(val) == type) return val; v = convert_type(val, tname, method, TRUE); if (TYPE(v) != type) { - conversion_mismatch(val, tname, method, v); + conversion_mismatch(val, tname, method, v); } return v; } @@ -2982,7 +2982,7 @@ rb_convert_type_with_id(VALUE val, int type, const char *tname, ID method) if (TYPE(val) == type) return val; v = convert_type_with_id(val, tname, method, TRUE, -1); if (TYPE(v) != type) { - conversion_mismatch(val, tname, RSTRING_PTR(rb_id2str(method)), v); + conversion_mismatch(val, tname, RSTRING_PTR(rb_id2str(method)), v); } return v; } @@ -2997,7 +2997,7 @@ rb_check_convert_type(VALUE val, int type, const char *tname, const char *method v = convert_type(val, tname, method, FALSE); if (NIL_P(v)) return Qnil; if (TYPE(v) != type) { - conversion_mismatch(val, tname, method, v); + conversion_mismatch(val, tname, method, v); } return v; } @@ -3013,7 +3013,7 @@ rb_check_convert_type_with_id(VALUE val, int type, const char *tname, ID method) v = convert_type_with_id(val, tname, method, FALSE, -1); if (NIL_P(v)) return Qnil; if (TYPE(v) != type) { - conversion_mismatch(val, tname, RSTRING_PTR(rb_id2str(method)), v); + conversion_mismatch(val, tname, RSTRING_PTR(rb_id2str(method)), v); } return v; } @@ -3393,24 +3393,24 @@ rb_str_to_dbl_raise(VALUE str, int badcheck, int raise, int *error) s = RSTRING_PTR(str); len = RSTRING_LEN(str); if (s) { - if (badcheck && memchr(s, '\0', len)) { + if (badcheck && memchr(s, '\0', len)) { if (raise) rb_raise(rb_eArgError, "string for Float contains null byte"); else { if (error) *error = 1; return 0.0; } - } - if (s[len]) { /* no sentinel somehow */ - char *p = ALLOCV(v, (size_t)len + 1); - MEMCPY(p, s, char, len); - p[len] = '\0'; - s = p; - } + } + if (s[len]) { /* no sentinel somehow */ + char *p = ALLOCV(v, (size_t)len + 1); + MEMCPY(p, s, char, len); + p[len] = '\0'; + s = p; + } } ret = rb_cstr_to_dbl_raise(s, badcheck, raise, error); if (v) - ALLOCV_END(v); + ALLOCV_END(v); return ret; } @@ -3442,11 +3442,11 @@ rat2dbl_without_to_f(VALUE x) #define special_const_to_float(val, pre, post) \ switch (val) { \ case Qnil: \ - rb_raise_static(rb_eTypeError, pre "nil" post); \ + rb_raise_static(rb_eTypeError, pre "nil" post); \ case Qtrue: \ - rb_raise_static(rb_eTypeError, pre "true" post); \ + rb_raise_static(rb_eTypeError, pre "true" post); \ case Qfalse: \ - rb_raise_static(rb_eTypeError, pre "false" post); \ + rb_raise_static(rb_eTypeError, pre "false" post); \ } /*! \endcond */ @@ -3467,31 +3467,31 @@ to_float(VALUE *valp, int raise_exception) { VALUE val = *valp; if (SPECIAL_CONST_P(val)) { - if (FIXNUM_P(val)) { - *valp = DBL2NUM(fix2dbl_without_to_f(val)); - return T_FLOAT; - } - else if (FLONUM_P(val)) { - return T_FLOAT; - } - else if (raise_exception) { - conversion_to_float(val); - } + if (FIXNUM_P(val)) { + *valp = DBL2NUM(fix2dbl_without_to_f(val)); + return T_FLOAT; + } + else if (FLONUM_P(val)) { + return T_FLOAT; + } + else if (raise_exception) { + conversion_to_float(val); + } } else { - int type = BUILTIN_TYPE(val); - switch (type) { - case T_FLOAT: - return T_FLOAT; - case T_BIGNUM: - *valp = DBL2NUM(big2dbl_without_to_f(val)); - return T_FLOAT; - case T_RATIONAL: - *valp = DBL2NUM(rat2dbl_without_to_f(val)); - return T_FLOAT; - case T_STRING: - return T_STRING; - } + int type = BUILTIN_TYPE(val); + switch (type) { + case T_FLOAT: + return T_FLOAT; + case T_BIGNUM: + *valp = DBL2NUM(big2dbl_without_to_f(val)); + return T_FLOAT; + case T_RATIONAL: + *valp = DBL2NUM(rat2dbl_without_to_f(val)); + return T_FLOAT; + case T_STRING: + return T_STRING; + } } return T_NONE; } @@ -3507,7 +3507,7 @@ rb_convert_to_float(VALUE val, int raise_exception) { switch (to_float(&val, raise_exception)) { case T_FLOAT: - return val; + return val; case T_STRING: if (!raise_exception) { int e = 0; @@ -3555,8 +3555,8 @@ static VALUE numeric_to_float(VALUE val) { if (!rb_obj_is_kind_of(val, rb_cNumeric)) { - rb_raise(rb_eTypeError, "can't convert %"PRIsVALUE" into Float", - rb_obj_class(val)); + rb_raise(rb_eTypeError, "can't convert %"PRIsVALUE" into Float", + rb_obj_class(val)); } return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f); } @@ -3566,7 +3566,7 @@ rb_to_float(VALUE val) { switch (to_float(&val, TRUE)) { case T_FLOAT: - return val; + return val; } return numeric_to_float(val); } @@ -3576,7 +3576,7 @@ rb_check_to_float(VALUE val) { if (RB_FLOAT_TYPE_P(val)) return val; if (!rb_obj_is_kind_of(val, rb_cNumeric)) { - return Qnil; + return Qnil; } return rb_check_convert_type_with_id(val, T_FLOAT, "Float", id_to_f); } @@ -3592,32 +3592,32 @@ double rb_num_to_dbl(VALUE val) { if (SPECIAL_CONST_P(val)) { - if (FIXNUM_P(val)) { - if (basic_to_f_p(rb_cInteger)) - return fix2dbl_without_to_f(val); - } - else if (FLONUM_P(val)) { - return rb_float_flonum_value(val); - } - else { - conversion_to_float(val); - } + if (FIXNUM_P(val)) { + if (basic_to_f_p(rb_cInteger)) + return fix2dbl_without_to_f(val); + } + else if (FLONUM_P(val)) { + return rb_float_flonum_value(val); + } + else { + conversion_to_float(val); + } } else { - switch (BUILTIN_TYPE(val)) { - case T_FLOAT: - return rb_float_noflonum_value(val); - case T_BIGNUM: - if (basic_to_f_p(rb_cInteger)) - return big2dbl_without_to_f(val); - break; - case T_RATIONAL: - if (basic_to_f_p(rb_cRational)) - return rat2dbl_without_to_f(val); - break; + switch (BUILTIN_TYPE(val)) { + case T_FLOAT: + return rb_float_noflonum_value(val); + case T_BIGNUM: + if (basic_to_f_p(rb_cInteger)) + return big2dbl_without_to_f(val); + break; + case T_RATIONAL: + if (basic_to_f_p(rb_cRational)) + return rat2dbl_without_to_f(val); + break; default: - break; - } + break; + } } val = numeric_to_float(val); return RFLOAT_VALUE(val); @@ -3627,29 +3627,29 @@ double rb_num2dbl(VALUE val) { if (SPECIAL_CONST_P(val)) { - if (FIXNUM_P(val)) { - return fix2dbl_without_to_f(val); - } - else if (FLONUM_P(val)) { - return rb_float_flonum_value(val); - } - else { - implicit_conversion_to_float(val); - } + if (FIXNUM_P(val)) { + return fix2dbl_without_to_f(val); + } + else if (FLONUM_P(val)) { + return rb_float_flonum_value(val); + } + else { + implicit_conversion_to_float(val); + } } else { - switch (BUILTIN_TYPE(val)) { - case T_FLOAT: - return rb_float_noflonum_value(val); - case T_BIGNUM: - return big2dbl_without_to_f(val); - case T_RATIONAL: - return rat2dbl_without_to_f(val); - case T_STRING: - rb_raise(rb_eTypeError, "no implicit conversion to float from string"); + switch (BUILTIN_TYPE(val)) { + case T_FLOAT: + return rb_float_noflonum_value(val); + case T_BIGNUM: + return big2dbl_without_to_f(val); + case T_RATIONAL: + return rat2dbl_without_to_f(val); + case T_STRING: + rb_raise(rb_eTypeError, "no implicit conversion to float from string"); default: - break; - } + break; + } } val = rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f); return RFLOAT_VALUE(val); @@ -3660,7 +3660,7 @@ rb_String(VALUE val) { VALUE tmp = rb_check_string_type(val); if (NIL_P(tmp)) - tmp = rb_convert_type_with_id(val, T_STRING, "String", idTo_s); + tmp = rb_convert_type_with_id(val, T_STRING, "String", idTo_s); return tmp; } @@ -3693,10 +3693,10 @@ rb_Array(VALUE val) VALUE tmp = rb_check_array_type(val); if (NIL_P(tmp)) { - tmp = rb_check_to_array(val); - if (NIL_P(tmp)) { - return rb_ary_new3(1, val); - } + tmp = rb_check_to_array(val); + if (NIL_P(tmp)) { + return rb_ary_new3(1, val); + } } return tmp; } @@ -3738,9 +3738,9 @@ rb_Hash(VALUE val) if (NIL_P(val)) return rb_hash_new(); tmp = rb_check_hash_type(val); if (NIL_P(tmp)) { - if (RB_TYPE_P(val, T_ARRAY) && RARRAY_LEN(val) == 0) - return rb_hash_new(); - rb_raise(rb_eTypeError, "can't convert %s into Hash", rb_obj_classname(val)); + if (RB_TYPE_P(val, T_ARRAY) && RARRAY_LEN(val) == 0) + return rb_hash_new(); + rb_raise(rb_eTypeError, "can't convert %s into Hash", rb_obj_classname(val)); } return tmp; } @@ -3786,8 +3786,8 @@ dig_basic_p(VALUE obj, struct dig_method *cache) { VALUE klass = RBASIC_CLASS(obj); if (klass != cache->klass) { - cache->klass = klass; - cache->basic = rb_method_basic_definition_p(klass, id_dig); + cache->klass = klass; + cache->basic = rb_method_basic_definition_p(klass, id_dig); } return cache->basic; } @@ -3796,8 +3796,8 @@ static void no_dig_method(int found, VALUE recv, ID mid, int argc, const VALUE *argv, VALUE data) { if (!found) { - rb_raise(rb_eTypeError, "%"PRIsVALUE" does not have #dig method", - CLASS_OF(data)); + rb_raise(rb_eTypeError, "%"PRIsVALUE" does not have #dig method", + CLASS_OF(data)); } } @@ -3808,31 +3808,31 @@ rb_obj_dig(int argc, VALUE *argv, VALUE obj, VALUE notfound) struct dig_method hash = {Qnil}, ary = {Qnil}, strt = {Qnil}; for (; argc > 0; ++argv, --argc) { - if (NIL_P(obj)) return notfound; - if (!SPECIAL_CONST_P(obj)) { - switch (BUILTIN_TYPE(obj)) { - case T_HASH: - if (dig_basic_p(obj, &hash)) { - obj = rb_hash_aref(obj, *argv); - continue; - } - break; - case T_ARRAY: - if (dig_basic_p(obj, &ary)) { - obj = rb_ary_at(obj, *argv); - continue; - } - break; - case T_STRUCT: - if (dig_basic_p(obj, &strt)) { - obj = rb_struct_lookup(obj, *argv); - continue; - } - break; + if (NIL_P(obj)) return notfound; + if (!SPECIAL_CONST_P(obj)) { + switch (BUILTIN_TYPE(obj)) { + case T_HASH: + if (dig_basic_p(obj, &hash)) { + obj = rb_hash_aref(obj, *argv); + continue; + } + break; + case T_ARRAY: + if (dig_basic_p(obj, &ary)) { + obj = rb_ary_at(obj, *argv); + continue; + } + break; + case T_STRUCT: + if (dig_basic_p(obj, &strt)) { + obj = rb_struct_lookup(obj, *argv); + continue; + } + break; default: break; - } - } + } + } return rb_check_funcall_with_hook_kw(obj, id_dig, argc, argv, no_dig_method, obj, RB_NO_KEYWORDS); @@ -4320,7 +4320,7 @@ InitVM_Object(void) rb_define_method(rb_mKernel, "instance_variable_set", rb_obj_ivar_set, 2); rb_define_method(rb_mKernel, "instance_variable_defined?", rb_obj_ivar_defined, 1); rb_define_method(rb_mKernel, "remove_instance_variable", - rb_obj_remove_instance_variable, 1); /* in variable.c */ + rb_obj_remove_instance_variable, 1); /* in variable.c */ rb_define_method(rb_mKernel, "instance_of?", rb_obj_is_instance_of, 1); rb_define_method(rb_mKernel, "kind_of?", rb_obj_is_kind_of, 1); @@ -4379,11 +4379,11 @@ InitVM_Object(void) rb_define_method(rb_cModule, "initialize_clone", rb_mod_initialize_clone, -1); rb_define_method(rb_cModule, "instance_methods", rb_class_instance_methods, -1); /* in class.c */ rb_define_method(rb_cModule, "public_instance_methods", - rb_class_public_instance_methods, -1); /* in class.c */ + rb_class_public_instance_methods, -1); /* in class.c */ rb_define_method(rb_cModule, "protected_instance_methods", - rb_class_protected_instance_methods, -1); /* in class.c */ + rb_class_protected_instance_methods, -1); /* in class.c */ rb_define_method(rb_cModule, "private_instance_methods", - rb_class_private_instance_methods, -1); /* in class.c */ + rb_class_private_instance_methods, -1); /* in class.c */ rb_define_method(rb_cModule, "undefined_instance_methods", rb_class_undefined_instance_methods, 0); /* in class.c */ @@ -4393,13 +4393,13 @@ InitVM_Object(void) rb_define_method(rb_cModule, "const_defined?", rb_mod_const_defined, -1); rb_define_method(rb_cModule, "const_source_location", rb_mod_const_source_location, -1); rb_define_private_method(rb_cModule, "remove_const", - rb_mod_remove_const, 1); /* in variable.c */ + rb_mod_remove_const, 1); /* in variable.c */ rb_define_method(rb_cModule, "const_missing", - rb_mod_const_missing, 1); /* in variable.c */ + rb_mod_const_missing, 1); /* in variable.c */ rb_define_method(rb_cModule, "class_variables", - rb_mod_class_variables, -1); /* in variable.c */ + rb_mod_class_variables, -1); /* in variable.c */ rb_define_method(rb_cModule, "remove_class_variable", - rb_mod_remove_cvar, 1); /* in variable.c */ + rb_mod_remove_cvar, 1); /* in variable.c */ rb_define_method(rb_cModule, "class_variable_get", rb_mod_cvar_get, 1); rb_define_method(rb_cModule, "class_variable_set", rb_mod_cvar_set, 2); rb_define_method(rb_cModule, "class_variable_defined?", rb_mod_cvar_defined, 1); diff --git a/pack.c b/pack.c index 1fbbd724d7..2817491b77 100644 --- a/pack.c +++ b/pack.c @@ -147,8 +147,8 @@ associated_pointer(VALUE associates, const char *t) const VALUE *p = RARRAY_CONST_PTR(associates); const VALUE *pend = p + RARRAY_LEN(associates); for (; p < pend; p++) { - VALUE tmp = *p; - if (RB_TYPE_P(tmp, T_STRING) && RSTRING_PTR(tmp) == t) return tmp; + VALUE tmp = *p; + if (RB_TYPE_P(tmp, T_STRING) && RSTRING_PTR(tmp) == t) return tmp; } rb_raise(rb_eArgError, "non associated pointer"); UNREACHABLE_RETURN(Qnil); @@ -212,12 +212,12 @@ pack_pack(rb_execution_context_t *ec, VALUE ary, VALUE fmt, VALUE buffer) pend = p + RSTRING_LEN(fmt); if (NIL_P(buffer)) { - res = rb_str_buf_new(0); + res = rb_str_buf_new(0); } else { if (!RB_TYPE_P(buffer, T_STRING)) rb_raise(rb_eTypeError, "buffer must be String, not %s", rb_obj_classname(buffer)); - res = buffer; + res = buffer; } idx = 0; @@ -228,327 +228,327 @@ pack_pack(rb_execution_context_t *ec, VALUE ary, VALUE fmt, VALUE buffer) #define NEXTFROM (MORE_ITEM ? RARRAY_AREF(ary, idx++) : TOO_FEW) while (p < pend) { - int explicit_endian = 0; - if (RSTRING_PTR(fmt) + RSTRING_LEN(fmt) != pend) { - rb_raise(rb_eRuntimeError, "format string modified"); - } - type = *p++; /* get data type */ + int explicit_endian = 0; + if (RSTRING_PTR(fmt) + RSTRING_LEN(fmt) != pend) { + rb_raise(rb_eRuntimeError, "format string modified"); + } + type = *p++; /* get data type */ #ifdef NATINT_PACK - natint = 0; + natint = 0; #endif - if (ISSPACE(type)) continue; - if (type == '#') { - while ((p < pend) && (*p != '\n')) { - p++; - } - continue; - } + if (ISSPACE(type)) continue; + if (type == '#') { + while ((p < pend) && (*p != '\n')) { + p++; + } + continue; + } - { + { modifiers: - switch (*p) { - case '_': - case '!': - if (strchr(natstr, type)) { + switch (*p) { + case '_': + case '!': + if (strchr(natstr, type)) { #ifdef NATINT_PACK - natint = 1; + natint = 1; #endif - p++; - } - else { - rb_raise(rb_eArgError, "'%c' allowed only after types %s", *p, natstr); - } - goto modifiers; + p++; + } + else { + rb_raise(rb_eArgError, "'%c' allowed only after types %s", *p, natstr); + } + goto modifiers; - case '<': - case '>': - if (!strchr(endstr, type)) { - rb_raise(rb_eArgError, "'%c' allowed only after types %s", *p, endstr); - } - if (explicit_endian) { - rb_raise(rb_eRangeError, "Can't use both '<' and '>'"); - } - explicit_endian = *p++; - goto modifiers; - } - } + case '<': + case '>': + if (!strchr(endstr, type)) { + rb_raise(rb_eArgError, "'%c' allowed only after types %s", *p, endstr); + } + if (explicit_endian) { + rb_raise(rb_eRangeError, "Can't use both '<' and '>'"); + } + explicit_endian = *p++; + goto modifiers; + } + } - if (*p == '*') { /* set data length */ - len = strchr("@Xxu", type) ? 0 + if (*p == '*') { /* set data length */ + len = strchr("@Xxu", type) ? 0 : strchr("PMm", type) ? 1 : RARRAY_LEN(ary) - idx; - p++; - } - else if (ISDIGIT(*p)) { - errno = 0; - len = STRTOUL(p, (char**)&p, 10); - if (errno) { - rb_raise(rb_eRangeError, "pack length too big"); - } - } - else { - len = 1; - } + p++; + } + else if (ISDIGIT(*p)) { + errno = 0; + len = STRTOUL(p, (char**)&p, 10); + if (errno) { + rb_raise(rb_eRangeError, "pack length too big"); + } + } + else { + len = 1; + } - switch (type) { - case 'U': - /* if encoding is US-ASCII, upgrade to UTF-8 */ - if (enc_info == 1) enc_info = 2; - break; - case 'm': case 'M': case 'u': - /* keep US-ASCII (do nothing) */ - break; - default: - /* fall back to BINARY */ - enc_info = 0; - break; - } - switch (type) { - case 'A': case 'a': case 'Z': - case 'B': case 'b': - case 'H': case 'h': - from = NEXTFROM; - if (NIL_P(from)) { - ptr = ""; - plen = 0; - } - else { - StringValue(from); - ptr = RSTRING_PTR(from); - plen = RSTRING_LEN(from); - } + switch (type) { + case 'U': + /* if encoding is US-ASCII, upgrade to UTF-8 */ + if (enc_info == 1) enc_info = 2; + break; + case 'm': case 'M': case 'u': + /* keep US-ASCII (do nothing) */ + break; + default: + /* fall back to BINARY */ + enc_info = 0; + break; + } + switch (type) { + case 'A': case 'a': case 'Z': + case 'B': case 'b': + case 'H': case 'h': + from = NEXTFROM; + if (NIL_P(from)) { + ptr = ""; + plen = 0; + } + else { + StringValue(from); + ptr = RSTRING_PTR(from); + plen = RSTRING_LEN(from); + } - if (p[-1] == '*') - len = plen; + if (p[-1] == '*') + len = plen; - switch (type) { - case 'a': /* arbitrary binary string (null padded) */ - case 'A': /* arbitrary binary string (ASCII space padded) */ - case 'Z': /* null terminated string */ - if (plen >= len) { - rb_str_buf_cat(res, ptr, len); - if (p[-1] == '*' && type == 'Z') - rb_str_buf_cat(res, nul10, 1); - } - else { - rb_str_buf_cat(res, ptr, plen); - len -= plen; - while (len >= 10) { - rb_str_buf_cat(res, (type == 'A')?spc10:nul10, 10); - len -= 10; - } - rb_str_buf_cat(res, (type == 'A')?spc10:nul10, len); - } - break; + switch (type) { + case 'a': /* arbitrary binary string (null padded) */ + case 'A': /* arbitrary binary string (ASCII space padded) */ + case 'Z': /* null terminated string */ + if (plen >= len) { + rb_str_buf_cat(res, ptr, len); + if (p[-1] == '*' && type == 'Z') + rb_str_buf_cat(res, nul10, 1); + } + else { + rb_str_buf_cat(res, ptr, plen); + len -= plen; + while (len >= 10) { + rb_str_buf_cat(res, (type == 'A')?spc10:nul10, 10); + len -= 10; + } + rb_str_buf_cat(res, (type == 'A')?spc10:nul10, len); + } + break; #define castchar(from) (char)((from) & 0xff) - case 'b': /* bit string (ascending) */ - { - int byte = 0; - long i, j = 0; + case 'b': /* bit string (ascending) */ + { + int byte = 0; + long i, j = 0; - if (len > plen) { - j = (len - plen + 1)/2; - len = plen; - } - for (i=0; i++ < len; ptr++) { - if (*ptr & 1) - byte |= 128; - if (i & 7) - byte >>= 1; - else { - char c = castchar(byte); - rb_str_buf_cat(res, &c, 1); - byte = 0; - } - } - if (len & 7) { - char c; - byte >>= 7 - (len & 7); - c = castchar(byte); - rb_str_buf_cat(res, &c, 1); - } - len = j; - goto grow; - } - break; + if (len > plen) { + j = (len - plen + 1)/2; + len = plen; + } + for (i=0; i++ < len; ptr++) { + if (*ptr & 1) + byte |= 128; + if (i & 7) + byte >>= 1; + else { + char c = castchar(byte); + rb_str_buf_cat(res, &c, 1); + byte = 0; + } + } + if (len & 7) { + char c; + byte >>= 7 - (len & 7); + c = castchar(byte); + rb_str_buf_cat(res, &c, 1); + } + len = j; + goto grow; + } + break; - case 'B': /* bit string (descending) */ - { - int byte = 0; - long i, j = 0; + case 'B': /* bit string (descending) */ + { + int byte = 0; + long i, j = 0; - if (len > plen) { - j = (len - plen + 1)/2; - len = plen; - } - for (i=0; i++ < len; ptr++) { - byte |= *ptr & 1; - if (i & 7) - byte <<= 1; - else { - char c = castchar(byte); - rb_str_buf_cat(res, &c, 1); - byte = 0; - } - } - if (len & 7) { - char c; - byte <<= 7 - (len & 7); - c = castchar(byte); - rb_str_buf_cat(res, &c, 1); - } - len = j; - goto grow; - } - break; + if (len > plen) { + j = (len - plen + 1)/2; + len = plen; + } + for (i=0; i++ < len; ptr++) { + byte |= *ptr & 1; + if (i & 7) + byte <<= 1; + else { + char c = castchar(byte); + rb_str_buf_cat(res, &c, 1); + byte = 0; + } + } + if (len & 7) { + char c; + byte <<= 7 - (len & 7); + c = castchar(byte); + rb_str_buf_cat(res, &c, 1); + } + len = j; + goto grow; + } + break; - case 'h': /* hex string (low nibble first) */ - { - int byte = 0; - long i, j = 0; + case 'h': /* hex string (low nibble first) */ + { + int byte = 0; + long i, j = 0; - if (len > plen) { - j = (len + 1) / 2 - (plen + 1) / 2; - len = plen; - } - for (i=0; i++ < len; ptr++) { - if (ISALPHA(*ptr)) - byte |= (((*ptr & 15) + 9) & 15) << 4; - else - byte |= (*ptr & 15) << 4; - if (i & 1) - byte >>= 4; - else { - char c = castchar(byte); - rb_str_buf_cat(res, &c, 1); - byte = 0; - } - } - if (len & 1) { - char c = castchar(byte); - rb_str_buf_cat(res, &c, 1); - } - len = j; - goto grow; - } - break; + if (len > plen) { + j = (len + 1) / 2 - (plen + 1) / 2; + len = plen; + } + for (i=0; i++ < len; ptr++) { + if (ISALPHA(*ptr)) + byte |= (((*ptr & 15) + 9) & 15) << 4; + else + byte |= (*ptr & 15) << 4; + if (i & 1) + byte >>= 4; + else { + char c = castchar(byte); + rb_str_buf_cat(res, &c, 1); + byte = 0; + } + } + if (len & 1) { + char c = castchar(byte); + rb_str_buf_cat(res, &c, 1); + } + len = j; + goto grow; + } + break; - case 'H': /* hex string (high nibble first) */ - { - int byte = 0; - long i, j = 0; + case 'H': /* hex string (high nibble first) */ + { + int byte = 0; + long i, j = 0; - if (len > plen) { - j = (len + 1) / 2 - (plen + 1) / 2; - len = plen; - } - for (i=0; i++ < len; ptr++) { - if (ISALPHA(*ptr)) - byte |= ((*ptr & 15) + 9) & 15; - else - byte |= *ptr & 15; - if (i & 1) - byte <<= 4; - else { - char c = castchar(byte); - rb_str_buf_cat(res, &c, 1); - byte = 0; - } - } - if (len & 1) { - char c = castchar(byte); - rb_str_buf_cat(res, &c, 1); - } - len = j; - goto grow; - } - break; - } - break; + if (len > plen) { + j = (len + 1) / 2 - (plen + 1) / 2; + len = plen; + } + for (i=0; i++ < len; ptr++) { + if (ISALPHA(*ptr)) + byte |= ((*ptr & 15) + 9) & 15; + else + byte |= *ptr & 15; + if (i & 1) + byte <<= 4; + else { + char c = castchar(byte); + rb_str_buf_cat(res, &c, 1); + byte = 0; + } + } + if (len & 1) { + char c = castchar(byte); + rb_str_buf_cat(res, &c, 1); + } + len = j; + goto grow; + } + break; + } + break; - case 'c': /* signed char */ - case 'C': /* unsigned char */ + case 'c': /* signed char */ + case 'C': /* unsigned char */ integer_size = 1; bigendian_p = BIGENDIAN_P(); /* not effective */ goto pack_integer; - case 's': /* s for int16_t, s! for signed short */ + case 's': /* s for int16_t, s! for signed short */ integer_size = NATINT_LEN(short, 2); bigendian_p = BIGENDIAN_P(); goto pack_integer; - case 'S': /* S for uint16_t, S! for unsigned short */ + case 'S': /* S for uint16_t, S! for unsigned short */ integer_size = NATINT_LEN(short, 2); bigendian_p = BIGENDIAN_P(); goto pack_integer; - case 'i': /* i and i! for signed int */ + case 'i': /* i and i! for signed int */ integer_size = (int)sizeof(int); bigendian_p = BIGENDIAN_P(); goto pack_integer; - case 'I': /* I and I! for unsigned int */ + case 'I': /* I and I! for unsigned int */ integer_size = (int)sizeof(int); bigendian_p = BIGENDIAN_P(); goto pack_integer; - case 'l': /* l for int32_t, l! for signed long */ + case 'l': /* l for int32_t, l! for signed long */ integer_size = NATINT_LEN(long, 4); bigendian_p = BIGENDIAN_P(); goto pack_integer; - case 'L': /* L for uint32_t, L! for unsigned long */ + case 'L': /* L for uint32_t, L! for unsigned long */ integer_size = NATINT_LEN(long, 4); bigendian_p = BIGENDIAN_P(); goto pack_integer; - case 'q': /* q for int64_t, q! for signed long long */ - integer_size = NATINT_LEN_Q; + case 'q': /* q for int64_t, q! for signed long long */ + integer_size = NATINT_LEN_Q; bigendian_p = BIGENDIAN_P(); goto pack_integer; - case 'Q': /* Q for uint64_t, Q! for unsigned long long */ - integer_size = NATINT_LEN_Q; + case 'Q': /* Q for uint64_t, Q! for unsigned long long */ + integer_size = NATINT_LEN_Q; bigendian_p = BIGENDIAN_P(); goto pack_integer; - case 'j': /* j for intptr_t */ - integer_size = sizeof(intptr_t); - bigendian_p = BIGENDIAN_P(); - goto pack_integer; + case 'j': /* j for intptr_t */ + integer_size = sizeof(intptr_t); + bigendian_p = BIGENDIAN_P(); + goto pack_integer; - case 'J': /* J for uintptr_t */ - integer_size = sizeof(uintptr_t); - bigendian_p = BIGENDIAN_P(); - goto pack_integer; + case 'J': /* J for uintptr_t */ + integer_size = sizeof(uintptr_t); + bigendian_p = BIGENDIAN_P(); + goto pack_integer; - case 'n': /* 16 bit (2 bytes) integer (network byte-order) */ + case 'n': /* 16 bit (2 bytes) integer (network byte-order) */ integer_size = 2; bigendian_p = 1; goto pack_integer; - case 'N': /* 32 bit (4 bytes) integer (network byte-order) */ + case 'N': /* 32 bit (4 bytes) integer (network byte-order) */ integer_size = 4; bigendian_p = 1; goto pack_integer; - case 'v': /* 16 bit (2 bytes) integer (VAX byte-order) */ + case 'v': /* 16 bit (2 bytes) integer (VAX byte-order) */ integer_size = 2; bigendian_p = 0; goto pack_integer; - case 'V': /* 32 bit (4 bytes) integer (VAX byte-order) */ + case 'V': /* 32 bit (4 bytes) integer (VAX byte-order) */ integer_size = 4; bigendian_p = 0; goto pack_integer; pack_integer: - if (explicit_endian) { - bigendian_p = explicit_endian == '>'; - } + if (explicit_endian) { + bigendian_p = explicit_endian == '>'; + } if (integer_size > MAX_INTEGER_PACK_SIZE) rb_bug("unexpected intger size for pack: %d", integer_size); while (len-- > 0) { @@ -560,192 +560,192 @@ pack_pack(rb_execution_context_t *ec, VALUE ary, VALUE fmt, VALUE buffer) (bigendian_p ? INTEGER_PACK_BIG_ENDIAN : INTEGER_PACK_LITTLE_ENDIAN)); rb_str_buf_cat(res, intbuf, integer_size); } - break; + break; - case 'f': /* single precision float in native format */ - case 'F': /* ditto */ - while (len-- > 0) { - float f; + case 'f': /* single precision float in native format */ + case 'F': /* ditto */ + while (len-- > 0) { + float f; - from = NEXTFROM; + from = NEXTFROM; f = VALUE_to_float(from); - rb_str_buf_cat(res, (char*)&f, sizeof(float)); - } - break; + rb_str_buf_cat(res, (char*)&f, sizeof(float)); + } + break; - case 'e': /* single precision float in VAX byte-order */ - while (len-- > 0) { - FLOAT_CONVWITH(tmp); + case 'e': /* single precision float in VAX byte-order */ + while (len-- > 0) { + FLOAT_CONVWITH(tmp); - from = NEXTFROM; + from = NEXTFROM; tmp.f = VALUE_to_float(from); - HTOVF(tmp); - rb_str_buf_cat(res, tmp.buf, sizeof(float)); - } - break; + HTOVF(tmp); + rb_str_buf_cat(res, tmp.buf, sizeof(float)); + } + break; - case 'E': /* double precision float in VAX byte-order */ - while (len-- > 0) { - DOUBLE_CONVWITH(tmp); - from = NEXTFROM; - tmp.d = RFLOAT_VALUE(rb_to_float(from)); - HTOVD(tmp); - rb_str_buf_cat(res, tmp.buf, sizeof(double)); - } - break; + case 'E': /* double precision float in VAX byte-order */ + while (len-- > 0) { + DOUBLE_CONVWITH(tmp); + from = NEXTFROM; + tmp.d = RFLOAT_VALUE(rb_to_float(from)); + HTOVD(tmp); + rb_str_buf_cat(res, tmp.buf, sizeof(double)); + } + break; - case 'd': /* double precision float in native format */ - case 'D': /* ditto */ - while (len-- > 0) { - double d; + case 'd': /* double precision float in native format */ + case 'D': /* ditto */ + while (len-- > 0) { + double d; - from = NEXTFROM; - d = RFLOAT_VALUE(rb_to_float(from)); - rb_str_buf_cat(res, (char*)&d, sizeof(double)); - } - break; + from = NEXTFROM; + d = RFLOAT_VALUE(rb_to_float(from)); + rb_str_buf_cat(res, (char*)&d, sizeof(double)); + } + break; - case 'g': /* single precision float in network byte-order */ - while (len-- > 0) { - FLOAT_CONVWITH(tmp); - from = NEXTFROM; + case 'g': /* single precision float in network byte-order */ + while (len-- > 0) { + FLOAT_CONVWITH(tmp); + from = NEXTFROM; tmp.f = VALUE_to_float(from); - HTONF(tmp); - rb_str_buf_cat(res, tmp.buf, sizeof(float)); - } - break; + HTONF(tmp); + rb_str_buf_cat(res, tmp.buf, sizeof(float)); + } + break; - case 'G': /* double precision float in network byte-order */ - while (len-- > 0) { - DOUBLE_CONVWITH(tmp); + case 'G': /* double precision float in network byte-order */ + while (len-- > 0) { + DOUBLE_CONVWITH(tmp); - from = NEXTFROM; - tmp.d = RFLOAT_VALUE(rb_to_float(from)); - HTOND(tmp); - rb_str_buf_cat(res, tmp.buf, sizeof(double)); - } - break; + from = NEXTFROM; + tmp.d = RFLOAT_VALUE(rb_to_float(from)); + HTOND(tmp); + rb_str_buf_cat(res, tmp.buf, sizeof(double)); + } + break; - case 'x': /* null byte */ - grow: - while (len >= 10) { - rb_str_buf_cat(res, nul10, 10); - len -= 10; - } - rb_str_buf_cat(res, nul10, len); - break; + case 'x': /* null byte */ + grow: + while (len >= 10) { + rb_str_buf_cat(res, nul10, 10); + len -= 10; + } + rb_str_buf_cat(res, nul10, len); + break; - case 'X': /* back up byte */ - shrink: - plen = RSTRING_LEN(res); - if (plen < len) - rb_raise(rb_eArgError, "X outside of string"); - rb_str_set_len(res, plen - len); - break; + case 'X': /* back up byte */ + shrink: + plen = RSTRING_LEN(res); + if (plen < len) + rb_raise(rb_eArgError, "X outside of string"); + rb_str_set_len(res, plen - len); + break; - case '@': /* null fill to absolute position */ - len -= RSTRING_LEN(res); - if (len > 0) goto grow; - len = -len; - if (len > 0) goto shrink; - break; + case '@': /* null fill to absolute position */ + len -= RSTRING_LEN(res); + if (len > 0) goto grow; + len = -len; + if (len > 0) goto shrink; + break; - case '%': - rb_raise(rb_eArgError, "%% is not supported"); - break; + case '%': + rb_raise(rb_eArgError, "%% is not supported"); + break; - case 'U': /* Unicode character */ - while (len-- > 0) { - SIGNED_VALUE l; - char buf[8]; - int le; + case 'U': /* Unicode character */ + while (len-- > 0) { + SIGNED_VALUE l; + char buf[8]; + int le; - from = NEXTFROM; - from = rb_to_int(from); - l = NUM2LONG(from); - if (l < 0) { - rb_raise(rb_eRangeError, "pack(U): value out of range"); - } - le = rb_uv_to_utf8(buf, l); - rb_str_buf_cat(res, (char*)buf, le); - } - break; + from = NEXTFROM; + from = rb_to_int(from); + l = NUM2LONG(from); + if (l < 0) { + rb_raise(rb_eRangeError, "pack(U): value out of range"); + } + le = rb_uv_to_utf8(buf, l); + rb_str_buf_cat(res, (char*)buf, le); + } + break; - case 'u': /* uuencoded string */ - case 'm': /* base64 encoded string */ - from = NEXTFROM; - StringValue(from); - ptr = RSTRING_PTR(from); - plen = RSTRING_LEN(from); + case 'u': /* uuencoded string */ + case 'm': /* base64 encoded string */ + from = NEXTFROM; + StringValue(from); + ptr = RSTRING_PTR(from); + plen = RSTRING_LEN(from); - if (len == 0 && type == 'm') { - encodes(res, ptr, plen, type, 0); - ptr += plen; - break; - } - if (len <= 2) - len = 45; - else if (len > 63 && type == 'u') - len = 63; - else - len = len / 3 * 3; - while (plen > 0) { - long todo; + if (len == 0 && type == 'm') { + encodes(res, ptr, plen, type, 0); + ptr += plen; + break; + } + if (len <= 2) + len = 45; + else if (len > 63 && type == 'u') + len = 63; + else + len = len / 3 * 3; + while (plen > 0) { + long todo; - if (plen > len) - todo = len; - else - todo = plen; - encodes(res, ptr, todo, type, 1); - plen -= todo; - ptr += todo; - } - break; + if (plen > len) + todo = len; + else + todo = plen; + encodes(res, ptr, todo, type, 1); + plen -= todo; + ptr += todo; + } + break; - case 'M': /* quoted-printable encoded string */ - from = rb_obj_as_string(NEXTFROM); - if (len <= 1) - len = 72; - qpencode(res, from, len); - break; + case 'M': /* quoted-printable encoded string */ + from = rb_obj_as_string(NEXTFROM); + if (len <= 1) + len = 72; + qpencode(res, from, len); + break; - case 'P': /* pointer to packed byte string */ - from = THISFROM; - if (!NIL_P(from)) { - StringValue(from); - if (RSTRING_LEN(from) < len) { - rb_raise(rb_eArgError, "too short buffer for P(%ld for %ld)", - RSTRING_LEN(from), len); - } - } - len = 1; - /* FALL THROUGH */ - case 'p': /* pointer to string */ - while (len-- > 0) { - char *t; - from = NEXTFROM; - if (NIL_P(from)) { - t = 0; - } - else { - t = StringValuePtr(from); - } - if (!associates) { - associates = rb_ary_new(); - } - rb_ary_push(associates, from); - rb_str_buf_cat(res, (char*)&t, sizeof(char*)); - } - break; + case 'P': /* pointer to packed byte string */ + from = THISFROM; + if (!NIL_P(from)) { + StringValue(from); + if (RSTRING_LEN(from) < len) { + rb_raise(rb_eArgError, "too short buffer for P(%ld for %ld)", + RSTRING_LEN(from), len); + } + } + len = 1; + /* FALL THROUGH */ + case 'p': /* pointer to string */ + while (len-- > 0) { + char *t; + from = NEXTFROM; + if (NIL_P(from)) { + t = 0; + } + else { + t = StringValuePtr(from); + } + if (!associates) { + associates = rb_ary_new(); + } + rb_ary_push(associates, from); + rb_str_buf_cat(res, (char*)&t, sizeof(char*)); + } + break; - case 'w': /* BER compressed integer */ - while (len-- > 0) { - VALUE buf = rb_str_new(0, 0); + case 'w': /* BER compressed integer */ + while (len-- > 0) { + VALUE buf = rb_str_new(0, 0); size_t numbytes; int sign; char *cp; - from = NEXTFROM; + from = NEXTFROM; from = rb_to_int(from); numbytes = rb_absint_numwords(from, 7, NULL); if (numbytes == 0) @@ -767,29 +767,29 @@ pack_pack(rb_execution_context_t *ec, VALUE ary, VALUE fmt, VALUE buffer) } rb_str_buf_cat(res, RSTRING_PTR(buf), RSTRING_LEN(buf)); - } - break; + } + break; - default: { + default: { unknown_directive("pack", type, fmt); - break; - } - } + break; + } + } } if (associates) { - str_associate(res, associates); + str_associate(res, associates); } switch (enc_info) { case 1: - ENCODING_CODERANGE_SET(res, rb_usascii_encindex(), ENC_CODERANGE_7BIT); - break; + ENCODING_CODERANGE_SET(res, rb_usascii_encindex(), ENC_CODERANGE_7BIT); + break; case 2: - rb_enc_set_index(res, rb_utf8_encindex()); - break; + rb_enc_set_index(res, rb_utf8_encindex()); + break; default: - /* do nothing, keep ASCII-8BIT */ - break; + /* do nothing, keep ASCII-8BIT */ + break; } return res; } @@ -810,11 +810,11 @@ encodes(VALUE str, const char *s0, long len, int type, int tail_lf) const unsigned char *s = (const unsigned char *)s0; if (type == 'u') { - buff[i++] = (char)len + ' '; - padding = '`'; + buff[i++] = (char)len + ' '; + padding = '`'; } else { - padding = '='; + padding = '='; } while (len >= input_unit) { while (len >= input_unit && buff_size-i >= encoded_unit) { @@ -832,16 +832,16 @@ encodes(VALUE str, const char *s0, long len, int type, int tail_lf) } if (len == 2) { - buff[i++] = trans[077 & (*s >> 2)]; - buff[i++] = trans[077 & (((*s << 4) & 060) | ((s[1] >> 4) & 017))]; - buff[i++] = trans[077 & (((s[1] << 2) & 074) | (('\0' >> 6) & 03))]; - buff[i++] = padding; + buff[i++] = trans[077 & (*s >> 2)]; + buff[i++] = trans[077 & (((*s << 4) & 060) | ((s[1] >> 4) & 017))]; + buff[i++] = trans[077 & (((s[1] << 2) & 074) | (('\0' >> 6) & 03))]; + buff[i++] = padding; } else if (len == 1) { - buff[i++] = trans[077 & (*s >> 2)]; - buff[i++] = trans[077 & (((*s << 4) & 060) | (('\0' >> 4) & 017))]; - buff[i++] = padding; - buff[i++] = padding; + buff[i++] = trans[077 & (*s >> 2)]; + buff[i++] = trans[077 & (((*s << 4) & 060) | (('\0' >> 4) & 017))]; + buff[i++] = padding; + buff[i++] = padding; } if (tail_lf) buff[i++] = '\n'; rb_str_buf_cat(str, buff, i); @@ -860,46 +860,46 @@ qpencode(VALUE str, VALUE from, long len) while (s < send) { if ((*s > 126) || - (*s < 32 && *s != '\n' && *s != '\t') || - (*s == '=')) { - buff[i++] = '='; - buff[i++] = hex_table[*s >> 4]; - buff[i++] = hex_table[*s & 0x0f]; + (*s < 32 && *s != '\n' && *s != '\t') || + (*s == '=')) { + buff[i++] = '='; + buff[i++] = hex_table[*s >> 4]; + buff[i++] = hex_table[*s & 0x0f]; n += 3; prev = EOF; } - else if (*s == '\n') { + else if (*s == '\n') { if (prev == ' ' || prev == '\t') { - buff[i++] = '='; - buff[i++] = *s; + buff[i++] = '='; + buff[i++] = *s; } - buff[i++] = *s; + buff[i++] = *s; n = 0; prev = *s; } - else { - buff[i++] = *s; + else { + buff[i++] = *s; n++; prev = *s; } if (n > len) { - buff[i++] = '='; - buff[i++] = '\n'; + buff[i++] = '='; + buff[i++] = '\n'; n = 0; prev = '\n'; } - if (i > 1024 - 5) { - rb_str_buf_cat(str, buff, i); - i = 0; - } - s++; + if (i > 1024 - 5) { + rb_str_buf_cat(str, buff, i); + i = 0; + } + s++; } if (n > 0) { - buff[i++] = '='; - buff[i++] = '\n'; + buff[i++] = '='; + buff[i++] = '\n'; } if (i > 0) { - rb_str_buf_cat(str, buff, i); + rb_str_buf_cat(str, buff, i); } } @@ -917,15 +917,15 @@ hex2num(char c) tmp_len = 0; \ if (len > (long)((send-s)/(sz))) { \ if (!star) { \ - tmp_len = len-(send-s)/(sz); \ + tmp_len = len-(send-s)/(sz); \ } \ - len = (send-s)/(sz); \ + len = (send-s)/(sz); \ } \ } while (0) #define PACK_ITEM_ADJUST() do { \ if (tmp_len > 0 && mode == UNPACK_ARRAY) \ - rb_ary_store(ary, RARRAY_LEN(ary)+tmp_len-1, Qnil); \ + rb_ary_store(ary, RARRAY_LEN(ary)+tmp_len-1, Qnil); \ } while (0) /* Workaround for Oracle Developer Studio (Oracle Solaris Studio) @@ -959,16 +959,16 @@ pack_unpack_internal(VALUE str, VALUE fmt, int mode, long offset) #endif int signed_p, integer_size, bigendian_p; #define UNPACK_PUSH(item) do {\ - VALUE item_val = (item);\ - if ((mode) == UNPACK_BLOCK) {\ - rb_yield(item_val);\ - }\ - else if ((mode) == UNPACK_ARRAY) {\ - rb_ary_push(ary, item_val);\ - }\ - else /* if ((mode) == UNPACK_1) { */ {\ - return item_val; \ - }\ + VALUE item_val = (item);\ + if ((mode) == UNPACK_BLOCK) {\ + rb_yield(item_val);\ + }\ + else if ((mode) == UNPACK_ARRAY) {\ + rb_ary_push(ary, item_val);\ + }\ + else /* if ((mode) == UNPACK_1) { */ {\ + return item_val; \ + }\ } while (0) StringValue(str); @@ -989,295 +989,295 @@ pack_unpack_internal(VALUE str, VALUE fmt, int mode, long offset) ary = mode == UNPACK_ARRAY ? rb_ary_new() : Qnil; while (p < pend) { - int explicit_endian = 0; - type = *p++; + int explicit_endian = 0; + type = *p++; #ifdef NATINT_PACK - natint = 0; + natint = 0; #endif - if (ISSPACE(type)) continue; - if (type == '#') { - while ((p < pend) && (*p != '\n')) { - p++; - } - continue; - } + if (ISSPACE(type)) continue; + if (type == '#') { + while ((p < pend) && (*p != '\n')) { + p++; + } + continue; + } - star = 0; - { + star = 0; + { modifiers: - switch (*p) { - case '_': - case '!': + switch (*p) { + case '_': + case '!': - if (strchr(natstr, type)) { + if (strchr(natstr, type)) { #ifdef NATINT_PACK - natint = 1; + natint = 1; #endif - p++; - } - else { - rb_raise(rb_eArgError, "'%c' allowed only after types %s", *p, natstr); - } - goto modifiers; + p++; + } + else { + rb_raise(rb_eArgError, "'%c' allowed only after types %s", *p, natstr); + } + goto modifiers; - case '<': - case '>': - if (!strchr(endstr, type)) { - rb_raise(rb_eArgError, "'%c' allowed only after types %s", *p, endstr); - } - if (explicit_endian) { - rb_raise(rb_eRangeError, "Can't use both '<' and '>'"); - } - explicit_endian = *p++; - goto modifiers; - } - } + case '<': + case '>': + if (!strchr(endstr, type)) { + rb_raise(rb_eArgError, "'%c' allowed only after types %s", *p, endstr); + } + if (explicit_endian) { + rb_raise(rb_eRangeError, "Can't use both '<' and '>'"); + } + explicit_endian = *p++; + goto modifiers; + } + } - if (p >= pend) - len = 1; - else if (*p == '*') { - star = 1; - len = send - s; - p++; - } - else if (ISDIGIT(*p)) { - errno = 0; - len = STRTOUL(p, (char**)&p, 10); - if (len < 0 || errno) { - rb_raise(rb_eRangeError, "pack length too big"); - } - } - else { - len = (type != '@'); - } + if (p >= pend) + len = 1; + else if (*p == '*') { + star = 1; + len = send - s; + p++; + } + else if (ISDIGIT(*p)) { + errno = 0; + len = STRTOUL(p, (char**)&p, 10); + if (len < 0 || errno) { + rb_raise(rb_eRangeError, "pack length too big"); + } + } + else { + len = (type != '@'); + } - switch (type) { - case '%': - rb_raise(rb_eArgError, "%% is not supported"); - break; + switch (type) { + case '%': + rb_raise(rb_eArgError, "%% is not supported"); + break; - case 'A': - if (len > send - s) len = send - s; - { - long end = len; - char *t = s + len - 1; + case 'A': + if (len > send - s) len = send - s; + { + long end = len; + char *t = s + len - 1; - while (t >= s) { - if (*t != ' ' && *t != '\0') break; - t--; len--; - } + while (t >= s) { + if (*t != ' ' && *t != '\0') break; + t--; len--; + } UNPACK_PUSH(rb_str_new(s, len)); - s += end; - } - break; + s += end; + } + break; - case 'Z': - { - char *t = s; + case 'Z': + { + char *t = s; - if (len > send-s) len = send-s; - while (t < s+len && *t) t++; + if (len > send-s) len = send-s; + while (t < s+len && *t) t++; UNPACK_PUSH(rb_str_new(s, t-s)); - if (t < send) t++; - s = star ? t : s+len; - } - break; + if (t < send) t++; + s = star ? t : s+len; + } + break; - case 'a': - if (len > send - s) len = send - s; + case 'a': + if (len > send - s) len = send - s; UNPACK_PUSH(rb_str_new(s, len)); - s += len; - break; + s += len; + break; - case 'b': - { - VALUE bitstr; - char *t; - int bits; - long i; + case 'b': + { + VALUE bitstr; + char *t; + int bits; + long i; - if (p[-1] == '*' || len > (send - s) * 8) - len = (send - s) * 8; - bits = 0; - bitstr = rb_usascii_str_new(0, len); - t = RSTRING_PTR(bitstr); - for (i=0; i>= 1; - else bits = (unsigned char)*s++; - *t++ = (bits & 1) ? '1' : '0'; - } - UNPACK_PUSH(bitstr); - } - break; + if (p[-1] == '*' || len > (send - s) * 8) + len = (send - s) * 8; + bits = 0; + bitstr = rb_usascii_str_new(0, len); + t = RSTRING_PTR(bitstr); + for (i=0; i>= 1; + else bits = (unsigned char)*s++; + *t++ = (bits & 1) ? '1' : '0'; + } + UNPACK_PUSH(bitstr); + } + break; - case 'B': - { - VALUE bitstr; - char *t; - int bits; - long i; + case 'B': + { + VALUE bitstr; + char *t; + int bits; + long i; - if (p[-1] == '*' || len > (send - s) * 8) - len = (send - s) * 8; - bits = 0; - bitstr = rb_usascii_str_new(0, len); - t = RSTRING_PTR(bitstr); - for (i=0; i (send - s) * 8) + len = (send - s) * 8; + bits = 0; + bitstr = rb_usascii_str_new(0, len); + t = RSTRING_PTR(bitstr); + for (i=0; i (send - s) * 2) - len = (send - s) * 2; - bits = 0; - bitstr = rb_usascii_str_new(0, len); - t = RSTRING_PTR(bitstr); - for (i=0; i>= 4; - else - bits = (unsigned char)*s++; - *t++ = hexdigits[bits & 15]; - } - UNPACK_PUSH(bitstr); - } - break; + if (p[-1] == '*' || len > (send - s) * 2) + len = (send - s) * 2; + bits = 0; + bitstr = rb_usascii_str_new(0, len); + t = RSTRING_PTR(bitstr); + for (i=0; i>= 4; + else + bits = (unsigned char)*s++; + *t++ = hexdigits[bits & 15]; + } + UNPACK_PUSH(bitstr); + } + break; - case 'H': - { - VALUE bitstr; - char *t; - int bits; - long i; + case 'H': + { + VALUE bitstr; + char *t; + int bits; + long i; - if (p[-1] == '*' || len > (send - s) * 2) - len = (send - s) * 2; - bits = 0; - bitstr = rb_usascii_str_new(0, len); - t = RSTRING_PTR(bitstr); - for (i=0; i> 4) & 15]; - } - UNPACK_PUSH(bitstr); - } - break; + if (p[-1] == '*' || len > (send - s) * 2) + len = (send - s) * 2; + bits = 0; + bitstr = rb_usascii_str_new(0, len); + t = RSTRING_PTR(bitstr); + for (i=0; i> 4) & 15]; + } + UNPACK_PUSH(bitstr); + } + break; - case 'c': - signed_p = 1; - integer_size = 1; - bigendian_p = BIGENDIAN_P(); /* not effective */ - goto unpack_integer; + case 'c': + signed_p = 1; + integer_size = 1; + bigendian_p = BIGENDIAN_P(); /* not effective */ + goto unpack_integer; - case 'C': - signed_p = 0; - integer_size = 1; - bigendian_p = BIGENDIAN_P(); /* not effective */ - goto unpack_integer; + case 'C': + signed_p = 0; + integer_size = 1; + bigendian_p = BIGENDIAN_P(); /* not effective */ + goto unpack_integer; - case 's': - signed_p = 1; - integer_size = NATINT_LEN(short, 2); - bigendian_p = BIGENDIAN_P(); - goto unpack_integer; + case 's': + signed_p = 1; + integer_size = NATINT_LEN(short, 2); + bigendian_p = BIGENDIAN_P(); + goto unpack_integer; - case 'S': - signed_p = 0; - integer_size = NATINT_LEN(short, 2); - bigendian_p = BIGENDIAN_P(); - goto unpack_integer; + case 'S': + signed_p = 0; + integer_size = NATINT_LEN(short, 2); + bigendian_p = BIGENDIAN_P(); + goto unpack_integer; - case 'i': - signed_p = 1; - integer_size = (int)sizeof(int); - bigendian_p = BIGENDIAN_P(); - goto unpack_integer; + case 'i': + signed_p = 1; + integer_size = (int)sizeof(int); + bigendian_p = BIGENDIAN_P(); + goto unpack_integer; - case 'I': - signed_p = 0; - integer_size = (int)sizeof(int); - bigendian_p = BIGENDIAN_P(); - goto unpack_integer; + case 'I': + signed_p = 0; + integer_size = (int)sizeof(int); + bigendian_p = BIGENDIAN_P(); + goto unpack_integer; - case 'l': - signed_p = 1; - integer_size = NATINT_LEN(long, 4); - bigendian_p = BIGENDIAN_P(); - goto unpack_integer; + case 'l': + signed_p = 1; + integer_size = NATINT_LEN(long, 4); + bigendian_p = BIGENDIAN_P(); + goto unpack_integer; - case 'L': - signed_p = 0; - integer_size = NATINT_LEN(long, 4); - bigendian_p = BIGENDIAN_P(); - goto unpack_integer; + case 'L': + signed_p = 0; + integer_size = NATINT_LEN(long, 4); + bigendian_p = BIGENDIAN_P(); + goto unpack_integer; - case 'q': - signed_p = 1; - integer_size = NATINT_LEN_Q; - bigendian_p = BIGENDIAN_P(); - goto unpack_integer; + case 'q': + signed_p = 1; + integer_size = NATINT_LEN_Q; + bigendian_p = BIGENDIAN_P(); + goto unpack_integer; - case 'Q': - signed_p = 0; - integer_size = NATINT_LEN_Q; - bigendian_p = BIGENDIAN_P(); - goto unpack_integer; + case 'Q': + signed_p = 0; + integer_size = NATINT_LEN_Q; + bigendian_p = BIGENDIAN_P(); + goto unpack_integer; - case 'j': - signed_p = 1; - integer_size = sizeof(intptr_t); - bigendian_p = BIGENDIAN_P(); - goto unpack_integer; + case 'j': + signed_p = 1; + integer_size = sizeof(intptr_t); + bigendian_p = BIGENDIAN_P(); + goto unpack_integer; - case 'J': - signed_p = 0; - integer_size = sizeof(uintptr_t); - bigendian_p = BIGENDIAN_P(); - goto unpack_integer; + case 'J': + signed_p = 0; + integer_size = sizeof(uintptr_t); + bigendian_p = BIGENDIAN_P(); + goto unpack_integer; - case 'n': - signed_p = 0; - integer_size = 2; - bigendian_p = 1; - goto unpack_integer; + case 'n': + signed_p = 0; + integer_size = 2; + bigendian_p = 1; + goto unpack_integer; - case 'N': - signed_p = 0; - integer_size = 4; - bigendian_p = 1; - goto unpack_integer; + case 'N': + signed_p = 0; + integer_size = 4; + bigendian_p = 1; + goto unpack_integer; - case 'v': - signed_p = 0; - integer_size = 2; - bigendian_p = 0; - goto unpack_integer; + case 'v': + signed_p = 0; + integer_size = 2; + bigendian_p = 0; + goto unpack_integer; - case 'V': - signed_p = 0; - integer_size = 4; - bigendian_p = 0; - goto unpack_integer; + case 'V': + signed_p = 0; + integer_size = 4; + bigendian_p = 0; + goto unpack_integer; - unpack_integer: - if (explicit_endian) { - bigendian_p = explicit_endian == '>'; - } + unpack_integer: + if (explicit_endian) { + bigendian_p = explicit_endian == '>'; + } PACK_LENGTH_ADJUST_SIZE(integer_size); while (len-- > 0) { int flags = bigendian_p ? INTEGER_PACK_BIG_ENDIAN : INTEGER_PACK_LITTLE_ENDIAN; @@ -1291,311 +1291,311 @@ pack_unpack_internal(VALUE str, VALUE fmt, int mode, long offset) PACK_ITEM_ADJUST(); break; - case 'f': - case 'F': - PACK_LENGTH_ADJUST_SIZE(sizeof(float)); - while (len-- > 0) { - float tmp; - UNPACK_FETCH(&tmp, float); - UNPACK_PUSH(DBL2NUM((double)tmp)); - } - PACK_ITEM_ADJUST(); - break; + case 'f': + case 'F': + PACK_LENGTH_ADJUST_SIZE(sizeof(float)); + while (len-- > 0) { + float tmp; + UNPACK_FETCH(&tmp, float); + UNPACK_PUSH(DBL2NUM((double)tmp)); + } + PACK_ITEM_ADJUST(); + break; - case 'e': - PACK_LENGTH_ADJUST_SIZE(sizeof(float)); - while (len-- > 0) { - FLOAT_CONVWITH(tmp); - UNPACK_FETCH(tmp.buf, float); - VTOHF(tmp); - UNPACK_PUSH(DBL2NUM(tmp.f)); - } - PACK_ITEM_ADJUST(); - break; + case 'e': + PACK_LENGTH_ADJUST_SIZE(sizeof(float)); + while (len-- > 0) { + FLOAT_CONVWITH(tmp); + UNPACK_FETCH(tmp.buf, float); + VTOHF(tmp); + UNPACK_PUSH(DBL2NUM(tmp.f)); + } + PACK_ITEM_ADJUST(); + break; - case 'E': - PACK_LENGTH_ADJUST_SIZE(sizeof(double)); - while (len-- > 0) { - DOUBLE_CONVWITH(tmp); - UNPACK_FETCH(tmp.buf, double); - VTOHD(tmp); - UNPACK_PUSH(DBL2NUM(tmp.d)); - } - PACK_ITEM_ADJUST(); - break; + case 'E': + PACK_LENGTH_ADJUST_SIZE(sizeof(double)); + while (len-- > 0) { + DOUBLE_CONVWITH(tmp); + UNPACK_FETCH(tmp.buf, double); + VTOHD(tmp); + UNPACK_PUSH(DBL2NUM(tmp.d)); + } + PACK_ITEM_ADJUST(); + break; - case 'D': - case 'd': - PACK_LENGTH_ADJUST_SIZE(sizeof(double)); - while (len-- > 0) { - double tmp; - UNPACK_FETCH(&tmp, double); - UNPACK_PUSH(DBL2NUM(tmp)); - } - PACK_ITEM_ADJUST(); - break; + case 'D': + case 'd': + PACK_LENGTH_ADJUST_SIZE(sizeof(double)); + while (len-- > 0) { + double tmp; + UNPACK_FETCH(&tmp, double); + UNPACK_PUSH(DBL2NUM(tmp)); + } + PACK_ITEM_ADJUST(); + break; - case 'g': - PACK_LENGTH_ADJUST_SIZE(sizeof(float)); - while (len-- > 0) { - FLOAT_CONVWITH(tmp); - UNPACK_FETCH(tmp.buf, float); - NTOHF(tmp); - UNPACK_PUSH(DBL2NUM(tmp.f)); - } - PACK_ITEM_ADJUST(); - break; + case 'g': + PACK_LENGTH_ADJUST_SIZE(sizeof(float)); + while (len-- > 0) { + FLOAT_CONVWITH(tmp); + UNPACK_FETCH(tmp.buf, float); + NTOHF(tmp); + UNPACK_PUSH(DBL2NUM(tmp.f)); + } + PACK_ITEM_ADJUST(); + break; - case 'G': - PACK_LENGTH_ADJUST_SIZE(sizeof(double)); - while (len-- > 0) { - DOUBLE_CONVWITH(tmp); - UNPACK_FETCH(tmp.buf, double); - NTOHD(tmp); - UNPACK_PUSH(DBL2NUM(tmp.d)); - } - PACK_ITEM_ADJUST(); - break; + case 'G': + PACK_LENGTH_ADJUST_SIZE(sizeof(double)); + while (len-- > 0) { + DOUBLE_CONVWITH(tmp); + UNPACK_FETCH(tmp.buf, double); + NTOHD(tmp); + UNPACK_PUSH(DBL2NUM(tmp.d)); + } + PACK_ITEM_ADJUST(); + break; - case 'U': - if (len > send - s) len = send - s; - while (len > 0 && s < send) { - long alen = send - s; - unsigned long l; + case 'U': + if (len > send - s) len = send - s; + while (len > 0 && s < send) { + long alen = send - s; + unsigned long l; - l = utf8_to_uv(s, &alen); - s += alen; len--; - UNPACK_PUSH(ULONG2NUM(l)); - } - break; + l = utf8_to_uv(s, &alen); + s += alen; len--; + UNPACK_PUSH(ULONG2NUM(l)); + } + break; - case 'u': - { + case 'u': + { VALUE buf = rb_str_new(0, (send - s)*3/4); - char *ptr = RSTRING_PTR(buf); - long total = 0; + char *ptr = RSTRING_PTR(buf); + long total = 0; - while (s < send && (unsigned char)*s > ' ' && (unsigned char)*s < 'a') { - long a,b,c,d; - char hunk[3]; + while (s < send && (unsigned char)*s > ' ' && (unsigned char)*s < 'a') { + long a,b,c,d; + char hunk[3]; - len = ((unsigned char)*s++ - ' ') & 077; + len = ((unsigned char)*s++ - ' ') & 077; - total += len; - if (total > RSTRING_LEN(buf)) { - len -= total - RSTRING_LEN(buf); - total = RSTRING_LEN(buf); - } + total += len; + if (total > RSTRING_LEN(buf)) { + len -= total - RSTRING_LEN(buf); + total = RSTRING_LEN(buf); + } - while (len > 0) { - long mlen = len > 3 ? 3 : len; + while (len > 0) { + long mlen = len > 3 ? 3 : len; - if (s < send && (unsigned char)*s >= ' ' && (unsigned char)*s < 'a') - a = ((unsigned char)*s++ - ' ') & 077; - else - a = 0; - if (s < send && (unsigned char)*s >= ' ' && (unsigned char)*s < 'a') - b = ((unsigned char)*s++ - ' ') & 077; - else - b = 0; - if (s < send && (unsigned char)*s >= ' ' && (unsigned char)*s < 'a') - c = ((unsigned char)*s++ - ' ') & 077; - else - c = 0; - if (s < send && (unsigned char)*s >= ' ' && (unsigned char)*s < 'a') - d = ((unsigned char)*s++ - ' ') & 077; - else - d = 0; - hunk[0] = (char)(a << 2 | b >> 4); - hunk[1] = (char)(b << 4 | c >> 2); - hunk[2] = (char)(c << 6 | d); - memcpy(ptr, hunk, mlen); - ptr += mlen; - len -= mlen; - } - if (s < send && (unsigned char)*s != '\r' && *s != '\n') - s++; /* possible checksum byte */ - if (s < send && *s == '\r') s++; - if (s < send && *s == '\n') s++; - } + if (s < send && (unsigned char)*s >= ' ' && (unsigned char)*s < 'a') + a = ((unsigned char)*s++ - ' ') & 077; + else + a = 0; + if (s < send && (unsigned char)*s >= ' ' && (unsigned char)*s < 'a') + b = ((unsigned char)*s++ - ' ') & 077; + else + b = 0; + if (s < send && (unsigned char)*s >= ' ' && (unsigned char)*s < 'a') + c = ((unsigned char)*s++ - ' ') & 077; + else + c = 0; + if (s < send && (unsigned char)*s >= ' ' && (unsigned char)*s < 'a') + d = ((unsigned char)*s++ - ' ') & 077; + else + d = 0; + hunk[0] = (char)(a << 2 | b >> 4); + hunk[1] = (char)(b << 4 | c >> 2); + hunk[2] = (char)(c << 6 | d); + memcpy(ptr, hunk, mlen); + ptr += mlen; + len -= mlen; + } + if (s < send && (unsigned char)*s != '\r' && *s != '\n') + s++; /* possible checksum byte */ + if (s < send && *s == '\r') s++; + if (s < send && *s == '\n') s++; + } - rb_str_set_len(buf, total); - UNPACK_PUSH(buf); - } - break; + rb_str_set_len(buf, total); + UNPACK_PUSH(buf); + } + break; - case 'm': - { + case 'm': + { VALUE buf = rb_str_new(0, (send - s + 3)*3/4); /* +3 is for skipping paddings */ - char *ptr = RSTRING_PTR(buf); - int a = -1,b = -1,c = 0,d = 0; - static signed char b64_xtable[256]; + char *ptr = RSTRING_PTR(buf); + int a = -1,b = -1,c = 0,d = 0; + static signed char b64_xtable[256]; - if (b64_xtable['/'] <= 0) { - int i; + if (b64_xtable['/'] <= 0) { + int i; - for (i = 0; i < 256; i++) { - b64_xtable[i] = -1; - } - for (i = 0; i < 64; i++) { - b64_xtable[(unsigned char)b64_table[i]] = (char)i; - } - } - if (len == 0) { - while (s < send) { - a = b = c = d = -1; - a = b64_xtable[(unsigned char)*s++]; - if (s >= send || a == -1) rb_raise(rb_eArgError, "invalid base64"); - b = b64_xtable[(unsigned char)*s++]; - if (s >= send || b == -1) rb_raise(rb_eArgError, "invalid base64"); - if (*s == '=') { - if (s + 2 == send && *(s + 1) == '=') break; - rb_raise(rb_eArgError, "invalid base64"); - } - c = b64_xtable[(unsigned char)*s++]; - if (s >= send || c == -1) rb_raise(rb_eArgError, "invalid base64"); - if (s + 1 == send && *s == '=') break; - d = b64_xtable[(unsigned char)*s++]; - if (d == -1) rb_raise(rb_eArgError, "invalid base64"); - *ptr++ = castchar(a << 2 | b >> 4); - *ptr++ = castchar(b << 4 | c >> 2); - *ptr++ = castchar(c << 6 | d); - } - if (c == -1) { - *ptr++ = castchar(a << 2 | b >> 4); - if (b & 0xf) rb_raise(rb_eArgError, "invalid base64"); - } - else if (d == -1) { - *ptr++ = castchar(a << 2 | b >> 4); - *ptr++ = castchar(b << 4 | c >> 2); - if (c & 0x3) rb_raise(rb_eArgError, "invalid base64"); - } - } - else { - while (s < send) { - a = b = c = d = -1; - while ((a = b64_xtable[(unsigned char)*s]) == -1 && s < send) {s++;} - if (s >= send) break; - s++; - while ((b = b64_xtable[(unsigned char)*s]) == -1 && s < send) {s++;} - if (s >= send) break; - s++; - while ((c = b64_xtable[(unsigned char)*s]) == -1 && s < send) {if (*s == '=') break; s++;} - if (*s == '=' || s >= send) break; - s++; - while ((d = b64_xtable[(unsigned char)*s]) == -1 && s < send) {if (*s == '=') break; s++;} - if (*s == '=' || s >= send) break; - s++; - *ptr++ = castchar(a << 2 | b >> 4); - *ptr++ = castchar(b << 4 | c >> 2); - *ptr++ = castchar(c << 6 | d); - a = -1; - } - if (a != -1 && b != -1) { - if (c == -1) - *ptr++ = castchar(a << 2 | b >> 4); - else { - *ptr++ = castchar(a << 2 | b >> 4); - *ptr++ = castchar(b << 4 | c >> 2); - } - } - } - rb_str_set_len(buf, ptr - RSTRING_PTR(buf)); - UNPACK_PUSH(buf); - } - break; + for (i = 0; i < 256; i++) { + b64_xtable[i] = -1; + } + for (i = 0; i < 64; i++) { + b64_xtable[(unsigned char)b64_table[i]] = (char)i; + } + } + if (len == 0) { + while (s < send) { + a = b = c = d = -1; + a = b64_xtable[(unsigned char)*s++]; + if (s >= send || a == -1) rb_raise(rb_eArgError, "invalid base64"); + b = b64_xtable[(unsigned char)*s++]; + if (s >= send || b == -1) rb_raise(rb_eArgError, "invalid base64"); + if (*s == '=') { + if (s + 2 == send && *(s + 1) == '=') break; + rb_raise(rb_eArgError, "invalid base64"); + } + c = b64_xtable[(unsigned char)*s++]; + if (s >= send || c == -1) rb_raise(rb_eArgError, "invalid base64"); + if (s + 1 == send && *s == '=') break; + d = b64_xtable[(unsigned char)*s++]; + if (d == -1) rb_raise(rb_eArgError, "invalid base64"); + *ptr++ = castchar(a << 2 | b >> 4); + *ptr++ = castchar(b << 4 | c >> 2); + *ptr++ = castchar(c << 6 | d); + } + if (c == -1) { + *ptr++ = castchar(a << 2 | b >> 4); + if (b & 0xf) rb_raise(rb_eArgError, "invalid base64"); + } + else if (d == -1) { + *ptr++ = castchar(a << 2 | b >> 4); + *ptr++ = castchar(b << 4 | c >> 2); + if (c & 0x3) rb_raise(rb_eArgError, "invalid base64"); + } + } + else { + while (s < send) { + a = b = c = d = -1; + while ((a = b64_xtable[(unsigned char)*s]) == -1 && s < send) {s++;} + if (s >= send) break; + s++; + while ((b = b64_xtable[(unsigned char)*s]) == -1 && s < send) {s++;} + if (s >= send) break; + s++; + while ((c = b64_xtable[(unsigned char)*s]) == -1 && s < send) {if (*s == '=') break; s++;} + if (*s == '=' || s >= send) break; + s++; + while ((d = b64_xtable[(unsigned char)*s]) == -1 && s < send) {if (*s == '=') break; s++;} + if (*s == '=' || s >= send) break; + s++; + *ptr++ = castchar(a << 2 | b >> 4); + *ptr++ = castchar(b << 4 | c >> 2); + *ptr++ = castchar(c << 6 | d); + a = -1; + } + if (a != -1 && b != -1) { + if (c == -1) + *ptr++ = castchar(a << 2 | b >> 4); + else { + *ptr++ = castchar(a << 2 | b >> 4); + *ptr++ = castchar(b << 4 | c >> 2); + } + } + } + rb_str_set_len(buf, ptr - RSTRING_PTR(buf)); + UNPACK_PUSH(buf); + } + break; - case 'M': - { + case 'M': + { VALUE buf = rb_str_new(0, send - s); - char *ptr = RSTRING_PTR(buf), *ss = s; - int csum = 0; - int c1, c2; + char *ptr = RSTRING_PTR(buf), *ss = s; + int csum = 0; + int c1, c2; - while (s < send) { - if (*s == '=') { - if (++s == send) break; - if (s+1 < send && *s == '\r' && *(s+1) == '\n') - s++; - if (*s != '\n') { - if ((c1 = hex2num(*s)) == -1) break; - if (++s == send) break; - if ((c2 = hex2num(*s)) == -1) break; - csum |= *ptr++ = castchar(c1 << 4 | c2); - } - } - else { - csum |= *ptr++ = *s; - } - s++; - ss = s; - } - rb_str_set_len(buf, ptr - RSTRING_PTR(buf)); - rb_str_buf_cat(buf, ss, send-ss); - csum = ISASCII(csum) ? ENC_CODERANGE_7BIT : ENC_CODERANGE_VALID; - ENCODING_CODERANGE_SET(buf, rb_ascii8bit_encindex(), csum); - UNPACK_PUSH(buf); - } - break; + while (s < send) { + if (*s == '=') { + if (++s == send) break; + if (s+1 < send && *s == '\r' && *(s+1) == '\n') + s++; + if (*s != '\n') { + if ((c1 = hex2num(*s)) == -1) break; + if (++s == send) break; + if ((c2 = hex2num(*s)) == -1) break; + csum |= *ptr++ = castchar(c1 << 4 | c2); + } + } + else { + csum |= *ptr++ = *s; + } + s++; + ss = s; + } + rb_str_set_len(buf, ptr - RSTRING_PTR(buf)); + rb_str_buf_cat(buf, ss, send-ss); + csum = ISASCII(csum) ? ENC_CODERANGE_7BIT : ENC_CODERANGE_VALID; + ENCODING_CODERANGE_SET(buf, rb_ascii8bit_encindex(), csum); + UNPACK_PUSH(buf); + } + break; - case '@': - if (len > RSTRING_LEN(str)) - rb_raise(rb_eArgError, "@ outside of string"); - s = RSTRING_PTR(str) + len; - break; + case '@': + if (len > RSTRING_LEN(str)) + rb_raise(rb_eArgError, "@ outside of string"); + s = RSTRING_PTR(str) + len; + break; - case 'X': - if (len > s - RSTRING_PTR(str)) - rb_raise(rb_eArgError, "X outside of string"); - s -= len; - break; + case 'X': + if (len > s - RSTRING_PTR(str)) + rb_raise(rb_eArgError, "X outside of string"); + s -= len; + break; - case 'x': - if (len > send - s) - rb_raise(rb_eArgError, "x outside of string"); - s += len; - break; + case 'x': + if (len > send - s) + rb_raise(rb_eArgError, "x outside of string"); + s += len; + break; - case 'P': - if (sizeof(char *) <= (size_t)(send - s)) { - VALUE tmp = Qnil; - char *t; + case 'P': + if (sizeof(char *) <= (size_t)(send - s)) { + VALUE tmp = Qnil; + char *t; - UNPACK_FETCH(&t, char *); - if (t) { - if (!associates) associates = str_associated(str); - tmp = associated_pointer(associates, t); - if (len < RSTRING_LEN(tmp)) { - tmp = rb_str_new(t, len); - str_associate(tmp, associates); - } - } - UNPACK_PUSH(tmp); - } - break; + UNPACK_FETCH(&t, char *); + if (t) { + if (!associates) associates = str_associated(str); + tmp = associated_pointer(associates, t); + if (len < RSTRING_LEN(tmp)) { + tmp = rb_str_new(t, len); + str_associate(tmp, associates); + } + } + UNPACK_PUSH(tmp); + } + break; - case 'p': - if (len > (long)((send - s) / sizeof(char *))) - len = (send - s) / sizeof(char *); - while (len-- > 0) { - if ((size_t)(send - s) < sizeof(char *)) - break; - else { - VALUE tmp = Qnil; - char *t; + case 'p': + if (len > (long)((send - s) / sizeof(char *))) + len = (send - s) / sizeof(char *); + while (len-- > 0) { + if ((size_t)(send - s) < sizeof(char *)) + break; + else { + VALUE tmp = Qnil; + char *t; - UNPACK_FETCH(&t, char *); - if (t) { - if (!associates) associates = str_associated(str); - tmp = associated_pointer(associates, t); - } - UNPACK_PUSH(tmp); - } - } - break; + UNPACK_FETCH(&t, char *); + if (t) { + if (!associates) associates = str_associated(str); + tmp = associated_pointer(associates, t); + } + UNPACK_PUSH(tmp); + } + } + break; - case 'w': - { + case 'w': + { char *s0 = s; while (len > 0 && s < send) { if (*s & 0x80) { @@ -1608,13 +1608,13 @@ pack_unpack_internal(VALUE str, VALUE fmt, int mode, long offset) s0 = s; } } - } - break; + } + break; - default: + default: unknown_directive("unpack", type, fmt); - break; - } + break; + } } return ary; @@ -1637,43 +1637,43 @@ int rb_uv_to_utf8(char buf[6], unsigned long uv) { if (uv <= 0x7f) { - buf[0] = (char)uv; - return 1; + buf[0] = (char)uv; + return 1; } if (uv <= 0x7ff) { - buf[0] = castchar(((uv>>6)&0xff)|0xc0); - buf[1] = castchar((uv&0x3f)|0x80); - return 2; + buf[0] = castchar(((uv>>6)&0xff)|0xc0); + buf[1] = castchar((uv&0x3f)|0x80); + return 2; } if (uv <= 0xffff) { - buf[0] = castchar(((uv>>12)&0xff)|0xe0); - buf[1] = castchar(((uv>>6)&0x3f)|0x80); - buf[2] = castchar((uv&0x3f)|0x80); - return 3; + buf[0] = castchar(((uv>>12)&0xff)|0xe0); + buf[1] = castchar(((uv>>6)&0x3f)|0x80); + buf[2] = castchar((uv&0x3f)|0x80); + return 3; } if (uv <= 0x1fffff) { - buf[0] = castchar(((uv>>18)&0xff)|0xf0); - buf[1] = castchar(((uv>>12)&0x3f)|0x80); - buf[2] = castchar(((uv>>6)&0x3f)|0x80); - buf[3] = castchar((uv&0x3f)|0x80); - return 4; + buf[0] = castchar(((uv>>18)&0xff)|0xf0); + buf[1] = castchar(((uv>>12)&0x3f)|0x80); + buf[2] = castchar(((uv>>6)&0x3f)|0x80); + buf[3] = castchar((uv&0x3f)|0x80); + return 4; } if (uv <= 0x3ffffff) { - buf[0] = castchar(((uv>>24)&0xff)|0xf8); - buf[1] = castchar(((uv>>18)&0x3f)|0x80); - buf[2] = castchar(((uv>>12)&0x3f)|0x80); - buf[3] = castchar(((uv>>6)&0x3f)|0x80); - buf[4] = castchar((uv&0x3f)|0x80); - return 5; + buf[0] = castchar(((uv>>24)&0xff)|0xf8); + buf[1] = castchar(((uv>>18)&0x3f)|0x80); + buf[2] = castchar(((uv>>12)&0x3f)|0x80); + buf[3] = castchar(((uv>>6)&0x3f)|0x80); + buf[4] = castchar((uv&0x3f)|0x80); + return 5; } if (uv <= 0x7fffffff) { - buf[0] = castchar(((uv>>30)&0xff)|0xfc); - buf[1] = castchar(((uv>>24)&0x3f)|0x80); - buf[2] = castchar(((uv>>18)&0x3f)|0x80); - buf[3] = castchar(((uv>>12)&0x3f)|0x80); - buf[4] = castchar(((uv>>6)&0x3f)|0x80); - buf[5] = castchar((uv&0x3f)|0x80); - return 6; + buf[0] = castchar(((uv>>30)&0xff)|0xfc); + buf[1] = castchar(((uv>>24)&0x3f)|0x80); + buf[2] = castchar(((uv>>18)&0x3f)|0x80); + buf[3] = castchar(((uv>>12)&0x3f)|0x80); + buf[4] = castchar(((uv>>6)&0x3f)|0x80); + buf[5] = castchar((uv&0x3f)|0x80); + return 6; } rb_raise(rb_eRangeError, "pack(U): value out of range"); @@ -1698,12 +1698,12 @@ utf8_to_uv(const char *p, long *lenp) long n; if (!(uv & 0x80)) { - *lenp = 1; + *lenp = 1; return uv; } if (!(uv & 0x40)) { - *lenp = 1; - rb_raise(rb_eArgError, "malformed UTF-8 character"); + *lenp = 1; + rb_raise(rb_eArgError, "malformed UTF-8 character"); } if (!(uv & 0x20)) { n = 2; uv &= 0x1f; } @@ -1712,30 +1712,30 @@ utf8_to_uv(const char *p, long *lenp) else if (!(uv & 0x04)) { n = 5; uv &= 0x03; } else if (!(uv & 0x02)) { n = 6; uv &= 0x01; } else { - *lenp = 1; - rb_raise(rb_eArgError, "malformed UTF-8 character"); + *lenp = 1; + rb_raise(rb_eArgError, "malformed UTF-8 character"); } if (n > *lenp) { - rb_raise(rb_eArgError, "malformed UTF-8 character (expected %ld bytes, given %ld bytes)", - n, *lenp); + rb_raise(rb_eArgError, "malformed UTF-8 character (expected %ld bytes, given %ld bytes)", + n, *lenp); } *lenp = n--; if (n != 0) { - while (n--) { - c = *p++ & 0xff; - if ((c & 0xc0) != 0x80) { - *lenp -= n + 1; - rb_raise(rb_eArgError, "malformed UTF-8 character"); - } - else { - c &= 0x3f; - uv = uv << 6 | c; - } - } + while (n--) { + c = *p++ & 0xff; + if ((c & 0xc0) != 0x80) { + *lenp -= n + 1; + rb_raise(rb_eArgError, "malformed UTF-8 character"); + } + else { + c &= 0x3f; + uv = uv << 6 | c; + } + } } n = *lenp - 1; if (uv < utf8_limits[n]) { - rb_raise(rb_eArgError, "redundant UTF-8 sequence"); + rb_raise(rb_eArgError, "redundant UTF-8 sequence"); } return uv; } diff --git a/probes_helper.h b/probes_helper.h index d2d0ebb6e2..0003e96dd8 100644 --- a/probes_helper.h +++ b/probes_helper.h @@ -19,13 +19,13 @@ MJIT_SYMBOL_EXPORT_END #define RUBY_DTRACE_METHOD_HOOK(name, ec, klazz, id) \ do { \ if (UNLIKELY(RUBY_DTRACE_##name##_ENABLED())) { \ - struct ruby_dtrace_method_hook_args args; \ - if (rb_dtrace_setup(ec, klazz, id, &args)) { \ - RUBY_DTRACE_##name(args.classname, \ - args.methodname, \ - args.filename, \ - args.line_no); \ - } \ + struct ruby_dtrace_method_hook_args args; \ + if (rb_dtrace_setup(ec, klazz, id, &args)) { \ + RUBY_DTRACE_##name(args.classname, \ + args.methodname, \ + args.filename, \ + args.line_no); \ + } \ } \ } while (0) diff --git a/proc.c b/proc.c index 9bb02a0114..1fa21a59ec 100644 --- a/proc.c +++ b/proc.c @@ -82,21 +82,21 @@ block_mark(const struct rb_block *block) switch (vm_block_type(block)) { case block_type_iseq: case block_type_ifunc: - { - const struct rb_captured_block *captured = &block->as.captured; - RUBY_MARK_MOVABLE_UNLESS_NULL(captured->self); - RUBY_MARK_MOVABLE_UNLESS_NULL((VALUE)captured->code.val); - if (captured->ep && captured->ep[VM_ENV_DATA_INDEX_ENV] != Qundef /* cfunc_proc_t */) { + { + const struct rb_captured_block *captured = &block->as.captured; + RUBY_MARK_MOVABLE_UNLESS_NULL(captured->self); + RUBY_MARK_MOVABLE_UNLESS_NULL((VALUE)captured->code.val); + if (captured->ep && captured->ep[VM_ENV_DATA_INDEX_ENV] != Qundef /* cfunc_proc_t */) { rb_gc_mark(VM_ENV_ENVVAL(captured->ep)); - } - } - break; + } + } + break; case block_type_symbol: - RUBY_MARK_MOVABLE_UNLESS_NULL(block->as.symbol); - break; + RUBY_MARK_MOVABLE_UNLESS_NULL(block->as.symbol); + break; case block_type_proc: - RUBY_MARK_MOVABLE_UNLESS_NULL(block->as.proc); - break; + RUBY_MARK_MOVABLE_UNLESS_NULL(block->as.proc); + break; } } @@ -106,18 +106,18 @@ block_compact(struct rb_block *block) switch (block->type) { case block_type_iseq: case block_type_ifunc: - { - struct rb_captured_block *captured = &block->as.captured; + { + struct rb_captured_block *captured = &block->as.captured; captured->self = rb_gc_location(captured->self); captured->code.val = rb_gc_location(captured->code.val); - } - break; + } + break; case block_type_symbol: block->as.symbol = rb_gc_location(block->as.symbol); - break; + break; case block_type_proc: block->as.proc = rb_gc_location(block->as.proc); - break; + break; } } @@ -146,17 +146,17 @@ proc_memsize(const void *ptr) { const rb_proc_t *proc = ptr; if (proc->block.as.captured.ep == ((const cfunc_proc_t *)ptr)->env+1) - return sizeof(cfunc_proc_t); + return sizeof(cfunc_proc_t); return sizeof(rb_proc_t); } static const rb_data_type_t proc_data_type = { "proc", { - proc_mark, - RUBY_TYPED_DEFAULT_FREE, - proc_memsize, - proc_compact, + proc_mark, + RUBY_TYPED_DEFAULT_FREE, + proc_memsize, + proc_compact, }, 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED }; @@ -334,10 +334,10 @@ binding_memsize(const void *ptr) const rb_data_type_t ruby_binding_data_type = { "binding", { - binding_mark, - binding_free, - binding_memsize, - binding_compact, + binding_mark, + binding_free, + binding_memsize, + binding_compact, }, 0, 0, RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_FREE_IMMEDIATELY }; @@ -438,37 +438,37 @@ get_local_variable_ptr(const rb_env_t **envp, ID lid) { const rb_env_t *env = *envp; do { - if (!VM_ENV_FLAGS(env->ep, VM_FRAME_FLAG_CFRAME)) { + if (!VM_ENV_FLAGS(env->ep, VM_FRAME_FLAG_CFRAME)) { if (VM_ENV_FLAGS(env->ep, VM_ENV_FLAG_ISOLATED)) { return NULL; } const rb_iseq_t *iseq = env->iseq; - unsigned int i; + unsigned int i; - VM_ASSERT(rb_obj_is_iseq((VALUE)iseq)); + VM_ASSERT(rb_obj_is_iseq((VALUE)iseq)); for (i=0; ilocal_table_size; i++) { if (ISEQ_BODY(iseq)->local_table[i] == lid) { if (ISEQ_BODY(iseq)->local_iseq == iseq && ISEQ_BODY(iseq)->param.flags.has_block && (unsigned int)ISEQ_BODY(iseq)->param.block_start == i) { - const VALUE *ep = env->ep; - if (!VM_ENV_FLAGS(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM)) { - RB_OBJ_WRITE(env, &env->env[i], rb_vm_bh_to_procval(GET_EC(), VM_ENV_BLOCK_HANDLER(ep))); - VM_ENV_FLAGS_SET(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM); - } - } + const VALUE *ep = env->ep; + if (!VM_ENV_FLAGS(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM)) { + RB_OBJ_WRITE(env, &env->env[i], rb_vm_bh_to_procval(GET_EC(), VM_ENV_BLOCK_HANDLER(ep))); + VM_ENV_FLAGS_SET(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM); + } + } - *envp = env; - return &env->env[i]; - } - } - } - else { - *envp = NULL; - return NULL; - } + *envp = env; + return &env->env[i]; + } + } + } + else { + *envp = NULL; + return NULL; + } } while ((env = rb_vm_env_prev_env(env)) != NULL); *envp = NULL; @@ -487,17 +487,17 @@ check_local_id(VALUE bindval, volatile VALUE *pname) VALUE name = *pname; if (lid) { - if (!rb_is_local_id(lid)) { - rb_name_err_raise("wrong local variable name `%1$s' for %2$s", - bindval, ID2SYM(lid)); - } + if (!rb_is_local_id(lid)) { + rb_name_err_raise("wrong local variable name `%1$s' for %2$s", + bindval, ID2SYM(lid)); + } } else { - if (!rb_is_local_name(name)) { - rb_name_err_raise("wrong local variable name `%1$s' for %2$s", - bindval, name); - } - return 0; + if (!rb_is_local_name(name)) { + rb_name_err_raise("wrong local variable name `%1$s' for %2$s", + bindval, name); + } + return 0; } return lid; } @@ -610,9 +610,9 @@ bind_local_variable_set(VALUE bindval, VALUE sym, VALUE val) GetBindingPtr(bindval, bind); env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block)); if ((ptr = get_local_variable_ptr(&env, lid)) == NULL) { - /* not found. create new env */ - ptr = rb_binding_add_dynavars(bindval, bind, 1, &lid); - env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block)); + /* not found. create new env */ + ptr = rb_binding_add_dynavars(bindval, bind, 1, &lid); + env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block)); } #if YJIT_STATS @@ -727,25 +727,25 @@ struct vm_ifunc * rb_vm_ifunc_new(rb_block_call_func_t func, const void *data, int min_argc, int max_argc) { union { - struct vm_ifunc_argc argc; - VALUE packed; + struct vm_ifunc_argc argc; + VALUE packed; } arity; if (min_argc < UNLIMITED_ARGUMENTS || #if SIZEOF_INT * 2 > SIZEOF_VALUE - min_argc >= (int)(1U << (SIZEOF_VALUE * CHAR_BIT) / 2) || + min_argc >= (int)(1U << (SIZEOF_VALUE * CHAR_BIT) / 2) || #endif - 0) { - rb_raise(rb_eRangeError, "minimum argument number out of range: %d", - min_argc); + 0) { + rb_raise(rb_eRangeError, "minimum argument number out of range: %d", + min_argc); } if (max_argc < UNLIMITED_ARGUMENTS || #if SIZEOF_INT * 2 > SIZEOF_VALUE - max_argc >= (int)(1U << (SIZEOF_VALUE * CHAR_BIT) / 2) || + max_argc >= (int)(1U << (SIZEOF_VALUE * CHAR_BIT) / 2) || #endif - 0) { - rb_raise(rb_eRangeError, "maximum argument number out of range: %d", - max_argc); + 0) { + rb_raise(rb_eRangeError, "maximum argument number out of range: %d", + max_argc); } arity.argc.min = min_argc; arity.argc.max = max_argc; @@ -784,26 +784,26 @@ proc_new(VALUE klass, int8_t is_lambda, int8_t kernel) /* block is in cf */ switch (vm_block_handler_type(block_handler)) { case block_handler_type_proc: - procval = VM_BH_TO_PROC(block_handler); + procval = VM_BH_TO_PROC(block_handler); - if (RBASIC_CLASS(procval) == klass) { - return procval; - } - else { - VALUE newprocval = rb_proc_dup(procval); + if (RBASIC_CLASS(procval) == klass) { + return procval; + } + else { + VALUE newprocval = rb_proc_dup(procval); RBASIC_SET_CLASS(newprocval, klass); - return newprocval; - } - break; + return newprocval; + } + break; case block_handler_type_symbol: - return (klass != rb_cProc) ? - sym_proc_new(klass, VM_BH_TO_SYMBOL(block_handler)) : - rb_sym_to_proc(VM_BH_TO_SYMBOL(block_handler)); - break; + return (klass != rb_cProc) ? + sym_proc_new(klass, VM_BH_TO_SYMBOL(block_handler)) : + rb_sym_to_proc(VM_BH_TO_SYMBOL(block_handler)); + break; case block_handler_type_ifunc: - return rb_vm_make_proc_lambda(ec, VM_BH_TO_CAPT_BLOCK(block_handler), klass, is_lambda); + return rb_vm_make_proc_lambda(ec, VM_BH_TO_CAPT_BLOCK(block_handler), klass, is_lambda); case block_handler_type_iseq: { const struct rb_captured_block *captured = VM_BH_TO_CAPT_BLOCK(block_handler); @@ -972,8 +972,8 @@ static inline int check_argc(long argc) { if (argc > INT_MAX || argc < 0) { - rb_raise(rb_eArgError, "too many arguments (%lu)", - (unsigned long)argc); + rb_raise(rb_eArgError, "too many arguments (%lu)", + (unsigned long)argc); } return (int)argc; } @@ -1091,20 +1091,20 @@ rb_vm_block_min_max_arity(const struct rb_block *block, int *max) again: switch (vm_block_type(block)) { case block_type_iseq: - return rb_iseq_min_max_arity(rb_iseq_check(block->as.captured.code.iseq), max); + return rb_iseq_min_max_arity(rb_iseq_check(block->as.captured.code.iseq), max); case block_type_proc: - block = vm_proc_block(block->as.proc); - goto again; + block = vm_proc_block(block->as.proc); + goto again; case block_type_ifunc: - { - const struct vm_ifunc *ifunc = block->as.captured.code.ifunc; - if (IS_METHOD_PROC_IFUNC(ifunc)) { - /* e.g. method(:foo).to_proc.arity */ - return method_min_max_arity((VALUE)ifunc->data, max); - } - *max = ifunc->argc.max; - return ifunc->argc.min; - } + { + const struct vm_ifunc *ifunc = block->as.captured.code.ifunc; + if (IS_METHOD_PROC_IFUNC(ifunc)) { + /* e.g. method(:foo).to_proc.arity */ + return method_min_max_arity((VALUE)ifunc->data, max); + } + *max = ifunc->argc.max; + return ifunc->argc.min; + } case block_type_symbol: *max = UNLIMITED_ARGUMENTS; return 1; @@ -1142,20 +1142,20 @@ block_setup(struct rb_block *block, VALUE block_handler) { switch (vm_block_handler_type(block_handler)) { case block_handler_type_iseq: - block->type = block_type_iseq; - block->as.captured = *VM_BH_TO_ISEQ_BLOCK(block_handler); - break; + block->type = block_type_iseq; + block->as.captured = *VM_BH_TO_ISEQ_BLOCK(block_handler); + break; case block_handler_type_ifunc: - block->type = block_type_ifunc; - block->as.captured = *VM_BH_TO_IFUNC_BLOCK(block_handler); - break; + block->type = block_type_ifunc; + block->as.captured = *VM_BH_TO_IFUNC_BLOCK(block_handler); + break; case block_handler_type_symbol: - block->type = block_type_symbol; - block->as.symbol = VM_BH_TO_SYMBOL(block_handler); - break; + block->type = block_type_symbol; + block->as.symbol = VM_BH_TO_SYMBOL(block_handler); + break; case block_handler_type_proc: - block->type = block_type_proc; - block->as.proc = VM_BH_TO_PROC(block_handler); + block->type = block_type_proc; + block->as.proc = VM_BH_TO_PROC(block_handler); } } @@ -1169,7 +1169,7 @@ rb_block_pair_yield_optimizable(void) struct rb_block block; if (block_handler == VM_BLOCK_HANDLER_NONE) { - rb_raise(rb_eArgError, "no block given"); + rb_raise(rb_eArgError, "no block given"); } block_setup(&block, block_handler); @@ -1180,14 +1180,14 @@ rb_block_pair_yield_optimizable(void) return 0; case block_handler_type_proc: - { - VALUE procval = block_handler; - rb_proc_t *proc; - GetProcPtr(procval, proc); + { + VALUE procval = block_handler; + rb_proc_t *proc; + GetProcPtr(procval, proc); if (proc->is_lambda) return 0; if (min != max) return 0; return min > 1; - } + } default: return min > 1; @@ -1204,21 +1204,21 @@ rb_block_arity(void) struct rb_block block; if (block_handler == VM_BLOCK_HANDLER_NONE) { - rb_raise(rb_eArgError, "no block given"); + rb_raise(rb_eArgError, "no block given"); } block_setup(&block, block_handler); switch (vm_block_type(&block)) { case block_handler_type_symbol: - return -1; + return -1; case block_handler_type_proc: return rb_proc_arity(block_handler); default: min = rb_vm_block_min_max_arity(&block, &max); - return max != UNLIMITED_ARGUMENTS ? min : -min-1; + return max != UNLIMITED_ARGUMENTS ? min : -min-1; } } @@ -1231,7 +1231,7 @@ rb_block_min_max_arity(int *max) struct rb_block block; if (block_handler == VM_BLOCK_HANDLER_NONE) { - rb_raise(rb_eArgError, "no block given"); + rb_raise(rb_eArgError, "no block given"); } block_setup(&block, block_handler); @@ -1250,23 +1250,23 @@ rb_proc_get_iseq(VALUE self, int *is_proc) switch (vm_block_type(block)) { case block_type_iseq: - return rb_iseq_check(block->as.captured.code.iseq); + return rb_iseq_check(block->as.captured.code.iseq); case block_type_proc: - return rb_proc_get_iseq(block->as.proc, is_proc); + return rb_proc_get_iseq(block->as.proc, is_proc); case block_type_ifunc: - { + { const struct vm_ifunc *ifunc = block->as.captured.code.ifunc; - if (IS_METHOD_PROC_IFUNC(ifunc)) { - /* method(:foo).to_proc */ - if (is_proc) *is_proc = 0; - return rb_method_iseq((VALUE)ifunc->data); - } - else { - return NULL; - } - } + if (IS_METHOD_PROC_IFUNC(ifunc)) { + /* method(:foo).to_proc */ + if (is_proc) *is_proc = 0; + return rb_method_iseq((VALUE)ifunc->data); + } + else { + return NULL; + } + } case block_type_symbol: - return NULL; + return NULL; } VM_UNREACHABLE(rb_proc_get_iseq); @@ -1399,11 +1399,11 @@ rb_unnamed_parameters(int arity) a = rb_ary_new3(1, ID2SYM(req)); OBJ_FREEZE(a); for (; n; --n) { - rb_ary_push(param, a); + rb_ary_push(param, a); } if (arity < 0) { - CONST_ID(rest, "rest"); - rb_ary_store(param, ~arity, rb_ary_new3(1, ID2SYM(rest))); + CONST_ID(rest, "rest"); + rb_ary_store(param, ~arity, rb_ary_new3(1, ID2SYM(rest))); } return param; } @@ -1451,7 +1451,7 @@ rb_proc_parameters(int argc, VALUE *argv, VALUE self) } if (!iseq) { - return rb_unnamed_parameters(rb_proc_arity(self)); + return rb_unnamed_parameters(rb_proc_arity(self)); } return rb_iseq_parameters(iseq, is_proc); } @@ -1491,9 +1491,9 @@ rb_sym_to_proc(VALUE sym) ID id; if (!sym_proc_cache) { - sym_proc_cache = rb_ary_tmp_new(SYM_PROC_CACHE_SIZE * 2); - rb_gc_register_mark_object(sym_proc_cache); - rb_ary_store(sym_proc_cache, SYM_PROC_CACHE_SIZE*2 - 1, Qnil); + sym_proc_cache = rb_ary_tmp_new(SYM_PROC_CACHE_SIZE * 2); + rb_gc_register_mark_object(sym_proc_cache); + rb_ary_store(sym_proc_cache, SYM_PROC_CACHE_SIZE*2 - 1, Qnil); } id = SYM2ID(sym); @@ -1506,7 +1506,7 @@ rb_sym_to_proc(VALUE sym) proc = sym_proc_new(rb_cProc, ID2SYM(id)); RARRAY_ASET(sym_proc_cache, index, sym); RARRAY_ASET(sym_proc_cache, index + 1, proc); - return proc; + return proc; } } @@ -1538,22 +1538,22 @@ rb_block_to_s(VALUE self, const struct rb_block *block, const char *additional_i again: switch (vm_block_type(block)) { case block_type_proc: - block = vm_proc_block(block->as.proc); - goto again; + block = vm_proc_block(block->as.proc); + goto again; case block_type_iseq: - { - const rb_iseq_t *iseq = rb_iseq_check(block->as.captured.code.iseq); + { + const rb_iseq_t *iseq = rb_iseq_check(block->as.captured.code.iseq); rb_str_catf(str, "%p %"PRIsVALUE":%d", (void *)self, - rb_iseq_path(iseq), + rb_iseq_path(iseq), FIX2INT(ISEQ_BODY(iseq)->location.first_lineno)); - } - break; + } + break; case block_type_symbol: - rb_str_catf(str, "%p(&%+"PRIsVALUE")", (void *)self, block->as.symbol); - break; + rb_str_catf(str, "%p(&%+"PRIsVALUE")", (void *)self, block->as.symbol); + break; case block_type_ifunc: - rb_str_catf(str, "%p", (void *)block->as.captured.code.ifunc); - break; + rb_str_catf(str, "%p", (void *)block->as.captured.code.ifunc); + break; } if (additional_info) rb_str_cat_cstr(str, additional_info); @@ -1620,10 +1620,10 @@ bm_memsize(const void *ptr) static const rb_data_type_t method_data_type = { "method", { - bm_mark, - RUBY_TYPED_DEFAULT_FREE, - bm_memsize, - bm_compact, + bm_mark, + RUBY_TYPED_DEFAULT_FREE, + bm_memsize, + bm_compact, }, 0, 0, RUBY_TYPED_FREE_IMMEDIATELY }; @@ -1680,7 +1680,7 @@ mnew_missing_by_name(VALUE klass, VALUE obj, VALUE *name, int scope, VALUE mclas static VALUE mnew_internal(const rb_method_entry_t *me, VALUE klass, VALUE iclass, - VALUE obj, ID id, VALUE mclass, int scope, int error) + VALUE obj, ID id, VALUE mclass, int scope, int error) { struct METHOD *data; VALUE method; @@ -1688,32 +1688,32 @@ mnew_internal(const rb_method_entry_t *me, VALUE klass, VALUE iclass, again: if (UNDEFINED_METHOD_ENTRY_P(me)) { - if (respond_to_missing_p(klass, obj, ID2SYM(id), scope)) { - return mnew_missing(klass, obj, id, mclass); - } - if (!error) return Qnil; - rb_print_undef(klass, id, METHOD_VISI_UNDEF); + if (respond_to_missing_p(klass, obj, ID2SYM(id), scope)) { + return mnew_missing(klass, obj, id, mclass); + } + if (!error) return Qnil; + rb_print_undef(klass, id, METHOD_VISI_UNDEF); } if (visi == METHOD_VISI_UNDEF) { - visi = METHOD_ENTRY_VISI(me); - RUBY_ASSERT(visi != METHOD_VISI_UNDEF); /* !UNDEFINED_METHOD_ENTRY_P(me) */ - if (scope && (visi != METHOD_VISI_PUBLIC)) { - if (!error) return Qnil; - rb_print_inaccessible(klass, id, visi); - } + visi = METHOD_ENTRY_VISI(me); + RUBY_ASSERT(visi != METHOD_VISI_UNDEF); /* !UNDEFINED_METHOD_ENTRY_P(me) */ + if (scope && (visi != METHOD_VISI_PUBLIC)) { + if (!error) return Qnil; + rb_print_inaccessible(klass, id, visi); + } } if (me->def->type == VM_METHOD_TYPE_ZSUPER) { - if (me->defined_class) { + if (me->defined_class) { VALUE klass = RCLASS_SUPER(RCLASS_ORIGIN(me->defined_class)); - id = me->def->original_id; + id = me->def->original_id; me = (rb_method_entry_t *)rb_callable_method_entry_with_refinements(klass, id, &iclass); - } - else { + } + else { VALUE klass = RCLASS_SUPER(RCLASS_ORIGIN(me->owner)); - id = me->def->original_id; - me = rb_method_entry_without_refinements(klass, id, &iclass); - } - goto again; + id = me->def->original_id; + me = rb_method_entry_without_refinements(klass, id, &iclass); + } + goto again; } method = TypedData_Make_Struct(mclass, struct METHOD, &method_data_type, data); @@ -1729,7 +1729,7 @@ mnew_internal(const rb_method_entry_t *me, VALUE klass, VALUE iclass, static VALUE mnew_from_me(const rb_method_entry_t *me, VALUE klass, VALUE iclass, - VALUE obj, ID id, VALUE mclass, int scope) + VALUE obj, ID id, VALUE mclass, int scope) { return mnew_internal(me, klass, iclass, obj, id, mclass, scope, TRUE); } @@ -1807,9 +1807,9 @@ method_eq(VALUE method, VALUE other) VALUE klass1, klass2; if (!rb_obj_is_method(other)) - return Qfalse; + return Qfalse; if (CLASS_OF(method) != CLASS_OF(other)) - return Qfalse; + return Qfalse; Check_TypedStruct(method, &method_data_type); m1 = (struct METHOD *)DATA_PTR(method); @@ -1819,11 +1819,11 @@ method_eq(VALUE method, VALUE other) klass2 = method_entry_defined_class(m2->me); if (!rb_method_entry_eq(m1->me, m2->me) || - klass1 != klass2 || + klass1 != klass2 || m1->visibility != m2->visibility || - m1->klass != m2->klass || - m1->recv != m2->recv) { - return Qfalse; + m1->klass != m2->klass || + m1->recv != m2->recv) { + return Qfalse; } return Qtrue; @@ -1869,7 +1869,7 @@ method_unbind(VALUE obj) TypedData_Get_Struct(obj, struct METHOD, &method_data_type, orig); method = TypedData_Make_Struct(rb_cUnboundMethod, struct METHOD, - &method_data_type, data); + &method_data_type, data); RB_OBJ_WRITE(method, &data->recv, Qundef); RB_OBJ_WRITE(method, &data->klass, orig->klass); RB_OBJ_WRITE(method, &data->iclass, orig->iclass); @@ -1961,22 +1961,22 @@ rb_method_name_error(VALUE klass, VALUE str) VALUE s = Qundef; if (FL_TEST(c, FL_SINGLETON)) { - VALUE obj = rb_ivar_get(klass, attached); + VALUE obj = rb_ivar_get(klass, attached); - switch (BUILTIN_TYPE(obj)) { - case T_MODULE: - case T_CLASS: - c = obj; + switch (BUILTIN_TYPE(obj)) { + case T_MODULE: + case T_CLASS: + c = obj; break; default: - break; - } + break; + } } else if (RB_TYPE_P(c, T_MODULE)) { - s = MSG(" module"); + s = MSG(" module"); } if (s == Qundef) { - s = MSG(" class"); + s = MSG(" class"); } rb_name_err_raise_str(s, c, str); #undef MSG @@ -1992,7 +1992,7 @@ obj_method(VALUE obj, VALUE vid, int scope) if (!id) { VALUE m = mnew_missing_by_name(klass, obj, &vid, scope, mclass); if (m) return m; - rb_method_name_error(klass, vid); + rb_method_name_error(klass, vid); } return mnew_callable(klass, obj, id, mclass, scope); } @@ -2153,7 +2153,7 @@ rb_mod_instance_method(VALUE mod, VALUE vid) { ID id = rb_check_id(&vid); if (!id) { - rb_method_name_error(mod, vid); + rb_method_name_error(mod, vid); } return mnew_unbound(mod, id, rb_cUnboundMethod, FALSE); } @@ -2170,7 +2170,7 @@ rb_mod_public_instance_method(VALUE mod, VALUE vid) { ID id = rb_check_id(&vid); if (!id) { - rb_method_name_error(mod, vid); + rb_method_name_error(mod, vid); } return mnew_unbound(mod, id, rb_cUnboundMethod, TRUE); } @@ -2187,57 +2187,57 @@ rb_mod_define_method_with_visibility(int argc, VALUE *argv, VALUE mod, const str name = argv[0]; id = rb_check_id(&name); if (argc == 1) { - body = rb_block_lambda(); + body = rb_block_lambda(); } else { - body = argv[1]; + body = argv[1]; - if (rb_obj_is_method(body)) { - is_method = TRUE; - } - else if (rb_obj_is_proc(body)) { - is_method = FALSE; - } - else { - rb_raise(rb_eTypeError, - "wrong argument type %s (expected Proc/Method/UnboundMethod)", - rb_obj_classname(body)); - } + if (rb_obj_is_method(body)) { + is_method = TRUE; + } + else if (rb_obj_is_proc(body)) { + is_method = FALSE; + } + else { + rb_raise(rb_eTypeError, + "wrong argument type %s (expected Proc/Method/UnboundMethod)", + rb_obj_classname(body)); + } } if (!id) id = rb_to_id(name); if (is_method) { - struct METHOD *method = (struct METHOD *)DATA_PTR(body); - if (method->me->owner != mod && !RB_TYPE_P(method->me->owner, T_MODULE) && - !RTEST(rb_class_inherited_p(mod, method->me->owner))) { - if (FL_TEST(method->me->owner, FL_SINGLETON)) { - rb_raise(rb_eTypeError, - "can't bind singleton method to a different class"); - } - else { - rb_raise(rb_eTypeError, - "bind argument must be a subclass of % "PRIsVALUE, - method->me->owner); - } - } - rb_method_entry_set(mod, id, method->me, scope_visi->method_visi); - if (scope_visi->module_func) { - rb_method_entry_set(rb_singleton_class(mod), id, method->me, METHOD_VISI_PUBLIC); - } - RB_GC_GUARD(body); + struct METHOD *method = (struct METHOD *)DATA_PTR(body); + if (method->me->owner != mod && !RB_TYPE_P(method->me->owner, T_MODULE) && + !RTEST(rb_class_inherited_p(mod, method->me->owner))) { + if (FL_TEST(method->me->owner, FL_SINGLETON)) { + rb_raise(rb_eTypeError, + "can't bind singleton method to a different class"); + } + else { + rb_raise(rb_eTypeError, + "bind argument must be a subclass of % "PRIsVALUE, + method->me->owner); + } + } + rb_method_entry_set(mod, id, method->me, scope_visi->method_visi); + if (scope_visi->module_func) { + rb_method_entry_set(rb_singleton_class(mod), id, method->me, METHOD_VISI_PUBLIC); + } + RB_GC_GUARD(body); } else { - VALUE procval = rb_proc_dup(body); - if (vm_proc_iseq(procval) != NULL) { - rb_proc_t *proc; - GetProcPtr(procval, proc); - proc->is_lambda = TRUE; - proc->is_from_method = TRUE; - } - rb_add_method(mod, id, VM_METHOD_TYPE_BMETHOD, (void *)procval, scope_visi->method_visi); - if (scope_visi->module_func) { - rb_add_method(rb_singleton_class(mod), id, VM_METHOD_TYPE_BMETHOD, (void *)body, METHOD_VISI_PUBLIC); - } + VALUE procval = rb_proc_dup(body); + if (vm_proc_iseq(procval) != NULL) { + rb_proc_t *proc; + GetProcPtr(procval, proc); + proc->is_lambda = TRUE; + proc->is_from_method = TRUE; + } + rb_add_method(mod, id, VM_METHOD_TYPE_BMETHOD, (void *)procval, scope_visi->method_visi); + if (scope_visi->module_func) { + rb_add_method(rb_singleton_class(mod), id, VM_METHOD_TYPE_BMETHOD, (void *)body, METHOD_VISI_PUBLIC); + } } return ID2SYM(id); @@ -2352,10 +2352,10 @@ top_define_method(int argc, VALUE *argv, VALUE obj) klass = th->top_wrapper; if (klass) { - rb_warning("main.define_method in the wrapped load is effective only in wrapper module"); + rb_warning("main.define_method in the wrapped load is effective only in wrapper module"); } else { - klass = rb_cObject; + klass = rb_cObject; } return rb_mod_define_method(argc, argv, klass); } @@ -2482,7 +2482,7 @@ rb_method_call_with_block_kw(int argc, const VALUE *argv, VALUE method, VALUE pa TypedData_Get_Struct(method, struct METHOD, &method_data_type, data); if (data->recv == Qundef) { - rb_raise(rb_eTypeError, "can't call unbound method; bind first"); + rb_raise(rb_eTypeError, "can't call unbound method; bind first"); } return call_method_data(ec, data, argc, argv, passed_procval, kw_splat); } @@ -2560,28 +2560,28 @@ convert_umethod_to_method_components(const struct METHOD *data, VALUE recv, VALU if (!NIL_P(refined_class)) methclass = refined_class; } if (!RB_TYPE_P(methclass, T_MODULE) && - methclass != CLASS_OF(recv) && !rb_obj_is_kind_of(recv, methclass)) { - if (FL_TEST(methclass, FL_SINGLETON)) { - rb_raise(rb_eTypeError, - "singleton method called for a different object"); - } - else { - rb_raise(rb_eTypeError, "bind argument must be an instance of % "PRIsVALUE, - methclass); - } + methclass != CLASS_OF(recv) && !rb_obj_is_kind_of(recv, methclass)) { + if (FL_TEST(methclass, FL_SINGLETON)) { + rb_raise(rb_eTypeError, + "singleton method called for a different object"); + } + else { + rb_raise(rb_eTypeError, "bind argument must be an instance of % "PRIsVALUE, + methclass); + } } const rb_method_entry_t *me = rb_method_entry_clone(data->me); if (RB_TYPE_P(me->owner, T_MODULE)) { - VALUE ic = rb_class_search_ancestor(klass, me->owner); - if (ic) { - klass = ic; + VALUE ic = rb_class_search_ancestor(klass, me->owner); + if (ic) { + klass = ic; iclass = ic; - } - else { - klass = rb_include_class_new(methclass, klass); - } + } + else { + klass = rb_include_class_new(methclass, klass); + } me = (const rb_method_entry_t *) rb_method_entry_complement_defined_class(me, me->called_id, klass); } @@ -2695,56 +2695,56 @@ method_def_min_max_arity(const rb_method_definition_t *def, int *max) if (!def) return *max = 0; switch (def->type) { case VM_METHOD_TYPE_CFUNC: - if (def->body.cfunc.argc < 0) { - *max = UNLIMITED_ARGUMENTS; - return 0; - } - return *max = check_argc(def->body.cfunc.argc); + if (def->body.cfunc.argc < 0) { + *max = UNLIMITED_ARGUMENTS; + return 0; + } + return *max = check_argc(def->body.cfunc.argc); case VM_METHOD_TYPE_ZSUPER: - *max = UNLIMITED_ARGUMENTS; - return 0; + *max = UNLIMITED_ARGUMENTS; + return 0; case VM_METHOD_TYPE_ATTRSET: - return *max = 1; + return *max = 1; case VM_METHOD_TYPE_IVAR: - return *max = 0; + return *max = 0; case VM_METHOD_TYPE_ALIAS: - def = def->body.alias.original_me->def; - goto again; + def = def->body.alias.original_me->def; + goto again; case VM_METHOD_TYPE_BMETHOD: return rb_proc_min_max_arity(def->body.bmethod.proc, max); case VM_METHOD_TYPE_ISEQ: - return rb_iseq_min_max_arity(rb_iseq_check(def->body.iseq.iseqptr), max); + return rb_iseq_min_max_arity(rb_iseq_check(def->body.iseq.iseqptr), max); case VM_METHOD_TYPE_UNDEF: case VM_METHOD_TYPE_NOTIMPLEMENTED: - return *max = 0; + return *max = 0; case VM_METHOD_TYPE_MISSING: - *max = UNLIMITED_ARGUMENTS; - return 0; + *max = UNLIMITED_ARGUMENTS; + return 0; case VM_METHOD_TYPE_OPTIMIZED: { - switch (def->body.optimized.type) { - case OPTIMIZED_METHOD_TYPE_SEND: - *max = UNLIMITED_ARGUMENTS; - return 0; - case OPTIMIZED_METHOD_TYPE_CALL: - *max = UNLIMITED_ARGUMENTS; - return 0; - case OPTIMIZED_METHOD_TYPE_BLOCK_CALL: - *max = UNLIMITED_ARGUMENTS; - return 0; + switch (def->body.optimized.type) { + case OPTIMIZED_METHOD_TYPE_SEND: + *max = UNLIMITED_ARGUMENTS; + return 0; + case OPTIMIZED_METHOD_TYPE_CALL: + *max = UNLIMITED_ARGUMENTS; + return 0; + case OPTIMIZED_METHOD_TYPE_BLOCK_CALL: + *max = UNLIMITED_ARGUMENTS; + return 0; case OPTIMIZED_METHOD_TYPE_STRUCT_AREF: *max = 0; return 0; case OPTIMIZED_METHOD_TYPE_STRUCT_ASET: *max = 1; return 1; - default: - break; - } - break; + default: + break; + } + break; } case VM_METHOD_TYPE_REFINED: - *max = UNLIMITED_ARGUMENTS; - return 0; + *max = UNLIMITED_ARGUMENTS; + return 0; } rb_bug("method_def_min_max_arity: invalid method entry type (%d)", def->type); UNREACHABLE_RETURN(Qnil); @@ -2828,10 +2828,10 @@ original_method_entry(VALUE mod, ID id) const rb_method_entry_t *me; while ((me = rb_method_entry(mod, id)) != 0) { - const rb_method_definition_t *def = me->def; - if (def->type != VM_METHOD_TYPE_ZSUPER) break; - mod = RCLASS_SUPER(me->owner); - id = def->original_id; + const rb_method_definition_t *def = me->def; + if (def->type != VM_METHOD_TYPE_ZSUPER) break; + mod = RCLASS_SUPER(me->owner); + id = def->original_id; } return me; } @@ -2888,11 +2888,11 @@ method_def_iseq(const rb_method_definition_t *def) { switch (def->type) { case VM_METHOD_TYPE_ISEQ: - return rb_iseq_check(def->body.iseq.iseqptr); + return rb_iseq_check(def->body.iseq.iseqptr); case VM_METHOD_TYPE_BMETHOD: return rb_proc_get_iseq(def->body.bmethod.proc, 0); case VM_METHOD_TYPE_ALIAS: - return method_def_iseq(def->body.alias.original_me->def); + return method_def_iseq(def->body.alias.original_me->def); case VM_METHOD_TYPE_CFUNC: case VM_METHOD_TYPE_ATTRSET: case VM_METHOD_TYPE_IVAR: @@ -2902,7 +2902,7 @@ method_def_iseq(const rb_method_definition_t *def) case VM_METHOD_TYPE_OPTIMIZED: case VM_METHOD_TYPE_MISSING: case VM_METHOD_TYPE_REFINED: - break; + break; } return NULL; } @@ -2921,12 +2921,12 @@ method_cref(VALUE method) again: switch (def->type) { case VM_METHOD_TYPE_ISEQ: - return def->body.iseq.cref; + return def->body.iseq.cref; case VM_METHOD_TYPE_ALIAS: - def = def->body.alias.original_me->def; - goto again; + def = def->body.alias.original_me->def; + goto again; default: - return NULL; + return NULL; } } @@ -2934,9 +2934,9 @@ static VALUE method_def_location(const rb_method_definition_t *def) { if (def->type == VM_METHOD_TYPE_ATTRSET || def->type == VM_METHOD_TYPE_IVAR) { - if (!def->body.attr.location) - return Qnil; - return rb_ary_dup(def->body.attr.location); + if (!def->body.attr.location) + return Qnil; + return rb_ary_dup(def->body.attr.location); } return iseq_location(method_def_iseq(def)); } @@ -3107,33 +3107,33 @@ method_inspect(VALUE method) } if (data->me->def->type == VM_METHOD_TYPE_ALIAS) { - defined_class = data->me->def->body.alias.original_me->owner; + defined_class = data->me->def->body.alias.original_me->owner; } else { - defined_class = method_entry_defined_class(data->me); + defined_class = method_entry_defined_class(data->me); } if (RB_TYPE_P(defined_class, T_ICLASS)) { - defined_class = RBASIC_CLASS(defined_class); + defined_class = RBASIC_CLASS(defined_class); } if (FL_TEST(mklass, FL_SINGLETON)) { - VALUE v = rb_ivar_get(mklass, attached); + VALUE v = rb_ivar_get(mklass, attached); - if (data->recv == Qundef) { - rb_str_buf_append(str, rb_inspect(mklass)); - } - else if (data->recv == v) { - rb_str_buf_append(str, rb_inspect(v)); - sharp = "."; - } - else { - rb_str_buf_append(str, rb_inspect(data->recv)); - rb_str_buf_cat2(str, "("); - rb_str_buf_append(str, rb_inspect(v)); - rb_str_buf_cat2(str, ")"); - sharp = "."; - } + if (data->recv == Qundef) { + rb_str_buf_append(str, rb_inspect(mklass)); + } + else if (data->recv == v) { + rb_str_buf_append(str, rb_inspect(v)); + sharp = "."; + } + else { + rb_str_buf_append(str, rb_inspect(data->recv)); + rb_str_buf_cat2(str, "("); + rb_str_buf_append(str, rb_inspect(v)); + rb_str_buf_cat2(str, ")"); + sharp = "."; + } } else { mklass = data->klass; @@ -3145,16 +3145,16 @@ method_inspect(VALUE method) } while (RB_TYPE_P(mklass, T_ICLASS)); } } - rb_str_buf_append(str, rb_inspect(mklass)); - if (defined_class != mklass) { - rb_str_catf(str, "(% "PRIsVALUE")", defined_class); - } + rb_str_buf_append(str, rb_inspect(mklass)); + if (defined_class != mklass) { + rb_str_catf(str, "(% "PRIsVALUE")", defined_class); + } } rb_str_buf_cat2(str, sharp); rb_str_append(str, rb_id2str(data->me->called_id)); if (data->me->called_id != data->me->def->original_id) { - rb_str_catf(str, "(%"PRIsVALUE")", - rb_id2str(data->me->def->original_id)); + rb_str_catf(str, "(%"PRIsVALUE")", + rb_id2str(data->me->def->original_id)); } if (data->me->def->type == VM_METHOD_TYPE_NOTIMPLEMENTED) { rb_str_buf_cat2(str, " (not-implemented)"); @@ -3438,7 +3438,7 @@ env_clone(const rb_env_t *env, const rb_cref_t *cref) VM_ASSERT(VM_ENV_ESCAPED_P(env->ep)); if (cref == NULL) { - cref = rb_vm_cref_new_toplevel(); + cref = rb_vm_cref_new_toplevel(); } new_body = ALLOC_N(VALUE, env->env_size); @@ -3481,31 +3481,31 @@ proc_binding(VALUE self) again: switch (vm_block_type(block)) { case block_type_iseq: - iseq = block->as.captured.code.iseq; - binding_self = block->as.captured.self; - env = VM_ENV_ENVVAL_PTR(block->as.captured.ep); - break; + iseq = block->as.captured.code.iseq; + binding_self = block->as.captured.self; + env = VM_ENV_ENVVAL_PTR(block->as.captured.ep); + break; case block_type_proc: - GetProcPtr(block->as.proc, proc); - block = &proc->block; - goto again; + GetProcPtr(block->as.proc, proc); + block = &proc->block; + goto again; case block_type_ifunc: - { - const struct vm_ifunc *ifunc = block->as.captured.code.ifunc; - if (IS_METHOD_PROC_IFUNC(ifunc)) { - VALUE method = (VALUE)ifunc->data; - VALUE name = rb_fstring_lit(""); - rb_iseq_t *empty; - binding_self = method_receiver(method); - iseq = rb_method_iseq(method); - env = VM_ENV_ENVVAL_PTR(block->as.captured.ep); - env = env_clone(env, method_cref(method)); - /* set empty iseq */ - empty = rb_iseq_new(NULL, name, name, Qnil, 0, ISEQ_TYPE_TOP); - RB_OBJ_WRITE(env, &env->iseq, empty); - break; - } - } + { + const struct vm_ifunc *ifunc = block->as.captured.code.ifunc; + if (IS_METHOD_PROC_IFUNC(ifunc)) { + VALUE method = (VALUE)ifunc->data; + VALUE name = rb_fstring_lit(""); + rb_iseq_t *empty; + binding_self = method_receiver(method); + iseq = rb_method_iseq(method); + env = VM_ENV_ENVVAL_PTR(block->as.captured.ep); + env = env_clone(env, method_cref(method)); + /* set empty iseq */ + empty = rb_iseq_new(NULL, name, name, Qnil, 0, ISEQ_TYPE_TOP); + RB_OBJ_WRITE(env, &env->iseq, empty); + break; + } + } /* FALLTHROUGH */ case block_type_symbol: rb_raise(rb_eArgError, "Can't create Binding from C level Proc"); @@ -3520,14 +3520,14 @@ proc_binding(VALUE self) RB_OBJ_WRITTEN(bindval, Qundef, VM_ENV_ENVVAL(env->ep)); if (iseq) { - rb_iseq_check(iseq); + rb_iseq_check(iseq); RB_OBJ_WRITE(bindval, &bind->pathobj, ISEQ_BODY(iseq)->location.pathobj); - bind->first_lineno = FIX2INT(rb_iseq_first_lineno(iseq)); + bind->first_lineno = FIX2INT(rb_iseq_first_lineno(iseq)); } else { - RB_OBJ_WRITE(bindval, &bind->pathobj, - rb_iseq_pathobj_new(rb_fstring_lit("(binding)"), Qnil)); - bind->first_lineno = 1; + RB_OBJ_WRITE(bindval, &bind->pathobj, + rb_iseq_pathobj_new(rb_fstring_lit("(binding)"), Qnil)); + bind->first_lineno = 1; } return bindval; @@ -3565,10 +3565,10 @@ curry(RB_BLOCK_CALL_FUNC_ARGLIST(_, args)) if (RARRAY_LEN(passed) < FIX2INT(arity)) { if (!NIL_P(blockarg)) { - rb_warn("given block not used"); - } - arity = make_curry_proc(proc, passed, arity); - return arity; + rb_warn("given block not used"); + } + arity = make_curry_proc(proc, passed, arity); + return arity; } else { return rb_proc_call_with_block(proc, check_argc(RARRAY_LEN(passed)), RARRAY_CONST_PTR(passed), blockarg); @@ -3628,13 +3628,13 @@ proc_curry(int argc, const VALUE *argv, VALUE self) VALUE arity; if (rb_check_arity(argc, 0, 1) == 0 || NIL_P(arity = argv[0])) { - arity = INT2FIX(min_arity); + arity = INT2FIX(min_arity); } else { - sarity = FIX2INT(arity); - if (rb_proc_lambda_p(self)) { - rb_check_arity(sarity, min_arity, max_arity); - } + sarity = FIX2INT(arity); + if (rb_proc_lambda_p(self)) { + rb_check_arity(sarity, min_arity, max_arity); + } } return make_curry_proc(self, rb_ary_new(), arity); @@ -4378,7 +4378,7 @@ Init_Proc(void) rb_define_method(rb_mKernel, "define_singleton_method", rb_obj_define_method, -1); rb_define_private_method(rb_singleton_class(rb_vm_top_self()), - "define_method", top_define_method, -1); + "define_method", top_define_method, -1); } /* diff --git a/process.c b/process.c index 57bfa808be..5d16a3854a 100644 --- a/process.c +++ b/process.c @@ -760,31 +760,31 @@ static VALUE pst_message_status(VALUE str, int status) { if (WIFSTOPPED(status)) { - int stopsig = WSTOPSIG(status); - const char *signame = ruby_signal_name(stopsig); - if (signame) { - rb_str_catf(str, " stopped SIG%s (signal %d)", signame, stopsig); - } - else { - rb_str_catf(str, " stopped signal %d", stopsig); - } + int stopsig = WSTOPSIG(status); + const char *signame = ruby_signal_name(stopsig); + if (signame) { + rb_str_catf(str, " stopped SIG%s (signal %d)", signame, stopsig); + } + else { + rb_str_catf(str, " stopped signal %d", stopsig); + } } if (WIFSIGNALED(status)) { - int termsig = WTERMSIG(status); - const char *signame = ruby_signal_name(termsig); - if (signame) { - rb_str_catf(str, " SIG%s (signal %d)", signame, termsig); - } - else { - rb_str_catf(str, " signal %d", termsig); - } + int termsig = WTERMSIG(status); + const char *signame = ruby_signal_name(termsig); + if (signame) { + rb_str_catf(str, " SIG%s (signal %d)", signame, termsig); + } + else { + rb_str_catf(str, " signal %d", termsig); + } } if (WIFEXITED(status)) { - rb_str_catf(str, " exit %d", WEXITSTATUS(status)); + rb_str_catf(str, " exit %d", WEXITSTATUS(status)); } #ifdef WCOREDUMP if (WCOREDUMP(status)) { - rb_str_cat2(str, " (core dumped)"); + rb_str_cat2(str, " (core dumped)"); } #endif return str; @@ -939,7 +939,7 @@ pst_wstopsig(VALUE st) int status = PST2INT(st); if (WIFSTOPPED(status)) - return INT2NUM(WSTOPSIG(status)); + return INT2NUM(WSTOPSIG(status)); return Qnil; } @@ -976,7 +976,7 @@ pst_wtermsig(VALUE st) int status = PST2INT(st); if (WIFSIGNALED(status)) - return INT2NUM(WTERMSIG(status)); + return INT2NUM(WTERMSIG(status)); return Qnil; } @@ -1023,7 +1023,7 @@ pst_wexitstatus(VALUE st) int status = PST2INT(st); if (WIFEXITED(status)) - return INT2NUM(WEXITSTATUS(status)); + return INT2NUM(WEXITSTATUS(status)); return Qnil; } @@ -1042,7 +1042,7 @@ pst_success_p(VALUE st) int status = PST2INT(st); if (!WIFEXITED(status)) - return Qnil; + return Qnil; return RBOOL(WEXITSTATUS(status) == EXIT_SUCCESS); } @@ -1591,14 +1591,14 @@ proc_waitall(VALUE _) rb_last_status_clear(); for (pid = -1;;) { - pid = rb_waitpid(-1, &status, 0); - if (pid == -1) { - int e = errno; - if (e == ECHILD) - break; - rb_syserr_fail(e, 0); - } - rb_ary_push(result, rb_assoc_new(PIDT2NUM(pid), rb_last_status_get())); + pid = rb_waitpid(-1, &status, 0); + if (pid == -1) { + int e = errno; + if (e == ECHILD) + break; + rb_syserr_fail(e, 0); + } + rb_ary_push(result, rb_assoc_new(PIDT2NUM(pid), rb_last_status_get())); } return result; } @@ -1618,7 +1618,7 @@ detach_process_watcher(void *arg) int status; while ((cpid = rb_waitpid(pid, &status, 0)) == 0) { - /* wait while alive */ + /* wait while alive */ } return rb_last_status_get(); } @@ -1813,7 +1813,7 @@ proc_exec_cmd(const char *prog, VALUE argv_str, VALUE envp_str) argv = ARGVSTR2ARGV(argv_str); if (!prog) { - return ENOENT; + return ENOENT; } #ifdef _WIN32 @@ -1839,7 +1839,7 @@ proc_exec_sh(const char *str, VALUE envp_str) s = str; while (*s == ' ' || *s == '\t' || *s == '\n') - s++; + s++; if (!*s) { return ENOENT; @@ -1955,19 +1955,19 @@ proc_spawn_cmd_internal(char **argv, char *prog) rb_pid_t status; if (!prog) - prog = argv[0]; + prog = argv[0]; prog = dln_find_exe_r(prog, 0, fbuf, sizeof(fbuf)); if (!prog) - return -1; + return -1; before_exec(); status = spawnv(P_NOWAIT, prog, (const char **)argv); if (status == -1 && errno == ENOEXEC) { - *argv = (char *)prog; - *--argv = (char *)"sh"; - status = spawnv(P_NOWAIT, "/bin/sh", (const char **)argv); - after_exec(); - if (status == -1) errno = ENOEXEC; + *argv = (char *)prog; + *--argv = (char *)"sh"; + status = spawnv(P_NOWAIT, "/bin/sh", (const char **)argv); + after_exec(); + if (status == -1) errno = ENOEXEC; } return status; } @@ -1980,13 +1980,13 @@ proc_spawn_cmd(char **argv, VALUE prog, struct rb_execarg *eargp) if (argv[0]) { #if defined(_WIN32) - DWORD flags = 0; - if (eargp->new_pgroup_given && eargp->new_pgroup_flag) { - flags = CREATE_NEW_PROCESS_GROUP; - } - pid = rb_w32_uaspawn_flags(P_NOWAIT, prog ? RSTRING_PTR(prog) : 0, argv, flags); + DWORD flags = 0; + if (eargp->new_pgroup_given && eargp->new_pgroup_flag) { + flags = CREATE_NEW_PROCESS_GROUP; + } + pid = rb_w32_uaspawn_flags(P_NOWAIT, prog ? RSTRING_PTR(prog) : 0, argv, flags); #else - pid = proc_spawn_cmd_internal(argv, prog ? RSTRING_PTR(prog) : 0); + pid = proc_spawn_cmd_internal(argv, prog ? RSTRING_PTR(prog) : 0); #endif } return pid; @@ -2156,18 +2156,18 @@ check_exec_redirect(VALUE key, VALUE val, struct rb_execarg *eargp) if (FIXNUM_P(key) && (FIX2INT(key) == 1 || FIX2INT(key) == 2)) flags = INT2NUM(O_WRONLY|O_CREAT|O_TRUNC); else if (RB_TYPE_P(key, T_ARRAY)) { - int i; - for (i = 0; i < RARRAY_LEN(key); i++) { + int i; + for (i = 0; i < RARRAY_LEN(key); i++) { VALUE v = RARRAY_AREF(key, i); - VALUE fd = check_exec_redirect_fd(v, 1); - if (FIX2INT(fd) != 1 && FIX2INT(fd) != 2) break; - } - if (i == RARRAY_LEN(key)) - flags = INT2NUM(O_WRONLY|O_CREAT|O_TRUNC); - else - flags = INT2NUM(O_RDONLY); - } - else + VALUE fd = check_exec_redirect_fd(v, 1); + if (FIX2INT(fd) != 1 && FIX2INT(fd) != 2) break; + } + if (i == RARRAY_LEN(key)) + flags = INT2NUM(O_WRONLY|O_CREAT|O_TRUNC); + else + flags = INT2NUM(O_RDONLY); + } + else flags = INT2NUM(O_RDONLY); perm = INT2FIX(0644); param = hide_obj(rb_ary_new3(4, hide_obj(EXPORT_DUP(path)), @@ -2176,9 +2176,9 @@ check_exec_redirect(VALUE key, VALUE val, struct rb_execarg *eargp) break; default: - tmp = val; - val = rb_io_check_io(tmp); - if (!NIL_P(val)) goto io; + tmp = val; + val = rb_io_check_io(tmp); + if (!NIL_P(val)) goto io; rb_raise(rb_eArgError, "wrong exec redirect action"); } @@ -2193,23 +2193,23 @@ rb_execarg_addopt_rlimit(struct rb_execarg *eargp, int rtype, VALUE val) VALUE ary = eargp->rlimit_limits; VALUE tmp, softlim, hardlim; if (eargp->rlimit_limits == Qfalse) - ary = eargp->rlimit_limits = hide_obj(rb_ary_new()); + ary = eargp->rlimit_limits = hide_obj(rb_ary_new()); else - ary = eargp->rlimit_limits; + ary = eargp->rlimit_limits; tmp = rb_check_array_type(val); if (!NIL_P(tmp)) { - if (RARRAY_LEN(tmp) == 1) - softlim = hardlim = rb_to_int(rb_ary_entry(tmp, 0)); - else if (RARRAY_LEN(tmp) == 2) { - softlim = rb_to_int(rb_ary_entry(tmp, 0)); - hardlim = rb_to_int(rb_ary_entry(tmp, 1)); - } - else { - rb_raise(rb_eArgError, "wrong exec rlimit option"); - } + if (RARRAY_LEN(tmp) == 1) + softlim = hardlim = rb_to_int(rb_ary_entry(tmp, 0)); + else if (RARRAY_LEN(tmp) == 2) { + softlim = rb_to_int(rb_ary_entry(tmp, 0)); + hardlim = rb_to_int(rb_ary_entry(tmp, 1)); + } + else { + rb_raise(rb_eArgError, "wrong exec rlimit option"); + } } else { - softlim = hardlim = rb_to_int(val); + softlim = hardlim = rb_to_int(val); } tmp = hide_obj(rb_ary_new3(3, INT2NUM(rtype), softlim, hardlim)); rb_ary_push(ary, tmp); @@ -2280,12 +2280,12 @@ rb_execarg_addopt(VALUE execarg_obj, VALUE key, VALUE val) rb_raise(rb_eArgError, "chdir option specified twice"); } FilePathValue(val); - val = rb_str_encode_ospath(val); + val = rb_str_encode_ospath(val); eargp->chdir_given = 1; eargp->chdir_dir = hide_obj(EXPORT_DUP(val)); } else if (id == id_umask) { - mode_t cmask = NUM2MODET(val); + mode_t cmask = NUM2MODET(val); if (eargp->umask_given) { rb_raise(rb_eArgError, "umask option specified twice"); } @@ -2311,36 +2311,36 @@ rb_execarg_addopt(VALUE execarg_obj, VALUE key, VALUE val) key = INT2FIX(2); goto redirect; } - else if (id == id_uid) { + else if (id == id_uid) { #ifdef HAVE_SETUID - if (eargp->uid_given) { - rb_raise(rb_eArgError, "uid option specified twice"); - } - check_uid_switch(); - { - eargp->uid = OBJ2UID(val); - eargp->uid_given = 1; - } + if (eargp->uid_given) { + rb_raise(rb_eArgError, "uid option specified twice"); + } + check_uid_switch(); + { + eargp->uid = OBJ2UID(val); + eargp->uid_given = 1; + } #else - rb_raise(rb_eNotImpError, - "uid option is unimplemented on this machine"); + rb_raise(rb_eNotImpError, + "uid option is unimplemented on this machine"); #endif - } - else if (id == id_gid) { + } + else if (id == id_gid) { #ifdef HAVE_SETGID - if (eargp->gid_given) { - rb_raise(rb_eArgError, "gid option specified twice"); - } - check_gid_switch(); - { - eargp->gid = OBJ2GID(val); - eargp->gid_given = 1; - } + if (eargp->gid_given) { + rb_raise(rb_eArgError, "gid option specified twice"); + } + check_gid_switch(); + { + eargp->gid = OBJ2GID(val); + eargp->gid_given = 1; + } #else - rb_raise(rb_eNotImpError, - "gid option is unimplemented on this machine"); + rb_raise(rb_eNotImpError, + "gid option is unimplemented on this machine"); #endif - } + } else if (id == id_exception) { if (eargp->exception_given) { rb_raise(rb_eArgError, "exception option specified twice"); @@ -2349,7 +2349,7 @@ rb_execarg_addopt(VALUE execarg_obj, VALUE key, VALUE val) eargp->exception = TO_BOOL(val, "exception"); } else { - return ST_STOP; + return ST_STOP; } break; @@ -2361,7 +2361,7 @@ redirect: break; default: - return ST_STOP; + return ST_STOP; } RB_GC_GUARD(execarg_obj); @@ -2375,10 +2375,10 @@ check_exec_options_i(st_data_t st_key, st_data_t st_val, st_data_t arg) VALUE val = (VALUE)st_val; VALUE execarg_obj = (VALUE)arg; if (rb_execarg_addopt(execarg_obj, key, val) != ST_CONTINUE) { - if (SYMBOL_P(key)) - rb_raise(rb_eArgError, "wrong exec option symbol: % "PRIsVALUE, - key); - rb_raise(rb_eArgError, "wrong exec option"); + if (SYMBOL_P(key)) + rb_raise(rb_eArgError, "wrong exec option symbol: % "PRIsVALUE, + key); + rb_raise(rb_eArgError, "wrong exec option"); } return ST_CONTINUE; } @@ -2391,9 +2391,9 @@ check_exec_options_i_extract(st_data_t st_key, st_data_t st_val, st_data_t arg) VALUE *args = (VALUE *)arg; VALUE execarg_obj = args[0]; if (rb_execarg_addopt(execarg_obj, key, val) != ST_CONTINUE) { - VALUE nonopts = args[1]; - if (NIL_P(nonopts)) args[1] = nonopts = rb_hash_new(); - rb_hash_aset(nonopts, key, val); + VALUE nonopts = args[1]; + if (NIL_P(nonopts)) args[1] = nonopts = rb_hash_new(); + rb_hash_aset(nonopts, key, val); } return ST_CONTINUE; } @@ -2521,7 +2521,7 @@ check_exec_env_i(st_data_t st_key, st_data_t st_val, st_data_t arg) if (!NIL_P(val)) val = EXPORT_STR(val); if (ENVMATCH(k, PATH_ENV)) { - *path = val; + *path = val; } rb_ary_push(env, hide_obj(rb_assoc_new(key, val))); @@ -2552,19 +2552,19 @@ rb_check_argv(int argc, VALUE *argv) prog = 0; tmp = rb_check_array_type(argv[0]); if (!NIL_P(tmp)) { - if (RARRAY_LEN(tmp) != 2) { - rb_raise(rb_eArgError, "wrong first argument"); - } - prog = RARRAY_AREF(tmp, 0); - argv[0] = RARRAY_AREF(tmp, 1); - SafeStringValue(prog); - StringValueCStr(prog); - prog = rb_str_new_frozen(prog); + if (RARRAY_LEN(tmp) != 2) { + rb_raise(rb_eArgError, "wrong first argument"); + } + prog = RARRAY_AREF(tmp, 0); + argv[0] = RARRAY_AREF(tmp, 1); + SafeStringValue(prog); + StringValueCStr(prog); + prog = rb_str_new_frozen(prog); } for (i = 0; i < argc; i++) { - SafeStringValue(argv[i]); - argv[i] = rb_str_new_frozen(argv[i]); - StringValueCStr(argv[i]); + SafeStringValue(argv[i]); + argv[i] = rb_str_new_frozen(argv[i]); + StringValueCStr(argv[i]); } return prog; } @@ -2576,7 +2576,7 @@ check_hash(VALUE obj) switch (RB_BUILTIN_TYPE(obj)) { case T_STRING: case T_ARRAY: - return Qnil; + return Qnil; default: break; } @@ -2656,39 +2656,39 @@ rb_exec_fillarg(VALUE prog, int argc, VALUE *argv, VALUE env, VALUE opthash, VAL #ifndef _WIN32 if (eargp->use_shell) { - static const char posix_sh_cmds[][9] = { - "!", /* reserved */ - ".", /* special built-in */ - ":", /* special built-in */ - "break", /* special built-in */ - "case", /* reserved */ - "continue", /* special built-in */ - "do", /* reserved */ - "done", /* reserved */ - "elif", /* reserved */ - "else", /* reserved */ - "esac", /* reserved */ - "eval", /* special built-in */ - "exec", /* special built-in */ - "exit", /* special built-in */ - "export", /* special built-in */ - "fi", /* reserved */ - "for", /* reserved */ - "if", /* reserved */ - "in", /* reserved */ - "readonly", /* special built-in */ - "return", /* special built-in */ - "set", /* special built-in */ - "shift", /* special built-in */ - "then", /* reserved */ - "times", /* special built-in */ - "trap", /* special built-in */ - "unset", /* special built-in */ - "until", /* reserved */ - "while", /* reserved */ - }; - const char *p; - struct string_part first = {0, 0}; + static const char posix_sh_cmds[][9] = { + "!", /* reserved */ + ".", /* special built-in */ + ":", /* special built-in */ + "break", /* special built-in */ + "case", /* reserved */ + "continue", /* special built-in */ + "do", /* reserved */ + "done", /* reserved */ + "elif", /* reserved */ + "else", /* reserved */ + "esac", /* reserved */ + "eval", /* special built-in */ + "exec", /* special built-in */ + "exit", /* special built-in */ + "export", /* special built-in */ + "fi", /* reserved */ + "for", /* reserved */ + "if", /* reserved */ + "in", /* reserved */ + "readonly", /* special built-in */ + "return", /* special built-in */ + "set", /* special built-in */ + "shift", /* special built-in */ + "then", /* reserved */ + "times", /* special built-in */ + "trap", /* special built-in */ + "unset", /* special built-in */ + "until", /* reserved */ + "while", /* reserved */ + }; + const char *p; + struct string_part first = {0, 0}; int has_meta = 0; /* * meta characters: @@ -2715,32 +2715,32 @@ rb_exec_fillarg(VALUE prog, int argc, VALUE *argv, VALUE env, VALUE opthash, VAL * % (used in Parameter Expansion) */ for (p = RSTRING_PTR(prog); *p; p++) { - if (*p == ' ' || *p == '\t') { - if (first.ptr && !first.len) first.len = p - first.ptr; - } - else { - if (!first.ptr) first.ptr = p; - } + if (*p == ' ' || *p == '\t') { + if (first.ptr && !first.len) first.len = p - first.ptr; + } + else { + if (!first.ptr) first.ptr = p; + } if (!has_meta && strchr("*?{}[]<>()~&|\\$;'`\"\n#", *p)) has_meta = 1; - if (!first.len) { - if (*p == '=') { - has_meta = 1; - } - else if (*p == '/') { - first.len = 0x100; /* longer than any posix_sh_cmds */ - } - } - if (has_meta) + if (!first.len) { + if (*p == '=') { + has_meta = 1; + } + else if (*p == '/') { + first.len = 0x100; /* longer than any posix_sh_cmds */ + } + } + if (has_meta) break; } - if (!has_meta && first.ptr) { - if (!first.len) first.len = p - first.ptr; - if (first.len > 0 && first.len <= sizeof(posix_sh_cmds[0]) && - bsearch(&first, posix_sh_cmds, numberof(posix_sh_cmds), sizeof(posix_sh_cmds[0]), compare_posix_sh)) - has_meta = 1; - } - if (!has_meta) { + if (!has_meta && first.ptr) { + if (!first.len) first.len = p - first.ptr; + if (first.len > 0 && first.len <= sizeof(posix_sh_cmds[0]) && + bsearch(&first, posix_sh_cmds, numberof(posix_sh_cmds), sizeof(posix_sh_cmds[0]), compare_posix_sh)) + has_meta = 1; + } + if (!has_meta) { /* avoid shell since no shell meta character found. */ eargp->use_shell = 0; } @@ -2752,7 +2752,7 @@ rb_exec_fillarg(VALUE prog, int argc, VALUE *argv, VALUE env, VALUE opthash, VAL while (*p == ' ' || *p == '\t') p++; if (*p) { - const char *w = p; + const char *w = p; while (*p && *p != ' ' && *p != '\t') p++; rb_str_buf_cat(argv_buf, w, p-w); @@ -2768,15 +2768,15 @@ rb_exec_fillarg(VALUE prog, int argc, VALUE *argv, VALUE env, VALUE opthash, VAL #endif if (!eargp->use_shell) { - const char *abspath; - const char *path_env = 0; - if (RTEST(eargp->path_env)) path_env = RSTRING_PTR(eargp->path_env); - abspath = dln_find_exe_r(RSTRING_PTR(eargp->invoke.cmd.command_name), - path_env, fbuf, sizeof(fbuf)); - if (abspath) - eargp->invoke.cmd.command_abspath = rb_str_new_cstr(abspath); - else - eargp->invoke.cmd.command_abspath = Qnil; + const char *abspath; + const char *path_env = 0; + if (RTEST(eargp->path_env)) path_env = RSTRING_PTR(eargp->path_env); + abspath = dln_find_exe_r(RSTRING_PTR(eargp->invoke.cmd.command_name), + path_env, fbuf, sizeof(fbuf)); + if (abspath) + eargp->invoke.cmd.command_abspath = rb_str_new_cstr(abspath); + else + eargp->invoke.cmd.command_abspath = Qnil; } if (!eargp->use_shell && !eargp->invoke.cmd.argv_buf) { @@ -2785,13 +2785,13 @@ rb_exec_fillarg(VALUE prog, int argc, VALUE *argv, VALUE env, VALUE opthash, VAL argv_buf = rb_str_buf_new(0); hide_obj(argv_buf); for (i = 0; i < argc; i++) { - VALUE arg = argv[i]; - const char *s = StringValueCStr(arg); + VALUE arg = argv[i]; + const char *s = StringValueCStr(arg); #ifdef DEFAULT_PROCESS_ENCODING - arg = EXPORT_STR(arg); - s = RSTRING_PTR(arg); + arg = EXPORT_STR(arg); + s = RSTRING_PTR(arg); #endif - rb_str_buf_cat(argv_buf, s, RSTRING_LEN(arg) + 1); /* include '\0' */ + rb_str_buf_cat(argv_buf, s, RSTRING_LEN(arg) + 1); /* include '\0' */ } eargp->invoke.cmd.argv_buf = argv_buf; } @@ -2972,20 +2972,20 @@ rb_execarg_parent_start1(VALUE execarg_obj) } hide_obj(envtbl); if (envopts != Qfalse) { - st_table *stenv = RHASH_TBL_RAW(envtbl); + st_table *stenv = RHASH_TBL_RAW(envtbl); long i; for (i = 0; i < RARRAY_LEN(envopts); i++) { VALUE pair = RARRAY_AREF(envopts, i); VALUE key = RARRAY_AREF(pair, 0); VALUE val = RARRAY_AREF(pair, 1); if (NIL_P(val)) { - st_data_t stkey = (st_data_t)key; - st_delete(stenv, &stkey, NULL); + st_data_t stkey = (st_data_t)key; + st_delete(stenv, &stkey, NULL); } else { - st_insert(stenv, (st_data_t)key, (st_data_t)val); - RB_OBJ_WRITTEN(envtbl, Qundef, key); - RB_OBJ_WRITTEN(envtbl, Qundef, val); + st_insert(stenv, (st_data_t)key, (st_data_t)val); + RB_OBJ_WRITTEN(envtbl, Qundef, key); + RB_OBJ_WRITTEN(envtbl, Qundef, val); } } } @@ -3070,7 +3070,7 @@ rb_exec_fail(struct rb_execarg *eargp, int err, const char *errmsg) { if (!errmsg || !*errmsg) return; if (strcmp(errmsg, "chdir") == 0) { - rb_sys_fail_str(eargp->chdir_dir); + rb_sys_fail_str(eargp->chdir_dir); } rb_sys_fail(errmsg); } @@ -3226,10 +3226,10 @@ save_redirect_fd(int fd, struct rb_execarg *sargp, char *errmsg, size_t errmsg_b newary = hide_obj(rb_ary_new()); sargp->fd_dup2 = newary; } - cloexec = fd_get_cloexec(fd, errmsg, errmsg_buflen); - redirection = hide_obj(rb_assoc_new(INT2FIX(fd), INT2FIX(save_fd))); - if (cloexec) rb_ary_push(redirection, Qtrue); - rb_ary_push(newary, redirection); + cloexec = fd_get_cloexec(fd, errmsg, errmsg_buflen); + redirection = hide_obj(rb_assoc_new(INT2FIX(fd), INT2FIX(save_fd))); + if (cloexec) rb_ary_push(redirection, Qtrue); + rb_ary_push(newary, redirection); newary = sargp->fd_close; if (newary == Qfalse) { @@ -3386,10 +3386,10 @@ run_exec_dup2(VALUE ary, VALUE tmpbuf, struct rb_execarg *sargp, char *errmsg, s ERRMSG("dup2"); goto fail; } - if (pairs[j].cloexec && - fd_set_cloexec(pairs[j].newfd, errmsg, errmsg_buflen)) { - goto fail; - } + if (pairs[j].cloexec && + fd_set_cloexec(pairs[j].newfd, errmsg, errmsg_buflen)) { + goto fail; + } rb_update_max_fd(pairs[j].newfd); /* async-signal-safe but don't need to call it in a child process. */ pairs[j].oldfd = -1; j = pairs[j].older_index; @@ -3697,18 +3697,18 @@ rb_execarg_run_options(const struct rb_execarg *eargp, struct rb_execarg *sargp, #ifdef HAVE_SETGID if (eargp->gid_given) { - if (setgid(eargp->gid) < 0) { - ERRMSG("setgid"); - return -1; - } + if (setgid(eargp->gid) < 0) { + ERRMSG("setgid"); + return -1; + } } #endif #ifdef HAVE_SETUID if (eargp->uid_given) { - if (setuid(eargp->uid) < 0) { - ERRMSG("setuid"); - return -1; - } + if (setuid(eargp->uid) < 0) { + ERRMSG("setuid"); + return -1; + } } #endif @@ -3746,17 +3746,17 @@ exec_async_signal_safe(const struct rb_execarg *eargp, char *errmsg, size_t errm int err; if (rb_execarg_run_options(eargp, sargp, errmsg, errmsg_buflen) < 0) { /* hopefully async-signal-safe */ - return errno; + return errno; } if (eargp->use_shell) { - err = proc_exec_sh(RSTRING_PTR(eargp->invoke.sh.shell_script), eargp->envp_str); /* async-signal-safe */ + err = proc_exec_sh(RSTRING_PTR(eargp->invoke.sh.shell_script), eargp->envp_str); /* async-signal-safe */ } else { - char *abspath = NULL; - if (!NIL_P(eargp->invoke.cmd.command_abspath)) - abspath = RSTRING_PTR(eargp->invoke.cmd.command_abspath); - err = proc_exec_cmd(abspath, eargp->invoke.cmd.argv_str, eargp->envp_str); /* async-signal-safe */ + char *abspath = NULL; + if (!NIL_P(eargp->invoke.cmd.command_abspath)) + abspath = RSTRING_PTR(eargp->invoke.cmd.command_abspath); + err = proc_exec_cmd(abspath, eargp->invoke.cmd.argv_str, eargp->envp_str); /* async-signal-safe */ } #if !defined(HAVE_WORKING_FORK) rb_execarg_run_options(sargp, NULL, errmsg, errmsg_buflen); @@ -3865,18 +3865,18 @@ handle_fork_error(int err, struct rb_process_status *status, int *ep, volatile i break; } if (ep) { - close(ep[0]); - close(ep[1]); - errno = err; + close(ep[0]); + close(ep[1]); + errno = err; } if (state && !status) rb_jump_tag(state); return -1; } #define prefork() ( \ - rb_io_flush(rb_stdout), \ - rb_io_flush(rb_stderr) \ - ) + rb_io_flush(rb_stdout), \ + rb_io_flush(rb_stderr) \ + ) /* * Forks child process, and returns the process ID in the parent @@ -3910,7 +3910,7 @@ write_retry(int fd, const void *buf, size_t len) ssize_t w; do { - w = write(fd, buf, len); + w = write(fd, buf, len); } while (w < 0 && errno == EINTR); return w; @@ -3928,7 +3928,7 @@ read_retry(int fd, void *buf, size_t len) } do { - r = read(fd, buf, len); + r = read(fd, buf, len); } while (r < 0 && errno == EINTR); return r; @@ -3981,7 +3981,7 @@ getresuid(rb_uid_t *ruid, rb_uid_t *euid, rb_uid_t *suid) *euid = geteuid(); ret = getuidx(ID_SAVED); if (ret == (rb_uid_t)-1) - return -1; + return -1; *suid = ret; return 0; } @@ -3999,7 +3999,7 @@ getresgid(rb_gid_t *rgid, rb_gid_t *egid, rb_gid_t *sgid) *egid = getegid(); ret = getgidx(ID_SAVED); if (ret == (rb_gid_t)-1) - return -1; + return -1; *sgid = ret; return 0; } @@ -4026,7 +4026,7 @@ has_privilege(void) #if defined HAVE_ISSETUGID if (issetugid()) - return 1; + return 1; #endif #ifdef HAVE_GETRESUID @@ -4087,7 +4087,7 @@ disable_child_handler_before_fork(struct child_handler_disabler_state *old) ret = pthread_sigmask(SIG_SETMASK, &all, &old->sigmask); /* not async-signal-safe */ if (ret != 0) { - rb_syserr_fail(ret, "pthread_sigmask"); + rb_syserr_fail(ret, "pthread_sigmask"); } #else # pragma GCC warning "pthread_sigmask on fork is not available. potentially dangerous" @@ -4102,7 +4102,7 @@ disable_child_handler_fork_parent(struct child_handler_disabler_state *old) ret = pthread_sigmask(SIG_SETMASK, &old->sigmask, NULL); /* not async-signal-safe */ if (ret != 0) { - rb_syserr_fail(ret, "pthread_sigmask"); + rb_syserr_fail(ret, "pthread_sigmask"); } #else # pragma GCC warning "pthread_sigmask on fork is not available. potentially dangerous" @@ -4117,24 +4117,24 @@ disable_child_handler_fork_child(struct child_handler_disabler_state *old, char int ret; for (sig = 1; sig < NSIG; sig++) { - sig_t handler = signal(sig, SIG_DFL); + sig_t handler = signal(sig, SIG_DFL); - if (handler == SIG_ERR && errno == EINVAL) { - continue; /* Ignore invalid signal number */ - } - if (handler == SIG_ERR) { - ERRMSG("signal to obtain old action"); - return -1; - } + if (handler == SIG_ERR && errno == EINVAL) { + continue; /* Ignore invalid signal number */ + } + if (handler == SIG_ERR) { + ERRMSG("signal to obtain old action"); + return -1; + } #ifdef SIGPIPE - if (sig == SIGPIPE) { - continue; - } + if (sig == SIGPIPE) { + continue; + } #endif - /* it will be reset to SIG_DFL at execve time, instead */ - if (handler == SIG_IGN) { - signal(sig, SIG_IGN); - } + /* it will be reset to SIG_DFL at execve time, instead */ + if (handler == SIG_IGN) { + signal(sig, SIG_IGN); + } } /* non-Ruby child process, ensure cmake can see SIGCHLD */ @@ -4199,11 +4199,11 @@ retry_fork_async_signal_safe(struct rb_process_status *status, int *ep, } rb_native_mutex_unlock(waitpid_lock); } - disable_child_handler_fork_parent(&old); + disable_child_handler_fork_parent(&old); if (0 < pid) /* fork succeed, parent process */ return pid; /* fork failed */ - if (handle_fork_error(err, status, ep, &try_gc)) + if (handle_fork_error(err, status, ep, &try_gc)) return -1; } } @@ -4360,7 +4360,7 @@ rb_proc__fork(VALUE _obj) rb_pid_t pid = rb_fork_ruby(NULL); if (pid == -1) { - rb_sys_fail("fork(2)"); + rb_sys_fail("fork(2)"); } return PIDT2NUM(pid); @@ -4399,12 +4399,12 @@ rb_f_fork(VALUE obj) pid = rb_call_proc__fork(); if (pid == 0) { - if (rb_block_given_p()) { - int status; - rb_protect(rb_yield, Qundef, &status); - ruby_stop(status); - } - return Qnil; + if (rb_block_given_p()) { + int status; + rb_protect(rb_yield, Qundef, &status); + ruby_stop(status); + } + return Qnil; } return PIDT2NUM(pid); @@ -4421,18 +4421,18 @@ exit_status_code(VALUE status) switch (status) { case Qtrue: - istatus = EXIT_SUCCESS; - break; + istatus = EXIT_SUCCESS; + break; case Qfalse: - istatus = EXIT_FAILURE; - break; + istatus = EXIT_FAILURE; + break; default: - istatus = NUM2INT(status); + istatus = NUM2INT(status); #if EXIT_SUCCESS != 0 - if (istatus == 0) - istatus = EXIT_SUCCESS; + if (istatus == 0) + istatus = EXIT_SUCCESS; #endif - break; + break; } return istatus; } @@ -4455,10 +4455,10 @@ rb_f_exit_bang(int argc, VALUE *argv, VALUE obj) int istatus; if (rb_check_arity(argc, 0, 1) == 1) { - istatus = exit_status_code(argv[0]); + istatus = exit_status_code(argv[0]); } else { - istatus = EXIT_FAILURE; + istatus = EXIT_FAILURE; } _exit(istatus); @@ -4469,11 +4469,11 @@ void rb_exit(int status) { if (GET_EC()->tag) { - VALUE args[2]; + VALUE args[2]; - args[0] = INT2NUM(status); - args[1] = rb_str_new2("exit"); - rb_exc_raise(rb_class_new_instance(2, args, rb_eSystemExit)); + args[0] = INT2NUM(status); + args[1] = rb_str_new2("exit"); + rb_exc_raise(rb_class_new_instance(2, args, rb_eSystemExit)); } ruby_stop(status); } @@ -4548,21 +4548,21 @@ rb_f_abort(int argc, const VALUE *argv) { rb_check_arity(argc, 0, 1); if (argc == 0) { - rb_execution_context_t *ec = GET_EC(); + rb_execution_context_t *ec = GET_EC(); VALUE errinfo = rb_ec_get_errinfo(ec); - if (!NIL_P(errinfo)) { - rb_ec_error_print(ec, errinfo); - } - rb_exit(EXIT_FAILURE); + if (!NIL_P(errinfo)) { + rb_ec_error_print(ec, errinfo); + } + rb_exit(EXIT_FAILURE); } else { - VALUE args[2]; + VALUE args[2]; - args[1] = args[0] = argv[0]; - StringValue(args[0]); - rb_io_puts(1, args, rb_ractor_stderr()); - args[0] = INT2NUM(EXIT_FAILURE); - rb_exc_raise(rb_class_new_instance(2, args, rb_eSystemExit)); + args[1] = args[0] = argv[0]; + StringValue(args[0]); + rb_io_puts(1, args, rb_ractor_stderr()); + args[0] = INT2NUM(EXIT_FAILURE); + rb_exc_raise(rb_class_new_instance(2, args, rb_eSystemExit)); } UNREACHABLE_RETURN(Qnil); @@ -4602,18 +4602,18 @@ rb_execarg_commandline(const struct rb_execarg *eargp, VALUE *prog) { VALUE cmd = *prog; if (eargp && !eargp->use_shell) { - VALUE str = eargp->invoke.cmd.argv_str; - VALUE buf = eargp->invoke.cmd.argv_buf; - char *p, **argv = ARGVSTR2ARGV(str); - long i, argc = ARGVSTR2ARGC(str); - const char *start = RSTRING_PTR(buf); - cmd = rb_str_new(start, RSTRING_LEN(buf)); - p = RSTRING_PTR(cmd); - for (i = 1; i < argc; ++i) { - p[argv[i] - start - 1] = ' '; - } - *prog = cmd; - return p; + VALUE str = eargp->invoke.cmd.argv_str; + VALUE buf = eargp->invoke.cmd.argv_buf; + char *p, **argv = ARGVSTR2ARGV(str); + long i, argc = ARGVSTR2ARGC(str); + const char *start = RSTRING_PTR(buf); + cmd = rb_str_new(start, RSTRING_LEN(buf)); + p = RSTRING_PTR(cmd); + for (i = 1; i < argc; ++i) { + p[argv[i] - start - 1] = ' '; + } + *prog = cmd; + return p; } return StringValueCStr(*prog); } @@ -4686,7 +4686,7 @@ do_spawn_process(VALUE arg) struct spawn_args *argp = (struct spawn_args *)arg; rb_execarg_parent_start1(argp->execarg); return (VALUE)rb_spawn_process(DATA_PTR(argp->execarg), - argp->errmsg.ptr, argp->errmsg.buflen); + argp->errmsg.ptr, argp->errmsg.buflen); } static rb_pid_t @@ -4707,7 +4707,7 @@ rb_execarg_spawn(VALUE execarg_obj, char *errmsg, size_t errmsg_buflen) args.errmsg.ptr = errmsg; args.errmsg.buflen = errmsg_buflen; return (rb_pid_t)rb_ensure(do_spawn_process, (VALUE)&args, - execarg_parent_end, execarg_obj); + execarg_parent_end, execarg_obj); } static rb_pid_t @@ -5131,10 +5131,10 @@ rb_f_spawn(int argc, VALUE *argv, VALUE _) pid = rb_execarg_spawn(execarg_obj, errmsg, sizeof(errmsg)); if (pid == -1) { - int err = errno; - rb_exec_fail(eargp, err, errmsg); - RB_GC_GUARD(execarg_obj); - rb_syserr_fail_str(err, fail_str); + int err = errno; + rb_exec_fail(eargp, err, errmsg); + RB_GC_GUARD(execarg_obj); + rb_syserr_fail_str(err, fail_str); } #if defined(HAVE_WORKING_FORK) || defined(HAVE_SPAWNV) return PIDT2NUM(pid); @@ -5315,7 +5315,7 @@ proc_getsid(int argc, VALUE *argv, VALUE _) rb_pid_t pid = 0; if (rb_check_arity(argc, 0, 1) == 1 && !NIL_P(argv[0])) - pid = NUM2PIDT(argv[0]); + pid = NUM2PIDT(argv[0]); sid = getsid(pid); if (sid < 0) rb_sys_fail(0); @@ -5373,8 +5373,8 @@ ruby_setsid(void) if ((fd = rb_cloexec_open("/dev/tty", O_RDWR, 0)) >= 0) { rb_update_max_fd(fd); - ioctl(fd, TIOCNOTTY, NULL); - close(fd); + ioctl(fd, TIOCNOTTY, NULL); + close(fd); } return pid; } @@ -5443,7 +5443,7 @@ proc_setpriority(VALUE obj, VALUE which, VALUE who, VALUE prio) iprio = NUM2INT(prio); if (setpriority(iwhich, iwho, iprio) < 0) - rb_sys_fail(0); + rb_sys_fail(0); return INT2FIX(0); } #else @@ -5583,7 +5583,7 @@ rlimit_type_by_sym(VALUE key) enum {prefix_len = sizeof(prefix)-1}; if (len > prefix_len && strncmp(prefix, rname, prefix_len) == 0) { - rtype = rlimit_type_by_lname(rname + prefix_len, len - prefix_len); + rtype = rlimit_type_by_lname(rname + prefix_len, len - prefix_len); } RB_GC_GUARD(key); @@ -5600,9 +5600,9 @@ rlimit_resource_type(VALUE rtype) switch (TYPE(rtype)) { case T_SYMBOL: - v = rb_sym2str(rtype); - name = RSTRING_PTR(v); - len = RSTRING_LEN(v); + v = rb_sym2str(rtype); + name = RSTRING_PTR(v); + len = RSTRING_LEN(v); break; default: @@ -5611,7 +5611,7 @@ rlimit_resource_type(VALUE rtype) rtype = v; case T_STRING: name = StringValueCStr(rtype); - len = RSTRING_LEN(rtype); + len = RSTRING_LEN(rtype); break; } /* fall through */ @@ -5638,8 +5638,8 @@ rlimit_resource_value(VALUE rval) switch (TYPE(rval)) { case T_SYMBOL: - v = rb_sym2str(rval); - name = RSTRING_PTR(v); + v = rb_sym2str(rval); + name = RSTRING_PTR(v); break; default: @@ -5699,7 +5699,7 @@ proc_getrlimit(VALUE obj, VALUE resource) struct rlimit rlim; if (getrlimit(rlimit_resource_type(resource), &rlim) < 0) { - rb_sys_fail("getrlimit"); + rb_sys_fail("getrlimit"); } return rb_assoc_new(RLIM2NUM(rlim.rlim_cur), RLIM2NUM(rlim.rlim_max)); } @@ -5775,7 +5775,7 @@ proc_setrlimit(int argc, VALUE *argv, VALUE obj) rlim.rlim_max = rlimit_resource_value(rlim_max); if (setrlimit(rlimit_resource_type(resource), &rlim) < 0) { - rb_sys_fail("setrlimit"); + rb_sys_fail("setrlimit"); } return Qnil; } @@ -5788,7 +5788,7 @@ static void check_uid_switch(void) { if (under_uid_switch) { - rb_raise(rb_eRuntimeError, "can't handle UID while evaluating block given to Process::UID.switch method"); + rb_raise(rb_eRuntimeError, "can't handle UID while evaluating block given to Process::UID.switch method"); } } @@ -5797,7 +5797,7 @@ static void check_gid_switch(void) { if (under_gid_switch) { - rb_raise(rb_eRuntimeError, "can't handle GID while evaluating block given to Process::UID.switch method"); + rb_raise(rb_eRuntimeError, "can't handle GID while evaluating block given to Process::UID.switch method"); } } @@ -6056,7 +6056,7 @@ rb_getpwdiruid(void) static rb_uid_t obj2uid(VALUE id # ifdef USE_GETPWNAM_R - , VALUE *getpw_tmp + , VALUE *getpw_tmp # endif ) { @@ -6064,46 +6064,46 @@ obj2uid(VALUE id VALUE tmp; if (FIXNUM_P(id) || NIL_P(tmp = rb_check_string_type(id))) { - uid = NUM2UIDT(id); + uid = NUM2UIDT(id); } else { - const char *usrname = StringValueCStr(id); - struct passwd *pwptr; + const char *usrname = StringValueCStr(id); + struct passwd *pwptr; #ifdef USE_GETPWNAM_R - struct passwd pwbuf; - char *getpw_buf; - long getpw_buf_len; - int e; - if (!*getpw_tmp) { - getpw_buf_len = GETPW_R_SIZE_INIT; - if (getpw_buf_len < 0) getpw_buf_len = GETPW_R_SIZE_DEFAULT; - *getpw_tmp = rb_str_tmp_new(getpw_buf_len); - } - getpw_buf = RSTRING_PTR(*getpw_tmp); - getpw_buf_len = rb_str_capacity(*getpw_tmp); - rb_str_set_len(*getpw_tmp, getpw_buf_len); - errno = 0; - while ((e = getpwnam_r(usrname, &pwbuf, getpw_buf, getpw_buf_len, &pwptr)) != 0) { - if (e != ERANGE || getpw_buf_len >= GETPW_R_SIZE_LIMIT) { - rb_str_resize(*getpw_tmp, 0); - rb_syserr_fail(e, "getpwnam_r"); - } - rb_str_modify_expand(*getpw_tmp, getpw_buf_len); - getpw_buf = RSTRING_PTR(*getpw_tmp); - getpw_buf_len = rb_str_capacity(*getpw_tmp); - } + struct passwd pwbuf; + char *getpw_buf; + long getpw_buf_len; + int e; + if (!*getpw_tmp) { + getpw_buf_len = GETPW_R_SIZE_INIT; + if (getpw_buf_len < 0) getpw_buf_len = GETPW_R_SIZE_DEFAULT; + *getpw_tmp = rb_str_tmp_new(getpw_buf_len); + } + getpw_buf = RSTRING_PTR(*getpw_tmp); + getpw_buf_len = rb_str_capacity(*getpw_tmp); + rb_str_set_len(*getpw_tmp, getpw_buf_len); + errno = 0; + while ((e = getpwnam_r(usrname, &pwbuf, getpw_buf, getpw_buf_len, &pwptr)) != 0) { + if (e != ERANGE || getpw_buf_len >= GETPW_R_SIZE_LIMIT) { + rb_str_resize(*getpw_tmp, 0); + rb_syserr_fail(e, "getpwnam_r"); + } + rb_str_modify_expand(*getpw_tmp, getpw_buf_len); + getpw_buf = RSTRING_PTR(*getpw_tmp); + getpw_buf_len = rb_str_capacity(*getpw_tmp); + } #else - pwptr = getpwnam(usrname); + pwptr = getpwnam(usrname); #endif - if (!pwptr) { + if (!pwptr) { #ifndef USE_GETPWNAM_R - endpwent(); + endpwent(); #endif rb_raise(rb_eArgError, "can't find user for %"PRIsVALUE, id); - } - uid = pwptr->pw_uid; + } + uid = pwptr->pw_uid; #ifndef USE_GETPWNAM_R - endpwent(); + endpwent(); #endif } return uid; @@ -6133,7 +6133,7 @@ p_uid_from_name(VALUE self, VALUE id) static rb_gid_t obj2gid(VALUE id # ifdef USE_GETGRNAM_R - , VALUE *getgr_tmp + , VALUE *getgr_tmp # endif ) { @@ -6141,48 +6141,48 @@ obj2gid(VALUE id VALUE tmp; if (FIXNUM_P(id) || NIL_P(tmp = rb_check_string_type(id))) { - gid = NUM2GIDT(id); + gid = NUM2GIDT(id); } else { - const char *grpname = StringValueCStr(id); - struct group *grptr; + const char *grpname = StringValueCStr(id); + struct group *grptr; #ifdef USE_GETGRNAM_R - struct group grbuf; - char *getgr_buf; - long getgr_buf_len; - int e; - if (!*getgr_tmp) { - getgr_buf_len = GETGR_R_SIZE_INIT; - if (getgr_buf_len < 0) getgr_buf_len = GETGR_R_SIZE_DEFAULT; - *getgr_tmp = rb_str_tmp_new(getgr_buf_len); - } - getgr_buf = RSTRING_PTR(*getgr_tmp); - getgr_buf_len = rb_str_capacity(*getgr_tmp); - rb_str_set_len(*getgr_tmp, getgr_buf_len); - errno = 0; - while ((e = getgrnam_r(grpname, &grbuf, getgr_buf, getgr_buf_len, &grptr)) != 0) { - if (e != ERANGE || getgr_buf_len >= GETGR_R_SIZE_LIMIT) { - rb_str_resize(*getgr_tmp, 0); - rb_syserr_fail(e, "getgrnam_r"); - } - rb_str_modify_expand(*getgr_tmp, getgr_buf_len); - getgr_buf = RSTRING_PTR(*getgr_tmp); - getgr_buf_len = rb_str_capacity(*getgr_tmp); - } + struct group grbuf; + char *getgr_buf; + long getgr_buf_len; + int e; + if (!*getgr_tmp) { + getgr_buf_len = GETGR_R_SIZE_INIT; + if (getgr_buf_len < 0) getgr_buf_len = GETGR_R_SIZE_DEFAULT; + *getgr_tmp = rb_str_tmp_new(getgr_buf_len); + } + getgr_buf = RSTRING_PTR(*getgr_tmp); + getgr_buf_len = rb_str_capacity(*getgr_tmp); + rb_str_set_len(*getgr_tmp, getgr_buf_len); + errno = 0; + while ((e = getgrnam_r(grpname, &grbuf, getgr_buf, getgr_buf_len, &grptr)) != 0) { + if (e != ERANGE || getgr_buf_len >= GETGR_R_SIZE_LIMIT) { + rb_str_resize(*getgr_tmp, 0); + rb_syserr_fail(e, "getgrnam_r"); + } + rb_str_modify_expand(*getgr_tmp, getgr_buf_len); + getgr_buf = RSTRING_PTR(*getgr_tmp); + getgr_buf_len = rb_str_capacity(*getgr_tmp); + } #elif defined(HAVE_GETGRNAM) - grptr = getgrnam(grpname); + grptr = getgrnam(grpname); #else - grptr = NULL; + grptr = NULL; #endif - if (!grptr) { + if (!grptr) { #if !defined(USE_GETGRNAM_R) && defined(HAVE_ENDGRENT) - endgrent(); + endgrent(); #endif rb_raise(rb_eArgError, "can't find group for %"PRIsVALUE, id); - } - gid = grptr->gr_gid; + } + gid = grptr->gr_gid; #if !defined(USE_GETGRNAM_R) && defined(HAVE_ENDGRENT) - endgrent(); + endgrent(); #endif } return gid; @@ -6377,12 +6377,12 @@ proc_setuid(VALUE obj, VALUE id) if (setruid(uid) < 0) rb_sys_fail(0); #elif defined HAVE_SETUID { - if (geteuid() == uid) { - if (setuid(uid) < 0) rb_sys_fail(0); - } - else { - rb_notimplement(); - } + if (geteuid() == uid) { + if (setuid(uid) < 0) rb_sys_fail(0); + } + else { + rb_notimplement(); + } } #endif return id; @@ -6409,11 +6409,11 @@ int setreuid(rb_uid_t ruid, rb_uid_t euid) { if (ruid != (rb_uid_t)-1 && ruid != getuid()) { - if (euid == (rb_uid_t)-1) euid = geteuid(); - if (setuid(ruid) < 0) return -1; + if (euid == (rb_uid_t)-1) euid = geteuid(); + if (setuid(ruid) < 0) return -1; } if (euid != (rb_uid_t)-1 && euid != geteuid()) { - if (seteuid(euid) < 0) return -1; + if (seteuid(euid) < 0) return -1; } return 0; } @@ -6443,144 +6443,144 @@ p_uid_change_privilege(VALUE obj, VALUE id) if (geteuid() == 0) { /* root-user */ #if defined(HAVE_SETRESUID) - if (setresuid(uid, uid, uid) < 0) rb_sys_fail(0); - SAVED_USER_ID = uid; + if (setresuid(uid, uid, uid) < 0) rb_sys_fail(0); + SAVED_USER_ID = uid; #elif defined(HAVE_SETUID) - if (setuid(uid) < 0) rb_sys_fail(0); - SAVED_USER_ID = uid; + if (setuid(uid) < 0) rb_sys_fail(0); + SAVED_USER_ID = uid; #elif defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID) - if (getuid() == uid) { - if (SAVED_USER_ID == uid) { - if (setreuid(-1, uid) < 0) rb_sys_fail(0); - } - else { - if (uid == 0) { /* (r,e,s) == (root, root, x) */ - if (setreuid(-1, SAVED_USER_ID) < 0) rb_sys_fail(0); - if (setreuid(SAVED_USER_ID, 0) < 0) rb_sys_fail(0); - SAVED_USER_ID = 0; /* (r,e,s) == (x, root, root) */ - if (setreuid(uid, uid) < 0) rb_sys_fail(0); - SAVED_USER_ID = uid; - } - else { - if (setreuid(0, -1) < 0) rb_sys_fail(0); - SAVED_USER_ID = 0; - if (setreuid(uid, uid) < 0) rb_sys_fail(0); - SAVED_USER_ID = uid; - } - } - } - else { - if (setreuid(uid, uid) < 0) rb_sys_fail(0); - SAVED_USER_ID = uid; - } + if (getuid() == uid) { + if (SAVED_USER_ID == uid) { + if (setreuid(-1, uid) < 0) rb_sys_fail(0); + } + else { + if (uid == 0) { /* (r,e,s) == (root, root, x) */ + if (setreuid(-1, SAVED_USER_ID) < 0) rb_sys_fail(0); + if (setreuid(SAVED_USER_ID, 0) < 0) rb_sys_fail(0); + SAVED_USER_ID = 0; /* (r,e,s) == (x, root, root) */ + if (setreuid(uid, uid) < 0) rb_sys_fail(0); + SAVED_USER_ID = uid; + } + else { + if (setreuid(0, -1) < 0) rb_sys_fail(0); + SAVED_USER_ID = 0; + if (setreuid(uid, uid) < 0) rb_sys_fail(0); + SAVED_USER_ID = uid; + } + } + } + else { + if (setreuid(uid, uid) < 0) rb_sys_fail(0); + SAVED_USER_ID = uid; + } #elif defined(HAVE_SETRUID) && defined(HAVE_SETEUID) - if (getuid() == uid) { - if (SAVED_USER_ID == uid) { - if (seteuid(uid) < 0) rb_sys_fail(0); - } - else { - if (uid == 0) { - if (setruid(SAVED_USER_ID) < 0) rb_sys_fail(0); - SAVED_USER_ID = 0; - if (setruid(0) < 0) rb_sys_fail(0); - } - else { - if (setruid(0) < 0) rb_sys_fail(0); - SAVED_USER_ID = 0; - if (seteuid(uid) < 0) rb_sys_fail(0); - if (setruid(uid) < 0) rb_sys_fail(0); - SAVED_USER_ID = uid; - } - } - } - else { - if (seteuid(uid) < 0) rb_sys_fail(0); - if (setruid(uid) < 0) rb_sys_fail(0); - SAVED_USER_ID = uid; - } + if (getuid() == uid) { + if (SAVED_USER_ID == uid) { + if (seteuid(uid) < 0) rb_sys_fail(0); + } + else { + if (uid == 0) { + if (setruid(SAVED_USER_ID) < 0) rb_sys_fail(0); + SAVED_USER_ID = 0; + if (setruid(0) < 0) rb_sys_fail(0); + } + else { + if (setruid(0) < 0) rb_sys_fail(0); + SAVED_USER_ID = 0; + if (seteuid(uid) < 0) rb_sys_fail(0); + if (setruid(uid) < 0) rb_sys_fail(0); + SAVED_USER_ID = uid; + } + } + } + else { + if (seteuid(uid) < 0) rb_sys_fail(0); + if (setruid(uid) < 0) rb_sys_fail(0); + SAVED_USER_ID = uid; + } #else - (void)uid; - rb_notimplement(); + (void)uid; + rb_notimplement(); #endif } else { /* unprivileged user */ #if defined(HAVE_SETRESUID) - if (setresuid((getuid() == uid)? (rb_uid_t)-1: uid, - (geteuid() == uid)? (rb_uid_t)-1: uid, - (SAVED_USER_ID == uid)? (rb_uid_t)-1: uid) < 0) rb_sys_fail(0); - SAVED_USER_ID = uid; + if (setresuid((getuid() == uid)? (rb_uid_t)-1: uid, + (geteuid() == uid)? (rb_uid_t)-1: uid, + (SAVED_USER_ID == uid)? (rb_uid_t)-1: uid) < 0) rb_sys_fail(0); + SAVED_USER_ID = uid; #elif defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID) - if (SAVED_USER_ID == uid) { - if (setreuid((getuid() == uid)? (rb_uid_t)-1: uid, - (geteuid() == uid)? (rb_uid_t)-1: uid) < 0) - rb_sys_fail(0); - } - else if (getuid() != uid) { - if (setreuid(uid, (geteuid() == uid)? (rb_uid_t)-1: uid) < 0) - rb_sys_fail(0); - SAVED_USER_ID = uid; - } - else if (/* getuid() == uid && */ geteuid() != uid) { - if (setreuid(geteuid(), uid) < 0) rb_sys_fail(0); - SAVED_USER_ID = uid; - if (setreuid(uid, -1) < 0) rb_sys_fail(0); - } - else { /* getuid() == uid && geteuid() == uid */ - if (setreuid(-1, SAVED_USER_ID) < 0) rb_sys_fail(0); - if (setreuid(SAVED_USER_ID, uid) < 0) rb_sys_fail(0); - SAVED_USER_ID = uid; - if (setreuid(uid, -1) < 0) rb_sys_fail(0); - } + if (SAVED_USER_ID == uid) { + if (setreuid((getuid() == uid)? (rb_uid_t)-1: uid, + (geteuid() == uid)? (rb_uid_t)-1: uid) < 0) + rb_sys_fail(0); + } + else if (getuid() != uid) { + if (setreuid(uid, (geteuid() == uid)? (rb_uid_t)-1: uid) < 0) + rb_sys_fail(0); + SAVED_USER_ID = uid; + } + else if (/* getuid() == uid && */ geteuid() != uid) { + if (setreuid(geteuid(), uid) < 0) rb_sys_fail(0); + SAVED_USER_ID = uid; + if (setreuid(uid, -1) < 0) rb_sys_fail(0); + } + else { /* getuid() == uid && geteuid() == uid */ + if (setreuid(-1, SAVED_USER_ID) < 0) rb_sys_fail(0); + if (setreuid(SAVED_USER_ID, uid) < 0) rb_sys_fail(0); + SAVED_USER_ID = uid; + if (setreuid(uid, -1) < 0) rb_sys_fail(0); + } #elif defined(HAVE_SETRUID) && defined(HAVE_SETEUID) - if (SAVED_USER_ID == uid) { - if (geteuid() != uid && seteuid(uid) < 0) rb_sys_fail(0); - if (getuid() != uid && setruid(uid) < 0) rb_sys_fail(0); - } - else if (/* SAVED_USER_ID != uid && */ geteuid() == uid) { - if (getuid() != uid) { - if (setruid(uid) < 0) rb_sys_fail(0); - SAVED_USER_ID = uid; - } - else { - if (setruid(SAVED_USER_ID) < 0) rb_sys_fail(0); - SAVED_USER_ID = uid; - if (setruid(uid) < 0) rb_sys_fail(0); - } - } - else if (/* geteuid() != uid && */ getuid() == uid) { - if (seteuid(uid) < 0) rb_sys_fail(0); - if (setruid(SAVED_USER_ID) < 0) rb_sys_fail(0); - SAVED_USER_ID = uid; - if (setruid(uid) < 0) rb_sys_fail(0); - } - else { - rb_syserr_fail(EPERM, 0); - } + if (SAVED_USER_ID == uid) { + if (geteuid() != uid && seteuid(uid) < 0) rb_sys_fail(0); + if (getuid() != uid && setruid(uid) < 0) rb_sys_fail(0); + } + else if (/* SAVED_USER_ID != uid && */ geteuid() == uid) { + if (getuid() != uid) { + if (setruid(uid) < 0) rb_sys_fail(0); + SAVED_USER_ID = uid; + } + else { + if (setruid(SAVED_USER_ID) < 0) rb_sys_fail(0); + SAVED_USER_ID = uid; + if (setruid(uid) < 0) rb_sys_fail(0); + } + } + else if (/* geteuid() != uid && */ getuid() == uid) { + if (seteuid(uid) < 0) rb_sys_fail(0); + if (setruid(SAVED_USER_ID) < 0) rb_sys_fail(0); + SAVED_USER_ID = uid; + if (setruid(uid) < 0) rb_sys_fail(0); + } + else { + rb_syserr_fail(EPERM, 0); + } #elif defined HAVE_44BSD_SETUID - if (getuid() == uid) { - /* (r,e,s)==(uid,?,?) ==> (uid,uid,uid) */ - if (setuid(uid) < 0) rb_sys_fail(0); - SAVED_USER_ID = uid; - } - else { - rb_syserr_fail(EPERM, 0); - } + if (getuid() == uid) { + /* (r,e,s)==(uid,?,?) ==> (uid,uid,uid) */ + if (setuid(uid) < 0) rb_sys_fail(0); + SAVED_USER_ID = uid; + } + else { + rb_syserr_fail(EPERM, 0); + } #elif defined HAVE_SETEUID - if (getuid() == uid && SAVED_USER_ID == uid) { - if (seteuid(uid) < 0) rb_sys_fail(0); - } - else { - rb_syserr_fail(EPERM, 0); - } + if (getuid() == uid && SAVED_USER_ID == uid) { + if (seteuid(uid) < 0) rb_sys_fail(0); + } + else { + rb_syserr_fail(EPERM, 0); + } #elif defined HAVE_SETUID - if (getuid() == uid && SAVED_USER_ID == uid) { - if (setuid(uid) < 0) rb_sys_fail(0); - } - else { - rb_syserr_fail(EPERM, 0); - } + if (getuid() == uid && SAVED_USER_ID == uid) { + if (setuid(uid) < 0) rb_sys_fail(0); + } + else { + rb_syserr_fail(EPERM, 0); + } #else - rb_notimplement(); + rb_notimplement(); #endif } return id; @@ -6774,12 +6774,12 @@ proc_setgid(VALUE obj, VALUE id) if (setrgid(gid) < 0) rb_sys_fail(0); #elif defined HAVE_SETGID { - if (getegid() == gid) { - if (setgid(gid) < 0) rb_sys_fail(0); - } - else { - rb_notimplement(); - } + if (getegid() == gid) { + if (setgid(gid) < 0) rb_sys_fail(0); + } + else { + rb_notimplement(); + } } #endif return GIDT2NUM(gid); @@ -6825,9 +6825,9 @@ static int maxgroups(void) { if (_maxgroups < 0) { - _maxgroups = get_sc_ngroups_max(); - if (_maxgroups < 0) - _maxgroups = RB_MAX_GROUPS; + _maxgroups = get_sc_ngroups_max(); + if (_maxgroups < 0) + _maxgroups = RB_MAX_GROUPS; } return _maxgroups; @@ -6871,17 +6871,17 @@ proc_getgroups(VALUE obj) ngroups = getgroups(0, NULL); if (ngroups == -1) - rb_sys_fail(0); + rb_sys_fail(0); groups = ALLOCV_N(rb_gid_t, tmp, ngroups); ngroups = getgroups(ngroups, groups); if (ngroups == -1) - rb_sys_fail(0); + rb_sys_fail(0); ary = rb_ary_new(); for (i = 0; i < ngroups; i++) - rb_ary_push(ary, GIDT2NUM(groups[i])); + rb_ary_push(ary, GIDT2NUM(groups[i])); ALLOCV_END(tmp); @@ -6918,19 +6918,19 @@ proc_setgroups(VALUE obj, VALUE ary) ngroups = RARRAY_LENINT(ary); if (ngroups > maxgroups()) - rb_raise(rb_eArgError, "too many groups, %d max", maxgroups()); + rb_raise(rb_eArgError, "too many groups, %d max", maxgroups()); groups = ALLOCV_N(rb_gid_t, tmp, ngroups); for (i = 0; i < ngroups; i++) { - VALUE g = RARRAY_AREF(ary, i); + VALUE g = RARRAY_AREF(ary, i); - groups[i] = OBJ2GID1(g); + groups[i] = OBJ2GID1(g); } FINISH_GETGRNAM; if (setgroups(ngroups, groups) == -1) /* ngroups <= maxgroups */ - rb_sys_fail(0); + rb_sys_fail(0); ALLOCV_END(tmp); @@ -6963,7 +6963,7 @@ static VALUE proc_initgroups(VALUE obj, VALUE uname, VALUE base_grp) { if (initgroups(StringValueCStr(uname), OBJ2GID(base_grp)) != 0) { - rb_sys_fail(0); + rb_sys_fail(0); } return proc_getgroups(obj); } @@ -7007,13 +7007,13 @@ proc_setmaxgroups(VALUE obj, VALUE val) int ngroups_max = get_sc_ngroups_max(); if (ngroups <= 0) - rb_raise(rb_eArgError, "maxgroups %d should be positive", ngroups); + rb_raise(rb_eArgError, "maxgroups %d should be positive", ngroups); if (ngroups > RB_MAX_GROUPS) - ngroups = RB_MAX_GROUPS; + ngroups = RB_MAX_GROUPS; if (ngroups_max > 0 && ngroups > ngroups_max) - ngroups = ngroups_max; + ngroups = ngroups_max; _maxgroups = ngroups; @@ -7084,15 +7084,15 @@ rb_daemon(int nochdir, int noclose) fork_daemon(); if (!nochdir) - err = chdir("/"); + err = chdir("/"); if (!noclose && (n = rb_cloexec_open("/dev/null", O_RDWR, 0)) != -1) { rb_update_max_fd(n); - (void)dup2(n, 0); - (void)dup2(n, 1); - (void)dup2(n, 2); - if (n > 2) - (void)close (n); + (void)dup2(n, 0); + (void)dup2(n, 1); + (void)dup2(n, 2); + if (n > 2) + (void)close (n); } #endif return err; @@ -7118,11 +7118,11 @@ int setregid(rb_gid_t rgid, rb_gid_t egid) { if (rgid != (rb_gid_t)-1 && rgid != getgid()) { - if (egid == (rb_gid_t)-1) egid = getegid(); - if (setgid(rgid) < 0) return -1; + if (egid == (rb_gid_t)-1) egid = getegid(); + if (setgid(rgid) < 0) return -1; } if (egid != (rb_gid_t)-1 && egid != getegid()) { - if (setegid(egid) < 0) return -1; + if (setegid(egid) < 0) return -1; } return 0; } @@ -7152,145 +7152,145 @@ p_gid_change_privilege(VALUE obj, VALUE id) if (geteuid() == 0) { /* root-user */ #if defined(HAVE_SETRESGID) - if (setresgid(gid, gid, gid) < 0) rb_sys_fail(0); - SAVED_GROUP_ID = gid; + if (setresgid(gid, gid, gid) < 0) rb_sys_fail(0); + SAVED_GROUP_ID = gid; #elif defined HAVE_SETGID - if (setgid(gid) < 0) rb_sys_fail(0); - SAVED_GROUP_ID = gid; + if (setgid(gid) < 0) rb_sys_fail(0); + SAVED_GROUP_ID = gid; #elif defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID) - if (getgid() == gid) { - if (SAVED_GROUP_ID == gid) { - if (setregid(-1, gid) < 0) rb_sys_fail(0); - } - else { - if (gid == 0) { /* (r,e,s) == (root, y, x) */ - if (setregid(-1, SAVED_GROUP_ID) < 0) rb_sys_fail(0); - if (setregid(SAVED_GROUP_ID, 0) < 0) rb_sys_fail(0); - SAVED_GROUP_ID = 0; /* (r,e,s) == (x, root, root) */ - if (setregid(gid, gid) < 0) rb_sys_fail(0); - SAVED_GROUP_ID = gid; - } - else { /* (r,e,s) == (z, y, x) */ - if (setregid(0, 0) < 0) rb_sys_fail(0); - SAVED_GROUP_ID = 0; - if (setregid(gid, gid) < 0) rb_sys_fail(0); - SAVED_GROUP_ID = gid; - } - } - } - else { - if (setregid(gid, gid) < 0) rb_sys_fail(0); - SAVED_GROUP_ID = gid; - } + if (getgid() == gid) { + if (SAVED_GROUP_ID == gid) { + if (setregid(-1, gid) < 0) rb_sys_fail(0); + } + else { + if (gid == 0) { /* (r,e,s) == (root, y, x) */ + if (setregid(-1, SAVED_GROUP_ID) < 0) rb_sys_fail(0); + if (setregid(SAVED_GROUP_ID, 0) < 0) rb_sys_fail(0); + SAVED_GROUP_ID = 0; /* (r,e,s) == (x, root, root) */ + if (setregid(gid, gid) < 0) rb_sys_fail(0); + SAVED_GROUP_ID = gid; + } + else { /* (r,e,s) == (z, y, x) */ + if (setregid(0, 0) < 0) rb_sys_fail(0); + SAVED_GROUP_ID = 0; + if (setregid(gid, gid) < 0) rb_sys_fail(0); + SAVED_GROUP_ID = gid; + } + } + } + else { + if (setregid(gid, gid) < 0) rb_sys_fail(0); + SAVED_GROUP_ID = gid; + } #elif defined(HAVE_SETRGID) && defined (HAVE_SETEGID) - if (getgid() == gid) { - if (SAVED_GROUP_ID == gid) { - if (setegid(gid) < 0) rb_sys_fail(0); - } - else { - if (gid == 0) { - if (setegid(gid) < 0) rb_sys_fail(0); - if (setrgid(SAVED_GROUP_ID) < 0) rb_sys_fail(0); - SAVED_GROUP_ID = 0; - if (setrgid(0) < 0) rb_sys_fail(0); - } - else { - if (setrgid(0) < 0) rb_sys_fail(0); - SAVED_GROUP_ID = 0; - if (setegid(gid) < 0) rb_sys_fail(0); - if (setrgid(gid) < 0) rb_sys_fail(0); - SAVED_GROUP_ID = gid; - } - } - } - else { - if (setegid(gid) < 0) rb_sys_fail(0); - if (setrgid(gid) < 0) rb_sys_fail(0); - SAVED_GROUP_ID = gid; - } + if (getgid() == gid) { + if (SAVED_GROUP_ID == gid) { + if (setegid(gid) < 0) rb_sys_fail(0); + } + else { + if (gid == 0) { + if (setegid(gid) < 0) rb_sys_fail(0); + if (setrgid(SAVED_GROUP_ID) < 0) rb_sys_fail(0); + SAVED_GROUP_ID = 0; + if (setrgid(0) < 0) rb_sys_fail(0); + } + else { + if (setrgid(0) < 0) rb_sys_fail(0); + SAVED_GROUP_ID = 0; + if (setegid(gid) < 0) rb_sys_fail(0); + if (setrgid(gid) < 0) rb_sys_fail(0); + SAVED_GROUP_ID = gid; + } + } + } + else { + if (setegid(gid) < 0) rb_sys_fail(0); + if (setrgid(gid) < 0) rb_sys_fail(0); + SAVED_GROUP_ID = gid; + } #else - rb_notimplement(); + rb_notimplement(); #endif } else { /* unprivileged user */ #if defined(HAVE_SETRESGID) - if (setresgid((getgid() == gid)? (rb_gid_t)-1: gid, - (getegid() == gid)? (rb_gid_t)-1: gid, - (SAVED_GROUP_ID == gid)? (rb_gid_t)-1: gid) < 0) rb_sys_fail(0); - SAVED_GROUP_ID = gid; + if (setresgid((getgid() == gid)? (rb_gid_t)-1: gid, + (getegid() == gid)? (rb_gid_t)-1: gid, + (SAVED_GROUP_ID == gid)? (rb_gid_t)-1: gid) < 0) rb_sys_fail(0); + SAVED_GROUP_ID = gid; #elif defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID) - if (SAVED_GROUP_ID == gid) { - if (setregid((getgid() == gid)? (rb_uid_t)-1: gid, - (getegid() == gid)? (rb_uid_t)-1: gid) < 0) - rb_sys_fail(0); - } - else if (getgid() != gid) { - if (setregid(gid, (getegid() == gid)? (rb_uid_t)-1: gid) < 0) - rb_sys_fail(0); - SAVED_GROUP_ID = gid; - } - else if (/* getgid() == gid && */ getegid() != gid) { - if (setregid(getegid(), gid) < 0) rb_sys_fail(0); - SAVED_GROUP_ID = gid; - if (setregid(gid, -1) < 0) rb_sys_fail(0); - } - else { /* getgid() == gid && getegid() == gid */ - if (setregid(-1, SAVED_GROUP_ID) < 0) rb_sys_fail(0); - if (setregid(SAVED_GROUP_ID, gid) < 0) rb_sys_fail(0); - SAVED_GROUP_ID = gid; - if (setregid(gid, -1) < 0) rb_sys_fail(0); - } + if (SAVED_GROUP_ID == gid) { + if (setregid((getgid() == gid)? (rb_uid_t)-1: gid, + (getegid() == gid)? (rb_uid_t)-1: gid) < 0) + rb_sys_fail(0); + } + else if (getgid() != gid) { + if (setregid(gid, (getegid() == gid)? (rb_uid_t)-1: gid) < 0) + rb_sys_fail(0); + SAVED_GROUP_ID = gid; + } + else if (/* getgid() == gid && */ getegid() != gid) { + if (setregid(getegid(), gid) < 0) rb_sys_fail(0); + SAVED_GROUP_ID = gid; + if (setregid(gid, -1) < 0) rb_sys_fail(0); + } + else { /* getgid() == gid && getegid() == gid */ + if (setregid(-1, SAVED_GROUP_ID) < 0) rb_sys_fail(0); + if (setregid(SAVED_GROUP_ID, gid) < 0) rb_sys_fail(0); + SAVED_GROUP_ID = gid; + if (setregid(gid, -1) < 0) rb_sys_fail(0); + } #elif defined(HAVE_SETRGID) && defined(HAVE_SETEGID) - if (SAVED_GROUP_ID == gid) { - if (getegid() != gid && setegid(gid) < 0) rb_sys_fail(0); - if (getgid() != gid && setrgid(gid) < 0) rb_sys_fail(0); - } - else if (/* SAVED_GROUP_ID != gid && */ getegid() == gid) { - if (getgid() != gid) { - if (setrgid(gid) < 0) rb_sys_fail(0); - SAVED_GROUP_ID = gid; - } - else { - if (setrgid(SAVED_GROUP_ID) < 0) rb_sys_fail(0); - SAVED_GROUP_ID = gid; - if (setrgid(gid) < 0) rb_sys_fail(0); - } - } - else if (/* getegid() != gid && */ getgid() == gid) { - if (setegid(gid) < 0) rb_sys_fail(0); - if (setrgid(SAVED_GROUP_ID) < 0) rb_sys_fail(0); - SAVED_GROUP_ID = gid; - if (setrgid(gid) < 0) rb_sys_fail(0); - } - else { - rb_syserr_fail(EPERM, 0); - } + if (SAVED_GROUP_ID == gid) { + if (getegid() != gid && setegid(gid) < 0) rb_sys_fail(0); + if (getgid() != gid && setrgid(gid) < 0) rb_sys_fail(0); + } + else if (/* SAVED_GROUP_ID != gid && */ getegid() == gid) { + if (getgid() != gid) { + if (setrgid(gid) < 0) rb_sys_fail(0); + SAVED_GROUP_ID = gid; + } + else { + if (setrgid(SAVED_GROUP_ID) < 0) rb_sys_fail(0); + SAVED_GROUP_ID = gid; + if (setrgid(gid) < 0) rb_sys_fail(0); + } + } + else if (/* getegid() != gid && */ getgid() == gid) { + if (setegid(gid) < 0) rb_sys_fail(0); + if (setrgid(SAVED_GROUP_ID) < 0) rb_sys_fail(0); + SAVED_GROUP_ID = gid; + if (setrgid(gid) < 0) rb_sys_fail(0); + } + else { + rb_syserr_fail(EPERM, 0); + } #elif defined HAVE_44BSD_SETGID - if (getgid() == gid) { - /* (r,e,s)==(gid,?,?) ==> (gid,gid,gid) */ - if (setgid(gid) < 0) rb_sys_fail(0); - SAVED_GROUP_ID = gid; - } - else { - rb_syserr_fail(EPERM, 0); - } + if (getgid() == gid) { + /* (r,e,s)==(gid,?,?) ==> (gid,gid,gid) */ + if (setgid(gid) < 0) rb_sys_fail(0); + SAVED_GROUP_ID = gid; + } + else { + rb_syserr_fail(EPERM, 0); + } #elif defined HAVE_SETEGID - if (getgid() == gid && SAVED_GROUP_ID == gid) { - if (setegid(gid) < 0) rb_sys_fail(0); - } - else { - rb_syserr_fail(EPERM, 0); - } + if (getgid() == gid && SAVED_GROUP_ID == gid) { + if (setegid(gid) < 0) rb_sys_fail(0); + } + else { + rb_syserr_fail(EPERM, 0); + } #elif defined HAVE_SETGID - if (getgid() == gid && SAVED_GROUP_ID == gid) { - if (setgid(gid) < 0) rb_sys_fail(0); - } - else { - rb_syserr_fail(EPERM, 0); - } + if (getgid() == gid && SAVED_GROUP_ID == gid) { + if (setgid(gid) < 0) rb_sys_fail(0); + } + else { + rb_syserr_fail(EPERM, 0); + } #else - (void)gid; - rb_notimplement(); + (void)gid; + rb_notimplement(); #endif } return id; @@ -7327,10 +7327,10 @@ proc_seteuid(rb_uid_t uid) if (seteuid(uid) < 0) rb_sys_fail(0); #elif defined HAVE_SETUID if (uid == getuid()) { - if (setuid(uid) < 0) rb_sys_fail(0); + if (setuid(uid) < 0) rb_sys_fail(0); } else { - rb_notimplement(); + rb_notimplement(); } #else rb_notimplement(); @@ -7373,18 +7373,18 @@ rb_seteuid_core(rb_uid_t euid) #if defined(HAVE_SETRESUID) if (uid != euid) { - if (setresuid(-1,euid,euid) < 0) rb_sys_fail(0); - SAVED_USER_ID = euid; + if (setresuid(-1,euid,euid) < 0) rb_sys_fail(0); + SAVED_USER_ID = euid; } else { - if (setresuid(-1,euid,-1) < 0) rb_sys_fail(0); + if (setresuid(-1,euid,-1) < 0) rb_sys_fail(0); } #elif defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID) if (setreuid(-1, euid) < 0) rb_sys_fail(0); if (uid != euid) { - if (setreuid(euid,uid) < 0) rb_sys_fail(0); - if (setreuid(uid,euid) < 0) rb_sys_fail(0); - SAVED_USER_ID = euid; + if (setreuid(euid,uid) < 0) rb_sys_fail(0); + if (setreuid(uid,euid) < 0) rb_sys_fail(0); + SAVED_USER_ID = euid; } #elif defined HAVE_SETEUID if (seteuid(euid) < 0) rb_sys_fail(0); @@ -7470,10 +7470,10 @@ proc_setegid(VALUE obj, VALUE egid) if (setegid(gid) < 0) rb_sys_fail(0); #elif defined HAVE_SETGID if (gid == getgid()) { - if (setgid(gid) < 0) rb_sys_fail(0); + if (setgid(gid) < 0) rb_sys_fail(0); } else { - rb_notimplement(); + rb_notimplement(); } #else rb_notimplement(); @@ -7503,18 +7503,18 @@ rb_setegid_core(rb_gid_t egid) #if defined(HAVE_SETRESGID) if (gid != egid) { - if (setresgid(-1,egid,egid) < 0) rb_sys_fail(0); - SAVED_GROUP_ID = egid; + if (setresgid(-1,egid,egid) < 0) rb_sys_fail(0); + SAVED_GROUP_ID = egid; } else { - if (setresgid(-1,egid,-1) < 0) rb_sys_fail(0); + if (setresgid(-1,egid,-1) < 0) rb_sys_fail(0); } #elif defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID) if (setregid(-1, egid) < 0) rb_sys_fail(0); if (gid != egid) { - if (setregid(egid,gid) < 0) rb_sys_fail(0); - if (setregid(gid,egid) < 0) rb_sys_fail(0); - SAVED_GROUP_ID = egid; + if (setregid(egid,gid) < 0) rb_sys_fail(0); + if (setregid(gid,egid) < 0) rb_sys_fail(0); + SAVED_GROUP_ID = egid; } #elif defined HAVE_SETEGID if (setegid(egid) < 0) rb_sys_fail(0); @@ -7730,27 +7730,27 @@ p_uid_switch(VALUE obj) euid = geteuid(); if (uid != euid) { - proc_seteuid(uid); - if (rb_block_given_p()) { - under_uid_switch = 1; - return rb_ensure(rb_yield, Qnil, p_uid_sw_ensure, SAVED_USER_ID); - } - else { - return UIDT2NUM(euid); - } + proc_seteuid(uid); + if (rb_block_given_p()) { + under_uid_switch = 1; + return rb_ensure(rb_yield, Qnil, p_uid_sw_ensure, SAVED_USER_ID); + } + else { + return UIDT2NUM(euid); + } } else if (euid != SAVED_USER_ID) { - proc_seteuid(SAVED_USER_ID); - if (rb_block_given_p()) { - under_uid_switch = 1; - return rb_ensure(rb_yield, Qnil, p_uid_sw_ensure, euid); - } - else { - return UIDT2NUM(uid); - } + proc_seteuid(SAVED_USER_ID); + if (rb_block_given_p()) { + under_uid_switch = 1; + return rb_ensure(rb_yield, Qnil, p_uid_sw_ensure, euid); + } + else { + return UIDT2NUM(uid); + } } else { - rb_syserr_fail(EPERM, 0); + rb_syserr_fail(EPERM, 0); } UNREACHABLE_RETURN(Qnil); @@ -7774,15 +7774,15 @@ p_uid_switch(VALUE obj) euid = geteuid(); if (uid == euid) { - rb_syserr_fail(EPERM, 0); + rb_syserr_fail(EPERM, 0); } p_uid_exchange(obj); if (rb_block_given_p()) { - under_uid_switch = 1; - return rb_ensure(rb_yield, Qnil, p_uid_sw_ensure, obj); + under_uid_switch = 1; + return rb_ensure(rb_yield, Qnil, p_uid_sw_ensure, obj); } else { - return UIDT2NUM(euid); + return UIDT2NUM(euid); } } #endif @@ -7844,27 +7844,27 @@ p_gid_switch(VALUE obj) egid = getegid(); if (gid != egid) { - proc_setegid(obj, GIDT2NUM(gid)); - if (rb_block_given_p()) { - under_gid_switch = 1; - return rb_ensure(rb_yield, Qnil, p_gid_sw_ensure, SAVED_GROUP_ID); - } - else { - return GIDT2NUM(egid); - } + proc_setegid(obj, GIDT2NUM(gid)); + if (rb_block_given_p()) { + under_gid_switch = 1; + return rb_ensure(rb_yield, Qnil, p_gid_sw_ensure, SAVED_GROUP_ID); + } + else { + return GIDT2NUM(egid); + } } else if (egid != SAVED_GROUP_ID) { - proc_setegid(obj, GIDT2NUM(SAVED_GROUP_ID)); - if (rb_block_given_p()) { - under_gid_switch = 1; - return rb_ensure(rb_yield, Qnil, p_gid_sw_ensure, egid); - } - else { - return GIDT2NUM(gid); - } + proc_setegid(obj, GIDT2NUM(SAVED_GROUP_ID)); + if (rb_block_given_p()) { + under_gid_switch = 1; + return rb_ensure(rb_yield, Qnil, p_gid_sw_ensure, egid); + } + else { + return GIDT2NUM(gid); + } } else { - rb_syserr_fail(EPERM, 0); + rb_syserr_fail(EPERM, 0); } UNREACHABLE_RETURN(Qnil); @@ -7888,15 +7888,15 @@ p_gid_switch(VALUE obj) egid = getegid(); if (gid == egid) { - rb_syserr_fail(EPERM, 0); + rb_syserr_fail(EPERM, 0); } p_gid_exchange(obj); if (rb_block_given_p()) { - under_gid_switch = 1; - return rb_ensure(rb_yield, Qnil, p_gid_sw_ensure, obj); + under_gid_switch = 1; + return rb_ensure(rb_yield, Qnil, p_gid_sw_ensure, obj); } else { - return GIDT2NUM(egid); + return GIDT2NUM(egid); } } #endif @@ -7937,7 +7937,7 @@ rb_proc_times(VALUE obj) struct rusage usage_s, usage_c; if (getrusage(RUSAGE_SELF, &usage_s) != 0 || getrusage(RUSAGE_CHILDREN, &usage_c) != 0) - rb_sys_fail("getrusage"); + rb_sys_fail("getrusage"); utime = DBL2NUM((double)usage_s.ru_utime.tv_sec + (double)usage_s.ru_utime.tv_usec/1e6); stime = DBL2NUM((double)usage_s.ru_stime.tv_sec + (double)usage_s.ru_stime.tv_usec/1e6); cutime = DBL2NUM((double)usage_c.ru_utime.tv_sec + (double)usage_c.ru_utime.tv_usec/1e6); @@ -8463,7 +8463,7 @@ rb_clock_gettime(int argc, VALUE *argv, VALUE _) #ifdef __APPLE__ if (clk_id == RUBY_MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC) { - const mach_timebase_info_data_t *info = get_mach_timebase_info(); + const mach_timebase_info_data_t *info = get_mach_timebase_info(); uint64_t t = mach_absolute_time(); tt.count = (int32_t)(t % 1000000000); tt.giga_count = t / 1000000000; @@ -8637,7 +8637,7 @@ rb_clock_getres(int argc, VALUE *argv, VALUE _) #ifdef RUBY_MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC if (clk_id == RUBY_MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC) { - const mach_timebase_info_data_t *info = get_mach_timebase_info(); + const mach_timebase_info_data_t *info = get_mach_timebase_info(); tt.count = 1; tt.giga_count = 0; numerators[num_numerators++] = info->numer; @@ -8851,20 +8851,20 @@ InitVM_process(void) { VALUE inf = RLIM2NUM(RLIM_INFINITY); #ifdef RLIM_SAVED_MAX - { - VALUE v = RLIM_INFINITY == RLIM_SAVED_MAX ? inf : RLIM2NUM(RLIM_SAVED_MAX); - /* see Process.setrlimit */ - rb_define_const(rb_mProcess, "RLIM_SAVED_MAX", v); - } + { + VALUE v = RLIM_INFINITY == RLIM_SAVED_MAX ? inf : RLIM2NUM(RLIM_SAVED_MAX); + /* see Process.setrlimit */ + rb_define_const(rb_mProcess, "RLIM_SAVED_MAX", v); + } #endif - /* see Process.setrlimit */ + /* see Process.setrlimit */ rb_define_const(rb_mProcess, "RLIM_INFINITY", inf); #ifdef RLIM_SAVED_CUR - { - VALUE v = RLIM_INFINITY == RLIM_SAVED_CUR ? inf : RLIM2NUM(RLIM_SAVED_CUR); - /* see Process.setrlimit */ - rb_define_const(rb_mProcess, "RLIM_SAVED_CUR", v); - } + { + VALUE v = RLIM_INFINITY == RLIM_SAVED_CUR ? inf : RLIM2NUM(RLIM_SAVED_CUR); + /* see Process.setrlimit */ + rb_define_const(rb_mProcess, "RLIM_SAVED_CUR", v); + } #endif } #ifdef RLIMIT_AS diff --git a/ractor.c b/ractor.c index ab993eb94e..c5df3cc6b0 100644 --- a/ractor.c +++ b/ractor.c @@ -263,7 +263,7 @@ static const rb_data_type_t ractor_data_type = { "ractor", { ractor_mark, - ractor_free, + ractor_free, ractor_memsize, NULL, // update }, @@ -1514,7 +1514,7 @@ rb_ractor_main_alloc(void) { rb_ractor_t *r = ruby_mimmalloc(sizeof(rb_ractor_t)); if (r == NULL) { - fprintf(stderr, "[FATAL] failed to allocate memory for main ractor\n"); + fprintf(stderr, "[FATAL] failed to allocate memory for main ractor\n"); exit(EXIT_FAILURE); } MEMZERO(r, rb_ractor_t, 1); diff --git a/random.c b/random.c index 30329ed45c..9476de0d4a 100644 --- a/random.c +++ b/random.c @@ -144,7 +144,7 @@ static rb_random_mt_t * rand_mt_start(rb_random_mt_t *r) { if (!genrand_initialized(&r->mt)) { - r->base.seed = rand_init(&random_mt_if, &r->base, random_seed(Qundef)); + r->base.seed = rand_init(&random_mt_if, &r->base, random_seed(Qundef)); } return r; } @@ -216,7 +216,7 @@ int_pair_to_real_inclusive(uint32_t a, uint32_t b) r = (double)(uint64_t)((x * m) >> 64); #elif defined HAVE_UINT64_T && !MSC_VERSION_BEFORE(1300) uint64_t x = ((uint64_t)a << dig_u) + - (((uint64_t)b + (a >> dig_u)) >> dig_r64); + (((uint64_t)b + (a >> dig_u)) >> dig_r64); r = (double)x; #else /* shift then add to get rid of overflow */ @@ -252,9 +252,9 @@ random_memsize(const void *ptr) const rb_data_type_t rb_random_data_type = { "random", { - random_mark, - random_free, - random_memsize, + random_mark, + random_free, + random_memsize, }, 0, 0, RUBY_TYPED_FREE_IMMEDIATELY }; @@ -271,9 +271,9 @@ random_mt_memsize(const void *ptr) static const rb_data_type_t random_mt_type = { "random/MT", { - random_mt_mark, - random_mt_free, - random_mt_memsize, + random_mt_mark, + random_mt_free, + random_mt_memsize, }, &rb_random_data_type, (void *)&random_mt_if, @@ -302,7 +302,7 @@ static rb_random_t * try_get_rnd(VALUE obj) { if (obj == rb_cRandom) { - return rand_start(default_rand()); + return rand_start(default_rand()); } if (!rb_typeddata_is_kind_of(obj, &rb_random_data_type)) return NULL; if (RTYPEDDATA_TYPE(obj) == &random_mt_type) @@ -319,7 +319,7 @@ static const rb_random_interface_t * try_rand_if(VALUE obj, rb_random_t *rnd) { if (rnd == &default_rand()->base) { - return &random_mt_if; + return &random_mt_if; } return rb_rand_if(obj); } @@ -426,12 +426,12 @@ fill_random_bytes_urandom(void *seed, size_t size) { unsigned char *p = (unsigned char *)seed; while (size) { - size_t len = size < MAX_SEED_LEN_PER_READ ? size : MAX_SEED_LEN_PER_READ; - if (getentropy(p, len) != 0) { + size_t len = size < MAX_SEED_LEN_PER_READ ? size : MAX_SEED_LEN_PER_READ; + if (getentropy(p, len) != 0) { return -1; - } - p += len; - size -= len; + } + p += len; + size -= len; } return 0; } @@ -446,12 +446,12 @@ fill_random_bytes_urandom(void *seed, size_t size) */ int fd = rb_cloexec_open("/dev/urandom", # ifdef O_NONBLOCK - O_NONBLOCK| + O_NONBLOCK| # endif # ifdef O_NOCTTY - O_NOCTTY| + O_NOCTTY| # endif - O_RDONLY, 0); + O_RDONLY, 0); struct stat statbuf; ssize_t ret = 0; size_t offset = 0; @@ -459,14 +459,14 @@ fill_random_bytes_urandom(void *seed, size_t size) if (fd < 0) return -1; rb_update_max_fd(fd); if (fstat(fd, &statbuf) == 0 && S_ISCHR(statbuf.st_mode)) { - do { - ret = read(fd, ((char*)seed) + offset, size - offset); - if (ret < 0) { - close(fd); - return -1; - } - offset += (size_t)ret; - } while (offset < size); + do { + ret = read(fd, ((char*)seed) + offset, size - offset); + if (ret < 0) { + close(fd); + return -1; + } + offset += (size_t)ret; + } while (offset < size); } close(fd); return 0; @@ -553,7 +553,7 @@ release_crypt(void *p) HCRYPTPROV *ptr = p; HCRYPTPROV prov = (HCRYPTPROV)ATOMIC_SIZE_EXCHANGE(*ptr, INVALID_HCRYPTPROV); if (prov && prov != INVALID_HCRYPTPROV) { - CryptReleaseContext(prov, 0); + CryptReleaseContext(prov, 0); } } @@ -563,23 +563,23 @@ fill_random_bytes_crypt(void *seed, size_t size) static HCRYPTPROV perm_prov; HCRYPTPROV prov = perm_prov, old_prov; if (!prov) { - if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { - prov = INVALID_HCRYPTPROV; - } - old_prov = (HCRYPTPROV)ATOMIC_SIZE_CAS(perm_prov, 0, prov); - if (LIKELY(!old_prov)) { /* no other threads acquired */ - if (prov != INVALID_HCRYPTPROV) { + if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { + prov = INVALID_HCRYPTPROV; + } + old_prov = (HCRYPTPROV)ATOMIC_SIZE_CAS(perm_prov, 0, prov); + if (LIKELY(!old_prov)) { /* no other threads acquired */ + if (prov != INVALID_HCRYPTPROV) { #undef RUBY_UNTYPED_DATA_WARNING #define RUBY_UNTYPED_DATA_WARNING 0 - rb_gc_register_mark_object(Data_Wrap_Struct(0, 0, release_crypt, &perm_prov)); - } - } - else { /* another thread acquired */ - if (prov != INVALID_HCRYPTPROV) { - CryptReleaseContext(prov, 0); - } - prov = old_prov; - } + rb_gc_register_mark_object(Data_Wrap_Struct(0, 0, release_crypt, &perm_prov)); + } + } + else { /* another thread acquired */ + if (prov != INVALID_HCRYPTPROV) { + CryptReleaseContext(prov, 0); + } + prov = old_prov; + } } if (prov == INVALID_HCRYPTPROV) return -1; while (size > 0) { @@ -619,20 +619,20 @@ fill_random_bytes_syscall(void *seed, size_t size, int need_secure) { static rb_atomic_t try_syscall = 1; if (try_syscall) { - size_t offset = 0; - int flags = 0; - if (!need_secure) - flags = GRND_NONBLOCK; - do { - errno = 0; + size_t offset = 0; + int flags = 0; + if (!need_secure) + flags = GRND_NONBLOCK; + do { + errno = 0; ssize_t ret = getrandom(((char*)seed) + offset, size - offset, flags); - if (ret == -1) { - ATOMIC_SET(try_syscall, 0); - return -1; - } - offset += (size_t)ret; - } while (offset < size); - return 0; + if (ret == -1) { + ATOMIC_SET(try_syscall, 0); + return -1; + } + offset += (size_t)ret; + } while (offset < size); + return 0; } return -1; } @@ -745,7 +745,7 @@ random_raw_seed(VALUE self, VALUE size) VALUE buf = rb_str_new(0, n); if (n == 0) return buf; if (fill_random_bytes(RSTRING_PTR(buf), n, TRUE)) - rb_raise(rb_eRuntimeError, "failed to get urandom"); + rb_raise(rb_eRuntimeError, "failed to get urandom"); return buf; } @@ -857,16 +857,16 @@ rand_mt_load(VALUE obj, VALUE dump) left = RARRAY_AREF(dump, 1); case 1: state = RARRAY_AREF(dump, 0); - break; + break; default: - rb_raise(rb_eArgError, "wrong dump data"); + rb_raise(rb_eArgError, "wrong dump data"); } rb_integer_pack(state, mt->state, numberof(mt->state), sizeof(*mt->state), 0, INTEGER_PACK_LSWORD_FIRST|INTEGER_PACK_NATIVE_BYTE_ORDER); x = NUM2ULONG(left); if (x > numberof(mt->state)) { - rb_raise(rb_eArgError, "wrong value"); + rb_raise(rb_eArgError, "wrong value"); } mt->left = (unsigned int)x; mt->next = mt->state + numberof(mt->state) - x + 1; @@ -933,7 +933,7 @@ rb_f_srand(int argc, VALUE *argv, VALUE obj) seed = random_seed(obj); } else { - seed = rb_to_int(argv[0]); + seed = rb_to_int(argv[0]); } old = r->base.seed; rand_init(&random_mt_if, &r->base, seed); @@ -1056,9 +1056,9 @@ obj_random_bytes(VALUE obj, void *p, long n) Check_Type(v, T_STRING); l = RSTRING_LEN(v); if (l < n) - rb_raise(rb_eRangeError, "random data too short %ld", l); + rb_raise(rb_eRangeError, "random data too short %ld", l); else if (l > n) - rb_raise(rb_eRangeError, "random data too long %ld", l); + rb_raise(rb_eRangeError, "random data too long %ld", l); if (p) memcpy(p, RSTRING_PTR(v), n); return v; } @@ -1074,9 +1074,9 @@ rb_random_int32(VALUE obj) { rb_random_t *rnd = try_get_rnd(obj); if (!rnd) { - uint32_t x; - obj_random_bytes(obj, &x, sizeof(x)); - return (unsigned int)x; + uint32_t x; + obj_random_bytes(obj, &x, sizeof(x)); + return (unsigned int)x; } return random_int32(try_rand_if(obj, rnd), rnd); } @@ -1087,10 +1087,10 @@ random_real(VALUE obj, rb_random_t *rnd, int excl) uint32_t a, b; if (!rnd) { - uint32_t x[2] = {0, 0}; - obj_random_bytes(obj, x, sizeof(x)); - a = x[0]; - b = x[1]; + uint32_t x[2] = {0, 0}; + obj_random_bytes(obj, x, sizeof(x)); + a = x[0]; + b = x[1]; } else { const rb_random_interface_t *rng = try_rand_if(obj, rnd); @@ -1105,10 +1105,10 @@ double rb_int_pair_to_real(uint32_t a, uint32_t b, int excl) { if (excl) { - return int_pair_to_real_exclusive(a, b); + return int_pair_to_real_exclusive(a, b); } else { - return int_pair_to_real_inclusive(a, b); + return int_pair_to_real_inclusive(a, b); } } @@ -1117,15 +1117,15 @@ rb_random_real(VALUE obj) { rb_random_t *rnd = try_get_rnd(obj); if (!rnd) { - VALUE v = rb_funcallv(obj, id_rand, 0, 0); - double d = NUM2DBL(v); - if (d < 0.0) { - rb_raise(rb_eRangeError, "random number too small %g", d); - } - else if (d >= 1.0) { - rb_raise(rb_eRangeError, "random number too big %g", d); - } - return d; + VALUE v = rb_funcallv(obj, id_rand, 0, 0); + double d = NUM2DBL(v); + if (d < 0.0) { + rb_raise(rb_eRangeError, "random number too small %g", d); + } + else if (d >= 1.0) { + rb_raise(rb_eRangeError, "random number too big %g", d); + } + return d; } return random_real(obj, rnd, TRUE); } @@ -1137,7 +1137,7 @@ ulong_to_num_plus_1(unsigned long n) return ULL2NUM((LONG_LONG)n+1); #else if (n >= ULONG_MAX) { - return rb_big_plus(ULONG2NUM(n), INT2FIX(1)); + return rb_big_plus(ULONG2NUM(n), INT2FIX(1)); } return ULONG2NUM(n+1); #endif @@ -1148,26 +1148,26 @@ random_ulong_limited(VALUE obj, rb_random_t *rnd, unsigned long limit) { if (!limit) return 0; if (!rnd) { - const int w = sizeof(limit) * CHAR_BIT - nlz_long(limit); - const int n = w > 32 ? sizeof(unsigned long) : sizeof(uint32_t); - const unsigned long mask = ~(~0UL << w); - const unsigned long full = - (size_t)n >= sizeof(unsigned long) ? ~0UL : - ~(~0UL << n * CHAR_BIT); - unsigned long val, bits = 0, rest = 0; - do { - if (mask & ~rest) { - union {uint32_t u32; unsigned long ul;} buf; - obj_random_bytes(obj, &buf, n); - rest = full; - bits = (n == sizeof(uint32_t)) ? buf.u32 : buf.ul; - } - val = bits; - bits >>= w; - rest >>= w; - val &= mask; - } while (limit < val); - return val; + const int w = sizeof(limit) * CHAR_BIT - nlz_long(limit); + const int n = w > 32 ? sizeof(unsigned long) : sizeof(uint32_t); + const unsigned long mask = ~(~0UL << w); + const unsigned long full = + (size_t)n >= sizeof(unsigned long) ? ~0UL : + ~(~0UL << n * CHAR_BIT); + unsigned long val, bits = 0, rest = 0; + do { + if (mask & ~rest) { + union {uint32_t u32; unsigned long ul;} buf; + obj_random_bytes(obj, &buf, n); + rest = full; + bits = (n == sizeof(uint32_t)) ? buf.u32 : buf.ul; + } + val = bits; + bits >>= w; + rest >>= w; + val &= mask; + } while (limit < val); + return val; } return limited_rand(try_rand_if(obj, rnd), rnd, limit); } @@ -1177,16 +1177,16 @@ rb_random_ulong_limited(VALUE obj, unsigned long limit) { rb_random_t *rnd = try_get_rnd(obj); if (!rnd) { - VALUE lim = ulong_to_num_plus_1(limit); - VALUE v = rb_to_int(rb_funcallv_public(obj, id_rand, 1, &lim)); - unsigned long r = NUM2ULONG(v); - if (rb_num_negative_p(v)) { - rb_raise(rb_eRangeError, "random number too small %ld", r); - } - if (r > limit) { - rb_raise(rb_eRangeError, "random number too big %ld", r); - } - return r; + VALUE lim = ulong_to_num_plus_1(limit); + VALUE v = rb_to_int(rb_funcallv_public(obj, id_rand, 1, &lim)); + unsigned long r = NUM2ULONG(v); + if (rb_num_negative_p(v)) { + rb_raise(rb_eRangeError, "random number too small %ld", r); + } + if (r > limit) { + rb_raise(rb_eRangeError, "random number too big %ld", r); + } + return r; } return limited_rand(try_rand_if(obj, rnd), rnd, limit); } @@ -1195,27 +1195,27 @@ static VALUE random_ulong_limited_big(VALUE obj, rb_random_t *rnd, VALUE vmax) { if (!rnd) { - VALUE v, vtmp; - size_t i, nlz, len = rb_absint_numwords(vmax, 32, &nlz); - uint32_t *tmp = ALLOCV_N(uint32_t, vtmp, len * 2); - uint32_t mask = (uint32_t)~0 >> nlz; - uint32_t *lim_array = tmp; - uint32_t *rnd_array = tmp + len; - int flag = INTEGER_PACK_MSWORD_FIRST|INTEGER_PACK_NATIVE_BYTE_ORDER; - rb_integer_pack(vmax, lim_array, len, sizeof(uint32_t), 0, flag); + VALUE v, vtmp; + size_t i, nlz, len = rb_absint_numwords(vmax, 32, &nlz); + uint32_t *tmp = ALLOCV_N(uint32_t, vtmp, len * 2); + uint32_t mask = (uint32_t)~0 >> nlz; + uint32_t *lim_array = tmp; + uint32_t *rnd_array = tmp + len; + int flag = INTEGER_PACK_MSWORD_FIRST|INTEGER_PACK_NATIVE_BYTE_ORDER; + rb_integer_pack(vmax, lim_array, len, sizeof(uint32_t), 0, flag); retry: - obj_random_bytes(obj, rnd_array, len * sizeof(uint32_t)); - rnd_array[0] &= mask; - for (i = 0; i < len; ++i) { - if (lim_array[i] < rnd_array[i]) - goto retry; - if (rnd_array[i] < lim_array[i]) - break; - } - v = rb_integer_unpack(rnd_array, len, sizeof(uint32_t), 0, flag); - ALLOCV_END(vtmp); - return v; + obj_random_bytes(obj, rnd_array, len * sizeof(uint32_t)); + rnd_array[0] &= mask; + for (i = 0; i < len; ++i) { + if (lim_array[i] < rnd_array[i]) + goto retry; + if (rnd_array[i] < lim_array[i]) + break; + } + v = rb_integer_unpack(rnd_array, len, sizeof(uint32_t), 0, flag); + ALLOCV_END(vtmp); + return v; } return limited_big_rand(try_rand_if(obj, rnd), rnd, vmax); } @@ -1255,18 +1255,18 @@ rb_rand_bytes_int32(rb_random_get_int32_func *get_int32, unsigned int r, i; for (; n >= SIZEOF_INT32; n -= SIZEOF_INT32) { r = get_int32(rnd); - i = SIZEOF_INT32; - do { - *ptr++ = (char)r; - r >>= CHAR_BIT; + i = SIZEOF_INT32; + do { + *ptr++ = (char)r; + r >>= CHAR_BIT; } while (--i); } if (n > 0) { r = get_int32(rnd); - do { - *ptr++ = (char)r; - r >>= CHAR_BIT; - } while (--n); + do { + *ptr++ = (char)r; + r >>= CHAR_BIT; + } while (--n); } } @@ -1275,7 +1275,7 @@ rb_random_bytes(VALUE obj, long n) { rb_random_t *rnd = try_get_rnd(obj); if (!rnd) { - return obj_random_bytes(obj, NULL, n); + return obj_random_bytes(obj, NULL, n); } return rand_bytes(try_rand_if(obj, rnd), rnd, n); } @@ -1335,32 +1335,32 @@ rand_int(VALUE obj, rb_random_t *rnd, VALUE vmax, int restrictive) unsigned long r; if (FIXNUM_P(vmax)) { - long max = FIX2LONG(vmax); - if (!max) return Qnil; - if (max < 0) { - if (restrictive) return Qnil; - max = -max; - } - r = random_ulong_limited(obj, rnd, (unsigned long)max - 1); - return ULONG2NUM(r); + long max = FIX2LONG(vmax); + if (!max) return Qnil; + if (max < 0) { + if (restrictive) return Qnil; + max = -max; + } + r = random_ulong_limited(obj, rnd, (unsigned long)max - 1); + return ULONG2NUM(r); } else { - VALUE ret; - if (rb_bigzero_p(vmax)) return Qnil; - if (!BIGNUM_SIGN(vmax)) { - if (restrictive) return Qnil; + VALUE ret; + if (rb_bigzero_p(vmax)) return Qnil; + if (!BIGNUM_SIGN(vmax)) { + if (restrictive) return Qnil; vmax = rb_big_uminus(vmax); - } - vmax = rb_big_minus(vmax, INT2FIX(1)); - if (FIXNUM_P(vmax)) { - long max = FIX2LONG(vmax); - if (max == -1) return Qnil; - r = random_ulong_limited(obj, rnd, max); - return LONG2NUM(r); - } - ret = random_ulong_limited_big(obj, rnd, vmax); - RB_GC_GUARD(vmax); - return ret; + } + vmax = rb_big_minus(vmax, INT2FIX(1)); + if (FIXNUM_P(vmax)) { + long max = FIX2LONG(vmax); + if (max == -1) return Qnil; + r = random_ulong_limited(obj, rnd, max); + return LONG2NUM(r); + } + ret = random_ulong_limited_big(obj, rnd, vmax); + RB_GC_GUARD(vmax); + return ret; } } @@ -1383,10 +1383,10 @@ check_random_number(VALUE v, const VALUE *argv) { switch (v) { case Qfalse: - (void)NUM2LONG(argv[0]); - break; + (void)NUM2LONG(argv[0]); + break; case Qnil: - invalid_argument(argv[0]); + invalid_argument(argv[0]); } return v; } @@ -1396,7 +1396,7 @@ float_value(VALUE v) { double x = RFLOAT_VALUE(v); if (!isfinite(x)) { - domain_error(); + domain_error(); } return x; } @@ -1408,71 +1408,71 @@ rand_range(VALUE obj, rb_random_t* rnd, VALUE range) int excl = 0; if ((v = vmax = range_values(range, &beg, &end, &excl)) == Qfalse) - return Qfalse; + return Qfalse; if (NIL_P(v)) domain_error(); if (!RB_FLOAT_TYPE_P(vmax) && (v = rb_check_to_int(vmax), !NIL_P(v))) { - long max; - vmax = v; - v = Qnil; + long max; + vmax = v; + v = Qnil; fixnum: - if (FIXNUM_P(vmax)) { - if ((max = FIX2LONG(vmax) - excl) >= 0) { - unsigned long r = random_ulong_limited(obj, rnd, (unsigned long)max); - v = ULONG2NUM(r); - } - } - else if (BUILTIN_TYPE(vmax) == T_BIGNUM && BIGNUM_SIGN(vmax) && !rb_bigzero_p(vmax)) { - vmax = excl ? rb_big_minus(vmax, INT2FIX(1)) : rb_big_norm(vmax); - if (FIXNUM_P(vmax)) { - excl = 0; - goto fixnum; - } - v = random_ulong_limited_big(obj, rnd, vmax); - } + if (FIXNUM_P(vmax)) { + if ((max = FIX2LONG(vmax) - excl) >= 0) { + unsigned long r = random_ulong_limited(obj, rnd, (unsigned long)max); + v = ULONG2NUM(r); + } + } + else if (BUILTIN_TYPE(vmax) == T_BIGNUM && BIGNUM_SIGN(vmax) && !rb_bigzero_p(vmax)) { + vmax = excl ? rb_big_minus(vmax, INT2FIX(1)) : rb_big_norm(vmax); + if (FIXNUM_P(vmax)) { + excl = 0; + goto fixnum; + } + v = random_ulong_limited_big(obj, rnd, vmax); + } } else if (v = rb_check_to_float(vmax), !NIL_P(v)) { - int scale = 1; - double max = RFLOAT_VALUE(v), mid = 0.5, r; - if (isinf(max)) { - double min = float_value(rb_to_float(beg)) / 2.0; - max = float_value(rb_to_float(end)) / 2.0; - scale = 2; - mid = max + min; - max -= min; - } - else if (isnan(max)) { - domain_error(); - } - v = Qnil; - if (max > 0.0) { - r = random_real(obj, rnd, excl); - if (scale > 1) { - return rb_float_new(+(+(+(r - 0.5) * max) * scale) + mid); - } - v = rb_float_new(r * max); - } - else if (max == 0.0 && !excl) { - v = rb_float_new(0.0); - } + int scale = 1; + double max = RFLOAT_VALUE(v), mid = 0.5, r; + if (isinf(max)) { + double min = float_value(rb_to_float(beg)) / 2.0; + max = float_value(rb_to_float(end)) / 2.0; + scale = 2; + mid = max + min; + max -= min; + } + else if (isnan(max)) { + domain_error(); + } + v = Qnil; + if (max > 0.0) { + r = random_real(obj, rnd, excl); + if (scale > 1) { + return rb_float_new(+(+(+(r - 0.5) * max) * scale) + mid); + } + v = rb_float_new(r * max); + } + else if (max == 0.0 && !excl) { + v = rb_float_new(0.0); + } } if (FIXNUM_P(beg) && FIXNUM_P(v)) { - long x = FIX2LONG(beg) + FIX2LONG(v); - return LONG2NUM(x); + long x = FIX2LONG(beg) + FIX2LONG(v); + return LONG2NUM(x); } switch (TYPE(v)) { case T_NIL: - break; + break; case T_BIGNUM: - return rb_big_plus(v, beg); + return rb_big_plus(v, beg); case T_FLOAT: { - VALUE f = rb_check_to_float(beg); - if (!NIL_P(f)) { - return DBL2NUM(RFLOAT_VALUE(v) + RFLOAT_VALUE(f)); - } + VALUE f = rb_check_to_float(beg); + if (!NIL_P(f)) { + return DBL2NUM(RFLOAT_VALUE(v) + RFLOAT_VALUE(f)); + } } default: - return rb_funcallv(beg, id_plus, 1, &v); + return rb_funcallv(beg, id_plus, 1, &v); } return v; @@ -1524,25 +1524,25 @@ rand_random(int argc, VALUE *argv, VALUE obj, rb_random_t *rnd) VALUE vmax, v; if (rb_check_arity(argc, 0, 1) == 0) { - return rb_float_new(random_real(obj, rnd, TRUE)); + return rb_float_new(random_real(obj, rnd, TRUE)); } vmax = argv[0]; if (NIL_P(vmax)) return Qnil; if (!RB_FLOAT_TYPE_P(vmax)) { - v = rb_check_to_int(vmax); - if (!NIL_P(v)) return rand_int(obj, rnd, v, 1); + v = rb_check_to_int(vmax); + if (!NIL_P(v)) return rand_int(obj, rnd, v, 1); } v = rb_check_to_float(vmax); if (!NIL_P(v)) { - const double max = float_value(v); - if (max < 0.0) { - return Qnil; - } - else { - double r = random_real(obj, rnd, TRUE); - if (max > 0.0) r *= max; - return rb_float_new(r); - } + const double max = float_value(v); + if (max < 0.0) { + return Qnil; + } + else { + double r = random_real(obj, rnd, TRUE); + if (max > 0.0) r *= max; + return rb_float_new(r); + } } return rand_range(obj, rnd, vmax); } @@ -1645,12 +1645,12 @@ rb_f_rand(int argc, VALUE *argv, VALUE obj) if (rb_check_arity(argc, 0, 1) && !NIL_P(vmax = argv[0])) { VALUE v = rand_range(obj, rnd, vmax); - if (v != Qfalse) return v; - vmax = rb_to_int(vmax); - if (vmax != INT2FIX(0)) { + if (v != Qfalse) return v; + vmax = rb_to_int(vmax); + if (vmax != INT2FIX(0)) { v = rand_int(obj, rnd, vmax, 0); - if (!NIL_P(v)) return v; - } + if (!NIL_P(v)) return v; + } } return DBL2NUM(random_real(obj, rnd, TRUE)); } @@ -1706,7 +1706,7 @@ init_hash_salt(struct MT *mt) int i; for (i = 0; i < numberof(hash_salt.u32); ++i) - hash_salt.u32[i] = genrand_int32(mt); + hash_salt.u32[i] = genrand_int32(mt); } NO_SANITIZE("unsigned-integer-overflow", extern st_index_t rb_hash_start(st_index_t h)); @@ -1826,7 +1826,7 @@ InitVM_Random(void) rb_define_private_method(CLASS_OF(rb_cRandom), "left", random_s_left, 0); { - /* + /* * Generate a random number in the given range as Random does * * prng.random_number #=> 0.5816771641321361 @@ -1836,11 +1836,11 @@ InitVM_Random(void) * prng.rand(1000) #=> 485 * prng.rand(1..6) #=> 3 */ - VALUE m = rb_define_module_under(rb_cRandom, "Formatter"); - rb_include_module(base, m); - rb_extend_object(base, m); - rb_define_method(m, "random_number", rand_random_number, -1); - rb_define_method(m, "rand", rand_random_number, -1); + VALUE m = rb_define_module_under(rb_cRandom, "Formatter"); + rb_include_module(base, m); + rb_extend_object(base, m); + rb_define_method(m, "random_number", rand_random_number, -1); + rb_define_method(m, "rand", rand_random_number, -1); } default_rand_key = rb_ractor_local_storage_ptr_newkey(&default_rand_key_storage_type); diff --git a/range.c b/range.c index e45e405f5a..39786ed97c 100644 --- a/range.c +++ b/range.c @@ -47,11 +47,11 @@ static void range_init(VALUE range, VALUE beg, VALUE end, VALUE exclude_end) { if ((!FIXNUM_P(beg) || !FIXNUM_P(end)) && !NIL_P(beg) && !NIL_P(end)) { - VALUE v; + VALUE v; - v = rb_funcall(beg, id_cmp, 1, end); - if (NIL_P(v)) - rb_raise(rb_eArgError, "bad value for range"); + v = rb_funcall(beg, id_cmp, 1, end); + if (NIL_P(v)) + rb_raise(rb_eArgError, "bad value for range"); } RANGE_SET_EXCL(range, exclude_end); @@ -78,7 +78,7 @@ range_modify(VALUE range) rb_check_frozen(range); /* Ranges are immutable, so that they should be initialized only once. */ if (RANGE_EXCL(range) != Qnil) { - rb_name_err_raise("`initialize' called twice", range, ID2SYM(idInitialize)); + rb_name_err_raise("`initialize' called twice", range, ID2SYM(idInitialize)); } } @@ -140,9 +140,9 @@ recursive_equal(VALUE range, VALUE obj, int recur) { if (recur) return Qtrue; /* Subtle! */ if (!rb_equal(RANGE_BEG(range), RANGE_BEG(obj))) - return Qfalse; + return Qfalse; if (!rb_equal(RANGE_END(range), RANGE_END(obj))) - return Qfalse; + return Qfalse; return RBOOL(EXCL(range) == EXCL(obj)); } @@ -183,9 +183,9 @@ static VALUE range_eq(VALUE range, VALUE obj) { if (range == obj) - return Qtrue; + return Qtrue; if (!rb_obj_is_kind_of(obj, rb_cRange)) - return Qfalse; + return Qfalse; return rb_exec_recursive_paired(recursive_equal, range, obj, obj); } @@ -201,7 +201,7 @@ r_less(VALUE a, VALUE b) VALUE r = rb_funcall(a, id_cmp, 1, b); if (NIL_P(r)) - return INT_MAX; + return INT_MAX; return rb_cmpint(r, a, b); } @@ -210,9 +210,9 @@ recursive_eql(VALUE range, VALUE obj, int recur) { if (recur) return Qtrue; /* Subtle! */ if (!rb_eql(RANGE_BEG(range), RANGE_BEG(obj))) - return Qfalse; + return Qfalse; if (!rb_eql(RANGE_END(range), RANGE_END(obj))) - return Qfalse; + return Qfalse; return RBOOL(EXCL(range) == EXCL(obj)); } @@ -251,9 +251,9 @@ static VALUE range_eql(VALUE range, VALUE obj) { if (range == obj) - return Qtrue; + return Qtrue; if (!rb_obj_is_kind_of(obj, rb_cRange)) - return Qfalse; + return Qfalse; return rb_exec_recursive_paired(recursive_eql, range, obj, obj); } @@ -294,17 +294,17 @@ range_each_func(VALUE range, int (*func)(VALUE, VALUE), VALUE arg) VALUE v = b; if (EXCL(range)) { - while (r_less(v, e) < 0) { - if ((*func)(v, arg)) break; - v = rb_funcallv(v, id_succ, 0, 0); - } + while (r_less(v, e) < 0) { + if ((*func)(v, arg)) break; + v = rb_funcallv(v, id_succ, 0, 0); + } } else { - while ((c = r_less(v, e)) <= 0) { - if ((*func)(v, arg)) break; - if (!c) break; - v = rb_funcallv(v, id_succ, 0, 0); - } + while ((c = r_less(v, e)) <= 0) { + if ((*func)(v, arg)) break; + if (!c) break; + v = rb_funcallv(v, id_succ, 0, 0); + } } } @@ -314,10 +314,10 @@ step_i_iter(VALUE arg) VALUE *iter = (VALUE *)arg; if (FIXNUM_P(iter[0])) { - iter[0] -= INT2FIX(1) & ~FIXNUM_FLAG; + iter[0] -= INT2FIX(1) & ~FIXNUM_FLAG; } else { - iter[0] = rb_funcall(iter[0], '-', 1, INT2FIX(1)); + iter[0] = rb_funcall(iter[0], '-', 1, INT2FIX(1)); } if (iter[0] != INT2FIX(0)) return false; iter[0] = iter[1]; @@ -328,7 +328,7 @@ static int sym_step_i(VALUE i, VALUE arg) { if (step_i_iter(arg)) { - rb_yield(rb_str_intern(i)); + rb_yield(rb_str_intern(i)); } return 0; } @@ -337,7 +337,7 @@ static int step_i(VALUE i, VALUE arg) { if (step_i_iter(arg)) { - rb_yield(i); + rb_yield(i); } return 0; } @@ -356,7 +356,7 @@ linear_object_p(VALUE obj) switch (BUILTIN_TYPE(obj)) { case T_FLOAT: case T_BIGNUM: - return TRUE; + return TRUE; default: break; } @@ -371,14 +371,14 @@ check_step_domain(VALUE step) VALUE zero = INT2FIX(0); int cmp; if (!rb_obj_is_kind_of(step, rb_cNumeric)) { - step = rb_to_int(step); + step = rb_to_int(step); } cmp = rb_cmpint(rb_funcallv(step, idCmp, 1, &zero), step, zero); if (cmp < 0) { - rb_raise(rb_eArgError, "step can't be negative"); + rb_raise(rb_eArgError, "step can't be negative"); } else if (cmp == 0) { - rb_raise(rb_eArgError, "step can't be 0"); + rb_raise(rb_eArgError, "step can't be 0"); } return step; } @@ -389,11 +389,11 @@ range_step_size(VALUE range, VALUE args, VALUE eobj) VALUE b = RANGE_BEG(range), e = RANGE_END(range); VALUE step = INT2FIX(1); if (args) { - step = check_step_domain(RARRAY_AREF(args, 0)); + step = check_step_domain(RARRAY_AREF(args, 0)); } if (rb_obj_is_kind_of(b, rb_cNumeric) && rb_obj_is_kind_of(e, rb_cNumeric)) { - return ruby_num_interval_step_size(b, e, step, EXCL(range)); + return ruby_num_interval_step_size(b, e, step, EXCL(range)); } return Qnil; } @@ -466,74 +466,74 @@ range_step(int argc, VALUE *argv, VALUE range) VALUE iter[2] = {INT2FIX(1), step}; if (FIXNUM_P(b) && NIL_P(e) && FIXNUM_P(step)) { - long i = FIX2LONG(b), unit = FIX2LONG(step); - do { - rb_yield(LONG2FIX(i)); - i += unit; /* FIXABLE+FIXABLE never overflow */ - } while (FIXABLE(i)); - b = LONG2NUM(i); + long i = FIX2LONG(b), unit = FIX2LONG(step); + do { + rb_yield(LONG2FIX(i)); + i += unit; /* FIXABLE+FIXABLE never overflow */ + } while (FIXABLE(i)); + b = LONG2NUM(i); - for (;; b = rb_big_plus(b, step)) - rb_yield(b); + for (;; b = rb_big_plus(b, step)) + rb_yield(b); } else if (FIXNUM_P(b) && FIXNUM_P(e) && FIXNUM_P(step)) { /* fixnums are special */ - long end = FIX2LONG(e); - long i, unit = FIX2LONG(step); + long end = FIX2LONG(e); + long i, unit = FIX2LONG(step); - if (!EXCL(range)) - end += 1; - i = FIX2LONG(b); - while (i < end) { - rb_yield(LONG2NUM(i)); - if (i + unit < i) break; - i += unit; - } + if (!EXCL(range)) + end += 1; + i = FIX2LONG(b); + while (i < end) { + rb_yield(LONG2NUM(i)); + if (i + unit < i) break; + i += unit; + } } else if (SYMBOL_P(b) && (NIL_P(e) || SYMBOL_P(e))) { /* symbols are special */ - b = rb_sym2str(b); - if (NIL_P(e)) { - rb_str_upto_endless_each(b, sym_step_i, (VALUE)iter); - } - else { - rb_str_upto_each(b, rb_sym2str(e), EXCL(range), sym_step_i, (VALUE)iter); - } + b = rb_sym2str(b); + if (NIL_P(e)) { + rb_str_upto_endless_each(b, sym_step_i, (VALUE)iter); + } + else { + rb_str_upto_each(b, rb_sym2str(e), EXCL(range), sym_step_i, (VALUE)iter); + } } else if (ruby_float_step(b, e, step, EXCL(range), TRUE)) { - /* done */ + /* done */ } else if (rb_obj_is_kind_of(b, rb_cNumeric) || - !NIL_P(rb_check_to_integer(b, "to_int")) || - !NIL_P(rb_check_to_integer(e, "to_int"))) { - ID op = EXCL(range) ? '<' : idLE; - VALUE v = b; - int i = 0; + !NIL_P(rb_check_to_integer(b, "to_int")) || + !NIL_P(rb_check_to_integer(e, "to_int"))) { + ID op = EXCL(range) ? '<' : idLE; + VALUE v = b; + int i = 0; - while (NIL_P(e) || RTEST(rb_funcall(v, op, 1, e))) { - rb_yield(v); - i++; - v = rb_funcall(b, '+', 1, rb_funcall(INT2NUM(i), '*', 1, step)); - } + while (NIL_P(e) || RTEST(rb_funcall(v, op, 1, e))) { + rb_yield(v); + i++; + v = rb_funcall(b, '+', 1, rb_funcall(INT2NUM(i), '*', 1, step)); + } } else { - tmp = rb_check_string_type(b); + tmp = rb_check_string_type(b); - if (!NIL_P(tmp)) { - b = tmp; - if (NIL_P(e)) { - rb_str_upto_endless_each(b, step_i, (VALUE)iter); - } - else { - rb_str_upto_each(b, e, EXCL(range), step_i, (VALUE)iter); - } - } - else { - if (!discrete_object_p(b)) { - rb_raise(rb_eTypeError, "can't iterate from %s", - rb_obj_classname(b)); - } - range_each_func(range, step_i, (VALUE)iter); - } + if (!NIL_P(tmp)) { + b = tmp; + if (NIL_P(e)) { + rb_str_upto_endless_each(b, step_i, (VALUE)iter); + } + else { + rb_str_upto_each(b, e, EXCL(range), step_i, (VALUE)iter); + } + } + else { + if (!discrete_object_p(b)) { + rb_raise(rb_eTypeError, "can't iterate from %s", + rb_obj_classname(b)); + } + range_each_func(range, step_i, (VALUE)iter); + } } return range; } @@ -582,12 +582,12 @@ int64_as_double_to_num(int64_t i) { union int64_double convert; if (i < 0) { - convert.i = -i; - return DBL2NUM(-convert.d); + convert.i = -i; + return DBL2NUM(-convert.d); } else { - convert.i = i; - return DBL2NUM(convert.d); + convert.i = i; + return DBL2NUM(convert.d); } } @@ -618,29 +618,29 @@ bsearch_integer_range(VALUE beg, VALUE end, int excl) #define BSEARCH_CHECK(expr) \ do { \ - VALUE val = (expr); \ - VALUE v = rb_yield(val); \ - if (FIXNUM_P(v)) { \ - if (v == INT2FIX(0)) return val; \ - smaller = (SIGNED_VALUE)v < 0; \ - } \ - else if (v == Qtrue) { \ - satisfied = val; \ - smaller = 1; \ - } \ - else if (!RTEST(v)) { \ - smaller = 0; \ - } \ - else if (rb_obj_is_kind_of(v, rb_cNumeric)) { \ - int cmp = rb_cmpint(rb_funcall(v, id_cmp, 1, INT2FIX(0)), v, INT2FIX(0)); \ - if (!cmp) return val; \ - smaller = cmp < 0; \ - } \ - else { \ - rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE \ - " (must be numeric, true, false or nil)", \ - rb_obj_class(v)); \ - } \ + VALUE val = (expr); \ + VALUE v = rb_yield(val); \ + if (FIXNUM_P(v)) { \ + if (v == INT2FIX(0)) return val; \ + smaller = (SIGNED_VALUE)v < 0; \ + } \ + else if (v == Qtrue) { \ + satisfied = val; \ + smaller = 1; \ + } \ + else if (!RTEST(v)) { \ + smaller = 0; \ + } \ + else if (rb_obj_is_kind_of(v, rb_cNumeric)) { \ + int cmp = rb_cmpint(rb_funcall(v, id_cmp, 1, INT2FIX(0)), v, INT2FIX(0)); \ + if (!cmp) return val; \ + smaller = cmp < 0; \ + } \ + else { \ + rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE \ + " (must be numeric, true, false or nil)", \ + rb_obj_class(v)); \ + } \ } while (0) VALUE low = rb_to_int(beg); @@ -653,18 +653,18 @@ bsearch_integer_range(VALUE beg, VALUE end, int excl) org_high = high; while (rb_cmpint(rb_funcall(low, id_cmp, 1, high), low, high) < 0) { - mid = rb_funcall(rb_funcall(high, '+', 1, low), id_div, 1, INT2FIX(2)); - BSEARCH_CHECK(mid); - if (smaller) { - high = mid; - } - else { - low = rb_funcall(mid, '+', 1, INT2FIX(1)); - } + mid = rb_funcall(rb_funcall(high, '+', 1, low), id_div, 1, INT2FIX(2)); + BSEARCH_CHECK(mid); + if (smaller) { + high = mid; + } + else { + low = rb_funcall(mid, '+', 1, INT2FIX(1)); + } } if (rb_equal(low, org_high)) { - BSEARCH_CHECK(low); - if (!smaller) return Qnil; + BSEARCH_CHECK(low); + if (!smaller) return Qnil; } return satisfied; } @@ -701,25 +701,25 @@ range_bsearch(VALUE range) #define BSEARCH(conv) \ do { \ - RETURN_ENUMERATOR(range, 0, 0); \ - if (EXCL(range)) high--; \ - org_high = high; \ - while (low < high) { \ - mid = ((high < 0) == (low < 0)) ? low + ((high - low) / 2) \ - : (low < -high) ? -((-1 - low - high)/2 + 1) : (low + high) / 2; \ - BSEARCH_CHECK(conv(mid)); \ - if (smaller) { \ - high = mid; \ - } \ - else { \ - low = mid + 1; \ - } \ - } \ - if (low == org_high) { \ - BSEARCH_CHECK(conv(low)); \ - if (!smaller) return Qnil; \ - } \ - return satisfied; \ + RETURN_ENUMERATOR(range, 0, 0); \ + if (EXCL(range)) high--; \ + org_high = high; \ + while (low < high) { \ + mid = ((high < 0) == (low < 0)) ? low + ((high - low) / 2) \ + : (low < -high) ? -((-1 - low - high)/2 + 1) : (low + high) / 2; \ + BSEARCH_CHECK(conv(mid)); \ + if (smaller) { \ + high = mid; \ + } \ + else { \ + low = mid + 1; \ + } \ + } \ + if (low == org_high) { \ + BSEARCH_CHECK(conv(low)); \ + if (!smaller) return Qnil; \ + } \ + return satisfied; \ } while (0) @@ -727,49 +727,49 @@ range_bsearch(VALUE range) end = RANGE_END(range); if (FIXNUM_P(beg) && FIXNUM_P(end)) { - long low = FIX2LONG(beg); - long high = FIX2LONG(end); - long mid, org_high; - BSEARCH(INT2FIX); + long low = FIX2LONG(beg); + long high = FIX2LONG(end); + long mid, org_high; + BSEARCH(INT2FIX); } #if SIZEOF_DOUBLE == 8 && defined(HAVE_INT64_T) else if (RB_FLOAT_TYPE_P(beg) || RB_FLOAT_TYPE_P(end)) { - int64_t low = double_as_int64(NIL_P(beg) ? -HUGE_VAL : RFLOAT_VALUE(rb_Float(beg))); - int64_t high = double_as_int64(NIL_P(end) ? HUGE_VAL : RFLOAT_VALUE(rb_Float(end))); - int64_t mid, org_high; - BSEARCH(int64_as_double_to_num); + int64_t low = double_as_int64(NIL_P(beg) ? -HUGE_VAL : RFLOAT_VALUE(rb_Float(beg))); + int64_t high = double_as_int64(NIL_P(end) ? HUGE_VAL : RFLOAT_VALUE(rb_Float(end))); + int64_t mid, org_high; + BSEARCH(int64_as_double_to_num); } #endif else if (is_integer_p(beg) && is_integer_p(end)) { - RETURN_ENUMERATOR(range, 0, 0); - return bsearch_integer_range(beg, end, EXCL(range)); + RETURN_ENUMERATOR(range, 0, 0); + return bsearch_integer_range(beg, end, EXCL(range)); } else if (is_integer_p(beg) && NIL_P(end)) { - VALUE diff = LONG2FIX(1); - RETURN_ENUMERATOR(range, 0, 0); - while (1) { - VALUE mid = rb_funcall(beg, '+', 1, diff); - BSEARCH_CHECK(mid); - if (smaller) { - return bsearch_integer_range(beg, mid, 0); - } - diff = rb_funcall(diff, '*', 1, LONG2FIX(2)); - } + VALUE diff = LONG2FIX(1); + RETURN_ENUMERATOR(range, 0, 0); + while (1) { + VALUE mid = rb_funcall(beg, '+', 1, diff); + BSEARCH_CHECK(mid); + if (smaller) { + return bsearch_integer_range(beg, mid, 0); + } + diff = rb_funcall(diff, '*', 1, LONG2FIX(2)); + } } else if (NIL_P(beg) && is_integer_p(end)) { - VALUE diff = LONG2FIX(-1); - RETURN_ENUMERATOR(range, 0, 0); - while (1) { - VALUE mid = rb_funcall(end, '+', 1, diff); - BSEARCH_CHECK(mid); - if (!smaller) { - return bsearch_integer_range(mid, end, 0); - } - diff = rb_funcall(diff, '*', 1, LONG2FIX(2)); - } + VALUE diff = LONG2FIX(-1); + RETURN_ENUMERATOR(range, 0, 0); + while (1) { + VALUE mid = rb_funcall(end, '+', 1, diff); + BSEARCH_CHECK(mid); + if (!smaller) { + return bsearch_integer_range(mid, end, 0); + } + diff = rb_funcall(diff, '*', 1, LONG2FIX(2)); + } } else { - rb_raise(rb_eTypeError, "can't do binary search for %s", rb_obj_classname(beg)); + rb_raise(rb_eTypeError, "can't do binary search for %s", rb_obj_classname(beg)); } return range; } @@ -809,7 +809,7 @@ range_size(VALUE range) VALUE b = RANGE_BEG(range), e = RANGE_END(range); if (rb_obj_is_kind_of(b, rb_cNumeric)) { if (rb_obj_is_kind_of(e, rb_cNumeric)) { - return ruby_num_interval_step_size(b, e, INT2FIX(1), EXCL(range)); + return ruby_num_interval_step_size(b, e, INT2FIX(1), EXCL(range)); } if (NIL_P(e)) { return DBL2NUM(HUGE_VAL); @@ -840,7 +840,7 @@ static VALUE range_to_a(VALUE range) { if (NIL_P(RANGE_END(range))) { - rb_raise(rb_eRangeError, "cannot convert endless range to an array"); + rb_raise(rb_eRangeError, "cannot convert endless range to an array"); } return rb_call_super(0, 0); } @@ -918,78 +918,78 @@ range_each(VALUE range) return range_each_fixnum_loop(beg, end, range); } else if (RB_INTEGER_TYPE_P(beg) && (NIL_P(end) || RB_INTEGER_TYPE_P(end))) { - if (SPECIAL_CONST_P(end) || RBIGNUM_POSITIVE_P(end)) { /* end >= FIXNUM_MIN */ - if (!FIXNUM_P(beg)) { - if (RBIGNUM_NEGATIVE_P(beg)) { - do { - rb_yield(beg); - } while (!FIXNUM_P(beg = rb_big_plus(beg, INT2FIX(1)))); + if (SPECIAL_CONST_P(end) || RBIGNUM_POSITIVE_P(end)) { /* end >= FIXNUM_MIN */ + if (!FIXNUM_P(beg)) { + if (RBIGNUM_NEGATIVE_P(beg)) { + do { + rb_yield(beg); + } while (!FIXNUM_P(beg = rb_big_plus(beg, INT2FIX(1)))); if (NIL_P(end)) range_each_fixnum_endless(beg); if (FIXNUM_P(end)) return range_each_fixnum_loop(beg, end, range); - } - else { + } + else { if (NIL_P(end)) range_each_bignum_endless(beg); - if (FIXNUM_P(end)) return range; - } - } - if (FIXNUM_P(beg)) { - i = FIX2LONG(beg); - do { - rb_yield(LONG2FIX(i)); - } while (POSFIXABLE(++i)); - beg = LONG2NUM(i); - } - ASSUME(!FIXNUM_P(beg)); - ASSUME(!SPECIAL_CONST_P(end)); - } - if (!FIXNUM_P(beg) && RBIGNUM_SIGN(beg) == RBIGNUM_SIGN(end)) { - if (EXCL(range)) { - while (rb_big_cmp(beg, end) == INT2FIX(-1)) { - rb_yield(beg); - beg = rb_big_plus(beg, INT2FIX(1)); - } - } - else { - VALUE c; - while ((c = rb_big_cmp(beg, end)) != INT2FIX(1)) { - rb_yield(beg); - if (c == INT2FIX(0)) break; - beg = rb_big_plus(beg, INT2FIX(1)); - } - } - } + if (FIXNUM_P(end)) return range; + } + } + if (FIXNUM_P(beg)) { + i = FIX2LONG(beg); + do { + rb_yield(LONG2FIX(i)); + } while (POSFIXABLE(++i)); + beg = LONG2NUM(i); + } + ASSUME(!FIXNUM_P(beg)); + ASSUME(!SPECIAL_CONST_P(end)); + } + if (!FIXNUM_P(beg) && RBIGNUM_SIGN(beg) == RBIGNUM_SIGN(end)) { + if (EXCL(range)) { + while (rb_big_cmp(beg, end) == INT2FIX(-1)) { + rb_yield(beg); + beg = rb_big_plus(beg, INT2FIX(1)); + } + } + else { + VALUE c; + while ((c = rb_big_cmp(beg, end)) != INT2FIX(1)) { + rb_yield(beg); + if (c == INT2FIX(0)) break; + beg = rb_big_plus(beg, INT2FIX(1)); + } + } + } } else if (SYMBOL_P(beg) && (NIL_P(end) || SYMBOL_P(end))) { /* symbols are special */ - beg = rb_sym2str(beg); - if (NIL_P(end)) { - rb_str_upto_endless_each(beg, sym_each_i, 0); - } - else { - rb_str_upto_each(beg, rb_sym2str(end), EXCL(range), sym_each_i, 0); - } + beg = rb_sym2str(beg); + if (NIL_P(end)) { + rb_str_upto_endless_each(beg, sym_each_i, 0); + } + else { + rb_str_upto_each(beg, rb_sym2str(end), EXCL(range), sym_each_i, 0); + } } else { - VALUE tmp = rb_check_string_type(beg); + VALUE tmp = rb_check_string_type(beg); - if (!NIL_P(tmp)) { - if (!NIL_P(end)) { - rb_str_upto_each(tmp, end, EXCL(range), each_i, 0); - } - else { - rb_str_upto_endless_each(tmp, each_i, 0); - } - } - else { - if (!discrete_object_p(beg)) { - rb_raise(rb_eTypeError, "can't iterate from %s", - rb_obj_classname(beg)); - } - if (!NIL_P(end)) - range_each_func(range, each_i, 0); - else - for (;; beg = rb_funcallv(beg, id_succ, 0, 0)) - rb_yield(beg); - } + if (!NIL_P(tmp)) { + if (!NIL_P(end)) { + rb_str_upto_each(tmp, end, EXCL(range), each_i, 0); + } + else { + rb_str_upto_endless_each(tmp, each_i, 0); + } + } + else { + if (!discrete_object_p(beg)) { + rb_raise(rb_eTypeError, "can't iterate from %s", + rb_obj_classname(beg)); + } + if (!NIL_P(end)) + range_each_func(range, each_i, 0); + else + for (;; beg = rb_funcallv(beg, id_succ, 0, 0)) + rb_yield(beg); + } } return range; } @@ -1041,7 +1041,7 @@ first_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, cbarg)) long n = NUM2LONG(ary[0]); if (n <= 0) { - rb_iter_break(); + rb_iter_break(); } rb_ary_push(ary[1], i); n--; @@ -1282,27 +1282,27 @@ static VALUE range_min(int argc, VALUE *argv, VALUE range) { if (NIL_P(RANGE_BEG(range))) { - rb_raise(rb_eRangeError, "cannot get the minimum of beginless range"); + rb_raise(rb_eRangeError, "cannot get the minimum of beginless range"); } if (rb_block_given_p()) { if (NIL_P(RANGE_END(range))) { rb_raise(rb_eRangeError, "cannot get the minimum of endless range with custom comparison method"); } - return rb_call_super(argc, argv); + return rb_call_super(argc, argv); } else if (argc != 0) { - return range_first(argc, argv, range); + return range_first(argc, argv, range); } else { - struct cmp_opt_data cmp_opt = { 0, 0 }; - VALUE b = RANGE_BEG(range); - VALUE e = RANGE_END(range); - int c = NIL_P(e) ? -1 : OPTIMIZED_CMP(b, e, cmp_opt); + struct cmp_opt_data cmp_opt = { 0, 0 }; + VALUE b = RANGE_BEG(range); + VALUE e = RANGE_END(range); + int c = NIL_P(e) ? -1 : OPTIMIZED_CMP(b, e, cmp_opt); - if (c > 0 || (c == 0 && EXCL(range))) - return Qnil; - return b; + if (c > 0 || (c == 0 && EXCL(range))) + return Qnil; + return b; } } @@ -1394,7 +1394,7 @@ range_max(int argc, VALUE *argv, VALUE range) int nm = FIXNUM_P(e) || rb_obj_is_kind_of(e, rb_cNumeric); if (NIL_P(RANGE_END(range))) { - rb_raise(rb_eRangeError, "cannot get the maximum of endless range"); + rb_raise(rb_eRangeError, "cannot get the maximum of endless range"); } VALUE b = RANGE_BEG(range); @@ -1493,22 +1493,22 @@ rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp) int excl; if (rb_obj_is_kind_of(range, rb_cRange)) { - b = RANGE_BEG(range); - e = RANGE_END(range); - excl = EXCL(range); + b = RANGE_BEG(range); + e = RANGE_END(range); + excl = EXCL(range); } else if (RTEST(rb_obj_is_kind_of(range, rb_cArithSeq))) { return (int)Qfalse; } else { - VALUE x; - b = rb_check_funcall(range, id_beg, 0, 0); - if (b == Qundef) return (int)Qfalse; - e = rb_check_funcall(range, id_end, 0, 0); - if (e == Qundef) return (int)Qfalse; - x = rb_check_funcall(range, rb_intern("exclude_end?"), 0, 0); - if (x == Qundef) return (int)Qfalse; - excl = RTEST(x); + VALUE x; + b = rb_check_funcall(range, id_beg, 0, 0); + if (b == Qundef) return (int)Qfalse; + e = rb_check_funcall(range, id_end, 0, 0); + if (e == Qundef) return (int)Qfalse; + x = rb_check_funcall(range, rb_intern("exclude_end?"), 0, 0); + if (x == Qundef) return (int)Qfalse; + excl = RTEST(x); } *begp = b; *endp = e; @@ -1632,7 +1632,7 @@ inspect_range(VALUE range, VALUE dummy, int recur) VALUE str, str2 = Qundef; if (recur) { - return rb_str_new2(EXCL(range) ? "(... ... ...)" : "(... .. ...)"); + return rb_str_new2(EXCL(range) ? "(... ... ...)" : "(... .. ...)"); } if (!NIL_P(RANGE_BEG(range)) || NIL_P(RANGE_END(range))) { str = rb_str_dup(rb_inspect(RANGE_BEG(range))); @@ -1772,12 +1772,12 @@ range_include_internal(VALUE range, VALUE val, int string_use_cover) VALUE beg = RANGE_BEG(range); VALUE end = RANGE_END(range); int nv = FIXNUM_P(beg) || FIXNUM_P(end) || - linear_object_p(beg) || linear_object_p(end); + linear_object_p(beg) || linear_object_p(end); if (nv || - !NIL_P(rb_check_to_integer(beg, "to_int")) || - !NIL_P(rb_check_to_integer(end, "to_int"))) { - return r_cover_p(range, beg, end, val); + !NIL_P(rb_check_to_integer(beg, "to_int")) || + !NIL_P(rb_check_to_integer(end, "to_int"))) { + return r_cover_p(range, beg, end, val); } else if (RB_TYPE_P(beg, T_STRING) || RB_TYPE_P(end, T_STRING)) { if (RB_TYPE_P(beg, T_STRING) && RB_TYPE_P(end, T_STRING)) { @@ -1790,18 +1790,18 @@ range_include_internal(VALUE range, VALUE val, int string_use_cover) } } else if (NIL_P(beg)) { - VALUE r = rb_funcall(val, id_cmp, 1, end); - if (NIL_P(r)) return Qfalse; + VALUE r = rb_funcall(val, id_cmp, 1, end); + if (NIL_P(r)) return Qfalse; if (RANGE_EXCL(range)) { return RBOOL(rb_cmpint(r, val, end) < 0); } return RBOOL(rb_cmpint(r, val, end) <= 0); } - else if (NIL_P(end)) { - VALUE r = rb_funcall(beg, id_cmp, 1, val); - if (NIL_P(r)) return Qfalse; + else if (NIL_P(end)) { + VALUE r = rb_funcall(beg, id_cmp, 1, val); + if (NIL_P(r)) return Qfalse; return RBOOL(rb_cmpint(r, beg, val) <= 0); - } + } } return Qundef; } @@ -2000,9 +2000,9 @@ static VALUE r_cover_p(VALUE range, VALUE beg, VALUE end, VALUE val) { if (NIL_P(beg) || r_less(beg, val) <= 0) { - int excl = EXCL(range); - if (NIL_P(end) || r_less(val, end) <= -excl) - return Qtrue; + int excl = EXCL(range); + if (NIL_P(end) || r_less(val, end) <= -excl) + return Qtrue; } return Qfalse; } @@ -2032,7 +2032,7 @@ range_loader(VALUE range, VALUE obj) end = rb_ivar_get(obj, id_end); excl = rb_ivar_get(obj, id_excl); if (!NIL_P(excl)) { - range_init(range, beg, end, RBOOL(RTEST(excl))); + range_init(range, beg, end, RBOOL(RTEST(excl))); } return range; } diff --git a/rational.c b/rational.c index 093de5fa5b..e537bd498b 100644 --- a/rational.c +++ b/rational.c @@ -62,9 +62,9 @@ inline static VALUE f_add(VALUE x, VALUE y) { if (FIXNUM_ZERO_P(y)) - return x; + return x; if (FIXNUM_ZERO_P(x)) - return y; + return y; if (RB_INTEGER_TYPE_P(x)) return rb_int_plus(x, y); return rb_funcall(x, '+', 1, y); @@ -74,9 +74,9 @@ inline static VALUE f_div(VALUE x, VALUE y) { if (y == ONE) - return x; + return x; if (RB_INTEGER_TYPE_P(x)) - return rb_int_div(x, y); + return rb_int_div(x, y); return rb_funcall(x, '/', 1, y); } @@ -84,7 +84,7 @@ inline static int f_lt_p(VALUE x, VALUE y) { if (FIXNUM_P(x) && FIXNUM_P(y)) - return (SIGNED_VALUE)x < (SIGNED_VALUE)y; + return (SIGNED_VALUE)x < (SIGNED_VALUE)y; if (RB_INTEGER_TYPE_P(x)) { VALUE r = rb_int_cmp(x, y); if (!NIL_P(r)) return rb_int_negative_p(r); @@ -107,13 +107,13 @@ inline static VALUE f_mul(VALUE x, VALUE y) { if (FIXNUM_ZERO_P(y) && RB_INTEGER_TYPE_P(x)) - return ZERO; + return ZERO; if (y == ONE) return x; if (FIXNUM_ZERO_P(x) && RB_INTEGER_TYPE_P(y)) - return ZERO; + return ZERO; if (x == ONE) return y; else if (RB_INTEGER_TYPE_P(x)) - return rb_int_mul(x, y); + return rb_int_mul(x, y); return rb_funcall(x, '*', 1, y); } @@ -121,7 +121,7 @@ inline static VALUE f_sub(VALUE x, VALUE y) { if (FIXNUM_P(y) && FIXNUM_ZERO_P(y)) - return x; + return x; return rb_funcall(x, '-', 1, y); } @@ -129,7 +129,7 @@ inline static VALUE f_abs(VALUE x) { if (RB_INTEGER_TYPE_P(x)) - return rb_int_abs(x); + return rb_int_abs(x); return rb_funcall(x, id_abs, 0); } @@ -144,7 +144,7 @@ inline static VALUE f_to_i(VALUE x) { if (RB_TYPE_P(x, T_STRING)) - return rb_str_to_inum(x, 10, 0); + return rb_str_to_inum(x, 10, 0); return rb_funcall(x, id_to_i, 0); } @@ -152,7 +152,7 @@ inline static int f_eqeq_p(VALUE x, VALUE y) { if (FIXNUM_P(x) && FIXNUM_P(y)) - return x == y; + return x == y; if (RB_INTEGER_TYPE_P(x)) return RTEST(rb_int_equal(x, y)); return (int)rb_equal(x, y); @@ -162,7 +162,7 @@ inline static VALUE f_idiv(VALUE x, VALUE y) { if (RB_INTEGER_TYPE_P(x)) - return rb_int_idiv(x, y); + return rb_int_idiv(x, y); return rb_funcall(x, id_idiv, 1, y); } @@ -172,12 +172,12 @@ inline static int f_zero_p(VALUE x) { if (RB_INTEGER_TYPE_P(x)) { - return FIXNUM_ZERO_P(x); + return FIXNUM_ZERO_P(x); } else if (RB_TYPE_P(x, T_RATIONAL)) { - VALUE num = RRATIONAL(x)->num; + VALUE num = RRATIONAL(x)->num; - return FIXNUM_ZERO_P(num); + return FIXNUM_ZERO_P(num); } return (int)rb_equal(x, ZERO); } @@ -188,13 +188,13 @@ inline static int f_one_p(VALUE x) { if (RB_INTEGER_TYPE_P(x)) { - return x == LONG2FIX(1); + return x == LONG2FIX(1); } else if (RB_TYPE_P(x, T_RATIONAL)) { - VALUE num = RRATIONAL(x)->num; - VALUE den = RRATIONAL(x)->den; + VALUE num = RRATIONAL(x)->num; + VALUE den = RRATIONAL(x)->den; - return num == LONG2FIX(1) && den == LONG2FIX(1); + return num == LONG2FIX(1) && den == LONG2FIX(1); } return (int)rb_equal(x, ONE); } @@ -203,16 +203,16 @@ inline static int f_minus_one_p(VALUE x) { if (RB_INTEGER_TYPE_P(x)) { - return x == LONG2FIX(-1); + return x == LONG2FIX(-1); } else if (RB_BIGNUM_TYPE_P(x)) { - return Qfalse; + return Qfalse; } else if (RB_TYPE_P(x, T_RATIONAL)) { - VALUE num = RRATIONAL(x)->num; - VALUE den = RRATIONAL(x)->den; + VALUE num = RRATIONAL(x)->num; + VALUE den = RRATIONAL(x)->den; - return num == LONG2FIX(-1) && den == LONG2FIX(1); + return num == LONG2FIX(-1) && den == LONG2FIX(1); } return (int)rb_equal(x, INT2FIX(-1)); } @@ -295,35 +295,35 @@ i_gcd(long x, long y) int shift; if (x < 0) - x = -x; + x = -x; if (y < 0) - y = -y; + y = -y; if (x == 0) - return y; + return y; if (y == 0) - return x; + return x; u = (unsigned long)x; v = (unsigned long)y; for (shift = 0; ((u | v) & 1) == 0; ++shift) { - u >>= 1; - v >>= 1; + u >>= 1; + v >>= 1; } while ((u & 1) == 0) - u >>= 1; + u >>= 1; do { - while ((v & 1) == 0) - v >>= 1; + while ((v & 1) == 0) + v >>= 1; - if (u > v) { - t = v; - v = u; - u = t; - } - v = v - u; + if (u > v) { + t = v; + v = u; + u = t; + } + v = v - u; } while (v != 0); return (long)(u << shift); @@ -335,28 +335,28 @@ f_gcd_normal(VALUE x, VALUE y) VALUE z; if (FIXNUM_P(x) && FIXNUM_P(y)) - return LONG2NUM(i_gcd(FIX2LONG(x), FIX2LONG(y))); + return LONG2NUM(i_gcd(FIX2LONG(x), FIX2LONG(y))); if (INT_NEGATIVE_P(x)) - x = rb_int_uminus(x); + x = rb_int_uminus(x); if (INT_NEGATIVE_P(y)) - y = rb_int_uminus(y); + y = rb_int_uminus(y); if (INT_ZERO_P(x)) - return y; + return y; if (INT_ZERO_P(y)) - return x; + return x; for (;;) { - if (FIXNUM_P(x)) { - if (FIXNUM_ZERO_P(x)) - return y; - if (FIXNUM_P(y)) - return LONG2NUM(i_gcd(FIX2LONG(x), FIX2LONG(y))); - } - z = x; - x = rb_int_modulo(y, x); - y = z; + if (FIXNUM_P(x)) { + if (FIXNUM_ZERO_P(x)) + return y; + if (FIXNUM_P(y)) + return LONG2NUM(i_gcd(FIX2LONG(x), FIX2LONG(y))); + } + z = x; + x = rb_int_modulo(y, x); + y = z; } /* NOTREACHED */ } @@ -389,8 +389,8 @@ f_gcd(VALUE x, VALUE y) { VALUE r = f_gcd_orig(x, y); if (f_nonzero_p(r)) { - assert(f_zero_p(f_mod(x, r))); - assert(f_zero_p(f_mod(y, r))); + assert(f_zero_p(f_mod(x, r))); + assert(f_zero_p(f_mod(y, r))); } return r; } @@ -400,7 +400,7 @@ inline static VALUE f_lcm(VALUE x, VALUE y) { if (INT_ZERO_P(x) || INT_ZERO_P(y)) - return ZERO; + return ZERO; return f_abs(f_mul(f_div(x, f_gcd(x, y)), y)); } @@ -438,8 +438,8 @@ inline static void nurat_int_check(VALUE num) { if (!RB_INTEGER_TYPE_P(num)) { - if (!k_numeric_p(num) || !f_integer_p(num)) - rb_raise(rb_eTypeError, "not an integer"); + if (!k_numeric_p(num) || !f_integer_p(num)) + rb_raise(rb_eTypeError, "not an integer"); } } @@ -448,7 +448,7 @@ nurat_int_value(VALUE num) { nurat_int_check(num); if (!k_integer_p(num)) - num = f_to_i(num); + num = f_to_i(num); return num; } @@ -625,14 +625,14 @@ f_imul(long a, long b) VALUE r; if (a == 0 || b == 0) - return ZERO; + return ZERO; else if (a == 1) - return LONG2NUM(b); + return LONG2NUM(b); else if (b == 1) - return LONG2NUM(a); + return LONG2NUM(a); if (MUL_OVERFLOW_LONG_P(a, b)) - r = rb_big_mul(rb_int2big(a), rb_int2big(b)); + r = rb_big_mul(rb_int2big(a), rb_int2big(b)); else r = LONG2NUM(a * b); return r; @@ -656,46 +656,46 @@ f_addsub(VALUE self, VALUE anum, VALUE aden, VALUE bnum, VALUE bden, int k) VALUE num, den; if (FIXNUM_P(anum) && FIXNUM_P(aden) && - FIXNUM_P(bnum) && FIXNUM_P(bden)) { - long an = FIX2LONG(anum); - long ad = FIX2LONG(aden); - long bn = FIX2LONG(bnum); - long bd = FIX2LONG(bden); - long ig = i_gcd(ad, bd); + FIXNUM_P(bnum) && FIXNUM_P(bden)) { + long an = FIX2LONG(anum); + long ad = FIX2LONG(aden); + long bn = FIX2LONG(bnum); + long bd = FIX2LONG(bden); + long ig = i_gcd(ad, bd); - VALUE g = LONG2NUM(ig); - VALUE a = f_imul(an, bd / ig); - VALUE b = f_imul(bn, ad / ig); - VALUE c; + VALUE g = LONG2NUM(ig); + VALUE a = f_imul(an, bd / ig); + VALUE b = f_imul(bn, ad / ig); + VALUE c; - if (k == '+') - c = rb_int_plus(a, b); - else - c = rb_int_minus(a, b); + if (k == '+') + c = rb_int_plus(a, b); + else + c = rb_int_minus(a, b); - b = rb_int_idiv(aden, g); - g = f_gcd(c, g); - num = rb_int_idiv(c, g); - a = rb_int_idiv(bden, g); - den = rb_int_mul(a, b); + b = rb_int_idiv(aden, g); + g = f_gcd(c, g); + num = rb_int_idiv(c, g); + a = rb_int_idiv(bden, g); + den = rb_int_mul(a, b); } else if (RB_INTEGER_TYPE_P(anum) && RB_INTEGER_TYPE_P(aden) && RB_INTEGER_TYPE_P(bnum) && RB_INTEGER_TYPE_P(bden)) { - VALUE g = f_gcd(aden, bden); - VALUE a = rb_int_mul(anum, rb_int_idiv(bden, g)); - VALUE b = rb_int_mul(bnum, rb_int_idiv(aden, g)); - VALUE c; + VALUE g = f_gcd(aden, bden); + VALUE a = rb_int_mul(anum, rb_int_idiv(bden, g)); + VALUE b = rb_int_mul(bnum, rb_int_idiv(aden, g)); + VALUE c; - if (k == '+') - c = rb_int_plus(a, b); - else - c = rb_int_minus(a, b); + if (k == '+') + c = rb_int_plus(a, b); + else + c = rb_int_minus(a, b); - b = rb_int_idiv(aden, g); - g = f_gcd(c, g); - num = rb_int_idiv(c, g); - a = rb_int_idiv(bden, g); - den = rb_int_mul(a, b); + b = rb_int_idiv(aden, g); + g = f_gcd(c, g); + num = rb_int_idiv(c, g); + a = rb_int_idiv(bden, g); + den = rb_int_mul(a, b); } else { double a = NUM2DBL(anum) / NUM2DBL(aden); @@ -723,28 +723,28 @@ VALUE rb_rational_plus(VALUE self, VALUE other) { if (RB_INTEGER_TYPE_P(other)) { - { - get_dat1(self); + { + get_dat1(self); - return f_rational_new_no_reduce2(CLASS_OF(self), - rb_int_plus(dat->num, rb_int_mul(other, dat->den)), - dat->den); - } + return f_rational_new_no_reduce2(CLASS_OF(self), + rb_int_plus(dat->num, rb_int_mul(other, dat->den)), + dat->den); + } } else if (RB_FLOAT_TYPE_P(other)) { - return DBL2NUM(nurat_to_double(self) + RFLOAT_VALUE(other)); + return DBL2NUM(nurat_to_double(self) + RFLOAT_VALUE(other)); } else if (RB_TYPE_P(other, T_RATIONAL)) { - { - get_dat2(self, other); + { + get_dat2(self, other); - return f_addsub(self, - adat->num, adat->den, - bdat->num, bdat->den, '+'); - } + return f_addsub(self, + adat->num, adat->den, + bdat->num, bdat->den, '+'); + } } else { - return rb_num_coerce_bin(self, other, '+'); + return rb_num_coerce_bin(self, other, '+'); } } @@ -764,28 +764,28 @@ VALUE rb_rational_minus(VALUE self, VALUE other) { if (RB_INTEGER_TYPE_P(other)) { - { - get_dat1(self); + { + get_dat1(self); - return f_rational_new_no_reduce2(CLASS_OF(self), - rb_int_minus(dat->num, rb_int_mul(other, dat->den)), - dat->den); - } + return f_rational_new_no_reduce2(CLASS_OF(self), + rb_int_minus(dat->num, rb_int_mul(other, dat->den)), + dat->den); + } } else if (RB_FLOAT_TYPE_P(other)) { - return DBL2NUM(nurat_to_double(self) - RFLOAT_VALUE(other)); + return DBL2NUM(nurat_to_double(self) - RFLOAT_VALUE(other)); } else if (RB_TYPE_P(other, T_RATIONAL)) { - { - get_dat2(self, other); + { + get_dat2(self, other); - return f_addsub(self, - adat->num, adat->den, - bdat->num, bdat->den, '-'); - } + return f_addsub(self, + adat->num, adat->den, + bdat->num, bdat->den, '-'); + } } else { - return rb_num_coerce_bin(self, other, '-'); + return rb_num_coerce_bin(self, other, '-'); } } @@ -811,35 +811,35 @@ f_muldiv(VALUE self, VALUE anum, VALUE aden, VALUE bnum, VALUE bden, int k) assert(RB_INTEGER_TYPE_P(bden)); if (k == '/') { - VALUE t; + VALUE t; - if (INT_NEGATIVE_P(bnum)) { - anum = rb_int_uminus(anum); - bnum = rb_int_uminus(bnum); - } - t = bnum; - bnum = bden; - bden = t; + if (INT_NEGATIVE_P(bnum)) { + anum = rb_int_uminus(anum); + bnum = rb_int_uminus(bnum); + } + t = bnum; + bnum = bden; + bden = t; } if (FIXNUM_P(anum) && FIXNUM_P(aden) && - FIXNUM_P(bnum) && FIXNUM_P(bden)) { - long an = FIX2LONG(anum); - long ad = FIX2LONG(aden); - long bn = FIX2LONG(bnum); - long bd = FIX2LONG(bden); - long g1 = i_gcd(an, bd); - long g2 = i_gcd(ad, bn); + FIXNUM_P(bnum) && FIXNUM_P(bden)) { + long an = FIX2LONG(anum); + long ad = FIX2LONG(aden); + long bn = FIX2LONG(bnum); + long bd = FIX2LONG(bden); + long g1 = i_gcd(an, bd); + long g2 = i_gcd(ad, bn); - num = f_imul(an / g1, bn / g2); - den = f_imul(ad / g2, bd / g1); + num = f_imul(an / g1, bn / g2); + den = f_imul(ad / g2, bd / g1); } else { - VALUE g1 = f_gcd(anum, bden); - VALUE g2 = f_gcd(aden, bnum); + VALUE g1 = f_gcd(anum, bden); + VALUE g2 = f_gcd(aden, bnum); - num = rb_int_mul(rb_int_idiv(anum, g1), rb_int_idiv(bnum, g2)); - den = rb_int_mul(rb_int_idiv(aden, g2), rb_int_idiv(bden, g1)); + num = rb_int_mul(rb_int_idiv(anum, g1), rb_int_idiv(bnum, g2)); + den = rb_int_mul(rb_int_idiv(aden, g2), rb_int_idiv(bden, g1)); } return f_rational_new_no_reduce2(CLASS_OF(self), num, den); } @@ -860,28 +860,28 @@ VALUE rb_rational_mul(VALUE self, VALUE other) { if (RB_INTEGER_TYPE_P(other)) { - { - get_dat1(self); + { + get_dat1(self); - return f_muldiv(self, - dat->num, dat->den, - other, ONE, '*'); - } + return f_muldiv(self, + dat->num, dat->den, + other, ONE, '*'); + } } else if (RB_FLOAT_TYPE_P(other)) { - return DBL2NUM(nurat_to_double(self) * RFLOAT_VALUE(other)); + return DBL2NUM(nurat_to_double(self) * RFLOAT_VALUE(other)); } else if (RB_TYPE_P(other, T_RATIONAL)) { - { - get_dat2(self, other); + { + get_dat2(self, other); - return f_muldiv(self, - adat->num, adat->den, - bdat->num, bdat->den, '*'); - } + return f_muldiv(self, + adat->num, adat->den, + bdat->num, bdat->den, '*'); + } } else { - return rb_num_coerce_bin(self, other, '*'); + return rb_num_coerce_bin(self, other, '*'); } } @@ -902,37 +902,37 @@ VALUE rb_rational_div(VALUE self, VALUE other) { if (RB_INTEGER_TYPE_P(other)) { - if (f_zero_p(other)) + if (f_zero_p(other)) rb_num_zerodiv(); - { - get_dat1(self); + { + get_dat1(self); - return f_muldiv(self, - dat->num, dat->den, - other, ONE, '/'); - } + return f_muldiv(self, + dat->num, dat->den, + other, ONE, '/'); + } } else if (RB_FLOAT_TYPE_P(other)) { VALUE v = nurat_to_f(self); return rb_flo_div_flo(v, other); } else if (RB_TYPE_P(other, T_RATIONAL)) { - if (f_zero_p(other)) + if (f_zero_p(other)) rb_num_zerodiv(); - { - get_dat2(self, other); + { + get_dat2(self, other); - if (f_one_p(self)) - return f_rational_new_no_reduce2(CLASS_OF(self), - bdat->den, bdat->num); + if (f_one_p(self)) + return f_rational_new_no_reduce2(CLASS_OF(self), + bdat->den, bdat->num); - return f_muldiv(self, - adat->num, adat->den, - bdat->num, bdat->den, '/'); - } + return f_muldiv(self, + adat->num, adat->den, + bdat->num, bdat->den, '/'); + } } else { - return rb_num_coerce_bin(self, other, '/'); + return rb_num_coerce_bin(self, other, '/'); } } @@ -953,12 +953,12 @@ nurat_fdiv(VALUE self, VALUE other) if (f_zero_p(other)) return rb_rational_div(self, rb_float_new(0.0)); if (FIXNUM_P(other) && other == LONG2FIX(1)) - return nurat_to_f(self); + return nurat_to_f(self); div = rb_rational_div(self, other); if (RB_TYPE_P(div, T_RATIONAL)) - return nurat_to_f(div); + return nurat_to_f(div); if (RB_FLOAT_TYPE_P(div)) - return div; + return div; return rb_funcall(div, idTo_f, 0); } @@ -979,76 +979,76 @@ VALUE rb_rational_pow(VALUE self, VALUE other) { if (k_numeric_p(other) && k_exact_zero_p(other)) - return f_rational_new_bang1(CLASS_OF(self), ONE); + return f_rational_new_bang1(CLASS_OF(self), ONE); if (k_rational_p(other)) { - get_dat1(other); + get_dat1(other); - if (f_one_p(dat->den)) - other = dat->num; /* c14n */ + if (f_one_p(dat->den)) + other = dat->num; /* c14n */ } /* Deal with special cases of 0**n and 1**n */ if (k_numeric_p(other) && k_exact_p(other)) { - get_dat1(self); - if (f_one_p(dat->den)) { - if (f_one_p(dat->num)) { - return f_rational_new_bang1(CLASS_OF(self), ONE); - } - else if (f_minus_one_p(dat->num) && RB_INTEGER_TYPE_P(other)) { - return f_rational_new_bang1(CLASS_OF(self), INT2FIX(rb_int_odd_p(other) ? -1 : 1)); - } - else if (INT_ZERO_P(dat->num)) { - if (rb_num_negative_p(other)) { + get_dat1(self); + if (f_one_p(dat->den)) { + if (f_one_p(dat->num)) { + return f_rational_new_bang1(CLASS_OF(self), ONE); + } + else if (f_minus_one_p(dat->num) && RB_INTEGER_TYPE_P(other)) { + return f_rational_new_bang1(CLASS_OF(self), INT2FIX(rb_int_odd_p(other) ? -1 : 1)); + } + else if (INT_ZERO_P(dat->num)) { + if (rb_num_negative_p(other)) { rb_num_zerodiv(); - } - else { - return f_rational_new_bang1(CLASS_OF(self), ZERO); - } - } - } + } + else { + return f_rational_new_bang1(CLASS_OF(self), ZERO); + } + } + } } /* General case */ if (FIXNUM_P(other)) { - { - VALUE num, den; + { + VALUE num, den; - get_dat1(self); + get_dat1(self); if (INT_POSITIVE_P(other)) { - num = rb_int_pow(dat->num, other); - den = rb_int_pow(dat->den, other); + num = rb_int_pow(dat->num, other); + den = rb_int_pow(dat->den, other); } else if (INT_NEGATIVE_P(other)) { - num = rb_int_pow(dat->den, rb_int_uminus(other)); - den = rb_int_pow(dat->num, rb_int_uminus(other)); + num = rb_int_pow(dat->den, rb_int_uminus(other)); + den = rb_int_pow(dat->num, rb_int_uminus(other)); } else { - num = ONE; - den = ONE; - } - if (RB_FLOAT_TYPE_P(num)) { /* infinity due to overflow */ - if (RB_FLOAT_TYPE_P(den)) - return DBL2NUM(nan("")); - return num; - } - if (RB_FLOAT_TYPE_P(den)) { /* infinity due to overflow */ - num = ZERO; - den = ONE; - } - return f_rational_new2(CLASS_OF(self), num, den); - } + num = ONE; + den = ONE; + } + if (RB_FLOAT_TYPE_P(num)) { /* infinity due to overflow */ + if (RB_FLOAT_TYPE_P(den)) + return DBL2NUM(nan("")); + return num; + } + if (RB_FLOAT_TYPE_P(den)) { /* infinity due to overflow */ + num = ZERO; + den = ONE; + } + return f_rational_new2(CLASS_OF(self), num, den); + } } else if (RB_BIGNUM_TYPE_P(other)) { - rb_warn("in a**b, b may be too big"); - return rb_float_pow(nurat_to_f(self), other); + rb_warn("in a**b, b may be too big"); + return rb_float_pow(nurat_to_f(self), other); } else if (RB_FLOAT_TYPE_P(other) || RB_TYPE_P(other, T_RATIONAL)) { - return rb_float_pow(nurat_to_f(self), other); + return rb_float_pow(nurat_to_f(self), other); } else { - return rb_num_coerce_bin(self, other, idPow); + return rb_num_coerce_bin(self, other, idPow); } } #define nurat_expt rb_rational_pow @@ -1076,38 +1076,38 @@ rb_rational_cmp(VALUE self, VALUE other) switch (TYPE(other)) { case T_FIXNUM: case T_BIGNUM: - { - get_dat1(self); + { + get_dat1(self); - if (dat->den == LONG2FIX(1)) - return rb_int_cmp(dat->num, other); /* c14n */ - other = f_rational_new_bang1(CLASS_OF(self), other); + if (dat->den == LONG2FIX(1)) + return rb_int_cmp(dat->num, other); /* c14n */ + other = f_rational_new_bang1(CLASS_OF(self), other); /* FALLTHROUGH */ - } + } case T_RATIONAL: - { - VALUE num1, num2; + { + VALUE num1, num2; - get_dat2(self, other); + get_dat2(self, other); - if (FIXNUM_P(adat->num) && FIXNUM_P(adat->den) && - FIXNUM_P(bdat->num) && FIXNUM_P(bdat->den)) { - num1 = f_imul(FIX2LONG(adat->num), FIX2LONG(bdat->den)); - num2 = f_imul(FIX2LONG(bdat->num), FIX2LONG(adat->den)); - } - else { - num1 = rb_int_mul(adat->num, bdat->den); - num2 = rb_int_mul(bdat->num, adat->den); - } - return rb_int_cmp(rb_int_minus(num1, num2), ZERO); - } + if (FIXNUM_P(adat->num) && FIXNUM_P(adat->den) && + FIXNUM_P(bdat->num) && FIXNUM_P(bdat->den)) { + num1 = f_imul(FIX2LONG(adat->num), FIX2LONG(bdat->den)); + num2 = f_imul(FIX2LONG(bdat->num), FIX2LONG(adat->den)); + } + else { + num1 = rb_int_mul(adat->num, bdat->den); + num2 = rb_int_mul(bdat->num, adat->den); + } + return rb_int_cmp(rb_int_minus(num1, num2), ZERO); + } case T_FLOAT: return rb_dbl_cmp(nurat_to_double(self), RFLOAT_VALUE(other)); default: - return rb_num_coerce_cmp(self, other, idCmp); + return rb_num_coerce_cmp(self, other, idCmp); } } @@ -1130,37 +1130,37 @@ nurat_eqeq_p(VALUE self, VALUE other) get_dat1(self); if (RB_INTEGER_TYPE_P(dat->num) && RB_INTEGER_TYPE_P(dat->den)) { - if (INT_ZERO_P(dat->num) && INT_ZERO_P(other)) - return Qtrue; + if (INT_ZERO_P(dat->num) && INT_ZERO_P(other)) + return Qtrue; - if (!FIXNUM_P(dat->den)) - return Qfalse; - if (FIX2LONG(dat->den) != 1) - return Qfalse; - return rb_int_equal(dat->num, other); - } + if (!FIXNUM_P(dat->den)) + return Qfalse; + if (FIX2LONG(dat->den) != 1) + return Qfalse; + return rb_int_equal(dat->num, other); + } else { const double d = nurat_to_double(self); return RBOOL(FIXNUM_ZERO_P(rb_dbl_cmp(d, NUM2DBL(other)))); } } else if (RB_FLOAT_TYPE_P(other)) { - const double d = nurat_to_double(self); - return RBOOL(FIXNUM_ZERO_P(rb_dbl_cmp(d, RFLOAT_VALUE(other)))); + const double d = nurat_to_double(self); + return RBOOL(FIXNUM_ZERO_P(rb_dbl_cmp(d, RFLOAT_VALUE(other)))); } else if (RB_TYPE_P(other, T_RATIONAL)) { - { - get_dat2(self, other); + { + get_dat2(self, other); - if (INT_ZERO_P(adat->num) && INT_ZERO_P(bdat->num)) - return Qtrue; + if (INT_ZERO_P(adat->num) && INT_ZERO_P(bdat->num)) + return Qtrue; - return RBOOL(rb_int_equal(adat->num, bdat->num) && - rb_int_equal(adat->den, bdat->den)); - } + return RBOOL(rb_int_equal(adat->num, bdat->num) && + rb_int_equal(adat->den, bdat->den)); + } } else { - return rb_equal(other, self); + return rb_equal(other, self); } } @@ -1169,17 +1169,17 @@ static VALUE nurat_coerce(VALUE self, VALUE other) { if (RB_INTEGER_TYPE_P(other)) { - return rb_assoc_new(f_rational_new_bang1(CLASS_OF(self), other), self); + return rb_assoc_new(f_rational_new_bang1(CLASS_OF(self), other), self); } else if (RB_FLOAT_TYPE_P(other)) { return rb_assoc_new(other, nurat_to_f(self)); } else if (RB_TYPE_P(other, T_RATIONAL)) { - return rb_assoc_new(other, self); + return rb_assoc_new(other, self); } else if (RB_TYPE_P(other, T_COMPLEX)) { - if (!k_exact_zero_p(RCOMPLEX(other)->imag)) - return rb_assoc_new(other, rb_Complex(self, INT2FIX(0))); + if (!k_exact_zero_p(RCOMPLEX(other)->imag)) + return rb_assoc_new(other, rb_Complex(self, INT2FIX(0))); other = RCOMPLEX(other)->real; if (RB_FLOAT_TYPE_P(other)) { other = float_to_r(other); @@ -1192,7 +1192,7 @@ nurat_coerce(VALUE self, VALUE other) } rb_raise(rb_eTypeError, "%s can't be coerced into %s", - rb_obj_classname(other), rb_obj_classname(self)); + rb_obj_classname(other), rb_obj_classname(self)); return Qnil; } @@ -1279,7 +1279,7 @@ nurat_truncate(VALUE self) { get_dat1(self); if (INT_NEGATIVE_P(dat->num)) - return rb_int_uminus(rb_int_idiv(rb_int_uminus(dat->num), dat->den)); + return rb_int_uminus(rb_int_idiv(rb_int_uminus(dat->num), dat->den)); return rb_int_idiv(dat->num, dat->den); } @@ -1295,14 +1295,14 @@ nurat_round_half_up(VALUE self) neg = INT_NEGATIVE_P(num); if (neg) - num = rb_int_uminus(num); + num = rb_int_uminus(num); num = rb_int_plus(rb_int_mul(num, TWO), den); den = rb_int_mul(den, TWO); num = rb_int_idiv(num, den); if (neg) - num = rb_int_uminus(num); + num = rb_int_uminus(num); return num; } @@ -1319,7 +1319,7 @@ nurat_round_half_down(VALUE self) neg = INT_NEGATIVE_P(num); if (neg) - num = rb_int_uminus(num); + num = rb_int_uminus(num); num = rb_int_plus(rb_int_mul(num, TWO), den); num = rb_int_minus(num, ONE); @@ -1327,7 +1327,7 @@ nurat_round_half_down(VALUE self) num = rb_int_idiv(num, den); if (neg) - num = rb_int_uminus(num); + num = rb_int_uminus(num); return num; } @@ -1344,17 +1344,17 @@ nurat_round_half_even(VALUE self) neg = INT_NEGATIVE_P(num); if (neg) - num = rb_int_uminus(num); + num = rb_int_uminus(num); num = rb_int_plus(rb_int_mul(num, TWO), den); den = rb_int_mul(den, TWO); qr = rb_int_divmod(num, den); num = RARRAY_AREF(qr, 0); if (INT_ZERO_P(RARRAY_AREF(qr, 1))) - num = rb_int_and(num, LONG2FIX(((int)~1))); + num = rb_int_and(num, LONG2FIX(((int)~1))); if (neg) - num = rb_int_uminus(num); + num = rb_int_uminus(num); return num; } @@ -1365,24 +1365,24 @@ f_round_common(int argc, VALUE *argv, VALUE self, VALUE (*func)(VALUE)) VALUE n, b, s; if (rb_check_arity(argc, 0, 1) == 0) - return (*func)(self); + return (*func)(self); n = argv[0]; if (!k_integer_p(n)) - rb_raise(rb_eTypeError, "not an integer"); + rb_raise(rb_eTypeError, "not an integer"); b = f_expt10(n); s = rb_rational_mul(self, b); if (k_float_p(s)) { - if (INT_NEGATIVE_P(n)) - return ZERO; - return self; + if (INT_NEGATIVE_P(n)) + return ZERO; + return self; } if (!k_rational_p(s)) { - s = f_rational_new_bang1(CLASS_OF(self), s); + s = f_rational_new_bang1(CLASS_OF(self), s); } s = (*func)(s); @@ -1390,7 +1390,7 @@ f_round_common(int argc, VALUE *argv, VALUE self, VALUE (*func)(VALUE)) s = rb_rational_div(f_rational_new_bang1(CLASS_OF(self), s), b); if (RB_TYPE_P(s, T_RATIONAL) && FIX2INT(rb_int_cmp(n, ONE)) < 0) - s = nurat_truncate(s); + s = nurat_truncate(s); return s; } @@ -1540,7 +1540,7 @@ nurat_round_n(int argc, VALUE *argv, VALUE self) VALUE opt; enum ruby_num_rounding_mode mode = ( argc = rb_scan_args(argc, argv, "*:", NULL, &opt), - rb_num_get_rounding_option(opt)); + rb_num_get_rounding_option(opt)); VALUE (*round_func)(VALUE) = ROUND_FUNC(mode, nurat_round); return f_round_common(argc, argv, self, round_func); } @@ -1689,19 +1689,19 @@ nurat_rationalize_internal(VALUE a, VALUE b, VALUE *p, VALUE *q) q1 = ZERO; while (1) { - c = f_ceil(a); - if (f_lt_p(c, b)) - break; - k = f_sub(c, ONE); - p2 = f_add(f_mul(k, p1), p0); - q2 = f_add(f_mul(k, q1), q0); - t = f_reciprocal(f_sub(b, k)); - b = f_reciprocal(f_sub(a, k)); - a = t; - p0 = p1; - q0 = q1; - p1 = p2; - q1 = q2; + c = f_ceil(a); + if (f_lt_p(c, b)) + break; + k = f_sub(c, ONE); + p2 = f_add(f_mul(k, p1), p0); + q2 = f_add(f_mul(k, q1), q0); + t = f_reciprocal(f_sub(b, k)); + b = f_reciprocal(f_sub(a, k)); + a = t; + p0 = p1; + q0 = q1; + p1 = p2; + q1 = q2; } *p = f_add(f_mul(c, p1), p0); *q = f_add(f_mul(c, q1), q0); @@ -1729,7 +1729,7 @@ nurat_rationalize(int argc, VALUE *argv, VALUE self) get_dat1(self); if (rb_check_arity(argc, 0, 1) == 0) - return self; + return self; e = f_abs(argv[0]); @@ -1741,7 +1741,7 @@ nurat_rationalize(int argc, VALUE *argv, VALUE self) b = FIXNUM_ZERO_P(e) ? rat : rb_rational_plus(rat, e); if (f_eqeq_p(a, b)) - return self; + return self; nurat_rationalize_internal(a, b, &p, &q); if (rat != self) { @@ -1874,7 +1874,7 @@ nurat_marshal_load(VALUE self, VALUE a) Check_Type(a, T_ARRAY); if (RARRAY_LEN(a) != 2) - rb_raise(rb_eArgError, "marshaled rational must have an array whose length is 2 but %ld", RARRAY_LEN(a)); + rb_raise(rb_eArgError, "marshaled rational must have an array whose length is 2 but %ld", RARRAY_LEN(a)); num = RARRAY_AREF(a, 0); den = RARRAY_AREF(a, 1); @@ -2101,7 +2101,7 @@ rb_float_numerator(VALUE self) double d = RFLOAT_VALUE(self); VALUE r; if (!isfinite(d)) - return self; + return self; r = float_to_r(self); return nurat_numerator(r); } @@ -2121,7 +2121,7 @@ rb_float_denominator(VALUE self) double d = RFLOAT_VALUE(self); VALUE r; if (!isfinite(d)) - return INT2FIX(1); + return INT2FIX(1); r = float_to_r(self); return nurat_denominator(r); } @@ -2229,7 +2229,7 @@ float_to_r(VALUE self) #else f = rb_int_mul(f, rb_int_pow(INT2FIX(FLT_RADIX), n)); if (RB_TYPE_P(f, T_RATIONAL)) - return f; + return f; return rb_rational_new1(f); #endif } @@ -2327,8 +2327,8 @@ read_sign(const char **s, const char *const e) int sign = '?'; if (*s < e && issign(**s)) { - sign = **s; - (*s)++; + sign = **s; + (*s)++; } return sign; } @@ -2343,11 +2343,11 @@ static VALUE negate_num(VALUE num) { if (FIXNUM_P(num)) { - return rb_int_uminus(num); + return rb_int_uminus(num); } else { - BIGNUM_NEGATE(num); - return rb_big_norm(num); + BIGNUM_NEGATE(num); + return rb_big_norm(num); } } @@ -2361,51 +2361,51 @@ read_num(const char **s, const char *const end, VALUE *num, VALUE *nexp) *nexp = ZERO; *num = ZERO; if (*s < end && **s != '.') { - n = rb_int_parse_cstr(*s, end-*s, &e, NULL, - 10, RB_INT_PARSE_UNDERSCORE); - if (NIL_P(n)) - return 0; - *s = e; - *num = n; - ok = 1; + n = rb_int_parse_cstr(*s, end-*s, &e, NULL, + 10, RB_INT_PARSE_UNDERSCORE); + if (NIL_P(n)) + return 0; + *s = e; + *num = n; + ok = 1; } if (*s < end && **s == '.') { - size_t count = 0; + size_t count = 0; - (*s)++; - fp = rb_int_parse_cstr(*s, end-*s, &e, &count, - 10, RB_INT_PARSE_UNDERSCORE); - if (NIL_P(fp)) - return 1; - *s = e; - { + (*s)++; + fp = rb_int_parse_cstr(*s, end-*s, &e, &count, + 10, RB_INT_PARSE_UNDERSCORE); + if (NIL_P(fp)) + return 1; + *s = e; + { VALUE l = f_expt10(*nexp = SIZET2NUM(count)); - n = n == ZERO ? fp : rb_int_plus(rb_int_mul(*num, l), fp); - *num = n; - fn = SIZET2NUM(count); - } - ok = 1; + n = n == ZERO ? fp : rb_int_plus(rb_int_mul(*num, l), fp); + *num = n; + fn = SIZET2NUM(count); + } + ok = 1; } if (ok && *s + 1 < end && islettere(**s)) { - (*s)++; - expsign = read_sign(s, end); - exp = rb_int_parse_cstr(*s, end-*s, &e, NULL, - 10, RB_INT_PARSE_UNDERSCORE); - if (NIL_P(exp)) - return 1; - *s = e; - if (exp != ZERO) { - if (expsign == '-') { - if (fn != ZERO) exp = rb_int_plus(exp, fn); - } - else { - if (fn != ZERO) exp = rb_int_minus(exp, fn); + (*s)++; + expsign = read_sign(s, end); + exp = rb_int_parse_cstr(*s, end-*s, &e, NULL, + 10, RB_INT_PARSE_UNDERSCORE); + if (NIL_P(exp)) + return 1; + *s = e; + if (exp != ZERO) { + if (expsign == '-') { + if (fn != ZERO) exp = rb_int_plus(exp, fn); + } + else { + if (fn != ZERO) exp = rb_int_minus(exp, fn); exp = negate_num(exp); - } + } *nexp = exp; - } + } } return ok; @@ -2415,7 +2415,7 @@ inline static const char * skip_ws(const char *s, const char *e) { while (s < e && isspace((unsigned char)*s)) - ++s; + ++s; return s; } @@ -2429,30 +2429,30 @@ parse_rat(const char *s, const char *const e, int strict, int raise) sign = read_sign(&s, e); if (!read_num(&s, e, &num, &nexp)) { - if (strict) return Qnil; - return nurat_s_alloc(rb_cRational); + if (strict) return Qnil; + return nurat_s_alloc(rb_cRational); } den = ONE; if (s < e && *s == '/') { - s++; + s++; if (!read_num(&s, e, &den, &dexp)) { - if (strict) return Qnil; + if (strict) return Qnil; den = ONE; - } - else if (den == ZERO) { + } + else if (den == ZERO) { if (!raise) return Qnil; - rb_num_zerodiv(); - } - else if (strict && skip_ws(s, e) != e) { - return Qnil; - } - else { + rb_num_zerodiv(); + } + else if (strict && skip_ws(s, e) != e) { + return Qnil; + } + else { nexp = rb_int_minus(nexp, dexp); - nurat_reduce(&num, &den); - } + nurat_reduce(&num, &den); + } } else if (strict && skip_ws(s, e) != e) { - return Qnil; + return Qnil; } if (nexp != ZERO) { @@ -2483,7 +2483,7 @@ parse_rat(const char *s, const char *const e, int strict, int raise) } if (sign == '-') { - num = negate_num(num); + num = negate_num(num); } return rb_rational_raw(num, den); @@ -2548,7 +2548,7 @@ string_to_r(VALUE self) num = parse_rat(RSTRING_PTR(self), RSTRING_END(self), 0, TRUE); if (RB_FLOAT_TYPE_P(num) && !FLOAT_ZERO_P(num)) - rb_raise(rb_eFloatDomainError, "Infinity"); + rb_raise(rb_eFloatDomainError, "Infinity"); return num; } @@ -2560,7 +2560,7 @@ rb_cstr_to_rat(const char *s, int strict) /* for complex's internal */ num = parse_rat(s, s + strlen(s), strict, TRUE); if (RB_FLOAT_TYPE_P(num) && !FLOAT_ZERO_P(num)) - rb_raise(rb_eFloatDomainError, "Infinity"); + rb_raise(rb_eFloatDomainError, "Infinity"); return num; } diff --git a/re.c b/re.c index 0f0eba0552..7642dc3651 100644 --- a/re.c +++ b/re.c @@ -94,8 +94,8 @@ rb_memcicmp(const void *x, const void *y, long len) int tmp; while (len--) { - if ((tmp = casetable[(unsigned)*p1++] - casetable[(unsigned)*p2++])) - return tmp; + if ((tmp = casetable[(unsigned)*p1++] - casetable[(unsigned)*p2++])) + return tmp; } return 0; } @@ -107,9 +107,9 @@ rb_memsearch_ss(const unsigned char *xs, long m, const unsigned char *ys, long n const unsigned char *y; if ((y = memmem(ys, n, xs, m)) != NULL) - return y - ys; + return y - ys; else - return -1; + return -1; } #else static inline long @@ -121,26 +121,26 @@ rb_memsearch_ss(const unsigned char *xs, long m, const unsigned char *ys, long n VALUE hx, hy, mask = VALUE_MAX >> ((SIZEOF_VALUE - m) * CHAR_BIT); if (m > SIZEOF_VALUE) - rb_bug("!!too long pattern string!!"); + rb_bug("!!too long pattern string!!"); if (!(y = memchr(y, *x, n - m + 1))) - return -1; + return -1; /* Prepare hash value */ for (hx = *x++, hy = *y++; x < xe; ++x, ++y) { - hx <<= CHAR_BIT; - hy <<= CHAR_BIT; - hx |= *x; - hy |= *y; + hx <<= CHAR_BIT; + hy <<= CHAR_BIT; + hx |= *x; + hy |= *y; } /* Searching */ while (hx != hy) { - if (y == ye) - return -1; - hy <<= CHAR_BIT; - hy |= *y; - hy &= mask; - y++; + if (y == ye) + return -1; + hy <<= CHAR_BIT; + hy |= *y; + hy &= mask; + y++; } return y - ys - m; } @@ -155,13 +155,13 @@ rb_memsearch_qs(const unsigned char *xs, long m, const unsigned char *ys, long n /* Preprocessing */ for (i = 0; i < 256; ++i) - qstable[i] = m + 1; + qstable[i] = m + 1; for (; x < xe; ++x) - qstable[*x] = xe - x; + qstable[*x] = xe - x; /* Searching */ for (; y + m <= ys + n; y += *(qstable + y[m])) { - if (*xs == *y && memcmp(xs, y, m) == 0) - return y - ys; + if (*xs == *y && memcmp(xs, y, m) == 0) + return y - ys; } return -1; } @@ -172,28 +172,28 @@ rb_memsearch_qs_utf8_hash(const unsigned char *x) register const unsigned int mix = 8353; register unsigned int h = *x; if (h < 0xC0) { - return h + 256; + return h + 256; } else if (h < 0xE0) { - h *= mix; - h += x[1]; + h *= mix; + h += x[1]; } else if (h < 0xF0) { - h *= mix; - h += x[1]; - h *= mix; - h += x[2]; + h *= mix; + h += x[1]; + h *= mix; + h += x[2]; } else if (h < 0xF5) { - h *= mix; - h += x[1]; - h *= mix; - h += x[2]; - h *= mix; - h += x[3]; + h *= mix; + h += x[1]; + h *= mix; + h += x[2]; + h *= mix; + h += x[3]; } else { - return h + 256; + return h + 256; } return (unsigned char)h; } @@ -207,15 +207,15 @@ rb_memsearch_qs_utf8(const unsigned char *xs, long m, const unsigned char *ys, l /* Preprocessing */ for (i = 0; i < 512; ++i) { - qstable[i] = m + 1; + qstable[i] = m + 1; } for (; x < xe; ++x) { - qstable[rb_memsearch_qs_utf8_hash(x)] = xe - x; + qstable[rb_memsearch_qs_utf8_hash(x)] = xe - x; } /* Searching */ for (; y + m <= ys + n; y += qstable[rb_memsearch_qs_utf8_hash(y+m)]) { - if (*xs == *y && memcmp(xs, y, m) == 0) - return y - ys; + if (*xs == *y && memcmp(xs, y, m) == 0) + return y - ys; } return -1; } @@ -227,8 +227,8 @@ rb_memsearch_wchar(const unsigned char *xs, long m, const unsigned char *ys, lon enum {char_size = 2}; for (n -= m; n >= 0; n -= char_size, y += char_size) { - if (x0 == *y && memcmp(x+1, y+1, m-1) == 0) - return y - ys; + if (x0 == *y && memcmp(x+1, y+1, m-1) == 0) + return y - ys; } return -1; } @@ -240,8 +240,8 @@ rb_memsearch_qchar(const unsigned char *xs, long m, const unsigned char *ys, lon enum {char_size = 4}; for (n -= m; n >= 0; n -= char_size, y += char_size) { - if (x0 == *y && memcmp(x+1, y+1, m-1) == 0) - return y - ys; + if (x0 == *y && memcmp(x+1, y+1, m-1) == 0) + return y - ys; } return -1; } @@ -253,32 +253,32 @@ rb_memsearch(const void *x0, long m, const void *y0, long n, rb_encoding *enc) if (m > n) return -1; else if (m == n) { - return memcmp(x0, y0, m) == 0 ? 0 : -1; + return memcmp(x0, y0, m) == 0 ? 0 : -1; } else if (m < 1) { - return 0; + return 0; } else if (m == 1) { - const unsigned char *ys = memchr(y, *x, n); + const unsigned char *ys = memchr(y, *x, n); - if (ys) - return ys - y; - else - return -1; + if (ys) + return ys - y; + else + return -1; } else if (LIKELY(rb_enc_mbminlen(enc) == 1)) { - if (m <= SIZEOF_VALUE) { - return rb_memsearch_ss(x0, m, y0, n); - } - else if (enc == rb_utf8_encoding()){ - return rb_memsearch_qs_utf8(x0, m, y0, n); - } + if (m <= SIZEOF_VALUE) { + return rb_memsearch_ss(x0, m, y0, n); + } + else if (enc == rb_utf8_encoding()){ + return rb_memsearch_qs_utf8(x0, m, y0, n); + } } else if (LIKELY(rb_enc_mbminlen(enc) == 2)) { - return rb_memsearch_wchar(x0, m, y0, n); + return rb_memsearch_wchar(x0, m, y0, n); } else if (LIKELY(rb_enc_mbminlen(enc) == 4)) { - return rb_memsearch_qchar(x0, m, y0, n); + return rb_memsearch_qchar(x0, m, y0, n); } return rb_memsearch_qs(x0, m, y0, n); } @@ -300,17 +300,17 @@ char_to_option(int c) switch (c) { case 'i': - val = ONIG_OPTION_IGNORECASE; - break; + val = ONIG_OPTION_IGNORECASE; + break; case 'x': - val = ONIG_OPTION_EXTEND; - break; + val = ONIG_OPTION_EXTEND; + break; case 'm': - val = ONIG_OPTION_MULTILINE; - break; + val = ONIG_OPTION_MULTILINE; + break; default: - val = 0; - break; + val = 0; + break; } return val; } @@ -338,17 +338,17 @@ rb_char_to_option_kcode(int c, int *option, int *kcode) *kcode = rb_ascii8bit_encindex(); return (*option = ARG_ENCODING_NONE); case 'e': - *kcode = ENCINDEX_EUC_JP; - break; + *kcode = ENCINDEX_EUC_JP; + break; case 's': - *kcode = ENCINDEX_Windows_31J; - break; + *kcode = ENCINDEX_Windows_31J; + break; case 'u': - *kcode = rb_utf8_encindex(); - break; + *kcode = rb_utf8_encindex(); + break; default: - *kcode = -1; - return (*option = char_to_option(c)); + *kcode = -1; + return (*option = char_to_option(c)); } *option = ARG_ENCODING_FIXED; return 1; @@ -358,13 +358,13 @@ static void rb_reg_check(VALUE re) { if (!RREGEXP_PTR(re) || !RREGEXP_SRC(re) || !RREGEXP_SRC_PTR(re)) { - rb_raise(rb_eTypeError, "uninitialized Regexp"); + rb_raise(rb_eTypeError, "uninitialized Regexp"); } } static void rb_reg_expr_str(VALUE str, const char *s, long len, - rb_encoding *enc, rb_encoding *resenc, int term) + rb_encoding *enc, rb_encoding *resenc, int term) { const char *p, *pend; int cr = ENC_CODERANGE_UNKNOWN; @@ -374,80 +374,80 @@ rb_reg_expr_str(VALUE str, const char *s, long len, p = s; pend = p + len; rb_str_coderange_scan_restartable(p, pend, enc, &cr); if (rb_enc_asciicompat(enc) && ENC_CODERANGE_CLEAN_P(cr)) { - while (p < pend) { - c = rb_enc_ascget(p, pend, &clen, enc); - if (c == -1) { - if (enc == resenc) { - p += mbclen(p, pend, enc); - } - else { - need_escape = 1; - break; - } - } - else if (c != term && rb_enc_isprint(c, enc)) { - p += clen; - } - else { - need_escape = 1; - break; - } - } + while (p < pend) { + c = rb_enc_ascget(p, pend, &clen, enc); + if (c == -1) { + if (enc == resenc) { + p += mbclen(p, pend, enc); + } + else { + need_escape = 1; + break; + } + } + else if (c != term && rb_enc_isprint(c, enc)) { + p += clen; + } + else { + need_escape = 1; + break; + } + } } else { - need_escape = 1; + need_escape = 1; } if (!need_escape) { - rb_str_buf_cat(str, s, len); + rb_str_buf_cat(str, s, len); } else { - int unicode_p = rb_enc_unicode_p(enc); - p = s; - while (poptions)) - rb_str_buf_cat2(str, opts); - if (RBASIC(re)->flags & REG_ENCODING_NONE) - rb_str_buf_cat2(str, "n"); + char opts[OPTBUF_SIZE]; + rb_reg_check(re); + if (*option_to_str(opts, RREGEXP_PTR(re)->options)) + rb_str_buf_cat2(str, opts); + if (RBASIC(re)->flags & REG_ENCODING_NONE) + rb_str_buf_cat2(str, "n"); } return str; } @@ -581,10 +581,10 @@ rb_reg_str_with_term(VALUE re, int term) len = RREGEXP_SRC_LEN(re); again: if (len >= 4 && ptr[0] == '(' && ptr[1] == '?') { - int err = 1; - ptr += 2; - if ((len -= 2) > 0) { - do { + int err = 1; + ptr += 2; + if ((len -= 2) > 0) { + do { opt = char_to_option((int )*ptr); if (opt != 0) { options |= opt; @@ -592,13 +592,13 @@ rb_reg_str_with_term(VALUE re, int term) else { break; } - ++ptr; - } while (--len > 0); - } - if (len > 1 && *ptr == '-') { - ++ptr; - --len; - do { + ++ptr; + } while (--len > 0); + } + if (len > 1 && *ptr == '-') { + ++ptr; + --len; + do { opt = char_to_option((int )*ptr); if (opt != 0) { options &= ~opt; @@ -606,65 +606,65 @@ rb_reg_str_with_term(VALUE re, int term) else { break; } - ++ptr; - } while (--len > 0); - } - if (*ptr == ')') { - --len; - ++ptr; - goto again; - } - if (*ptr == ':' && ptr[len-1] == ')') { - Regexp *rp; - VALUE verbose = ruby_verbose; - ruby_verbose = Qfalse; + ++ptr; + } while (--len > 0); + } + if (*ptr == ')') { + --len; + ++ptr; + goto again; + } + if (*ptr == ':' && ptr[len-1] == ')') { + Regexp *rp; + VALUE verbose = ruby_verbose; + ruby_verbose = Qfalse; - ++ptr; - len -= 2; + ++ptr; + len -= 2; err = onig_new(&rp, ptr, ptr + len, options, - enc, OnigDefaultSyntax, NULL); - onig_free(rp); - ruby_verbose = verbose; - } - if (err) { - options = RREGEXP_PTR(re)->options; - ptr = (UChar*)RREGEXP_SRC_PTR(re); - len = RREGEXP_SRC_LEN(re); - } + enc, OnigDefaultSyntax, NULL); + onig_free(rp); + ruby_verbose = verbose; + } + if (err) { + options = RREGEXP_PTR(re)->options; + ptr = (UChar*)RREGEXP_SRC_PTR(re); + len = RREGEXP_SRC_LEN(re); + } } if (*option_to_str(optbuf, options)) rb_str_buf_cat2(str, optbuf); if ((options & embeddable) != embeddable) { - optbuf[0] = '-'; - option_to_str(optbuf + 1, ~options); - rb_str_buf_cat2(str, optbuf); + optbuf[0] = '-'; + option_to_str(optbuf + 1, ~options); + rb_str_buf_cat2(str, optbuf); } rb_str_buf_cat2(str, ":"); if (rb_enc_asciicompat(enc)) { - rb_reg_expr_str(str, (char*)ptr, len, enc, NULL, term); - rb_str_buf_cat2(str, ")"); + rb_reg_expr_str(str, (char*)ptr, len, enc, NULL, term); + rb_str_buf_cat2(str, ")"); } else { - const char *s, *e; - char *paren; - ptrdiff_t n; - rb_str_buf_cat2(str, ")"); - rb_enc_associate(str, rb_usascii_encoding()); - str = rb_str_encode(str, rb_enc_from_encoding(enc), 0, Qnil); + const char *s, *e; + char *paren; + ptrdiff_t n; + rb_str_buf_cat2(str, ")"); + rb_enc_associate(str, rb_usascii_encoding()); + str = rb_str_encode(str, rb_enc_from_encoding(enc), 0, Qnil); - /* backup encoded ")" to paren */ - s = RSTRING_PTR(str); - e = RSTRING_END(str); - s = rb_enc_left_char_head(s, e-1, e, enc); - n = e - s; - paren = ALLOCA_N(char, n); - memcpy(paren, s, n); - rb_str_resize(str, RSTRING_LEN(str) - n); + /* backup encoded ")" to paren */ + s = RSTRING_PTR(str); + e = RSTRING_END(str); + s = rb_enc_left_char_head(s, e-1, e, enc); + n = e - s; + paren = ALLOCA_N(char, n); + memcpy(paren, s, n); + rb_str_resize(str, RSTRING_LEN(str) - n); - rb_reg_expr_str(str, (char*)ptr, len, enc, NULL, term); - rb_str_buf_cat(str, paren, n); + rb_reg_expr_str(str, (char*)ptr, len, enc, NULL, term); + rb_str_buf_cat(str, paren, n); } rb_enc_copy(str, re); @@ -710,7 +710,7 @@ static VALUE rb_reg_error_desc(VALUE str, int options, const char *err) { return rb_enc_reg_error_desc(RSTRING_PTR(str), RSTRING_LEN(str), - rb_enc_get(str), options, err); + rb_enc_get(str), options, err); } NORETURN(static void rb_reg_raise_str(VALUE str, int options, const char *err)); @@ -864,8 +864,8 @@ rb_reg_named_captures(VALUE re) static int onig_new_with_source(regex_t** reg, const UChar* pattern, const UChar* pattern_end, - OnigOptionType option, OnigEncoding enc, const OnigSyntaxType* syntax, - OnigErrorInfo* einfo, const char *sourcefile, int sourceline) + OnigOptionType option, OnigEncoding enc, const OnigSyntaxType* syntax, + OnigErrorInfo* einfo, const char *sourcefile, int sourceline) { int r; @@ -878,15 +878,15 @@ onig_new_with_source(regex_t** reg, const UChar* pattern, const UChar* pattern_e r = onig_compile_ruby(*reg, pattern, pattern_end, einfo, sourcefile, sourceline); if (r) { err: - onig_free(*reg); - *reg = NULL; + onig_free(*reg); + *reg = NULL; } return r; } static Regexp* make_regexp(const char *s, long len, rb_encoding *enc, int flags, onig_errmsg_buffer err, - const char *sourcefile, int sourceline) + const char *sourcefile, int sourceline) { Regexp *rp; int r; @@ -900,10 +900,10 @@ make_regexp(const char *s, long len, rb_encoding *enc, int flags, onig_errmsg_bu */ r = onig_new_with_source(&rp, (UChar*)s, (UChar*)(s + len), flags, - enc, OnigDefaultSyntax, &einfo, sourcefile, sourceline); + enc, OnigDefaultSyntax, &einfo, sourcefile, sourceline); if (r) { - onig_error_code_to_str((UChar*)err, r, &einfo); - return 0; + onig_error_code_to_str((UChar*)err, r, &einfo); + return 0; } return rp; } @@ -1072,7 +1072,7 @@ static void match_check(VALUE match) { if (!RMATCH(match)->regexp) { - rb_raise(rb_eTypeError, "uninitialized MatchData"); + rb_raise(rb_eTypeError, "uninitialized MatchData"); } } @@ -1089,7 +1089,7 @@ match_init_copy(VALUE obj, VALUE orig) rm = RMATCH(obj)->rmatch; if (rb_reg_region_copy(&rm->regs, RMATCH_REGS(orig))) - rb_memerror(); + rb_memerror(); if (RMATCH(orig)->rmatch->char_offset_num_allocated) { if (rm->char_offset_num_allocated < rm->regs.num_regs) { @@ -1098,7 +1098,7 @@ match_init_copy(VALUE obj, VALUE orig) } MEMCPY(rm->char_offset, RMATCH(orig)->rmatch->char_offset, struct rmatch_offset, rm->regs.num_regs); - RB_GC_GUARD(orig); + RB_GC_GUARD(orig); } return obj; @@ -1123,9 +1123,9 @@ match_regexp(VALUE match) match_check(match); regexp = RMATCH(match)->regexp; if (NIL_P(regexp)) { - VALUE str = rb_reg_nth_match(0, match); - regexp = rb_reg_regcomp(rb_reg_quote(str)); - RMATCH(match)->regexp = regexp; + VALUE str = rb_reg_nth_match(0, match); + regexp = rb_reg_regcomp(rb_reg_quote(str)); + RMATCH(match)->regexp = regexp; } return regexp; } @@ -1156,7 +1156,7 @@ match_names(VALUE match) { match_check(match); if (NIL_P(RMATCH(match)->regexp)) - return rb_ary_new_capa(0); + return rb_ary_new_capa(0); return rb_reg_names(RMATCH(match)->regexp); } @@ -1188,14 +1188,14 @@ static void name_to_backref_error(VALUE name) { rb_raise(rb_eIndexError, "undefined group name reference: % "PRIsVALUE, - name); + name); } static void backref_number_check(struct re_registers *regs, int i) { if (i < 0 || regs->num_regs <= i) - rb_raise(rb_eIndexError, "index %d out of matches", i); + rb_raise(rb_eIndexError, "index %d out of matches", i); } static int @@ -1209,10 +1209,10 @@ match_backref_number(VALUE match, VALUE backref) match_check(match); if (SYMBOL_P(backref)) { - backref = rb_sym2str(backref); + backref = rb_sym2str(backref); } else if (!RB_TYPE_P(backref, T_STRING)) { - return NUM2INT(backref); + return NUM2INT(backref); } name = StringValueCStr(backref); @@ -1250,7 +1250,7 @@ match_offset(VALUE match, VALUE n) backref_number_check(regs, i); if (BEG(i) < 0) - return rb_assoc_new(Qnil, Qnil); + return rb_assoc_new(Qnil, Qnil); update_char_offset(match); return rb_assoc_new(LONG2NUM(RMATCH(match)->rmatch->char_offset[i].beg), @@ -1309,7 +1309,7 @@ match_begin(VALUE match, VALUE n) backref_number_check(regs, i); if (BEG(i) < 0) - return Qnil; + return Qnil; update_char_offset(match); return LONG2NUM(RMATCH(match)->rmatch->char_offset[i].beg); @@ -1335,7 +1335,7 @@ match_end(VALUE match, VALUE n) backref_number_check(regs, i); if (BEG(i) < 0) - return Qnil; + return Qnil; update_char_offset(match); return LONG2NUM(RMATCH(match)->rmatch->char_offset[i].end); @@ -1377,7 +1377,7 @@ match_nth(VALUE match, VALUE n) long start = BEG(i), end = END(i); if (start < 0) - return Qnil; + return Qnil; return rb_str_subseq(RMATCH(match)->str, start, end - start); } @@ -1421,11 +1421,11 @@ match_nth_length(VALUE match, VALUE n) backref_number_check(regs, i); if (BEG(i) < 0) - return Qnil; + return Qnil; update_char_offset(match); const struct rmatch_offset *const ofs = - &RMATCH(match)->rmatch->char_offset[i]; + &RMATCH(match)->rmatch->char_offset[i]; return LONG2NUM(ofs->end - ofs->beg); } @@ -1461,11 +1461,11 @@ rb_match_nth_defined(int nth, VALUE match) regs = RMATCH_REGS(match); if (!regs) return FALSE; if (nth >= regs->num_regs) { - return FALSE; + return FALSE; } if (nth < 0) { - nth += regs->num_regs; - if (nth <= 0) return FALSE; + nth += regs->num_regs; + if (nth <= 0) return FALSE; } return (BEG(nth) != -1); } @@ -1489,7 +1489,7 @@ rb_backref_set_string(VALUE string, long pos, long len) { VALUE match = rb_backref_get(); if (NIL_P(match) || FL_TEST(match, MATCH_BUSY)) { - match = match_alloc(rb_cMatch); + match = match_alloc(rb_cMatch); } match_set_string(match, string, pos, len); rb_backref_set(match); @@ -1540,9 +1540,9 @@ static void reg_enc_error(VALUE re, VALUE str) { rb_raise(rb_eEncCompatError, - "incompatible encoding regexp match (%s regexp with %s string)", - rb_enc_name(rb_enc_get(re)), - rb_enc_name(rb_enc_get(str))); + "incompatible encoding regexp match (%s regexp with %s string)", + rb_enc_name(rb_enc_get(re)), + rb_enc_name(rb_enc_get(str))); } static inline int @@ -1550,7 +1550,7 @@ str_coderange(VALUE str) { int cr = ENC_CODERANGE(str); if (cr == ENC_CODERANGE_UNKNOWN) { - cr = rb_enc_str_coderange(str); + cr = rb_enc_str_coderange(str); } return cr; } @@ -1572,24 +1572,24 @@ rb_reg_prepare_enc(VALUE re, VALUE str, int warn) if (RREGEXP_PTR(re)->enc == enc) { } else if (cr == ENC_CODERANGE_7BIT && - RREGEXP_PTR(re)->enc == rb_usascii_encoding()) { - enc = RREGEXP_PTR(re)->enc; + RREGEXP_PTR(re)->enc == rb_usascii_encoding()) { + enc = RREGEXP_PTR(re)->enc; } else if (!rb_enc_asciicompat(enc)) { - reg_enc_error(re, str); + reg_enc_error(re, str); } else if (rb_reg_fixed_encoding_p(re)) { if ((!rb_enc_asciicompat(RREGEXP_PTR(re)->enc) || - cr != ENC_CODERANGE_7BIT)) { - reg_enc_error(re, str); - } - enc = RREGEXP_PTR(re)->enc; + cr != ENC_CODERANGE_7BIT)) { + reg_enc_error(re, str); + } + enc = RREGEXP_PTR(re)->enc; } else if (warn && (RBASIC(re)->flags & REG_ENCODING_NONE) && - enc != rb_ascii8bit_encoding() && - cr != ENC_CODERANGE_7BIT) { - rb_warn("historical binary regexp match /.../n against %s string", - rb_enc_name(enc)); + enc != rb_ascii8bit_encoding() && + cr != ENC_CODERANGE_7BIT) { + rb_warn("historical binary regexp match /.../n against %s string", + rb_enc_name(enc)); } return enc; } @@ -1612,11 +1612,11 @@ rb_reg_prepare_re0(VALUE re, VALUE str, onig_errmsg_buffer err) pattern = RREGEXP_SRC_PTR(re); unescaped = rb_reg_preprocess( - pattern, pattern + RREGEXP_SRC_LEN(re), enc, + pattern, pattern + RREGEXP_SRC_LEN(re), enc, &fixed_enc, err, 0); if (NIL_P(unescaped)) { - rb_raise(rb_eArgError, "regexp preprocess failed: %s", err); + rb_raise(rb_eArgError, "regexp preprocess failed: %s", err); } // inherit the timeout settings @@ -1626,11 +1626,11 @@ rb_reg_prepare_re0(VALUE re, VALUE str, onig_errmsg_buffer err) long len; RSTRING_GETMEM(unescaped, ptr, len); r = onig_new(®, (UChar *)ptr, (UChar *)(ptr + len), - reg->options, enc, - OnigDefaultSyntax, &einfo); + reg->options, enc, + OnigDefaultSyntax, &einfo); if (r) { - onig_error_code_to_str((UChar*)err, r, &einfo); - rb_reg_raise(pattern, RREGEXP_SRC_LEN(re), err, re); + onig_error_code_to_str((UChar*)err, r, &einfo); + rb_reg_raise(pattern, RREGEXP_SRC_LEN(re), err, re); } reg->timelimit = timelimit; @@ -1656,22 +1656,22 @@ rb_reg_adjust_startpos(VALUE re, VALUE str, long pos, int reverse) enc = rb_reg_prepare_enc(re, str, 0); if (reverse) { - range = -pos; + range = -pos; } else { - range = RSTRING_LEN(str) - pos; + range = RSTRING_LEN(str) - pos; } if (pos > 0 && ONIGENC_MBC_MAXLEN(enc) != 1 && pos < RSTRING_LEN(str)) { - string = (UChar*)RSTRING_PTR(str); + string = (UChar*)RSTRING_PTR(str); - if (range > 0) { - p = onigenc_get_right_adjust_char_head(enc, string, string + pos, string + RSTRING_LEN(str)); - } - else { - p = ONIGENC_LEFT_ADJUST_CHAR_HEAD(enc, string, string + pos, string + RSTRING_LEN(str)); - } - return p - string; + if (range > 0) { + p = onigenc_get_right_adjust_char_head(enc, string, string + pos, string + RSTRING_LEN(str)); + } + else { + p = ONIGENC_LEFT_ADJUST_CHAR_HEAD(enc, string, string + pos, string + RSTRING_LEN(str)); + } + return p - string; } return pos; @@ -1693,8 +1693,8 @@ rb_reg_search_set_match(VALUE re, VALUE str, long pos, int reverse, int set_back RSTRING_GETMEM(str, start, len); range = start; if (pos > len || pos < 0) { - rb_backref_set(Qnil); - return -1; + rb_backref_set(Qnil); + return -1; } reg = rb_reg_prepare_re0(re, str, err); @@ -1703,35 +1703,35 @@ rb_reg_search_set_match(VALUE re, VALUE str, long pos, int reverse, int set_back MEMZERO(regs, struct re_registers, 1); if (!reverse) { - range += len; + range += len; } result = onig_search(reg, - (UChar*)start, - ((UChar*)(start + len)), - ((UChar*)(start + pos)), - ((UChar*)range), - regs, ONIG_OPTION_NONE); + (UChar*)start, + ((UChar*)(start + len)), + ((UChar*)(start + pos)), + ((UChar*)range), + regs, ONIG_OPTION_NONE); if (!tmpreg) RREGEXP(re)->usecnt--; if (tmpreg) { - if (RREGEXP(re)->usecnt) { - onig_free(reg); - } - else { - onig_free(RREGEXP_PTR(re)); - RREGEXP_PTR(re) = reg; - } + if (RREGEXP(re)->usecnt) { + onig_free(reg); + } + else { + onig_free(RREGEXP_PTR(re)); + RREGEXP_PTR(re) = reg; + } } if (result < 0) { - if (regs == ®i) - onig_region_free(regs, 0); - if (result == ONIG_MISMATCH) { - rb_backref_set(Qnil); - return result; - } - else { - onig_error_code_to_str((UChar*)err, (int)result); - rb_reg_raise(RREGEXP_SRC_PTR(re), RREGEXP_SRC_LEN(re), err, re); - } + if (regs == ®i) + onig_region_free(regs, 0); + if (result == ONIG_MISMATCH) { + rb_backref_set(Qnil); + return result; + } + else { + onig_error_code_to_str((UChar*)err, (int)result); + rb_reg_raise(RREGEXP_SRC_PTR(re), RREGEXP_SRC_LEN(re), err, re); + } } match = match_alloc(rb_cMatch); @@ -1740,7 +1740,7 @@ rb_reg_search_set_match(VALUE re, VALUE str, long pos, int reverse, int set_back if (copy_err) rb_memerror(); if (set_backref_str) { - RMATCH(match)->str = rb_str_new4(str); + RMATCH(match)->str = rb_str_new4(str); } RMATCH(match)->regexp = re; @@ -1778,53 +1778,53 @@ rb_reg_start_with_p(VALUE re, VALUE str) match = rb_backref_get(); if (!NIL_P(match)) { - if (FL_TEST(match, MATCH_BUSY)) { - match = Qnil; - } - else { - regs = RMATCH_REGS(match); - } + if (FL_TEST(match, MATCH_BUSY)) { + match = Qnil; + } + else { + regs = RMATCH_REGS(match); + } } if (NIL_P(match)) { - MEMZERO(regs, struct re_registers, 1); + MEMZERO(regs, struct re_registers, 1); } const char *ptr; long len; RSTRING_GETMEM(str, ptr, len); result = onig_match(reg, - (UChar*)(ptr), - ((UChar*)(ptr + len)), - (UChar*)(ptr), - regs, ONIG_OPTION_NONE); + (UChar*)(ptr), + ((UChar*)(ptr + len)), + (UChar*)(ptr), + regs, ONIG_OPTION_NONE); if (!tmpreg) RREGEXP(re)->usecnt--; if (tmpreg) { - if (RREGEXP(re)->usecnt) { - onig_free(reg); - } - else { - onig_free(RREGEXP_PTR(re)); - RREGEXP_PTR(re) = reg; - } + if (RREGEXP(re)->usecnt) { + onig_free(reg); + } + else { + onig_free(RREGEXP_PTR(re)); + RREGEXP_PTR(re) = reg; + } } if (result < 0) { - if (regs == ®i) - onig_region_free(regs, 0); - if (result == ONIG_MISMATCH) { - rb_backref_set(Qnil); - return false; - } - else { - onig_error_code_to_str((UChar*)err, (int)result); - rb_reg_raise(RREGEXP_SRC_PTR(re), RREGEXP_SRC_LEN(re), err, re); - } + if (regs == ®i) + onig_region_free(regs, 0); + if (result == ONIG_MISMATCH) { + rb_backref_set(Qnil); + return false; + } + else { + onig_error_code_to_str((UChar*)err, (int)result); + rb_reg_raise(RREGEXP_SRC_PTR(re), RREGEXP_SRC_LEN(re), err, re); + } } if (NIL_P(match)) { - int err; - match = match_alloc(rb_cMatch); - err = rb_reg_region_copy(RMATCH_REGS(match), regs); - onig_region_free(regs, 0); - if (err) rb_memerror(); + int err; + match = match_alloc(rb_cMatch); + err = rb_reg_region_copy(RMATCH_REGS(match), regs); + onig_region_free(regs, 0); + if (err) rb_memerror(); } RMATCH(match)->str = rb_str_new4(str); @@ -1843,11 +1843,11 @@ rb_reg_nth_defined(int nth, VALUE match) match_check(match); regs = RMATCH_REGS(match); if (nth >= regs->num_regs) { - return Qnil; + return Qnil; } if (nth < 0) { - nth += regs->num_regs; - if (nth <= 0) return Qnil; + nth += regs->num_regs; + if (nth <= 0) return Qnil; } return RBOOL(BEG(nth) != -1); } @@ -1863,11 +1863,11 @@ rb_reg_nth_match(int nth, VALUE match) match_check(match); regs = RMATCH_REGS(match); if (nth >= regs->num_regs) { - return Qnil; + return Qnil; } if (nth < 0) { - nth += regs->num_regs; - if (nth <= 0) return Qnil; + nth += regs->num_regs; + if (nth <= 0) return Qnil; } start = BEG(nth); if (start == -1) return Qnil; @@ -1963,7 +1963,7 @@ rb_reg_match_last(VALUE match) if (BEG(0) == -1) return Qnil; for (i=regs->num_regs-1; BEG(i) == -1 && i > 0; i--) - ; + ; if (i == 0) return Qnil; return rb_reg_nth_match(i, match); } @@ -2006,13 +2006,13 @@ match_array(VALUE match, int start) target = RMATCH(match)->str; for (i=start; inum_regs; i++) { - if (regs->beg[i] == -1) { - rb_ary_push(ary, Qnil); - } - else { - VALUE str = rb_str_subseq(target, regs->beg[i], regs->end[i]-regs->beg[i]); - rb_ary_push(ary, str); - } + if (regs->beg[i] == -1) { + rb_ary_push(ary, Qnil); + } + else { + VALUE str = rb_str_subseq(target, regs->beg[i], regs->end[i]-regs->beg[i]); + rb_ary_push(ary, str); + } } return ary; } @@ -2065,7 +2065,7 @@ name_to_backref_number(struct re_registers *regs, VALUE regexp, const char* name { if (NIL_P(regexp)) return -1; return onig_name_to_backref_number(RREGEXP_PTR(regexp), - (const unsigned char *)name, (const unsigned char *)name_end, regs); + (const unsigned char *)name, (const unsigned char *)name_end, regs); } #define NAME_TO_NUMBER(regs, re, name, name_ptr, name_end) \ @@ -2079,15 +2079,15 @@ namev_to_backref_number(struct re_registers *regs, VALUE re, VALUE name) int num; if (SYMBOL_P(name)) { - name = rb_sym2str(name); + name = rb_sym2str(name); } else if (!RB_TYPE_P(name, T_STRING)) { - return -1; + return -1; } num = NAME_TO_NUMBER(regs, re, name, - RSTRING_PTR(name), RSTRING_END(name)); + RSTRING_PTR(name), RSTRING_END(name)); if (num < 1) { - name_to_backref_error(name); + name_to_backref_error(name); } return num; } @@ -2101,10 +2101,10 @@ match_ary_subseq(VALUE match, long beg, long len, VALUE result) if (len == 0) return result; for (j = beg; j < end; j++) { - rb_ary_push(result, rb_reg_nth_match((int)j, match)); + rb_ary_push(result, rb_reg_nth_match((int)j, match)); } if (beg + len > j) { - rb_ary_resize(result, RARRAY_LEN(result) + (beg + len) - j); + rb_ary_resize(result, RARRAY_LEN(result) + (beg + len) - j); } return result; } @@ -2118,13 +2118,13 @@ match_ary_aref(VALUE match, VALUE idx, VALUE result) /* check if idx is Range */ switch (rb_range_beg_len(idx, &beg, &len, (long)num_regs, !NIL_P(result))) { case Qfalse: - if (NIL_P(result)) return rb_reg_nth_match(NUM2INT(idx), match); - rb_ary_push(result, rb_reg_nth_match(NUM2INT(idx), match)); - return result; + if (NIL_P(result)) return rb_reg_nth_match(NUM2INT(idx), match); + rb_ary_push(result, rb_reg_nth_match(NUM2INT(idx), match)); + return result; case Qnil: - return Qnil; + return Qnil; default: - return match_ary_subseq(match, beg, len, result); + return match_ary_subseq(match, beg, len, result); } } @@ -2164,37 +2164,37 @@ match_aref(int argc, VALUE *argv, VALUE match) rb_scan_args(argc, argv, "11", &idx, &length); if (NIL_P(length)) { - if (FIXNUM_P(idx)) { - return rb_reg_nth_match(FIX2INT(idx), match); - } - else { - int num = namev_to_backref_number(RMATCH_REGS(match), RMATCH(match)->regexp, idx); - if (num >= 0) { - return rb_reg_nth_match(num, match); - } - else { - return match_ary_aref(match, idx, Qnil); - } - } + if (FIXNUM_P(idx)) { + return rb_reg_nth_match(FIX2INT(idx), match); + } + else { + int num = namev_to_backref_number(RMATCH_REGS(match), RMATCH(match)->regexp, idx); + if (num >= 0) { + return rb_reg_nth_match(num, match); + } + else { + return match_ary_aref(match, idx, Qnil); + } + } } else { - long beg = NUM2LONG(idx); - long len = NUM2LONG(length); - long num_regs = RMATCH_REGS(match)->num_regs; - if (len < 0) { - return Qnil; - } - if (beg < 0) { - beg += num_regs; - if (beg < 0) return Qnil; - } - else if (beg > num_regs) { - return Qnil; - } - if (beg+len > num_regs) { - len = num_regs - beg; - } - return match_ary_subseq(match, beg, len, Qnil); + long beg = NUM2LONG(idx); + long len = NUM2LONG(length); + long num_regs = RMATCH_REGS(match)->num_regs; + if (len < 0) { + return Qnil; + } + if (beg < 0) { + beg += num_regs; + if (beg < 0) return Qnil; + } + else if (beg > num_regs) { + return Qnil; + } + if (beg+len > num_regs) { + len = num_regs - beg; + } + return match_ary_subseq(match, beg, len, Qnil); } } @@ -2234,18 +2234,18 @@ match_values_at(int argc, VALUE *argv, VALUE match) result = rb_ary_new2(argc); for (i=0; iregexp, argv[i]); - if (num >= 0) { - rb_ary_push(result, rb_reg_nth_match(num, match)); - } - else { - match_ary_aref(match, argv[i], result); - } - } + if (FIXNUM_P(argv[i])) { + rb_ary_push(result, rb_reg_nth_match(FIX2INT(argv[i]), match)); + } + else { + int num = namev_to_backref_number(RMATCH_REGS(match), RMATCH(match)->regexp, argv[i]); + if (num >= 0) { + rb_ary_push(result, rb_reg_nth_match(num, match)); + } + else { + match_ary_aref(match, argv[i], result); + } + } } return result; } @@ -2281,7 +2281,7 @@ match_to_s(VALUE match) static int match_named_captures_iter(const OnigUChar *name, const OnigUChar *name_end, - int back_num, int *back_refs, OnigRegex regex, void *arg) { + int back_num, int *back_refs, OnigRegex regex, void *arg) { struct MEMO *memo = MEMO_CAST(arg); VALUE hash = memo->v1; VALUE match = memo->v2; @@ -2293,15 +2293,15 @@ match_named_captures_iter(const OnigUChar *name, const OnigUChar *name_end, int found = 0; for (i = 0; i < back_num; i++) { - value = rb_reg_nth_match(back_refs[i], match); - if (RTEST(value)) { - rb_hash_aset(hash, key, value); - found = 1; - } + value = rb_reg_nth_match(back_refs[i], match); + if (RTEST(value)) { + rb_hash_aset(hash, key, value); + found = 1; + } } if (found == 0) { - rb_hash_aset(hash, key, Qnil); + rb_hash_aset(hash, key, Qnil); } return 0; @@ -2340,7 +2340,7 @@ match_named_captures(VALUE match) match_check(match); if (NIL_P(RMATCH(match)->regexp)) - return rb_hash_new(); + return rb_hash_new(); hash = rb_hash_new(); memo = MEMO_NEW(hash, match, 0); @@ -2427,7 +2427,7 @@ match_inspect(VALUE match) } else if (NIL_P(regexp)) { return rb_sprintf("#<%"PRIsVALUE": %"PRIsVALUE">", - cname, rb_reg_nth_match(0, match)); + cname, rb_reg_nth_match(0, match)); } names = ALLOCA_N(struct backref_name_tag, num_regs); @@ -2761,7 +2761,7 @@ unescape_nonascii(const char *p, const char *end, rb_encoding *enc, goto invalid_multibyte; } if ((chlen = MBCLEN_CHARFOUND_LEN(chlen)) > 1) { - /* include the previous backslash */ + /* include the previous backslash */ --p; ++chlen; goto multibyte; @@ -2787,17 +2787,17 @@ unescape_nonascii(const char *p, const char *end, rb_encoding *enc, case 'C': /* \C-X, \C-\M-X */ case 'M': /* \M-X, \M-\C-X, \M-\cX */ p = p-2; - if (enc == rb_usascii_encoding()) { - const char *pbeg = p; + if (enc == rb_usascii_encoding()) { + const char *pbeg = p; int byte = read_escaped_byte(&p, end, err); if (byte == -1) return -1; c = byte; - rb_str_buf_cat(buf, pbeg, p-pbeg); - } - else { - if (unescape_escaped_nonascii(&p, end, enc, buf, encp, err) != 0) - return -1; - } + rb_str_buf_cat(buf, pbeg, p-pbeg); + } + else { + if (unescape_escaped_nonascii(&p, end, enc, buf, encp, err) != 0) + return -1; + } break; case 'u': @@ -2865,10 +2865,10 @@ escape_asis: while (cont && (p < end)) { switch (c = *p++) { - default: + default: if (!(c & 0x80)) break; - --p; - /* fallthrough */ + --p; + /* fallthrough */ case '\\': chlen = rb_enc_precise_mbclen(p, end, enc); if (!MBCLEN_CHARFOUND_P(chlen)) { @@ -2950,7 +2950,7 @@ rb_reg_check_preprocess(VALUE str) RB_GC_GUARD(str); if (NIL_P(buf)) { - return rb_reg_error_desc(str, 0, err); + return rb_reg_error_desc(str, 0, err); } return Qnil; } @@ -2975,14 +2975,14 @@ rb_reg_preprocess_dregexp(VALUE ary, int options) char *p, *end; rb_encoding *src_enc; - src_enc = rb_enc_get(str); - if (options & ARG_ENCODING_NONE && - src_enc != ascii8bit) { - if (str_coderange(str) != ENC_CODERANGE_7BIT) - rb_raise(rb_eRegexpError, "/.../n has a non escaped non ASCII character in non ASCII-8BIT script"); - else - src_enc = ascii8bit; - } + src_enc = rb_enc_get(str); + if (options & ARG_ENCODING_NONE && + src_enc != ascii8bit) { + if (str_coderange(str) != ENC_CODERANGE_7BIT) + rb_raise(rb_eRegexpError, "/.../n has a non escaped non ASCII character in non ASCII-8BIT script"); + else + src_enc = ascii8bit; + } StringValue(str); p = RSTRING_PTR(str); @@ -3015,8 +3015,8 @@ rb_reg_preprocess_dregexp(VALUE ary, int options) static int rb_reg_initialize(VALUE obj, const char *s, long len, rb_encoding *enc, - int options, onig_errmsg_buffer err, - const char *sourcefile, int sourceline) + int options, onig_errmsg_buffer err, + const char *sourcefile, int sourceline) { struct RRegexp *re = RREGEXP(obj); VALUE unescaped; @@ -3025,14 +3025,14 @@ rb_reg_initialize(VALUE obj, const char *s, long len, rb_encoding *enc, rb_check_frozen(obj); if (FL_TEST(obj, REG_LITERAL)) - rb_raise(rb_eSecurityError, "can't modify literal regexp"); + rb_raise(rb_eSecurityError, "can't modify literal regexp"); if (re->ptr) rb_raise(rb_eTypeError, "already initialized regexp"); re->ptr = 0; if (rb_enc_dummy_p(enc)) { - errcpy(err, "can't make regexp with dummy encoding"); - return -1; + errcpy(err, "can't make regexp with dummy encoding"); + return -1; } unescaped = rb_reg_preprocess(s, s+len, enc, &fixed_enc, err, options); @@ -3040,15 +3040,15 @@ rb_reg_initialize(VALUE obj, const char *s, long len, rb_encoding *enc, return -1; if (fixed_enc) { - if ((fixed_enc != enc && (options & ARG_ENCODING_FIXED)) || + if ((fixed_enc != enc && (options & ARG_ENCODING_FIXED)) || (fixed_enc != a_enc && (options & ARG_ENCODING_NONE))) { - errcpy(err, "incompatible character encoding"); - return -1; - } + errcpy(err, "incompatible character encoding"); + return -1; + } if (fixed_enc != a_enc) { - options |= ARG_ENCODING_FIXED; - enc = fixed_enc; - } + options |= ARG_ENCODING_FIXED; + enc = fixed_enc; + } } else if (!(options & ARG_ENCODING_FIXED)) { enc = rb_usascii_encoding(); @@ -3056,15 +3056,15 @@ rb_reg_initialize(VALUE obj, const char *s, long len, rb_encoding *enc, rb_enc_associate((VALUE)re, enc); if ((options & ARG_ENCODING_FIXED) || fixed_enc) { - re->basic.flags |= KCODE_FIXED; + re->basic.flags |= KCODE_FIXED; } if (options & ARG_ENCODING_NONE) { re->basic.flags |= REG_ENCODING_NONE; } re->ptr = make_regexp(RSTRING_PTR(unescaped), RSTRING_LEN(unescaped), enc, - options & ARG_REG_OPTION_MASK, err, - sourcefile, sourceline); + options & ARG_REG_OPTION_MASK, err, + sourcefile, sourceline); if (!re->ptr) return -1; RB_GC_GUARD(unescaped); return 0; @@ -3075,14 +3075,14 @@ reg_set_source(VALUE reg, VALUE str, rb_encoding *enc) { rb_encoding *regenc = rb_enc_get(reg); if (regenc != enc) { - str = rb_enc_associate(rb_str_dup(str), enc = regenc); + str = rb_enc_associate(rb_str_dup(str), enc = regenc); } RB_OBJ_WRITE(reg, &RREGEXP(reg)->src, rb_fstring(str)); } static int rb_reg_initialize_str(VALUE obj, VALUE str, int options, onig_errmsg_buffer err, - const char *sourcefile, int sourceline) + const char *sourcefile, int sourceline) { int ret; rb_encoding *str_enc = rb_enc_get(str), *enc = str_enc; @@ -3097,7 +3097,7 @@ rb_reg_initialize_str(VALUE obj, VALUE str, int options, onig_errmsg_buffer err, } } ret = rb_reg_initialize(obj, RSTRING_PTR(str), RSTRING_LEN(str), enc, - options, err, sourcefile, sourceline); + options, err, sourcefile, sourceline); if (ret == 0) reg_set_source(obj, str, str_enc); return ret; } @@ -3132,7 +3132,7 @@ rb_reg_init_str(VALUE re, VALUE s, int options) onig_errmsg_buffer err = ""; if (rb_reg_initialize_str(re, s, options, err, NULL, 0) != 0) { - rb_reg_raise_str(s, options, err); + rb_reg_raise_str(s, options, err); } return re; @@ -3144,8 +3144,8 @@ rb_reg_init_str_enc(VALUE re, VALUE s, rb_encoding *enc, int options) onig_errmsg_buffer err = ""; if (rb_reg_initialize(re, RSTRING_PTR(s), RSTRING_LEN(s), - enc, options, err, NULL, 0) != 0) { - rb_reg_raise_str(s, options, err); + enc, options, err, NULL, 0) != 0) { + rb_reg_raise_str(s, options, err); } reg_set_source(re, s, enc); @@ -3167,7 +3167,7 @@ rb_enc_reg_new(const char *s, long len, rb_encoding *enc, int options) onig_errmsg_buffer err = ""; if (rb_reg_initialize(re, s, len, enc, options, err, NULL, 0) != 0) { - rb_enc_reg_raise(s, len, enc, options, err); + rb_enc_reg_raise(s, len, enc, options, err); } RB_OBJ_WRITE(re, &RREGEXP(re)->src, rb_fstring(rb_enc_str_new(s, len, enc))); @@ -3188,8 +3188,8 @@ rb_reg_compile(VALUE str, int options, const char *sourcefile, int sourceline) if (!str) str = rb_str_new(0,0); if (rb_reg_initialize_str(re, str, options, err, sourcefile, sourceline) != 0) { - rb_set_errinfo(rb_reg_error_desc(str, options, err)); - return Qnil; + rb_set_errinfo(rb_reg_error_desc(str, options, err)); + return Qnil; } FL_SET(re, REG_LITERAL); rb_obj_freeze(re); @@ -3202,9 +3202,9 @@ VALUE rb_reg_regcomp(VALUE str) { if (reg_cache && RREGEXP_SRC_LEN(reg_cache) == RSTRING_LEN(str) - && ENCODING_GET(reg_cache) == ENCODING_GET(str) - && memcmp(RREGEXP_SRC_PTR(reg_cache), RSTRING_PTR(str), RSTRING_LEN(str)) == 0) - return reg_cache; + && ENCODING_GET(reg_cache) == ENCODING_GET(str) + && memcmp(RREGEXP_SRC_PTR(reg_cache), RSTRING_PTR(str), RSTRING_LEN(str)) == 0) + return reg_cache; return reg_cache = rb_reg_new_str(str, 0); } @@ -3330,7 +3330,7 @@ static VALUE reg_operand(VALUE s, int check) { if (SYMBOL_P(s)) { - return rb_sym2str(s); + return rb_sym2str(s); } else if (RB_TYPE_P(s, T_STRING)) { return s; @@ -3346,19 +3346,19 @@ reg_match_pos(VALUE re, VALUE *strp, long pos, VALUE* set_match) VALUE str = *strp; if (NIL_P(str)) { - rb_backref_set(Qnil); - return -1; + rb_backref_set(Qnil); + return -1; } *strp = str = reg_operand(str, TRUE); if (pos != 0) { - if (pos < 0) { - VALUE l = rb_str_length(str); - pos += NUM2INT(l); - if (pos < 0) { - return pos; - } - } - pos = rb_str_offset(str, pos); + if (pos < 0) { + VALUE l = rb_str_length(str); + pos += NUM2INT(l); + if (pos < 0) { + return pos; + } + } + pos = rb_str_offset(str, pos); } return rb_reg_search_set_match(re, str, pos, 0, 1, set_match); } @@ -3455,8 +3455,8 @@ rb_reg_eqq(VALUE re, VALUE str) str = reg_operand(str, FALSE); if (NIL_P(str)) { - rb_backref_set(Qnil); - return Qfalse; + rb_backref_set(Qnil); + return Qfalse; } start = rb_reg_search(re, str, 0, 0); return RBOOL(start >= 0); @@ -3481,13 +3481,13 @@ rb_reg_match2(VALUE re) VALUE line = rb_lastline_get(); if (!RB_TYPE_P(line, T_STRING)) { - rb_backref_set(Qnil); - return Qnil; + rb_backref_set(Qnil); + return Qnil; } start = rb_reg_search(re, line, 0, 0); if (start < 0) { - return Qnil; + return Qnil; } start = rb_str_sublen(line, start); return LONG2FIX(start); @@ -3537,20 +3537,20 @@ rb_reg_match_m(int argc, VALUE *argv, VALUE re) long pos; if (rb_scan_args(argc, argv, "11", &str, &initpos) == 2) { - pos = NUM2LONG(initpos); + pos = NUM2LONG(initpos); } else { - pos = 0; + pos = 0; } pos = reg_match_pos(re, &str, pos, &result); if (pos < 0) { - rb_backref_set(Qnil); - return Qnil; + rb_backref_set(Qnil); + return Qnil; } rb_match_busy(result); if (!NIL_P(result) && rb_block_given_p()) { - return rb_yield(result); + return rb_yield(result); } return result; } @@ -3590,16 +3590,16 @@ rb_reg_match_p(VALUE re, VALUE str, long pos) if (NIL_P(str)) return Qfalse; str = SYMBOL_P(str) ? rb_sym2str(str) : StringValue(str); if (pos) { - if (pos < 0) { - pos += NUM2LONG(rb_str_length(str)); - if (pos < 0) return Qfalse; - } - if (pos > 0) { - long len = 1; - const char *beg = rb_str_subpos(str, pos, &len); - if (!beg) return Qfalse; - pos = beg - RSTRING_PTR(str); - } + if (pos < 0) { + pos += NUM2LONG(rb_str_length(str)); + if (pos < 0) return Qfalse; + } + if (pos > 0) { + long len = 1; + const char *beg = rb_str_subpos(str, pos, &len); + if (!beg) return Qfalse; + pos = beg - RSTRING_PTR(str); + } } reg = rb_reg_prepare_re0(re, str, err); tmpreg = reg != RREGEXP_PTR(re); @@ -3607,25 +3607,25 @@ rb_reg_match_p(VALUE re, VALUE str, long pos) start = ((UChar*)RSTRING_PTR(str)); end = start + RSTRING_LEN(str); result = onig_search(reg, start, end, start + pos, end, - NULL, ONIG_OPTION_NONE); + NULL, ONIG_OPTION_NONE); if (!tmpreg) RREGEXP(re)->usecnt--; if (tmpreg) { - if (RREGEXP(re)->usecnt) { - onig_free(reg); - } - else { - onig_free(RREGEXP_PTR(re)); - RREGEXP_PTR(re) = reg; - } + if (RREGEXP(re)->usecnt) { + onig_free(reg); + } + else { + onig_free(RREGEXP_PTR(re)); + RREGEXP_PTR(re) = reg; + } } if (result < 0) { - if (result == ONIG_MISMATCH) { - return Qfalse; - } - else { - onig_error_code_to_str((UChar*)err, (int)result); - rb_reg_raise(RREGEXP_SRC_PTR(re), RREGEXP_SRC_LEN(re), err, re); - } + if (result == ONIG_MISMATCH) { + return Qfalse; + } + else { + onig_error_code_to_str((UChar*)err, (int)result); + rb_reg_raise(RREGEXP_SRC_PTR(re), RREGEXP_SRC_LEN(re), err, re); + } } return Qtrue; } @@ -3646,11 +3646,11 @@ str_to_option(VALUE str) if (NIL_P(str)) return -1; RSTRING_GETMEM(str, ptr, len); for (long i = 0; i < len; ++i) { - int f = char_to_option(ptr[i]); - if (!f) { - rb_raise(rb_eArgError, "unknown regexp option: %"PRIsVALUE, str); - } - flag |= f; + int f = char_to_option(ptr[i]); + if (!f) { + rb_raise(rb_eArgError, "unknown regexp option: %"PRIsVALUE, str); + } + flag |= f; } return flag; } @@ -3725,47 +3725,47 @@ rb_reg_initialize_m(int argc, VALUE *argv, VALUE self) rb_scan_args(argc, argv, "12:", &src, &opts, &n_flag, &kwargs); if (!NIL_P(kwargs)) { - static ID keywords[1]; - if (!keywords[0]) { - keywords[0] = rb_intern_const("timeout"); - } - rb_get_kwargs(kwargs, keywords, 0, 1, &timeout); + static ID keywords[1]; + if (!keywords[0]) { + keywords[0] = rb_intern_const("timeout"); + } + rb_get_kwargs(kwargs, keywords, 0, 1, &timeout); } if (RB_TYPE_P(src, T_REGEXP)) { - VALUE re = src; + VALUE re = src; - if (opts != Qnil) { - rb_warn("flags ignored"); - } - rb_reg_check(re); - flags = rb_reg_options(re); - str = RREGEXP_SRC(re); + if (opts != Qnil) { + rb_warn("flags ignored"); + } + rb_reg_check(re); + flags = rb_reg_options(re); + str = RREGEXP_SRC(re); } else { if (opts != Qundef) { - int f; - if (FIXNUM_P(opts)) flags = FIX2INT(opts); - else if ((f = str_to_option(opts)) >= 0) flags = f; - else if (!NIL_P(opts) && rb_bool_expected(opts, "ignorecase", FALSE)) - flags = ONIG_OPTION_IGNORECASE; - } + int f; + if (FIXNUM_P(opts)) flags = FIX2INT(opts); + else if ((f = str_to_option(opts)) >= 0) flags = f; + else if (!NIL_P(opts) && rb_bool_expected(opts, "ignorecase", FALSE)) + flags = ONIG_OPTION_IGNORECASE; + } if (n_flag != Qundef && !NIL_P(n_flag)) { - char *kcode = StringValuePtr(n_flag); - if (kcode[0] == 'n' || kcode[0] == 'N') { - enc = rb_ascii8bit_encoding(); - flags |= ARG_ENCODING_NONE; - } - else { + char *kcode = StringValuePtr(n_flag); + if (kcode[0] == 'n' || kcode[0] == 'N') { + enc = rb_ascii8bit_encoding(); + flags |= ARG_ENCODING_NONE; + } + else { rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "encoding option is ignored - %s", kcode); - } - } - str = StringValue(src); + } + } + str = StringValue(src); } if (enc && rb_enc_get(str) != enc) - rb_reg_init_str_enc(self, str, enc, flags); + rb_reg_init_str_enc(self, str, enc, flags); else - rb_reg_init_str(self, str, flags); + rb_reg_init_str(self, str, flags); regex_t *reg = RREGEXP_PTR(self); @@ -3791,19 +3791,19 @@ rb_reg_quote(VALUE str) send = s + RSTRING_LEN(str); while (s < send) { c = rb_enc_ascget(s, send, &clen, enc); - if (c == -1) { + if (c == -1) { s += mbclen(s, send, enc); - continue; - } - switch (c) { - case '[': case ']': case '{': case '}': - case '(': case ')': case '|': case '-': - case '*': case '.': case '\\': - case '?': case '+': case '^': case '$': - case ' ': case '#': - case '\t': case '\f': case '\v': case '\n': case '\r': - goto meta_found; - } + continue; + } + switch (c) { + case '[': case ']': case '{': case '}': + case '(': case ')': case '|': case '-': + case '*': case '.': case '\\': + case '?': case '+': case '^': case '$': + case ' ': case '#': + case '\t': case '\f': case '\v': case '\n': case '\r': + goto meta_found; + } s += clen; } tmp = rb_str_new3(str); @@ -3828,47 +3828,47 @@ rb_reg_quote(VALUE str) while (s < send) { c = rb_enc_ascget(s, send, &clen, enc); - if (c == -1) { - int n = mbclen(s, send, enc); + if (c == -1) { + int n = mbclen(s, send, enc); - while (n--) - *t++ = *s++; - continue; - } + while (n--) + *t++ = *s++; + continue; + } s += clen; - switch (c) { - case '[': case ']': case '{': case '}': - case '(': case ')': case '|': case '-': - case '*': case '.': case '\\': - case '?': case '+': case '^': case '$': - case '#': + switch (c) { + case '[': case ']': case '{': case '}': + case '(': case ')': case '|': case '-': + case '*': case '.': case '\\': + case '?': case '+': case '^': case '$': + case '#': t += rb_enc_mbcput('\\', t, enc); - break; - case ' ': + break; + case ' ': t += rb_enc_mbcput('\\', t, enc); t += rb_enc_mbcput(' ', t, enc); - continue; - case '\t': + continue; + case '\t': t += rb_enc_mbcput('\\', t, enc); t += rb_enc_mbcput('t', t, enc); - continue; - case '\n': + continue; + case '\n': t += rb_enc_mbcput('\\', t, enc); t += rb_enc_mbcput('n', t, enc); - continue; - case '\r': + continue; + case '\r': t += rb_enc_mbcput('\\', t, enc); t += rb_enc_mbcput('r', t, enc); - continue; - case '\f': + continue; + case '\f': t += rb_enc_mbcput('\\', t, enc); t += rb_enc_mbcput('f', t, enc); - continue; - case '\v': + continue; + case '\v': t += rb_enc_mbcput('\\', t, enc); t += rb_enc_mbcput('v', t, enc); - continue; - } + continue; + } t += rb_enc_mbcput(c, t, enc); } rb_str_resize(tmp, t - RSTRING_PTR(tmp)); @@ -3964,23 +3964,23 @@ rb_reg_s_union(VALUE self, VALUE args0) } } else { - int i; - VALUE source = rb_str_buf_new(0); - rb_encoding *result_enc; + int i; + VALUE source = rb_str_buf_new(0); + rb_encoding *result_enc; int has_asciionly = 0; rb_encoding *has_ascii_compat_fixed = 0; rb_encoding *has_ascii_incompat = 0; - for (i = 0; i < argc; i++) { - volatile VALUE v; - VALUE e = rb_ary_entry(args0, i); + for (i = 0; i < argc; i++) { + volatile VALUE v; + VALUE e = rb_ary_entry(args0, i); - if (0 < i) - rb_str_buf_cat_ascii(source, "|"); + if (0 < i) + rb_str_buf_cat_ascii(source, "|"); - v = rb_check_regexp_type(e); - if (!NIL_P(v)) { + v = rb_check_regexp_type(e); + if (!NIL_P(v)) { rb_encoding *enc = rb_enc_get(v); if (!rb_enc_asciicompat(enc)) { if (!has_ascii_incompat) @@ -3999,9 +3999,9 @@ rb_reg_s_union(VALUE self, VALUE args0) else { has_asciionly = 1; } - v = rb_reg_str_with_term(v, -1); - } - else { + v = rb_reg_str_with_term(v, -1); + } + else { rb_encoding *enc; StringValue(e); enc = rb_enc_get(e); @@ -4022,8 +4022,8 @@ rb_reg_s_union(VALUE self, VALUE args0) rb_raise(rb_eArgError, "incompatible encodings: %s and %s", rb_enc_name(has_ascii_compat_fixed), rb_enc_name(enc)); } - v = rb_reg_s_quote(Qnil, e); - } + v = rb_reg_s_quote(Qnil, e); + } if (has_ascii_incompat) { if (has_asciionly) { rb_raise(rb_eArgError, "ASCII incompatible encoding: %s", @@ -4038,8 +4038,8 @@ rb_reg_s_union(VALUE self, VALUE args0) if (i == 0) { rb_enc_copy(source, v); } - rb_str_append(source, v); - } + rb_str_append(source, v); + } if (has_ascii_incompat) { result_enc = has_ascii_incompat; @@ -4128,42 +4128,42 @@ rb_reg_regsub(VALUE str, VALUE src, struct re_registers *regs, VALUE regexp) while (s < e) { int c = ASCGET(s, e, &clen); - char *ss; + char *ss; - if (c == -1) { - s += mbclen(s, e, str_enc); - continue; - } - ss = s; + if (c == -1) { + s += mbclen(s, e, str_enc); + continue; + } + ss = s; s += clen; - if (c != '\\' || s == e) continue; + if (c != '\\' || s == e) continue; - if (!val) { - val = rb_str_buf_new(ss-p); - } + if (!val) { + val = rb_str_buf_new(ss-p); + } rb_enc_str_buf_cat(val, p, ss-p, str_enc); c = ASCGET(s, e, &clen); if (c == -1) { s += mbclen(s, e, str_enc); - rb_enc_str_buf_cat(val, ss, s-ss, str_enc); + rb_enc_str_buf_cat(val, ss, s-ss, str_enc); p = s; - continue; + continue; } s += clen; - p = s; - switch (c) { - case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': + p = s; + switch (c) { + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': if (!NIL_P(regexp) && onig_noname_group_capture_is_active(RREGEXP_PTR(regexp))) { no = c - '0'; } else { continue; } - break; + break; case 'k': if (s < e && ASCGET(s, e, &clen) == '<') { @@ -4176,11 +4176,11 @@ rb_reg_regsub(VALUE str, VALUE src, struct re_registers *regs, VALUE regexp) name_end += c == -1 ? mbclen(name_end, e, str_enc) : clen; } if (name_end < e) { - VALUE n = rb_str_subseq(str, (long)(name - RSTRING_PTR(str)), - (long)(name_end - name)); - if ((no = NAME_TO_NUMBER(regs, regexp, n, name, name_end)) < 1) { - name_to_backref_error(n); - } + VALUE n = rb_str_subseq(str, (long)(name - RSTRING_PTR(str)), + (long)(name_end - name)); + if ((no = NAME_TO_NUMBER(regs, regexp, n, name, name_end)) < 1) { + name_to_backref_error(n); + } p = s = name_end + clen; break; } @@ -4193,38 +4193,38 @@ rb_reg_regsub(VALUE str, VALUE src, struct re_registers *regs, VALUE regexp) continue; case '0': - case '&': - no = 0; - break; + case '&': + no = 0; + break; - case '`': - rb_enc_str_buf_cat(val, RSTRING_PTR(src), BEG(0), src_enc); - continue; + case '`': + rb_enc_str_buf_cat(val, RSTRING_PTR(src), BEG(0), src_enc); + continue; - case '\'': - rb_enc_str_buf_cat(val, RSTRING_PTR(src)+END(0), RSTRING_LEN(src)-END(0), src_enc); - continue; + case '\'': + rb_enc_str_buf_cat(val, RSTRING_PTR(src)+END(0), RSTRING_LEN(src)-END(0), src_enc); + continue; - case '+': - no = regs->num_regs-1; - while (BEG(no) == -1 && no > 0) no--; - if (no == 0) continue; - break; + case '+': + no = regs->num_regs-1; + while (BEG(no) == -1 && no > 0) no--; + if (no == 0) continue; + break; - case '\\': - rb_enc_str_buf_cat(val, s-clen, clen, str_enc); - continue; + case '\\': + rb_enc_str_buf_cat(val, s-clen, clen, str_enc); + continue; - default: - rb_enc_str_buf_cat(val, ss, s-ss, str_enc); - continue; - } + default: + rb_enc_str_buf_cat(val, ss, s-ss, str_enc); + continue; + } - if (no >= 0) { - if (no >= regs->num_regs) continue; - if (BEG(no) == -1) continue; - rb_enc_str_buf_cat(val, RSTRING_PTR(src)+BEG(no), END(no)-BEG(no), src_enc); - } + if (no >= 0) { + if (no >= regs->num_regs) continue; + if (BEG(no) == -1) continue; + rb_enc_str_buf_cat(val, RSTRING_PTR(src)+BEG(no), END(no)-BEG(no), src_enc); + } } if (!val) return str; @@ -4268,7 +4268,7 @@ static void match_setter(VALUE val, ID _x, VALUE *_y) { if (!NIL_P(val)) { - Check_Type(val, T_MATCH); + Check_Type(val, T_MATCH); } rb_backref_set(val); } @@ -4319,7 +4319,7 @@ rb_reg_s_last_match(int argc, VALUE *argv, VALUE _) int n; if (NIL_P(match)) return Qnil; n = match_backref_number(match, argv[0]); - return rb_reg_nth_match(n, match); + return rb_reg_nth_match(n, match); } return match_getter(); } diff --git a/ruby-runner.c b/ruby-runner.c index b756c219fa..e1a53d5236 100644 --- a/ruby-runner.c +++ b/ruby-runner.c @@ -24,29 +24,29 @@ insert_env_path(const char *envname, const char *paths, size_t size, int prepend size_t n = 0; if (env) { - while ((c = *env) == PATH_SEP) ++env; - n = strlen(env); - while (n > 0 && env[n-1] == PATH_SEP) --n; + while ((c = *env) == PATH_SEP) ++env; + n = strlen(env); + while (n > 0 && env[n-1] == PATH_SEP) --n; } if (c) { - char *e = malloc(size+n+1); - size_t pos = 0; - if (prepend) { - memcpy(e, paths, pos = size-1); - e[pos++] = PATH_SEP; - } - memcpy(e+pos, env, n); - pos += n; - if (!prepend) { - e[pos++] = PATH_SEP; - memcpy(e+pos, paths, size-1); - pos += size-1; - } - e[pos] = '\0'; - env = e; + char *e = malloc(size+n+1); + size_t pos = 0; + if (prepend) { + memcpy(e, paths, pos = size-1); + e[pos++] = PATH_SEP; + } + memcpy(e+pos, env, n); + pos += n; + if (!prepend) { + e[pos++] = PATH_SEP; + memcpy(e+pos, paths, size-1); + pos += size-1; + } + e[pos] = '\0'; + env = e; } else { - env = paths; + env = paths; } setenv(envname, env, 1); } @@ -58,12 +58,12 @@ main(int argc, char **argv) static const char builddir[] = BUILDDIR; static const char rubypath[] = BUILDDIR"/"STRINGIZE(RUBY_INSTALL_NAME); static const char rubylib[] = - ABS_SRCDIR"/lib" - PATH_SEPARATOR - EXTOUT_DIR"/common" - PATH_SEPARATOR - EXTOUT_DIR"/"ARCH - ; + ABS_SRCDIR"/lib" + PATH_SEPARATOR + EXTOUT_DIR"/common" + PATH_SEPARATOR + EXTOUT_DIR"/"ARCH + ; #ifndef LOAD_RELATIVE static const char mjit_build_dir[] = BUILDDIR"/mjit_build_dir."SOEXT; struct stat stbuf; @@ -84,9 +84,9 @@ main(int argc, char **argv) if (!(p = strrchr(arg0, '/'))) p = arg0; else p++; if (strlen(p) < namesize - 1) { - argv[0] = malloc(p - arg0 + namesize); - memcpy(argv[0], arg0, p - arg0); - p = argv[0] + (p - arg0); + argv[0] = malloc(p - arg0 + namesize); + memcpy(argv[0], arg0, p - arg0); + p = argv[0] + (p - arg0); } memcpy(p, rubyname, namesize); diff --git a/ruby.c b/ruby.c index 311e92a235..87876d5160 100644 --- a/ruby.c +++ b/ruby.c @@ -154,8 +154,8 @@ enum dump_flag_bits { dump_version_v, EACH_DUMPS(DEFINE_DUMP, COMMA), dump_exit_bits = (DUMP_BIT(yydebug) | DUMP_BIT(syntax) | - DUMP_BIT(parsetree) | DUMP_BIT(parsetree_with_comment) | - DUMP_BIT(insns) | DUMP_BIT(insns_without_opt)) + DUMP_BIT(parsetree) | DUMP_BIT(parsetree_with_comment) | + DUMP_BIT(insns) | DUMP_BIT(insns_without_opt)) }; static inline void @@ -179,18 +179,18 @@ static void init_ids(ruby_cmdline_options_t *); enum { COMPILATION_FEATURES = ( - 0 - | FEATURE_BIT(frozen_string_literal) - | FEATURE_BIT(debug_frozen_string_literal) - ), + 0 + | FEATURE_BIT(frozen_string_literal) + | FEATURE_BIT(debug_frozen_string_literal) + ), DEFAULT_FEATURES = ( - (FEATURE_BIT(debug_flag_first)-1) + (FEATURE_BIT(debug_flag_first)-1) #if DISABLE_RUBYGEMS - & ~FEATURE_BIT(gems) + & ~FEATURE_BIT(gems) #endif - & ~FEATURE_BIT(frozen_string_literal) + & ~FEATURE_BIT(frozen_string_literal) & ~feature_jit_mask - ) + ) }; static ruby_cmdline_options_t * @@ -212,7 +212,7 @@ cmdline_options_init(ruby_cmdline_options_t *opt) } static rb_ast_t *load_file(VALUE parser, VALUE fname, VALUE f, int script, - ruby_cmdline_options_t *opt); + ruby_cmdline_options_t *opt); static VALUE open_load_file(VALUE fname_v, int *xflag); static void forbid_setid(const char *, const ruby_cmdline_options_t *); #define forbid_setid(s) forbid_setid((s), opt) @@ -234,10 +234,10 @@ show_usage_line(const char *str, unsigned int namelen, unsigned int secondlen, i const char *se = highlight ? esc_reset : esc_none; const int wrap = help && namelen + secondlen - 1 > w; printf(" %s%.*s%-*.*s%s%-*s%s\n", sb, namelen-1, str, - (wrap ? 0 : w - namelen + 1), - (help ? secondlen-1 : 0), str + namelen, se, - (wrap ? w + 3 : 0), (wrap ? "\n" : ""), - str + namelen + secondlen); + (wrap ? 0 : w - namelen + 1), + (help ? secondlen-1 : 0), str + namelen, se, + (wrap ? w + 3 : 0), (wrap ? "\n" : ""), + str + namelen + secondlen); } static void @@ -254,26 +254,26 @@ usage(const char *name, int help, int highlight, int columns) # define PLATFORM_JIT_OPTION "--mjit" #endif static const struct ruby_opt_message usage_msg[] = { - M("-0[octal]", "", "specify record separator (\\0, if no argument)"), - M("-a", "", "autosplit mode with -n or -p (splits $_ into $F)"), - M("-c", "", "check syntax only"), - M("-Cdirectory", "", "cd to directory before executing your script"), - M("-d", ", --debug", "set debugging flags (set $DEBUG to true)"), - M("-e 'command'", "", "one line of script. Several -e's allowed. Omit [programfile]"), - M("-Eex[:in]", ", --encoding=ex[:in]", "specify the default external and internal character encodings"), - M("-Fpattern", "", "split() pattern for autosplit (-a)"), - M("-i[extension]", "", "edit ARGV files in place (make backup if extension supplied)"), - M("-Idirectory", "", "specify $LOAD_PATH directory (may be used more than once)"), - M("-l", "", "enable line ending processing"), - M("-n", "", "assume 'while gets(); ... end' loop around your script"), - M("-p", "", "assume loop like -n but print line also like sed"), - M("-rlibrary", "", "require the library before executing your script"), - M("-s", "", "enable some switch parsing for switches after script name"), - M("-S", "", "look for the script using PATH environment variable"), - M("-v", "", "print the version number, then turn on verbose mode"), - M("-w", "", "turn warnings on for your script"), - M("-W[level=2|:category]", "", "set warning level; 0=silence, 1=medium, 2=verbose"), - M("-x[directory]", "", "strip off text before #!ruby line and perhaps cd to directory"), + M("-0[octal]", "", "specify record separator (\\0, if no argument)"), + M("-a", "", "autosplit mode with -n or -p (splits $_ into $F)"), + M("-c", "", "check syntax only"), + M("-Cdirectory", "", "cd to directory before executing your script"), + M("-d", ", --debug", "set debugging flags (set $DEBUG to true)"), + M("-e 'command'", "", "one line of script. Several -e's allowed. Omit [programfile]"), + M("-Eex[:in]", ", --encoding=ex[:in]", "specify the default external and internal character encodings"), + M("-Fpattern", "", "split() pattern for autosplit (-a)"), + M("-i[extension]", "", "edit ARGV files in place (make backup if extension supplied)"), + M("-Idirectory", "", "specify $LOAD_PATH directory (may be used more than once)"), + M("-l", "", "enable line ending processing"), + M("-n", "", "assume 'while gets(); ... end' loop around your script"), + M("-p", "", "assume loop like -n but print line also like sed"), + M("-rlibrary", "", "require the library before executing your script"), + M("-s", "", "enable some switch parsing for switches after script name"), + M("-S", "", "look for the script using PATH environment variable"), + M("-v", "", "print the version number, then turn on verbose mode"), + M("-w", "", "turn warnings on for your script"), + M("-W[level=2|:category]", "", "set warning level; 0=silence, 1=medium, 2=verbose"), + M("-x[directory]", "", "strip off text before #!ruby line and perhaps cd to directory"), M("--jit", "", "enable JIT for the platform, same as " PLATFORM_JIT_OPTION " (experimental)"), #if USE_MJIT M("--mjit", "", "enable C compiler-based JIT compiler (experimental)"), @@ -281,34 +281,34 @@ usage(const char *name, int help, int highlight, int columns) #if YJIT_BUILD M("--yjit", "", "enable in-process JIT compiler (experimental)"), #endif - M("-h", "", "show this message, --help for more info"), + M("-h", "", "show this message, --help for more info"), }; static const struct ruby_opt_message help_msg[] = { - M("--copyright", "", "print the copyright"), - M("--dump={insns|parsetree|...}[,...]", "", + M("--copyright", "", "print the copyright"), + M("--dump={insns|parsetree|...}[,...]", "", "dump debug information. see below for available dump list"), - M("--enable={jit|rubyopt|...}[,...]", ", --disable={jit|rubyopt|...}[,...]", - "enable or disable features. see below for available features"), - M("--external-encoding=encoding", ", --internal-encoding=encoding", - "specify the default external or internal character encoding"), - M("--backtrace-limit=num", "", "limit the maximum length of backtrace"), - M("--verbose", "", "turn on verbose mode and disable script from stdin"), - M("--version", "", "print the version number, then exit"), - M("--help", "", "show this message, -h for short message"), + M("--enable={jit|rubyopt|...}[,...]", ", --disable={jit|rubyopt|...}[,...]", + "enable or disable features. see below for available features"), + M("--external-encoding=encoding", ", --internal-encoding=encoding", + "specify the default external or internal character encoding"), + M("--backtrace-limit=num", "", "limit the maximum length of backtrace"), + M("--verbose", "", "turn on verbose mode and disable script from stdin"), + M("--version", "", "print the version number, then exit"), + M("--help", "", "show this message, -h for short message"), }; static const struct ruby_opt_message dumps[] = { - M("insns", "", "instruction sequences"), - M("insns_without_opt", "", "instruction sequences compiled with no optimization"), - M("yydebug", "", "yydebug of yacc parser generator"), - M("parsetree", "", "AST"), - M("parsetree_with_comment", "", "AST with comments"), + M("insns", "", "instruction sequences"), + M("insns_without_opt", "", "instruction sequences compiled with no optimization"), + M("yydebug", "", "yydebug of yacc parser generator"), + M("parsetree", "", "AST"), + M("parsetree_with_comment", "", "AST with comments"), }; static const struct ruby_opt_message features[] = { - M("gems", "", "rubygems (only for debugging, default: "DEFAULT_RUBYGEMS_ENABLED")"), - M("error_highlight", "", "error_highlight (default: "DEFAULT_RUBYGEMS_ENABLED")"), - M("did_you_mean", "", "did_you_mean (default: "DEFAULT_RUBYGEMS_ENABLED")"), - M("rubyopt", "", "RUBYOPT environment variable (default: enabled)"), - M("frozen-string-literal", "", "freeze all string literals (default: disabled)"), + M("gems", "", "rubygems (only for debugging, default: "DEFAULT_RUBYGEMS_ENABLED")"), + M("error_highlight", "", "error_highlight (default: "DEFAULT_RUBYGEMS_ENABLED")"), + M("did_you_mean", "", "did_you_mean (default: "DEFAULT_RUBYGEMS_ENABLED")"), + M("rubyopt", "", "RUBYOPT environment variable (default: enabled)"), + M("frozen-string-literal", "", "freeze all string literals (default: disabled)"), #if USE_MJIT M("mjit", "", "C compiler-based JIT compiler (default: disabled)"), #endif @@ -343,27 +343,27 @@ usage(const char *name, int help, int highlight, int columns) printf("%sUsage:%s %s [switches] [--] [programfile] [arguments]\n", sb, se, name); for (i = 0; i < num; ++i) - SHOW(usage_msg[i]); + SHOW(usage_msg[i]); if (!help) return; if (highlight) sb = esc_standout; for (i = 0; i < numberof(help_msg); ++i) - SHOW(help_msg[i]); + SHOW(help_msg[i]); printf("%s""Dump List:%s\n", sb, se); for (i = 0; i < numberof(dumps); ++i) - SHOW(dumps[i]); + SHOW(dumps[i]); printf("%s""Features:%s\n", sb, se); for (i = 0; i < numberof(features); ++i) - SHOW(features[i]); + SHOW(features[i]); printf("%s""Warning categories:%s\n", sb, se); for (i = 0; i < numberof(warn_categories); ++i) - SHOW(warn_categories[i]); + SHOW(warn_categories[i]); #if USE_MJIT printf("%s""MJIT options (experimental):%s\n", sb, se); for (i = 0; mjit_option_messages[i].str; ++i) - SHOW(mjit_option_messages[i]); + SHOW(mjit_option_messages[i]); #endif #if YJIT_BUILD printf("%s""YJIT options (experimental):%s\n", sb, se); @@ -383,12 +383,12 @@ push_include(const char *path, VALUE (*filter)(VALUE)) p = path; while (*p) { - while (*p == sep) - p++; - if (!*p) break; - for (s = p; *s && *s != sep; s = CharNext(s)); - rb_ary_push(load_path, (*filter)(rubylib_path_new(p, s - p))); - p = s; + while (*p == sep) + p++; + if (!*p) break; + for (s = p; *s && *s != sep; s = CharNext(s)); + rb_ary_push(load_path, (*filter)(rubylib_path_new(p, s - p))); + p = s; } } @@ -402,33 +402,33 @@ push_include_cygwin(const char *path, VALUE (*filter)(VALUE)) p = path; while (*p) { - unsigned int len; - while (*p == ';') - p++; - if (!*p) break; - for (s = p; *s && *s != ';'; s = CharNext(s)); - len = s - p; - if (*s) { - if (!buf) { - buf = rb_str_new(p, len); - p = RSTRING_PTR(buf); - } - else { - rb_str_resize(buf, len); - p = strncpy(RSTRING_PTR(buf), p, len); - } - } + unsigned int len; + while (*p == ';') + p++; + if (!*p) break; + for (s = p; *s && *s != ';'; s = CharNext(s)); + len = s - p; + if (*s) { + if (!buf) { + buf = rb_str_new(p, len); + p = RSTRING_PTR(buf); + } + else { + rb_str_resize(buf, len); + p = strncpy(RSTRING_PTR(buf), p, len); + } + } #ifdef HAVE_CYGWIN_CONV_PATH #define CONV_TO_POSIX_PATH(p, lib) \ - cygwin_conv_path(CCP_WIN_A_TO_POSIX|CCP_RELATIVE, (p), (lib), sizeof(lib)) + cygwin_conv_path(CCP_WIN_A_TO_POSIX|CCP_RELATIVE, (p), (lib), sizeof(lib)) #else # error no cygwin_conv_path #endif - if (CONV_TO_POSIX_PATH(p, rubylib) == 0) - p = rubylib; - push_include(p, filter); - if (!*s) break; - p = s + 1; + if (CONV_TO_POSIX_PATH(p, rubylib) == 0) + p = rubylib; + push_include(p, filter); + if (!*s) break; + p = s + 1; } } @@ -439,7 +439,7 @@ void ruby_push_include(const char *path, VALUE (*filter)(VALUE)) { if (path == 0) - return; + return; push_include(path, filter); } @@ -466,9 +466,9 @@ expand_include_path(VALUE path) { char *p = RSTRING_PTR(path); if (!p) - return path; + return path; if (*p == '.' && p[1] == '/') - return path; + return path; return rb_file_expand_path(path, Qnil); } @@ -486,7 +486,7 @@ BOOL WINAPI DllMain(HINSTANCE dll, DWORD reason, LPVOID reserved) { if (reason == DLL_PROCESS_ATTACH) - libruby = dll; + libruby = dll; return TRUE; } @@ -500,9 +500,9 @@ static inline void translit_char_bin(char *p, int from, int to) { while (*p) { - if ((unsigned char)*p == from) - *p = to; - p++; + if ((unsigned char)*p == from) + *p = to; + p++; } } #endif @@ -525,8 +525,8 @@ static VALUE str_conv_enc(VALUE str, rb_encoding *from, rb_encoding *to) { return rb_str_conv_enc_opts(str, from, to, - ECONV_UNDEF_REPLACE|ECONV_INVALID_REPLACE, - Qnil); + ECONV_UNDEF_REPLACE|ECONV_INVALID_REPLACE, + Qnil); } #else # define str_conv_enc(str, from, to) (str) @@ -551,33 +551,33 @@ runtime_libruby_path(void) char *libpath; while (wlibpath = (WCHAR *)RSTRING_PTR(wsopath), - ret = GetModuleFileNameW(libruby, wlibpath, len), - (ret == len)) + ret = GetModuleFileNameW(libruby, wlibpath, len), + (ret == len)) { - rb_str_modify_expand(wsopath, len*sizeof(WCHAR)); - rb_str_set_len(wsopath, (len += len)*sizeof(WCHAR)); + rb_str_modify_expand(wsopath, len*sizeof(WCHAR)); + rb_str_set_len(wsopath, (len += len)*sizeof(WCHAR)); } if (!ret || ret > len) rb_fatal("failed to get module file name"); #if defined __CYGWIN__ { - const int win_to_posix = CCP_WIN_W_TO_POSIX | CCP_RELATIVE; - size_t newsize = cygwin_conv_path(win_to_posix, wlibpath, 0, 0); - if (!newsize) rb_fatal("failed to convert module path to cygwin"); - path = rb_str_new(0, newsize); - libpath = RSTRING_PTR(path); - if (cygwin_conv_path(win_to_posix, wlibpath, libpath, newsize)) { - rb_str_resize(path, 0); - } + const int win_to_posix = CCP_WIN_W_TO_POSIX | CCP_RELATIVE; + size_t newsize = cygwin_conv_path(win_to_posix, wlibpath, 0, 0); + if (!newsize) rb_fatal("failed to convert module path to cygwin"); + path = rb_str_new(0, newsize); + libpath = RSTRING_PTR(path); + if (cygwin_conv_path(win_to_posix, wlibpath, libpath, newsize)) { + rb_str_resize(path, 0); + } } #else { - DWORD i; - for (len = ret, i = 0; i < len; ++i) { - if (wlibpath[i] == L'\\') { - wlibpath[i] = L'/'; - ret = i+1; /* chop after the last separator */ - } - } + DWORD i; + for (len = ret, i = 0; i < len; ++i) { + if (wlibpath[i] == L'\\') { + wlibpath[i] = L'/'; + ret = i+1; /* chop after the last separator */ + } + } } len = WideCharToMultiByte(CP_UTF8, 0, wlibpath, ret, NULL, 0, NULL, NULL); path = rb_utf8_str_new(0, len); @@ -592,17 +592,17 @@ runtime_libruby_path(void) const void* addr = (void *)(VALUE)expand_include_path; if (!dladdr((void *)addr, &dli)) { - return rb_str_new(0, 0); + return rb_str_new(0, 0); } #ifdef __linux__ else if (origarg.argc > 0 && origarg.argv && dli.dli_fname == origarg.argv[0]) { - fname = rb_str_new_cstr("/proc/self/exe"); - path = rb_readlink(fname, NULL); + fname = rb_str_new_cstr("/proc/self/exe"); + path = rb_readlink(fname, NULL); } #endif else { - fname = rb_str_new_cstr(dli.dli_fname); - path = rb_realpath_internal(Qnil, fname, 1); + fname = rb_str_new_cstr(dli.dli_fname); + path = rb_realpath_internal(Qnil, fname, 1); } rb_str_resize(fname, 0); return path; @@ -640,44 +640,44 @@ ruby_init_loadpath(void) p = strrchr(libpath, '/'); if (p) { - static const char libdir[] = "/" + static const char libdir[] = "/" #ifdef LIBDIR_BASENAME - LIBDIR_BASENAME + LIBDIR_BASENAME #else - "lib" + "lib" #endif - RUBY_ARCH_PATH; - const ptrdiff_t libdir_len = (ptrdiff_t)sizeof(libdir) - - rb_strlen_lit(RUBY_ARCH_PATH) - 1; - static const char bindir[] = "/bin"; - const ptrdiff_t bindir_len = (ptrdiff_t)sizeof(bindir) - 1; + RUBY_ARCH_PATH; + const ptrdiff_t libdir_len = (ptrdiff_t)sizeof(libdir) + - rb_strlen_lit(RUBY_ARCH_PATH) - 1; + static const char bindir[] = "/bin"; + const ptrdiff_t bindir_len = (ptrdiff_t)sizeof(bindir) - 1; - const char *p2 = NULL; + const char *p2 = NULL; #ifdef ENABLE_MULTIARCH multiarch: #endif - if (p - libpath >= bindir_len && !STRNCASECMP(p - bindir_len, bindir, bindir_len)) { - p -= bindir_len; - archlibdir = rb_str_subseq(sopath, 0, p - libpath); - rb_str_cat_cstr(archlibdir, libdir); - OBJ_FREEZE_RAW(archlibdir); - } - else if (p - libpath >= libdir_len && !strncmp(p - libdir_len, libdir, libdir_len)) { - archlibdir = rb_str_subseq(sopath, 0, (p2 ? p2 : p) - libpath); - OBJ_FREEZE_RAW(archlibdir); - p -= libdir_len; - } + if (p - libpath >= bindir_len && !STRNCASECMP(p - bindir_len, bindir, bindir_len)) { + p -= bindir_len; + archlibdir = rb_str_subseq(sopath, 0, p - libpath); + rb_str_cat_cstr(archlibdir, libdir); + OBJ_FREEZE_RAW(archlibdir); + } + else if (p - libpath >= libdir_len && !strncmp(p - libdir_len, libdir, libdir_len)) { + archlibdir = rb_str_subseq(sopath, 0, (p2 ? p2 : p) - libpath); + OBJ_FREEZE_RAW(archlibdir); + p -= libdir_len; + } #ifdef ENABLE_MULTIARCH - else if (p2) { - p = p2; - } - else { - p2 = p; - p = rb_enc_path_last_separator(libpath, p, rb_ascii8bit_encoding()); - if (p) goto multiarch; - p = p2; - } + else if (p2) { + p = p2; + } + else { + p2 = p; + p = rb_enc_path_last_separator(libpath, p, rb_ascii8bit_encoding()); + if (p) goto multiarch; + p = p2; + } #endif baselen = p - libpath; } @@ -707,11 +707,11 @@ ruby_init_loadpath(void) id_initial_load_path_mark = INITIAL_LOAD_PATH_MARK; while (*paths) { - size_t len = strlen(paths); - VALUE path = RUBY_RELATIVE(paths, len); - rb_ivar_set(path, id_initial_load_path_mark, path); - rb_ary_push(load_path, path); - paths += len + 1; + size_t len = strlen(paths); + VALUE path = RUBY_RELATIVE(paths, len); + rb_ivar_set(path, id_initial_load_path_mark, path); + rb_ary_push(load_path, path); + paths += len + 1; } rb_const_set(rb_cObject, rb_intern_const("TMP_RUBY_PREFIX"), ruby_prefix_path); @@ -725,7 +725,7 @@ add_modules(VALUE *req_list, const char *mod) VALUE feature; if (!list) { - *req_list = list = rb_ary_tmp_new(0); + *req_list = list = rb_ary_tmp_new(0); } feature = rb_str_cat_cstr(rb_str_tmp_new(0), mod); rb_ary_push(list, feature); @@ -741,11 +741,11 @@ require_libraries(VALUE *req_list) CONST_ID(require, "require"); while (list && RARRAY_LEN(list) > 0) { - VALUE feature = rb_ary_shift(list); - rb_enc_associate(feature, extenc); - RBASIC_SET_CLASS_RAW(feature, rb_cString); - OBJ_FREEZE(feature); - rb_funcallv(self, require, 1, &feature); + VALUE feature = rb_ary_shift(list); + rb_enc_associate(feature, extenc); + RBASIC_SET_CLASS_RAW(feature, rb_cString); + OBJ_FREEZE(feature); + rb_funcallv(self, require, 1, &feature); } *req_list = 0; } @@ -760,63 +760,63 @@ static void process_sflag(int *sflag) { if (*sflag > 0) { - long n; - const VALUE *args; - VALUE argv = rb_argv; + long n; + const VALUE *args; + VALUE argv = rb_argv; - n = RARRAY_LEN(argv); - args = RARRAY_CONST_PTR(argv); - while (n > 0) { - VALUE v = *args++; - char *s = StringValuePtr(v); - char *p; - int hyphen = FALSE; + n = RARRAY_LEN(argv); + args = RARRAY_CONST_PTR(argv); + while (n > 0) { + VALUE v = *args++; + char *s = StringValuePtr(v); + char *p; + int hyphen = FALSE; - if (s[0] != '-') - break; - n--; - if (s[1] == '-' && s[2] == '\0') - break; + if (s[0] != '-') + break; + n--; + if (s[1] == '-' && s[2] == '\0') + break; - v = Qtrue; - /* check if valid name before replacing - with _ */ - for (p = s + 1; *p; p++) { - if (*p == '=') { - *p++ = '\0'; - v = rb_str_new2(p); - break; - } - if (*p == '-') { - hyphen = TRUE; - } - else if (*p != '_' && !ISALNUM(*p)) { - VALUE name_error[2]; - name_error[0] = - rb_str_new2("invalid name for global variable - "); - if (!(p = strchr(p, '='))) { - rb_str_cat2(name_error[0], s); - } - else { - rb_str_cat(name_error[0], s, p - s); - } - name_error[1] = args[-1]; - rb_exc_raise(rb_class_new_instance(2, name_error, rb_eNameError)); - } - } - s[0] = '$'; - if (hyphen) { - for (p = s + 1; *p; ++p) { - if (*p == '-') - *p = '_'; - } - } - rb_gv_set(s, v); - } - n = RARRAY_LEN(argv) - n; - while (n--) { - rb_ary_shift(argv); - } - *sflag = -1; + v = Qtrue; + /* check if valid name before replacing - with _ */ + for (p = s + 1; *p; p++) { + if (*p == '=') { + *p++ = '\0'; + v = rb_str_new2(p); + break; + } + if (*p == '-') { + hyphen = TRUE; + } + else if (*p != '_' && !ISALNUM(*p)) { + VALUE name_error[2]; + name_error[0] = + rb_str_new2("invalid name for global variable - "); + if (!(p = strchr(p, '='))) { + rb_str_cat2(name_error[0], s); + } + else { + rb_str_cat(name_error[0], s, p - s); + } + name_error[1] = args[-1]; + rb_exc_raise(rb_class_new_instance(2, name_error, rb_eNameError)); + } + } + s[0] = '$'; + if (hyphen) { + for (p = s + 1; *p; ++p) { + if (*p == '-') + *p = '_'; + } + } + rb_gv_set(s, v); + } + n = RARRAY_LEN(argv) - n; + while (n--) { + rb_ary_shift(argv); + } + *sflag = -1; } } @@ -842,12 +842,12 @@ moreswitches(const char *s, ruby_cmdline_options_t *opt, int envopt) ap = 0; rb_str_cat(argary, (char *)&ap, sizeof(ap)); while (*p) { - ap = p; - rb_str_cat(argary, (char *)&ap, sizeof(ap)); - while (*p && !ISSPACE(*p)) ++p; - if (!*p) break; - *p++ = '\0'; - while (ISSPACE(*p)) ++p; + ap = p; + rb_str_cat(argary, (char *)&ap, sizeof(ap)); + while (*p && !ISSPACE(*p)) ++p; + if (!*p) break; + *p++ = '\0'; + while (ISSPACE(*p)) ++p; } argc = RSTRING_LEN(argary) / sizeof(ap); ap = 0; @@ -856,14 +856,14 @@ moreswitches(const char *s, ruby_cmdline_options_t *opt, int envopt) MEMMOVE(argv, RSTRING_PTR(argary), char *, argc); while ((i = proc_options(argc, argv, opt, envopt)) > 1 && envopt && (argc -= i) > 0) { - argv += i; - if (**argv != '-') { - *--*argv = '-'; - } - if ((*argv)[1]) { - ++argc; - --argv; - } + argv += i; + if (**argv != '-') { + *--*argv = '-'; + } + if ((*argv)[1]) { + ++argc; + --argv; + } } ruby_xfree(ptr); @@ -877,15 +877,15 @@ name_match_p(const char *name, const char *str, size_t len) { if (len == 0) return 0; while (1) { - while (TOLOWER(*str) == *name) { - if (!--len || !*++str) return 1; - ++name; - } - if (*str != '-' && *str != '_') return 0; - while (ISALNUM(*name)) name++; - if (*name != '-' && *name != '_') return 0; - ++name; - ++str; + while (TOLOWER(*str) == *name) { + if (!--len || !*++str) return 1; + ++name; + } + if (*str != '-' && *str != '_') return 0; + while (ISALNUM(*name)) name++; + if (*name != '-' && *name != '_') return 0; + ++name; + ++str; } } @@ -894,14 +894,14 @@ name_match_p(const char *name, const char *str, size_t len) #define UNSET_WHEN(name, bit, str, len) \ if (NAME_MATCH_P((name), (str), (len))) { \ - *(unsigned int *)arg &= ~(bit); \ - return; \ + *(unsigned int *)arg &= ~(bit); \ + return; \ } #define SET_WHEN(name, bit, str, len) \ if (NAME_MATCH_P((name), (str), (len))) { \ - *(unsigned int *)arg |= (bit); \ - return; \ + *(unsigned int *)arg |= (bit); \ + return; \ } #define LITERAL_NAME_ELEMENT(name) #name @@ -934,22 +934,22 @@ feature_option(const char *str, int len, void *arg, const unsigned int enable) #if AMBIGUOUS_FEATURE_NAMES if (matched == 1) goto found; if (matched > 1) { - VALUE mesg = rb_sprintf("ambiguous feature: `%.*s' (", len, str); + VALUE mesg = rb_sprintf("ambiguous feature: `%.*s' (", len, str); #define ADD_FEATURE_NAME(bit) \ - if (FEATURE_BIT(bit) & set) { \ - rb_str_cat_cstr(mesg, #bit); \ - if (--matched) rb_str_cat_cstr(mesg, ", "); \ - } - EACH_FEATURES(ADD_FEATURE_NAME, ;); - rb_str_cat_cstr(mesg, ")"); - rb_exc_raise(rb_exc_new_str(rb_eRuntimeError, mesg)); + if (FEATURE_BIT(bit) & set) { \ + rb_str_cat_cstr(mesg, #bit); \ + if (--matched) rb_str_cat_cstr(mesg, ", "); \ + } + EACH_FEATURES(ADD_FEATURE_NAME, ;); + rb_str_cat_cstr(mesg, ")"); + rb_exc_raise(rb_exc_new_str(rb_eRuntimeError, mesg)); #undef ADD_FEATURE_NAME } #else (void)set; #endif rb_warn("unknown argument for --%s: `%.*s'", - enable ? "enable" : "disable", len, str); + enable ? "enable" : "disable", len, str); rb_warn("features are [%.*s].", (int)strlen(list), list); return; @@ -1010,9 +1010,9 @@ set_option_encoding_once(const char *type, VALUE *name, const char *e, long elen ename = rb_str_new(e, elen); if (*name && - rb_funcall(ename, rb_intern("casecmp"), 1, *name) != INT2FIX(0)) { - rb_raise(rb_eRuntimeError, - "%s already set to %"PRIsVALUE, type, *name); + rb_funcall(ename, rb_intern("casecmp"), 1, *name) != INT2FIX(0)) { + rb_raise(rb_eRuntimeError, + "%s already set to %"PRIsVALUE, type, *name); } *name = ename; } @@ -1057,61 +1057,61 @@ proc_options(long argc, char **argv, ruby_cmdline_options_t *opt, int envopt) int warning = opt->warning; if (argc <= 0 || !argv) - return 0; + return 0; for (argc--, argv++; argc > 0; argc--, argv++) { - const char *const arg = argv[0]; - if (!arg || arg[0] != '-' || !arg[1]) - break; + const char *const arg = argv[0]; + if (!arg || arg[0] != '-' || !arg[1]) + break; - s = arg + 1; + s = arg + 1; reswitch: - switch (*s) { - case 'a': - if (envopt) goto noenvopt; - opt->do_split = TRUE; - s++; - goto reswitch; + switch (*s) { + case 'a': + if (envopt) goto noenvopt; + opt->do_split = TRUE; + s++; + goto reswitch; - case 'p': - if (envopt) goto noenvopt; - opt->do_print = TRUE; - /* through */ - case 'n': - if (envopt) goto noenvopt; - opt->do_loop = TRUE; - s++; - goto reswitch; + case 'p': + if (envopt) goto noenvopt; + opt->do_print = TRUE; + /* through */ + case 'n': + if (envopt) goto noenvopt; + opt->do_loop = TRUE; + s++; + goto reswitch; - case 'd': - ruby_debug = Qtrue; - ruby_verbose = Qtrue; - s++; - goto reswitch; + case 'd': + ruby_debug = Qtrue; + ruby_verbose = Qtrue; + s++; + goto reswitch; - case 'y': - if (envopt) goto noenvopt; - opt->dump |= DUMP_BIT(yydebug); - s++; - goto reswitch; + case 'y': + if (envopt) goto noenvopt; + opt->dump |= DUMP_BIT(yydebug); + s++; + goto reswitch; - case 'v': - if (opt->verbose) { - s++; - goto reswitch; - } - opt->dump |= DUMP_BIT(version_v); - opt->verbose = 1; - case 'w': - if (!opt->warning) { - warning = 1; - ruby_verbose = Qtrue; - } - FEATURE_SET(opt->warn, RB_WARN_CATEGORY_ALL_BITS); - s++; - goto reswitch; + case 'v': + if (opt->verbose) { + s++; + goto reswitch; + } + opt->dump |= DUMP_BIT(version_v); + opt->verbose = 1; + case 'w': + if (!opt->warning) { + warning = 1; + ruby_verbose = Qtrue; + } + FEATURE_SET(opt->warn, RB_WARN_CATEGORY_ALL_BITS); + s++; + goto reswitch; - case 'W': + case 'W': if (s[1] == ':') { unsigned int bits = 0; static const char no_prefix[] = "no-"; @@ -1130,293 +1130,293 @@ proc_options(long argc, char **argv, ruby_cmdline_options_t *opt, int envopt) if (bits) FEATURE_SET_TO(opt->warn, bits, enable ? bits : 0); break; } - { - size_t numlen; - int v = 2; /* -W as -W2 */ + { + size_t numlen; + int v = 2; /* -W as -W2 */ - if (*++s) { - v = scan_oct(s, 1, &numlen); - if (numlen == 0) + if (*++s) { + v = scan_oct(s, 1, &numlen); + if (numlen == 0) v = 2; - s += numlen; - } - if (!opt->warning) { - switch (v) { - case 0: - ruby_verbose = Qnil; - break; - case 1: - ruby_verbose = Qfalse; - break; - default: - ruby_verbose = Qtrue; - break; - } - } - warning = 1; - switch (v) { - case 0: - FEATURE_SET_TO(opt->warn, RB_WARN_CATEGORY_ALL_BITS, 0); - break; - case 1: - FEATURE_SET_TO(opt->warn, 1U << RB_WARN_CATEGORY_DEPRECATED, 0); - break; - default: - FEATURE_SET(opt->warn, RB_WARN_CATEGORY_ALL_BITS); - break; - } - } - goto reswitch; + s += numlen; + } + if (!opt->warning) { + switch (v) { + case 0: + ruby_verbose = Qnil; + break; + case 1: + ruby_verbose = Qfalse; + break; + default: + ruby_verbose = Qtrue; + break; + } + } + warning = 1; + switch (v) { + case 0: + FEATURE_SET_TO(opt->warn, RB_WARN_CATEGORY_ALL_BITS, 0); + break; + case 1: + FEATURE_SET_TO(opt->warn, 1U << RB_WARN_CATEGORY_DEPRECATED, 0); + break; + default: + FEATURE_SET(opt->warn, RB_WARN_CATEGORY_ALL_BITS); + break; + } + } + goto reswitch; - case 'c': - if (envopt) goto noenvopt; - opt->dump |= DUMP_BIT(syntax); - s++; - goto reswitch; + case 'c': + if (envopt) goto noenvopt; + opt->dump |= DUMP_BIT(syntax); + s++; + goto reswitch; - case 's': - if (envopt) goto noenvopt; - forbid_setid("-s"); - if (!opt->sflag) opt->sflag = 1; - s++; - goto reswitch; + case 's': + if (envopt) goto noenvopt; + forbid_setid("-s"); + if (!opt->sflag) opt->sflag = 1; + s++; + goto reswitch; - case 'h': - if (envopt) goto noenvopt; - opt->dump |= DUMP_BIT(usage); - goto switch_end; + case 'h': + if (envopt) goto noenvopt; + opt->dump |= DUMP_BIT(usage); + goto switch_end; - case 'l': - if (envopt) goto noenvopt; - opt->do_line = TRUE; - rb_output_rs = rb_rs; - s++; - goto reswitch; + case 'l': + if (envopt) goto noenvopt; + opt->do_line = TRUE; + rb_output_rs = rb_rs; + s++; + goto reswitch; - case 'S': - if (envopt) goto noenvopt; - forbid_setid("-S"); - opt->do_search = TRUE; - s++; - goto reswitch; + case 'S': + if (envopt) goto noenvopt; + forbid_setid("-S"); + opt->do_search = TRUE; + s++; + goto reswitch; - case 'e': - if (envopt) goto noenvopt; - forbid_setid("-e"); - if (!*++s) { - if (!--argc) - rb_raise(rb_eRuntimeError, "no code specified for -e"); - s = *++argv; - } - if (!opt->e_script) { - opt->e_script = rb_str_new(0, 0); - if (opt->script == 0) - opt->script = "-e"; - } - rb_str_cat2(opt->e_script, s); - rb_str_cat2(opt->e_script, "\n"); - break; + case 'e': + if (envopt) goto noenvopt; + forbid_setid("-e"); + if (!*++s) { + if (!--argc) + rb_raise(rb_eRuntimeError, "no code specified for -e"); + s = *++argv; + } + if (!opt->e_script) { + opt->e_script = rb_str_new(0, 0); + if (opt->script == 0) + opt->script = "-e"; + } + rb_str_cat2(opt->e_script, s); + rb_str_cat2(opt->e_script, "\n"); + break; - case 'r': - forbid_setid("-r"); - if (*++s) { - add_modules(&opt->req_list, s); - } - else if (argc > 1) { - add_modules(&opt->req_list, argv[1]); - argc--, argv++; - } - break; + case 'r': + forbid_setid("-r"); + if (*++s) { + add_modules(&opt->req_list, s); + } + else if (argc > 1) { + add_modules(&opt->req_list, argv[1]); + argc--, argv++; + } + break; - case 'i': - if (envopt) goto noenvopt; - forbid_setid("-i"); - ruby_set_inplace_mode(s + 1); - break; + case 'i': + if (envopt) goto noenvopt; + forbid_setid("-i"); + ruby_set_inplace_mode(s + 1); + break; - case 'x': - if (envopt) goto noenvopt; - forbid_setid("-x"); - opt->xflag = TRUE; - s++; - if (*s && chdir(s) < 0) { - rb_fatal("Can't chdir to %s", s); - } - break; + case 'x': + if (envopt) goto noenvopt; + forbid_setid("-x"); + opt->xflag = TRUE; + s++; + if (*s && chdir(s) < 0) { + rb_fatal("Can't chdir to %s", s); + } + break; - case 'C': - case 'X': - if (envopt) goto noenvopt; - if (!*++s && (!--argc || !(s = *++argv) || !*s)) { - rb_fatal("Can't chdir"); - } - if (chdir(s) < 0) { - rb_fatal("Can't chdir to %s", s); - } - break; + case 'C': + case 'X': + if (envopt) goto noenvopt; + if (!*++s && (!--argc || !(s = *++argv) || !*s)) { + rb_fatal("Can't chdir"); + } + if (chdir(s) < 0) { + rb_fatal("Can't chdir to %s", s); + } + break; - case 'F': - if (envopt) goto noenvopt; - if (*++s) { - rb_fs = rb_reg_new(s, strlen(s), 0); - } - break; + case 'F': + if (envopt) goto noenvopt; + if (*++s) { + rb_fs = rb_reg_new(s, strlen(s), 0); + } + break; - case 'E': - if (!*++s && (!--argc || !(s = *++argv))) { - rb_raise(rb_eRuntimeError, "missing argument for -E"); - } - goto encoding; + case 'E': + if (!*++s && (!--argc || !(s = *++argv))) { + rb_raise(rb_eRuntimeError, "missing argument for -E"); + } + goto encoding; - case 'U': - set_internal_encoding_once(opt, "UTF-8", 0); - ++s; - goto reswitch; + case 'U': + set_internal_encoding_once(opt, "UTF-8", 0); + ++s; + goto reswitch; - case 'K': - if (*++s) { - const char *enc_name = 0; - switch (*s) { - case 'E': case 'e': - enc_name = "EUC-JP"; - break; - case 'S': case 's': - enc_name = "Windows-31J"; - break; - case 'U': case 'u': - enc_name = "UTF-8"; - break; - case 'N': case 'n': case 'A': case 'a': - enc_name = "ASCII-8BIT"; - break; - } - if (enc_name) { - opt->src.enc.name = rb_str_new2(enc_name); - if (!opt->ext.enc.name) - opt->ext.enc.name = opt->src.enc.name; - } - s++; - } - goto reswitch; + case 'K': + if (*++s) { + const char *enc_name = 0; + switch (*s) { + case 'E': case 'e': + enc_name = "EUC-JP"; + break; + case 'S': case 's': + enc_name = "Windows-31J"; + break; + case 'U': case 'u': + enc_name = "UTF-8"; + break; + case 'N': case 'n': case 'A': case 'a': + enc_name = "ASCII-8BIT"; + break; + } + if (enc_name) { + opt->src.enc.name = rb_str_new2(enc_name); + if (!opt->ext.enc.name) + opt->ext.enc.name = opt->src.enc.name; + } + s++; + } + goto reswitch; - case 'I': - forbid_setid("-I"); - if (*++s) - ruby_incpush_expand(s); - else if (argc > 1) { - ruby_incpush_expand(argv[1]); - argc--, argv++; - } - break; + case 'I': + forbid_setid("-I"); + if (*++s) + ruby_incpush_expand(s); + else if (argc > 1) { + ruby_incpush_expand(argv[1]); + argc--, argv++; + } + break; - case '0': - if (envopt) goto noenvopt; - { - size_t numlen; - int v; - char c; + case '0': + if (envopt) goto noenvopt; + { + size_t numlen; + int v; + char c; - v = scan_oct(s, 4, &numlen); - s += numlen; - if (v > 0377) - rb_rs = Qnil; - else if (v == 0 && numlen >= 2) { - rb_rs = rb_str_new2(""); - } - else { - c = v & 0xff; - rb_rs = rb_str_new(&c, 1); - } - } - goto reswitch; + v = scan_oct(s, 4, &numlen); + s += numlen; + if (v > 0377) + rb_rs = Qnil; + else if (v == 0 && numlen >= 2) { + rb_rs = rb_str_new2(""); + } + else { + c = v & 0xff; + rb_rs = rb_str_new(&c, 1); + } + } + goto reswitch; - case '-': - if (!s[1] || (s[1] == '\r' && !s[2])) { - argc--, argv++; - goto switch_end; - } - s++; + case '-': + if (!s[1] || (s[1] == '\r' && !s[2])) { + argc--, argv++; + goto switch_end; + } + s++; # define is_option_end(c, allow_hyphen) \ - (!(c) || ((allow_hyphen) && (c) == '-') || (c) == '=') + (!(c) || ((allow_hyphen) && (c) == '-') || (c) == '=') # define check_envopt(name, allow_envopt) \ - (((allow_envopt) || !envopt) ? (void)0 : \ - rb_raise(rb_eRuntimeError, "invalid switch in RUBYOPT: --" name)) + (((allow_envopt) || !envopt) ? (void)0 : \ + rb_raise(rb_eRuntimeError, "invalid switch in RUBYOPT: --" name)) # define need_argument(name, s, needs_arg, next_arg) \ - ((*(s) ? !*++(s) : (next_arg) && (!argc || !((s) = argv[1]) || (--argc, ++argv, 0))) && (needs_arg) ? \ - rb_raise(rb_eRuntimeError, "missing argument for --" name) \ - : (void)0) + ((*(s) ? !*++(s) : (next_arg) && (!argc || !((s) = argv[1]) || (--argc, ++argv, 0))) && (needs_arg) ? \ + rb_raise(rb_eRuntimeError, "missing argument for --" name) \ + : (void)0) # define is_option_with_arg(name, allow_hyphen, allow_envopt) \ - is_option_with_optarg(name, allow_hyphen, allow_envopt, Qtrue, Qtrue) + is_option_with_optarg(name, allow_hyphen, allow_envopt, Qtrue, Qtrue) # define is_option_with_optarg(name, allow_hyphen, allow_envopt, needs_arg, next_arg) \ - (strncmp((name), s, n = sizeof(name) - 1) == 0 && is_option_end(s[n], (allow_hyphen)) && \ + (strncmp((name), s, n = sizeof(name) - 1) == 0 && is_option_end(s[n], (allow_hyphen)) && \ (s[n] != '-' || s[n+1]) ? \ - (check_envopt(name, (allow_envopt)), s += n, \ - need_argument(name, s, needs_arg, next_arg), 1) : 0) + (check_envopt(name, (allow_envopt)), s += n, \ + need_argument(name, s, needs_arg, next_arg), 1) : 0) - if (strcmp("copyright", s) == 0) { - if (envopt) goto noenvopt_long; - opt->dump |= DUMP_BIT(copyright); - } - else if (is_option_with_optarg("debug", Qtrue, Qtrue, Qfalse, Qfalse)) { - if (s && *s) { - ruby_each_words(s, debug_option, &opt->features); - } - else { - ruby_debug = Qtrue; - ruby_verbose = Qtrue; - } + if (strcmp("copyright", s) == 0) { + if (envopt) goto noenvopt_long; + opt->dump |= DUMP_BIT(copyright); } - else if (is_option_with_arg("enable", Qtrue, Qtrue)) { - ruby_each_words(s, enable_option, &opt->features); - } - else if (is_option_with_arg("disable", Qtrue, Qtrue)) { - ruby_each_words(s, disable_option, &opt->features); - } - else if (is_option_with_arg("encoding", Qfalse, Qtrue)) { - char *p; - encoding: - do { + else if (is_option_with_optarg("debug", Qtrue, Qtrue, Qfalse, Qfalse)) { + if (s && *s) { + ruby_each_words(s, debug_option, &opt->features); + } + else { + ruby_debug = Qtrue; + ruby_verbose = Qtrue; + } + } + else if (is_option_with_arg("enable", Qtrue, Qtrue)) { + ruby_each_words(s, enable_option, &opt->features); + } + else if (is_option_with_arg("disable", Qtrue, Qtrue)) { + ruby_each_words(s, disable_option, &opt->features); + } + else if (is_option_with_arg("encoding", Qfalse, Qtrue)) { + char *p; + encoding: + do { # define set_encoding_part(type) \ - if (!(p = strchr(s, ':'))) { \ - set_##type##_encoding_once(opt, s, 0); \ - break; \ - } \ - else if (p > s) { \ - set_##type##_encoding_once(opt, s, p-s); \ - } - set_encoding_part(external); - if (!*(s = ++p)) break; - set_encoding_part(internal); - if (!*(s = ++p)) break; + if (!(p = strchr(s, ':'))) { \ + set_##type##_encoding_once(opt, s, 0); \ + break; \ + } \ + else if (p > s) { \ + set_##type##_encoding_once(opt, s, p-s); \ + } + set_encoding_part(external); + if (!*(s = ++p)) break; + set_encoding_part(internal); + if (!*(s = ++p)) break; #if defined ALLOW_DEFAULT_SOURCE_ENCODING && ALLOW_DEFAULT_SOURCE_ENCODING - set_encoding_part(source); - if (!*(s = ++p)) break; + set_encoding_part(source); + if (!*(s = ++p)) break; #endif - rb_raise(rb_eRuntimeError, "extra argument for %s: %s", - (arg[1] == '-' ? "--encoding" : "-E"), s); + rb_raise(rb_eRuntimeError, "extra argument for %s: %s", + (arg[1] == '-' ? "--encoding" : "-E"), s); # undef set_encoding_part - } while (0); - } - else if (is_option_with_arg("internal-encoding", Qfalse, Qtrue)) { - set_internal_encoding_once(opt, s, 0); - } - else if (is_option_with_arg("external-encoding", Qfalse, Qtrue)) { - set_external_encoding_once(opt, s, 0); - } + } while (0); + } + else if (is_option_with_arg("internal-encoding", Qfalse, Qtrue)) { + set_internal_encoding_once(opt, s, 0); + } + else if (is_option_with_arg("external-encoding", Qfalse, Qtrue)) { + set_external_encoding_once(opt, s, 0); + } #if defined ALLOW_DEFAULT_SOURCE_ENCODING && ALLOW_DEFAULT_SOURCE_ENCODING - else if (is_option_with_arg("source-encoding", Qfalse, Qtrue)) { - set_source_encoding_once(opt, s, 0); - } + else if (is_option_with_arg("source-encoding", Qfalse, Qtrue)) { + set_source_encoding_once(opt, s, 0); + } #endif - else if (strcmp("version", s) == 0) { - if (envopt) goto noenvopt_long; - opt->dump |= DUMP_BIT(version); - } - else if (strcmp("verbose", s) == 0) { - opt->verbose = 1; - ruby_verbose = Qtrue; - } + else if (strcmp("version", s) == 0) { + if (envopt) goto noenvopt_long; + opt->dump |= DUMP_BIT(version); + } + else if (strcmp("verbose", s) == 0) { + opt->verbose = 1; + ruby_verbose = Qtrue; + } else if (strcmp("jit", s) == 0) { #if !USE_MJIT rb_warn("Ruby was built without JIT support"); @@ -1441,59 +1441,59 @@ proc_options(long argc, char **argv, ruby_cmdline_options_t *opt, int envopt) rb_warn("Ruby was built without YJIT support"); #endif } - else if (strcmp("yydebug", s) == 0) { - if (envopt) goto noenvopt_long; - opt->dump |= DUMP_BIT(yydebug); - } - else if (is_option_with_arg("dump", Qfalse, Qfalse)) { - ruby_each_words(s, dump_option, &opt->dump); - } - else if (strcmp("help", s) == 0) { - if (envopt) goto noenvopt_long; - opt->dump |= DUMP_BIT(help); - goto switch_end; - } + else if (strcmp("yydebug", s) == 0) { + if (envopt) goto noenvopt_long; + opt->dump |= DUMP_BIT(yydebug); + } + else if (is_option_with_arg("dump", Qfalse, Qfalse)) { + ruby_each_words(s, dump_option, &opt->dump); + } + else if (strcmp("help", s) == 0) { + if (envopt) goto noenvopt_long; + opt->dump |= DUMP_BIT(help); + goto switch_end; + } else if (is_option_with_arg("backtrace-limit", Qfalse, Qfalse)) { char *e; long n = strtol(s, &e, 10); if (errno == ERANGE || n < 0 || *e) rb_raise(rb_eRuntimeError, "wrong limit for backtrace length"); rb_backtrace_length_limit = n; } - else { - rb_raise(rb_eRuntimeError, - "invalid option --%s (-h will show valid options)", s); - } - break; - - case '\r': - if (!s[1]) - break; - - default: - { + else { rb_raise(rb_eRuntimeError, - "invalid option -%c (-h will show valid options)", + "invalid option --%s (-h will show valid options)", s); + } + break; + + case '\r': + if (!s[1]) + break; + + default: + { + rb_raise(rb_eRuntimeError, + "invalid option -%c (-h will show valid options)", (int)(unsigned char)*s); - } - goto switch_end; + } + goto switch_end; - noenvopt: - /* "EIdvwWrKU" only */ - rb_raise(rb_eRuntimeError, "invalid switch in RUBYOPT: -%c", *s); - break; + noenvopt: + /* "EIdvwWrKU" only */ + rb_raise(rb_eRuntimeError, "invalid switch in RUBYOPT: -%c", *s); + break; - noenvopt_long: - rb_raise(rb_eRuntimeError, "invalid switch in RUBYOPT: --%s", s); - break; + noenvopt_long: + rb_raise(rb_eRuntimeError, "invalid switch in RUBYOPT: --%s", s); + break; - case 0: - break; + case 0: + break; # undef is_option_end # undef check_envopt # undef need_argument # undef is_option_with_arg # undef is_option_with_optarg - } + } } switch_end: @@ -1554,10 +1554,10 @@ opt_enc_index(VALUE enc_name) int i = rb_enc_find_index(s); if (i < 0) { - rb_raise(rb_eRuntimeError, "unknown encoding name - %s", s); + rb_raise(rb_eRuntimeError, "unknown encoding name - %s", s); } else if (rb_enc_dummy_p(rb_enc_from_index(i))) { - rb_raise(rb_eRuntimeError, "dummy encoding is not acceptable - %s ", s); + rb_raise(rb_eRuntimeError, "dummy encoding is not acceptable - %s ", s); } return i; } @@ -1589,8 +1589,8 @@ uscore_get(void) line = rb_lastline_get(); if (!RB_TYPE_P(line, T_STRING)) { - rb_raise(rb_eTypeError, "$_ value need to be String (%s given)", - NIL_P(line) ? "nil" : rb_obj_classname(line)); + rb_raise(rb_eTypeError, "$_ value need to be String (%s given)", + NIL_P(line) ? "nil" : rb_obj_classname(line)); } return line; } @@ -1725,10 +1725,10 @@ process_options(int argc, char **argv, ruby_cmdline_options_t *opt) if (opt->dump & (DUMP_BIT(usage)|DUMP_BIT(help))) { int tty = isatty(1); - const char *const progname = - (argc > 0 && argv && argv[0] ? argv[0] : - origarg.argc > 0 && origarg.argv && origarg.argv[0] ? origarg.argv[0] : - ruby_engine); + const char *const progname = + (argc > 0 && argv && argv[0] ? argv[0] : + origarg.argc > 0 && origarg.argv && origarg.argv[0] ? origarg.argv[0] : + ruby_engine); int columns = 0; if ((opt->dump & DUMP_BIT(help)) && tty) { const char *pager_env = getenv("RUBY_PAGER"); @@ -1779,28 +1779,28 @@ process_options(int argc, char **argv, ruby_cmdline_options_t *opt) #endif } } - usage(progname, (opt->dump & DUMP_BIT(help)), tty, columns); - return Qtrue; + usage(progname, (opt->dump & DUMP_BIT(help)), tty, columns); + return Qtrue; } argc -= i; argv += i; if (FEATURE_SET_P(opt->features, rubyopt) && (s = getenv("RUBYOPT"))) { - VALUE src_enc_name = opt->src.enc.name; - VALUE ext_enc_name = opt->ext.enc.name; - VALUE int_enc_name = opt->intern.enc.name; + VALUE src_enc_name = opt->src.enc.name; + VALUE ext_enc_name = opt->ext.enc.name; + VALUE int_enc_name = opt->intern.enc.name; ruby_features_t feat = opt->features; ruby_features_t warn = opt->warn; - opt->src.enc.name = opt->ext.enc.name = opt->intern.enc.name = 0; - moreswitches(s, opt, 1); - if (src_enc_name) - opt->src.enc.name = src_enc_name; - if (ext_enc_name) - opt->ext.enc.name = ext_enc_name; - if (int_enc_name) - opt->intern.enc.name = int_enc_name; + opt->src.enc.name = opt->ext.enc.name = opt->intern.enc.name = 0; + moreswitches(s, opt, 1); + if (src_enc_name) + opt->src.enc.name = src_enc_name; + if (ext_enc_name) + opt->ext.enc.name = ext_enc_name; + if (int_enc_name) + opt->intern.enc.name = int_enc_name; FEATURE_SET_RESTORE(opt->features, feat); FEATURE_SET_RESTORE(opt->warn, warn); } @@ -1838,44 +1838,44 @@ process_options(int argc, char **argv, ruby_cmdline_options_t *opt) #endif Init_ruby_description(); if (opt->dump & (DUMP_BIT(version) | DUMP_BIT(version_v))) { - ruby_show_version(); - if (opt->dump & DUMP_BIT(version)) return Qtrue; + ruby_show_version(); + if (opt->dump & DUMP_BIT(version)) return Qtrue; } if (opt->dump & DUMP_BIT(copyright)) { - ruby_show_copyright(); - return Qtrue; + ruby_show_copyright(); + return Qtrue; } if (!opt->e_script) { - if (argc <= 0) { /* no more args */ - if (opt->verbose) - return Qtrue; - opt->script = "-"; - } - else { - opt->script = argv[0]; - if (!opt->script || opt->script[0] == '\0') { - opt->script = "-"; - } - else if (opt->do_search) { - const char *path = getenv("RUBYPATH"); + if (argc <= 0) { /* no more args */ + if (opt->verbose) + return Qtrue; + opt->script = "-"; + } + else { + opt->script = argv[0]; + if (!opt->script || opt->script[0] == '\0') { + opt->script = "-"; + } + else if (opt->do_search) { + const char *path = getenv("RUBYPATH"); - opt->script = 0; - if (path) { - opt->script = dln_find_file_r(argv[0], path, fbuf, sizeof(fbuf)); - } - if (!opt->script) { - opt->script = dln_find_file_r(argv[0], getenv(PATH_ENV), fbuf, sizeof(fbuf)); - } - if (!opt->script) - opt->script = argv[0]; - } - argc--; - argv++; - } - if (opt->script[0] == '-' && !opt->script[1]) { - forbid_setid("program input from stdin"); - } + opt->script = 0; + if (path) { + opt->script = dln_find_file_r(argv[0], path, fbuf, sizeof(fbuf)); + } + if (!opt->script) { + opt->script = dln_find_file_r(argv[0], getenv(PATH_ENV), fbuf, sizeof(fbuf)); + } + if (!opt->script) + opt->script = argv[0]; + } + argc--; + argv++; + } + if (opt->script[0] == '-' && !opt->script[1]) { + forbid_setid("program input from stdin"); + } } opt->script_name = rb_str_new_cstr(opt->script); @@ -1902,66 +1902,66 @@ process_options(int argc, char **argv, ruby_cmdline_options_t *opt) rb_obj_freeze(rb_progname); parser = rb_parser_new(); if (opt->dump & DUMP_BIT(yydebug)) { - rb_parser_set_yydebug(parser, Qtrue); + rb_parser_set_yydebug(parser, Qtrue); } if (opt->ext.enc.name != 0) { - opt->ext.enc.index = opt_enc_index(opt->ext.enc.name); + opt->ext.enc.index = opt_enc_index(opt->ext.enc.name); } if (opt->intern.enc.name != 0) { - opt->intern.enc.index = opt_enc_index(opt->intern.enc.name); + opt->intern.enc.index = opt_enc_index(opt->intern.enc.name); } if (opt->src.enc.name != 0) { - opt->src.enc.index = opt_enc_index(opt->src.enc.name); - src_encoding_index = opt->src.enc.index; + opt->src.enc.index = opt_enc_index(opt->src.enc.name); + src_encoding_index = opt->src.enc.index; } if (opt->ext.enc.index >= 0) { - enc = rb_enc_from_index(opt->ext.enc.index); + enc = rb_enc_from_index(opt->ext.enc.index); } else { - enc = IF_UTF8_PATH(uenc, lenc); + enc = IF_UTF8_PATH(uenc, lenc); } rb_enc_set_default_external(rb_enc_from_encoding(enc)); if (opt->intern.enc.index >= 0) { - enc = rb_enc_from_index(opt->intern.enc.index); - rb_enc_set_default_internal(rb_enc_from_encoding(enc)); - opt->intern.enc.index = -1; + enc = rb_enc_from_index(opt->intern.enc.index); + rb_enc_set_default_internal(rb_enc_from_encoding(enc)); + opt->intern.enc.index = -1; #if UTF8_PATH - ienc = enc; + ienc = enc; #endif } script_name = opt->script_name; rb_enc_associate(opt->script_name, IF_UTF8_PATH(uenc, lenc)); #if UTF8_PATH if (uenc != lenc) { - opt->script_name = str_conv_enc(opt->script_name, uenc, lenc); - opt->script = RSTRING_PTR(opt->script_name); + opt->script_name = str_conv_enc(opt->script_name, uenc, lenc); + opt->script = RSTRING_PTR(opt->script_name); } #endif rb_obj_freeze(opt->script_name); if (IF_UTF8_PATH(uenc != lenc, 1)) { - long i; + long i; VALUE load_path = vm->load_path; - const ID id_initial_load_path_mark = INITIAL_LOAD_PATH_MARK; + const ID id_initial_load_path_mark = INITIAL_LOAD_PATH_MARK; int modifiable = FALSE; rb_get_expanded_load_path(); - for (i = 0; i < RARRAY_LEN(load_path); ++i) { - VALUE path = RARRAY_AREF(load_path, i); - int mark = rb_attr_get(path, id_initial_load_path_mark) == path; + for (i = 0; i < RARRAY_LEN(load_path); ++i) { + VALUE path = RARRAY_AREF(load_path, i); + int mark = rb_attr_get(path, id_initial_load_path_mark) == path; #if UTF8_PATH - VALUE newpath = rb_str_conv_enc(path, uenc, lenc); - if (newpath == path) continue; - path = newpath; + VALUE newpath = rb_str_conv_enc(path, uenc, lenc); + if (newpath == path) continue; + path = newpath; #else - if (!(path = copy_str(path, lenc, !mark))) continue; + if (!(path = copy_str(path, lenc, !mark))) continue; #endif - if (mark) rb_ivar_set(path, id_initial_load_path_mark, path); + if (mark) rb_ivar_set(path, id_initial_load_path_mark, path); if (!modifiable) { rb_ary_modify(load_path); modifiable = TRUE; } - RARRAY_ASET(load_path, i, path); - } + RARRAY_ASET(load_path, i, path); + } if (modifiable) { rb_ary_replace(vm->load_path_snapshot, load_path); } @@ -1970,13 +1970,13 @@ process_options(int argc, char **argv, ruby_cmdline_options_t *opt) VALUE loaded_features = vm->loaded_features; bool modified = false; for (long i = loaded_before_enc; i < RARRAY_LEN(loaded_features); ++i) { - VALUE path = RARRAY_AREF(loaded_features, i); + VALUE path = RARRAY_AREF(loaded_features, i); if (!(path = copy_str(path, IF_UTF8_PATH(uenc, lenc), true))) continue; if (!modified) { rb_ary_modify(loaded_features); modified = true; } - RARRAY_ASET(loaded_features, i, path); + RARRAY_ASET(loaded_features, i, path); } if (modified) { rb_ary_replace(vm->loaded_features_snapshot, loaded_features); @@ -1984,13 +1984,13 @@ process_options(int argc, char **argv, ruby_cmdline_options_t *opt) } if (opt->features.mask & COMPILATION_FEATURES) { - VALUE option = rb_hash_new(); + VALUE option = rb_hash_new(); #define SET_COMPILE_OPTION(h, o, name) \ - rb_hash_aset((h), ID2SYM(rb_intern_const(#name)), \ + rb_hash_aset((h), ID2SYM(rb_intern_const(#name)), \ RBOOL(FEATURE_SET_P(o->features, name))) - SET_COMPILE_OPTION(option, opt, frozen_string_literal); - SET_COMPILE_OPTION(option, opt, debug_frozen_string_literal); - rb_funcallv(rb_cISeq, rb_intern_const("compile_option="), 1, &option); + SET_COMPILE_OPTION(option, opt, frozen_string_literal); + SET_COMPILE_OPTION(option, opt, debug_frozen_string_literal); + rb_funcallv(rb_cISeq, rb_intern_const("compile_option="), 1, &option); #undef SET_COMPILE_OPTION } ruby_set_argv(argc, argv); @@ -1999,115 +1999,115 @@ process_options(int argc, char **argv, ruby_cmdline_options_t *opt) rb_parser_set_context(parser, 0, TRUE); if (opt->e_script) { - VALUE progname = rb_progname; - rb_encoding *eenc; - if (opt->src.enc.index >= 0) { - eenc = rb_enc_from_index(opt->src.enc.index); - } - else { - eenc = lenc; + VALUE progname = rb_progname; + rb_encoding *eenc; + if (opt->src.enc.index >= 0) { + eenc = rb_enc_from_index(opt->src.enc.index); + } + else { + eenc = lenc; #if UTF8_PATH - if (ienc) eenc = ienc; + if (ienc) eenc = ienc; #endif - } + } #if UTF8_PATH - if (eenc != uenc) { - opt->e_script = str_conv_enc(opt->e_script, uenc, eenc); - } + if (eenc != uenc) { + opt->e_script = str_conv_enc(opt->e_script, uenc, eenc); + } #endif - rb_enc_associate(opt->e_script, eenc); + rb_enc_associate(opt->e_script, eenc); ruby_opt_init(opt); ruby_set_script_name(progname); - rb_parser_set_options(parser, opt->do_print, opt->do_loop, - opt->do_line, opt->do_split); - ast = rb_parser_compile_string(parser, opt->script, opt->e_script, 1); + rb_parser_set_options(parser, opt->do_print, opt->do_loop, + opt->do_line, opt->do_split); + ast = rb_parser_compile_string(parser, opt->script, opt->e_script, 1); } else { - VALUE f; - f = open_load_file(script_name, &opt->xflag); - ast = load_file(parser, opt->script_name, f, 1, opt); + VALUE f; + f = open_load_file(script_name, &opt->xflag); + ast = load_file(parser, opt->script_name, f, 1, opt); } ruby_set_script_name(opt->script_name); if (dump & DUMP_BIT(yydebug)) { - dump &= ~DUMP_BIT(yydebug); - if (!dump) return Qtrue; + dump &= ~DUMP_BIT(yydebug); + if (!dump) return Qtrue; } if (opt->ext.enc.index >= 0) { - enc = rb_enc_from_index(opt->ext.enc.index); + enc = rb_enc_from_index(opt->ext.enc.index); } else { - enc = IF_UTF8_PATH(uenc, lenc); + enc = IF_UTF8_PATH(uenc, lenc); } rb_enc_set_default_external(rb_enc_from_encoding(enc)); if (opt->intern.enc.index >= 0) { - /* Set in the shebang line */ - enc = rb_enc_from_index(opt->intern.enc.index); - rb_enc_set_default_internal(rb_enc_from_encoding(enc)); + /* Set in the shebang line */ + enc = rb_enc_from_index(opt->intern.enc.index); + rb_enc_set_default_internal(rb_enc_from_encoding(enc)); } else if (!rb_default_internal_encoding()) - /* Freeze default_internal */ - rb_enc_set_default_internal(Qnil); + /* Freeze default_internal */ + rb_enc_set_default_internal(Qnil); rb_stdio_set_default_encoding(); if (!ast->body.root) { - rb_ast_dispose(ast); - return Qfalse; + rb_ast_dispose(ast); + return Qfalse; } process_sflag(&opt->sflag); opt->xflag = 0; if (dump & DUMP_BIT(syntax)) { - printf("Syntax OK\n"); - dump &= ~DUMP_BIT(syntax); - if (!dump) return Qtrue; + printf("Syntax OK\n"); + dump &= ~DUMP_BIT(syntax); + if (!dump) return Qtrue; } if (opt->do_loop) { - rb_define_global_function("sub", rb_f_sub, -1); - rb_define_global_function("gsub", rb_f_gsub, -1); - rb_define_global_function("chop", rb_f_chop, 0); - rb_define_global_function("chomp", rb_f_chomp, -1); + rb_define_global_function("sub", rb_f_sub, -1); + rb_define_global_function("gsub", rb_f_gsub, -1); + rb_define_global_function("chop", rb_f_chop, 0); + rb_define_global_function("chomp", rb_f_chomp, -1); } if (dump & (DUMP_BIT(parsetree)|DUMP_BIT(parsetree_with_comment))) { - rb_io_write(rb_stdout, rb_parser_dump_tree(ast->body.root, dump & DUMP_BIT(parsetree_with_comment))); - rb_io_flush(rb_stdout); - dump &= ~DUMP_BIT(parsetree)&~DUMP_BIT(parsetree_with_comment); - if (!dump) { - rb_ast_dispose(ast); - return Qtrue; - } + rb_io_write(rb_stdout, rb_parser_dump_tree(ast->body.root, dump & DUMP_BIT(parsetree_with_comment))); + rb_io_flush(rb_stdout); + dump &= ~DUMP_BIT(parsetree)&~DUMP_BIT(parsetree_with_comment); + if (!dump) { + rb_ast_dispose(ast); + return Qtrue; + } } { - VALUE path = Qnil; - if (!opt->e_script && strcmp(opt->script, "-")) { - path = rb_realpath_internal(Qnil, script_name, 1); + VALUE path = Qnil; + if (!opt->e_script && strcmp(opt->script, "-")) { + path = rb_realpath_internal(Qnil, script_name, 1); #if UTF8_PATH - if (uenc != lenc) { - path = str_conv_enc(path, uenc, lenc); - } + if (uenc != lenc) { + path = str_conv_enc(path, uenc, lenc); + } #endif - if (!ENCODING_GET(path)) { /* ASCII-8BIT */ - rb_enc_copy(path, opt->script_name); - } - } + if (!ENCODING_GET(path)) { /* ASCII-8BIT */ + rb_enc_copy(path, opt->script_name); + } + } rb_binding_t *toplevel_binding; GetBindingPtr(rb_const_get(rb_cObject, rb_intern("TOPLEVEL_BINDING")), toplevel_binding); const struct rb_block *base_block = toplevel_context(toplevel_binding); - iseq = rb_iseq_new_main(&ast->body, opt->script_name, path, vm_block_iseq(base_block), !(dump & DUMP_BIT(insns_without_opt))); - rb_ast_dispose(ast); + iseq = rb_iseq_new_main(&ast->body, opt->script_name, path, vm_block_iseq(base_block), !(dump & DUMP_BIT(insns_without_opt))); + rb_ast_dispose(ast); } if (dump & (DUMP_BIT(insns) | DUMP_BIT(insns_without_opt))) { - rb_io_write(rb_stdout, rb_iseq_disasm((const rb_iseq_t *)iseq)); - rb_io_flush(rb_stdout); - dump &= ~DUMP_BIT(insns); - if (!dump) return Qtrue; + rb_io_write(rb_stdout, rb_iseq_disasm((const rb_iseq_t *)iseq)); + rb_io_flush(rb_stdout); + dump &= ~DUMP_BIT(insns); + if (!dump) return Qtrue; } if (opt->dump & dump_exit_bits) return Qtrue; @@ -2144,7 +2144,7 @@ static void warn_cr_in_shebang(const char *str, long len) { if (str[len-1] == '\n' && str[len-2] == '\r') { - rb_warn("shebang line ending with \\r may cause problems"); + rb_warn("shebang line ending with \\r may cause problems"); } } #else @@ -2177,115 +2177,115 @@ load_file_internal(VALUE argp_v) CONST_ID(set_encoding, "set_encoding"); if (script) { - VALUE c = 1; /* something not nil */ - VALUE line; - char *p, *str; - long len; - int no_src_enc = !opt->src.enc.name; - int no_ext_enc = !opt->ext.enc.name; - int no_int_enc = !opt->intern.enc.name; + VALUE c = 1; /* something not nil */ + VALUE line; + char *p, *str; + long len; + int no_src_enc = !opt->src.enc.name; + int no_ext_enc = !opt->ext.enc.name; + int no_int_enc = !opt->intern.enc.name; - enc = rb_ascii8bit_encoding(); - rb_funcall(f, set_encoding, 1, rb_enc_from_encoding(enc)); + enc = rb_ascii8bit_encoding(); + rb_funcall(f, set_encoding, 1, rb_enc_from_encoding(enc)); - if (opt->xflag) { - line_start--; - search_shebang: - while (!NIL_P(line = rb_io_gets(f))) { - line_start++; - RSTRING_GETMEM(line, str, len); - if (len > 2 && str[0] == '#' && str[1] == '!') { - if (line_start == 1) warn_cr_in_shebang(str, len); - if ((p = strstr(str+2, ruby_engine)) != 0) { - goto start_read; - } - } - } - rb_loaderror("no Ruby script found in input"); - } + if (opt->xflag) { + line_start--; + search_shebang: + while (!NIL_P(line = rb_io_gets(f))) { + line_start++; + RSTRING_GETMEM(line, str, len); + if (len > 2 && str[0] == '#' && str[1] == '!') { + if (line_start == 1) warn_cr_in_shebang(str, len); + if ((p = strstr(str+2, ruby_engine)) != 0) { + goto start_read; + } + } + } + rb_loaderror("no Ruby script found in input"); + } - c = rb_io_getbyte(f); - if (c == INT2FIX('#')) { - c = rb_io_getbyte(f); + c = rb_io_getbyte(f); + if (c == INT2FIX('#')) { + c = rb_io_getbyte(f); if (c == INT2FIX('!') && !NIL_P(line = rb_io_gets(f))) { - RSTRING_GETMEM(line, str, len); - warn_cr_in_shebang(str, len); - if ((p = strstr(str, ruby_engine)) == 0) { - /* not ruby script, assume -x flag */ - goto search_shebang; - } + RSTRING_GETMEM(line, str, len); + warn_cr_in_shebang(str, len); + if ((p = strstr(str, ruby_engine)) == 0) { + /* not ruby script, assume -x flag */ + goto search_shebang; + } - start_read: - str += len - 1; - if (*str == '\n') *str-- = '\0'; - if (*str == '\r') *str-- = '\0'; - /* ruby_engine should not contain a space */ - if ((p = strstr(p, " -")) != 0) { - opt->warning = 0; - moreswitches(p + 1, opt, 0); - } + start_read: + str += len - 1; + if (*str == '\n') *str-- = '\0'; + if (*str == '\r') *str-- = '\0'; + /* ruby_engine should not contain a space */ + if ((p = strstr(p, " -")) != 0) { + opt->warning = 0; + moreswitches(p + 1, opt, 0); + } - /* push back shebang for pragma may exist in next line */ - rb_io_ungetbyte(f, rb_str_new2("!\n")); - } - else if (!NIL_P(c)) { - rb_io_ungetbyte(f, c); - } - rb_io_ungetbyte(f, INT2FIX('#')); - if (no_src_enc && opt->src.enc.name) { - opt->src.enc.index = opt_enc_index(opt->src.enc.name); - src_encoding_index = opt->src.enc.index; - } - if (no_ext_enc && opt->ext.enc.name) { - opt->ext.enc.index = opt_enc_index(opt->ext.enc.name); - } - if (no_int_enc && opt->intern.enc.name) { - opt->intern.enc.index = opt_enc_index(opt->intern.enc.name); - } - } - else if (!NIL_P(c)) { - rb_io_ungetbyte(f, c); - } + /* push back shebang for pragma may exist in next line */ + rb_io_ungetbyte(f, rb_str_new2("!\n")); + } + else if (!NIL_P(c)) { + rb_io_ungetbyte(f, c); + } + rb_io_ungetbyte(f, INT2FIX('#')); + if (no_src_enc && opt->src.enc.name) { + opt->src.enc.index = opt_enc_index(opt->src.enc.name); + src_encoding_index = opt->src.enc.index; + } + if (no_ext_enc && opt->ext.enc.name) { + opt->ext.enc.index = opt_enc_index(opt->ext.enc.name); + } + if (no_int_enc && opt->intern.enc.name) { + opt->intern.enc.index = opt_enc_index(opt->intern.enc.name); + } + } + else if (!NIL_P(c)) { + rb_io_ungetbyte(f, c); + } if (NIL_P(c)) { - argp->f = f = Qnil; - } + argp->f = f = Qnil; + } rb_reset_argf_lineno(0); ruby_opt_init(opt); } if (opt->src.enc.index >= 0) { - enc = rb_enc_from_index(opt->src.enc.index); + enc = rb_enc_from_index(opt->src.enc.index); } else if (f == rb_stdin) { - enc = rb_locale_encoding(); + enc = rb_locale_encoding(); } else { - enc = rb_utf8_encoding(); + enc = rb_utf8_encoding(); } rb_parser_set_options(parser, opt->do_print, opt->do_loop, - opt->do_line, opt->do_split); + opt->do_line, opt->do_split); if (NIL_P(f)) { - f = rb_str_new(0, 0); - rb_enc_associate(f, enc); - return (VALUE)rb_parser_compile_string_path(parser, orig_fname, f, line_start); + f = rb_str_new(0, 0); + rb_enc_associate(f, enc); + return (VALUE)rb_parser_compile_string_path(parser, orig_fname, f, line_start); } rb_funcall(f, set_encoding, 2, rb_enc_from_encoding(enc), rb_str_new_cstr("-")); ast = rb_parser_compile_file_path(parser, orig_fname, f, line_start); rb_funcall(f, set_encoding, 1, rb_parser_encoding(parser)); if (script && rb_parser_end_seen_p(parser)) { - /* - * DATA is a File that contains the data section of the executed file. - * To create a data section use __END__: - * - * $ cat t.rb - * puts DATA.gets - * __END__ - * hello world! - * - * $ ruby t.rb - * hello world! - */ - rb_define_global_const("DATA", f); - argp->f = Qnil; + /* + * DATA is a File that contains the data section of the executed file. + * To create a data section use __END__: + * + * $ cat t.rb + * puts DATA.gets + * __END__ + * hello world! + * + * $ ruby t.rb + * hello world! + */ + rb_define_global_const("DATA", f); + argp->f = Qnil; } return (VALUE)ast; } @@ -2314,72 +2314,72 @@ static VALUE open_load_file(VALUE fname_v, int *xflag) { const char *fname = (fname_v = rb_str_encode_ospath(fname_v), - StringValueCStr(fname_v)); + StringValueCStr(fname_v)); long flen = RSTRING_LEN(fname_v); VALUE f; int e; if (flen == 1 && fname[0] == '-') { - f = rb_stdin; + f = rb_stdin; } else { - int fd; - /* open(2) may block if fname is point to FIFO and it's empty. Let's - use O_NONBLOCK. */ - const int MODE_TO_LOAD = O_RDONLY | ( + int fd; + /* open(2) may block if fname is point to FIFO and it's empty. Let's + use O_NONBLOCK. */ + const int MODE_TO_LOAD = O_RDONLY | ( #if defined O_NONBLOCK && HAVE_FCNTL - /* TODO: fix conflicting O_NONBLOCK in ruby/win32.h */ - !(O_NONBLOCK & O_ACCMODE) ? O_NONBLOCK : + /* TODO: fix conflicting O_NONBLOCK in ruby/win32.h */ + !(O_NONBLOCK & O_ACCMODE) ? O_NONBLOCK : #endif #if defined O_NDELAY && HAVE_FCNTL !(O_NDELAY & O_ACCMODE) ? O_NDELAY : #endif 0); - int mode = MODE_TO_LOAD; + int mode = MODE_TO_LOAD; #if defined DOSISH || defined __CYGWIN__ # define isdirsep(x) ((x) == '/' || (x) == '\\') - { - static const char exeext[] = ".exe"; - enum {extlen = sizeof(exeext)-1}; - if (flen > extlen && !isdirsep(fname[flen-extlen-1]) && - STRNCASECMP(fname+flen-extlen, exeext, extlen) == 0) { - mode |= O_BINARY; - *xflag = 1; - } - } + { + static const char exeext[] = ".exe"; + enum {extlen = sizeof(exeext)-1}; + if (flen > extlen && !isdirsep(fname[flen-extlen-1]) && + STRNCASECMP(fname+flen-extlen, exeext, extlen) == 0) { + mode |= O_BINARY; + *xflag = 1; + } + } #endif - if ((fd = rb_cloexec_open(fname, mode, 0)) < 0) { - e = errno; - if (!rb_gc_for_fd(e)) { - rb_load_fail(fname_v, strerror(e)); - } - if ((fd = rb_cloexec_open(fname, mode, 0)) < 0) { - rb_load_fail(fname_v, strerror(errno)); - } - } - rb_update_max_fd(fd); + if ((fd = rb_cloexec_open(fname, mode, 0)) < 0) { + e = errno; + if (!rb_gc_for_fd(e)) { + rb_load_fail(fname_v, strerror(e)); + } + if ((fd = rb_cloexec_open(fname, mode, 0)) < 0) { + rb_load_fail(fname_v, strerror(errno)); + } + } + rb_update_max_fd(fd); - if (MODE_TO_LOAD != O_RDONLY && (e = disable_nonblock(fd)) != 0) { - (void)close(fd); - rb_load_fail(fname_v, strerror(e)); - } + if (MODE_TO_LOAD != O_RDONLY && (e = disable_nonblock(fd)) != 0) { + (void)close(fd); + rb_load_fail(fname_v, strerror(e)); + } - e = ruby_is_fd_loadable(fd); - if (!e) { - e = errno; - (void)close(fd); - rb_load_fail(fname_v, strerror(e)); - } + e = ruby_is_fd_loadable(fd); + if (!e) { + e = errno; + (void)close(fd); + rb_load_fail(fname_v, strerror(e)); + } - f = rb_io_fdopen(fd, mode, fname); - if (e < 0) { - /* - We need to wait if FIFO is empty. It's FIFO's semantics. - rb_thread_wait_fd() release GVL. So, it's safe. - */ - rb_io_wait(f, RB_INT2NUM(RUBY_IO_READABLE), Qnil); - } + f = rb_io_fdopen(fd, mode, fname); + if (e < 0) { + /* + We need to wait if FIFO is empty. It's FIFO's semantics. + rb_thread_wait_fd() release GVL. So, it's safe. + */ + rb_io_wait(f, RB_INT2NUM(RUBY_IO_READABLE), Qnil); + } } return f; } @@ -2391,7 +2391,7 @@ restore_load_file(VALUE arg) VALUE f = argp->f; if (!NIL_P(f) && f != rb_stdin) { - rb_io_close(f); + rb_io_close(f); } return Qnil; } @@ -2406,7 +2406,7 @@ load_file(VALUE parser, VALUE fname, VALUE f, int script, ruby_cmdline_options_t arg.opt = opt; arg.f = f; return (rb_ast_t *)rb_ensure(load_file_internal, (VALUE)&arg, - restore_load_file, (VALUE)&arg); + restore_load_file, (VALUE)&arg); } void * @@ -2484,7 +2484,7 @@ static void set_arg0(VALUE val, ID id, VALUE *_) { if (origarg.argv == 0) - rb_raise(rb_eRuntimeError, "$0 not initialized"); + rb_raise(rb_eRuntimeError, "$0 not initialized"); rb_progname = rb_str_new_frozen(ruby_setproctitle(val)); } @@ -2505,8 +2505,8 @@ void ruby_script(const char *name) { if (name) { - rb_orig_progname = rb_progname = external_str_new_cstr(name); - rb_vm_set_progname(rb_progname); + rb_orig_progname = rb_progname = external_str_new_cstr(name); + rb_vm_set_progname(rb_progname); } } @@ -2562,13 +2562,13 @@ opt_W_getter(ID id, VALUE *dmy) switch (v) { case Qnil: - return INT2FIX(0); + return INT2FIX(0); case Qfalse: - return INT2FIX(1); + return INT2FIX(1); case Qtrue: - return INT2FIX(2); + return INT2FIX(2); default: - return Qnil; + return Qnil; } } @@ -2624,10 +2624,10 @@ ruby_set_argv(int argc, char **argv) rb_ary_clear(av); for (i = 0; i < argc; i++) { - VALUE arg = external_str_new_cstr(argv[i]); + VALUE arg = external_str_new_cstr(argv[i]); - OBJ_FREEZE(arg); - rb_ary_push(av, arg); + OBJ_FREEZE(arg); + rb_ary_push(av, arg); } } @@ -2639,8 +2639,8 @@ ruby_process_options(int argc, char **argv) const char *script_name = (argc > 0 && argv[0]) ? argv[0] : ruby_engine; if (!origarg.argv || origarg.argc <= 0) { - origarg.argc = argc; - origarg.argv = argv; + origarg.argc = argc; + origarg.argv = argv; } ruby_script(script_name); /* for the time being */ rb_argv0 = rb_str_new4(rb_progname); @@ -2691,8 +2691,8 @@ ruby_sysinit(int *argc, char ***argv) rb_w32_sysinit(argc, argv); #endif if (*argc >= 0 && *argv) { - origarg.argc = *argc; - origarg.argv = *argv; + origarg.argc = *argc; + origarg.argv = *argv; } fill_standard_fds(); } diff --git a/rubystub.c b/rubystub.c index 1b10cdd4c4..e7f46e78a5 100644 --- a/rubystub.c +++ b/rubystub.c @@ -23,23 +23,23 @@ stub_options(int argc, char **argv) * use argv[0] as is */ #elif defined __linux__ { - char selfexe[MAXPATHLEN]; - ssize_t len = readlink("/proc/self/exe", selfexe, sizeof(selfexe)); - if (len < 0) { - perror("readlink(\"/proc/self/exe\")"); - return NULL; - } - selfexe[len] = '\0'; - cmd = selfexe; + char selfexe[MAXPATHLEN]; + ssize_t len = readlink("/proc/self/exe", selfexe, sizeof(selfexe)); + if (len < 0) { + perror("readlink(\"/proc/self/exe\")"); + return NULL; + } + selfexe[len] = '\0'; + cmd = selfexe; } #elif defined HAVE_DLADDR { - Dl_info dli; - if (!dladdr(stub_options, &dli)) { - perror("dladdr"); - return NULL; - } - cmd = (char *)dli.dli_fname; + Dl_info dli; + if (!dladdr(stub_options, &dli)) { + perror("dladdr"); + return NULL; + } + cmd = (char *)dli.dli_fname; } #endif diff --git a/signal.c b/signal.c index 4ca52b2ee6..874afd28d5 100644 --- a/signal.c +++ b/signal.c @@ -56,11 +56,11 @@ ruby_atomic_exchange(rb_atomic_t *ptr, rb_atomic_t val) rb_atomic_t ruby_atomic_compare_and_swap(rb_atomic_t *ptr, rb_atomic_t cmp, - rb_atomic_t newval) + rb_atomic_t newval) { rb_atomic_t old = *ptr; if (old == cmp) { - *ptr = newval; + *ptr = newval; } return old; } @@ -214,34 +214,34 @@ signm2signo(VALUE *sig_ptr, int negative, int exit, int *prefix_ptr) int prefix = 0; if (RB_SYMBOL_P(vsig)) { - *sig_ptr = vsig = rb_sym2str(vsig); + *sig_ptr = vsig = rb_sym2str(vsig); } else if (!RB_TYPE_P(vsig, T_STRING)) { - VALUE str = rb_check_string_type(vsig); - if (NIL_P(str)) { - rb_raise(rb_eArgError, "bad signal type %s", - rb_obj_classname(vsig)); - } - *sig_ptr = vsig = str; + VALUE str = rb_check_string_type(vsig); + if (NIL_P(str)) { + rb_raise(rb_eArgError, "bad signal type %s", + rb_obj_classname(vsig)); + } + *sig_ptr = vsig = str; } rb_must_asciicompat(vsig); RSTRING_GETMEM(vsig, nm, len); if (memchr(nm, '\0', len)) { - rb_raise(rb_eArgError, "signal name with null byte"); + rb_raise(rb_eArgError, "signal name with null byte"); } if (len > 0 && nm[0] == '-') { - if (!negative) - rb_raise(rb_eArgError, "negative signal name: % "PRIsVALUE, vsig); - prefix = 1; + if (!negative) + rb_raise(rb_eArgError, "negative signal name: % "PRIsVALUE, vsig); + prefix = 1; } else { - negative = 0; + negative = 0; } if (len >= prefix + signame_prefix_len) { if (memcmp(nm + prefix, signame_prefix, signame_prefix_len) == 0) - prefix += signame_prefix_len; + prefix += signame_prefix_len; } if (len <= (long)prefix) { goto unsupported; @@ -252,10 +252,10 @@ signm2signo(VALUE *sig_ptr, int negative, int exit, int *prefix_ptr) nm += prefix; if (nmlen > LONGEST_SIGNAME) goto unsupported; FOREACH_SIGNAL(sigs, !exit) { - if (memcmp(sigs->signm, nm, nmlen) == 0 && - sigs->signm[nmlen] == '\0') { - return negative ? -sigs->signo : sigs->signo; - } + if (memcmp(sigs->signm, nm, nmlen) == 0 && + sigs->signm[nmlen] == '\0') { + return negative ? -sigs->signo : sigs->signo; + } } unsupported: @@ -284,8 +284,8 @@ signo2signm(int no) const struct signals *sigs; FOREACH_SIGNAL(sigs, 0) { - if (sigs->signo == no) - return sigs->signm; + if (sigs->signo == no) + return sigs->signm; } return 0; } @@ -323,10 +323,10 @@ rb_signo2signm(int signo) { const char *const signm = signo2signm(signo); if (signm) { - return rb_sprintf("SIG%s", signm); + return rb_sprintf("SIG%s", signm); } else { - return rb_sprintf("SIG%u", signo); + return rb_sprintf("SIG%u", signo); } } @@ -347,29 +347,29 @@ esignal_init(int argc, VALUE *argv, VALUE self) int signo; if (argc > 0) { - sig = rb_check_to_integer(argv[0], "to_int"); - if (!NIL_P(sig)) argnum = 2; - else sig = argv[0]; + sig = rb_check_to_integer(argv[0], "to_int"); + if (!NIL_P(sig)) argnum = 2; + else sig = argv[0]; } rb_check_arity(argc, 1, argnum); if (argnum == 2) { - signo = NUM2INT(sig); - if (signo < 0 || signo > NSIG) { - rb_raise(rb_eArgError, "invalid signal number (%d)", signo); - } - if (argc > 1) { - sig = argv[1]; - } - else { - sig = rb_signo2signm(signo); - } + signo = NUM2INT(sig); + if (signo < 0 || signo > NSIG) { + rb_raise(rb_eArgError, "invalid signal number (%d)", signo); + } + if (argc > 1) { + sig = argv[1]; + } + else { + sig = rb_signo2signm(signo); + } } else { - int prefix; - signo = signm2signo(&sig, FALSE, FALSE, &prefix); - if (prefix != signame_prefix_len) { - sig = rb_str_append(rb_str_new_cstr("SIG"), sig); - } + int prefix; + signo = signm2signo(&sig, FALSE, FALSE, &prefix); + if (prefix != signame_prefix_len) { + sig = rb_str_append(rb_str_new_cstr("SIG"), sig); + } } rb_call_super(1, &sig); rb_ivar_set(self, id_signo, INT2NUM(signo)); @@ -432,72 +432,72 @@ rb_f_kill(int argc, const VALUE *argv) rb_check_arity(argc, 2, UNLIMITED_ARGUMENTS); if (FIXNUM_P(argv[0])) { - sig = FIX2INT(argv[0]); + sig = FIX2INT(argv[0]); } else { - str = argv[0]; - sig = signm2signo(&str, TRUE, FALSE, NULL); + str = argv[0]; + sig = signm2signo(&str, TRUE, FALSE, NULL); } if (argc <= 1) return INT2FIX(0); if (sig < 0) { - sig = -sig; - for (i=1; iractor.main_thread) ? getpid() : -1; - int wakeup = 0; + const rb_pid_t self = (GET_THREAD() == GET_VM()->ractor.main_thread) ? getpid() : -1; + int wakeup = 0; - for (i=1; iractor.main_thread); - } + kill(pid, sig); + break; + default: + t = signal_ignored(sig); + if (t) { + if (t < 0 && kill(pid, sig)) + rb_sys_fail(0); + break; + } + signal_enque(sig); + wakeup = 1; + } + } + else if (kill(pid, sig) < 0) { + rb_sys_fail(0); + } + } + if (wakeup) { + rb_threadptr_check_signal(GET_VM()->ractor.main_thread); + } } rb_thread_execute_interrupts(rb_thread_current()); @@ -542,10 +542,10 @@ rb_sigaltstack_size(void) #endif #if defined(HAVE_SYSCONF) && defined(_SC_PAGE_SIZE) { - int pagesize; - pagesize = (int)sysconf(_SC_PAGE_SIZE); - if (size < pagesize) - size = pagesize; + int pagesize; + pagesize = (int)sysconf(_SC_PAGE_SIZE); + if (size < pagesize) + size = pagesize; } #endif @@ -559,7 +559,7 @@ rb_allocate_sigaltstack(void) { void *altstack; if (!rb_sigaltstack_size_value) { - rb_sigaltstack_size_value = rb_sigaltstack_size(); + rb_sigaltstack_size_value = rb_sigaltstack_size(); } altstack = malloc(rb_sigaltstack_size_value); if (!altstack) rb_memerror(); @@ -610,42 +610,42 @@ ruby_signal(int signum, sighandler_t handler) switch (signum) { #if RUBY_SIGCHLD case RUBY_SIGCHLD: - if (handler == SIG_IGN) { - ruby_nocldwait = 1; + if (handler == SIG_IGN) { + ruby_nocldwait = 1; # ifdef USE_SIGALTSTACK - if (sigact.sa_flags & SA_SIGINFO) { - sigact.sa_sigaction = (ruby_sigaction_t*)sighandler; - } - else { - sigact.sa_handler = sighandler; - } + if (sigact.sa_flags & SA_SIGINFO) { + sigact.sa_sigaction = (ruby_sigaction_t*)sighandler; + } + else { + sigact.sa_handler = sighandler; + } # else - sigact.sa_handler = handler; - sigact.sa_flags = 0; + sigact.sa_handler = handler; + sigact.sa_flags = 0; # endif - } - else { - ruby_nocldwait = 0; - } - break; + } + else { + ruby_nocldwait = 0; + } + break; #endif #if defined(SA_ONSTACK) && defined(USE_SIGALTSTACK) case SIGSEGV: #ifdef SIGBUS case SIGBUS: #endif - sigact.sa_flags |= SA_ONSTACK; - break; + sigact.sa_flags |= SA_ONSTACK; + break; #endif } (void)VALGRIND_MAKE_MEM_DEFINED(&old, sizeof(old)); if (sigaction(signum, &sigact, &old) < 0) { - return SIG_ERR; + return SIG_ERR; } if (old.sa_flags & SA_SIGINFO) - handler = (sighandler_t)old.sa_sigaction; + handler = (sighandler_t)old.sa_sigaction; else - handler = old.sa_handler; + handler = old.sa_handler; ASSUME(handler != SIG_ERR); return handler; } @@ -661,8 +661,8 @@ static inline sighandler_t ruby_signal(int signum, sighandler_t handler) { if (signum == SIGKILL) { - errno = EINVAL; - return SIG_ERR; + errno = EINVAL; + return SIG_ERR; } return signal(signum, handler); } @@ -775,14 +775,14 @@ rb_get_next_signal(void) int i, sig = 0; if (signal_buff.size != 0) { - for (i=1; i 0) { - ATOMIC_DEC(signal_buff.cnt[i]); - ATOMIC_DEC(signal_buff.size); - sig = i; - break; - } - } + for (i=1; i 0) { + ATOMIC_DEC(signal_buff.cnt[i]); + ATOMIC_DEC(signal_buff.size); + sig = i; + break; + } + } } return sig; } @@ -822,7 +822,7 @@ reset_sigmask(int sig) sigemptyset(&mask); sigaddset(&mask, sig); if (ruby_sigunmask(SIG_UNBLOCK, &mask, NULL)) { - rb_bug_errno(STRINGIZE(ruby_sigunmask)":unblock", errno); + rb_bug_errno(STRINGIZE(ruby_sigunmask)":unblock", errno); } #endif } @@ -879,18 +879,18 @@ check_stack_overflow(int sig, const uintptr_t addr, const ucontext_t *ctx) * the fault page can be the next. */ if (sp_page == fault_page || sp_page == fault_page + 1 || (sp_page <= fault_page && fault_page <= bp_page)) { - rb_execution_context_t *ec = GET_EC(); - int crit = FALSE; - int uplevel = roomof(pagesize, sizeof(*ec->tag)) / 2; /* XXX: heuristic */ - while ((uintptr_t)ec->tag->buf / pagesize <= fault_page + 1) { - /* drop the last tag if it is close to the fault, - * otherwise it can cause stack overflow again at the same - * place. */ - if ((crit = (!ec->tag->prev || !--uplevel)) != FALSE) break; - ec->tag = ec->tag->prev; - } - reset_sigmask(sig); - rb_ec_stack_overflow(ec, crit); + rb_execution_context_t *ec = GET_EC(); + int crit = FALSE; + int uplevel = roomof(pagesize, sizeof(*ec->tag)) / 2; /* XXX: heuristic */ + while ((uintptr_t)ec->tag->buf / pagesize <= fault_page + 1) { + /* drop the last tag if it is close to the fault, + * otherwise it can cause stack overflow again at the same + * place. */ + if ((crit = (!ec->tag->prev || !--uplevel)) != FALSE) break; + ec->tag = ec->tag->prev; + } + reset_sigmask(sig); + rb_ec_stack_overflow(ec, crit); } } # else @@ -900,8 +900,8 @@ check_stack_overflow(int sig, const void *addr) int ruby_stack_overflowed_p(const rb_thread_t *, const void *); rb_thread_t *th = GET_THREAD(); if (ruby_stack_overflowed_p(th, addr)) { - reset_sigmask(sig); - rb_ec_stack_overflow(th->ec, FALSE); + reset_sigmask(sig); + rb_ec_stack_overflow(th->ec, FALSE); } } # endif @@ -1004,30 +1004,30 @@ check_reserved_signal_(const char *name, size_t name_len) const char *prev = ATOMIC_PTR_EXCHANGE(received_signal, name); if (prev) { - ssize_t RB_UNUSED_VAR(err); + ssize_t RB_UNUSED_VAR(err); #define NOZ(name, str) name[sizeof(str)-1] = str - static const char NOZ(msg1, " received in "); - static const char NOZ(msg2, " handler\n"); + static const char NOZ(msg1, " received in "); + static const char NOZ(msg2, " handler\n"); #ifdef HAVE_WRITEV - struct iovec iov[4]; + struct iovec iov[4]; - iov[0].iov_base = (void *)name; - iov[0].iov_len = name_len; - iov[1].iov_base = (void *)msg1; - iov[1].iov_len = sizeof(msg1); - iov[2].iov_base = (void *)prev; - iov[2].iov_len = strlen(prev); - iov[3].iov_base = (void *)msg2; - iov[3].iov_len = sizeof(msg2); - err = writev(2, iov, 4); + iov[0].iov_base = (void *)name; + iov[0].iov_len = name_len; + iov[1].iov_base = (void *)msg1; + iov[1].iov_len = sizeof(msg1); + iov[2].iov_base = (void *)prev; + iov[2].iov_len = strlen(prev); + iov[3].iov_base = (void *)msg2; + iov[3].iov_len = sizeof(msg2); + err = writev(2, iov, 4); #else - err = write(2, name, name_len); - err = write(2, msg1, sizeof(msg1)); - err = write(2, prev, strlen(prev)); - err = write(2, msg2, sizeof(msg2)); + err = write(2, name, name_len); + err = write(2, msg1, sizeof(msg1)); + err = write(2, prev, strlen(prev)); + err = write(2, msg2, sizeof(msg2)); #endif - ruby_abort(); + ruby_abort(); } ruby_disable_gc = 1; @@ -1055,12 +1055,12 @@ signal_exec(VALUE cmd, int sig) * 3. rb_signal_exec runs on queued signal */ if (IMMEDIATE_P(cmd)) - return FALSE; + return FALSE; ec->interrupt_mask |= TRAP_INTERRUPT_MASK; EC_PUSH_TAG(ec); if ((state = EC_EXEC_TAG()) == TAG_NONE) { - VALUE signum = INT2NUM(sig); + VALUE signum = INT2NUM(sig); rb_eval_cmd_kw(cmd, rb_ary_new3(1, signum), RB_NO_KEYWORDS); } EC_POP_TAG(); @@ -1068,8 +1068,8 @@ signal_exec(VALUE cmd, int sig) ec->interrupt_mask = old_interrupt_mask; if (state) { - /* XXX: should be replaced with rb_threadptr_pending_interrupt_enque() */ - EC_JUMP_TAG(ec, state); + /* XXX: should be replaced with rb_threadptr_pending_interrupt_enque() */ + EC_JUMP_TAG(ec, state); } return TRUE; } @@ -1080,7 +1080,7 @@ rb_vm_trap_exit(rb_vm_t *vm) VALUE trap_exit = vm->trap_list.cmd[0]; if (trap_exit) { - vm->trap_list.cmd[0] = 0; + vm->trap_list.cmd[0] = 0; signal_exec(trap_exit, 0); } } @@ -1103,34 +1103,34 @@ rb_signal_exec(rb_thread_t *th, int sig) VALUE cmd = vm->trap_list.cmd[sig]; if (cmd == 0) { - switch (sig) { - case SIGINT: - rb_interrupt(); - break; + switch (sig) { + case SIGINT: + rb_interrupt(); + break; #ifdef SIGHUP - case SIGHUP: + case SIGHUP: #endif #ifdef SIGQUIT - case SIGQUIT: + case SIGQUIT: #endif #ifdef SIGTERM - case SIGTERM: + case SIGTERM: #endif #ifdef SIGALRM - case SIGALRM: + case SIGALRM: #endif #ifdef SIGUSR1 - case SIGUSR1: + case SIGUSR1: #endif #ifdef SIGUSR2 - case SIGUSR2: + case SIGUSR2: #endif - rb_threadptr_signal_raise(th, sig); - break; - } + rb_threadptr_signal_raise(th, sig); + break; + } } else if (cmd == Qundef) { - rb_threadptr_signal_exit(th); + rb_threadptr_signal_exit(th); } else { return signal_exec(cmd, sig); @@ -1202,21 +1202,21 @@ trap_handler(VALUE *cmd, int sig) VALUE command; if (NIL_P(*cmd)) { - func = SIG_IGN; + func = SIG_IGN; } else { - command = rb_check_string_type(*cmd); - if (NIL_P(command) && SYMBOL_P(*cmd)) { - command = rb_sym2str(*cmd); - if (!command) rb_raise(rb_eArgError, "bad handler"); - } - if (!NIL_P(command)) { - const char *cptr; - long len; + command = rb_check_string_type(*cmd); + if (NIL_P(command) && SYMBOL_P(*cmd)) { + command = rb_sym2str(*cmd); + if (!command) rb_raise(rb_eArgError, "bad handler"); + } + if (!NIL_P(command)) { + const char *cptr; + long len; StringValue(command); - *cmd = command; - RSTRING_GETMEM(command, cptr, len); - switch (len) { + *cmd = command; + RSTRING_GETMEM(command, cptr, len); + switch (len) { sig_ign: func = SIG_IGN; *cmd = Qtrue; @@ -1225,46 +1225,46 @@ trap_handler(VALUE *cmd, int sig) func = default_handler(sig); *cmd = 0; break; - case 0: + case 0: goto sig_ign; - break; + break; case 14: - if (memcmp(cptr, "SYSTEM_DEFAULT", 14) == 0) { + if (memcmp(cptr, "SYSTEM_DEFAULT", 14) == 0) { if (sig == RUBY_SIGCHLD) { goto sig_dfl; } func = SIG_DFL; *cmd = 0; - } + } break; - case 7: - if (memcmp(cptr, "SIG_IGN", 7) == 0) { + case 7: + if (memcmp(cptr, "SIG_IGN", 7) == 0) { goto sig_ign; - } - else if (memcmp(cptr, "SIG_DFL", 7) == 0) { + } + else if (memcmp(cptr, "SIG_DFL", 7) == 0) { goto sig_dfl; - } - else if (memcmp(cptr, "DEFAULT", 7) == 0) { + } + else if (memcmp(cptr, "DEFAULT", 7) == 0) { goto sig_dfl; - } - break; - case 6: - if (memcmp(cptr, "IGNORE", 6) == 0) { + } + break; + case 6: + if (memcmp(cptr, "IGNORE", 6) == 0) { goto sig_ign; - } - break; - case 4: - if (memcmp(cptr, "EXIT", 4) == 0) { - *cmd = Qundef; - } - break; - } - } - else { - rb_proc_t *proc; - GetProcPtr(*cmd, proc); - (void)proc; - } + } + break; + case 4: + if (memcmp(cptr, "EXIT", 4) == 0) { + *cmd = Qundef; + } + break; + } + } + else { + rb_proc_t *proc; + GetProcPtr(*cmd, proc); + (void)proc; + } } return func; @@ -1276,13 +1276,13 @@ trap_signm(VALUE vsig) int sig = -1; if (FIXNUM_P(vsig)) { - sig = FIX2INT(vsig); - if (sig < 0 || sig >= NSIG) { - rb_raise(rb_eArgError, "invalid signal number (%d)", sig); - } + sig = FIX2INT(vsig); + if (sig < 0 || sig >= NSIG) { + rb_raise(rb_eArgError, "invalid signal number (%d)", sig); + } } else { - sig = signm2signo(&vsig, FALSE, TRUE, NULL); + sig = signm2signo(&vsig, FALSE, TRUE, NULL); } return sig; } @@ -1300,26 +1300,26 @@ trap(int sig, sighandler_t func, VALUE command) * RUBY_VM_CHECK_INTS(). */ if (sig == 0) { - oldfunc = SIG_ERR; + oldfunc = SIG_ERR; } else { - oldfunc = ruby_signal(sig, func); - if (oldfunc == SIG_ERR) rb_sys_fail_str(rb_signo2signm(sig)); + oldfunc = ruby_signal(sig, func); + if (oldfunc == SIG_ERR) rb_sys_fail_str(rb_signo2signm(sig)); } oldcmd = vm->trap_list.cmd[sig]; switch (oldcmd) { case 0: case Qtrue: - if (oldfunc == SIG_IGN) oldcmd = rb_str_new2("IGNORE"); + if (oldfunc == SIG_IGN) oldcmd = rb_str_new2("IGNORE"); else if (oldfunc == SIG_DFL) oldcmd = rb_str_new2("SYSTEM_DEFAULT"); - else if (oldfunc == sighandler) oldcmd = rb_str_new2("DEFAULT"); - else oldcmd = Qnil; - break; + else if (oldfunc == sighandler) oldcmd = rb_str_new2("DEFAULT"); + else oldcmd = Qnil; + break; case Qnil: - break; + break; case Qundef: - oldcmd = rb_str_new2("EXIT"); - break; + oldcmd = rb_str_new2("EXIT"); + break; } ACCESS_ONCE(VALUE, vm->trap_list.cmd[sig]) = command; @@ -1333,25 +1333,25 @@ reserved_signal_p(int signo) /* Synchronous signal can't deliver to main thread */ #ifdef SIGSEGV if (signo == SIGSEGV) - return 1; + return 1; #endif #ifdef SIGBUS if (signo == SIGBUS) - return 1; + return 1; #endif #ifdef SIGILL if (signo == SIGILL) - return 1; + return 1; #endif #ifdef SIGFPE if (signo == SIGFPE) - return 1; + return 1; #endif /* used ubf internal see thread_pthread.c. */ #ifdef SIGVTALRM if (signo == SIGVTALRM) - return 1; + return 1; #endif return 0; @@ -1407,12 +1407,12 @@ sig_trap(int argc, VALUE *argv, VALUE _) } if (argc == 1) { - cmd = rb_block_proc(); - func = sighandler; + cmd = rb_block_proc(); + func = sighandler; } else { - cmd = argv[1]; - func = trap_handler(&cmd, sig); + cmd = argv[1]; + func = trap_handler(&cmd, sig); } if (rb_obj_is_proc(cmd) && @@ -1439,16 +1439,16 @@ sig_list(VALUE _) const struct signals *sigs; FOREACH_SIGNAL(sigs, 0) { - rb_hash_aset(h, rb_fstring_cstr(sigs->signm), INT2FIX(sigs->signo)); + rb_hash_aset(h, rb_fstring_cstr(sigs->signm), INT2FIX(sigs->signo)); } return h; } #define INSTALL_SIGHANDLER(cond, signame, signum) do { \ - static const char failed[] = "failed to install "signame" handler"; \ - if (!(cond)) break; \ - if (reserved_signal_p(signum)) rb_bug(failed); \ - perror(failed); \ + static const char failed[] = "failed to install "signame" handler"; \ + if (!(cond)) break; \ + if (reserved_signal_p(signum)) rb_bug(failed); \ + perror(failed); \ } while (0) static int install_sighandler_core(int signum, sighandler_t handler, sighandler_t *old_handler) @@ -1500,7 +1500,7 @@ ruby_sig_finalize(void) oldfunc = ruby_signal(SIGINT, SIG_IGN); if (oldfunc == sighandler) { - ruby_signal(SIGINT, SIG_DFL); + ruby_signal(SIGINT, SIG_DFL); } } @@ -1584,14 +1584,14 @@ Init_signal(void) if (!ruby_enable_coredump) { #ifdef SIGBUS - force_install_sighandler(SIGBUS, (sighandler_t)sigbus, &default_sigbus_handler); + force_install_sighandler(SIGBUS, (sighandler_t)sigbus, &default_sigbus_handler); #endif #ifdef SIGILL - force_install_sighandler(SIGILL, (sighandler_t)sigill, &default_sigill_handler); + force_install_sighandler(SIGILL, (sighandler_t)sigill, &default_sigill_handler); #endif #ifdef SIGSEGV - RB_ALTSTACK_INIT(GET_VM()->main_altstack, rb_allocate_sigaltstack()); - force_install_sighandler(SIGSEGV, (sighandler_t)sigsegv, &default_sigsegv_handler); + RB_ALTSTACK_INIT(GET_VM()->main_altstack, rb_allocate_sigaltstack()); + force_install_sighandler(SIGSEGV, (sighandler_t)sigsegv, &default_sigsegv_handler); #endif } #ifdef SIGPIPE diff --git a/siphash.c b/siphash.c index 091376747f..294e75eaec 100644 --- a/siphash.c +++ b/siphash.c @@ -96,7 +96,7 @@ u64to8_le(uint8_t *p, uint64_t v) } #define ROTL64_TO(v, s) ((s) > 32 ? rotl64_swap(rotl64_to(&(v), (s) - 32)) : \ - (s) == 32 ? rotl64_swap(&(v)) : rotl64_to(&(v), (s))) + (s) == 32 ? rotl64_swap(&(v)) : rotl64_to(&(v), (s))) static inline uint64_t * rotl64_to(uint64_t *v, unsigned int s) { @@ -188,9 +188,9 @@ int_sip_dump(sip_state *state) for (v = 0; v < 4; v++) { #ifdef HAVE_UINT64_T - printf("v%d: %" PRIx64 "\n", v, state->v[v]); + printf("v%d: %" PRIx64 "\n", v, state->v[v]); #else - printf("v%d: %" PRIx32 "%.8" PRIx32 "\n", v, state->v[v].hi, state->v[v].lo); + printf("v%d: %" PRIx32 "%.8" PRIx32 "\n", v, state->v[v].hi, state->v[v].lo); #endif } } @@ -215,7 +215,7 @@ int_sip_round(sip_state *state, int n) int i; for (i = 0; i < n; i++) { - SIP_COMPRESS(state->v[0], state->v[1], state->v[2], state->v[3]); + SIP_COMPRESS(state->v[0], state->v[1], state->v[2], state->v[3]); } } @@ -249,8 +249,8 @@ int_sip_post_update(sip_state *state, const uint8_t *data, size_t len) { uint8_t r = len % sizeof(uint64_t); if (r) { - memcpy(state->buf, data + len - r, r); - state->buflen = r; + memcpy(state->buf, data + len - r, r); + state->buflen = r; } } @@ -269,16 +269,16 @@ int_sip_update(sip_state *state, const uint8_t *data, size_t len) #if BYTE_ORDER == LITTLE_ENDIAN while (data64 != end) { - int_sip_update_block(state, *data64++); + int_sip_update_block(state, *data64++); } #elif BYTE_ORDER == BIG_ENDIAN { - uint64_t m; - uint8_t *data8 = data; - for (; data8 != (uint8_t *) end; data8 += sizeof(uint64_t)) { - m = U8TO64_LE(data8); - int_sip_update_block(state, m); - } + uint64_t m; + uint8_t *data8 = data; + for (; data8 != (uint8_t *) end; data8 += sizeof(uint64_t)) { + m = U8TO64_LE(data8); + int_sip_update_block(state, m); + } } #endif @@ -291,7 +291,7 @@ int_sip_pad_final_block(sip_state *state) int i; /* pad with 0's and finalize with msg_len mod 256 */ for (i = state->buflen; i < sizeof(uint64_t); i++) { - state->buf[i] = 0x00; + state->buf[i] = 0x00; } state->buf[sizeof(uint64_t) - 1] = state->msglen_byte; } @@ -420,14 +420,14 @@ sip_hash13(const uint8_t key[16], const uint8_t *data, size_t len) { uint64_t *data64 = (uint64_t *)data; while (data64 != (uint64_t *) end) { - m = *data64++; - SIP_ROUND(m, v0, v1, v2, v3); + m = *data64++; + SIP_ROUND(m, v0, v1, v2, v3); } } #else for (; data != end; data += sizeof(uint64_t)) { - m = U8TO64_LE(data); - SIP_ROUND(m, v0, v1, v2, v3); + m = U8TO64_LE(data); + SIP_ROUND(m, v0, v1, v2, v3); } #endif @@ -438,40 +438,40 @@ sip_hash13(const uint8_t key[16], const uint8_t *data, size_t len) last.hi = len << 24; last.lo = 0; #define OR_BYTE(n) do { \ - if (n >= 4) \ - last.hi |= ((uint32_t) end[n]) << ((n) >= 4 ? (n) * 8 - 32 : 0); \ - else \ - last.lo |= ((uint32_t) end[n]) << ((n) >= 4 ? 0 : (n) * 8); \ + if (n >= 4) \ + last.hi |= ((uint32_t) end[n]) << ((n) >= 4 ? (n) * 8 - 32 : 0); \ + else \ + last.lo |= ((uint32_t) end[n]) << ((n) >= 4 ? 0 : (n) * 8); \ } while (0) #endif switch (len % sizeof(uint64_t)) { - case 7: - OR_BYTE(6); - case 6: - OR_BYTE(5); - case 5: - OR_BYTE(4); - case 4: + case 7: + OR_BYTE(6); + case 6: + OR_BYTE(5); + case 5: + OR_BYTE(4); + case 4: #if BYTE_ORDER == LITTLE_ENDIAN && UNALIGNED_WORD_ACCESS #ifdef HAVE_UINT64_T - last |= (uint64_t) ((uint32_t *) end)[0]; + last |= (uint64_t) ((uint32_t *) end)[0]; #else - last.lo |= ((uint32_t *) end)[0]; + last.lo |= ((uint32_t *) end)[0]; #endif - break; + break; #else - OR_BYTE(3); + OR_BYTE(3); #endif - case 3: - OR_BYTE(2); - case 2: - OR_BYTE(1); - case 1: - OR_BYTE(0); - break; - case 0: - break; + case 3: + OR_BYTE(2); + case 2: + OR_BYTE(1); + case 1: + OR_BYTE(0); + break; + case 0: + break; } SIP_ROUND(last, v0, v1, v2, v3); diff --git a/sprintf.c b/sprintf.c index f4aa7f6d1d..09b9bf15d2 100644 --- a/sprintf.c +++ b/sprintf.c @@ -44,13 +44,13 @@ sign_bits(int base, const char *p) switch (base) { case 16: - if (*p == 'X') c = 'F'; - else c = 'f'; - break; + if (*p == 'X') c = 'F'; + else c = 'f'; + break; case 8: - c = '7'; break; + c = '7'; break; case 2: - c = '1'; break; + c = '1'; break; } return c; } @@ -68,8 +68,8 @@ sign_bits(int base, const char *p) #define CHECK(l) do {\ int cr = ENC_CODERANGE(result);\ while ((l) >= bsiz - blen) {\ - bsiz*=2;\ - if (bsiz<0) rb_raise(rb_eArgError, "too big specifier");\ + bsiz*=2;\ + if (bsiz<0) rb_raise(rb_eArgError, "too big specifier");\ }\ rb_str_resize(result, bsiz);\ ENC_CODERANGE_SET(result, cr);\ @@ -98,7 +98,7 @@ sign_bits(int base, const char *p) } while (0) #define GETARG() (nextvalue != Qundef ? nextvalue : \ - GETNEXTARG()) + GETNEXTARG()) #define GETNEXTARG() ( \ check_next_arg(posarg, nextarg), \ @@ -124,11 +124,11 @@ sign_bits(int base, const char *p) n = 0; \ GETNUM(n, val); \ if (*p == '$') { \ - tmp = GETPOSARG(n); \ + tmp = GETPOSARG(n); \ } \ else { \ - tmp = GETNEXTARG(); \ - p = t; \ + tmp = GETNEXTARG(); \ + p = t; \ } \ (val) = NUM2INT(tmp); \ } while (0) @@ -138,15 +138,15 @@ get_num(const char *p, const char *end, rb_encoding *enc, int *valp) { int next_n = *valp; for (; p < end && rb_enc_isdigit(*p, enc); p++) { - if (MUL_OVERFLOW_INT_P(10, next_n)) - return NULL; - next_n *= 10; - if (INT_MAX - (*p - '0') < next_n) - return NULL; - next_n += *p - '0'; + if (MUL_OVERFLOW_INT_P(10, next_n)) + return NULL; + next_n *= 10; + if (INT_MAX - (*p - '0') < next_n) + return NULL; + next_n += *p - '0'; } if (p >= end) { - rb_raise(rb_eArgError, "malformed format string - %%*[0-9]"); + rb_raise(rb_eArgError, "malformed format string - %%*[0-9]"); } *valp = next_n; return p; @@ -157,9 +157,9 @@ check_next_arg(int posarg, int nextarg) { switch (posarg) { case -1: - rb_raise(rb_eArgError, "unnumbered(%d) mixed with numbered", nextarg); + rb_raise(rb_eArgError, "unnumbered(%d) mixed with numbered", nextarg); case -2: - rb_raise(rb_eArgError, "unnumbered(%d) mixed with named", nextarg); + rb_raise(rb_eArgError, "unnumbered(%d) mixed with named", nextarg); } } @@ -167,13 +167,13 @@ static void check_pos_arg(int posarg, int n) { if (posarg > 0) { - rb_raise(rb_eArgError, "numbered(%d) after unnumbered(%d)", n, posarg); + rb_raise(rb_eArgError, "numbered(%d) after unnumbered(%d)", n, posarg); } if (posarg == -2) { - rb_raise(rb_eArgError, "numbered(%d) after named", n); + rb_raise(rb_eArgError, "numbered(%d) after named", n); } if (n < 1) { - rb_raise(rb_eArgError, "invalid index - %d$", n); + rb_raise(rb_eArgError, "invalid index - %d$", n); } } @@ -181,10 +181,10 @@ static void check_name_arg(int posarg, const char *name, int len, rb_encoding *enc) { if (posarg > 0) { - rb_enc_raise(enc, rb_eArgError, "named%.*s after unnumbered(%d)", len, name, posarg); + rb_enc_raise(enc, rb_eArgError, "named%.*s after unnumbered(%d)", len, name, posarg); } if (posarg == -1) { - rb_enc_raise(enc, rb_eArgError, "named%.*s after numbered", len, name); + rb_enc_raise(enc, rb_eArgError, "named%.*s after numbered", len, name); } } @@ -195,11 +195,11 @@ get_hash(volatile VALUE *hash, int argc, const VALUE *argv) if (*hash != Qundef) return *hash; if (argc != 2) { - rb_raise(rb_eArgError, "one hash required"); + rb_raise(rb_eArgError, "one hash required"); } tmp = rb_check_hash_type(argv[1]); if (NIL_P(tmp)) { - rb_raise(rb_eArgError, "one hash required"); + rb_raise(rb_eArgError, "one hash required"); } return (*hash = tmp); } @@ -233,17 +233,17 @@ rb_str_format(int argc, const VALUE *argv, VALUE fmt) #define CHECK_FOR_WIDTH(f) \ if ((f) & FWIDTH) { \ - rb_raise(rb_eArgError, "width given twice"); \ + rb_raise(rb_eArgError, "width given twice"); \ } \ if ((f) & FPREC0) { \ - rb_raise(rb_eArgError, "width after precision"); \ + rb_raise(rb_eArgError, "width after precision"); \ } #define CHECK_FOR_FLAGS(f) \ if ((f) & FWIDTH) { \ - rb_raise(rb_eArgError, "flag after width"); \ + rb_raise(rb_eArgError, "flag after width"); \ } \ if ((f) & FPREC0) { \ - rb_raise(rb_eArgError, "flag after precision"); \ + rb_raise(rb_eArgError, "flag after precision"); \ } ++argc; @@ -263,362 +263,362 @@ rb_str_format(int argc, const VALUE *argv, VALUE fmt) ENC_CODERANGE_SET(result, coderange); for (; p < end; p++) { - const char *t; - int n; - VALUE sym = Qnil; + const char *t; + int n; + VALUE sym = Qnil; - for (t = p; t < end && *t != '%'; t++) ; - if (t + 1 == end) { - rb_raise(rb_eArgError, "incomplete format specifier; use %%%% (double %%) instead"); - } - PUSH(p, t - p); - if (coderange != ENC_CODERANGE_BROKEN && scanned < blen) { - scanned += rb_str_coderange_scan_restartable(buf+scanned, buf+blen, enc, &coderange); - ENC_CODERANGE_SET(result, coderange); - } - if (t >= end) { - /* end of fmt string */ - goto sprint_exit; - } - p = t + 1; /* skip `%' */ + for (t = p; t < end && *t != '%'; t++) ; + if (t + 1 == end) { + rb_raise(rb_eArgError, "incomplete format specifier; use %%%% (double %%) instead"); + } + PUSH(p, t - p); + if (coderange != ENC_CODERANGE_BROKEN && scanned < blen) { + scanned += rb_str_coderange_scan_restartable(buf+scanned, buf+blen, enc, &coderange); + ENC_CODERANGE_SET(result, coderange); + } + if (t >= end) { + /* end of fmt string */ + goto sprint_exit; + } + p = t + 1; /* skip `%' */ - width = prec = -1; - nextvalue = Qundef; + width = prec = -1; + nextvalue = Qundef; retry: - switch (*p) { - default: - if (rb_enc_isprint(*p, enc)) - rb_raise(rb_eArgError, "malformed format string - %%%c", *p); - else - rb_raise(rb_eArgError, "malformed format string"); - break; + switch (*p) { + default: + if (rb_enc_isprint(*p, enc)) + rb_raise(rb_eArgError, "malformed format string - %%%c", *p); + else + rb_raise(rb_eArgError, "malformed format string"); + break; - case ' ': - CHECK_FOR_FLAGS(flags); - flags |= FSPACE; - p++; - goto retry; + case ' ': + CHECK_FOR_FLAGS(flags); + flags |= FSPACE; + p++; + goto retry; - case '#': - CHECK_FOR_FLAGS(flags); - flags |= FSHARP; - p++; - goto retry; + case '#': + CHECK_FOR_FLAGS(flags); + flags |= FSHARP; + p++; + goto retry; - case '+': - CHECK_FOR_FLAGS(flags); - flags |= FPLUS; - p++; - goto retry; + case '+': + CHECK_FOR_FLAGS(flags); + flags |= FPLUS; + p++; + goto retry; - case '-': - CHECK_FOR_FLAGS(flags); - flags |= FMINUS; - p++; - goto retry; + case '-': + CHECK_FOR_FLAGS(flags); + flags |= FMINUS; + p++; + goto retry; - case '0': - CHECK_FOR_FLAGS(flags); - flags |= FZERO; - p++; - goto retry; + case '0': + CHECK_FOR_FLAGS(flags); + flags |= FZERO; + p++; + goto retry; - case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': - n = 0; - GETNUM(n, width); - if (*p == '$') { - if (nextvalue != Qundef) { - rb_raise(rb_eArgError, "value given twice - %d$", n); - } - nextvalue = GETPOSARG(n); - p++; - goto retry; - } - CHECK_FOR_WIDTH(flags); - width = n; - flags |= FWIDTH; - goto retry; + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + n = 0; + GETNUM(n, width); + if (*p == '$') { + if (nextvalue != Qundef) { + rb_raise(rb_eArgError, "value given twice - %d$", n); + } + nextvalue = GETPOSARG(n); + p++; + goto retry; + } + CHECK_FOR_WIDTH(flags); + width = n; + flags |= FWIDTH; + goto retry; - case '<': - case '{': - { - const char *start = p; - char term = (*p == '<') ? '>' : '}'; - int len; + case '<': + case '{': + { + const char *start = p; + char term = (*p == '<') ? '>' : '}'; + int len; - for (; p < end && *p != term; ) { - p += rb_enc_mbclen(p, end, enc); - } - if (p >= end) { - rb_raise(rb_eArgError, "malformed name - unmatched parenthesis"); - } + for (; p < end && *p != term; ) { + p += rb_enc_mbclen(p, end, enc); + } + if (p >= end) { + rb_raise(rb_eArgError, "malformed name - unmatched parenthesis"); + } #if SIZEOF_INT < SIZEOF_SIZE_T - if ((size_t)(p - start) >= INT_MAX) { - const int message_limit = 20; - len = (int)(rb_enc_right_char_head(start, start + message_limit, p, enc) - start); - rb_enc_raise(enc, rb_eArgError, - "too long name (%"PRIuSIZE" bytes) - %.*s...%c", - (size_t)(p - start - 2), len, start, term); - } + if ((size_t)(p - start) >= INT_MAX) { + const int message_limit = 20; + len = (int)(rb_enc_right_char_head(start, start + message_limit, p, enc) - start); + rb_enc_raise(enc, rb_eArgError, + "too long name (%"PRIuSIZE" bytes) - %.*s...%c", + (size_t)(p - start - 2), len, start, term); + } #endif - len = (int)(p - start + 1); /* including parenthesis */ - if (sym != Qnil) { - rb_enc_raise(enc, rb_eArgError, "named%.*s after <%"PRIsVALUE">", - len, start, rb_sym2str(sym)); - } - CHECKNAMEARG(start, len, enc); - get_hash(&hash, argc, argv); - sym = rb_check_symbol_cstr(start + 1, - len - 2 /* without parenthesis */, - enc); - if (!NIL_P(sym)) nextvalue = rb_hash_lookup2(hash, sym, Qundef); - if (nextvalue == Qundef) { - if (NIL_P(sym)) { - sym = rb_sym_intern(start + 1, - len - 2 /* without parenthesis */, - enc); - } - nextvalue = rb_hash_default_value(hash, sym); - if (NIL_P(nextvalue)) { - rb_key_err_raise(rb_enc_sprintf(enc, "key%.*s not found", len, start), hash, sym); - } - } - if (term == '}') goto format_s; - p++; - goto retry; - } + len = (int)(p - start + 1); /* including parenthesis */ + if (sym != Qnil) { + rb_enc_raise(enc, rb_eArgError, "named%.*s after <%"PRIsVALUE">", + len, start, rb_sym2str(sym)); + } + CHECKNAMEARG(start, len, enc); + get_hash(&hash, argc, argv); + sym = rb_check_symbol_cstr(start + 1, + len - 2 /* without parenthesis */, + enc); + if (!NIL_P(sym)) nextvalue = rb_hash_lookup2(hash, sym, Qundef); + if (nextvalue == Qundef) { + if (NIL_P(sym)) { + sym = rb_sym_intern(start + 1, + len - 2 /* without parenthesis */, + enc); + } + nextvalue = rb_hash_default_value(hash, sym); + if (NIL_P(nextvalue)) { + rb_key_err_raise(rb_enc_sprintf(enc, "key%.*s not found", len, start), hash, sym); + } + } + if (term == '}') goto format_s; + p++; + goto retry; + } - case '*': - CHECK_FOR_WIDTH(flags); - flags |= FWIDTH; - GETASTER(width); - if (width < 0) { - flags |= FMINUS; - width = -width; - if (width < 0) rb_raise(rb_eArgError, "width too big"); - } - p++; - goto retry; + case '*': + CHECK_FOR_WIDTH(flags); + flags |= FWIDTH; + GETASTER(width); + if (width < 0) { + flags |= FMINUS; + width = -width; + if (width < 0) rb_raise(rb_eArgError, "width too big"); + } + p++; + goto retry; - case '.': - if (flags & FPREC0) { - rb_raise(rb_eArgError, "precision given twice"); - } - flags |= FPREC|FPREC0; + case '.': + if (flags & FPREC0) { + rb_raise(rb_eArgError, "precision given twice"); + } + flags |= FPREC|FPREC0; - prec = 0; - p++; - if (*p == '*') { - GETASTER(prec); - if (prec < 0) { /* ignore negative precision */ - flags &= ~FPREC; - } - p++; - goto retry; - } + prec = 0; + p++; + if (*p == '*') { + GETASTER(prec); + if (prec < 0) { /* ignore negative precision */ + flags &= ~FPREC; + } + p++; + goto retry; + } - GETNUM(prec, precision); - goto retry; + GETNUM(prec, precision); + goto retry; - case '\n': - case '\0': - p--; + case '\n': + case '\0': + p--; /* fall through */ - case '%': - if (flags != FNONE) { - rb_raise(rb_eArgError, "invalid format character - %%"); - } - PUSH("%", 1); - break; + case '%': + if (flags != FNONE) { + rb_raise(rb_eArgError, "invalid format character - %%"); + } + PUSH("%", 1); + break; - case 'c': - { - VALUE val = GETARG(); - VALUE tmp; - unsigned int c; - int n; + case 'c': + { + VALUE val = GETARG(); + VALUE tmp; + unsigned int c; + int n; - tmp = rb_check_string_type(val); - if (!NIL_P(tmp)) { - if (rb_enc_strlen(RSTRING_PTR(tmp),RSTRING_END(tmp),enc) != 1) { - rb_raise(rb_eArgError, "%%c requires a character"); - } - c = rb_enc_codepoint_len(RSTRING_PTR(tmp), RSTRING_END(tmp), &n, enc); - RB_GC_GUARD(tmp); - } - else { - c = NUM2INT(val); - n = rb_enc_codelen(c, enc); - } - if (n <= 0) { - rb_raise(rb_eArgError, "invalid character"); - } - if (!(flags & FWIDTH)) { - CHECK(n); - rb_enc_mbcput(c, &buf[blen], enc); - blen += n; - } - else if ((flags & FMINUS)) { - CHECK(n); - rb_enc_mbcput(c, &buf[blen], enc); - blen += n; - if (width > 1) FILL(' ', width-1); - } - else { - if (width > 1) FILL(' ', width-1); - CHECK(n); - rb_enc_mbcput(c, &buf[blen], enc); - blen += n; - } - } - break; + tmp = rb_check_string_type(val); + if (!NIL_P(tmp)) { + if (rb_enc_strlen(RSTRING_PTR(tmp),RSTRING_END(tmp),enc) != 1) { + rb_raise(rb_eArgError, "%%c requires a character"); + } + c = rb_enc_codepoint_len(RSTRING_PTR(tmp), RSTRING_END(tmp), &n, enc); + RB_GC_GUARD(tmp); + } + else { + c = NUM2INT(val); + n = rb_enc_codelen(c, enc); + } + if (n <= 0) { + rb_raise(rb_eArgError, "invalid character"); + } + if (!(flags & FWIDTH)) { + CHECK(n); + rb_enc_mbcput(c, &buf[blen], enc); + blen += n; + } + else if ((flags & FMINUS)) { + CHECK(n); + rb_enc_mbcput(c, &buf[blen], enc); + blen += n; + if (width > 1) FILL(' ', width-1); + } + else { + if (width > 1) FILL(' ', width-1); + CHECK(n); + rb_enc_mbcput(c, &buf[blen], enc); + blen += n; + } + } + break; - case 's': - case 'p': - format_s: - { - VALUE arg = GETARG(); - long len, slen; + case 's': + case 'p': + format_s: + { + VALUE arg = GETARG(); + long len, slen; - if (*p == 'p') { - str = rb_inspect(arg); - } - else { - str = rb_obj_as_string(arg); - } - len = RSTRING_LEN(str); - rb_str_set_len(result, blen); - if (coderange != ENC_CODERANGE_BROKEN && scanned < blen) { - int cr = coderange; - scanned += rb_str_coderange_scan_restartable(buf+scanned, buf+blen, enc, &cr); - ENC_CODERANGE_SET(result, - (cr == ENC_CODERANGE_UNKNOWN ? - ENC_CODERANGE_BROKEN : (coderange = cr))); - } - enc = rb_enc_check(result, str); - if (flags&(FPREC|FWIDTH)) { - slen = rb_enc_strlen(RSTRING_PTR(str),RSTRING_END(str),enc); - if (slen < 0) { - rb_raise(rb_eArgError, "invalid mbstring sequence"); - } - if ((flags&FPREC) && (prec < slen)) { - char *p = rb_enc_nth(RSTRING_PTR(str), RSTRING_END(str), - prec, enc); - slen = prec; - len = p - RSTRING_PTR(str); - } - /* need to adjust multi-byte string pos */ - if ((flags&FWIDTH) && (width > slen)) { - width -= (int)slen; - if (!(flags&FMINUS)) { - FILL(' ', width); - width = 0; - } - CHECK(len); - memcpy(&buf[blen], RSTRING_PTR(str), len); - RB_GC_GUARD(str); - blen += len; - if (flags&FMINUS) { - FILL(' ', width); - } - rb_enc_associate(result, enc); - break; - } - } - PUSH(RSTRING_PTR(str), len); - RB_GC_GUARD(str); - rb_enc_associate(result, enc); - } - break; + if (*p == 'p') { + str = rb_inspect(arg); + } + else { + str = rb_obj_as_string(arg); + } + len = RSTRING_LEN(str); + rb_str_set_len(result, blen); + if (coderange != ENC_CODERANGE_BROKEN && scanned < blen) { + int cr = coderange; + scanned += rb_str_coderange_scan_restartable(buf+scanned, buf+blen, enc, &cr); + ENC_CODERANGE_SET(result, + (cr == ENC_CODERANGE_UNKNOWN ? + ENC_CODERANGE_BROKEN : (coderange = cr))); + } + enc = rb_enc_check(result, str); + if (flags&(FPREC|FWIDTH)) { + slen = rb_enc_strlen(RSTRING_PTR(str),RSTRING_END(str),enc); + if (slen < 0) { + rb_raise(rb_eArgError, "invalid mbstring sequence"); + } + if ((flags&FPREC) && (prec < slen)) { + char *p = rb_enc_nth(RSTRING_PTR(str), RSTRING_END(str), + prec, enc); + slen = prec; + len = p - RSTRING_PTR(str); + } + /* need to adjust multi-byte string pos */ + if ((flags&FWIDTH) && (width > slen)) { + width -= (int)slen; + if (!(flags&FMINUS)) { + FILL(' ', width); + width = 0; + } + CHECK(len); + memcpy(&buf[blen], RSTRING_PTR(str), len); + RB_GC_GUARD(str); + blen += len; + if (flags&FMINUS) { + FILL(' ', width); + } + rb_enc_associate(result, enc); + break; + } + } + PUSH(RSTRING_PTR(str), len); + RB_GC_GUARD(str); + rb_enc_associate(result, enc); + } + break; - case 'd': - case 'i': - case 'o': - case 'x': - case 'X': - case 'b': - case 'B': - case 'u': - { - volatile VALUE val = GETARG(); + case 'd': + case 'i': + case 'o': + case 'x': + case 'X': + case 'b': + case 'B': + case 'u': + { + volatile VALUE val = GETARG(); int valsign; - char nbuf[BIT_DIGITS(SIZEOF_LONG*CHAR_BIT)+2], *s; - const char *prefix = 0; - int sign = 0, dots = 0; - char sc = 0; - long v = 0; - int base, bignum = 0; - int len; + char nbuf[BIT_DIGITS(SIZEOF_LONG*CHAR_BIT)+2], *s; + const char *prefix = 0; + int sign = 0, dots = 0; + char sc = 0; + long v = 0; + int base, bignum = 0; + int len; - switch (*p) { - case 'd': - case 'i': - case 'u': - sign = 1; break; - case 'o': - case 'x': - case 'X': - case 'b': - case 'B': - if (flags&(FPLUS|FSPACE)) sign = 1; - break; - } - if (flags & FSHARP) { - switch (*p) { - case 'o': - prefix = "0"; break; - case 'x': - prefix = "0x"; break; - case 'X': - prefix = "0X"; break; - case 'b': - prefix = "0b"; break; - case 'B': - prefix = "0B"; break; - } - } + switch (*p) { + case 'd': + case 'i': + case 'u': + sign = 1; break; + case 'o': + case 'x': + case 'X': + case 'b': + case 'B': + if (flags&(FPLUS|FSPACE)) sign = 1; + break; + } + if (flags & FSHARP) { + switch (*p) { + case 'o': + prefix = "0"; break; + case 'x': + prefix = "0x"; break; + case 'X': + prefix = "0X"; break; + case 'b': + prefix = "0b"; break; + case 'B': + prefix = "0B"; break; + } + } - bin_retry: - switch (TYPE(val)) { - case T_FLOAT: - if (FIXABLE(RFLOAT_VALUE(val))) { - val = LONG2FIX((long)RFLOAT_VALUE(val)); - goto bin_retry; - } - val = rb_dbl2big(RFLOAT_VALUE(val)); - if (FIXNUM_P(val)) goto bin_retry; - bignum = 1; - break; - case T_STRING: - val = rb_str_to_inum(val, 0, TRUE); - goto bin_retry; - case T_BIGNUM: - bignum = 1; - break; - case T_FIXNUM: - v = FIX2LONG(val); - break; - default: - val = rb_Integer(val); - goto bin_retry; - } + bin_retry: + switch (TYPE(val)) { + case T_FLOAT: + if (FIXABLE(RFLOAT_VALUE(val))) { + val = LONG2FIX((long)RFLOAT_VALUE(val)); + goto bin_retry; + } + val = rb_dbl2big(RFLOAT_VALUE(val)); + if (FIXNUM_P(val)) goto bin_retry; + bignum = 1; + break; + case T_STRING: + val = rb_str_to_inum(val, 0, TRUE); + goto bin_retry; + case T_BIGNUM: + bignum = 1; + break; + case T_FIXNUM: + v = FIX2LONG(val); + break; + default: + val = rb_Integer(val); + goto bin_retry; + } - switch (*p) { - case 'o': - base = 8; break; - case 'x': - case 'X': - base = 16; break; - case 'b': - case 'B': - base = 2; break; - case 'u': - case 'd': - case 'i': - default: - base = 10; break; - } + switch (*p) { + case 'o': + base = 8; break; + case 'x': + case 'X': + base = 16; break; + case 'b': + case 'B': + base = 2; break; + case 'u': + case 'd': + case 'i': + default: + base = 10; break; + } if (base != 10) { int numbits = ffs(base)-1; @@ -690,10 +690,10 @@ rb_str_format(int argc, const VALUE *argv, VALUE fmt) sc = ' '; width--; } - s = ruby_ultoa((unsigned long)v, nbuf + sizeof(nbuf), 10, 0); - len = (int)(nbuf + sizeof(nbuf) - s); - } - else { + s = ruby_ultoa((unsigned long)v, nbuf + sizeof(nbuf), 10, 0); + len = (int)(nbuf + sizeof(nbuf) - s); + } + else { tmp = rb_big2str(val, 10); s = RSTRING_PTR(tmp); valsign = 1; @@ -711,220 +711,220 @@ rb_str_format(int argc, const VALUE *argv, VALUE fmt) sc = ' '; width--; } - len = rb_long2int(RSTRING_END(tmp) - s); - } + len = rb_long2int(RSTRING_END(tmp) - s); + } - if (dots) { - prec -= 2; - width -= 2; - } + if (dots) { + prec -= 2; + width -= 2; + } - if (*p == 'X') { - char *pp = s; - int c; - while ((c = (int)(unsigned char)*pp) != 0) { - *pp = rb_enc_toupper(c, enc); - pp++; - } - } - if (prefix && !prefix[1]) { /* octal */ - if (dots) { - prefix = 0; - } - else if (len == 1 && *s == '0') { - len = 0; - if (flags & FPREC) prec--; - } - else if ((flags & FPREC) && (prec > len)) { - prefix = 0; - } - } - else if (len == 1 && *s == '0') { - prefix = 0; - } - if (prefix) { - width -= (int)strlen(prefix); - } - if ((flags & (FZERO|FMINUS|FPREC)) == FZERO) { - prec = width; - width = 0; - } - else { - if (prec < len) { - if (!prefix && prec == 0 && len == 1 && *s == '0') len = 0; - prec = len; - } - width -= prec; - } - if (!(flags&FMINUS)) { - FILL(' ', width); - width = 0; - } - if (sc) PUSH(&sc, 1); - if (prefix) { - int plen = (int)strlen(prefix); - PUSH(prefix, plen); - } - if (dots) PUSH("..", 2); - if (prec > len) { - CHECK(prec - len); - if (!sign && valsign < 0) { - char c = sign_bits(base, p); - FILL_(c, prec - len); - } - else if ((flags & (FMINUS|FPREC)) != FMINUS) { - FILL_('0', prec - len); - } - } - PUSH(s, len); - RB_GC_GUARD(tmp); - FILL(' ', width); - } - break; + if (*p == 'X') { + char *pp = s; + int c; + while ((c = (int)(unsigned char)*pp) != 0) { + *pp = rb_enc_toupper(c, enc); + pp++; + } + } + if (prefix && !prefix[1]) { /* octal */ + if (dots) { + prefix = 0; + } + else if (len == 1 && *s == '0') { + len = 0; + if (flags & FPREC) prec--; + } + else if ((flags & FPREC) && (prec > len)) { + prefix = 0; + } + } + else if (len == 1 && *s == '0') { + prefix = 0; + } + if (prefix) { + width -= (int)strlen(prefix); + } + if ((flags & (FZERO|FMINUS|FPREC)) == FZERO) { + prec = width; + width = 0; + } + else { + if (prec < len) { + if (!prefix && prec == 0 && len == 1 && *s == '0') len = 0; + prec = len; + } + width -= prec; + } + if (!(flags&FMINUS)) { + FILL(' ', width); + width = 0; + } + if (sc) PUSH(&sc, 1); + if (prefix) { + int plen = (int)strlen(prefix); + PUSH(prefix, plen); + } + if (dots) PUSH("..", 2); + if (prec > len) { + CHECK(prec - len); + if (!sign && valsign < 0) { + char c = sign_bits(base, p); + FILL_(c, prec - len); + } + else if ((flags & (FMINUS|FPREC)) != FMINUS) { + FILL_('0', prec - len); + } + } + PUSH(s, len); + RB_GC_GUARD(tmp); + FILL(' ', width); + } + break; - case 'f': - { - VALUE val = GETARG(), num, den; - int sign = (flags&FPLUS) ? 1 : 0, zero = 0; - long len, fill; - if (RB_INTEGER_TYPE_P(val)) { - den = INT2FIX(1); - num = val; - } - else if (RB_TYPE_P(val, T_RATIONAL)) { - den = rb_rational_den(val); - num = rb_rational_num(val); - } - else { - nextvalue = val; - goto float_value; - } - if (!(flags&FPREC)) prec = default_float_precision; - if (FIXNUM_P(num)) { - if ((SIGNED_VALUE)num < 0) { - long n = -FIX2LONG(num); - num = LONG2FIX(n); - sign = -1; - } - } - else if (BIGNUM_NEGATIVE_P(num)) { - sign = -1; - num = rb_big_uminus(num); - } - if (den != INT2FIX(1)) { - num = rb_int_mul(num, rb_int_positive_pow(10, prec)); - num = rb_int_plus(num, rb_int_idiv(den, INT2FIX(2))); - num = rb_int_idiv(num, den); - } - else if (prec >= 0) { - zero = prec; - } - val = rb_int2str(num, 10); - len = RSTRING_LEN(val) + zero; - if (prec >= len) len = prec + 1; /* integer part 0 */ - if (sign || (flags&FSPACE)) ++len; - if (prec > 0) ++len; /* period */ - fill = width > len ? width - len : 0; - CHECK(fill + len); - if (fill && !(flags&(FMINUS|FZERO))) { - FILL_(' ', fill); - } - if (sign || (flags&FSPACE)) { - buf[blen++] = sign > 0 ? '+' : sign < 0 ? '-' : ' '; - } - if (fill && (flags&(FMINUS|FZERO)) == FZERO) { - FILL_('0', fill); - } - len = RSTRING_LEN(val) + zero; - t = RSTRING_PTR(val); - if (len > prec) { - PUSH_(t, len - prec); - } - else { - buf[blen++] = '0'; - } - if (prec > 0) { - buf[blen++] = '.'; - } - if (zero) { - FILL_('0', zero); - } - else if (prec > len) { - FILL_('0', prec - len); - PUSH_(t, len); - } - else if (prec > 0) { - PUSH_(t + len - prec, prec); - } - if (fill && (flags&FMINUS)) { - FILL_(' ', fill); - } - RB_GC_GUARD(val); - break; - } - case 'g': - case 'G': - case 'e': - case 'E': - /* TODO: rational support */ - case 'a': - case 'A': - float_value: - { - VALUE val = GETARG(); - double fval; + case 'f': + { + VALUE val = GETARG(), num, den; + int sign = (flags&FPLUS) ? 1 : 0, zero = 0; + long len, fill; + if (RB_INTEGER_TYPE_P(val)) { + den = INT2FIX(1); + num = val; + } + else if (RB_TYPE_P(val, T_RATIONAL)) { + den = rb_rational_den(val); + num = rb_rational_num(val); + } + else { + nextvalue = val; + goto float_value; + } + if (!(flags&FPREC)) prec = default_float_precision; + if (FIXNUM_P(num)) { + if ((SIGNED_VALUE)num < 0) { + long n = -FIX2LONG(num); + num = LONG2FIX(n); + sign = -1; + } + } + else if (BIGNUM_NEGATIVE_P(num)) { + sign = -1; + num = rb_big_uminus(num); + } + if (den != INT2FIX(1)) { + num = rb_int_mul(num, rb_int_positive_pow(10, prec)); + num = rb_int_plus(num, rb_int_idiv(den, INT2FIX(2))); + num = rb_int_idiv(num, den); + } + else if (prec >= 0) { + zero = prec; + } + val = rb_int2str(num, 10); + len = RSTRING_LEN(val) + zero; + if (prec >= len) len = prec + 1; /* integer part 0 */ + if (sign || (flags&FSPACE)) ++len; + if (prec > 0) ++len; /* period */ + fill = width > len ? width - len : 0; + CHECK(fill + len); + if (fill && !(flags&(FMINUS|FZERO))) { + FILL_(' ', fill); + } + if (sign || (flags&FSPACE)) { + buf[blen++] = sign > 0 ? '+' : sign < 0 ? '-' : ' '; + } + if (fill && (flags&(FMINUS|FZERO)) == FZERO) { + FILL_('0', fill); + } + len = RSTRING_LEN(val) + zero; + t = RSTRING_PTR(val); + if (len > prec) { + PUSH_(t, len - prec); + } + else { + buf[blen++] = '0'; + } + if (prec > 0) { + buf[blen++] = '.'; + } + if (zero) { + FILL_('0', zero); + } + else if (prec > len) { + FILL_('0', prec - len); + PUSH_(t, len); + } + else if (prec > 0) { + PUSH_(t + len - prec, prec); + } + if (fill && (flags&FMINUS)) { + FILL_(' ', fill); + } + RB_GC_GUARD(val); + break; + } + case 'g': + case 'G': + case 'e': + case 'E': + /* TODO: rational support */ + case 'a': + case 'A': + float_value: + { + VALUE val = GETARG(); + double fval; - fval = RFLOAT_VALUE(rb_Float(val)); - if (!isfinite(fval)) { - const char *expr; - int need; - int elen; - char sign = '\0'; + fval = RFLOAT_VALUE(rb_Float(val)); + if (!isfinite(fval)) { + const char *expr; + int need; + int elen; + char sign = '\0'; - if (isnan(fval)) { - expr = "NaN"; - } - else { - expr = "Inf"; - } - need = (int)strlen(expr); - elen = need; - if (!isnan(fval) && fval < 0.0) - sign = '-'; - else if (flags & (FPLUS|FSPACE)) - sign = (flags & FPLUS) ? '+' : ' '; - if (sign) - ++need; - if ((flags & FWIDTH) && need < width) - need = width; + if (isnan(fval)) { + expr = "NaN"; + } + else { + expr = "Inf"; + } + need = (int)strlen(expr); + elen = need; + if (!isnan(fval) && fval < 0.0) + sign = '-'; + else if (flags & (FPLUS|FSPACE)) + sign = (flags & FPLUS) ? '+' : ' '; + if (sign) + ++need; + if ((flags & FWIDTH) && need < width) + need = width; - FILL(' ', need); - if (flags & FMINUS) { - if (sign) - buf[blen - need--] = sign; - memcpy(&buf[blen - need], expr, elen); - } - else { - if (sign) - buf[blen - elen - 1] = sign; - memcpy(&buf[blen - elen], expr, elen); - } - break; - } - else { - int cr = ENC_CODERANGE(result); - char fbuf[2*BIT_DIGITS(SIZEOF_INT*CHAR_BIT)+10]; - char *fmt = fmt_setup(fbuf, sizeof(fbuf), *p, flags, width, prec); - rb_str_set_len(result, blen); - rb_str_catf(result, fmt, fval); - ENC_CODERANGE_SET(result, cr); - bsiz = rb_str_capacity(result); - RSTRING_GETMEM(result, buf, blen); - } - } - break; - } - flags = FNONE; + FILL(' ', need); + if (flags & FMINUS) { + if (sign) + buf[blen - need--] = sign; + memcpy(&buf[blen - need], expr, elen); + } + else { + if (sign) + buf[blen - elen - 1] = sign; + memcpy(&buf[blen - elen], expr, elen); + } + break; + } + else { + int cr = ENC_CODERANGE(result); + char fbuf[2*BIT_DIGITS(SIZEOF_INT*CHAR_BIT)+10]; + char *fmt = fmt_setup(fbuf, sizeof(fbuf), *p, flags, width, prec); + rb_str_set_len(result, blen); + rb_str_catf(result, fmt, fval); + ENC_CODERANGE_SET(result, cr); + bsiz = rb_str_capacity(result); + RSTRING_GETMEM(result, buf, blen); + } + } + break; + } + flags = FNONE; } sprint_exit: @@ -932,9 +932,9 @@ rb_str_format(int argc, const VALUE *argv, VALUE fmt) /* XXX - We cannot validate the number of arguments if (digit)$ style used. */ if (posarg >= 0 && nextarg < argc) { - const char *mesg = "too many arguments for format string"; - if (RTEST(ruby_debug)) rb_raise(rb_eArgError, "%s", mesg); - if (RTEST(ruby_verbose)) rb_warn("%s", mesg); + const char *mesg = "too many arguments for format string"; + if (RTEST(ruby_debug)) rb_raise(rb_eArgError, "%s", mesg); + if (RTEST(ruby_verbose)) rb_warn("%s", mesg); } rb_str_resize(result, blen); @@ -949,12 +949,12 @@ fmt_setup(char *buf, size_t size, int c, int flags, int width, int prec) *--buf = c; if (flags & FPREC) { - buf = ruby_ultoa(prec, buf, 10, 0); - *--buf = '.'; + buf = ruby_ultoa(prec, buf, 10, 0); + *--buf = '.'; } if (flags & FWIDTH) { - buf = ruby_ultoa(width, buf, 10, 0); + buf = ruby_ultoa(width, buf, 10, 0); } if (flags & FSPACE) *--buf = ' '; @@ -1008,7 +1008,7 @@ int ruby_vsnprintf(char *str, size_t n, const char *fmt, va_list ap) { if (str && (ssize_t)n < 1) - return (EOF); + return (EOF); return ruby_do_vsnprintf(str, n, fmt, ap); } @@ -1038,7 +1038,7 @@ ruby_snprintf(char *str, size_t n, char const *fmt, ...) va_list ap; if (str && (ssize_t)n < 1) - return (EOF); + return (EOF); va_start(ap, fmt); ret = ruby_do_vsnprintf(str, n, fmt, ap); @@ -1061,22 +1061,22 @@ ruby__sfvwrite(register rb_printf_buffer *fp, register struct __suio *uio) long blen = buf - RSTRING_PTR(result), bsiz = fp->_w; if (RBASIC(result)->klass) { - rb_raise(rb_eRuntimeError, "rb_vsprintf reentered"); + rb_raise(rb_eRuntimeError, "rb_vsprintf reentered"); } if (uio->uio_resid == 0) - return 0; + return 0; #if SIZE_MAX > LONG_MAX if (uio->uio_resid >= LONG_MAX) - rb_raise(rb_eRuntimeError, "too big string"); + rb_raise(rb_eRuntimeError, "too big string"); #endif len = (long)uio->uio_resid; CHECK(len); buf += blen; fp->_w = bsiz; for (iov = uio->uio_iov; len > 0; ++iov) { - MEMCPY(buf, iov->iov_base, char, n = iov->iov_len); - buf += n; - len -= n; + MEMCPY(buf, iov->iov_base, char, n = iov->iov_len); + buf += n; + len -= n; } fp->_p = (unsigned char *)buf; rb_str_set_len(result, buf - RSTRING_PTR(result)); @@ -1093,51 +1093,51 @@ ruby__sfvextra(rb_printf_buffer *fp, size_t valsize, void *valp, long *sz, int s if (valsize != sizeof(VALUE)) return 0; value = *(VALUE *)valp; if (RBASIC(result)->klass) { - rb_raise(rb_eRuntimeError, "rb_vsprintf reentered"); + rb_raise(rb_eRuntimeError, "rb_vsprintf reentered"); } if (sign == '+') { - if (RB_TYPE_P(value, T_CLASS)) { + if (RB_TYPE_P(value, T_CLASS)) { # define LITERAL(str) (*sz = rb_strlen_lit(str), str) - if (value == rb_cNilClass) { - return LITERAL("nil"); - } - else if (value == rb_cInteger) { - return LITERAL("Integer"); - } - else if (value == rb_cSymbol) { - return LITERAL("Symbol"); - } - else if (value == rb_cTrueClass) { - return LITERAL("true"); - } - else if (value == rb_cFalseClass) { - return LITERAL("false"); - } + if (value == rb_cNilClass) { + return LITERAL("nil"); + } + else if (value == rb_cInteger) { + return LITERAL("Integer"); + } + else if (value == rb_cSymbol) { + return LITERAL("Symbol"); + } + else if (value == rb_cTrueClass) { + return LITERAL("true"); + } + else if (value == rb_cFalseClass) { + return LITERAL("false"); + } # undef LITERAL - } - value = rb_inspect(value); + } + value = rb_inspect(value); } else if (SYMBOL_P(value)) { - value = rb_sym2str(value); - if (sign == ' ' && !rb_str_symname_p(value)) { - value = rb_str_escape(value); - } + value = rb_sym2str(value); + if (sign == ' ' && !rb_str_symname_p(value)) { + value = rb_str_escape(value); + } } else { - value = rb_obj_as_string(value); - if (sign == ' ') value = QUOTE(value); + value = rb_obj_as_string(value); + if (sign == ' ') value = QUOTE(value); } enc = rb_enc_compatible(result, value); if (enc) { - rb_enc_associate(result, enc); + rb_enc_associate(result, enc); } else { - enc = rb_enc_get(result); - value = rb_str_conv_enc_opts(value, rb_enc_get(value), enc, - ECONV_UNDEF_REPLACE|ECONV_INVALID_REPLACE, - Qnil); - *(volatile VALUE *)valp = value; + enc = rb_enc_get(result); + value = rb_str_conv_enc_opts(value, rb_enc_get(value), enc, + ECONV_UNDEF_REPLACE|ECONV_INVALID_REPLACE, + Qnil); + *(volatile VALUE *)valp = value; } StringValueCStr(value); RSTRING_GETMEM(value, cp, *sz); @@ -1157,12 +1157,12 @@ rb_enc_vsprintf(rb_encoding *enc, const char *fmt, va_list ap) f._w = 120; result = rb_str_buf_new(f._w); if (enc) { - if (rb_enc_mbminlen(enc) > 1) { - /* the implementation deeply depends on plain char */ - rb_raise(rb_eArgError, "cannot construct wchar_t based encoding string: %s", - rb_enc_name(enc)); - } - rb_enc_associate(result, enc); + if (rb_enc_mbminlen(enc) > 1) { + /* the implementation deeply depends on plain char */ + rb_raise(rb_eArgError, "cannot construct wchar_t based encoding string: %s", + rb_enc_name(enc)); + } + rb_enc_associate(result, enc); } f._bf._base = (unsigned char *)result; f._p = (unsigned char *)RSTRING_PTR(result); diff --git a/st.c b/st.c index c4966f1d8c..6b534a856a 100644 --- a/st.c +++ b/st.c @@ -181,9 +181,9 @@ static const struct st_hash_type type_strcasehash = { up to TRUE if the table is rebuilt during the comparison. */ #define DO_PTR_EQUAL_CHECK(tab, ptr, hash_val, key, res, rebuilt_p) \ do { \ - unsigned int _old_rebuilds_num = (tab)->rebuilds_num; \ - res = PTR_EQUAL(tab, ptr, hash_val, key); \ - rebuilt_p = _old_rebuilds_num != (tab)->rebuilds_num; \ + unsigned int _old_rebuilds_num = (tab)->rebuilds_num; \ + res = PTR_EQUAL(tab, ptr, hash_val, key); \ + rebuilt_p = _old_rebuilds_num != (tab)->rebuilds_num; \ } while (FALSE) /* Features of a table. */ @@ -356,9 +356,9 @@ static inline st_index_t get_bin(st_index_t *bins, int s, st_index_t n) { return (s == 0 ? ((unsigned char *) bins)[n] - : s == 1 ? ((unsigned short *) bins)[n] - : s == 2 ? ((unsigned int *) bins)[n] - : ((st_index_t *) bins)[n]); + : s == 1 ? ((unsigned short *) bins)[n] + : s == 2 ? ((unsigned int *) bins)[n] + : ((st_index_t *) bins)[n]); } /* Set up N-th bin in array BINS of table with bins size index S to @@ -557,7 +557,7 @@ st_init_table_with_size(const struct st_hash_type *type, st_index_t size) #endif } tab->entries = (st_table_entry *) malloc(get_allocated_entries(tab) - * sizeof(st_table_entry)); + * sizeof(st_table_entry)); #ifndef RUBY if (tab->entries == NULL) { st_free_table(tab); @@ -661,7 +661,7 @@ find_table_bin_ind_direct(st_table *table, st_hash_t hash_value, st_data_t key); static st_index_t find_table_bin_ptr_and_reserve(st_table *tab, st_hash_t *hash_value, - st_data_t key, st_index_t *bin_ind); + st_data_t key, st_index_t *bin_ind); #ifdef HASH_LOG static void @@ -714,48 +714,48 @@ rebuild_table(st_table *tab) bound = tab->entries_bound; entries = tab->entries; if ((2 * tab->num_entries <= get_allocated_entries(tab) - && REBUILD_THRESHOLD * tab->num_entries > get_allocated_entries(tab)) - || tab->num_entries < (1 << MINIMAL_POWER2)) { + && REBUILD_THRESHOLD * tab->num_entries > get_allocated_entries(tab)) + || tab->num_entries < (1 << MINIMAL_POWER2)) { /* Compaction: */ tab->num_entries = 0; - if (tab->bins != NULL) - initialize_bins(tab); - new_tab = tab; - new_entries = entries; + if (tab->bins != NULL) + initialize_bins(tab); + new_tab = tab; + new_entries = entries; } else { new_tab = st_init_table_with_size(tab->type, - 2 * tab->num_entries - 1); - new_entries = new_tab->entries; + 2 * tab->num_entries - 1); + new_entries = new_tab->entries; } ni = 0; bins = new_tab->bins; size_ind = get_size_ind(new_tab); for (i = tab->entries_start; i < bound; i++) { curr_entry_ptr = &entries[i]; - PREFETCH(entries + i + 1, 0); - if (EXPECT(DELETED_ENTRY_P(curr_entry_ptr), 0)) - continue; - if (&new_entries[ni] != curr_entry_ptr) - new_entries[ni] = *curr_entry_ptr; - if (EXPECT(bins != NULL, 1)) { - bin_ind = find_table_bin_ind_direct(new_tab, curr_entry_ptr->hash, - curr_entry_ptr->key); - set_bin(bins, size_ind, bin_ind, ni + ENTRY_BASE); - } - new_tab->num_entries++; - ni++; + PREFETCH(entries + i + 1, 0); + if (EXPECT(DELETED_ENTRY_P(curr_entry_ptr), 0)) + continue; + if (&new_entries[ni] != curr_entry_ptr) + new_entries[ni] = *curr_entry_ptr; + if (EXPECT(bins != NULL, 1)) { + bin_ind = find_table_bin_ind_direct(new_tab, curr_entry_ptr->hash, + curr_entry_ptr->key); + set_bin(bins, size_ind, bin_ind, ni + ENTRY_BASE); + } + new_tab->num_entries++; + ni++; } if (new_tab != tab) { tab->entry_power = new_tab->entry_power; - tab->bin_power = new_tab->bin_power; - tab->size_ind = new_tab->size_ind; - if (tab->bins != NULL) - free(tab->bins); - tab->bins = new_tab->bins; - free(tab->entries); - tab->entries = new_tab->entries; - free(new_tab); + tab->bin_power = new_tab->bin_power; + tab->size_ind = new_tab->size_ind; + if (tab->bins != NULL) + free(tab->bins); + tab->bins = new_tab->bins; + free(tab->entries); + tab->entries = new_tab->entries; + free(new_tab); } tab->entries_start = 0; tab->entries_bound = tab->num_entries; @@ -796,11 +796,11 @@ find_entry(st_table *tab, st_hash_t hash_value, st_data_t key) bound = tab->entries_bound; entries = tab->entries; for (i = tab->entries_start; i < bound; i++) { - DO_PTR_EQUAL_CHECK(tab, &entries[i], hash_value, key, eq_p, rebuilt_p); - if (EXPECT(rebuilt_p, 0)) - return REBUILT_TABLE_ENTRY_IND; - if (eq_p) - return i; + DO_PTR_EQUAL_CHECK(tab, &entries[i], hash_value, key, eq_p, rebuilt_p); + if (EXPECT(rebuilt_p, 0)) + return REBUILT_TABLE_ENTRY_IND; + if (eq_p) + return i; } return UNDEFINED_ENTRY_IND; } @@ -836,17 +836,17 @@ find_table_entry_ind(st_table *tab, st_hash_t hash_value, st_data_t key) for (;;) { bin = get_bin(tab->bins, get_size_ind(tab), ind); if (! EMPTY_OR_DELETED_BIN_P(bin)) { - DO_PTR_EQUAL_CHECK(tab, &entries[bin - ENTRY_BASE], hash_value, key, eq_p, rebuilt_p); - if (EXPECT(rebuilt_p, 0)) - return REBUILT_TABLE_ENTRY_IND; - if (eq_p) - break; - } - else if (EMPTY_BIN_P(bin)) + DO_PTR_EQUAL_CHECK(tab, &entries[bin - ENTRY_BASE], hash_value, key, eq_p, rebuilt_p); + if (EXPECT(rebuilt_p, 0)) + return REBUILT_TABLE_ENTRY_IND; + if (eq_p) + break; + } + else if (EMPTY_BIN_P(bin)) return UNDEFINED_ENTRY_IND; #ifdef QUADRATIC_PROBE - ind = hash_bin(ind + d, tab); - d++; + ind = hash_bin(ind + d, tab); + d++; #else ind = secondary_hash(ind, tab, &peterb); #endif @@ -882,17 +882,17 @@ find_table_bin_ind(st_table *tab, st_hash_t hash_value, st_data_t key) for (;;) { bin = get_bin(tab->bins, get_size_ind(tab), ind); if (! EMPTY_OR_DELETED_BIN_P(bin)) { - DO_PTR_EQUAL_CHECK(tab, &entries[bin - ENTRY_BASE], hash_value, key, eq_p, rebuilt_p); - if (EXPECT(rebuilt_p, 0)) - return REBUILT_TABLE_BIN_IND; - if (eq_p) - break; - } - else if (EMPTY_BIN_P(bin)) + DO_PTR_EQUAL_CHECK(tab, &entries[bin - ENTRY_BASE], hash_value, key, eq_p, rebuilt_p); + if (EXPECT(rebuilt_p, 0)) + return REBUILT_TABLE_BIN_IND; + if (eq_p) + break; + } + else if (EMPTY_BIN_P(bin)) return UNDEFINED_BIN_IND; #ifdef QUADRATIC_PROBE - ind = hash_bin(ind + d, tab); - d++; + ind = hash_bin(ind + d, tab); + d++; #else ind = secondary_hash(ind, tab, &peterb); #endif @@ -925,10 +925,10 @@ find_table_bin_ind_direct(st_table *tab, st_hash_t hash_value, st_data_t key) for (;;) { bin = get_bin(tab->bins, get_size_ind(tab), ind); if (EMPTY_OR_DELETED_BIN_P(bin)) - return ind; + return ind; #ifdef QUADRATIC_PROBE - ind = hash_bin(ind + d, tab); - d++; + ind = hash_bin(ind + d, tab); + d++; #else ind = secondary_hash(ind, tab, &peterb); #endif @@ -947,7 +947,7 @@ find_table_bin_ind_direct(st_table *tab, st_hash_t hash_value, st_data_t key) during the search, return REBUILT_TABLE_ENTRY_IND. */ static st_index_t find_table_bin_ptr_and_reserve(st_table *tab, st_hash_t *hash_value, - st_data_t key, st_index_t *bin_ind) + st_data_t key, st_index_t *bin_ind) { int eq_p, rebuilt_p; st_index_t ind; @@ -974,26 +974,26 @@ find_table_bin_ptr_and_reserve(st_table *tab, st_hash_t *hash_value, entry_index = get_bin(tab->bins, get_size_ind(tab), ind); if (EMPTY_BIN_P(entry_index)) { tab->num_entries++; - entry_index = UNDEFINED_ENTRY_IND; + entry_index = UNDEFINED_ENTRY_IND; if (first_deleted_bin_ind != UNDEFINED_BIN_IND) { /* We can reuse bin of a deleted entry. */ ind = first_deleted_bin_ind; MARK_BIN_EMPTY(tab, ind); } break; - } - else if (! DELETED_BIN_P(entry_index)) { - DO_PTR_EQUAL_CHECK(tab, &entries[entry_index - ENTRY_BASE], curr_hash_value, key, eq_p, rebuilt_p); - if (EXPECT(rebuilt_p, 0)) - return REBUILT_TABLE_ENTRY_IND; + } + else if (! DELETED_BIN_P(entry_index)) { + DO_PTR_EQUAL_CHECK(tab, &entries[entry_index - ENTRY_BASE], curr_hash_value, key, eq_p, rebuilt_p); + if (EXPECT(rebuilt_p, 0)) + return REBUILT_TABLE_ENTRY_IND; if (eq_p) break; - } - else if (first_deleted_bin_ind == UNDEFINED_BIN_IND) + } + else if (first_deleted_bin_ind == UNDEFINED_BIN_IND) first_deleted_bin_ind = ind; #ifdef QUADRATIC_PROBE - ind = hash_bin(ind + d, tab); - d++; + ind = hash_bin(ind + d, tab); + d++; #else ind = secondary_hash(ind, tab, &peterb); #endif @@ -1014,18 +1014,18 @@ st_lookup(st_table *tab, st_data_t key, st_data_t *value) retry: if (tab->bins == NULL) { bin = find_entry(tab, hash, key); - if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) - goto retry; - if (bin == UNDEFINED_ENTRY_IND) - return 0; + if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) + goto retry; + if (bin == UNDEFINED_ENTRY_IND) + return 0; } else { bin = find_table_entry_ind(tab, hash, key); - if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) - goto retry; - if (bin == UNDEFINED_ENTRY_IND) - return 0; - bin -= ENTRY_BASE; + if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) + goto retry; + if (bin == UNDEFINED_ENTRY_IND) + return 0; + bin -= ENTRY_BASE; } if (value != 0) *value = tab->entries[bin].record; @@ -1043,18 +1043,18 @@ st_get_key(st_table *tab, st_data_t key, st_data_t *result) retry: if (tab->bins == NULL) { bin = find_entry(tab, hash, key); - if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) - goto retry; - if (bin == UNDEFINED_ENTRY_IND) - return 0; + if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) + goto retry; + if (bin == UNDEFINED_ENTRY_IND) + return 0; } else { bin = find_table_entry_ind(tab, hash, key); - if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) - goto retry; - if (bin == UNDEFINED_ENTRY_IND) - return 0; - bin -= ENTRY_BASE; + if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) + goto retry; + if (bin == UNDEFINED_ENTRY_IND) + return 0; + bin -= ENTRY_BASE; } if (result != 0) *result = tab->entries[bin].key; @@ -1089,29 +1089,29 @@ st_insert(st_table *tab, st_data_t key, st_data_t value) rebuild_table_if_necessary(tab); if (tab->bins == NULL) { bin = find_entry(tab, hash_value, key); - if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) - goto retry; - new_p = bin == UNDEFINED_ENTRY_IND; - if (new_p) - tab->num_entries++; - bin_ind = UNDEFINED_BIN_IND; + if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) + goto retry; + new_p = bin == UNDEFINED_ENTRY_IND; + if (new_p) + tab->num_entries++; + bin_ind = UNDEFINED_BIN_IND; } else { bin = find_table_bin_ptr_and_reserve(tab, &hash_value, - key, &bin_ind); - if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) - goto retry; - new_p = bin == UNDEFINED_ENTRY_IND; - bin -= ENTRY_BASE; + key, &bin_ind); + if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) + goto retry; + new_p = bin == UNDEFINED_ENTRY_IND; + bin -= ENTRY_BASE; } if (new_p) { - ind = tab->entries_bound++; + ind = tab->entries_bound++; entry = &tab->entries[ind]; entry->hash = hash_value; entry->key = key; entry->record = value; - if (bin_ind != UNDEFINED_BIN_IND) - set_bin(tab->bins, get_size_ind(tab), bin_ind, ind + ENTRY_BASE); + if (bin_ind != UNDEFINED_BIN_IND) + set_bin(tab->bins, get_size_ind(tab), bin_ind, ind + ENTRY_BASE); return 0; } tab->entries[bin].record = value; @@ -1122,7 +1122,7 @@ st_insert(st_table *tab, st_data_t key, st_data_t value) entry with KEY before the insertion. */ static inline void st_add_direct_with_hash(st_table *tab, - st_data_t key, st_data_t value, st_hash_t hash) + st_data_t key, st_data_t value, st_hash_t hash) { st_table_entry *entry; st_index_t ind; @@ -1137,7 +1137,7 @@ st_add_direct_with_hash(st_table *tab, tab->num_entries++; if (tab->bins != NULL) { bin_ind = find_table_bin_ind_direct(tab, hash, key); - set_bin(tab->bins, get_size_ind(tab), bin_ind, ind + ENTRY_BASE); + set_bin(tab->bins, get_size_ind(tab), bin_ind, ind + ENTRY_BASE); } } @@ -1171,20 +1171,20 @@ st_insert2(st_table *tab, st_data_t key, st_data_t value, rebuild_table_if_necessary (tab); if (tab->bins == NULL) { bin = find_entry(tab, hash_value, key); - if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) - goto retry; - new_p = bin == UNDEFINED_ENTRY_IND; - if (new_p) - tab->num_entries++; - bin_ind = UNDEFINED_BIN_IND; + if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) + goto retry; + new_p = bin == UNDEFINED_ENTRY_IND; + if (new_p) + tab->num_entries++; + bin_ind = UNDEFINED_BIN_IND; } else { bin = find_table_bin_ptr_and_reserve(tab, &hash_value, - key, &bin_ind); - if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) - goto retry; - new_p = bin == UNDEFINED_ENTRY_IND; - bin -= ENTRY_BASE; + key, &bin_ind); + if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) + goto retry; + new_p = bin == UNDEFINED_ENTRY_IND; + bin -= ENTRY_BASE; } if (new_p) { key = (*func)(key); @@ -1193,8 +1193,8 @@ st_insert2(st_table *tab, st_data_t key, st_data_t value, entry->hash = hash_value; entry->key = key; entry->record = value; - if (bin_ind != UNDEFINED_BIN_IND) - set_bin(tab->bins, get_size_ind(tab), bin_ind, ind + ENTRY_BASE); + if (bin_ind != UNDEFINED_BIN_IND) + set_bin(tab->bins, get_size_ind(tab), bin_ind, ind + ENTRY_BASE); return 0; } tab->entries[bin].record = value; @@ -1225,7 +1225,7 @@ st_copy(st_table *old_tab) #endif } new_tab->entries = (st_table_entry *) malloc(get_allocated_entries(old_tab) - * sizeof(st_table_entry)); + * sizeof(st_table_entry)); #ifndef RUBY if (new_tab->entries == NULL) { st_free_table(new_tab); @@ -1233,7 +1233,7 @@ st_copy(st_table *old_tab) } #endif MEMCPY(new_tab->entries, old_tab->entries, st_table_entry, - get_allocated_entries(old_tab)); + get_allocated_entries(old_tab)); if (old_tab->bins != NULL) MEMCPY(new_tab->bins, old_tab->bins, char, bins_size(old_tab)); return new_tab; @@ -1271,23 +1271,23 @@ st_general_delete(st_table *tab, st_data_t *key, st_data_t *value) retry: if (tab->bins == NULL) { bin = find_entry(tab, hash, *key); - if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) - goto retry; - if (bin == UNDEFINED_ENTRY_IND) { - if (value != 0) *value = 0; - return 0; - } + if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) + goto retry; + if (bin == UNDEFINED_ENTRY_IND) { + if (value != 0) *value = 0; + return 0; + } } else { bin_ind = find_table_bin_ind(tab, hash, *key); - if (EXPECT(bin_ind == REBUILT_TABLE_BIN_IND, 0)) - goto retry; - if (bin_ind == UNDEFINED_BIN_IND) { - if (value != 0) *value = 0; - return 0; - } - bin = get_bin(tab->bins, get_size_ind(tab), bin_ind) - ENTRY_BASE; - MARK_BIN_DELETED(tab, bin_ind); + if (EXPECT(bin_ind == REBUILT_TABLE_BIN_IND, 0)) + goto retry; + if (bin_ind == UNDEFINED_BIN_IND) { + if (value != 0) *value = 0; + return 0; + } + bin = get_bin(tab->bins, get_size_ind(tab), bin_ind) - ENTRY_BASE; + MARK_BIN_DELETED(tab, bin_ind); } entry = &tab->entries[bin]; *key = entry->key; @@ -1332,36 +1332,36 @@ st_shift(st_table *tab, st_data_t *key, st_data_t *value) bound = tab->entries_bound; for (i = tab->entries_start; i < bound; i++) { curr_entry_ptr = &entries[i]; - if (! DELETED_ENTRY_P(curr_entry_ptr)) { - st_hash_t entry_hash = curr_entry_ptr->hash; - st_data_t entry_key = curr_entry_ptr->key; + if (! DELETED_ENTRY_P(curr_entry_ptr)) { + st_hash_t entry_hash = curr_entry_ptr->hash; + st_data_t entry_key = curr_entry_ptr->key; - if (value != 0) *value = curr_entry_ptr->record; - *key = entry_key; - retry: - if (tab->bins == NULL) { - bin = find_entry(tab, entry_hash, entry_key); - if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) { - entries = tab->entries; - goto retry; - } - curr_entry_ptr = &entries[bin]; - } - else { - bin_ind = find_table_bin_ind(tab, entry_hash, entry_key); - if (EXPECT(bin_ind == REBUILT_TABLE_BIN_IND, 0)) { - entries = tab->entries; - goto retry; - } - curr_entry_ptr = &entries[get_bin(tab->bins, get_size_ind(tab), bin_ind) - - ENTRY_BASE]; - MARK_BIN_DELETED(tab, bin_ind); - } - MARK_ENTRY_DELETED(curr_entry_ptr); - tab->num_entries--; - update_range_for_deleted(tab, i); - return 1; - } + if (value != 0) *value = curr_entry_ptr->record; + *key = entry_key; + retry: + if (tab->bins == NULL) { + bin = find_entry(tab, entry_hash, entry_key); + if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) { + entries = tab->entries; + goto retry; + } + curr_entry_ptr = &entries[bin]; + } + else { + bin_ind = find_table_bin_ind(tab, entry_hash, entry_key); + if (EXPECT(bin_ind == REBUILT_TABLE_BIN_IND, 0)) { + entries = tab->entries; + goto retry; + } + curr_entry_ptr = &entries[get_bin(tab->bins, get_size_ind(tab), bin_ind) + - ENTRY_BASE]; + MARK_BIN_DELETED(tab, bin_ind); + } + MARK_ENTRY_DELETED(curr_entry_ptr); + tab->num_entries--; + update_range_for_deleted(tab, i); + return 1; + } } if (value != 0) *value = 0; return 0; @@ -1385,7 +1385,7 @@ st_cleanup_safe(st_table *tab ATTRIBUTE_UNUSED, the table before the call. */ int st_update(st_table *tab, st_data_t key, - st_update_callback_func *func, st_data_t arg) + st_update_callback_func *func, st_data_t arg) { st_table_entry *entry = NULL; /* to avoid uninitialized value warning */ st_index_t bin = 0; /* Ditto */ @@ -1399,21 +1399,21 @@ st_update(st_table *tab, st_data_t key, entries = tab->entries; if (tab->bins == NULL) { bin = find_entry(tab, hash, key); - if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) - goto retry; - existing = bin != UNDEFINED_ENTRY_IND; - entry = &entries[bin]; - bin_ind = UNDEFINED_BIN_IND; + if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) + goto retry; + existing = bin != UNDEFINED_ENTRY_IND; + entry = &entries[bin]; + bin_ind = UNDEFINED_BIN_IND; } else { bin_ind = find_table_bin_ind(tab, hash, key); - if (EXPECT(bin_ind == REBUILT_TABLE_BIN_IND, 0)) - goto retry; - existing = bin_ind != UNDEFINED_BIN_IND; - if (existing) { - bin = get_bin(tab->bins, get_size_ind(tab), bin_ind) - ENTRY_BASE; - entry = &entries[bin]; - } + if (EXPECT(bin_ind == REBUILT_TABLE_BIN_IND, 0)) + goto retry; + existing = bin_ind != UNDEFINED_BIN_IND; + if (existing) { + bin = get_bin(tab->bins, get_size_ind(tab), bin_ind) - ENTRY_BASE; + entry = &entries[bin]; + } } if (existing) { key = entry->key; @@ -1424,7 +1424,7 @@ st_update(st_table *tab, st_data_t key, switch (retval) { case ST_CONTINUE: if (! existing) { - st_add_direct_with_hash(tab, key, value, hash); + st_add_direct_with_hash(tab, key, value, hash); break; } if (old_key != key) { @@ -1434,11 +1434,11 @@ st_update(st_table *tab, st_data_t key, break; case ST_DELETE: if (existing) { - if (bin_ind != UNDEFINED_BIN_IND) - MARK_BIN_DELETED(tab, bin_ind); + if (bin_ind != UNDEFINED_BIN_IND) + MARK_BIN_DELETED(tab, bin_ind); MARK_ENTRY_DELETED(entry); - tab->num_entries--; - update_range_for_deleted(tab, bin); + tab->num_entries--; + update_range_for_deleted(tab, bin); } break; } @@ -1455,7 +1455,7 @@ st_update(st_table *tab, st_data_t key, during traversing. */ static inline int st_general_foreach(st_table *tab, st_foreach_check_callback_func *func, st_update_callback_func *replace, st_data_t arg, - int check_p) + int check_p) { st_index_t bin; st_index_t bin_ind; @@ -1471,12 +1471,12 @@ st_general_foreach(st_table *tab, st_foreach_check_callback_func *func, st_updat the table, e.g. by an entry insertion. */ for (i = tab->entries_start; i < tab->entries_bound; i++) { curr_entry_ptr = &entries[i]; - if (EXPECT(DELETED_ENTRY_P(curr_entry_ptr), 0)) - continue; - key = curr_entry_ptr->key; - rebuilds_num = tab->rebuilds_num; - hash = curr_entry_ptr->hash; - retval = (*func)(key, curr_entry_ptr->record, arg, 0); + if (EXPECT(DELETED_ENTRY_P(curr_entry_ptr), 0)) + continue; + key = curr_entry_ptr->key; + rebuilds_num = tab->rebuilds_num; + hash = curr_entry_ptr->hash; + retval = (*func)(key, curr_entry_ptr->record, arg, 0); if (retval == ST_REPLACE && replace) { st_data_t value; @@ -1486,44 +1486,44 @@ st_general_foreach(st_table *tab, st_foreach_check_callback_func *func, st_updat curr_entry_ptr->record = value; } - if (rebuilds_num != tab->rebuilds_num) { - retry: - entries = tab->entries; - packed_p = tab->bins == NULL; - if (packed_p) { - i = find_entry(tab, hash, key); - if (EXPECT(i == REBUILT_TABLE_ENTRY_IND, 0)) - goto retry; - error_p = i == UNDEFINED_ENTRY_IND; - } - else { - i = find_table_entry_ind(tab, hash, key); - if (EXPECT(i == REBUILT_TABLE_ENTRY_IND, 0)) - goto retry; - error_p = i == UNDEFINED_ENTRY_IND; - i -= ENTRY_BASE; - } - if (error_p && check_p) { - /* call func with error notice */ - retval = (*func)(0, 0, arg, 1); - return 1; - } - curr_entry_ptr = &entries[i]; - } - switch (retval) { + if (rebuilds_num != tab->rebuilds_num) { + retry: + entries = tab->entries; + packed_p = tab->bins == NULL; + if (packed_p) { + i = find_entry(tab, hash, key); + if (EXPECT(i == REBUILT_TABLE_ENTRY_IND, 0)) + goto retry; + error_p = i == UNDEFINED_ENTRY_IND; + } + else { + i = find_table_entry_ind(tab, hash, key); + if (EXPECT(i == REBUILT_TABLE_ENTRY_IND, 0)) + goto retry; + error_p = i == UNDEFINED_ENTRY_IND; + i -= ENTRY_BASE; + } + if (error_p && check_p) { + /* call func with error notice */ + retval = (*func)(0, 0, arg, 1); + return 1; + } + curr_entry_ptr = &entries[i]; + } + switch (retval) { case ST_REPLACE: break; - case ST_CONTINUE: + case ST_CONTINUE: break; - case ST_CHECK: + case ST_CHECK: if (check_p) break; - case ST_STOP: + case ST_STOP: return 0; - case ST_DELETE: { + case ST_DELETE: { st_data_t key = curr_entry_ptr->key; - again: + again: if (packed_p) { bin = find_entry(tab, hash, key); if (EXPECT(bin == REBUILT_TABLE_ENTRY_IND, 0)) @@ -1545,8 +1545,8 @@ st_general_foreach(st_table *tab, st_foreach_check_callback_func *func, st_updat tab->num_entries--; update_range_for_deleted(tab, bin); break; - } - } + } + } } return 0; } @@ -1597,12 +1597,12 @@ st_general_keys(st_table *tab, st_data_t *keys, st_index_t size) keys_start = keys; keys_end = keys + size; for (i = tab->entries_start; i < bound; i++) { - if (keys == keys_end) - break; - curr_entry_ptr = &entries[i]; - key = curr_entry_ptr->key; + if (keys == keys_end) + break; + curr_entry_ptr = &entries[i]; + key = curr_entry_ptr->key; if (! DELETED_ENTRY_P(curr_entry_ptr)) - *keys++ = key; + *keys++ = key; } return keys - keys_start; @@ -1635,11 +1635,11 @@ st_general_values(st_table *tab, st_data_t *values, st_index_t size) values_end = values + size; bound = tab->entries_bound; for (i = tab->entries_start; i < bound; i++) { - if (values == values_end) - break; + if (values == values_end) + break; curr_entry_ptr = &entries[i]; if (! DELETED_ENTRY_P(curr_entry_ptr)) - *values++ = curr_entry_ptr->record; + *values++ = curr_entry_ptr->record; } return values - values_start; @@ -1654,7 +1654,7 @@ st_values(st_table *tab, st_data_t *values, st_index_t size) /* See comments for function st_delete_safe. */ st_index_t st_values_check(st_table *tab, st_data_t *values, st_index_t size, - st_data_t never ATTRIBUTE_UNUSED) + st_data_t never ATTRIBUTE_UNUSED) { return st_general_values(tab, values, size); } @@ -1770,87 +1770,87 @@ st_hash(const void *ptr, size_t len, st_index_t h) #undef SKIP_TAIL if (len >= sizeof(st_index_t)) { #if !UNALIGNED_WORD_ACCESS - int align = (int)((st_data_t)data % sizeof(st_index_t)); - if (align) { - st_index_t d = 0; - int sl, sr, pack; + int align = (int)((st_data_t)data % sizeof(st_index_t)); + if (align) { + st_index_t d = 0; + int sl, sr, pack; - switch (align) { + switch (align) { #ifdef WORDS_BIGENDIAN # define UNALIGNED_ADD(n) case SIZEOF_ST_INDEX_T - (n) - 1: \ - t |= data_at(n) << CHAR_BIT*(SIZEOF_ST_INDEX_T - (n) - 2) + t |= data_at(n) << CHAR_BIT*(SIZEOF_ST_INDEX_T - (n) - 2) #else # define UNALIGNED_ADD(n) case SIZEOF_ST_INDEX_T - (n) - 1: \ - t |= data_at(n) << CHAR_BIT*(n) + t |= data_at(n) << CHAR_BIT*(n) #endif - UNALIGNED_ADD_ALL; + UNALIGNED_ADD_ALL; #undef UNALIGNED_ADD - } + } #ifdef WORDS_BIGENDIAN - t >>= (CHAR_BIT * align) - CHAR_BIT; + t >>= (CHAR_BIT * align) - CHAR_BIT; #else - t <<= (CHAR_BIT * align); + t <<= (CHAR_BIT * align); #endif - data += sizeof(st_index_t)-align; - len -= sizeof(st_index_t)-align; + data += sizeof(st_index_t)-align; + len -= sizeof(st_index_t)-align; - sl = CHAR_BIT * (SIZEOF_ST_INDEX_T-align); - sr = CHAR_BIT * align; + sl = CHAR_BIT * (SIZEOF_ST_INDEX_T-align); + sr = CHAR_BIT * align; - while (len >= sizeof(st_index_t)) { - d = *(st_index_t *)data; + while (len >= sizeof(st_index_t)) { + d = *(st_index_t *)data; #ifdef WORDS_BIGENDIAN - t = (t << sr) | (d >> sl); + t = (t << sr) | (d >> sl); #else - t = (t >> sr) | (d << sl); + t = (t >> sr) | (d << sl); #endif - h = murmur_step(h, t); - t = d; - data += sizeof(st_index_t); - len -= sizeof(st_index_t); - } + h = murmur_step(h, t); + t = d; + data += sizeof(st_index_t); + len -= sizeof(st_index_t); + } - pack = len < (size_t)align ? (int)len : align; - d = 0; - switch (pack) { + pack = len < (size_t)align ? (int)len : align; + d = 0; + switch (pack) { #ifdef WORDS_BIGENDIAN # define UNALIGNED_ADD(n) case (n) + 1: \ - d |= data_at(n) << CHAR_BIT*(SIZEOF_ST_INDEX_T - (n) - 1) + d |= data_at(n) << CHAR_BIT*(SIZEOF_ST_INDEX_T - (n) - 1) #else # define UNALIGNED_ADD(n) case (n) + 1: \ - d |= data_at(n) << CHAR_BIT*(n) + d |= data_at(n) << CHAR_BIT*(n) #endif - UNALIGNED_ADD_ALL; + UNALIGNED_ADD_ALL; #undef UNALIGNED_ADD - } + } #ifdef WORDS_BIGENDIAN - t = (t << sr) | (d >> sl); + t = (t << sr) | (d >> sl); #else - t = (t >> sr) | (d << sl); + t = (t >> sr) | (d << sl); #endif - if (len < (size_t)align) goto skip_tail; + if (len < (size_t)align) goto skip_tail; # define SKIP_TAIL 1 - h = murmur_step(h, t); - data += pack; - len -= pack; - } - else + h = murmur_step(h, t); + data += pack; + len -= pack; + } + else #endif #ifdef HAVE_BUILTIN___BUILTIN_ASSUME_ALIGNED #define aligned_data __builtin_assume_aligned(data, sizeof(st_index_t)) #else #define aligned_data data #endif - { - do { - h = murmur_step(h, *(st_index_t *)aligned_data); - data += sizeof(st_index_t); - len -= sizeof(st_index_t); - } while (len >= sizeof(st_index_t)); - } + { + do { + h = murmur_step(h, *(st_index_t *)aligned_data); + data += sizeof(st_index_t); + len -= sizeof(st_index_t); + } while (len >= sizeof(st_index_t)); + } } t = 0; @@ -1862,8 +1862,8 @@ st_hash(const void *ptr, size_t len, st_index_t h) case 6: t |= data_at(5) << 40; case 5: t |= data_at(4) << 32; case 4: - t |= (st_index_t)*(uint32_t*)aligned_data; - goto skip_tail; + t |= (st_index_t)*(uint32_t*)aligned_data; + goto skip_tail; # define SKIP_TAIL 1 #endif case 3: t |= data_at(2) << 16; @@ -1872,19 +1872,19 @@ st_hash(const void *ptr, size_t len, st_index_t h) #else #ifdef WORDS_BIGENDIAN # define UNALIGNED_ADD(n) case (n) + 1: \ - t |= data_at(n) << CHAR_BIT*(SIZEOF_ST_INDEX_T - (n) - 1) + t |= data_at(n) << CHAR_BIT*(SIZEOF_ST_INDEX_T - (n) - 1) #else # define UNALIGNED_ADD(n) case (n) + 1: \ - t |= data_at(n) << CHAR_BIT*(n) + t |= data_at(n) << CHAR_BIT*(n) #endif - UNALIGNED_ADD_ALL; + UNALIGNED_ADD_ALL; #undef UNALIGNED_ADD #endif #ifdef SKIP_TAIL skip_tail: #endif - h ^= t; h -= ROTL(t, 7); - h *= C2; + h ^= t; h -= ROTL(t, 7); + h *= C2; } h ^= l; #undef aligned_data @@ -2010,12 +2010,12 @@ strcasehash(st_data_t arg) * FNV-1a hash each octet in the buffer */ while (*string) { - unsigned int c = (unsigned char)*string++; - if ((unsigned int)(c - 'A') <= ('Z' - 'A')) c += 'a' - 'A'; - hval ^= c; + unsigned int c = (unsigned char)*string++; + if ((unsigned int)(c - 'A') <= ('Z' - 'A')) c += 'a' - 'A'; + hval ^= c; - /* multiply by the 32 bit FNV magic prime mod 2^32 */ - hval *= FNV_32_PRIME; + /* multiply by the 32 bit FNV magic prime mod 2^32 */ + hval *= FNV_32_PRIME; } return hval; } @@ -2082,10 +2082,10 @@ st_rehash_linear(st_table *tab) q = &tab->entries[j]; if (DELETED_ENTRY_P(q)) continue; - DO_PTR_EQUAL_CHECK(tab, p, q->hash, q->key, eq_p, rebuilt_p); - if (EXPECT(rebuilt_p, 0)) - return TRUE; - if (eq_p) { + DO_PTR_EQUAL_CHECK(tab, p, q->hash, q->key, eq_p, rebuilt_p); + if (EXPECT(rebuilt_p, 0)) + return TRUE; + if (eq_p) { *p = *q; MARK_ENTRY_DELETED(q); tab->num_entries--; @@ -2130,27 +2130,27 @@ st_rehash_indexed(st_table *tab) } else { st_table_entry *q = &tab->entries[bin - ENTRY_BASE]; - DO_PTR_EQUAL_CHECK(tab, q, p->hash, p->key, eq_p, rebuilt_p); - if (EXPECT(rebuilt_p, 0)) - return TRUE; - if (eq_p) { - /* duplicated key; delete it */ - q->record = p->record; - MARK_ENTRY_DELETED(p); - tab->num_entries--; - update_range_for_deleted(tab, bin); - break; - } - else { - /* hash collision; skip it */ + DO_PTR_EQUAL_CHECK(tab, q, p->hash, p->key, eq_p, rebuilt_p); + if (EXPECT(rebuilt_p, 0)) + return TRUE; + if (eq_p) { + /* duplicated key; delete it */ + q->record = p->record; + MARK_ENTRY_DELETED(p); + tab->num_entries--; + update_range_for_deleted(tab, bin); + break; + } + else { + /* hash collision; skip it */ #ifdef QUADRATIC_PROBE - ind = hash_bin(ind + d, tab); - d++; + ind = hash_bin(ind + d, tab); + d++; #else - ind = secondary_hash(ind, tab, &peterb); + ind = secondary_hash(ind, tab, &peterb); #endif - } - } + } + } } } return FALSE; @@ -2165,10 +2165,10 @@ st_rehash(st_table *tab) int rebuilt_p; do { - if (tab->bin_power <= MAX_POWER2_FOR_TABLES_WITHOUT_BINS) - rebuilt_p = st_rehash_linear(tab); - else - rebuilt_p = st_rehash_indexed(tab); + if (tab->bin_power <= MAX_POWER2_FOR_TABLES_WITHOUT_BINS) + rebuilt_p = st_rehash_linear(tab); + else + rebuilt_p = st_rehash_indexed(tab); } while (rebuilt_p); } diff --git a/string.c b/string.c index 72f6dbd67c..f3f5ea92cc 100644 --- a/string.c +++ b/string.c @@ -132,21 +132,21 @@ VALUE rb_cSymbol; #define STR_SET_LEN(str, n) do { \ if (STR_EMBED_P(str)) {\ - STR_SET_EMBED_LEN((str), (n));\ + STR_SET_EMBED_LEN((str), (n));\ }\ else {\ - RSTRING(str)->as.heap.len = (n);\ + RSTRING(str)->as.heap.len = (n);\ }\ } while (0) #define STR_DEC_LEN(str) do {\ if (STR_EMBED_P(str)) {\ - long n = RSTRING_LEN(str);\ - n--;\ - STR_SET_EMBED_LEN((str), n);\ + long n = RSTRING_LEN(str);\ + n--;\ + STR_SET_EMBED_LEN((str), n);\ }\ else {\ - RSTRING(str)->as.heap.len--;\ + RSTRING(str)->as.heap.len--;\ }\ } while (0) @@ -170,7 +170,7 @@ str_enc_fastpath(VALUE str) const int term_fill_len = (termlen);\ *term_fill_ptr = '\0';\ if (UNLIKELY(term_fill_len > 1))\ - memset(term_fill_ptr, 0, term_fill_len);\ + memset(term_fill_ptr, 0, term_fill_len);\ } while (0) #define RESIZE_CAPA(str,capacity) do {\ @@ -179,21 +179,21 @@ str_enc_fastpath(VALUE str) } while (0) #define RESIZE_CAPA_TERM(str,capacity,termlen) do {\ if (STR_EMBED_P(str)) {\ - if (str_embed_capa(str) < capacity + termlen) {\ - char *const tmp = ALLOC_N(char, (size_t)(capacity) + (termlen));\ - const long tlen = RSTRING_LEN(str);\ - memcpy(tmp, RSTRING_PTR(str), tlen);\ - RSTRING(str)->as.heap.ptr = tmp;\ - RSTRING(str)->as.heap.len = tlen;\ + if (str_embed_capa(str) < capacity + termlen) {\ + char *const tmp = ALLOC_N(char, (size_t)(capacity) + (termlen));\ + const long tlen = RSTRING_LEN(str);\ + memcpy(tmp, RSTRING_PTR(str), tlen);\ + RSTRING(str)->as.heap.ptr = tmp;\ + RSTRING(str)->as.heap.len = tlen;\ STR_SET_NOEMBED(str);\ - RSTRING(str)->as.heap.aux.capa = (capacity);\ - }\ + RSTRING(str)->as.heap.aux.capa = (capacity);\ + }\ }\ else {\ - assert(!FL_TEST((str), STR_SHARED)); \ - SIZED_REALLOC_N(RSTRING(str)->as.heap.ptr, char, \ - (size_t)(capacity) + (termlen), STR_HEAP_SIZE(str)); \ - RSTRING(str)->as.heap.aux.capa = (capacity);\ + assert(!FL_TEST((str), STR_SHARED)); \ + SIZED_REALLOC_N(RSTRING(str)->as.heap.ptr, char, \ + (size_t)(capacity) + (termlen), STR_HEAP_SIZE(str)); \ + RSTRING(str)->as.heap.aux.capa = (capacity);\ }\ } while (0) @@ -201,11 +201,11 @@ str_enc_fastpath(VALUE str) if (!FL_TEST(str, STR_FAKESTR)) { \ assert(RSTRING_PTR(shared_str) <= RSTRING_PTR(str)); \ assert(RSTRING_PTR(str) <= RSTRING_PTR(shared_str) + RSTRING_LEN(shared_str)); \ - RB_OBJ_WRITE((str), &RSTRING(str)->as.heap.aux.shared, (shared_str)); \ - FL_SET((str), STR_SHARED); \ + RB_OBJ_WRITE((str), &RSTRING(str)->as.heap.aux.shared, (shared_str)); \ + FL_SET((str), STR_SHARED); \ FL_SET((shared_str), STR_SHARED_ROOT); \ - if (RBASIC_CLASS((shared_str)) == 0) /* for CoW-friendliness */ \ - FL_SET_RAW((shared_str), STR_BORROWED); \ + if (RBASIC_CLASS((shared_str)) == 0) /* for CoW-friendliness */ \ + FL_SET_RAW((shared_str), STR_BORROWED); \ } \ } while (0) @@ -349,7 +349,7 @@ rb_debug_rstring_null_ptr(const char *func) "SIGSEGV is highly expected to follow immediately.\n" "If you could reproduce, attach your debugger here, " "and look at the passed string.\n", - func); + func); } /* symbols for [up|down|swap]case/capitalize options */ @@ -362,25 +362,25 @@ get_actual_encoding(const int encidx, VALUE str) switch (encidx) { case ENCINDEX_UTF_16: - if (RSTRING_LEN(str) < 2) break; - q = (const unsigned char *)RSTRING_PTR(str); - if (q[0] == 0xFE && q[1] == 0xFF) { - return rb_enc_get_from_index(ENCINDEX_UTF_16BE); - } - if (q[0] == 0xFF && q[1] == 0xFE) { - return rb_enc_get_from_index(ENCINDEX_UTF_16LE); - } - return rb_ascii8bit_encoding(); + if (RSTRING_LEN(str) < 2) break; + q = (const unsigned char *)RSTRING_PTR(str); + if (q[0] == 0xFE && q[1] == 0xFF) { + return rb_enc_get_from_index(ENCINDEX_UTF_16BE); + } + if (q[0] == 0xFF && q[1] == 0xFE) { + return rb_enc_get_from_index(ENCINDEX_UTF_16LE); + } + return rb_ascii8bit_encoding(); case ENCINDEX_UTF_32: - if (RSTRING_LEN(str) < 4) break; - q = (const unsigned char *)RSTRING_PTR(str); - if (q[0] == 0 && q[1] == 0 && q[2] == 0xFE && q[3] == 0xFF) { - return rb_enc_get_from_index(ENCINDEX_UTF_32BE); - } - if (q[3] == 0 && q[2] == 0 && q[1] == 0xFE && q[0] == 0xFF) { - return rb_enc_get_from_index(ENCINDEX_UTF_32LE); - } - return rb_ascii8bit_encoding(); + if (RSTRING_LEN(str) < 4) break; + q = (const unsigned char *)RSTRING_PTR(str); + if (q[0] == 0 && q[1] == 0 && q[2] == 0xFE && q[3] == 0xFF) { + return rb_enc_get_from_index(ENCINDEX_UTF_32BE); + } + if (q[3] == 0 && q[2] == 0 && q[1] == 0xFE && q[0] == 0xFF) { + return rb_enc_get_from_index(ENCINDEX_UTF_32LE); + } + return rb_ascii8bit_encoding(); } return rb_enc_from_index(encidx); } @@ -395,7 +395,7 @@ static void mustnot_broken(VALUE str) { if (is_broken_string(str)) { - rb_raise(rb_eArgError, "invalid byte sequence in %s", rb_enc_name(STR_ENC_GET(str))); + rb_raise(rb_eArgError, "invalid byte sequence in %s", rb_enc_name(STR_ENC_GET(str))); } } @@ -404,7 +404,7 @@ mustnot_wchar(VALUE str) { rb_encoding *enc = STR_ENC_GET(str); if (rb_enc_mbminlen(enc) > 1) { - rb_raise(rb_eArgError, "wide char encoding: %s", rb_enc_name(enc)); + rb_raise(rb_eArgError, "wide char encoding: %s", rb_enc_name(enc)); } } @@ -432,47 +432,47 @@ fstr_update_callback(st_data_t *key, st_data_t *value, st_data_t data, int exist VALUE str = (VALUE)*key; if (existing) { - /* because of lazy sweep, str may be unmarked already and swept - * at next time */ + /* because of lazy sweep, str may be unmarked already and swept + * at next time */ - if (rb_objspace_garbage_object_p(str)) { - arg->fstr = Qundef; - return ST_DELETE; - } + if (rb_objspace_garbage_object_p(str)) { + arg->fstr = Qundef; + return ST_DELETE; + } - arg->fstr = str; - return ST_STOP; + arg->fstr = str; + return ST_STOP; } else { - if (FL_TEST_RAW(str, STR_FAKESTR)) { - if (arg->copy) { - VALUE new_str = str_new(rb_cString, RSTRING(str)->as.heap.ptr, RSTRING(str)->as.heap.len); - rb_enc_copy(new_str, str); - str = new_str; - } - else { - str = str_new_static(rb_cString, RSTRING(str)->as.heap.ptr, - RSTRING(str)->as.heap.len, - ENCODING_GET(str)); - } - OBJ_FREEZE_RAW(str); - } - else { - if (!OBJ_FROZEN(str)) - str = str_new_frozen(rb_cString, str); - if (STR_SHARED_P(str)) { /* str should not be shared */ - /* shared substring */ + if (FL_TEST_RAW(str, STR_FAKESTR)) { + if (arg->copy) { + VALUE new_str = str_new(rb_cString, RSTRING(str)->as.heap.ptr, RSTRING(str)->as.heap.len); + rb_enc_copy(new_str, str); + str = new_str; + } + else { + str = str_new_static(rb_cString, RSTRING(str)->as.heap.ptr, + RSTRING(str)->as.heap.len, + ENCODING_GET(str)); + } + OBJ_FREEZE_RAW(str); + } + else { + if (!OBJ_FROZEN(str)) + str = str_new_frozen(rb_cString, str); + if (STR_SHARED_P(str)) { /* str should not be shared */ + /* shared substring */ str_make_independent(str); - assert(OBJ_FROZEN(str)); - } - if (!BARE_STRING_P(str)) { - str = str_new_frozen(rb_cString, str); - } - } - RBASIC(str)->flags |= RSTRING_FSTR; + assert(OBJ_FROZEN(str)); + } + if (!BARE_STRING_P(str)) { + str = str_new_frozen(rb_cString, str); + } + } + RBASIC(str)->flags |= RSTRING_FSTR; - *key = *value = arg->fstr = str; - return ST_CONTINUE; + *key = *value = arg->fstr = str; + return ST_CONTINUE; } } @@ -486,7 +486,7 @@ rb_fstring(VALUE str) Check_Type(str, T_STRING); if (FL_TEST(str, RSTRING_FSTR)) - return str; + return str; bare = BARE_STRING_P(str); if (!bare) { @@ -506,9 +506,9 @@ rb_fstring(VALUE str) fstr = register_fstring(str, FALSE); if (!bare) { - str_replace_shared_without_enc(str, fstr); - OBJ_FREEZE_RAW(str); - return str; + str_replace_shared_without_enc(str, fstr); + OBJ_FREEZE_RAW(str); + return str; } return fstr; } @@ -543,8 +543,8 @@ setup_fake_str(struct RString *fake_str, const char *name, long len, int encidx) /* SHARED to be allocated by the callback */ if (!name) { - RUBY_ASSERT_ALWAYS(len == 0); - name = ""; + RUBY_ASSERT_ALWAYS(len == 0); + name = ""; } ENCODING_SET_INLINED((VALUE)fake_str, encidx); @@ -605,8 +605,8 @@ fstring_cmp(VALUE a, VALUE b) RSTRING_GETMEM(a, aptr, alen); RSTRING_GETMEM(b, bptr, blen); return (alen != blen || - ENCODING_GET(a) != ENCODING_GET(b) || - memcmp(aptr, bptr, alen) != 0); + ENCODING_GET(a) != ENCODING_GET(b) || + memcmp(aptr, bptr, alen) != 0); } static inline int @@ -654,23 +654,23 @@ search_nonascii(const char *p, const char *e) if (UNALIGNED_WORD_ACCESS || e - p >= SIZEOF_VOIDP) { #if !UNALIGNED_WORD_ACCESS - if ((uintptr_t)p % SIZEOF_VOIDP) { - int l = SIZEOF_VOIDP - (uintptr_t)p % SIZEOF_VOIDP; - p += l; - switch (l) { - default: UNREACHABLE; + if ((uintptr_t)p % SIZEOF_VOIDP) { + int l = SIZEOF_VOIDP - (uintptr_t)p % SIZEOF_VOIDP; + p += l; + switch (l) { + default: UNREACHABLE; #if SIZEOF_VOIDP > 4 - case 7: if (p[-7]&0x80) return p-7; - case 6: if (p[-6]&0x80) return p-6; - case 5: if (p[-5]&0x80) return p-5; - case 4: if (p[-4]&0x80) return p-4; + case 7: if (p[-7]&0x80) return p-7; + case 6: if (p[-6]&0x80) return p-6; + case 5: if (p[-5]&0x80) return p-5; + case 4: if (p[-4]&0x80) return p-4; #endif - case 3: if (p[-3]&0x80) return p-3; - case 2: if (p[-2]&0x80) return p-2; - case 1: if (p[-1]&0x80) return p-1; - case 0: break; - } - } + case 3: if (p[-3]&0x80) return p-3; + case 2: if (p[-2]&0x80) return p-2; + case 1: if (p[-1]&0x80) return p-1; + case 0: break; + } + } #endif #if defined(HAVE_BUILTIN___BUILTIN_ASSUME_ALIGNED) &&! UNALIGNED_WORD_ACCESS #define aligned_ptr(value) \ @@ -678,19 +678,19 @@ search_nonascii(const char *p, const char *e) #else #define aligned_ptr(value) (uintptr_t *)(value) #endif - s = aligned_ptr(p); - t = (uintptr_t *)(e - (SIZEOF_VOIDP-1)); + s = aligned_ptr(p); + t = (uintptr_t *)(e - (SIZEOF_VOIDP-1)); #undef aligned_ptr - for (;s < t; s++) { - if (*s & NONASCII_MASK) { + for (;s < t; s++) { + if (*s & NONASCII_MASK) { #ifdef WORDS_BIGENDIAN - return (const char *)s + (nlz_intptr(*s&NONASCII_MASK)>>3); + return (const char *)s + (nlz_intptr(*s&NONASCII_MASK)>>3); #else - return (const char *)s + (ntz_intptr(*s&NONASCII_MASK)>>3); + return (const char *)s + (ntz_intptr(*s&NONASCII_MASK)>>3); #endif - } - } - p = (const char *)s; + } + } + p = (const char *)s; } switch (e - p) { @@ -747,42 +747,42 @@ rb_str_coderange_scan_restartable(const char *s, const char *e, rb_encoding *enc const char *p = s; if (*cr == ENC_CODERANGE_BROKEN) - return e - s; + return e - s; if (rb_enc_to_index(enc) == rb_ascii8bit_encindex()) { - /* enc is ASCII-8BIT. ASCII-8BIT string never be broken. */ - if (*cr == ENC_CODERANGE_VALID) return e - s; - p = search_nonascii(p, e); + /* enc is ASCII-8BIT. ASCII-8BIT string never be broken. */ + if (*cr == ENC_CODERANGE_VALID) return e - s; + p = search_nonascii(p, e); *cr = p ? ENC_CODERANGE_VALID : ENC_CODERANGE_7BIT; - return e - s; + return e - s; } else if (rb_enc_asciicompat(enc)) { - p = search_nonascii(p, e); - if (!p) { - if (*cr != ENC_CODERANGE_VALID) *cr = ENC_CODERANGE_7BIT; - return e - s; - } - for (;;) { - int ret = rb_enc_precise_mbclen(p, e, enc); - if (!MBCLEN_CHARFOUND_P(ret)) { - *cr = MBCLEN_INVALID_P(ret) ? ENC_CODERANGE_BROKEN: ENC_CODERANGE_UNKNOWN; - return p - s; - } - p += MBCLEN_CHARFOUND_LEN(ret); - if (p == e) break; - p = search_nonascii(p, e); - if (!p) break; - } + p = search_nonascii(p, e); + if (!p) { + if (*cr != ENC_CODERANGE_VALID) *cr = ENC_CODERANGE_7BIT; + return e - s; + } + for (;;) { + int ret = rb_enc_precise_mbclen(p, e, enc); + if (!MBCLEN_CHARFOUND_P(ret)) { + *cr = MBCLEN_INVALID_P(ret) ? ENC_CODERANGE_BROKEN: ENC_CODERANGE_UNKNOWN; + return p - s; + } + p += MBCLEN_CHARFOUND_LEN(ret); + if (p == e) break; + p = search_nonascii(p, e); + if (!p) break; + } } else { - while (p < e) { - int ret = rb_enc_precise_mbclen(p, e, enc); - if (!MBCLEN_CHARFOUND_P(ret)) { - *cr = MBCLEN_INVALID_P(ret) ? ENC_CODERANGE_BROKEN: ENC_CODERANGE_UNKNOWN; - return p - s; - } - p += MBCLEN_CHARFOUND_LEN(ret); - } + while (p < e) { + int ret = rb_enc_precise_mbclen(p, e, enc); + if (!MBCLEN_CHARFOUND_P(ret)) { + *cr = MBCLEN_INVALID_P(ret) ? ENC_CODERANGE_BROKEN: ENC_CODERANGE_UNKNOWN; + return p - s; + } + p += MBCLEN_CHARFOUND_LEN(ret); + } } *cr = ENC_CODERANGE_VALID; return e - s; @@ -802,25 +802,25 @@ rb_enc_cr_str_copy_for_substr(VALUE dest, VALUE src) */ str_enc_copy(dest, src); if (RSTRING_LEN(dest) == 0) { - if (!rb_enc_asciicompat(STR_ENC_GET(src))) - ENC_CODERANGE_SET(dest, ENC_CODERANGE_VALID); - else - ENC_CODERANGE_SET(dest, ENC_CODERANGE_7BIT); - return; + if (!rb_enc_asciicompat(STR_ENC_GET(src))) + ENC_CODERANGE_SET(dest, ENC_CODERANGE_VALID); + else + ENC_CODERANGE_SET(dest, ENC_CODERANGE_7BIT); + return; } switch (ENC_CODERANGE(src)) { case ENC_CODERANGE_7BIT: - ENC_CODERANGE_SET(dest, ENC_CODERANGE_7BIT); - break; + ENC_CODERANGE_SET(dest, ENC_CODERANGE_7BIT); + break; case ENC_CODERANGE_VALID: - if (!rb_enc_asciicompat(STR_ENC_GET(src)) || - search_nonascii(RSTRING_PTR(dest), RSTRING_END(dest))) - ENC_CODERANGE_SET(dest, ENC_CODERANGE_VALID); - else - ENC_CODERANGE_SET(dest, ENC_CODERANGE_7BIT); - break; + if (!rb_enc_asciicompat(STR_ENC_GET(src)) || + search_nonascii(RSTRING_PTR(dest), RSTRING_END(dest))) + ENC_CODERANGE_SET(dest, ENC_CODERANGE_VALID); + else + ENC_CODERANGE_SET(dest, ENC_CODERANGE_7BIT); + break; default: - break; + break; } } @@ -835,11 +835,11 @@ static int enc_coderange_scan(VALUE str, rb_encoding *enc, int encidx) { if (rb_enc_mbminlen(enc) > 1 && rb_enc_dummy_p(enc) && - rb_enc_mbminlen(enc = get_actual_encoding(encidx, str)) == 1) { - return ENC_CODERANGE_BROKEN; + rb_enc_mbminlen(enc = get_actual_encoding(encidx, str)) == 1) { + return ENC_CODERANGE_BROKEN; } else { - return coderange_scan(RSTRING_PTR(str), RSTRING_LEN(str), enc); + return coderange_scan(RSTRING_PTR(str), RSTRING_LEN(str), enc); } } @@ -855,9 +855,9 @@ rb_enc_str_coderange(VALUE str) int cr = ENC_CODERANGE(str); if (cr == ENC_CODERANGE_UNKNOWN) { - int encidx = ENCODING_GET(str); - rb_encoding *enc = rb_enc_from_index(encidx); - cr = enc_coderange_scan(str, enc, encidx); + int encidx = ENCODING_GET(str); + rb_encoding *enc = rb_enc_from_index(encidx); + cr = enc_coderange_scan(str, enc, encidx); ENC_CODERANGE_SET(str, cr); } return cr; @@ -879,7 +879,7 @@ static inline void str_mod_check(VALUE s, const char *p, long len) { if (RSTRING_PTR(s) != p || RSTRING_LEN(s) != len){ - rb_raise(rb_eRuntimeError, "string modified"); + rb_raise(rb_eRuntimeError, "string modified"); } } @@ -890,14 +890,14 @@ str_capacity(VALUE str, const int termlen) #if USE_RVARGC return str_embed_capa(str) - termlen; #else - return (RSTRING_EMBED_LEN_MAX + 1 - termlen); + return (RSTRING_EMBED_LEN_MAX + 1 - termlen); #endif } else if (FL_TEST(str, STR_SHARED|STR_NOFREE)) { - return RSTRING(str)->as.heap.len; + return RSTRING(str)->as.heap.len; } else { - return RSTRING(str)->as.heap.aux.capa; + return RSTRING(str)->as.heap.aux.capa; } } @@ -911,7 +911,7 @@ static inline void must_not_null(const char *ptr) { if (!ptr) { - rb_raise(rb_eArgError, "NULL pointer given"); + rb_raise(rb_eArgError, "NULL pointer given"); } } @@ -956,7 +956,7 @@ str_new0(VALUE klass, const char *ptr, long len, int termlen) VALUE str; if (len < 0) { - rb_raise(rb_eArgError, "negative string size (or size too big)"); + rb_raise(rb_eArgError, "negative string size (or size too big)"); } RUBY_DTRACE_CREATE_HOOK(STRING, len); @@ -969,16 +969,16 @@ str_new0(VALUE klass, const char *ptr, long len, int termlen) } else { str = str_alloc_heap(klass); - RSTRING(str)->as.heap.aux.capa = len; + RSTRING(str)->as.heap.aux.capa = len; /* :FIXME: @shyouhei guesses `len + termlen` is guaranteed to never * integer overflow. If we can STATIC_ASSERT that, the following * mul_add_mul can be reverted to a simple ALLOC_N. */ RSTRING(str)->as.heap.ptr = rb_xmalloc_mul_add_mul(sizeof(char), len, sizeof(char), termlen); - STR_SET_NOEMBED(str); + STR_SET_NOEMBED(str); } if (ptr) { - memcpy(RSTRING_PTR(str), ptr, len); + memcpy(RSTRING_PTR(str), ptr, len); } STR_SET_LEN(str, len); TERM_FILL(RSTRING_PTR(str) + len, termlen); @@ -1058,7 +1058,7 @@ rb_enc_str_new_cstr(const char *ptr, rb_encoding *enc) { must_not_null(ptr); if (rb_enc_mbminlen(enc) != 1) { - rb_raise(rb_eArgError, "wchar encoding given"); + rb_raise(rb_eArgError, "wchar encoding given"); } return rb_enc_str_new(ptr, strlen(ptr), enc); } @@ -1069,21 +1069,21 @@ str_new_static(VALUE klass, const char *ptr, long len, int encindex) VALUE str; if (len < 0) { - rb_raise(rb_eArgError, "negative string size (or size too big)"); + rb_raise(rb_eArgError, "negative string size (or size too big)"); } if (!ptr) { - rb_encoding *enc = rb_enc_get_from_index(encindex); - str = str_new0(klass, ptr, len, rb_enc_mbminlen(enc)); + rb_encoding *enc = rb_enc_get_from_index(encindex); + str = str_new0(klass, ptr, len, rb_enc_mbminlen(enc)); } else { - RUBY_DTRACE_CREATE_HOOK(STRING, len); + RUBY_DTRACE_CREATE_HOOK(STRING, len); str = str_alloc_heap(klass); - RSTRING(str)->as.heap.len = len; - RSTRING(str)->as.heap.ptr = (char *)ptr; - RSTRING(str)->as.heap.aux.capa = len; - STR_SET_NOEMBED(str); - RBASIC(str)->flags |= STR_NOFREE; + RSTRING(str)->as.heap.len = len; + RSTRING(str)->as.heap.ptr = (char *)ptr; + RSTRING(str)->as.heap.aux.capa = len; + STR_SET_NOEMBED(str); + RBASIC(str)->flags |= STR_NOFREE; } rb_enc_associate_index(str, encindex); return str; @@ -1114,15 +1114,15 @@ rb_enc_str_new_static(const char *ptr, long len, rb_encoding *enc) } static VALUE str_cat_conv_enc_opts(VALUE newstr, long ofs, const char *ptr, long len, - rb_encoding *from, rb_encoding *to, - int ecflags, VALUE ecopts); + rb_encoding *from, rb_encoding *to, + int ecflags, VALUE ecopts); static inline bool is_enc_ascii_string(VALUE str, rb_encoding *enc) { int encidx = rb_enc_to_index(enc); if (rb_enc_get_index(str) == encidx) - return is_ascii_string(str); + return is_ascii_string(str); return enc_coderange_scan(str, enc, encidx) == ENC_CODERANGE_7BIT; } @@ -1137,27 +1137,27 @@ rb_str_conv_enc_opts(VALUE str, rb_encoding *from, rb_encoding *to, int ecflags, if (!from) from = rb_enc_get(str); if (from == to) return str; if ((rb_enc_asciicompat(to) && is_enc_ascii_string(str, from)) || - to == rb_ascii8bit_encoding()) { - if (STR_ENC_GET(str) != to) { - str = rb_str_dup(str); - rb_enc_associate(str, to); - } - return str; + to == rb_ascii8bit_encoding()) { + if (STR_ENC_GET(str) != to) { + str = rb_str_dup(str); + rb_enc_associate(str, to); + } + return str; } RSTRING_GETMEM(str, ptr, len); newstr = str_cat_conv_enc_opts(rb_str_buf_new(len), 0, ptr, len, - from, to, ecflags, ecopts); + from, to, ecflags, ecopts); if (NIL_P(newstr)) { - /* some error, return original */ - return str; + /* some error, return original */ + return str; } return newstr; } VALUE rb_str_cat_conv_enc_opts(VALUE newstr, long ofs, const char *ptr, long len, - rb_encoding *from, int ecflags, VALUE ecopts) + rb_encoding *from, int ecflags, VALUE ecopts) { long olen; @@ -1166,14 +1166,14 @@ rb_str_cat_conv_enc_opts(VALUE newstr, long ofs, const char *ptr, long len, rb_raise(rb_eIndexError, "index %ld out of string", ofs); if (ofs < 0) ofs += olen; if (!from) { - STR_SET_LEN(newstr, ofs); - return rb_str_cat(newstr, ptr, len); + STR_SET_LEN(newstr, ofs); + return rb_str_cat(newstr, ptr, len); } rb_str_modify(newstr); return str_cat_conv_enc_opts(newstr, ofs, ptr, len, from, - rb_enc_get(newstr), - ecflags, ecopts); + rb_enc_get(newstr), + ecflags, ecopts); } VALUE @@ -1187,8 +1187,8 @@ rb_str_initialize(VALUE str, const char *ptr, long len, rb_encoding *enc) static VALUE str_cat_conv_enc_opts(VALUE newstr, long ofs, const char *ptr, long len, - rb_encoding *from, rb_encoding *to, - int ecflags, VALUE ecopts) + rb_encoding *from, rb_encoding *to, + int ecflags, VALUE ecopts) { rb_econv_t *ec; rb_econv_result_t ret; @@ -1209,35 +1209,35 @@ str_cat_conv_enc_opts(VALUE newstr, long ofs, const char *ptr, long len, sp = (unsigned char*)ptr; start = sp; while ((dest = (unsigned char*)RSTRING_PTR(newstr)), - (dp = dest + converted_output), - (ret = rb_econv_convert(ec, &sp, start + len, &dp, dest + olen, 0)), - ret == econv_destination_buffer_full) { - /* destination buffer short */ - size_t converted_input = sp - start; - size_t rest = len - converted_input; - converted_output = dp - dest; - rb_str_set_len(newstr, converted_output); - if (converted_input && converted_output && - rest < (LONG_MAX / converted_output)) { - rest = (rest * converted_output) / converted_input; - } - else { - rest = olen; - } - olen += rest < 2 ? 2 : rest; - rb_str_resize(newstr, olen); + (dp = dest + converted_output), + (ret = rb_econv_convert(ec, &sp, start + len, &dp, dest + olen, 0)), + ret == econv_destination_buffer_full) { + /* destination buffer short */ + size_t converted_input = sp - start; + size_t rest = len - converted_input; + converted_output = dp - dest; + rb_str_set_len(newstr, converted_output); + if (converted_input && converted_output && + rest < (LONG_MAX / converted_output)) { + rest = (rest * converted_output) / converted_input; + } + else { + rest = olen; + } + olen += rest < 2 ? 2 : rest; + rb_str_resize(newstr, olen); } DATA_PTR(econv_wrapper) = 0; rb_econv_close(ec); switch (ret) { case econv_finished: - len = dp - (unsigned char*)RSTRING_PTR(newstr); - rb_str_set_len(newstr, len); - rb_enc_associate(newstr, to); - return newstr; + len = dp - (unsigned char*)RSTRING_PTR(newstr); + rb_str_set_len(newstr, len); + rb_enc_associate(newstr, to); + return newstr; default: - return Qnil; + return Qnil; } } @@ -1260,7 +1260,7 @@ rb_external_str_new_with_enc(const char *ptr, long len, rb_encoding *eenc) /* ASCII-8BIT case, no conversion */ if ((eidx == rb_ascii8bit_encindex()) || - (eidx == rb_usascii_encindex() && search_nonascii(ptr, ptr + len))) { + (eidx == rb_usascii_encindex() && search_nonascii(ptr, ptr + len))) { return rb_str_new(ptr, len); } /* no default_internal or same encoding, no conversion */ @@ -1271,8 +1271,8 @@ rb_external_str_new_with_enc(const char *ptr, long len, rb_encoding *eenc) /* ASCII compatible, and ASCII only string, no conversion in * default_internal */ if ((eidx == rb_ascii8bit_encindex()) || - (eidx == rb_usascii_encindex()) || - (rb_enc_asciicompat(eenc) && !search_nonascii(ptr, ptr + len))) { + (eidx == rb_usascii_encindex()) || + (rb_enc_asciicompat(eenc) && !search_nonascii(ptr, ptr + len))) { return rb_enc_str_new(ptr, len, ienc); } /* convert from the given encoding to default_internal */ @@ -1280,7 +1280,7 @@ rb_external_str_new_with_enc(const char *ptr, long len, rb_encoding *eenc) /* when the conversion failed for some reason, just ignore the * default_internal and result in the given encoding as-is. */ if (NIL_P(rb_str_cat_conv_enc_opts(str, 0, ptr, len, eenc, 0, Qnil))) { - rb_str_initialize(str, ptr, len, eenc); + rb_str_initialize(str, ptr, len, eenc); } return str; } @@ -1290,9 +1290,9 @@ rb_external_str_with_enc(VALUE str, rb_encoding *eenc) { int eidx = rb_enc_to_index(eenc); if (eidx == rb_usascii_encindex() && - !is_ascii_string(str)) { - rb_enc_associate_index(str, rb_ascii8bit_encindex()); - return str; + !is_ascii_string(str)) { + rb_enc_associate_index(str, rb_ascii8bit_encindex()); + return str; } rb_enc_associate_index(str, eidx); return rb_str_conv_enc(str, eenc, rb_default_internal_encoding()); @@ -1362,10 +1362,10 @@ str_replace_shared_without_enc(VALUE str2, VALUE str) RSTRING_GETMEM(str, ptr, len); if (str_embed_capa(str2) >= len + termlen) { char *ptr2 = RSTRING(str2)->as.embed.ary; - STR_SET_EMBED(str2); - memcpy(ptr2, RSTRING_PTR(str), len); - STR_SET_EMBED_LEN(str2, len); - TERM_FILL(ptr2+len, termlen); + STR_SET_EMBED(str2); + memcpy(ptr2, RSTRING_PTR(str), len); + STR_SET_EMBED_LEN(str2, len); + TERM_FILL(ptr2+len, termlen); } else { VALUE root; @@ -1387,9 +1387,9 @@ str_replace_shared_without_enc(VALUE str2, VALUE str) ruby_sized_xfree(ptr2, STR_HEAP_SIZE(str2)); } } - FL_SET(str2, STR_NOEMBED); - RSTRING(str2)->as.heap.len = len; - RSTRING(str2)->as.heap.ptr = ptr; + FL_SET(str2, STR_NOEMBED); + RSTRING(str2)->as.heap.len = len; + RSTRING(str2)->as.heap.ptr = ptr; STR_SET_SHARED(str2, root); } return str2; @@ -1440,29 +1440,29 @@ void rb_str_tmp_frozen_release(VALUE orig, VALUE tmp) { if (RBASIC_CLASS(tmp) != 0) - return; + return; if (STR_EMBED_P(tmp)) { - assert(OBJ_FROZEN_RAW(tmp)); + assert(OBJ_FROZEN_RAW(tmp)); } else if (FL_TEST_RAW(orig, STR_SHARED) && - !FL_TEST_RAW(orig, STR_TMPLOCK|RUBY_FL_FREEZE)) { - VALUE shared = RSTRING(orig)->as.heap.aux.shared; + !FL_TEST_RAW(orig, STR_TMPLOCK|RUBY_FL_FREEZE)) { + VALUE shared = RSTRING(orig)->as.heap.aux.shared; - if (shared == tmp && !FL_TEST_RAW(tmp, STR_BORROWED)) { + if (shared == tmp && !FL_TEST_RAW(tmp, STR_BORROWED)) { assert(RSTRING(orig)->as.heap.ptr == RSTRING(tmp)->as.heap.ptr); assert(RSTRING(orig)->as.heap.len == RSTRING(tmp)->as.heap.len); /* Unshare orig since the root (tmp) only has this one child. */ - FL_UNSET_RAW(orig, STR_SHARED); - RSTRING(orig)->as.heap.aux.capa = RSTRING(tmp)->as.heap.aux.capa; - RBASIC(orig)->flags |= RBASIC(tmp)->flags & STR_NOFREE; - assert(OBJ_FROZEN_RAW(tmp)); + FL_UNSET_RAW(orig, STR_SHARED); + RSTRING(orig)->as.heap.aux.capa = RSTRING(tmp)->as.heap.aux.capa; + RBASIC(orig)->flags |= RBASIC(tmp)->flags & STR_NOFREE; + assert(OBJ_FROZEN_RAW(tmp)); /* Make tmp embedded and empty so it is safe for sweeping. */ STR_SET_EMBED(tmp); STR_SET_EMBED_LEN(tmp, 0); - } + } } } @@ -1504,42 +1504,42 @@ str_new_frozen_buffer(VALUE klass, VALUE orig, int copy_encoding) assert(STR_EMBED_P(str)); } else { - if (FL_TEST_RAW(orig, STR_SHARED)) { - VALUE shared = RSTRING(orig)->as.heap.aux.shared; + if (FL_TEST_RAW(orig, STR_SHARED)) { + VALUE shared = RSTRING(orig)->as.heap.aux.shared; long ofs = RSTRING(orig)->as.heap.ptr - RSTRING_PTR(shared); long rest = RSTRING_LEN(shared) - ofs - RSTRING(orig)->as.heap.len; assert(ofs >= 0); assert(rest >= 0); assert(ofs + rest <= RSTRING_LEN(shared)); #if !USE_RVARGC - assert(!STR_EMBED_P(shared)); + assert(!STR_EMBED_P(shared)); #endif - assert(OBJ_FROZEN(shared)); + assert(OBJ_FROZEN(shared)); - if ((ofs > 0) || (rest > 0) || - (klass != RBASIC(shared)->klass) || - ENCODING_GET(shared) != ENCODING_GET(orig)) { - str = str_new_shared(klass, shared); + if ((ofs > 0) || (rest > 0) || + (klass != RBASIC(shared)->klass) || + ENCODING_GET(shared) != ENCODING_GET(orig)) { + str = str_new_shared(klass, shared); assert(!STR_EMBED_P(str)); - RSTRING(str)->as.heap.ptr += ofs; - RSTRING(str)->as.heap.len -= ofs + rest; - } - else { - if (RBASIC_CLASS(shared) == 0) - FL_SET_RAW(shared, STR_BORROWED); - return shared; - } - } + RSTRING(str)->as.heap.ptr += ofs; + RSTRING(str)->as.heap.len -= ofs + rest; + } + else { + if (RBASIC_CLASS(shared) == 0) + FL_SET_RAW(shared, STR_BORROWED); + return shared; + } + } else if (STR_EMBEDDABLE_P(RSTRING_LEN(orig), TERM_LEN(orig))) { str = str_alloc_embed(klass, RSTRING_LEN(orig) + TERM_LEN(orig)); - STR_SET_EMBED(str); - memcpy(RSTRING_PTR(str), RSTRING_PTR(orig), RSTRING_LEN(orig)); - STR_SET_EMBED_LEN(str, RSTRING_LEN(orig)); - TERM_FILL(RSTRING_END(str), TERM_LEN(orig)); - } - else { + STR_SET_EMBED(str); + memcpy(RSTRING_PTR(str), RSTRING_PTR(orig), RSTRING_LEN(orig)); + STR_SET_EMBED_LEN(str, RSTRING_LEN(orig)); + TERM_FILL(RSTRING_END(str), TERM_LEN(orig)); + } + else { str = heap_str_make_shared(klass, orig); - } + } } if (copy_encoding) rb_enc_cr_str_exact_copy(str, orig); @@ -1577,7 +1577,7 @@ rb_str_buf_new(long capa) #if !USE_RVARGC if (capa < STR_BUF_MIN_SIZE) { - capa = STR_BUF_MIN_SIZE; + capa = STR_BUF_MIN_SIZE; } #endif FL_SET(str, STR_NOEMBED); @@ -1610,7 +1610,7 @@ void rb_str_free(VALUE str) { if (FL_TEST(str, RSTRING_FSTR)) { - st_data_t fstr = (st_data_t)str; + st_data_t fstr = (st_data_t)str; RB_VM_LOCK_ENTER(); { @@ -1621,15 +1621,15 @@ rb_str_free(VALUE str) } if (STR_EMBED_P(str)) { - RB_DEBUG_COUNTER_INC(obj_str_embed); + RB_DEBUG_COUNTER_INC(obj_str_embed); } else if (FL_TEST(str, STR_SHARED | STR_NOFREE)) { - (void)RB_DEBUG_COUNTER_INC_IF(obj_str_shared, FL_TEST(str, STR_SHARED)); - (void)RB_DEBUG_COUNTER_INC_IF(obj_str_shared, FL_TEST(str, STR_NOFREE)); + (void)RB_DEBUG_COUNTER_INC_IF(obj_str_shared, FL_TEST(str, STR_SHARED)); + (void)RB_DEBUG_COUNTER_INC_IF(obj_str_shared, FL_TEST(str, STR_NOFREE)); } else { - RB_DEBUG_COUNTER_INC(obj_str_ptr); - ruby_sized_xfree(STR_HEAP_PTR(str), STR_HEAP_SIZE(str)); + RB_DEBUG_COUNTER_INC(obj_str_ptr); + ruby_sized_xfree(STR_HEAP_PTR(str), STR_HEAP_SIZE(str)); } } @@ -1637,10 +1637,10 @@ RUBY_FUNC_EXPORTED size_t rb_str_memsize(VALUE str) { if (FL_TEST(str, STR_NOEMBED|STR_SHARED|STR_NOFREE) == STR_NOEMBED) { - return STR_HEAP_SIZE(str); + return STR_HEAP_SIZE(str); } else { - return 0; + return 0; } } @@ -1673,9 +1673,9 @@ str_shared_replace(VALUE str, VALUE str2) termlen = rb_enc_mbminlen(enc); if (str_embed_capa(str) >= RSTRING_LEN(str2) + termlen) { - STR_SET_EMBED(str); - memcpy(RSTRING_PTR(str), RSTRING_PTR(str2), (size_t)RSTRING_LEN(str2) + termlen); - STR_SET_EMBED_LEN(str, RSTRING_LEN(str2)); + STR_SET_EMBED(str); + memcpy(RSTRING_PTR(str), RSTRING_PTR(str2), (size_t)RSTRING_LEN(str2) + termlen); + STR_SET_EMBED_LEN(str, RSTRING_LEN(str2)); rb_enc_associate(str, enc); ENC_CODERANGE_SET(str, cr); } @@ -1695,25 +1695,25 @@ str_shared_replace(VALUE str, VALUE str2) } #endif - STR_SET_NOEMBED(str); - FL_UNSET(str, STR_SHARED); - RSTRING(str)->as.heap.ptr = RSTRING_PTR(str2); - RSTRING(str)->as.heap.len = RSTRING_LEN(str2); + STR_SET_NOEMBED(str); + FL_UNSET(str, STR_SHARED); + RSTRING(str)->as.heap.ptr = RSTRING_PTR(str2); + RSTRING(str)->as.heap.len = RSTRING_LEN(str2); - if (FL_TEST(str2, STR_SHARED)) { - VALUE shared = RSTRING(str2)->as.heap.aux.shared; - STR_SET_SHARED(str, shared); - } - else { - RSTRING(str)->as.heap.aux.capa = RSTRING(str2)->as.heap.aux.capa; - } + if (FL_TEST(str2, STR_SHARED)) { + VALUE shared = RSTRING(str2)->as.heap.aux.shared; + STR_SET_SHARED(str, shared); + } + else { + RSTRING(str)->as.heap.aux.capa = RSTRING(str2)->as.heap.aux.capa; + } - /* abandon str2 */ - STR_SET_EMBED(str2); - RSTRING_PTR(str2)[0] = 0; - STR_SET_EMBED_LEN(str2, 0); - rb_enc_associate(str, enc); - ENC_CODERANGE_SET(str, cr); + /* abandon str2 */ + STR_SET_EMBED(str2); + RSTRING_PTR(str2)[0] = 0; + STR_SET_EMBED_LEN(str2, 0); + rb_enc_associate(str, enc); + ENC_CODERANGE_SET(str, cr); } } @@ -1723,7 +1723,7 @@ rb_obj_as_string(VALUE obj) VALUE str; if (RB_TYPE_P(obj, T_STRING)) { - return obj; + return obj; } str = rb_funcall(obj, idTo_s, 0); return rb_obj_as_string_result(str, obj); @@ -1733,7 +1733,7 @@ MJIT_FUNC_EXPORTED VALUE rb_obj_as_string_result(VALUE str, VALUE obj) { if (!RB_TYPE_P(str, T_STRING)) - return rb_any_to_s(obj); + return rb_any_to_s(obj); return str; } @@ -1744,16 +1744,16 @@ str_replace(VALUE str, VALUE str2) len = RSTRING_LEN(str2); if (STR_SHARED_P(str2)) { - VALUE shared = RSTRING(str2)->as.heap.aux.shared; - assert(OBJ_FROZEN(shared)); - STR_SET_NOEMBED(str); - RSTRING(str)->as.heap.len = len; - RSTRING(str)->as.heap.ptr = RSTRING_PTR(str2); - STR_SET_SHARED(str, shared); - rb_enc_cr_str_exact_copy(str, str2); + VALUE shared = RSTRING(str2)->as.heap.aux.shared; + assert(OBJ_FROZEN(shared)); + STR_SET_NOEMBED(str); + RSTRING(str)->as.heap.len = len; + RSTRING(str)->as.heap.ptr = RSTRING_PTR(str2); + STR_SET_SHARED(str, shared); + rb_enc_cr_str_exact_copy(str, str2); } else { - str_replace_shared(str, str2); + str_replace_shared(str, str2); } return str; @@ -1790,11 +1790,11 @@ str_duplicate_setup(VALUE klass, VALUE str, VALUE dup) { const VALUE flag_mask = #if !USE_RVARGC - RSTRING_NOEMBED | RSTRING_EMBED_LEN_MASK | + RSTRING_NOEMBED | RSTRING_EMBED_LEN_MASK | #endif ENC_CODERANGE_MASK | ENCODING_MASK | FL_FREEZE - ; + ; VALUE flags = FL_TEST_RAW(str, flag_mask); int encidx = 0; if (STR_EMBED_P(str)) { @@ -1831,8 +1831,8 @@ str_duplicate_setup(VALUE klass, VALUE str, VALUE dup) } if ((flags & ENCODING_MASK) == (ENCODING_INLINE_MAX<as.embed.len + 1 <= str_embed_capa(str)); @@ -1953,30 +1953,30 @@ rb_str_init(int argc, VALUE *argv, VALUE str) memcpy(new_ptr, old_ptr, osize < size ? osize : size); FL_UNSET_RAW(str, STR_SHARED|STR_NOFREE); RSTRING(str)->as.heap.ptr = new_ptr; - } - else if (STR_HEAP_SIZE(str) != (size_t)capa + termlen) { - SIZED_REALLOC_N(RSTRING(str)->as.heap.ptr, char, - (size_t)capa + termlen, STR_HEAP_SIZE(str)); - } - RSTRING(str)->as.heap.len = len; - TERM_FILL(&RSTRING(str)->as.heap.ptr[len], termlen); - if (n == 1) { - memcpy(RSTRING(str)->as.heap.ptr, RSTRING_PTR(orig), len); - rb_enc_cr_str_exact_copy(str, orig); - } - FL_SET(str, STR_NOEMBED); - RSTRING(str)->as.heap.aux.capa = capa; - } - else if (n == 1) { - rb_str_replace(str, orig); - } - if (enc) { - rb_enc_associate(str, enc); - ENC_CODERANGE_CLEAR(str); - } + } + else if (STR_HEAP_SIZE(str) != (size_t)capa + termlen) { + SIZED_REALLOC_N(RSTRING(str)->as.heap.ptr, char, + (size_t)capa + termlen, STR_HEAP_SIZE(str)); + } + RSTRING(str)->as.heap.len = len; + TERM_FILL(&RSTRING(str)->as.heap.ptr[len], termlen); + if (n == 1) { + memcpy(RSTRING(str)->as.heap.ptr, RSTRING_PTR(orig), len); + rb_enc_cr_str_exact_copy(str, orig); + } + FL_SET(str, STR_NOEMBED); + RSTRING(str)->as.heap.aux.capa = capa; + } + else if (n == 1) { + rb_str_replace(str, orig); + } + if (enc) { + rb_enc_associate(str, enc); + ENC_CODERANGE_CLEAR(str); + } } else if (n == 1) { - rb_str_replace(str, orig); + rb_str_replace(str, orig); } return str; } @@ -2028,62 +2028,62 @@ enc_strlen(const char *p, const char *e, rb_encoding *enc, int cr) const char *q; if (rb_enc_mbmaxlen(enc) == rb_enc_mbminlen(enc)) { - long diff = (long)(e - p); - return diff / rb_enc_mbminlen(enc) + !!(diff % rb_enc_mbminlen(enc)); + long diff = (long)(e - p); + return diff / rb_enc_mbminlen(enc) + !!(diff % rb_enc_mbminlen(enc)); } #ifdef NONASCII_MASK else if (cr == ENC_CODERANGE_VALID && enc == rb_utf8_encoding()) { - uintptr_t len = 0; - if ((int)sizeof(uintptr_t) * 2 < e - p) { - const uintptr_t *s, *t; - const uintptr_t lowbits = sizeof(uintptr_t) - 1; - s = (const uintptr_t*)(~lowbits & ((uintptr_t)p + lowbits)); - t = (const uintptr_t*)(~lowbits & (uintptr_t)e); - while (p < (const char *)s) { - if (is_utf8_lead_byte(*p)) len++; - p++; - } - while (s < t) { - len += count_utf8_lead_bytes_with_word(s); - s++; - } - p = (const char *)s; - } - while (p < e) { - if (is_utf8_lead_byte(*p)) len++; - p++; - } - return (long)len; + uintptr_t len = 0; + if ((int)sizeof(uintptr_t) * 2 < e - p) { + const uintptr_t *s, *t; + const uintptr_t lowbits = sizeof(uintptr_t) - 1; + s = (const uintptr_t*)(~lowbits & ((uintptr_t)p + lowbits)); + t = (const uintptr_t*)(~lowbits & (uintptr_t)e); + while (p < (const char *)s) { + if (is_utf8_lead_byte(*p)) len++; + p++; + } + while (s < t) { + len += count_utf8_lead_bytes_with_word(s); + s++; + } + p = (const char *)s; + } + while (p < e) { + if (is_utf8_lead_byte(*p)) len++; + p++; + } + return (long)len; } #endif else if (rb_enc_asciicompat(enc)) { c = 0; - if (ENC_CODERANGE_CLEAN_P(cr)) { - while (p < e) { - if (ISASCII(*p)) { - q = search_nonascii(p, e); - if (!q) - return c + (e - p); - c += q - p; - p = q; - } - p += rb_enc_fast_mbclen(p, e, enc); - c++; - } - } - else { - while (p < e) { - if (ISASCII(*p)) { - q = search_nonascii(p, e); - if (!q) - return c + (e - p); - c += q - p; - p = q; - } - p += rb_enc_mbclen(p, e, enc); - c++; - } - } + if (ENC_CODERANGE_CLEAN_P(cr)) { + while (p < e) { + if (ISASCII(*p)) { + q = search_nonascii(p, e); + if (!q) + return c + (e - p); + c += q - p; + p = q; + } + p += rb_enc_fast_mbclen(p, e, enc); + c++; + } + } + else { + while (p < e) { + if (ISASCII(*p)) { + q = search_nonascii(p, e); + if (!q) + return c + (e - p); + c += q - p; + p = q; + } + p += rb_enc_mbclen(p, e, enc); + c++; + } + } return c; } @@ -2111,49 +2111,49 @@ rb_enc_strlen_cr(const char *p, const char *e, rb_encoding *enc, int *cr) *cr = 0; if (rb_enc_mbmaxlen(enc) == rb_enc_mbminlen(enc)) { - long diff = (long)(e - p); - return diff / rb_enc_mbminlen(enc) + !!(diff % rb_enc_mbminlen(enc)); + long diff = (long)(e - p); + return diff / rb_enc_mbminlen(enc) + !!(diff % rb_enc_mbminlen(enc)); } else if (rb_enc_asciicompat(enc)) { - c = 0; - while (p < e) { - if (ISASCII(*p)) { - q = search_nonascii(p, e); - if (!q) { - if (!*cr) *cr = ENC_CODERANGE_7BIT; - return c + (e - p); - } - c += q - p; - p = q; - } - ret = rb_enc_precise_mbclen(p, e, enc); - if (MBCLEN_CHARFOUND_P(ret)) { - *cr |= ENC_CODERANGE_VALID; - p += MBCLEN_CHARFOUND_LEN(ret); - } - else { - *cr = ENC_CODERANGE_BROKEN; - p++; - } - c++; - } - if (!*cr) *cr = ENC_CODERANGE_7BIT; - return c; + c = 0; + while (p < e) { + if (ISASCII(*p)) { + q = search_nonascii(p, e); + if (!q) { + if (!*cr) *cr = ENC_CODERANGE_7BIT; + return c + (e - p); + } + c += q - p; + p = q; + } + ret = rb_enc_precise_mbclen(p, e, enc); + if (MBCLEN_CHARFOUND_P(ret)) { + *cr |= ENC_CODERANGE_VALID; + p += MBCLEN_CHARFOUND_LEN(ret); + } + else { + *cr = ENC_CODERANGE_BROKEN; + p++; + } + c++; + } + if (!*cr) *cr = ENC_CODERANGE_7BIT; + return c; } for (c=0; p LONG_MAX - len2) { - rb_raise(rb_eArgError, "string size too big"); + rb_raise(rb_eArgError, "string size too big"); } str3 = str_new0(rb_cString, 0, len1+len2, termlen); ptr3 = RSTRING_PTR(str3); @@ -2268,7 +2268,7 @@ rb_str_plus(VALUE str1, VALUE str2) TERM_FILL(&ptr3[len1+len2], termlen); ENCODING_CODERANGE_SET(str3, rb_enc_to_index(enc), - ENC_CODERANGE_AND(ENC_CODERANGE(str1), ENC_CODERANGE(str2))); + ENC_CODERANGE_AND(ENC_CODERANGE(str1), ENC_CODERANGE(str2))); RB_GC_GUARD(str1); RB_GC_GUARD(str2); return str3; @@ -2329,12 +2329,12 @@ rb_str_times(VALUE str, VALUE times) } if (times == INT2FIX(0)) { str2 = str_alloc_embed(rb_cString, 0); - rb_enc_copy(str2, str); - return str2; + rb_enc_copy(str2, str); + return str2; } len = NUM2LONG(times); if (len < 0) { - rb_raise(rb_eArgError, "negative argument"); + rb_raise(rb_eArgError, "negative argument"); } if (RSTRING_LEN(str) == 1 && RSTRING_PTR(str)[0] == 0) { if (STR_EMBEDDABLE_P(len, 1)) { @@ -2352,7 +2352,7 @@ rb_str_times(VALUE str, VALUE times) return str2; } if (len && LONG_MAX/len < RSTRING_LEN(str)) { - rb_raise(rb_eArgError, "argument too big"); + rb_raise(rb_eArgError, "argument too big"); } len *= RSTRING_LEN(str); @@ -2408,7 +2408,7 @@ static inline void rb_check_lockedtmp(VALUE str) { if (FL_TEST(str, STR_TMPLOCK)) { - rb_raise(rb_eRuntimeError, "can't modify string; temporarily locked"); + rb_raise(rb_eRuntimeError, "can't modify string; temporarily locked"); } } @@ -2423,10 +2423,10 @@ static inline int str_dependent_p(VALUE str) { if (STR_EMBED_P(str) || !FL_TEST(str, STR_SHARED|STR_NOFREE)) { - return 0; + return 0; } else { - return 1; + return 1; } } @@ -2447,18 +2447,18 @@ str_make_independent_expand(VALUE str, long len, long expand, const int termlen) if (len > capa) len = capa; if (!STR_EMBED_P(str) && str_embed_capa(str) >= capa + termlen) { - ptr = RSTRING(str)->as.heap.ptr; - STR_SET_EMBED(str); + ptr = RSTRING(str)->as.heap.ptr; + STR_SET_EMBED(str); memcpy(RSTRING(str)->as.embed.ary, ptr, len); TERM_FILL(RSTRING(str)->as.embed.ary + len, termlen); - STR_SET_EMBED_LEN(str, len); - return; + STR_SET_EMBED_LEN(str, len); + return; } ptr = ALLOC_N(char, (size_t)capa + termlen); oldptr = RSTRING_PTR(str); if (oldptr) { - memcpy(ptr, oldptr, len); + memcpy(ptr, oldptr, len); } if (FL_TEST_RAW(str, STR_NOEMBED|STR_NOFREE|STR_SHARED) == STR_NOEMBED) { xfree(oldptr); @@ -2475,7 +2475,7 @@ void rb_str_modify(VALUE str) { if (!str_independent(str)) - str_make_independent(str); + str_make_independent(str); ENC_CODERANGE_CLEAR(str); } @@ -2486,17 +2486,17 @@ rb_str_modify_expand(VALUE str, long expand) long len = RSTRING_LEN(str); if (expand < 0) { - rb_raise(rb_eArgError, "negative expanding string size"); + rb_raise(rb_eArgError, "negative expanding string size"); } if (expand >= LONG_MAX - len) { - rb_raise(rb_eArgError, "string size too big"); + rb_raise(rb_eArgError, "string size too big"); } if (!str_independent(str)) { - str_make_independent_expand(str, len, expand, termlen); + str_make_independent_expand(str, len, expand, termlen); } else if (expand > 0) { - RESIZE_CAPA_TERM(str, len + expand, termlen); + RESIZE_CAPA_TERM(str, len + expand, termlen); } ENC_CODERANGE_CLEAR(str); } @@ -2506,10 +2506,10 @@ static void str_modify_keep_cr(VALUE str) { if (!str_independent(str)) - str_make_independent(str); + str_make_independent(str); if (ENC_CODERANGE(str) == ENC_CODERANGE_BROKEN) - /* Force re-scan later */ - ENC_CODERANGE_CLEAR(str); + /* Force re-scan later */ + ENC_CODERANGE_CLEAR(str); } static inline void @@ -2517,9 +2517,9 @@ str_discard(VALUE str) { str_modifiable(str); if (!STR_EMBED_P(str) && !FL_TEST(str, STR_SHARED|STR_NOFREE)) { - ruby_sized_xfree(STR_HEAP_PTR(str), STR_HEAP_SIZE(str)); - RSTRING(str)->as.heap.ptr = 0; - RSTRING(str)->as.heap.len = 0; + ruby_sized_xfree(STR_HEAP_PTR(str), STR_HEAP_SIZE(str)); + RSTRING(str)->as.heap.ptr = 0; + RSTRING(str)->as.heap.len = 0; } } @@ -2528,7 +2528,7 @@ rb_must_asciicompat(VALUE str) { rb_encoding *enc = rb_enc_get(str); if (!rb_enc_asciicompat(enc)) { - rb_raise(rb_eEncCompatError, "ASCII incompatible encoding: %s", rb_enc_name(enc)); + rb_raise(rb_eEncCompatError, "ASCII incompatible encoding: %s", rb_enc_name(enc)); } } @@ -2537,8 +2537,8 @@ rb_string_value(volatile VALUE *ptr) { VALUE s = *ptr; if (!RB_TYPE_P(s, T_STRING)) { - s = rb_str_to_str(s); - *ptr = s; + s = rb_str_to_str(s); + *ptr = s; } return s; } @@ -2554,7 +2554,7 @@ static int zero_filled(const char *s, int n) { for (; n > 0; --n) { - if (*s++) return 0; + if (*s++) return 0; } return 1; } @@ -2565,7 +2565,7 @@ str_null_char(const char *s, long len, const int minlen, rb_encoding *enc) const char *e = s + len; for (; s + minlen <= e; s += rb_enc_mbclen(s, e, enc)) { - if (zero_filled(s, minlen)) return s; + if (zero_filled(s, minlen)) return s; } return 0; } @@ -2577,12 +2577,12 @@ str_fill_term(VALUE str, char *s, long len, int termlen) * is allocated, like many other functions in this file. */ if (str_dependent_p(str)) { - if (!zero_filled(s + len, termlen)) - str_make_independent_expand(str, len, 0L, termlen); + if (!zero_filled(s + len, termlen)) + str_make_independent_expand(str, len, 0L, termlen); } else { - TERM_FILL(s + len, termlen); - return s; + TERM_FILL(s + len, termlen); + return s; } return RSTRING_PTR(str); } @@ -2595,22 +2595,22 @@ rb_str_change_terminator_length(VALUE str, const int oldtermlen, const int terml assert(capa >= len); if (capa - len < termlen) { - rb_check_lockedtmp(str); - str_make_independent_expand(str, len, 0L, termlen); + rb_check_lockedtmp(str); + str_make_independent_expand(str, len, 0L, termlen); } else if (str_dependent_p(str)) { - if (termlen > oldtermlen) - str_make_independent_expand(str, len, 0L, termlen); + if (termlen > oldtermlen) + str_make_independent_expand(str, len, 0L, termlen); } else { - if (!STR_EMBED_P(str)) { - /* modify capa instead of realloc */ - assert(!FL_TEST((str), STR_SHARED)); - RSTRING(str)->as.heap.aux.capa = capa - termlen; - } - if (termlen > oldtermlen) { - TERM_FILL(RSTRING_PTR(str) + len, termlen); - } + if (!STR_EMBED_P(str)) { + /* modify capa instead of realloc */ + assert(!FL_TEST((str), STR_SHARED)); + RSTRING(str)->as.heap.aux.capa = capa - termlen; + } + if (termlen > oldtermlen) { + TERM_FILL(RSTRING_PTR(str) + len, termlen); + } } return; @@ -2625,18 +2625,18 @@ str_null_check(VALUE str, int *w) const int minlen = rb_enc_mbminlen(enc); if (minlen > 1) { - *w = 1; - if (str_null_char(s, len, minlen, enc)) { - return NULL; - } - return str_fill_term(str, s, len, minlen); + *w = 1; + if (str_null_char(s, len, minlen, enc)) { + return NULL; + } + return str_fill_term(str, s, len, minlen); } *w = 0; if (!s || memchr(s, 0, len)) { - return NULL; + return NULL; } if (s[len]) { - s = str_fill_term(str, s, len, minlen); + s = str_fill_term(str, s, len, minlen); } return s; } @@ -2655,10 +2655,10 @@ rb_string_value_cstr(volatile VALUE *ptr) int w; char *s = str_null_check(str, &w); if (!s) { - if (w) { - rb_raise(rb_eArgError, "string contains null char"); - } - rb_raise(rb_eArgError, "string contains null byte"); + if (w) { + rb_raise(rb_eArgError, "string contains null char"); + } + rb_raise(rb_eArgError, "string contains null byte"); } return s; } @@ -2720,8 +2720,8 @@ str_nth_len(const char *p, const char *e, long *nthp, rb_encoding *enc) if (ISASCII(*p)) { p2 = search_nonascii(p, e2); if (!p2) { - nth -= e2 - p; - *nthp = nth; + nth -= e2 - p; + *nthp = nth; return (char *)e2; } nth -= p2 - p; @@ -2757,9 +2757,9 @@ static char* str_nth(const char *p, const char *e, long nth, rb_encoding *enc, int singlebyte) { if (singlebyte) - p += nth; + p += nth; else { - p = str_nth_len(p, e, &nth, enc); + p = str_nth_len(p, e, &nth, enc); } if (!p) return 0; if (p > e) p = e; @@ -2779,7 +2779,7 @@ long rb_str_offset(VALUE str, long pos) { return str_offset(RSTRING_PTR(str), RSTRING_END(str), pos, - STR_ENC_GET(str), single_byte_optimizable(str)); + STR_ENC_GET(str), single_byte_optimizable(str)); } #ifdef NONASCII_MASK @@ -2788,26 +2788,26 @@ str_utf8_nth(const char *p, const char *e, long *nthp) { long nth = *nthp; if ((int)SIZEOF_VOIDP * 2 < e - p && (int)SIZEOF_VOIDP * 2 < nth) { - const uintptr_t *s, *t; - const uintptr_t lowbits = SIZEOF_VOIDP - 1; - s = (const uintptr_t*)(~lowbits & ((uintptr_t)p + lowbits)); - t = (const uintptr_t*)(~lowbits & (uintptr_t)e); - while (p < (const char *)s) { - if (is_utf8_lead_byte(*p)) nth--; - p++; - } - do { - nth -= count_utf8_lead_bytes_with_word(s); - s++; - } while (s < t && (int)SIZEOF_VOIDP <= nth); - p = (char *)s; + const uintptr_t *s, *t; + const uintptr_t lowbits = SIZEOF_VOIDP - 1; + s = (const uintptr_t*)(~lowbits & ((uintptr_t)p + lowbits)); + t = (const uintptr_t*)(~lowbits & (uintptr_t)e); + while (p < (const char *)s) { + if (is_utf8_lead_byte(*p)) nth--; + p++; + } + do { + nth -= count_utf8_lead_bytes_with_word(s); + s++; + } while (s < t && (int)SIZEOF_VOIDP <= nth); + p = (char *)s; } while (p < e) { - if (is_utf8_lead_byte(*p)) { - if (nth == 0) break; - nth--; - } - p++; + if (is_utf8_lead_byte(*p)) { + if (nth == 0) break; + nth--; + } + p++; } *nthp = nth; return (char *)p; @@ -2828,7 +2828,7 @@ rb_str_sublen(VALUE str, long pos) if (single_byte_optimizable(str) || pos < 0) return pos; else { - char *p = RSTRING_PTR(str); + char *p = RSTRING_PTR(str); return enc_strlen(p, p + pos, STR_ENC_GET(str), ENC_CODERANGE(str)); } } @@ -2839,12 +2839,12 @@ rb_str_subseq(VALUE str, long beg, long len) VALUE str2; if (!STR_EMBEDDABLE_P(len, TERM_LEN(str)) && - SHARABLE_SUBSTRING_P(beg, len, RSTRING_LEN(str))) { - long olen; + SHARABLE_SUBSTRING_P(beg, len, RSTRING_LEN(str))) { + long olen; str2 = rb_str_new_shared(rb_str_new_frozen_String(str)); - RSTRING(str2)->as.heap.ptr += beg; - olen = RSTRING(str2)->as.heap.len; - if (olen > len) RSTRING(str2)->as.heap.len = len; + RSTRING(str2)->as.heap.ptr += beg; + olen = RSTRING(str2)->as.heap.len; + if (olen > len) RSTRING(str2)->as.heap.len = len; } else { str2 = rb_str_new(RSTRING_PTR(str)+beg, len); @@ -2867,46 +2867,46 @@ rb_str_subpos(VALUE str, long beg, long *lenp) if (len < 0) return 0; if (!blen) { - len = 0; + len = 0; } if (single_byte_optimizable(str)) { - if (beg > blen) return 0; - if (beg < 0) { - beg += blen; - if (beg < 0) return 0; - } - if (len > blen - beg) - len = blen - beg; - if (len < 0) return 0; - p = s + beg; - goto end; + if (beg > blen) return 0; + if (beg < 0) { + beg += blen; + if (beg < 0) return 0; + } + if (len > blen - beg) + len = blen - beg; + if (len < 0) return 0; + p = s + beg; + goto end; } if (beg < 0) { - if (len > -beg) len = -beg; - if (-beg * rb_enc_mbmaxlen(enc) < RSTRING_LEN(str) / 8) { - beg = -beg; - while (beg-- > len && (e = rb_enc_prev_char(s, e, e, enc)) != 0); - p = e; - if (!p) return 0; - while (len-- > 0 && (p = rb_enc_prev_char(s, p, e, enc)) != 0); - if (!p) return 0; - len = e - p; - goto end; - } - else { - slen = str_strlen(str, enc); - beg += slen; - if (beg < 0) return 0; - p = s + beg; - if (len == 0) goto end; - } + if (len > -beg) len = -beg; + if (-beg * rb_enc_mbmaxlen(enc) < RSTRING_LEN(str) / 8) { + beg = -beg; + while (beg-- > len && (e = rb_enc_prev_char(s, e, e, enc)) != 0); + p = e; + if (!p) return 0; + while (len-- > 0 && (p = rb_enc_prev_char(s, p, e, enc)) != 0); + if (!p) return 0; + len = e - p; + goto end; + } + else { + slen = str_strlen(str, enc); + beg += slen; + if (beg < 0) return 0; + p = s + beg; + if (len == 0) goto end; + } } else if (beg > 0 && beg > RSTRING_LEN(str)) { - return 0; + return 0; } if (len == 0) { - if (beg > str_strlen(str, enc)) return 0; /* str's enc */ - p = s + beg; + if (beg > str_strlen(str, enc)) return 0; /* str's enc */ + p = s + beg; } #ifdef NONASCII_MASK else if (ENC_CODERANGE(str) == ENC_CODERANGE_VALID && @@ -2917,23 +2917,23 @@ rb_str_subpos(VALUE str, long beg, long *lenp) } #endif else if (rb_enc_mbmaxlen(enc) == rb_enc_mbminlen(enc)) { - int char_sz = rb_enc_mbmaxlen(enc); + int char_sz = rb_enc_mbmaxlen(enc); - p = s + beg * char_sz; - if (p > e) { - return 0; - } + p = s + beg * char_sz; + if (p > e) { + return 0; + } else if (len * char_sz > e - p) len = e - p; else - len *= char_sz; + len *= char_sz; } else if ((p = str_nth_len(s, e, &beg, enc)) == e) { - if (beg > 0) return 0; - len = 0; + if (beg > 0) return 0; + len = 0; } else { - len = str_offset(p, e, len, enc, 0); + len = str_offset(p, e, len, enc, 0); } end: *lenp = len; @@ -2957,18 +2957,18 @@ str_substr(VALUE str, long beg, long len, int empty) if (!p) return Qnil; if (!STR_EMBEDDABLE_P(len, TERM_LEN(str)) && - SHARABLE_SUBSTRING_P(p, len, RSTRING_END(str))) { - long ofs = p - RSTRING_PTR(str); - str2 = rb_str_new_frozen(str); + SHARABLE_SUBSTRING_P(p, len, RSTRING_END(str))) { + long ofs = p - RSTRING_PTR(str); + str2 = rb_str_new_frozen(str); str2 = str_new_shared(rb_cString, str2); - RSTRING(str2)->as.heap.ptr += ofs; - RSTRING(str2)->as.heap.len = len; - ENC_CODERANGE_CLEAR(str2); + RSTRING(str2)->as.heap.ptr += ofs; + RSTRING(str2)->as.heap.len = len; + ENC_CODERANGE_CLEAR(str2); } else { - if (!len && !empty) return Qnil; + if (!len && !empty) return Qnil; str2 = rb_str_new(p, len); - RB_GC_GUARD(str); + RB_GC_GUARD(str); } rb_enc_cr_str_copy_for_substr(str2, str); @@ -2996,10 +2996,10 @@ static VALUE str_uplus(VALUE str) { if (OBJ_FROZEN(str)) { - return rb_str_dup(str); + return rb_str_dup(str); } else { - return str; + return str; } } @@ -3030,7 +3030,7 @@ VALUE rb_str_locktmp(VALUE str) { if (FL_TEST(str, STR_TMPLOCK)) { - rb_raise(rb_eRuntimeError, "temporal locking already locked string"); + rb_raise(rb_eRuntimeError, "temporal locking already locked string"); } FL_SET(str, STR_TMPLOCK); return str; @@ -3040,7 +3040,7 @@ VALUE rb_str_unlocktmp(VALUE str) { if (!FL_TEST(str, STR_TMPLOCK)) { - rb_raise(rb_eRuntimeError, "temporal unlocking already unlocked string"); + rb_raise(rb_eRuntimeError, "temporal unlocking already unlocked string"); } FL_UNSET(str, STR_TMPLOCK); return str; @@ -3061,10 +3061,10 @@ rb_str_set_len(VALUE str, long len) str_modifiable(str); if (STR_SHARED_P(str)) { - rb_raise(rb_eRuntimeError, "can't set length of shared string"); + rb_raise(rb_eRuntimeError, "can't set length of shared string"); } if (len > (capa = (long)str_capacity(str, termlen)) || len < 0) { - rb_bug("probable buffer overflow: %ld for %ld", len, capa); + rb_bug("probable buffer overflow: %ld for %ld", len, capa); } STR_SET_LEN(str, len); TERM_FILL(&RSTRING_PTR(str)[len], termlen); @@ -3077,7 +3077,7 @@ rb_str_resize(VALUE str, long len) int independent; if (len < 0) { - rb_raise(rb_eArgError, "negative string size (or size too big)"); + rb_raise(rb_eArgError, "negative string size (or size too big)"); } independent = str_independent(str); @@ -3085,40 +3085,40 @@ rb_str_resize(VALUE str, long len) slen = RSTRING_LEN(str); { - long capa; - const int termlen = TERM_LEN(str); - if (STR_EMBED_P(str)) { - if (len == slen) return str; + long capa; + const int termlen = TERM_LEN(str); + if (STR_EMBED_P(str)) { + if (len == slen) return str; if (str_embed_capa(str) >= len + termlen) { - STR_SET_EMBED_LEN(str, len); + STR_SET_EMBED_LEN(str, len); TERM_FILL(RSTRING(str)->as.embed.ary + len, termlen); - return str; - } - str_make_independent_expand(str, slen, len - slen, termlen); - } + return str; + } + str_make_independent_expand(str, slen, len - slen, termlen); + } else if (str_embed_capa(str) >= len + termlen) { - char *ptr = STR_HEAP_PTR(str); - STR_SET_EMBED(str); - if (slen > len) slen = len; + char *ptr = STR_HEAP_PTR(str); + STR_SET_EMBED(str); + if (slen > len) slen = len; if (slen > 0) MEMCPY(RSTRING(str)->as.embed.ary, ptr, char, slen); TERM_FILL(RSTRING(str)->as.embed.ary + len, termlen); - STR_SET_EMBED_LEN(str, len); - if (independent) ruby_xfree(ptr); - return str; - } - else if (!independent) { - if (len == slen) return str; - str_make_independent_expand(str, slen, len - slen, termlen); - } - else if ((capa = RSTRING(str)->as.heap.aux.capa) < len || - (capa - len) > (len < 1024 ? len : 1024)) { - SIZED_REALLOC_N(RSTRING(str)->as.heap.ptr, char, - (size_t)len + termlen, STR_HEAP_SIZE(str)); - RSTRING(str)->as.heap.aux.capa = len; - } - else if (len == slen) return str; - RSTRING(str)->as.heap.len = len; - TERM_FILL(RSTRING(str)->as.heap.ptr + len, termlen); /* sentinel */ + STR_SET_EMBED_LEN(str, len); + if (independent) ruby_xfree(ptr); + return str; + } + else if (!independent) { + if (len == slen) return str; + str_make_independent_expand(str, slen, len - slen, termlen); + } + else if ((capa = RSTRING(str)->as.heap.aux.capa) < len || + (capa - len) > (len < 1024 ? len : 1024)) { + SIZED_REALLOC_N(RSTRING(str)->as.heap.ptr, char, + (size_t)len + termlen, STR_HEAP_SIZE(str)); + RSTRING(str)->as.heap.aux.capa = len; + } + else if (len == slen) return str; + RSTRING(str)->as.heap.len = len; + TERM_FILL(RSTRING(str)->as.heap.ptr + len, termlen); /* sentinel */ } return str; } @@ -3152,23 +3152,23 @@ str_buf_cat4(VALUE str, const char *ptr, long len, bool keep_cr) olen = RSTRING_EMBED_LEN(str); } else { - capa = RSTRING(str)->as.heap.aux.capa; - sptr = RSTRING(str)->as.heap.ptr; - olen = RSTRING(str)->as.heap.len; + capa = RSTRING(str)->as.heap.aux.capa; + sptr = RSTRING(str)->as.heap.ptr; + olen = RSTRING(str)->as.heap.len; } if (olen > LONG_MAX - len) { - rb_raise(rb_eArgError, "string sizes too big"); + rb_raise(rb_eArgError, "string sizes too big"); } total = olen + len; if (capa < total) { - if (total >= LONG_MAX / 2) { - capa = total; - } - while (total > capa) { - capa = 2 * capa + termlen; /* == 2*(capa+termlen)-termlen */ - } - RESIZE_CAPA_TERM(str, capa, termlen); - sptr = RSTRING_PTR(str); + if (total >= LONG_MAX / 2) { + capa = total; + } + while (total > capa) { + capa = 2 * capa + termlen; /* == 2*(capa+termlen)-termlen */ + } + RESIZE_CAPA_TERM(str, capa, termlen); + sptr = RSTRING_PTR(str); } if (off != -1) { ptr = sptr + off; @@ -3188,7 +3188,7 @@ rb_str_cat(VALUE str, const char *ptr, long len) { if (len == 0) return str; if (len < 0) { - rb_raise(rb_eArgError, "negative string size (or size too big)"); + rb_raise(rb_eArgError, "negative string size (or size too big)"); } return str_buf_cat(str, ptr, len); } @@ -3216,13 +3216,13 @@ rb_enc_cr_str_buf_cat(VALUE str, const char *ptr, long len, str_cr = RSTRING_LEN(str) ? ENC_CODERANGE(str) : ENC_CODERANGE_7BIT; if (str_encindex == ptr_encindex) { - if (str_cr != ENC_CODERANGE_UNKNOWN && ptr_cr == ENC_CODERANGE_UNKNOWN) { + if (str_cr != ENC_CODERANGE_UNKNOWN && ptr_cr == ENC_CODERANGE_UNKNOWN) { ptr_cr = coderange_scan(ptr, len, rb_enc_from_index(ptr_encindex)); } } else { - str_enc = rb_enc_from_index(str_encindex); - ptr_enc = rb_enc_from_index(ptr_encindex); + str_enc = rb_enc_from_index(str_encindex); + ptr_enc = rb_enc_from_index(ptr_encindex); if (!rb_enc_asciicompat(str_enc) || !rb_enc_asciicompat(ptr_enc)) { if (len == 0) return str; @@ -3234,9 +3234,9 @@ rb_enc_cr_str_buf_cat(VALUE str, const char *ptr, long len, } goto incompatible; } - if (ptr_cr == ENC_CODERANGE_UNKNOWN) { - ptr_cr = coderange_scan(ptr, len, ptr_enc); - } + if (ptr_cr == ENC_CODERANGE_UNKNOWN) { + ptr_cr = coderange_scan(ptr, len, ptr_enc); + } if (str_cr == ENC_CODERANGE_UNKNOWN) { if (ENCODING_IS_ASCII8BIT(str) || ptr_cr != ENC_CODERANGE_7BIT) { str_cr = rb_enc_str_coderange(str); @@ -3249,8 +3249,8 @@ rb_enc_cr_str_buf_cat(VALUE str, const char *ptr, long len, if (str_encindex != ptr_encindex && str_cr != ENC_CODERANGE_7BIT && ptr_cr != ENC_CODERANGE_7BIT) { - str_enc = rb_enc_from_index(str_encindex); - ptr_enc = rb_enc_from_index(ptr_encindex); + str_enc = rb_enc_from_index(str_encindex); + ptr_enc = rb_enc_from_index(ptr_encindex); goto incompatible; } @@ -3270,10 +3270,10 @@ rb_enc_cr_str_buf_cat(VALUE str, const char *ptr, long len, } else if (str_cr == ENC_CODERANGE_VALID) { res_encindex = str_encindex; - if (ENC_CODERANGE_CLEAN_P(ptr_cr)) - res_cr = str_cr; - else - res_cr = ptr_cr; + if (ENC_CODERANGE_CLEAN_P(ptr_cr)) + res_cr = str_cr; + else + res_cr = ptr_cr; } else { /* str_cr == ENC_CODERANGE_BROKEN */ res_encindex = str_encindex; @@ -3282,7 +3282,7 @@ rb_enc_cr_str_buf_cat(VALUE str, const char *ptr, long len, } if (len < 0) { - rb_raise(rb_eArgError, "negative string size (or size too big)"); + rb_raise(rb_eArgError, "negative string size (or size too big)"); } str_buf_cat(str, ptr, len); ENCODING_CODERANGE_SET(str, res_encindex, res_cr); @@ -3363,25 +3363,25 @@ rb_str_concat_literals(size_t num, const VALUE *strary) for (i = 0; i < num; ++i) { len += RSTRING_LEN(strary[i]); } if (LIKELY(len < MIN_PRE_ALLOC_SIZE)) { - str = rb_str_resurrect(strary[0]); - s = 1; + str = rb_str_resurrect(strary[0]); + s = 1; } else { - str = rb_str_buf_new(len); - rb_enc_copy(str, strary[0]); - s = 0; + str = rb_str_buf_new(len); + rb_enc_copy(str, strary[0]); + s = 0; } for (i = s; i < num; ++i) { - const VALUE v = strary[i]; - int encidx = ENCODING_GET(v); + const VALUE v = strary[i]; + int encidx = ENCODING_GET(v); - rb_enc_cr_str_buf_cat(str, RSTRING_PTR(v), RSTRING_LEN(v), - encidx, ENC_CODERANGE(v), NULL); - if (encidx != ENCINDEX_US_ASCII) { - if (ENCODING_GET_INLINED(str) == ENCINDEX_US_ASCII) - rb_enc_set_index(str, encidx); - } + rb_enc_cr_str_buf_cat(str, RSTRING_PTR(v), RSTRING_LEN(v), + encidx, ENC_CODERANGE(v), NULL); + if (encidx != ENCINDEX_US_ASCII) { + if (ENCODING_GET_INLINED(str) == ENCINDEX_US_ASCII) + rb_enc_set_index(str, encidx); + } } return str; } @@ -3410,16 +3410,16 @@ rb_str_concat_multi(int argc, VALUE *argv, VALUE str) str_modifiable(str); if (argc == 1) { - return rb_str_concat(str, argv[0]); + return rb_str_concat(str, argv[0]); } else if (argc > 1) { - int i; - VALUE arg_str = rb_str_tmp_new(0); - rb_enc_copy(arg_str, str); - for (i = 0; i < argc; i++) { - rb_str_concat(arg_str, argv[i]); - } - rb_str_buf_append(str, arg_str); + int i; + VALUE arg_str = rb_str_tmp_new(0); + rb_enc_copy(arg_str, str); + for (i = 0; i < argc; i++) { + rb_str_concat(arg_str, argv[i]); + } + rb_str_buf_append(str, arg_str); } return str; @@ -3451,58 +3451,58 @@ rb_str_concat(VALUE str1, VALUE str2) int encidx; if (RB_INTEGER_TYPE_P(str2)) { - if (rb_num_to_uint(str2, &code) == 0) { - } - else if (FIXNUM_P(str2)) { - rb_raise(rb_eRangeError, "%ld out of char range", FIX2LONG(str2)); - } - else { - rb_raise(rb_eRangeError, "bignum out of char range"); - } + if (rb_num_to_uint(str2, &code) == 0) { + } + else if (FIXNUM_P(str2)) { + rb_raise(rb_eRangeError, "%ld out of char range", FIX2LONG(str2)); + } + else { + rb_raise(rb_eRangeError, "bignum out of char range"); + } } else { - return rb_str_append(str1, str2); + return rb_str_append(str1, str2); } encidx = rb_enc_to_index(enc); if (encidx == ENCINDEX_ASCII_8BIT || encidx == ENCINDEX_US_ASCII) { - /* US-ASCII automatically extended to ASCII-8BIT */ - char buf[1]; - buf[0] = (char)code; - if (code > 0xFF) { - rb_raise(rb_eRangeError, "%u out of char range", code); - } - rb_str_cat(str1, buf, 1); - if (encidx == ENCINDEX_US_ASCII && code > 127) { - rb_enc_associate_index(str1, ENCINDEX_ASCII_8BIT); - ENC_CODERANGE_SET(str1, ENC_CODERANGE_VALID); - } + /* US-ASCII automatically extended to ASCII-8BIT */ + char buf[1]; + buf[0] = (char)code; + if (code > 0xFF) { + rb_raise(rb_eRangeError, "%u out of char range", code); + } + rb_str_cat(str1, buf, 1); + if (encidx == ENCINDEX_US_ASCII && code > 127) { + rb_enc_associate_index(str1, ENCINDEX_ASCII_8BIT); + ENC_CODERANGE_SET(str1, ENC_CODERANGE_VALID); + } } else { - long pos = RSTRING_LEN(str1); - int cr = ENC_CODERANGE(str1); - int len; - char *buf; + long pos = RSTRING_LEN(str1); + int cr = ENC_CODERANGE(str1); + int len; + char *buf; - switch (len = rb_enc_codelen(code, enc)) { - case ONIGERR_INVALID_CODE_POINT_VALUE: - rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc)); - break; - case ONIGERR_TOO_BIG_WIDE_CHAR_VALUE: - case 0: - rb_raise(rb_eRangeError, "%u out of char range", code); - break; - } - buf = ALLOCA_N(char, len + 1); - rb_enc_mbcput(code, buf, enc); - if (rb_enc_precise_mbclen(buf, buf + len + 1, enc) != len) { - rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc)); - } - rb_str_resize(str1, pos+len); - memcpy(RSTRING_PTR(str1) + pos, buf, len); - if (cr == ENC_CODERANGE_7BIT && code > 127) - cr = ENC_CODERANGE_VALID; - ENC_CODERANGE_SET(str1, cr); + switch (len = rb_enc_codelen(code, enc)) { + case ONIGERR_INVALID_CODE_POINT_VALUE: + rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc)); + break; + case ONIGERR_TOO_BIG_WIDE_CHAR_VALUE: + case 0: + rb_raise(rb_eRangeError, "%u out of char range", code); + break; + } + buf = ALLOCA_N(char, len + 1); + rb_enc_mbcput(code, buf, enc); + if (rb_enc_precise_mbclen(buf, buf + len + 1, enc) != len) { + rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc)); + } + rb_str_resize(str1, pos+len); + memcpy(RSTRING_PTR(str1) + pos, buf, len); + if (cr == ENC_CODERANGE_7BIT && code > 127) + cr = ENC_CODERANGE_VALID; + ENC_CODERANGE_SET(str1, cr); } return str1; } @@ -3526,16 +3526,16 @@ rb_str_prepend_multi(int argc, VALUE *argv, VALUE str) str_modifiable(str); if (argc == 1) { - rb_str_update(str, 0L, 0L, argv[0]); + rb_str_update(str, 0L, 0L, argv[0]); } else if (argc > 1) { - int i; - VALUE arg_str = rb_str_tmp_new(0); - rb_enc_copy(arg_str, str); - for (i = 0; i < argc; i++) { - rb_str_append(arg_str, argv[i]); - } - rb_str_update(str, 0L, 0L, arg_str); + int i; + VALUE arg_str = rb_str_tmp_new(0); + rb_enc_copy(arg_str, str); + for (i = 0; i < argc; i++) { + rb_str_append(arg_str, argv[i]); + } + rb_str_update(str, 0L, 0L, arg_str); } return str; @@ -3546,7 +3546,7 @@ rb_str_hash(VALUE str) { int e = ENCODING_GET(str); if (e && is_ascii_string(str)) { - e = 0; + e = 0; } return rb_memhash((const void *)RSTRING_PTR(str), RSTRING_LEN(str)) ^ e; } @@ -3559,8 +3559,8 @@ rb_str_hash_cmp(VALUE str1, VALUE str2) RSTRING_GETMEM(str1, ptr1, len1); RSTRING_GETMEM(str2, ptr2, len2); return (len1 != len2 || - !rb_str_comparable(str1, str2) || - memcmp(ptr1, ptr2, len1) != 0); + !rb_str_comparable(str1, str2) || + memcmp(ptr1, ptr2, len1) != 0); } /* @@ -3596,13 +3596,13 @@ rb_str_comparable(VALUE str1, VALUE str2) rc1 = rb_enc_str_coderange(str1); rc2 = rb_enc_str_coderange(str2); if (rc1 == ENC_CODERANGE_7BIT) { - if (rc2 == ENC_CODERANGE_7BIT) return TRUE; - if (rb_enc_asciicompat(rb_enc_from_index(idx2))) - return TRUE; + if (rc2 == ENC_CODERANGE_7BIT) return TRUE; + if (rb_enc_asciicompat(rb_enc_from_index(idx2))) + return TRUE; } if (rc2 == ENC_CODERANGE_7BIT) { - if (rb_enc_asciicompat(rb_enc_from_index(idx1))) - return TRUE; + if (rb_enc_asciicompat(rb_enc_from_index(idx1))) + return TRUE; } return FALSE; } @@ -3618,16 +3618,16 @@ rb_str_cmp(VALUE str1, VALUE str2) RSTRING_GETMEM(str1, ptr1, len1); RSTRING_GETMEM(str2, ptr2, len2); if (ptr1 == ptr2 || (retval = memcmp(ptr1, ptr2, lesser(len1, len2))) == 0) { - if (len1 == len2) { - if (!rb_str_comparable(str1, str2)) { - if (ENCODING_GET(str1) > ENCODING_GET(str2)) - return 1; - return -1; - } - return 0; - } - if (len1 > len2) return 1; - return -1; + if (len1 == len2) { + if (!rb_str_comparable(str1, str2)) { + if (ENCODING_GET(str1) > ENCODING_GET(str2)) + return 1; + return -1; + } + return 0; + } + if (len1 > len2) return 1; + return -1; } if (retval > 0) return 1; return -1; @@ -3658,10 +3658,10 @@ rb_str_equal(VALUE str1, VALUE str2) { if (str1 == str2) return Qtrue; if (!RB_TYPE_P(str2, T_STRING)) { - if (!rb_respond_to(str2, idTo_str)) { - return Qfalse; - } - return rb_equal(str2, str1); + if (!rb_respond_to(str2, idTo_str)) { + return Qfalse; + } + return rb_equal(str2, str1); } return rb_str_eql_internal(str1, str2); } @@ -3720,7 +3720,7 @@ rb_str_cmp_m(VALUE str1, VALUE str2) int result; VALUE s = rb_check_string_type(str2); if (NIL_P(s)) { - return rb_invcmp(str1, str2); + return rb_invcmp(str1, str2); } result = rb_str_cmp(str1, s); return INT2FIX(result); @@ -3760,7 +3760,7 @@ rb_str_casecmp(VALUE str1, VALUE str2) { VALUE s = rb_check_string_type(str2); if (NIL_P(s)) { - return Qnil; + return Qnil; } return str_casecmp(str1, s); } @@ -3774,25 +3774,25 @@ str_casecmp(VALUE str1, VALUE str2) enc = rb_enc_compatible(str1, str2); if (!enc) { - return Qnil; + return Qnil; } p1 = RSTRING_PTR(str1); p1end = RSTRING_END(str1); p2 = RSTRING_PTR(str2); p2end = RSTRING_END(str2); if (single_byte_optimizable(str1) && single_byte_optimizable(str2)) { - while (p1 < p1end && p2 < p2end) { - if (*p1 != *p2) { + while (p1 < p1end && p2 < p2end) { + if (*p1 != *p2) { unsigned int c1 = TOLOWER(*p1 & 0xff); unsigned int c2 = TOLOWER(*p2 & 0xff); if (c1 != c2) return INT2FIX(c1 < c2 ? -1 : 1); - } - p1++; - p2++; - } + } + p1++; + p2++; + } } else { - while (p1 < p1end && p2 < p2end) { + while (p1 < p1end && p2 < p2end) { int l1, c1 = rb_enc_ascget(p1, p1end, &l1, enc); int l2, c2 = rb_enc_ascget(p2, p2end, &l2, enc); @@ -3813,9 +3813,9 @@ str_casecmp(VALUE str1, VALUE str2) if (l1 != l2) return INT2FIX(l1 < l2 ? -1 : 1); } - p1 += l1; - p2 += l2; - } + p1 += l1; + p2 += l2; + } } if (RSTRING_LEN(str1) == RSTRING_LEN(str2)) return INT2FIX(0); if (RSTRING_LEN(str1) > RSTRING_LEN(str2)) return INT2FIX(1); @@ -3850,7 +3850,7 @@ rb_str_casecmp_p(VALUE str1, VALUE str2) { VALUE s = rb_check_string_type(str2); if (NIL_P(s)) { - return Qnil; + return Qnil; } return str_casecmp_p(str1, s); } @@ -3864,7 +3864,7 @@ str_casecmp_p(VALUE str1, VALUE str2) enc = rb_enc_compatible(str1, str2); if (!enc) { - return Qnil; + return Qnil; } folded_str1 = rb_str_downcase(1, &fold_opt, str1); @@ -3875,21 +3875,21 @@ str_casecmp_p(VALUE str1, VALUE str2) static long strseq_core(const char *str_ptr, const char *str_ptr_end, long str_len, - const char *sub_ptr, long sub_len, long offset, rb_encoding *enc) + const char *sub_ptr, long sub_len, long offset, rb_encoding *enc) { const char *search_start = str_ptr; long pos, search_len = str_len - offset; for (;;) { - const char *t; - pos = rb_memsearch(sub_ptr, sub_len, search_start, search_len, enc); - if (pos < 0) return pos; - t = rb_enc_right_char_head(search_start, search_start+pos, str_ptr_end, enc); - if (t == search_start + pos) break; - search_len -= t - search_start; - if (search_len <= 0) return -1; - offset += t - search_start; - search_start = t; + const char *t; + pos = rb_memsearch(sub_ptr, sub_len, search_start, search_len, enc); + if (pos < 0) return pos; + t = rb_enc_right_char_head(search_start, search_start+pos, str_ptr_end, enc); + if (t == search_start + pos) break; + search_len -= t - search_start; + if (search_len <= 0) return -1; + offset += t - search_start; + search_start = t; } return pos + offset; } @@ -3915,17 +3915,17 @@ rb_strseq_index(VALUE str, VALUE sub, long offset, int in_byte) if (str_len < sub_len) return -1; if (offset != 0) { - long str_len_char, sub_len_char; + long str_len_char, sub_len_char; int single_byte = single_byte_optimizable(str); - str_len_char = (in_byte || single_byte) ? str_len : str_strlen(str, enc); - sub_len_char = in_byte ? sub_len : str_strlen(sub, enc); - if (offset < 0) { - offset += str_len_char; - if (offset < 0) return -1; - } - if (str_len_char - offset < sub_len_char) return -1; - if (!in_byte) offset = str_offset(str_ptr, str_ptr_end, offset, enc, single_byte); - str_ptr += offset; + str_len_char = (in_byte || single_byte) ? str_len : str_strlen(str, enc); + sub_len_char = in_byte ? sub_len : str_strlen(sub, enc); + if (offset < 0) { + offset += str_len_char; + if (offset < 0) return -1; + } + if (str_len_char - offset < sub_len_char) return -1; + if (!in_byte) offset = str_offset(str_ptr, str_ptr_end, offset, enc, single_byte); + str_ptr += offset; } if (sub_len == 0) return offset; @@ -3951,28 +3951,28 @@ rb_str_index_m(int argc, VALUE *argv, VALUE str) long pos; if (rb_scan_args(argc, argv, "11", &sub, &initpos) == 2) { - pos = NUM2LONG(initpos); + pos = NUM2LONG(initpos); } else { - pos = 0; + pos = 0; } if (pos < 0) { - pos += str_strlen(str, NULL); - if (pos < 0) { - if (RB_TYPE_P(sub, T_REGEXP)) { - rb_backref_set(Qnil); - } - return Qnil; - } + pos += str_strlen(str, NULL); + if (pos < 0) { + if (RB_TYPE_P(sub, T_REGEXP)) { + rb_backref_set(Qnil); + } + return Qnil; + } } if (RB_TYPE_P(sub, T_REGEXP)) { - if (pos > str_strlen(str, NULL)) - return Qnil; - pos = str_offset(RSTRING_PTR(str), RSTRING_END(str), pos, - rb_enc_check(str, sub), single_byte_optimizable(str)); + if (pos > str_strlen(str, NULL)) + return Qnil; + pos = str_offset(RSTRING_PTR(str), RSTRING_END(str), pos, + rb_enc_check(str, sub), single_byte_optimizable(str)); - if (rb_reg_search(sub, str, pos, 0) < 0) { + if (rb_reg_search(sub, str, pos, 0) < 0) { return Qnil; } else { @@ -3984,8 +3984,8 @@ rb_str_index_m(int argc, VALUE *argv, VALUE str) } else { StringValue(sub); - pos = rb_str_index(str, sub, pos); - pos = rb_str_sublen(str, pos); + pos = rb_str_index(str, sub, pos); + pos = rb_str_sublen(str, pos); } if (pos == -1) return Qnil; @@ -4115,16 +4115,16 @@ str_rindex(VALUE str, VALUE sub, const char *s, rb_encoding *enc) searchlen = s - sbeg + 1; do { - hit = memrchr(sbeg, c, searchlen); - if (!hit) break; - adjusted = rb_enc_left_char_head(sbeg, hit, e, enc); - if (hit != adjusted) { - searchlen = adjusted - sbeg; - continue; - } - if (memcmp(hit, t, slen) == 0) - return hit - sbeg; - searchlen = adjusted - sbeg; + hit = memrchr(sbeg, c, searchlen); + if (!hit) break; + adjusted = rb_enc_left_char_head(sbeg, hit, e, enc); + if (hit != adjusted) { + searchlen = adjusted - sbeg; + continue; + } + if (memcmp(hit, t, slen) == 0) + return hit - sbeg; + searchlen = adjusted - sbeg; } while (searchlen > 0); return -1; @@ -4142,11 +4142,11 @@ str_rindex(VALUE str, VALUE sub, const char *s, rb_encoding *enc) slen = RSTRING_LEN(sub); while (s) { - if (memcmp(s, t, slen) == 0) { - return s - sbeg; - } + if (memcmp(s, t, slen) == 0) { + return s - sbeg; + } if (s <= sbeg) break; - s = rb_enc_prev_char(sbeg, s, e, enc); + s = rb_enc_prev_char(sbeg, s, e, enc); } return -1; @@ -4175,10 +4175,10 @@ rb_str_rindex(VALUE str, VALUE sub, long pos) sbeg = RSTRING_PTR(str); if (pos == 0) { - if (memcmp(sbeg, RSTRING_PTR(sub), RSTRING_LEN(sub)) == 0) - return 0; - else - return -1; + if (memcmp(sbeg, RSTRING_PTR(sub), RSTRING_LEN(sub)) == 0) + return 0; + else + return -1; } s = str_nth(sbeg, RSTRING_END(str), pos, enc, singlebyte); @@ -4251,28 +4251,28 @@ rb_str_rindex_m(int argc, VALUE *argv, VALUE str) long pos, len = str_strlen(str, enc); /* str's enc */ if (rb_scan_args(argc, argv, "11", &sub, &vpos) == 2) { - pos = NUM2LONG(vpos); - if (pos < 0) { - pos += len; - if (pos < 0) { - if (RB_TYPE_P(sub, T_REGEXP)) { - rb_backref_set(Qnil); - } - return Qnil; - } - } - if (pos > len) pos = len; + pos = NUM2LONG(vpos); + if (pos < 0) { + pos += len; + if (pos < 0) { + if (RB_TYPE_P(sub, T_REGEXP)) { + rb_backref_set(Qnil); + } + return Qnil; + } + } + if (pos > len) pos = len; } else { - pos = len; + pos = len; } if (RB_TYPE_P(sub, T_REGEXP)) { - /* enc = rb_get_check(str, sub); */ - pos = str_offset(RSTRING_PTR(str), RSTRING_END(str), pos, - enc, single_byte_optimizable(str)); + /* enc = rb_get_check(str, sub); */ + pos = str_offset(RSTRING_PTR(str), RSTRING_END(str), pos, + enc, single_byte_optimizable(str)); - if (rb_reg_search(sub, str, pos, 1) >= 0) { + if (rb_reg_search(sub, str, pos, 1) >= 0) { VALUE match = rb_backref_get(); struct re_registers *regs = RMATCH_REGS(match); pos = rb_str_sublen(str, BEG(0)); @@ -4281,8 +4281,8 @@ rb_str_rindex_m(int argc, VALUE *argv, VALUE str) } else { StringValue(sub); - pos = rb_str_rindex(str, sub, pos); - if (pos >= 0) return LONG2NUM(pos); + pos = rb_str_rindex(str, sub, pos); + if (pos >= 0) return LONG2NUM(pos); } return Qnil; } @@ -4456,13 +4456,13 @@ rb_str_match(VALUE x, VALUE y) { switch (OBJ_BUILTIN_TYPE(y)) { case T_STRING: - rb_raise(rb_eTypeError, "type mismatch: String given"); + rb_raise(rb_eTypeError, "type mismatch: String given"); case T_REGEXP: - return rb_reg_match(y, x); + return rb_reg_match(y, x); default: - return rb_funcall(y, idEqTilde, 1, x); + return rb_funcall(y, idEqTilde, 1, x); } } @@ -4510,12 +4510,12 @@ rb_str_match_m(int argc, VALUE *argv, VALUE str) { VALUE re, result; if (argc < 1) - rb_check_arity(argc, 1, 2); + rb_check_arity(argc, 1, 2); re = argv[0]; argv[0] = str; result = rb_funcallv(get_pat(re), rb_intern("match"), argc, argv); if (!NIL_P(result) && rb_block_given_p()) { - return rb_yield(result); + return rb_yield(result); } return result; } @@ -4566,21 +4566,21 @@ enc_succ_char(char *p, long len, rb_encoding *enc) int l; if (rb_enc_mbminlen(enc) > 1) { - /* wchar, trivial case */ - int r = rb_enc_precise_mbclen(p, p + len, enc), c; - if (!MBCLEN_CHARFOUND_P(r)) { - return NEIGHBOR_NOT_CHAR; - } - c = rb_enc_mbc_to_codepoint(p, p + len, enc) + 1; - l = rb_enc_code_to_mbclen(c, enc); - if (!l) return NEIGHBOR_NOT_CHAR; - if (l != len) return NEIGHBOR_WRAPPED; - rb_enc_mbcput(c, p, enc); - r = rb_enc_precise_mbclen(p, p + len, enc); - if (!MBCLEN_CHARFOUND_P(r)) { - return NEIGHBOR_NOT_CHAR; - } - return NEIGHBOR_FOUND; + /* wchar, trivial case */ + int r = rb_enc_precise_mbclen(p, p + len, enc), c; + if (!MBCLEN_CHARFOUND_P(r)) { + return NEIGHBOR_NOT_CHAR; + } + c = rb_enc_mbc_to_codepoint(p, p + len, enc) + 1; + l = rb_enc_code_to_mbclen(c, enc); + if (!l) return NEIGHBOR_NOT_CHAR; + if (l != len) return NEIGHBOR_WRAPPED; + rb_enc_mbcput(c, p, enc); + r = rb_enc_precise_mbclen(p, p + len, enc); + if (!MBCLEN_CHARFOUND_P(r)) { + return NEIGHBOR_NOT_CHAR; + } + return NEIGHBOR_FOUND; } while (1) { for (i = len-1; 0 <= i && (unsigned char)p[i] == 0xff; i--) @@ -4617,23 +4617,23 @@ enc_pred_char(char *p, long len, rb_encoding *enc) long i; int l; if (rb_enc_mbminlen(enc) > 1) { - /* wchar, trivial case */ - int r = rb_enc_precise_mbclen(p, p + len, enc), c; - if (!MBCLEN_CHARFOUND_P(r)) { - return NEIGHBOR_NOT_CHAR; - } - c = rb_enc_mbc_to_codepoint(p, p + len, enc); - if (!c) return NEIGHBOR_NOT_CHAR; - --c; - l = rb_enc_code_to_mbclen(c, enc); - if (!l) return NEIGHBOR_NOT_CHAR; - if (l != len) return NEIGHBOR_WRAPPED; - rb_enc_mbcput(c, p, enc); - r = rb_enc_precise_mbclen(p, p + len, enc); - if (!MBCLEN_CHARFOUND_P(r)) { - return NEIGHBOR_NOT_CHAR; - } - return NEIGHBOR_FOUND; + /* wchar, trivial case */ + int r = rb_enc_precise_mbclen(p, p + len, enc), c; + if (!MBCLEN_CHARFOUND_P(r)) { + return NEIGHBOR_NOT_CHAR; + } + c = rb_enc_mbc_to_codepoint(p, p + len, enc); + if (!c) return NEIGHBOR_NOT_CHAR; + --c; + l = rb_enc_code_to_mbclen(c, enc); + if (!l) return NEIGHBOR_NOT_CHAR; + if (l != len) return NEIGHBOR_WRAPPED; + rb_enc_mbcput(c, p, enc); + r = rb_enc_precise_mbclen(p, p + len, enc); + if (!MBCLEN_CHARFOUND_P(r)) { + return NEIGHBOR_NOT_CHAR; + } + return NEIGHBOR_FOUND; } while (1) { for (i = len-1; 0 <= i && (unsigned char)p[i] == 0; i--) @@ -4696,12 +4696,12 @@ enc_succ_alnum_char(char *p, long len, rb_encoding *enc, char *carry) MEMCPY(save, p, char, len); for (try = 0; try <= max_gaps; ++try) { - ret = enc_succ_char(p, len, enc); - if (ret == NEIGHBOR_FOUND) { - c = rb_enc_mbc_to_codepoint(p, p+len, enc); - if (rb_enc_isctype(c, ctype, enc)) - return NEIGHBOR_FOUND; - } + ret = enc_succ_char(p, len, enc); + if (ret == NEIGHBOR_FOUND) { + c = rb_enc_mbc_to_codepoint(p, p+len, enc); + if (rb_enc_isctype(c, ctype, enc)) + return NEIGHBOR_FOUND; + } } MEMCPY(p, save, char, len); range = 1; @@ -4825,50 +4825,50 @@ str_succ(VALUE str) s = e = sbeg + slen; while ((s = rb_enc_prev_char(sbeg, s, e, enc)) != 0) { - if (neighbor == NEIGHBOR_NOT_CHAR && last_alnum) { - if (ISALPHA(*last_alnum) ? ISDIGIT(*s) : - ISDIGIT(*last_alnum) ? ISALPHA(*s) : 0) { - break; - } - } - l = rb_enc_precise_mbclen(s, e, enc); - if (!ONIGENC_MBCLEN_CHARFOUND_P(l)) continue; - l = ONIGENC_MBCLEN_CHARFOUND_LEN(l); + if (neighbor == NEIGHBOR_NOT_CHAR && last_alnum) { + if (ISALPHA(*last_alnum) ? ISDIGIT(*s) : + ISDIGIT(*last_alnum) ? ISALPHA(*s) : 0) { + break; + } + } + l = rb_enc_precise_mbclen(s, e, enc); + if (!ONIGENC_MBCLEN_CHARFOUND_P(l)) continue; + l = ONIGENC_MBCLEN_CHARFOUND_LEN(l); neighbor = enc_succ_alnum_char(s, l, enc, carry); switch (neighbor) { - case NEIGHBOR_NOT_CHAR: - continue; - case NEIGHBOR_FOUND: - return str; - case NEIGHBOR_WRAPPED: - last_alnum = s; - break; - } + case NEIGHBOR_NOT_CHAR: + continue; + case NEIGHBOR_FOUND: + return str; + case NEIGHBOR_WRAPPED: + last_alnum = s; + break; + } found_alnum = 1; carry_pos = s - sbeg; carry_len = l; } if (!found_alnum) { /* str contains no alnum */ - s = e; - while ((s = rb_enc_prev_char(sbeg, s, e, enc)) != 0) { + s = e; + while ((s = rb_enc_prev_char(sbeg, s, e, enc)) != 0) { enum neighbor_char neighbor; - char tmp[ONIGENC_CODE_TO_MBC_MAXLEN]; - l = rb_enc_precise_mbclen(s, e, enc); - if (!ONIGENC_MBCLEN_CHARFOUND_P(l)) continue; - l = ONIGENC_MBCLEN_CHARFOUND_LEN(l); - MEMCPY(tmp, s, char, l); - neighbor = enc_succ_char(tmp, l, enc); - switch (neighbor) { - case NEIGHBOR_FOUND: - MEMCPY(s, tmp, char, l); + char tmp[ONIGENC_CODE_TO_MBC_MAXLEN]; + l = rb_enc_precise_mbclen(s, e, enc); + if (!ONIGENC_MBCLEN_CHARFOUND_P(l)) continue; + l = ONIGENC_MBCLEN_CHARFOUND_LEN(l); + MEMCPY(tmp, s, char, l); + neighbor = enc_succ_char(tmp, l, enc); + switch (neighbor) { + case NEIGHBOR_FOUND: + MEMCPY(s, tmp, char, l); return str; - break; - case NEIGHBOR_WRAPPED: - MEMCPY(s, tmp, char, l); - break; - case NEIGHBOR_NOT_CHAR: - break; - } + break; + case NEIGHBOR_WRAPPED: + MEMCPY(s, tmp, char, l); + break; + case NEIGHBOR_NOT_CHAR: + break; + } if (rb_enc_precise_mbclen(s, s+l, enc) != l) { /* wrapped to \0...\0. search next valid char. */ enc_succ_char(s, l, enc); @@ -4878,8 +4878,8 @@ str_succ(VALUE str) carry_len = l; } carry_pos = s - sbeg; - } - ENC_CODERANGE_SET(str, ENC_CODERANGE_UNKNOWN); + } + ENC_CODERANGE_SET(str, ENC_CODERANGE_UNKNOWN); } RESIZE_CAPA(str, slen + carry_len); sbeg = RSTRING_PTR(str); @@ -4915,8 +4915,8 @@ static int all_digits_p(const char *s, long len) { while (len-- > 0) { - if (!ISDIGIT(*s)) return 0; - s++; + if (!ISDIGIT(*s)) return 0; + s++; } return 1; } @@ -4987,51 +4987,51 @@ rb_str_upto_each(VALUE beg, VALUE end, int excl, int (*each)(VALUE, VALUE), VALU ascii = (is_ascii_string(beg) && is_ascii_string(end)); /* single character */ if (RSTRING_LEN(beg) == 1 && RSTRING_LEN(end) == 1 && ascii) { - char c = RSTRING_PTR(beg)[0]; - char e = RSTRING_PTR(end)[0]; + char c = RSTRING_PTR(beg)[0]; + char e = RSTRING_PTR(end)[0]; - if (c > e || (excl && c == e)) return beg; - for (;;) { - if ((*each)(rb_enc_str_new(&c, 1, enc), arg)) break; - if (!excl && c == e) break; - c++; - if (excl && c == e) break; - } - return beg; + if (c > e || (excl && c == e)) return beg; + for (;;) { + if ((*each)(rb_enc_str_new(&c, 1, enc), arg)) break; + if (!excl && c == e) break; + c++; + if (excl && c == e) break; + } + return beg; } /* both edges are all digits */ if (ascii && ISDIGIT(RSTRING_PTR(beg)[0]) && ISDIGIT(RSTRING_PTR(end)[0]) && - all_digits_p(RSTRING_PTR(beg), RSTRING_LEN(beg)) && - all_digits_p(RSTRING_PTR(end), RSTRING_LEN(end))) { - VALUE b, e; - int width; + all_digits_p(RSTRING_PTR(beg), RSTRING_LEN(beg)) && + all_digits_p(RSTRING_PTR(end), RSTRING_LEN(end))) { + VALUE b, e; + int width; - width = RSTRING_LENINT(beg); - b = rb_str_to_inum(beg, 10, FALSE); - e = rb_str_to_inum(end, 10, FALSE); - if (FIXNUM_P(b) && FIXNUM_P(e)) { - long bi = FIX2LONG(b); - long ei = FIX2LONG(e); - rb_encoding *usascii = rb_usascii_encoding(); + width = RSTRING_LENINT(beg); + b = rb_str_to_inum(beg, 10, FALSE); + e = rb_str_to_inum(end, 10, FALSE); + if (FIXNUM_P(b) && FIXNUM_P(e)) { + long bi = FIX2LONG(b); + long ei = FIX2LONG(e); + rb_encoding *usascii = rb_usascii_encoding(); - while (bi <= ei) { - if (excl && bi == ei) break; - if ((*each)(rb_enc_sprintf(usascii, "%.*ld", width, bi), arg)) break; - bi++; - } - } - else { - ID op = excl ? '<' : idLE; - VALUE args[2], fmt = rb_fstring_lit("%.*d"); + while (bi <= ei) { + if (excl && bi == ei) break; + if ((*each)(rb_enc_sprintf(usascii, "%.*ld", width, bi), arg)) break; + bi++; + } + } + else { + ID op = excl ? '<' : idLE; + VALUE args[2], fmt = rb_fstring_lit("%.*d"); - args[0] = INT2FIX(width); - while (rb_funcall(b, op, 1, e)) { - args[1] = b; - if ((*each)(rb_str_format(numberof(args), args, fmt), arg)) break; - b = rb_funcallv(b, succ, 0, 0); - } - } - return beg; + args[0] = INT2FIX(width); + while (rb_funcall(b, op, 1, e)) { + args[1] = b; + if ((*each)(rb_str_format(numberof(args), args, fmt), arg)) break; + b = rb_funcallv(b, succ, 0, 0); + } + } + return beg; } /* normal case */ n = rb_str_cmp(beg, end); @@ -5040,16 +5040,16 @@ rb_str_upto_each(VALUE beg, VALUE end, int excl, int (*each)(VALUE, VALUE), VALU after_end = rb_funcallv(end, succ, 0, 0); current = str_duplicate(rb_cString, beg); while (!rb_str_equal(current, after_end)) { - VALUE next = Qnil; - if (excl || !rb_str_equal(current, end)) - next = rb_funcallv(current, succ, 0, 0); - if ((*each)(current, arg)) break; - if (NIL_P(next)) break; - current = next; - StringValue(current); - if (excl && rb_str_equal(current, end)) break; - if (RSTRING_LEN(current) > RSTRING_LEN(end) || RSTRING_LEN(current) == 0) - break; + VALUE next = Qnil; + if (excl || !rb_str_equal(current, end)) + next = rb_funcallv(current, succ, 0, 0); + if ((*each)(current, arg)) break; + if (NIL_P(next)) break; + current = next; + StringValue(current); + if (excl && rb_str_equal(current, end)) break; + if (RSTRING_LEN(current) > RSTRING_LEN(end) || RSTRING_LEN(current) == 0) + break; } return beg; @@ -5064,36 +5064,36 @@ rb_str_upto_endless_each(VALUE beg, int (*each)(VALUE, VALUE), VALUE arg) CONST_ID(succ, "succ"); /* both edges are all digits */ if (is_ascii_string(beg) && ISDIGIT(RSTRING_PTR(beg)[0]) && - all_digits_p(RSTRING_PTR(beg), RSTRING_LEN(beg))) { - VALUE b, args[2], fmt = rb_fstring_lit("%.*d"); - int width = RSTRING_LENINT(beg); - b = rb_str_to_inum(beg, 10, FALSE); - if (FIXNUM_P(b)) { - long bi = FIX2LONG(b); - rb_encoding *usascii = rb_usascii_encoding(); + all_digits_p(RSTRING_PTR(beg), RSTRING_LEN(beg))) { + VALUE b, args[2], fmt = rb_fstring_lit("%.*d"); + int width = RSTRING_LENINT(beg); + b = rb_str_to_inum(beg, 10, FALSE); + if (FIXNUM_P(b)) { + long bi = FIX2LONG(b); + rb_encoding *usascii = rb_usascii_encoding(); - while (FIXABLE(bi)) { - if ((*each)(rb_enc_sprintf(usascii, "%.*ld", width, bi), arg)) break; - bi++; - } - b = LONG2NUM(bi); - } - args[0] = INT2FIX(width); - while (1) { - args[1] = b; - if ((*each)(rb_str_format(numberof(args), args, fmt), arg)) break; - b = rb_funcallv(b, succ, 0, 0); - } + while (FIXABLE(bi)) { + if ((*each)(rb_enc_sprintf(usascii, "%.*ld", width, bi), arg)) break; + bi++; + } + b = LONG2NUM(bi); + } + args[0] = INT2FIX(width); + while (1) { + args[1] = b; + if ((*each)(rb_str_format(numberof(args), args, fmt), arg)) break; + b = rb_funcallv(b, succ, 0, 0); + } } /* normal case */ current = str_duplicate(rb_cString, beg); while (1) { - VALUE next = rb_funcallv(current, succ, 0, 0); - if ((*each)(current, arg)) break; - current = next; - StringValue(current); - if (RSTRING_LEN(current) == 0) - break; + VALUE next = rb_funcallv(current, succ, 0, 0); + if ((*each)(current, arg)) break; + current = next; + StringValue(current); + if (RSTRING_LEN(current) == 0) + break; } return beg; @@ -5118,32 +5118,32 @@ rb_str_include_range_p(VALUE beg, VALUE end, VALUE val, VALUE exclusive) val = rb_check_string_type(val); if (NIL_P(val)) return Qfalse; if (rb_enc_asciicompat(STR_ENC_GET(beg)) && - rb_enc_asciicompat(STR_ENC_GET(end)) && - rb_enc_asciicompat(STR_ENC_GET(val))) { - const char *bp = RSTRING_PTR(beg); - const char *ep = RSTRING_PTR(end); - const char *vp = RSTRING_PTR(val); - if (RSTRING_LEN(beg) == 1 && RSTRING_LEN(end) == 1) { - if (RSTRING_LEN(val) == 0 || RSTRING_LEN(val) > 1) - return Qfalse; - else { - char b = *bp; - char e = *ep; - char v = *vp; + rb_enc_asciicompat(STR_ENC_GET(end)) && + rb_enc_asciicompat(STR_ENC_GET(val))) { + const char *bp = RSTRING_PTR(beg); + const char *ep = RSTRING_PTR(end); + const char *vp = RSTRING_PTR(val); + if (RSTRING_LEN(beg) == 1 && RSTRING_LEN(end) == 1) { + if (RSTRING_LEN(val) == 0 || RSTRING_LEN(val) > 1) + return Qfalse; + else { + char b = *bp; + char e = *ep; + char v = *vp; - if (ISASCII(b) && ISASCII(e) && ISASCII(v)) { - if (b <= v && v < e) return Qtrue; - return RBOOL(!RTEST(exclusive) && v == e); - } - } - } + if (ISASCII(b) && ISASCII(e) && ISASCII(v)) { + if (b <= v && v < e) return Qtrue; + return RBOOL(!RTEST(exclusive) && v == e); + } + } + } #if 0 - /* both edges are all digits */ - if (ISDIGIT(*bp) && ISDIGIT(*ep) && - all_digits_p(bp, RSTRING_LEN(beg)) && - all_digits_p(ep, RSTRING_LEN(end))) { - /* TODO */ - } + /* both edges are all digits */ + if (ISDIGIT(*bp) && ISDIGIT(*ep) && + all_digits_p(bp, RSTRING_LEN(beg)) && + all_digits_p(ep, RSTRING_LEN(end))) { + /* TODO */ + } #endif } rb_str_upto_each(beg, end, RTEST(exclusive), include_range_i, (VALUE)&val); @@ -5157,7 +5157,7 @@ rb_str_subpat(VALUE str, VALUE re, VALUE backref) if (rb_reg_search(re, str, 0, 0) >= 0) { VALUE match = rb_backref_get(); int nth = rb_reg_backref_number(match, backref); - return rb_reg_nth_match(nth, match); + return rb_reg_nth_match(nth, match); } return Qnil; } @@ -5168,28 +5168,28 @@ rb_str_aref(VALUE str, VALUE indx) long idx; if (FIXNUM_P(indx)) { - idx = FIX2LONG(indx); + idx = FIX2LONG(indx); } else if (RB_TYPE_P(indx, T_REGEXP)) { - return rb_str_subpat(str, indx, INT2FIX(0)); + return rb_str_subpat(str, indx, INT2FIX(0)); } else if (RB_TYPE_P(indx, T_STRING)) { - if (rb_str_index(str, indx, 0) != -1) + if (rb_str_index(str, indx, 0) != -1) return str_duplicate(rb_cString, indx); - return Qnil; + return Qnil; } else { - /* check if indx is Range */ - long beg, len = str_strlen(str, NULL); - switch (rb_range_beg_len(indx, &beg, &len, len, 0)) { - case Qfalse: - break; - case Qnil: - return Qnil; - default: - return rb_str_substr(str, beg, len); - } - idx = NUM2LONG(indx); + /* check if indx is Range */ + long beg, len = str_strlen(str, NULL); + switch (rb_range_beg_len(indx, &beg, &len, len, 0)) { + case Qfalse: + break; + case Qnil: + return Qnil; + default: + return rb_str_substr(str, beg, len); + } + idx = NUM2LONG(indx); } return str_substr(str, idx, 1, FALSE); @@ -5214,14 +5214,14 @@ static VALUE rb_str_aref_m(int argc, VALUE *argv, VALUE str) { if (argc == 2) { - if (RB_TYPE_P(argv[0], T_REGEXP)) { - return rb_str_subpat(str, argv[0], argv[1]); - } - else { - long beg = NUM2LONG(argv[0]); - long len = NUM2LONG(argv[1]); - return rb_str_substr(str, beg, len); - } + if (RB_TYPE_P(argv[0], T_REGEXP)) { + return rb_str_subpat(str, argv[0], argv[1]); + } + else { + long beg = NUM2LONG(argv[0]); + long len = NUM2LONG(argv[1]); + return rb_str_substr(str, beg, len); + } } rb_check_arity(argc, 1, 2); return rb_str_aref(str, argv[0]); @@ -5237,13 +5237,13 @@ rb_str_drop_bytes(VALUE str, long len) if (len > olen) len = olen; nlen = olen - len; if (str_embed_capa(str) >= nlen + TERM_LEN(str)) { - char *oldptr = ptr; - int fl = (int)(RBASIC(str)->flags & (STR_NOEMBED|STR_SHARED|STR_NOFREE)); - STR_SET_EMBED(str); - STR_SET_EMBED_LEN(str, nlen); + char *oldptr = ptr; + int fl = (int)(RBASIC(str)->flags & (STR_NOEMBED|STR_SHARED|STR_NOFREE)); + STR_SET_EMBED(str); + STR_SET_EMBED_LEN(str, nlen); ptr = RSTRING(str)->as.embed.ary; - memmove(ptr, oldptr + len, nlen); - if (fl == STR_NOEMBED) xfree(oldptr); + memmove(ptr, oldptr + len, nlen); + if (fl == STR_NOEMBED) xfree(oldptr); } else { if (!STR_SHARED_P(str)) { @@ -5251,8 +5251,8 @@ rb_str_drop_bytes(VALUE str, long len) rb_enc_cr_str_exact_copy(shared, str); OBJ_FREEZE(shared); } - ptr = RSTRING(str)->as.heap.ptr += len; - RSTRING(str)->as.heap.len = nlen; + ptr = RSTRING(str)->as.heap.ptr += len; + RSTRING(str)->as.heap.len = nlen; } ptr[nlen] = 0; ENC_CODERANGE_CLEAR(str); @@ -5267,33 +5267,33 @@ rb_str_splice_0(VALUE str, long beg, long len, VALUE val) int cr; if (beg == 0 && vlen == 0) { - rb_str_drop_bytes(str, len); - return; + rb_str_drop_bytes(str, len); + return; } str_modify_keep_cr(str); RSTRING_GETMEM(str, sptr, slen); if (len < vlen) { - /* expand string */ - RESIZE_CAPA(str, slen + vlen - len); - sptr = RSTRING_PTR(str); + /* expand string */ + RESIZE_CAPA(str, slen + vlen - len); + sptr = RSTRING_PTR(str); } if (ENC_CODERANGE(str) == ENC_CODERANGE_7BIT) - cr = rb_enc_str_coderange(val); + cr = rb_enc_str_coderange(val); else - cr = ENC_CODERANGE_UNKNOWN; + cr = ENC_CODERANGE_UNKNOWN; if (vlen != len) { - memmove(sptr + beg + vlen, - sptr + beg + len, - slen - (beg + len)); + memmove(sptr + beg + vlen, + sptr + beg + len, + slen - (beg + len)); } if (vlen < beg && len < 0) { - MEMZERO(sptr + slen, char, -len); + MEMZERO(sptr + slen, char, -len); } if (vlen > 0) { - memmove(sptr + beg, RSTRING_PTR(val), vlen); + memmove(sptr + beg, RSTRING_PTR(val), vlen); } slen += vlen - len; STR_SET_LEN(str, slen); @@ -5317,15 +5317,15 @@ rb_str_update(VALUE str, long beg, long len, VALUE val) slen = str_strlen(str, enc); /* rb_enc_check */ if ((slen < beg) || ((beg < 0) && (beg + slen < 0))) { - rb_raise(rb_eIndexError, "index %ld out of string", beg); + rb_raise(rb_eIndexError, "index %ld out of string", beg); } if (beg < 0) { - beg += slen; + beg += slen; } assert(beg >= 0); assert(beg <= slen); if (len > slen - beg) { - len = slen - beg; + len = slen - beg; } str_modify_keep_cr(str); p = str_nth(RSTRING_PTR(str), RSTRING_END(str), beg, enc, singlebyte); @@ -5339,7 +5339,7 @@ rb_str_update(VALUE str, long beg, long len, VALUE val) rb_enc_associate(str, enc); cr = ENC_CODERANGE_AND(ENC_CODERANGE(str), ENC_CODERANGE(val)); if (cr != ENC_CODERANGE_BROKEN) - ENC_CODERANGE_SET(str, cr); + ENC_CODERANGE_SET(str, cr); } #define rb_str_splice(str, beg, len, val) rb_str_update(str, beg, len, val) @@ -5354,21 +5354,21 @@ rb_str_subpat_set(VALUE str, VALUE re, VALUE backref, VALUE val) struct re_registers *regs; if (rb_reg_search(re, str, 0, 0) < 0) { - rb_raise(rb_eIndexError, "regexp not matched"); + rb_raise(rb_eIndexError, "regexp not matched"); } match = rb_backref_get(); nth = rb_reg_backref_number(match, backref); regs = RMATCH_REGS(match); if ((nth >= regs->num_regs) || ((nth < 0) && (-nth >= regs->num_regs))) { - rb_raise(rb_eIndexError, "index %d out of regexp", nth); + rb_raise(rb_eIndexError, "index %d out of regexp", nth); } if (nth < 0) { - nth += regs->num_regs; + nth += regs->num_regs; } start = BEG(nth); if (start == -1) { - rb_raise(rb_eIndexError, "regexp group %d not matched", nth); + rb_raise(rb_eIndexError, "regexp group %d not matched", nth); } end = END(nth); len = end - start; @@ -5385,31 +5385,31 @@ rb_str_aset(VALUE str, VALUE indx, VALUE val) switch (TYPE(indx)) { case T_REGEXP: - rb_str_subpat_set(str, indx, INT2FIX(0), val); - return val; + rb_str_subpat_set(str, indx, INT2FIX(0), val); + return val; case T_STRING: - beg = rb_str_index(str, indx, 0); - if (beg < 0) { - rb_raise(rb_eIndexError, "string not matched"); - } - beg = rb_str_sublen(str, beg); - rb_str_splice(str, beg, str_strlen(indx, NULL), val); - return val; + beg = rb_str_index(str, indx, 0); + if (beg < 0) { + rb_raise(rb_eIndexError, "string not matched"); + } + beg = rb_str_sublen(str, beg); + rb_str_splice(str, beg, str_strlen(indx, NULL), val); + return val; default: - /* check if indx is Range */ - { - long beg, len; - if (rb_range_beg_len(indx, &beg, &len, str_strlen(str, NULL), 2)) { - rb_str_splice(str, beg, len, val); - return val; - } - } + /* check if indx is Range */ + { + long beg, len; + if (rb_range_beg_len(indx, &beg, &len, str_strlen(str, NULL), 2)) { + rb_str_splice(str, beg, len, val); + return val; + } + } /* FALLTHROUGH */ case T_FIXNUM: - idx = NUM2LONG(indx); + idx = NUM2LONG(indx); rb_str_splice(str, idx, 1, val); return val; } @@ -5448,13 +5448,13 @@ static VALUE rb_str_aset_m(int argc, VALUE *argv, VALUE str) { if (argc == 3) { - if (RB_TYPE_P(argv[0], T_REGEXP)) { - rb_str_subpat_set(str, argv[0], argv[1], argv[2]); - } - else { - rb_str_splice(str, NUM2LONG(argv[0]), NUM2LONG(argv[1]), argv[2]); - } - return argv[2]; + if (RB_TYPE_P(argv[0], T_REGEXP)) { + rb_str_subpat_set(str, argv[0], argv[1], argv[2]); + } + else { + rb_str_splice(str, NUM2LONG(argv[0]), NUM2LONG(argv[1]), argv[2]); + } + return argv[2]; } rb_check_arity(argc, 2, 3); return rb_str_aset(str, argv[0], argv[1]); @@ -5484,10 +5484,10 @@ rb_str_insert(VALUE str, VALUE idx, VALUE str2) long pos = NUM2LONG(idx); if (pos == -1) { - return rb_str_append(str, str2); + return rb_str_append(str, str2); } else if (pos < 0) { - pos++; + pos++; } rb_str_splice(str, pos, 0, str2); return str; @@ -5528,50 +5528,50 @@ rb_str_slice_bang(int argc, VALUE *argv, VALUE str) str_modify_keep_cr(str); indx = argv[0]; if (RB_TYPE_P(indx, T_REGEXP)) { - if (rb_reg_search(indx, str, 0, 0) < 0) return Qnil; - VALUE match = rb_backref_get(); - struct re_registers *regs = RMATCH_REGS(match); - int nth = 0; - if (argc > 1 && (nth = rb_reg_backref_number(match, argv[1])) < 0) { - if ((nth += regs->num_regs) <= 0) return Qnil; - } - else if (nth >= regs->num_regs) return Qnil; - beg = BEG(nth); - len = END(nth) - beg; + if (rb_reg_search(indx, str, 0, 0) < 0) return Qnil; + VALUE match = rb_backref_get(); + struct re_registers *regs = RMATCH_REGS(match); + int nth = 0; + if (argc > 1 && (nth = rb_reg_backref_number(match, argv[1])) < 0) { + if ((nth += regs->num_regs) <= 0) return Qnil; + } + else if (nth >= regs->num_regs) return Qnil; + beg = BEG(nth); + len = END(nth) - beg; goto subseq; } else if (argc == 2) { - beg = NUM2LONG(indx); - len = NUM2LONG(argv[1]); + beg = NUM2LONG(indx); + len = NUM2LONG(argv[1]); goto num_index; } else if (FIXNUM_P(indx)) { - beg = FIX2LONG(indx); - if (!(p = rb_str_subpos(str, beg, &len))) return Qnil; - if (!len) return Qnil; - beg = p - RSTRING_PTR(str); - goto subseq; + beg = FIX2LONG(indx); + if (!(p = rb_str_subpos(str, beg, &len))) return Qnil; + if (!len) return Qnil; + beg = p - RSTRING_PTR(str); + goto subseq; } else if (RB_TYPE_P(indx, T_STRING)) { - beg = rb_str_index(str, indx, 0); - if (beg == -1) return Qnil; - len = RSTRING_LEN(indx); + beg = rb_str_index(str, indx, 0); + if (beg == -1) return Qnil; + len = RSTRING_LEN(indx); result = str_duplicate(rb_cString, indx); goto squash; } else { - switch (rb_range_beg_len(indx, &beg, &len, str_strlen(str, NULL), 0)) { - case Qnil: - return Qnil; - case Qfalse: - beg = NUM2LONG(indx); - if (!(p = rb_str_subpos(str, beg, &len))) return Qnil; - if (!len) return Qnil; - beg = p - RSTRING_PTR(str); - goto subseq; - default: - goto num_index; - } + switch (rb_range_beg_len(indx, &beg, &len, str_strlen(str, NULL), 0)) { + case Qnil: + return Qnil; + case Qfalse: + beg = NUM2LONG(indx); + if (!(p = rb_str_subpos(str, beg, &len))) return Qnil; + if (!len) return Qnil; + beg = p - RSTRING_PTR(str); + goto subseq; + default: + goto num_index; + } } num_index: @@ -5584,21 +5584,21 @@ rb_str_slice_bang(int argc, VALUE *argv, VALUE str) squash: if (len > 0) { - if (beg == 0) { - rb_str_drop_bytes(str, len); - } - else { - char *sptr = RSTRING_PTR(str); - long slen = RSTRING_LEN(str); - if (beg + len > slen) /* pathological check */ - len = slen - beg; - memmove(sptr + beg, - sptr + beg + len, - slen - (beg + len)); - slen -= len; - STR_SET_LEN(str, slen); - TERM_FILL(&sptr[slen], TERM_LEN(str)); - } + if (beg == 0) { + rb_str_drop_bytes(str, len); + } + else { + char *sptr = RSTRING_PTR(str); + long slen = RSTRING_LEN(str); + if (beg + len > slen) /* pathological check */ + len = slen - beg; + memmove(sptr + beg, + sptr + beg + len, + slen - (beg + len)); + slen -= len; + STR_SET_LEN(str, slen); + TERM_FILL(&sptr[slen], TERM_LEN(str)); + } } return result; } @@ -5610,17 +5610,17 @@ get_pat(VALUE pat) switch (OBJ_BUILTIN_TYPE(pat)) { case T_REGEXP: - return pat; + return pat; case T_STRING: - break; + break; default: - val = rb_check_string_type(pat); - if (NIL_P(val)) { - Check_Type(pat, T_REGEXP); - } - pat = val; + val = rb_check_string_type(pat); + if (NIL_P(val)) { + Check_Type(pat, T_REGEXP); + } + pat = val; } return rb_reg_regcomp(pat); @@ -5633,20 +5633,20 @@ get_pat_quoted(VALUE pat, int check) switch (OBJ_BUILTIN_TYPE(pat)) { case T_REGEXP: - return pat; + return pat; case T_STRING: - break; + break; default: - val = rb_check_string_type(pat); - if (NIL_P(val)) { - Check_Type(pat, T_REGEXP); - } - pat = val; + val = rb_check_string_type(pat); + if (NIL_P(val)) { + Check_Type(pat, T_REGEXP); + } + pat = val; } if (check && is_broken_string(pat)) { - rb_exc_raise(rb_reg_check_preprocess(pat)); + rb_exc_raise(rb_reg_check_preprocess(pat)); } return pat; } @@ -5655,20 +5655,20 @@ static long rb_pat_search(VALUE pat, VALUE str, long pos, int set_backref_str) { if (BUILTIN_TYPE(pat) == T_STRING) { - pos = rb_strseq_index(str, pat, pos, 1); - if (set_backref_str) { - if (pos >= 0) { + pos = rb_strseq_index(str, pat, pos, 1); + if (set_backref_str) { + if (pos >= 0) { str = rb_str_new_frozen_String(str); - rb_backref_set_string(str, pos, RSTRING_LEN(pat)); - } - else { - rb_backref_set(Qnil); - } - } - return pos; + rb_backref_set_string(str, pos, RSTRING_LEN(pat)); + } + else { + rb_backref_set(Qnil); + } + } + return pos; } else { - return rb_reg_search0(pat, str, pos, 0, set_backref_str); + return rb_reg_search0(pat, str, pos, 0, set_backref_str); } } @@ -5698,14 +5698,14 @@ rb_str_sub_bang(int argc, VALUE *argv, VALUE str) rb_check_arity(argc, min_arity, 2); if (argc == 1) { - iter = 1; + iter = 1; } else { - repl = argv[1]; - hash = rb_check_hash_type(argv[1]); - if (NIL_P(hash)) { - StringValue(repl); - } + repl = argv[1]; + hash = rb_check_hash_type(argv[1]); + if (NIL_P(hash)) { + StringValue(repl); + } } pat = get_pat_quoted(argv[0], 1); @@ -5713,29 +5713,29 @@ rb_str_sub_bang(int argc, VALUE *argv, VALUE str) str_modifiable(str); beg = rb_pat_search(pat, str, 0, 1); if (beg >= 0) { - rb_encoding *enc; - int cr = ENC_CODERANGE(str); - long beg0, end0; - VALUE match, match0 = Qnil; - struct re_registers *regs; - char *p, *rp; - long len, rlen; + rb_encoding *enc; + int cr = ENC_CODERANGE(str); + long beg0, end0; + VALUE match, match0 = Qnil; + struct re_registers *regs; + char *p, *rp; + long len, rlen; - match = rb_backref_get(); - regs = RMATCH_REGS(match); - if (RB_TYPE_P(pat, T_STRING)) { - beg0 = beg; - end0 = beg0 + RSTRING_LEN(pat); - match0 = pat; - } - else { - beg0 = BEG(0); - end0 = END(0); - if (iter) match0 = rb_reg_nth_match(0, match); - } + match = rb_backref_get(); + regs = RMATCH_REGS(match); + if (RB_TYPE_P(pat, T_STRING)) { + beg0 = beg; + end0 = beg0 + RSTRING_LEN(pat); + match0 = pat; + } + else { + beg0 = BEG(0); + end0 = END(0); + if (iter) match0 = rb_reg_nth_match(0, match); + } - if (iter || !NIL_P(hash)) { - p = RSTRING_PTR(str); len = RSTRING_LEN(str); + if (iter || !NIL_P(hash)) { + p = RSTRING_PTR(str); len = RSTRING_LEN(str); if (iter) { repl = rb_obj_as_string(rb_yield(match0)); @@ -5744,53 +5744,53 @@ rb_str_sub_bang(int argc, VALUE *argv, VALUE str) repl = rb_hash_aref(hash, rb_str_subseq(str, beg0, end0 - beg0)); repl = rb_obj_as_string(repl); } - str_mod_check(str, p, len); - rb_check_frozen(str); - } - else { - repl = rb_reg_regsub(repl, str, regs, RB_TYPE_P(pat, T_STRING) ? Qnil : pat); - } + str_mod_check(str, p, len); + rb_check_frozen(str); + } + else { + repl = rb_reg_regsub(repl, str, regs, RB_TYPE_P(pat, T_STRING) ? Qnil : pat); + } enc = rb_enc_compatible(str, repl); if (!enc) { rb_encoding *str_enc = STR_ENC_GET(str); - p = RSTRING_PTR(str); len = RSTRING_LEN(str); - if (coderange_scan(p, beg0, str_enc) != ENC_CODERANGE_7BIT || - coderange_scan(p+end0, len-end0, str_enc) != ENC_CODERANGE_7BIT) { + p = RSTRING_PTR(str); len = RSTRING_LEN(str); + if (coderange_scan(p, beg0, str_enc) != ENC_CODERANGE_7BIT || + coderange_scan(p+end0, len-end0, str_enc) != ENC_CODERANGE_7BIT) { rb_raise(rb_eEncCompatError, "incompatible character encodings: %s and %s", - rb_enc_name(str_enc), - rb_enc_name(STR_ENC_GET(repl))); + rb_enc_name(str_enc), + rb_enc_name(STR_ENC_GET(repl))); } enc = STR_ENC_GET(repl); } - rb_str_modify(str); - rb_enc_associate(str, enc); - if (ENC_CODERANGE_UNKNOWN < cr && cr < ENC_CODERANGE_BROKEN) { - int cr2 = ENC_CODERANGE(repl); + rb_str_modify(str); + rb_enc_associate(str, enc); + if (ENC_CODERANGE_UNKNOWN < cr && cr < ENC_CODERANGE_BROKEN) { + int cr2 = ENC_CODERANGE(repl); if (cr2 == ENC_CODERANGE_BROKEN || (cr == ENC_CODERANGE_VALID && cr2 == ENC_CODERANGE_7BIT)) cr = ENC_CODERANGE_UNKNOWN; else cr = cr2; - } - plen = end0 - beg0; + } + plen = end0 - beg0; rlen = RSTRING_LEN(repl); - len = RSTRING_LEN(str); - if (rlen > plen) { - RESIZE_CAPA(str, len + rlen - plen); - } - p = RSTRING_PTR(str); - if (rlen != plen) { - memmove(p + beg0 + rlen, p + beg0 + plen, len - beg0 - plen); - } + len = RSTRING_LEN(str); + if (rlen > plen) { + RESIZE_CAPA(str, len + rlen - plen); + } + p = RSTRING_PTR(str); + if (rlen != plen) { + memmove(p + beg0 + rlen, p + beg0 + plen, len - beg0 - plen); + } rp = RSTRING_PTR(repl); memmove(p + beg0, rp, rlen); - len += rlen - plen; - STR_SET_LEN(str, len); - TERM_FILL(&RSTRING_PTR(str)[len], TERM_LEN(str)); - ENC_CODERANGE_SET(str, cr); + len += rlen - plen; + STR_SET_LEN(str, len); + TERM_FILL(&RSTRING_PTR(str)[len], TERM_LEN(str)); + ENC_CODERANGE_SET(str, cr); - return str; + return str; } return Qnil; } @@ -5832,19 +5832,19 @@ str_gsub(int argc, VALUE *argv, VALUE str, int bang) switch (argc) { case 1: - RETURN_ENUMERATOR(str, argc, argv); - mode = ITER; - break; + RETURN_ENUMERATOR(str, argc, argv); + mode = ITER; + break; case 2: - repl = argv[1]; - hash = rb_check_hash_type(argv[1]); - if (NIL_P(hash)) { - StringValue(repl); - } - else { - mode = MAP; - } - break; + repl = argv[1]; + hash = rb_check_hash_type(argv[1]); + if (NIL_P(hash)) { + StringValue(repl); + } + else { + mode = MAP; + } + break; default: rb_error_arity(argc, 1, 2); } @@ -5852,7 +5852,7 @@ str_gsub(int argc, VALUE *argv, VALUE str, int bang) pat = get_pat_quoted(argv[0], 1); beg = rb_pat_search(pat, str, 0, need_backref); if (beg < 0) { - if (bang) return Qnil; /* no match, no substitution */ + if (bang) return Qnil; /* no match, no substitution */ return str_duplicate(rb_cString, str); } @@ -5867,20 +5867,20 @@ str_gsub(int argc, VALUE *argv, VALUE str, int bang) ENC_CODERANGE_SET(dest, rb_enc_asciicompat(str_enc) ? ENC_CODERANGE_7BIT : ENC_CODERANGE_VALID); do { - match = rb_backref_get(); - regs = RMATCH_REGS(match); - if (RB_TYPE_P(pat, T_STRING)) { - beg0 = beg; - end0 = beg0 + RSTRING_LEN(pat); - match0 = pat; - } - else { - beg0 = BEG(0); - end0 = END(0); - if (mode == ITER) match0 = rb_reg_nth_match(0, match); - } + match = rb_backref_get(); + regs = RMATCH_REGS(match); + if (RB_TYPE_P(pat, T_STRING)) { + beg0 = beg; + end0 = beg0 + RSTRING_LEN(pat); + match0 = pat; + } + else { + beg0 = BEG(0); + end0 = END(0); + if (mode == ITER) match0 = rb_reg_nth_match(0, match); + } - if (mode) { + if (mode) { if (mode == ITER) { val = rb_obj_as_string(rb_yield(match0)); } @@ -5888,43 +5888,43 @@ str_gsub(int argc, VALUE *argv, VALUE str, int bang) val = rb_hash_aref(hash, rb_str_subseq(str, beg0, end0 - beg0)); val = rb_obj_as_string(val); } - str_mod_check(str, sp, slen); - if (val == dest) { /* paranoid check [ruby-dev:24827] */ - rb_raise(rb_eRuntimeError, "block should not cheat"); - } - } - else if (need_backref) { - val = rb_reg_regsub(repl, str, regs, RB_TYPE_P(pat, T_STRING) ? Qnil : pat); - if (need_backref < 0) { - need_backref = val != repl; - } - } - else { - val = repl; - } + str_mod_check(str, sp, slen); + if (val == dest) { /* paranoid check [ruby-dev:24827] */ + rb_raise(rb_eRuntimeError, "block should not cheat"); + } + } + else if (need_backref) { + val = rb_reg_regsub(repl, str, regs, RB_TYPE_P(pat, T_STRING) ? Qnil : pat); + if (need_backref < 0) { + need_backref = val != repl; + } + } + else { + val = repl; + } - len = beg0 - offset; /* copy pre-match substr */ + len = beg0 - offset; /* copy pre-match substr */ if (len) { rb_enc_str_buf_cat(dest, cp, len, str_enc); } rb_str_buf_append(dest, val); - last = offset; - offset = end0; - if (beg0 == end0) { - /* - * Always consume at least one character of the input string - * in order to prevent infinite loops. - */ - if (RSTRING_LEN(str) <= end0) break; - len = rb_enc_fast_mbclen(RSTRING_PTR(str)+end0, RSTRING_END(str), str_enc); + last = offset; + offset = end0; + if (beg0 == end0) { + /* + * Always consume at least one character of the input string + * in order to prevent infinite loops. + */ + if (RSTRING_LEN(str) <= end0) break; + len = rb_enc_fast_mbclen(RSTRING_PTR(str)+end0, RSTRING_END(str), str_enc); rb_enc_str_buf_cat(dest, RSTRING_PTR(str)+end0, len, str_enc); - offset = end0 + len; - } - cp = RSTRING_PTR(str) + offset; - if (offset > RSTRING_LEN(str)) break; - beg = rb_pat_search(pat, str, offset, need_backref); + offset = end0 + len; + } + cp = RSTRING_PTR(str) + offset; + if (offset > RSTRING_LEN(str)) break; + beg = rb_pat_search(pat, str, offset, need_backref); } while (beg >= 0); if (RSTRING_LEN(str) > offset) { rb_enc_str_buf_cat(dest, cp, RSTRING_LEN(str) - offset, str_enc); @@ -5934,7 +5934,7 @@ str_gsub(int argc, VALUE *argv, VALUE str, int bang) str_shared_replace(str, dest); } else { - str = dest; + str = dest; } return str; @@ -6030,9 +6030,9 @@ rb_str_clear(VALUE str) STR_SET_EMBED_LEN(str, 0); RSTRING_PTR(str)[0] = 0; if (rb_enc_asciicompat(STR_ENC_GET(str))) - ENC_CODERANGE_SET(str, ENC_CODERANGE_7BIT); + ENC_CODERANGE_SET(str, ENC_CODERANGE_7BIT); else - ENC_CODERANGE_SET(str, ENC_CODERANGE_VALID); + ENC_CODERANGE_SET(str, ENC_CODERANGE_VALID); return str; } @@ -6110,34 +6110,34 @@ rb_str_setbyte(VALUE str, VALUE index, VALUE value) char byte = (char)(NUM2INT(w) & 0xFF); if (!str_independent(str)) - str_make_independent(str); + str_make_independent(str); enc = STR_ENC_GET(str); head = RSTRING_PTR(str); ptr = &head[pos]; if (!STR_EMBED_P(str)) { - cr = ENC_CODERANGE(str); - switch (cr) { - case ENC_CODERANGE_7BIT: + cr = ENC_CODERANGE(str); + switch (cr) { + case ENC_CODERANGE_7BIT: left = ptr; - *ptr = byte; - if (ISASCII(byte)) goto end; - nlen = rb_enc_precise_mbclen(left, head+len, enc); - if (!MBCLEN_CHARFOUND_P(nlen)) - ENC_CODERANGE_SET(str, ENC_CODERANGE_BROKEN); - else - ENC_CODERANGE_SET(str, ENC_CODERANGE_VALID); - goto end; - case ENC_CODERANGE_VALID: - left = rb_enc_left_char_head(head, ptr, head+len, enc); - width = rb_enc_precise_mbclen(left, head+len, enc); - *ptr = byte; - nlen = rb_enc_precise_mbclen(left, head+len, enc); - if (!MBCLEN_CHARFOUND_P(nlen)) - ENC_CODERANGE_SET(str, ENC_CODERANGE_BROKEN); - else if (MBCLEN_CHARFOUND_LEN(nlen) != width || ISASCII(byte)) - ENC_CODERANGE_CLEAR(str); - goto end; - } + *ptr = byte; + if (ISASCII(byte)) goto end; + nlen = rb_enc_precise_mbclen(left, head+len, enc); + if (!MBCLEN_CHARFOUND_P(nlen)) + ENC_CODERANGE_SET(str, ENC_CODERANGE_BROKEN); + else + ENC_CODERANGE_SET(str, ENC_CODERANGE_VALID); + goto end; + case ENC_CODERANGE_VALID: + left = rb_enc_left_char_head(head, ptr, head+len, enc); + width = rb_enc_precise_mbclen(left, head+len, enc); + *ptr = byte; + nlen = rb_enc_precise_mbclen(left, head+len, enc); + if (!MBCLEN_CHARFOUND_P(nlen)) + ENC_CODERANGE_SET(str, ENC_CODERANGE_BROKEN); + else if (MBCLEN_CHARFOUND_LEN(nlen) != width || ISASCII(byte)) + ENC_CODERANGE_CLEAR(str); + goto end; + } } ENC_CODERANGE_CLEAR(str); *ptr = byte; @@ -6155,24 +6155,24 @@ str_byte_substr(VALUE str, long beg, long len, int empty) if (beg > n || len < 0) return Qnil; if (beg < 0) { - beg += n; - if (beg < 0) return Qnil; + beg += n; + if (beg < 0) return Qnil; } if (len > n - beg) - len = n - beg; + len = n - beg; if (len <= 0) { - if (!empty) return Qnil; - len = 0; - p = 0; + if (!empty) return Qnil; + len = 0; + p = 0; } else - p = s + beg; + p = s + beg; if (!STR_EMBEDDABLE_P(len, TERM_LEN(str)) && SHARABLE_SUBSTRING_P(beg, len, n)) { - str2 = rb_str_new_frozen(str); + str2 = rb_str_new_frozen(str); str2 = str_new_shared(rb_cString, str2); - RSTRING(str2)->as.heap.ptr += beg; - RSTRING(str2)->as.heap.len = len; + RSTRING(str2)->as.heap.ptr += beg; + RSTRING(str2)->as.heap.len = len; } else { str2 = rb_str_new(p, len); @@ -6181,20 +6181,20 @@ str_byte_substr(VALUE str, long beg, long len, int empty) str_enc_copy(str2, str); if (RSTRING_LEN(str2) == 0) { - if (!rb_enc_asciicompat(STR_ENC_GET(str))) - ENC_CODERANGE_SET(str2, ENC_CODERANGE_VALID); - else - ENC_CODERANGE_SET(str2, ENC_CODERANGE_7BIT); + if (!rb_enc_asciicompat(STR_ENC_GET(str))) + ENC_CODERANGE_SET(str2, ENC_CODERANGE_VALID); + else + ENC_CODERANGE_SET(str2, ENC_CODERANGE_7BIT); } else { - switch (ENC_CODERANGE(str)) { - case ENC_CODERANGE_7BIT: - ENC_CODERANGE_SET(str2, ENC_CODERANGE_7BIT); - break; - default: - ENC_CODERANGE_SET(str2, ENC_CODERANGE_UNKNOWN); - break; - } + switch (ENC_CODERANGE(str)) { + case ENC_CODERANGE_7BIT: + ENC_CODERANGE_SET(str2, ENC_CODERANGE_7BIT); + break; + default: + ENC_CODERANGE_SET(str2, ENC_CODERANGE_UNKNOWN); + break; + } } return str2; @@ -6205,22 +6205,22 @@ str_byte_aref(VALUE str, VALUE indx) { long idx; if (FIXNUM_P(indx)) { - idx = FIX2LONG(indx); + idx = FIX2LONG(indx); } else { - /* check if indx is Range */ - long beg, len = RSTRING_LEN(str); + /* check if indx is Range */ + long beg, len = RSTRING_LEN(str); - switch (rb_range_beg_len(indx, &beg, &len, len, 0)) { - case Qfalse: - break; - case Qnil: - return Qnil; - default: - return str_byte_substr(str, beg, len, TRUE); - } + switch (rb_range_beg_len(indx, &beg, &len, len, 0)) { + case Qfalse: + break; + case Qnil: + return Qnil; + default: + return str_byte_substr(str, beg, len, TRUE); + } - idx = NUM2LONG(indx); + idx = NUM2LONG(indx); } return str_byte_substr(str, idx, 1, FALSE); } @@ -6376,32 +6376,32 @@ rb_str_reverse(VALUE str) cr = ENC_CODERANGE(str); if (RSTRING_LEN(str) > 1) { - if (single_byte_optimizable(str)) { - while (s < e) { - *--p = *s++; - } - } - else if (cr == ENC_CODERANGE_VALID) { - while (s < e) { - int clen = rb_enc_fast_mbclen(s, e, enc); + if (single_byte_optimizable(str)) { + while (s < e) { + *--p = *s++; + } + } + else if (cr == ENC_CODERANGE_VALID) { + while (s < e) { + int clen = rb_enc_fast_mbclen(s, e, enc); - p -= clen; - memcpy(p, s, clen); - s += clen; - } - } - else { - cr = rb_enc_asciicompat(enc) ? - ENC_CODERANGE_7BIT : ENC_CODERANGE_VALID; - while (s < e) { - int clen = rb_enc_mbclen(s, e, enc); + p -= clen; + memcpy(p, s, clen); + s += clen; + } + } + else { + cr = rb_enc_asciicompat(enc) ? + ENC_CODERANGE_7BIT : ENC_CODERANGE_VALID; + while (s < e) { + int clen = rb_enc_mbclen(s, e, enc); - if (clen > 1 || (*s & 0x80)) cr = ENC_CODERANGE_UNKNOWN; - p -= clen; - memcpy(p, s, clen); - s += clen; - } - } + if (clen > 1 || (*s & 0x80)) cr = ENC_CODERANGE_UNKNOWN; + p -= clen; + memcpy(p, s, clen); + s += clen; + } + } } STR_SET_LEN(rev, RSTRING_LEN(str)); str_enc_copy(rev, str); @@ -6427,24 +6427,24 @@ static VALUE rb_str_reverse_bang(VALUE str) { if (RSTRING_LEN(str) > 1) { - if (single_byte_optimizable(str)) { - char *s, *e, c; + if (single_byte_optimizable(str)) { + char *s, *e, c; - str_modify_keep_cr(str); - s = RSTRING_PTR(str); - e = RSTRING_END(str) - 1; - while (s < e) { - c = *s; - *s++ = *e; - *e-- = c; - } - } - else { - str_shared_replace(str, rb_str_reverse(str)); - } + str_modify_keep_cr(str); + s = RSTRING_PTR(str); + e = RSTRING_END(str) - 1; + while (s < e) { + c = *s; + *s++ = *e; + *e-- = c; + } + } + else { + str_shared_replace(str, rb_str_reverse(str)); + } } else { - str_modify_keep_cr(str); + str_modify_keep_cr(str); } return str; } @@ -6503,7 +6503,7 @@ rb_str_to_i(int argc, VALUE *argv, VALUE str) int base = 10; if (rb_check_arity(argc, 0, 1) && (base = NUM2INT(argv[0])) < 0) { - rb_raise(rb_eArgError, "invalid radix %d", base); + rb_raise(rb_eArgError, "invalid radix %d", base); } return rb_str_to_inum(str, base, FALSE); } @@ -6550,7 +6550,7 @@ static VALUE rb_str_to_s(VALUE str) { if (rb_obj_class(str) != rb_cString) { - return str_duplicate(rb_cString, str); + return str_duplicate(rb_cString, str); } return str; } @@ -6579,23 +6579,23 @@ rb_str_buf_cat_escaped_char(VALUE result, unsigned int c, int unicode_p) c &= 0xffffffff; #endif if (unicode_p) { - if (c < 0x7F && ISPRINT(c)) { - snprintf(buf, CHAR_ESC_LEN, "%c", c); - } - else if (c < 0x10000) { - snprintf(buf, CHAR_ESC_LEN, "\\u%04X", c); - } - else { - snprintf(buf, CHAR_ESC_LEN, "\\u{%X}", c); - } + if (c < 0x7F && ISPRINT(c)) { + snprintf(buf, CHAR_ESC_LEN, "%c", c); + } + else if (c < 0x10000) { + snprintf(buf, CHAR_ESC_LEN, "\\u%04X", c); + } + else { + snprintf(buf, CHAR_ESC_LEN, "\\u{%X}", c); + } } else { - if (c < 0x100) { - snprintf(buf, CHAR_ESC_LEN, "\\x%02X", c); - } - else { - snprintf(buf, CHAR_ESC_LEN, "\\x{%X}", c); - } + if (c < 0x100) { + snprintf(buf, CHAR_ESC_LEN, "\\x%02X", c); + } + else { + snprintf(buf, CHAR_ESC_LEN, "\\x{%X}", c); + } } l = (int)strlen(buf); /* CHAR_ESC_LEN cannot exceed INT_MAX */ rb_str_buf_cat(result, buf, l); @@ -6636,9 +6636,9 @@ rb_str_escape(VALUE str) while (p < pend) { unsigned int c; const char *cc; - int n = rb_enc_precise_mbclen(p, pend, enc); + int n = rb_enc_precise_mbclen(p, pend, enc); if (!MBCLEN_CHARFOUND_P(n)) { - if (p > prev) str_buf_cat(result, prev, p - prev); + if (p > prev) str_buf_cat(result, prev, p - prev); n = rb_enc_mbminlen(enc); if (pend < p + n) n = (int)(pend - p); @@ -6647,24 +6647,24 @@ rb_str_escape(VALUE str) str_buf_cat(result, buf, strlen(buf)); prev = ++p; } - continue; - } + continue; + } n = MBCLEN_CHARFOUND_LEN(n); - c = rb_enc_mbc_to_codepoint(p, pend, enc); - p += n; + c = rb_enc_mbc_to_codepoint(p, pend, enc); + p += n; cc = ruby_escaped_char(c); - if (cc) { - if (p - n > prev) str_buf_cat(result, prev, p - n - prev); + if (cc) { + if (p - n > prev) str_buf_cat(result, prev, p - n - prev); str_buf_cat(result, cc, strlen(cc)); - prev = p; - } - else if (asciicompat && rb_enc_isascii(c, enc) && ISPRINT(c)) { - } - else { - if (p - n > prev) str_buf_cat(result, prev, p - n - prev); - rb_str_buf_cat_escaped_char(result, c, unicode_p); - prev = p; - } + prev = p; + } + else if (asciicompat && rb_enc_isascii(c, enc) && ISPRINT(c)) { + } + else { + if (p - n > prev) str_buf_cat(result, prev, p - n - prev); + rb_str_buf_cat_escaped_char(result, c, unicode_p); + prev = p; + } } if (p > prev) str_buf_cat(result, prev, p - prev); ENCODING_CODERANGE_SET(result, rb_usascii_encindex(), ENC_CODERANGE_7BIT); @@ -6706,16 +6706,16 @@ rb_str_inspect(VALUE str) prev = p; actenc = get_actual_encoding(encidx, str); if (actenc != enc) { - enc = actenc; - if (unicode_p) unicode_p = rb_enc_unicode_p(enc); + enc = actenc; + if (unicode_p) unicode_p = rb_enc_unicode_p(enc); } while (p < pend) { - unsigned int c, cc; - int n; + unsigned int c, cc; + int n; n = rb_enc_precise_mbclen(p, pend, enc); if (!MBCLEN_CHARFOUND_P(n)) { - if (p > prev) str_buf_cat(result, prev, p - prev); + if (p > prev) str_buf_cat(result, prev, p - prev); n = rb_enc_mbminlen(enc); if (pend < p + n) n = (int)(pend - p); @@ -6724,54 +6724,54 @@ rb_str_inspect(VALUE str) str_buf_cat(result, buf, strlen(buf)); prev = ++p; } - continue; - } + continue; + } n = MBCLEN_CHARFOUND_LEN(n); - c = rb_enc_mbc_to_codepoint(p, pend, enc); - p += n; - if ((asciicompat || unicode_p) && - (c == '"'|| c == '\\' || - (c == '#' && + c = rb_enc_mbc_to_codepoint(p, pend, enc); + p += n; + if ((asciicompat || unicode_p) && + (c == '"'|| c == '\\' || + (c == '#' && p < pend && MBCLEN_CHARFOUND_P(rb_enc_precise_mbclen(p,pend,enc)) && (cc = rb_enc_codepoint(p,pend,enc), (cc == '$' || cc == '@' || cc == '{'))))) { - if (p - n > prev) str_buf_cat(result, prev, p - n - prev); - str_buf_cat2(result, "\\"); - if (asciicompat || enc == resenc) { - prev = p - n; - continue; - } - } - switch (c) { - case '\n': cc = 'n'; break; - case '\r': cc = 'r'; break; - case '\t': cc = 't'; break; - case '\f': cc = 'f'; break; - case '\013': cc = 'v'; break; - case '\010': cc = 'b'; break; - case '\007': cc = 'a'; break; - case 033: cc = 'e'; break; - default: cc = 0; break; - } - if (cc) { - if (p - n > prev) str_buf_cat(result, prev, p - n - prev); - buf[0] = '\\'; - buf[1] = (char)cc; - str_buf_cat(result, buf, 2); - prev = p; - continue; - } - if ((enc == resenc && rb_enc_isprint(c, enc)) || - (asciicompat && rb_enc_isascii(c, enc) && ISPRINT(c))) { - continue; - } - else { - if (p - n > prev) str_buf_cat(result, prev, p - n - prev); - rb_str_buf_cat_escaped_char(result, c, unicode_p); - prev = p; - continue; - } + if (p - n > prev) str_buf_cat(result, prev, p - n - prev); + str_buf_cat2(result, "\\"); + if (asciicompat || enc == resenc) { + prev = p - n; + continue; + } + } + switch (c) { + case '\n': cc = 'n'; break; + case '\r': cc = 'r'; break; + case '\t': cc = 't'; break; + case '\f': cc = 'f'; break; + case '\013': cc = 'v'; break; + case '\010': cc = 'b'; break; + case '\007': cc = 'a'; break; + case 033: cc = 'e'; break; + default: cc = 0; break; + } + if (cc) { + if (p - n > prev) str_buf_cat(result, prev, p - n - prev); + buf[0] = '\\'; + buf[1] = (char)cc; + str_buf_cat(result, buf, 2); + prev = p; + continue; + } + if ((enc == resenc && rb_enc_isprint(c, enc)) || + (asciicompat && rb_enc_isascii(c, enc) && ISPRINT(c))) { + continue; + } + else { + if (p - n > prev) str_buf_cat(result, prev, p - n - prev); + rb_str_buf_cat_escaped_char(result, c, unicode_p); + prev = p; + continue; + } } if (p > prev) str_buf_cat(result, prev, p - prev); str_buf_cat2(result, "\""); @@ -6810,55 +6810,55 @@ rb_str_dump(VALUE str) len = 2; /* "" */ if (!rb_enc_asciicompat(enc)) { - len += strlen(nonascii_suffix) - rb_strlen_lit("%s"); - len += strlen(enc->name); + len += strlen(nonascii_suffix) - rb_strlen_lit("%s"); + len += strlen(enc->name); } p = RSTRING_PTR(str); pend = p + RSTRING_LEN(str); while (p < pend) { - int clen; - unsigned char c = *p++; + int clen; + unsigned char c = *p++; - switch (c) { - case '"': case '\\': - case '\n': case '\r': - case '\t': case '\f': - case '\013': case '\010': case '\007': case '\033': - clen = 2; - break; + switch (c) { + case '"': case '\\': + case '\n': case '\r': + case '\t': case '\f': + case '\013': case '\010': case '\007': case '\033': + clen = 2; + break; - case '#': - clen = IS_EVSTR(p, pend) ? 2 : 1; - break; + case '#': + clen = IS_EVSTR(p, pend) ? 2 : 1; + break; - default: - if (ISPRINT(c)) { - clen = 1; - } - else { - if (u8 && c > 0x7F) { /* \u notation */ - int n = rb_enc_precise_mbclen(p-1, pend, enc); - if (MBCLEN_CHARFOUND_P(n)) { - unsigned int cc = rb_enc_mbc_to_codepoint(p-1, pend, enc); - if (cc <= 0xFFFF) - clen = 6; /* \uXXXX */ - else if (cc <= 0xFFFFF) - clen = 9; /* \u{XXXXX} */ - else - clen = 10; /* \u{XXXXXX} */ - p += MBCLEN_CHARFOUND_LEN(n)-1; - break; - } - } - clen = 4; /* \xNN */ - } - break; - } + default: + if (ISPRINT(c)) { + clen = 1; + } + else { + if (u8 && c > 0x7F) { /* \u notation */ + int n = rb_enc_precise_mbclen(p-1, pend, enc); + if (MBCLEN_CHARFOUND_P(n)) { + unsigned int cc = rb_enc_mbc_to_codepoint(p-1, pend, enc); + if (cc <= 0xFFFF) + clen = 6; /* \uXXXX */ + else if (cc <= 0xFFFFF) + clen = 9; /* \u{XXXXX} */ + else + clen = 10; /* \u{XXXXXX} */ + p += MBCLEN_CHARFOUND_LEN(n)-1; + break; + } + } + clen = 4; /* \xNN */ + } + break; + } - if (clen > LONG_MAX - len) { - rb_raise(rb_eRuntimeError, "string size too big"); - } - len += clen; + if (clen > LONG_MAX - len) { + rb_raise(rb_eRuntimeError, "string size too big"); + } + len += clen; } result = rb_str_new(0, len); @@ -6867,75 +6867,75 @@ rb_str_dump(VALUE str) *q++ = '"'; while (p < pend) { - unsigned char c = *p++; + unsigned char c = *p++; - if (c == '"' || c == '\\') { - *q++ = '\\'; - *q++ = c; - } - else if (c == '#') { - if (IS_EVSTR(p, pend)) *q++ = '\\'; - *q++ = '#'; - } - else if (c == '\n') { - *q++ = '\\'; - *q++ = 'n'; - } - else if (c == '\r') { - *q++ = '\\'; - *q++ = 'r'; - } - else if (c == '\t') { - *q++ = '\\'; - *q++ = 't'; - } - else if (c == '\f') { - *q++ = '\\'; - *q++ = 'f'; - } - else if (c == '\013') { - *q++ = '\\'; - *q++ = 'v'; - } - else if (c == '\010') { - *q++ = '\\'; - *q++ = 'b'; - } - else if (c == '\007') { - *q++ = '\\'; - *q++ = 'a'; - } - else if (c == '\033') { - *q++ = '\\'; - *q++ = 'e'; - } - else if (ISPRINT(c)) { - *q++ = c; - } - else { - *q++ = '\\'; - if (u8) { - int n = rb_enc_precise_mbclen(p-1, pend, enc) - 1; - if (MBCLEN_CHARFOUND_P(n)) { - int cc = rb_enc_mbc_to_codepoint(p-1, pend, enc); - p += n; - if (cc <= 0xFFFF) - snprintf(q, qend-q, "u%04X", cc); /* \uXXXX */ - else - snprintf(q, qend-q, "u{%X}", cc); /* \u{XXXXX} or \u{XXXXXX} */ - q += strlen(q); - continue; - } - } - snprintf(q, qend-q, "x%02X", c); - q += 3; - } + if (c == '"' || c == '\\') { + *q++ = '\\'; + *q++ = c; + } + else if (c == '#') { + if (IS_EVSTR(p, pend)) *q++ = '\\'; + *q++ = '#'; + } + else if (c == '\n') { + *q++ = '\\'; + *q++ = 'n'; + } + else if (c == '\r') { + *q++ = '\\'; + *q++ = 'r'; + } + else if (c == '\t') { + *q++ = '\\'; + *q++ = 't'; + } + else if (c == '\f') { + *q++ = '\\'; + *q++ = 'f'; + } + else if (c == '\013') { + *q++ = '\\'; + *q++ = 'v'; + } + else if (c == '\010') { + *q++ = '\\'; + *q++ = 'b'; + } + else if (c == '\007') { + *q++ = '\\'; + *q++ = 'a'; + } + else if (c == '\033') { + *q++ = '\\'; + *q++ = 'e'; + } + else if (ISPRINT(c)) { + *q++ = c; + } + else { + *q++ = '\\'; + if (u8) { + int n = rb_enc_precise_mbclen(p-1, pend, enc) - 1; + if (MBCLEN_CHARFOUND_P(n)) { + int cc = rb_enc_mbc_to_codepoint(p-1, pend, enc); + p += n; + if (cc <= 0xFFFF) + snprintf(q, qend-q, "u%04X", cc); /* \uXXXX */ + else + snprintf(q, qend-q, "u{%X}", cc); /* \u{XXXXX} or \u{XXXXXX} */ + q += strlen(q); + continue; + } + } + snprintf(q, qend-q, "x%02X", c); + q += 3; + } } *q++ = '"'; *q = '\0'; if (!rb_enc_asciicompat(enc)) { - snprintf(q, qend-q, nonascii_suffix, enc->name); - encidx = rb_ascii8bit_encindex(); + snprintf(q, qend-q, nonascii_suffix, enc->name); + encidx = rb_ascii8bit_encindex(); } /* result from dump is ASCII */ rb_enc_associate_index(result, encidx); @@ -6948,21 +6948,21 @@ unescape_ascii(unsigned int c) { switch (c) { case 'n': - return '\n'; + return '\n'; case 'r': - return '\r'; + return '\r'; case 't': - return '\t'; + return '\t'; case 'f': - return '\f'; + return '\f'; case 'v': - return '\13'; + return '\13'; case 'b': - return '\010'; + return '\010'; case 'a': - return '\007'; + return '\007'; case 'e': - return 033; + return 033; } UNREACHABLE_RETURN(-1); } @@ -6981,9 +6981,9 @@ undump_after_backslash(VALUE undumped, const char **ss, const char *s_end, rb_en case '\\': case '"': case '#': - rb_str_cat(undumped, s, 1); /* cat itself */ - s++; - break; + rb_str_cat(undumped, s, 1); /* cat itself */ + s++; + break; case 'n': case 'r': case 't': @@ -6994,81 +6994,81 @@ undump_after_backslash(VALUE undumped, const char **ss, const char *s_end, rb_en case 'e': *buf = unescape_ascii(*s); rb_str_cat(undumped, (char *)buf, 1); - s++; - break; + s++; + break; case 'u': - if (*binary) { - rb_raise(rb_eRuntimeError, "hex escape and Unicode escape are mixed"); - } - *utf8 = true; - if (++s >= s_end) { - rb_raise(rb_eRuntimeError, "invalid Unicode escape"); - } - if (enc_utf8 == NULL) enc_utf8 = rb_utf8_encoding(); - if (*penc != enc_utf8) { - *penc = enc_utf8; - rb_enc_associate(undumped, enc_utf8); - } - if (*s == '{') { /* handle \u{...} form */ - s++; - for (;;) { - if (s >= s_end) { - rb_raise(rb_eRuntimeError, "unterminated Unicode escape"); - } - if (*s == '}') { - s++; - break; - } - if (ISSPACE(*s)) { - s++; - continue; - } - c = scan_hex(s, s_end-s, &hexlen); - if (hexlen == 0 || hexlen > 6) { - rb_raise(rb_eRuntimeError, "invalid Unicode escape"); - } - if (c > 0x10ffff) { - rb_raise(rb_eRuntimeError, "invalid Unicode codepoint (too large)"); - } - if (0xd800 <= c && c <= 0xdfff) { - rb_raise(rb_eRuntimeError, "invalid Unicode codepoint"); - } + if (*binary) { + rb_raise(rb_eRuntimeError, "hex escape and Unicode escape are mixed"); + } + *utf8 = true; + if (++s >= s_end) { + rb_raise(rb_eRuntimeError, "invalid Unicode escape"); + } + if (enc_utf8 == NULL) enc_utf8 = rb_utf8_encoding(); + if (*penc != enc_utf8) { + *penc = enc_utf8; + rb_enc_associate(undumped, enc_utf8); + } + if (*s == '{') { /* handle \u{...} form */ + s++; + for (;;) { + if (s >= s_end) { + rb_raise(rb_eRuntimeError, "unterminated Unicode escape"); + } + if (*s == '}') { + s++; + break; + } + if (ISSPACE(*s)) { + s++; + continue; + } + c = scan_hex(s, s_end-s, &hexlen); + if (hexlen == 0 || hexlen > 6) { + rb_raise(rb_eRuntimeError, "invalid Unicode escape"); + } + if (c > 0x10ffff) { + rb_raise(rb_eRuntimeError, "invalid Unicode codepoint (too large)"); + } + if (0xd800 <= c && c <= 0xdfff) { + rb_raise(rb_eRuntimeError, "invalid Unicode codepoint"); + } codelen = rb_enc_mbcput(c, (char *)buf, *penc); rb_str_cat(undumped, (char *)buf, codelen); - s += hexlen; - } - } - else { /* handle \uXXXX form */ - c = scan_hex(s, 4, &hexlen); - if (hexlen != 4) { - rb_raise(rb_eRuntimeError, "invalid Unicode escape"); - } - if (0xd800 <= c && c <= 0xdfff) { - rb_raise(rb_eRuntimeError, "invalid Unicode codepoint"); - } + s += hexlen; + } + } + else { /* handle \uXXXX form */ + c = scan_hex(s, 4, &hexlen); + if (hexlen != 4) { + rb_raise(rb_eRuntimeError, "invalid Unicode escape"); + } + if (0xd800 <= c && c <= 0xdfff) { + rb_raise(rb_eRuntimeError, "invalid Unicode codepoint"); + } codelen = rb_enc_mbcput(c, (char *)buf, *penc); rb_str_cat(undumped, (char *)buf, codelen); - s += hexlen; - } - break; + s += hexlen; + } + break; case 'x': - if (*utf8) { - rb_raise(rb_eRuntimeError, "hex escape and Unicode escape are mixed"); - } - *binary = true; - if (++s >= s_end) { - rb_raise(rb_eRuntimeError, "invalid hex escape"); - } - *buf = scan_hex(s, 2, &hexlen); - if (hexlen != 2) { - rb_raise(rb_eRuntimeError, "invalid hex escape"); - } + if (*utf8) { + rb_raise(rb_eRuntimeError, "hex escape and Unicode escape are mixed"); + } + *binary = true; + if (++s >= s_end) { + rb_raise(rb_eRuntimeError, "invalid hex escape"); + } + *buf = scan_hex(s, 2, &hexlen); + if (hexlen != 2) { + rb_raise(rb_eRuntimeError, "invalid hex escape"); + } rb_str_cat(undumped, (char *)buf, 1); - s += hexlen; - break; + s += hexlen; + break; default: - rb_str_cat(undumped, s-1, 2); - s++; + rb_str_cat(undumped, s-1, 2); + s++; } *ss = s; @@ -7104,10 +7104,10 @@ str_undump(VALUE str) rb_must_asciicompat(str); if (rb_str_is_ascii_only_p(str) == Qfalse) { - rb_raise(rb_eRuntimeError, "non-ASCII character detected"); + rb_raise(rb_eRuntimeError, "non-ASCII character detected"); } if (!str_null_check(str, &w)) { - rb_raise(rb_eRuntimeError, "string contains null byte"); + rb_raise(rb_eRuntimeError, "string contains null byte"); } if (RSTRING_LEN(str) < 2) goto invalid_format; if (*s != '"') goto invalid_format; @@ -7116,63 +7116,63 @@ str_undump(VALUE str) s++; for (;;) { - if (s >= s_end) { - rb_raise(rb_eRuntimeError, "unterminated dumped string"); - } + if (s >= s_end) { + rb_raise(rb_eRuntimeError, "unterminated dumped string"); + } - if (*s == '"') { - /* epilogue */ - s++; - if (s == s_end) { - /* ascii compatible dumped string */ - break; - } - else { - static const char force_encoding_suffix[] = ".force_encoding(\""; /* "\")" */ - static const char dup_suffix[] = ".dup"; - const char *encname; - int encidx; - ptrdiff_t size; + if (*s == '"') { + /* epilogue */ + s++; + if (s == s_end) { + /* ascii compatible dumped string */ + break; + } + else { + static const char force_encoding_suffix[] = ".force_encoding(\""; /* "\")" */ + static const char dup_suffix[] = ".dup"; + const char *encname; + int encidx; + ptrdiff_t size; - /* check separately for strings dumped by older versions */ - size = sizeof(dup_suffix) - 1; - if (s_end - s > size && memcmp(s, dup_suffix, size) == 0) s += size; + /* check separately for strings dumped by older versions */ + size = sizeof(dup_suffix) - 1; + if (s_end - s > size && memcmp(s, dup_suffix, size) == 0) s += size; - size = sizeof(force_encoding_suffix) - 1; - if (s_end - s <= size) goto invalid_format; - if (memcmp(s, force_encoding_suffix, size) != 0) goto invalid_format; - s += size; + size = sizeof(force_encoding_suffix) - 1; + if (s_end - s <= size) goto invalid_format; + if (memcmp(s, force_encoding_suffix, size) != 0) goto invalid_format; + s += size; - if (utf8) { - rb_raise(rb_eRuntimeError, "dumped string contained Unicode escape but used force_encoding"); - } + if (utf8) { + rb_raise(rb_eRuntimeError, "dumped string contained Unicode escape but used force_encoding"); + } - encname = s; - s = memchr(s, '"', s_end-s); - size = s - encname; - if (!s) goto invalid_format; - if (s_end - s != 2) goto invalid_format; - if (s[0] != '"' || s[1] != ')') goto invalid_format; + encname = s; + s = memchr(s, '"', s_end-s); + size = s - encname; + if (!s) goto invalid_format; + if (s_end - s != 2) goto invalid_format; + if (s[0] != '"' || s[1] != ')') goto invalid_format; - encidx = rb_enc_find_index2(encname, (long)size); - if (encidx < 0) { - rb_raise(rb_eRuntimeError, "dumped string has unknown encoding name"); - } - rb_enc_associate_index(undumped, encidx); - } - break; - } + encidx = rb_enc_find_index2(encname, (long)size); + if (encidx < 0) { + rb_raise(rb_eRuntimeError, "dumped string has unknown encoding name"); + } + rb_enc_associate_index(undumped, encidx); + } + break; + } - if (*s == '\\') { - s++; - if (s >= s_end) { - rb_raise(rb_eRuntimeError, "invalid escape"); - } - undump_after_backslash(undumped, &s, s_end, &enc, &utf8, &binary); - } - else { - rb_str_cat(undumped, s++, 1); - } + if (*s == '\\') { + s++; + if (s >= s_end) { + rb_raise(rb_eRuntimeError, "invalid escape"); + } + undump_after_backslash(undumped, &s, s_end, &enc, &utf8, &binary); + } + else { + rb_str_cat(undumped, s++, 1); + } } return undumped; @@ -7184,8 +7184,8 @@ static void rb_str_check_dummy_enc(rb_encoding *enc) { if (rb_enc_dummy_p(enc)) { - rb_raise(rb_eEncCompatError, "incompatible encoding with this operation: %s", - rb_enc_name(enc)); + rb_raise(rb_eEncCompatError, "incompatible encoding with this operation: %s", + rb_enc_name(enc)); } } @@ -7205,35 +7205,35 @@ check_case_options(int argc, VALUE *argv, OnigCaseFoldType flags) if (argc>2) rb_raise(rb_eArgError, "too many options"); if (argv[0]==sym_turkic) { - flags |= ONIGENC_CASE_FOLD_TURKISH_AZERI; - if (argc==2) { - if (argv[1]==sym_lithuanian) - flags |= ONIGENC_CASE_FOLD_LITHUANIAN; - else - rb_raise(rb_eArgError, "invalid second option"); - } + flags |= ONIGENC_CASE_FOLD_TURKISH_AZERI; + if (argc==2) { + if (argv[1]==sym_lithuanian) + flags |= ONIGENC_CASE_FOLD_LITHUANIAN; + else + rb_raise(rb_eArgError, "invalid second option"); + } } else if (argv[0]==sym_lithuanian) { - flags |= ONIGENC_CASE_FOLD_LITHUANIAN; - if (argc==2) { - if (argv[1]==sym_turkic) - flags |= ONIGENC_CASE_FOLD_TURKISH_AZERI; - else - rb_raise(rb_eArgError, "invalid second option"); - } + flags |= ONIGENC_CASE_FOLD_LITHUANIAN; + if (argc==2) { + if (argv[1]==sym_turkic) + flags |= ONIGENC_CASE_FOLD_TURKISH_AZERI; + else + rb_raise(rb_eArgError, "invalid second option"); + } } else if (argc>1) - rb_raise(rb_eArgError, "too many options"); + rb_raise(rb_eArgError, "too many options"); else if (argv[0]==sym_ascii) - flags |= ONIGENC_CASE_ASCII_ONLY; + flags |= ONIGENC_CASE_ASCII_ONLY; else if (argv[0]==sym_fold) { - if ((flags & (ONIGENC_CASE_UPCASE|ONIGENC_CASE_DOWNCASE)) == ONIGENC_CASE_DOWNCASE) - flags ^= ONIGENC_CASE_FOLD|ONIGENC_CASE_DOWNCASE; - else - rb_raise(rb_eArgError, "option :fold only allowed for downcasing"); + if ((flags & (ONIGENC_CASE_UPCASE|ONIGENC_CASE_DOWNCASE)) == ONIGENC_CASE_DOWNCASE) + flags ^= ONIGENC_CASE_FOLD|ONIGENC_CASE_DOWNCASE; + else + rb_raise(rb_eArgError, "option :fold only allowed for downcasing"); } else - rb_raise(rb_eArgError, "invalid option"); + rb_raise(rb_eArgError, "invalid option"); return flags; } @@ -7297,47 +7297,47 @@ rb_str_casemap(VALUE source, OnigCaseFoldType *flags, rb_encoding *enc) buffer_anchor = TypedData_Wrap_Struct(0, &mapping_buffer_type, 0); pre_buffer = (mapping_buffer **)&DATA_PTR(buffer_anchor); while (source_current < source_end) { - /* increase multiplier using buffer count to converge quickly */ - size_t capa = (size_t)(source_end-source_current)*++buffer_count + CASE_MAPPING_ADDITIONAL_LENGTH; - if (CASEMAP_DEBUG) { - fprintf(stderr, "Buffer allocation, capa is %"PRIuSIZE"\n", capa); /* for tuning */ - } + /* increase multiplier using buffer count to converge quickly */ + size_t capa = (size_t)(source_end-source_current)*++buffer_count + CASE_MAPPING_ADDITIONAL_LENGTH; + if (CASEMAP_DEBUG) { + fprintf(stderr, "Buffer allocation, capa is %"PRIuSIZE"\n", capa); /* for tuning */ + } current_buffer = xmalloc(offsetof(mapping_buffer, space) + capa); *pre_buffer = current_buffer; pre_buffer = ¤t_buffer->next; - current_buffer->next = NULL; - current_buffer->capa = capa; - buffer_length_or_invalid = enc->case_map(flags, - &source_current, source_end, - current_buffer->space, - current_buffer->space+current_buffer->capa, - enc); - if (buffer_length_or_invalid < 0) { + current_buffer->next = NULL; + current_buffer->capa = capa; + buffer_length_or_invalid = enc->case_map(flags, + &source_current, source_end, + current_buffer->space, + current_buffer->space+current_buffer->capa, + enc); + if (buffer_length_or_invalid < 0) { current_buffer = DATA_PTR(buffer_anchor); DATA_PTR(buffer_anchor) = 0; mapping_buffer_free(current_buffer); - rb_raise(rb_eArgError, "input string invalid"); - } - target_length += current_buffer->used = buffer_length_or_invalid; + rb_raise(rb_eArgError, "input string invalid"); + } + target_length += current_buffer->used = buffer_length_or_invalid; } if (CASEMAP_DEBUG) { - fprintf(stderr, "Buffer count is %"PRIuSIZE"\n", buffer_count); /* for tuning */ + fprintf(stderr, "Buffer count is %"PRIuSIZE"\n", buffer_count); /* for tuning */ } if (buffer_count==1) { target = rb_str_new((const char*)current_buffer->space, target_length); } else { - char *target_current; + char *target_current; target = rb_str_new(0, target_length); - target_current = RSTRING_PTR(target); + target_current = RSTRING_PTR(target); current_buffer = DATA_PTR(buffer_anchor); - while (current_buffer) { - memcpy(target_current, current_buffer->space, current_buffer->used); - target_current += current_buffer->used; - current_buffer = current_buffer->next; - } + while (current_buffer) { + memcpy(target_current, current_buffer->space, current_buffer->used); + target_current += current_buffer->used; + current_buffer = current_buffer->next; + } } current_buffer = DATA_PTR(buffer_anchor); DATA_PTR(buffer_anchor) = 0; @@ -7377,10 +7377,10 @@ rb_str_ascii_casemap(VALUE source, VALUE target, OnigCaseFoldType *flags, rb_enc if (length_or_invalid < 0) rb_raise(rb_eArgError, "input string invalid"); if (CASEMAP_DEBUG && length_or_invalid != old_length) { - fprintf(stderr, "problem with rb_str_ascii_casemap" - "; old_length=%ld, new_length=%d\n", old_length, length_or_invalid); - rb_raise(rb_eArgError, "internal problem with rb_str_ascii_casemap" - "; old_length=%ld, new_length=%d\n", old_length, length_or_invalid); + fprintf(stderr, "problem with rb_str_ascii_casemap" + "; old_length=%ld, new_length=%d\n", old_length, length_or_invalid); + rb_raise(rb_eArgError, "internal problem with rb_str_ascii_casemap" + "; old_length=%ld, new_length=%d\n", old_length, length_or_invalid); } str_enc_copy(target, source); @@ -7441,7 +7441,7 @@ rb_str_upcase_bang(int argc, VALUE *argv, VALUE str) else if (flags&ONIGENC_CASE_ASCII_ONLY) rb_str_ascii_casemap(str, str, &flags, enc); else - str_shared_replace(str, rb_str_casemap(str, &flags, enc)); + str_shared_replace(str, rb_str_casemap(str, &flags, enc)); if (ONIGENC_CASE_MODIFIED&flags) return str; return Qnil; @@ -7543,7 +7543,7 @@ rb_str_downcase_bang(int argc, VALUE *argv, VALUE str) else if (flags&ONIGENC_CASE_ASCII_ONLY) rb_str_ascii_casemap(str, str, &flags, enc); else - str_shared_replace(str, rb_str_casemap(str, &flags, enc)); + str_shared_replace(str, rb_str_casemap(str, &flags, enc)); if (ONIGENC_CASE_MODIFIED&flags) return str; return Qnil; @@ -7625,7 +7625,7 @@ rb_str_capitalize_bang(int argc, VALUE *argv, VALUE str) if (flags&ONIGENC_CASE_ASCII_ONLY) rb_str_ascii_casemap(str, str, &flags, enc); else - str_shared_replace(str, rb_str_casemap(str, &flags, enc)); + str_shared_replace(str, rb_str_casemap(str, &flags, enc)); if (ONIGENC_CASE_MODIFIED&flags) return str; return Qnil; @@ -7703,7 +7703,7 @@ rb_str_swapcase_bang(int argc, VALUE *argv, VALUE str) if (flags&ONIGENC_CASE_ASCII_ONLY) rb_str_ascii_casemap(str, str, &flags, enc); else - str_shared_replace(str, rb_str_casemap(str, &flags, enc)); + str_shared_replace(str, rb_str_casemap(str, &flags, enc)); if (ONIGENC_CASE_MODIFIED&flags) return str; return Qnil; @@ -7763,50 +7763,50 @@ trnext(struct tr *t, rb_encoding *enc) for (;;) { nextpart: - if (!t->gen) { - if (t->p == t->pend) return -1; - if (rb_enc_ascget(t->p, t->pend, &n, enc) == '\\' && t->p + n < t->pend) { - t->p += n; - } - t->now = rb_enc_codepoint_len(t->p, t->pend, &n, enc); - t->p += n; - if (rb_enc_ascget(t->p, t->pend, &n, enc) == '-' && t->p + n < t->pend) { - t->p += n; - if (t->p < t->pend) { - unsigned int c = rb_enc_codepoint_len(t->p, t->pend, &n, enc); - t->p += n; - if (t->now > c) { - if (t->now < 0x80 && c < 0x80) { - rb_raise(rb_eArgError, - "invalid range \"%c-%c\" in string transliteration", - t->now, c); - } - else { - rb_raise(rb_eArgError, "invalid range in string transliteration"); - } - continue; /* not reached */ - } - t->gen = 1; - t->max = c; - } - } - return t->now; - } - else { - while (ONIGENC_CODE_TO_MBCLEN(enc, ++t->now) <= 0) { - if (t->now == t->max) { - t->gen = 0; - goto nextpart; - } - } - if (t->now < t->max) { - return t->now; - } - else { - t->gen = 0; - return t->max; - } - } + if (!t->gen) { + if (t->p == t->pend) return -1; + if (rb_enc_ascget(t->p, t->pend, &n, enc) == '\\' && t->p + n < t->pend) { + t->p += n; + } + t->now = rb_enc_codepoint_len(t->p, t->pend, &n, enc); + t->p += n; + if (rb_enc_ascget(t->p, t->pend, &n, enc) == '-' && t->p + n < t->pend) { + t->p += n; + if (t->p < t->pend) { + unsigned int c = rb_enc_codepoint_len(t->p, t->pend, &n, enc); + t->p += n; + if (t->now > c) { + if (t->now < 0x80 && c < 0x80) { + rb_raise(rb_eArgError, + "invalid range \"%c-%c\" in string transliteration", + t->now, c); + } + else { + rb_raise(rb_eArgError, "invalid range in string transliteration"); + } + continue; /* not reached */ + } + t->gen = 1; + t->max = c; + } + } + return t->now; + } + else { + while (ONIGENC_CODE_TO_MBCLEN(enc, ++t->now) <= 0) { + if (t->now == t->max) { + t->gen = 0; + goto nextpart; + } + } + if (t->now < t->max) { + return t->now; + } + else { + t->gen = 0; + return t->max; + } + } } } @@ -7830,30 +7830,30 @@ tr_trans(VALUE str, VALUE src, VALUE repl, int sflag) #define CHECK_IF_ASCII(c) \ (void)((cr == ENC_CODERANGE_7BIT && !rb_isascii(c)) ? \ - (cr = ENC_CODERANGE_VALID) : 0) + (cr = ENC_CODERANGE_VALID) : 0) StringValue(src); StringValue(repl); if (RSTRING_LEN(str) == 0 || !RSTRING_PTR(str)) return Qnil; if (RSTRING_LEN(repl) == 0) { - return rb_str_delete_bang(1, &src, str); + return rb_str_delete_bang(1, &src, str); } cr = ENC_CODERANGE(str); e1 = rb_enc_check(str, src); e2 = rb_enc_check(str, repl); if (e1 == e2) { - enc = e1; + enc = e1; } else { - enc = rb_enc_check(src, repl); + enc = rb_enc_check(src, repl); } trsrc.p = RSTRING_PTR(src); trsrc.pend = trsrc.p + RSTRING_LEN(src); if (RSTRING_LEN(src) > 1 && - rb_enc_ascget(trsrc.p, trsrc.pend, &l, enc) == '^' && - trsrc.p + l < trsrc.pend) { - cflag = 1; - trsrc.p += l; + rb_enc_ascget(trsrc.p, trsrc.pend, &l, enc) == '^' && + trsrc.p + l < trsrc.pend) { + cflag = 1; + trsrc.p += l; } trrepl.p = RSTRING_PTR(repl); trrepl.pend = trrepl.p + RSTRING_LEN(repl); @@ -7862,198 +7862,198 @@ tr_trans(VALUE str, VALUE src, VALUE repl, int sflag) trsrc.max = trrepl.max = 0; if (cflag) { - for (i=0; i<256; i++) { - trans[i] = 1; - } - while ((c = trnext(&trsrc, enc)) != errc) { - if (c < 256) { - trans[c] = errc; - } - else { - if (!hash) hash = rb_hash_new(); - rb_hash_aset(hash, UINT2NUM(c), Qtrue); - } - } - while ((c = trnext(&trrepl, enc)) != errc) - /* retrieve last replacer */; - last = trrepl.now; - for (i=0; i<256; i++) { - if (trans[i] != errc) { - trans[i] = last; - } - } + for (i=0; i<256; i++) { + trans[i] = 1; + } + while ((c = trnext(&trsrc, enc)) != errc) { + if (c < 256) { + trans[c] = errc; + } + else { + if (!hash) hash = rb_hash_new(); + rb_hash_aset(hash, UINT2NUM(c), Qtrue); + } + } + while ((c = trnext(&trrepl, enc)) != errc) + /* retrieve last replacer */; + last = trrepl.now; + for (i=0; i<256; i++) { + if (trans[i] != errc) { + trans[i] = last; + } + } } else { - unsigned int r; + unsigned int r; - for (i=0; i<256; i++) { - trans[i] = errc; - } - while ((c = trnext(&trsrc, enc)) != errc) { - r = trnext(&trrepl, enc); - if (r == errc) r = trrepl.now; - if (c < 256) { - trans[c] = r; - if (rb_enc_codelen(r, enc) != 1) singlebyte = 0; - } - else { - if (!hash) hash = rb_hash_new(); - rb_hash_aset(hash, UINT2NUM(c), UINT2NUM(r)); - } - } + for (i=0; i<256; i++) { + trans[i] = errc; + } + while ((c = trnext(&trsrc, enc)) != errc) { + r = trnext(&trrepl, enc); + if (r == errc) r = trrepl.now; + if (c < 256) { + trans[c] = r; + if (rb_enc_codelen(r, enc) != 1) singlebyte = 0; + } + else { + if (!hash) hash = rb_hash_new(); + rb_hash_aset(hash, UINT2NUM(c), UINT2NUM(r)); + } + } } if (cr == ENC_CODERANGE_VALID && rb_enc_asciicompat(e1)) - cr = ENC_CODERANGE_7BIT; + cr = ENC_CODERANGE_7BIT; str_modify_keep_cr(str); s = (unsigned char *)RSTRING_PTR(str); send = (unsigned char *)RSTRING_END(str); termlen = rb_enc_mbminlen(enc); if (sflag) { - int clen, tlen; - long offset, max = RSTRING_LEN(str); - unsigned int save = -1; + int clen, tlen; + long offset, max = RSTRING_LEN(str); + unsigned int save = -1; unsigned char *buf = ALLOC_N(unsigned char, max + termlen), *t = buf; - while (s < send) { - int may_modify = 0; + while (s < send) { + int may_modify = 0; c0 = c = rb_enc_codepoint_len((char *)s, (char *)send, &clen, e1); - tlen = enc == e1 ? clen : rb_enc_codelen(c, enc); + tlen = enc == e1 ? clen : rb_enc_codelen(c, enc); - s += clen; - if (c < 256) { - c = trans[c]; - } - else if (hash) { - VALUE tmp = rb_hash_lookup(hash, UINT2NUM(c)); - if (NIL_P(tmp)) { - if (cflag) c = last; - else c = errc; - } - else if (cflag) c = errc; - else c = NUM2INT(tmp); - } - else { - c = errc; - } - if (c != (unsigned int)-1) { - if (save == c) { - CHECK_IF_ASCII(c); - continue; - } - save = c; - tlen = rb_enc_codelen(c, enc); - modify = 1; - } - else { - save = -1; - c = c0; - if (enc != e1) may_modify = 1; - } - if ((offset = t - buf) + tlen > max) { - size_t MAYBE_UNUSED(old) = max + termlen; - max = offset + tlen + (send - s); + s += clen; + if (c < 256) { + c = trans[c]; + } + else if (hash) { + VALUE tmp = rb_hash_lookup(hash, UINT2NUM(c)); + if (NIL_P(tmp)) { + if (cflag) c = last; + else c = errc; + } + else if (cflag) c = errc; + else c = NUM2INT(tmp); + } + else { + c = errc; + } + if (c != (unsigned int)-1) { + if (save == c) { + CHECK_IF_ASCII(c); + continue; + } + save = c; + tlen = rb_enc_codelen(c, enc); + modify = 1; + } + else { + save = -1; + c = c0; + if (enc != e1) may_modify = 1; + } + if ((offset = t - buf) + tlen > max) { + size_t MAYBE_UNUSED(old) = max + termlen; + max = offset + tlen + (send - s); SIZED_REALLOC_N(buf, unsigned char, max + termlen, old); - t = buf + offset; - } - rb_enc_mbcput(c, t, enc); - if (may_modify && memcmp(s, t, tlen) != 0) { - modify = 1; - } - CHECK_IF_ASCII(c); - t += tlen; - } - if (!STR_EMBED_P(str)) { - ruby_sized_xfree(STR_HEAP_PTR(str), STR_HEAP_SIZE(str)); - } + t = buf + offset; + } + rb_enc_mbcput(c, t, enc); + if (may_modify && memcmp(s, t, tlen) != 0) { + modify = 1; + } + CHECK_IF_ASCII(c); + t += tlen; + } + if (!STR_EMBED_P(str)) { + ruby_sized_xfree(STR_HEAP_PTR(str), STR_HEAP_SIZE(str)); + } TERM_FILL((char *)t, termlen); RSTRING(str)->as.heap.ptr = (char *)buf; - RSTRING(str)->as.heap.len = t - buf; - STR_SET_NOEMBED(str); - RSTRING(str)->as.heap.aux.capa = max; + RSTRING(str)->as.heap.len = t - buf; + STR_SET_NOEMBED(str); + RSTRING(str)->as.heap.aux.capa = max; } else if (rb_enc_mbmaxlen(enc) == 1 || (singlebyte && !hash)) { - while (s < send) { - c = (unsigned char)*s; - if (trans[c] != errc) { - if (!cflag) { - c = trans[c]; - *s = c; - modify = 1; - } - else { - *s = last; - modify = 1; - } - } - CHECK_IF_ASCII(c); - s++; - } + while (s < send) { + c = (unsigned char)*s; + if (trans[c] != errc) { + if (!cflag) { + c = trans[c]; + *s = c; + modify = 1; + } + else { + *s = last; + modify = 1; + } + } + CHECK_IF_ASCII(c); + s++; + } } else { - int clen, tlen; - long offset, max = (long)((send - s) * 1.2); + int clen, tlen; + long offset, max = (long)((send - s) * 1.2); unsigned char *buf = ALLOC_N(unsigned char, max + termlen), *t = buf; - while (s < send) { - int may_modify = 0; + while (s < send) { + int may_modify = 0; c0 = c = rb_enc_codepoint_len((char *)s, (char *)send, &clen, e1); - tlen = enc == e1 ? clen : rb_enc_codelen(c, enc); + tlen = enc == e1 ? clen : rb_enc_codelen(c, enc); - if (c < 256) { - c = trans[c]; - } - else if (hash) { - VALUE tmp = rb_hash_lookup(hash, UINT2NUM(c)); - if (NIL_P(tmp)) { - if (cflag) c = last; - else c = errc; - } - else if (cflag) c = errc; - else c = NUM2INT(tmp); - } - else { - c = cflag ? last : errc; - } - if (c != errc) { - tlen = rb_enc_codelen(c, enc); - modify = 1; - } - else { - c = c0; - if (enc != e1) may_modify = 1; - } - if ((offset = t - buf) + tlen > max) { - size_t MAYBE_UNUSED(old) = max + termlen; - max = offset + tlen + (long)((send - s) * 1.2); + if (c < 256) { + c = trans[c]; + } + else if (hash) { + VALUE tmp = rb_hash_lookup(hash, UINT2NUM(c)); + if (NIL_P(tmp)) { + if (cflag) c = last; + else c = errc; + } + else if (cflag) c = errc; + else c = NUM2INT(tmp); + } + else { + c = cflag ? last : errc; + } + if (c != errc) { + tlen = rb_enc_codelen(c, enc); + modify = 1; + } + else { + c = c0; + if (enc != e1) may_modify = 1; + } + if ((offset = t - buf) + tlen > max) { + size_t MAYBE_UNUSED(old) = max + termlen; + max = offset + tlen + (long)((send - s) * 1.2); SIZED_REALLOC_N(buf, unsigned char, max + termlen, old); - t = buf + offset; - } - if (s != t) { - rb_enc_mbcput(c, t, enc); - if (may_modify && memcmp(s, t, tlen) != 0) { - modify = 1; - } - } - CHECK_IF_ASCII(c); - s += clen; - t += tlen; - } - if (!STR_EMBED_P(str)) { - ruby_sized_xfree(STR_HEAP_PTR(str), STR_HEAP_SIZE(str)); - } + t = buf + offset; + } + if (s != t) { + rb_enc_mbcput(c, t, enc); + if (may_modify && memcmp(s, t, tlen) != 0) { + modify = 1; + } + } + CHECK_IF_ASCII(c); + s += clen; + t += tlen; + } + if (!STR_EMBED_P(str)) { + ruby_sized_xfree(STR_HEAP_PTR(str), STR_HEAP_SIZE(str)); + } TERM_FILL((char *)t, termlen); RSTRING(str)->as.heap.ptr = (char *)buf; - RSTRING(str)->as.heap.len = t - buf; - STR_SET_NOEMBED(str); - RSTRING(str)->as.heap.aux.capa = max; + RSTRING(str)->as.heap.len = t - buf; + STR_SET_NOEMBED(str); + RSTRING(str)->as.heap.aux.capa = max; } if (modify) { - if (cr != ENC_CODERANGE_BROKEN) - ENC_CODERANGE_SET(str, cr); - rb_enc_associate(str, enc); - return str; + if (cr != ENC_CODERANGE_BROKEN) + ENC_CODERANGE_SET(str, cr); + rb_enc_associate(str, enc); + return str; } return Qnil; } @@ -8126,7 +8126,7 @@ rb_str_tr(VALUE str, VALUE src, VALUE repl) #define TR_TABLE_SIZE (TR_TABLE_MAX+1) static void tr_setup_table(VALUE str, char stable[TR_TABLE_SIZE], int first, - VALUE *tablep, VALUE *ctablep, rb_encoding *enc) + VALUE *tablep, VALUE *ctablep, rb_encoding *enc) { const unsigned int errc = -1; char buf[TR_TABLE_MAX]; @@ -8139,51 +8139,51 @@ tr_setup_table(VALUE str, char stable[TR_TABLE_SIZE], int first, tr.gen = tr.now = tr.max = 0; if (RSTRING_LEN(str) > 1 && rb_enc_ascget(tr.p, tr.pend, &l, enc) == '^') { - cflag = 1; - tr.p += l; + cflag = 1; + tr.p += l; } if (first) { - for (i=0; i 0 && !squeez[c])) { - *t++ = save = c; - } - } + if (c != save || (argc > 0 && !squeez[c])) { + *t++ = save = c; + } + } } else { - while (s < send) { - unsigned int c; - int clen; + while (s < send) { + unsigned int c; + int clen; if (ascompat && (c = *s) < 0x80) { - if (c != save || (argc > 0 && !squeez[c])) { - *t++ = save = c; - } - s++; - } - else { + if (c != save || (argc > 0 && !squeez[c])) { + *t++ = save = c; + } + s++; + } + else { c = rb_enc_codepoint_len((char *)s, (char *)send, &clen, enc); - if (c != save || (argc > 0 && !tr_find(c, squeez, del, nodel))) { - if (t != s) rb_enc_mbcput(c, t, enc); - save = c; - t += clen; - } - s += clen; - } - } + if (c != save || (argc > 0 && !tr_find(c, squeez, del, nodel))) { + if (t != s) rb_enc_mbcput(c, t, enc); + save = c; + t += clen; + } + s += clen; + } + } } TERM_FILL((char *)t, TERM_LEN(str)); if ((char *)t - RSTRING_PTR(str) != RSTRING_LEN(str)) { STR_SET_LEN(str, (char *)t - RSTRING_PTR(str)); - modify = 1; + modify = 1; } if (modify) return str; @@ -8495,30 +8495,30 @@ rb_str_count(int argc, VALUE *argv, VALUE str) StringValue(tstr); enc = rb_enc_check(str, tstr); if (argc == 1) { - const char *ptstr; - if (RSTRING_LEN(tstr) == 1 && rb_enc_asciicompat(enc) && - (ptstr = RSTRING_PTR(tstr), - ONIGENC_IS_ALLOWED_REVERSE_MATCH(enc, (const unsigned char *)ptstr, (const unsigned char *)ptstr+1)) && - !is_broken_string(str)) { - int clen; - unsigned char c = rb_enc_codepoint_len(ptstr, ptstr+1, &clen, enc); + const char *ptstr; + if (RSTRING_LEN(tstr) == 1 && rb_enc_asciicompat(enc) && + (ptstr = RSTRING_PTR(tstr), + ONIGENC_IS_ALLOWED_REVERSE_MATCH(enc, (const unsigned char *)ptstr, (const unsigned char *)ptstr+1)) && + !is_broken_string(str)) { + int clen; + unsigned char c = rb_enc_codepoint_len(ptstr, ptstr+1, &clen, enc); - s = RSTRING_PTR(str); - if (!s || RSTRING_LEN(str) == 0) return INT2FIX(0); - send = RSTRING_END(str); - while (s < send) { - if (*(unsigned char*)s++ == c) n++; - } - return SIZET2NUM(n); - } + s = RSTRING_PTR(str); + if (!s || RSTRING_LEN(str) == 0) return INT2FIX(0); + send = RSTRING_END(str); + while (s < send) { + if (*(unsigned char*)s++ == c) n++; + } + return SIZET2NUM(n); + } } tr_setup_table(tstr, table, TRUE, &del, &nodel, enc); for (i=1; i= 0 && len == 0) { - return empty_count + 1; + return empty_count + 1; } if (empty_count > 0) { - /* make different substrings */ - if (result) { - do { + /* make different substrings */ + if (result) { + do { rb_ary_push(result, str_new_empty_String(str)); - } while (--empty_count > 0); - } - else { - do { + } while (--empty_count > 0); + } + else { + do { rb_yield(str_new_empty_String(str)); - } while (--empty_count > 0); - } + } while (--empty_count > 0); + } } str = rb_str_subseq(str, beg, len); if (result) { - rb_ary_push(result, str); + rb_ary_push(result, str); } else { - rb_yield(str); + rb_yield(str); } return empty_count; } @@ -8658,32 +8658,32 @@ rb_str_split_m(int argc, VALUE *argv, VALUE str) result = rb_block_given_p() ? Qfalse : Qnil; if (rb_scan_args(argc, argv, "02", &spat, &limit) == 2) { - lim = NUM2INT(limit); - if (lim <= 0) limit = Qnil; - else if (lim == 1) { - if (RSTRING_LEN(str) == 0) + lim = NUM2INT(limit); + if (lim <= 0) limit = Qnil; + else if (lim == 1) { + if (RSTRING_LEN(str) == 0) return result ? rb_ary_new2(0) : str; tmp = str_duplicate(rb_cString, str); - if (!result) { - rb_yield(tmp); + if (!result) { + rb_yield(tmp); return str; - } - return rb_ary_new3(1, tmp); - } - i = 1; + } + return rb_ary_new3(1, tmp); + } + i = 1; } if (NIL_P(limit) && !lim) empty_count = 0; enc = STR_ENC_GET(str); split_type = SPLIT_TYPE_REGEXP; if (!NIL_P(spat)) { - spat = get_pat_quoted(spat, 0); + spat = get_pat_quoted(spat, 0); } else if (NIL_P(spat = rb_fs)) { - split_type = SPLIT_TYPE_AWK; + split_type = SPLIT_TYPE_AWK; } else if (!(spat = rb_fs_check(spat))) { - rb_raise(rb_eTypeError, "value of $; must be String or Regexp"); + rb_raise(rb_eTypeError, "value of $; must be String or Regexp"); } else { rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "$; is set to non-nil value"); @@ -8701,13 +8701,13 @@ rb_str_split_m(int argc, VALUE *argv, VALUE str) break; case T_STRING: - mustnot_broken(spat); + mustnot_broken(spat); split_type = literal_split_pattern(spat, SPLIT_TYPE_STRING); break; default: UNREACHABLE_RETURN(Qnil); - } + } } #define SPLIT_STR(beg, len) (empty_count = split_string(result, str, beg, len, empty_count)) @@ -8717,85 +8717,85 @@ rb_str_split_m(int argc, VALUE *argv, VALUE str) char *ptr = RSTRING_PTR(str); char *eptr = RSTRING_END(str); if (split_type == SPLIT_TYPE_AWK) { - char *bptr = ptr; - int skip = 1; - unsigned int c; + char *bptr = ptr; + int skip = 1; + unsigned int c; - end = beg; - if (is_ascii_string(str)) { - while (ptr < eptr) { - c = (unsigned char)*ptr++; - if (skip) { - if (ascii_isspace(c)) { - beg = ptr - bptr; - } - else { - end = ptr - bptr; - skip = 0; - if (!NIL_P(limit) && lim <= i) break; - } - } - else if (ascii_isspace(c)) { - SPLIT_STR(beg, end-beg); - skip = 1; - beg = ptr - bptr; - if (!NIL_P(limit)) ++i; - } - else { - end = ptr - bptr; - } - } - } - else { - while (ptr < eptr) { - int n; + end = beg; + if (is_ascii_string(str)) { + while (ptr < eptr) { + c = (unsigned char)*ptr++; + if (skip) { + if (ascii_isspace(c)) { + beg = ptr - bptr; + } + else { + end = ptr - bptr; + skip = 0; + if (!NIL_P(limit) && lim <= i) break; + } + } + else if (ascii_isspace(c)) { + SPLIT_STR(beg, end-beg); + skip = 1; + beg = ptr - bptr; + if (!NIL_P(limit)) ++i; + } + else { + end = ptr - bptr; + } + } + } + else { + while (ptr < eptr) { + int n; - c = rb_enc_codepoint_len(ptr, eptr, &n, enc); - ptr += n; - if (skip) { - if (rb_isspace(c)) { - beg = ptr - bptr; - } - else { - end = ptr - bptr; - skip = 0; - if (!NIL_P(limit) && lim <= i) break; - } - } - else if (rb_isspace(c)) { - SPLIT_STR(beg, end-beg); - skip = 1; - beg = ptr - bptr; - if (!NIL_P(limit)) ++i; - } - else { - end = ptr - bptr; - } - } - } + c = rb_enc_codepoint_len(ptr, eptr, &n, enc); + ptr += n; + if (skip) { + if (rb_isspace(c)) { + beg = ptr - bptr; + } + else { + end = ptr - bptr; + skip = 0; + if (!NIL_P(limit) && lim <= i) break; + } + } + else if (rb_isspace(c)) { + SPLIT_STR(beg, end-beg); + skip = 1; + beg = ptr - bptr; + if (!NIL_P(limit)) ++i; + } + else { + end = ptr - bptr; + } + } + } } else if (split_type == SPLIT_TYPE_STRING) { - char *str_start = ptr; - char *substr_start = ptr; - char *sptr = RSTRING_PTR(spat); - long slen = RSTRING_LEN(spat); + char *str_start = ptr; + char *substr_start = ptr; + char *sptr = RSTRING_PTR(spat); + long slen = RSTRING_LEN(spat); - mustnot_broken(str); - enc = rb_enc_check(str, spat); - while (ptr < eptr && - (end = rb_memsearch(sptr, slen, ptr, eptr - ptr, enc)) >= 0) { - /* Check we are at the start of a char */ - char *t = rb_enc_right_char_head(ptr, ptr + end, eptr, enc); - if (t != ptr + end) { - ptr = t; - continue; - } - SPLIT_STR(substr_start - str_start, (ptr+end) - substr_start); - ptr += end + slen; - substr_start = ptr; - if (!NIL_P(limit) && lim <= ++i) break; - } - beg = ptr - str_start; + mustnot_broken(str); + enc = rb_enc_check(str, spat); + while (ptr < eptr && + (end = rb_memsearch(sptr, slen, ptr, eptr - ptr, enc)) >= 0) { + /* Check we are at the start of a char */ + char *t = rb_enc_right_char_head(ptr, ptr + end, eptr, enc); + if (t != ptr + end) { + ptr = t; + continue; + } + SPLIT_STR(substr_start - str_start, (ptr+end) - substr_start); + ptr += end + slen; + substr_start = ptr; + if (!NIL_P(limit) && lim <= ++i) break; + } + beg = ptr - str_start; } else if (split_type == SPLIT_TYPE_CHARS) { char *str_start = ptr; @@ -8812,11 +8812,11 @@ rb_str_split_m(int argc, VALUE *argv, VALUE str) beg = ptr - str_start; } else { - long len = RSTRING_LEN(str); - long start = beg; - long idx; - int last_null = 0; - struct re_registers *regs; + long len = RSTRING_LEN(str); + long start = beg; + long idx; + int last_null = 0; + struct re_registers *regs; VALUE match = 0; for (; rb_reg_search(spat, str, start, 0) >= 0; @@ -8825,40 +8825,40 @@ rb_str_split_m(int argc, VALUE *argv, VALUE str) if (!result) rb_match_busy(match); regs = RMATCH_REGS(match); end = BEG(0); - if (start == end && BEG(0) == END(0)) { - if (!ptr) { - SPLIT_STR(0, 0); - break; - } - else if (last_null == 1) { + if (start == end && BEG(0) == END(0)) { + if (!ptr) { + SPLIT_STR(0, 0); + break; + } + else if (last_null == 1) { SPLIT_STR(beg, rb_enc_fast_mbclen(ptr+beg, eptr, enc)); - beg = start; - } - else { + beg = start; + } + else { if (start == len) start++; else start += rb_enc_fast_mbclen(ptr+start,eptr,enc); - last_null = 1; - continue; - } - } - else { - SPLIT_STR(beg, end-beg); - beg = start = END(0); - } - last_null = 0; + last_null = 1; + continue; + } + } + else { + SPLIT_STR(beg, end-beg); + beg = start = END(0); + } + last_null = 0; - for (idx=1; idx < regs->num_regs; idx++) { - if (BEG(idx) == -1) continue; - SPLIT_STR(BEG(idx), END(idx)-BEG(idx)); - } - if (!NIL_P(limit) && lim <= ++i) break; - } + for (idx=1; idx < regs->num_regs; idx++) { + if (BEG(idx) == -1) continue; + SPLIT_STR(BEG(idx), END(idx)-BEG(idx)); + } + if (!NIL_P(limit) && lim <= ++i) break; + } if (match) rb_match_unbusy(match); } if (RSTRING_LEN(str) > 0 && (!NIL_P(limit) || RSTRING_LEN(str) > beg || lim < 0)) { - SPLIT_STR(beg, RSTRING_LEN(str)-beg); + SPLIT_STR(beg, RSTRING_LEN(str)-beg); } return result ? result : str; @@ -8880,12 +8880,12 @@ static inline int enumerator_element(VALUE ary, VALUE e) { if (ary) { - rb_ary_push(ary, e); - return 0; + rb_ary_push(ary, e); + return 0; } else { - rb_yield(e); - return 1; + rb_yield(e); + return 1; } } @@ -8896,10 +8896,10 @@ chomp_newline(const char *p, const char *e, rb_encoding *enc) { const char *prev = rb_enc_prev_char(p, e, e, enc); if (rb_enc_is_newline(prev, e, enc)) { - e = prev; - prev = rb_enc_prev_char(p, e, e, enc); - if (prev && rb_enc_ascget(prev, e, NULL, enc) == '\r') - e = prev; + e = prev; + prev = rb_enc_prev_char(p, e, e, enc); + if (prev && rb_enc_ascget(prev, e, NULL, enc) == '\r') + e = prev; } return e; } @@ -8909,9 +8909,9 @@ get_rs(void) { VALUE rs = rb_rs; if (!NIL_P(rs) && - (!RB_TYPE_P(rs, T_STRING) || - RSTRING_LEN(rs) != 1 || - RSTRING_PTR(rs)[0] != '\n')) { + (!RB_TYPE_P(rs, T_STRING) || + RSTRING_LEN(rs) != 1 || + RSTRING_PTR(rs)[0] != '\n')) { rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "$/ is set to non-default value"); } return rs; @@ -8929,23 +8929,23 @@ rb_str_enumerate_lines(int argc, VALUE *argv, VALUE str, VALUE ary) int rsnewline = 0; if (rb_scan_args(argc, argv, "01:", &rs, &opts) == 0) - rs = rb_rs; + rs = rb_rs; if (!NIL_P(opts)) { - static ID keywords[1]; - if (!keywords[0]) { - keywords[0] = rb_intern_const("chomp"); - } - rb_get_kwargs(opts, keywords, 0, 1, &chomp); - chomp = (chomp != Qundef && RTEST(chomp)); + static ID keywords[1]; + if (!keywords[0]) { + keywords[0] = rb_intern_const("chomp"); + } + rb_get_kwargs(opts, keywords, 0, 1, &chomp); + chomp = (chomp != Qundef && RTEST(chomp)); } if (NIL_P(rs)) { - if (!ENUM_ELEM(ary, str)) { - return ary; - } - else { - return orig; - } + if (!ENUM_ELEM(ary, str)) { + return ary; + } + else { + return orig; + } } if (!RSTRING_LEN(str)) goto end; @@ -8957,106 +8957,106 @@ rb_str_enumerate_lines(int argc, VALUE *argv, VALUE str, VALUE ary) rslen = RSTRING_LEN(rs); if (rs == rb_default_rs) - enc = rb_enc_get(str); + enc = rb_enc_get(str); else - enc = rb_enc_check(str, rs); + enc = rb_enc_check(str, rs); if (rslen == 0) { - /* paragraph mode */ - int n; - const char *eol = NULL; - subend = subptr; - while (subend < pend) { + /* paragraph mode */ + int n; + const char *eol = NULL; + subend = subptr; + while (subend < pend) { long chomp_rslen = 0; - do { - if (rb_enc_ascget(subend, pend, &n, enc) != '\r') - n = 0; - rslen = n + rb_enc_mbclen(subend + n, pend, enc); - if (rb_enc_is_newline(subend + n, pend, enc)) { - if (eol == subend) break; - subend += rslen; + do { + if (rb_enc_ascget(subend, pend, &n, enc) != '\r') + n = 0; + rslen = n + rb_enc_mbclen(subend + n, pend, enc); + if (rb_enc_is_newline(subend + n, pend, enc)) { + if (eol == subend) break; + subend += rslen; if (subptr) { eol = subend; chomp_rslen = -rslen; } - } - else { - if (!subptr) subptr = subend; - subend += rslen; - } - rslen = 0; - } while (subend < pend); - if (!subptr) break; + } + else { + if (!subptr) subptr = subend; + subend += rslen; + } + rslen = 0; + } while (subend < pend); + if (!subptr) break; if (rslen == 0) chomp_rslen = 0; - line = rb_str_subseq(str, subptr - ptr, + line = rb_str_subseq(str, subptr - ptr, subend - subptr + (chomp ? chomp_rslen : rslen)); - if (ENUM_ELEM(ary, line)) { - str_mod_check(str, ptr, len); - } - subptr = eol = NULL; - } - goto end; + if (ENUM_ELEM(ary, line)) { + str_mod_check(str, ptr, len); + } + subptr = eol = NULL; + } + goto end; } else { - rsptr = RSTRING_PTR(rs); - if (RSTRING_LEN(rs) == rb_enc_mbminlen(enc) && - rb_enc_is_newline(rsptr, rsptr + RSTRING_LEN(rs), enc)) { - rsnewline = 1; - } + rsptr = RSTRING_PTR(rs); + if (RSTRING_LEN(rs) == rb_enc_mbminlen(enc) && + rb_enc_is_newline(rsptr, rsptr + RSTRING_LEN(rs), enc)) { + rsnewline = 1; + } } if ((rs == rb_default_rs) && !rb_enc_asciicompat(enc)) { - rs = rb_str_new(rsptr, rslen); - rs = rb_str_encode(rs, rb_enc_from_encoding(enc), 0, Qnil); - rsptr = RSTRING_PTR(rs); - rslen = RSTRING_LEN(rs); + rs = rb_str_new(rsptr, rslen); + rs = rb_str_encode(rs, rb_enc_from_encoding(enc), 0, Qnil); + rsptr = RSTRING_PTR(rs); + rslen = RSTRING_LEN(rs); } while (subptr < pend) { - pos = rb_memsearch(rsptr, rslen, subptr, pend - subptr, enc); - if (pos < 0) break; - hit = subptr + pos; - adjusted = rb_enc_right_char_head(subptr, hit, pend, enc); - if (hit != adjusted) { - subptr = adjusted; - continue; - } - subend = hit += rslen; - if (chomp) { - if (rsnewline) { - subend = chomp_newline(subptr, subend, enc); - } - else { - subend -= rslen; - } - } - line = rb_str_subseq(str, subptr - ptr, subend - subptr); - if (ENUM_ELEM(ary, line)) { - str_mod_check(str, ptr, len); - } - subptr = hit; + pos = rb_memsearch(rsptr, rslen, subptr, pend - subptr, enc); + if (pos < 0) break; + hit = subptr + pos; + adjusted = rb_enc_right_char_head(subptr, hit, pend, enc); + if (hit != adjusted) { + subptr = adjusted; + continue; + } + subend = hit += rslen; + if (chomp) { + if (rsnewline) { + subend = chomp_newline(subptr, subend, enc); + } + else { + subend -= rslen; + } + } + line = rb_str_subseq(str, subptr - ptr, subend - subptr); + if (ENUM_ELEM(ary, line)) { + str_mod_check(str, ptr, len); + } + subptr = hit; } if (subptr != pend) { - if (chomp) { - if (rsnewline) { - pend = chomp_newline(subptr, pend, enc); - } - else if (pend - subptr >= rslen && - memcmp(pend - rslen, rsptr, rslen) == 0) { - pend -= rslen; - } - } - line = rb_str_subseq(str, subptr - ptr, pend - subptr); - ENUM_ELEM(ary, line); - RB_GC_GUARD(str); + if (chomp) { + if (rsnewline) { + pend = chomp_newline(subptr, pend, enc); + } + else if (pend - subptr >= rslen && + memcmp(pend - rslen, rsptr, rslen) == 0) { + pend -= rslen; + } + } + line = rb_str_subseq(str, subptr - ptr, pend - subptr); + ENUM_ELEM(ary, line); + RB_GC_GUARD(str); } end: if (ary) - return ary; + return ary; else - return orig; + return orig; } /* @@ -9103,12 +9103,12 @@ rb_str_enumerate_bytes(VALUE str, VALUE ary) long i; for (i=0; i beg && rb_enc_ascget(p, end, 0, enc) == '\n') { - p2 = rb_enc_prev_char(beg, p, end, enc); - if (p2 && rb_enc_ascget(p2, end, 0, enc) == '\r') p = p2; + p2 = rb_enc_prev_char(beg, p, end, enc); + if (p2 && rb_enc_ascget(p2, end, 0, enc) == '\r') p = p2; } return p - beg; } @@ -9444,14 +9444,14 @@ rb_str_chop_bang(VALUE str) { str_modify_keep_cr(str); if (RSTRING_LEN(str) > 0) { - long len; - len = chopped_length(str); - STR_SET_LEN(str, len); - TERM_FILL(&RSTRING_PTR(str)[len], TERM_LEN(str)); - if (ENC_CODERANGE(str) != ENC_CODERANGE_7BIT) { - ENC_CODERANGE_CLEAR(str); - } - return str; + long len; + len = chopped_length(str); + STR_SET_LEN(str, len); + TERM_FILL(&RSTRING_PTR(str)[len], TERM_LEN(str)); + if (ENC_CODERANGE(str) != ENC_CODERANGE_7BIT) { + ENC_CODERANGE_CLEAR(str); + } + return str; } return Qnil; } @@ -9522,55 +9522,55 @@ chompped_length(VALUE str, VALUE rs) enc = rb_enc_get(str); RSTRING_GETMEM(rs, rsptr, rslen); if (rslen == 0) { - if (rb_enc_mbminlen(enc) > 1) { - while (e > p) { - pp = rb_enc_left_char_head(p, e-rb_enc_mbminlen(enc), e, enc); - if (!rb_enc_is_newline(pp, e, enc)) break; - e = pp; - pp -= rb_enc_mbminlen(enc); - if (pp >= p) { - pp = rb_enc_left_char_head(p, pp, e, enc); - if (rb_enc_ascget(pp, e, 0, enc) == '\r') { - e = pp; - } - } - } - } - else { - while (e > p && *(e-1) == '\n') { - --e; - if (e > p && *(e-1) == '\r') - --e; - } - } - return e - p; + if (rb_enc_mbminlen(enc) > 1) { + while (e > p) { + pp = rb_enc_left_char_head(p, e-rb_enc_mbminlen(enc), e, enc); + if (!rb_enc_is_newline(pp, e, enc)) break; + e = pp; + pp -= rb_enc_mbminlen(enc); + if (pp >= p) { + pp = rb_enc_left_char_head(p, pp, e, enc); + if (rb_enc_ascget(pp, e, 0, enc) == '\r') { + e = pp; + } + } + } + } + else { + while (e > p && *(e-1) == '\n') { + --e; + if (e > p && *(e-1) == '\r') + --e; + } + } + return e - p; } if (rslen > len) return len; enc = rb_enc_get(rs); newline = rsptr[rslen-1]; if (rslen == rb_enc_mbminlen(enc)) { - if (rslen == 1) { - if (newline == '\n') + if (rslen == 1) { + if (newline == '\n') return smart_chomp(str, e, p); - } - else { - if (rb_enc_is_newline(rsptr, rsptr+rslen, enc)) + } + else { + if (rb_enc_is_newline(rsptr, rsptr+rslen, enc)) return smart_chomp(str, e, p); - } + } } enc = rb_enc_check(str, rs); if (is_broken_string(rs)) { - return len; + return len; } pp = e - rslen; if (p[len-1] == newline && - (rslen <= 1 || - memcmp(rsptr, pp, rslen) == 0)) { - if (rb_enc_left_char_head(p, pp, e, enc) == pp) - return len - rslen; - RB_GC_GUARD(rs); + (rslen <= 1 || + memcmp(rsptr, pp, rslen) == 0)) { + if (rb_enc_left_char_head(p, pp, e, enc) == pp) + return len - rslen; + RB_GC_GUARD(rs); } return len; } @@ -9585,12 +9585,12 @@ chomp_rs(int argc, const VALUE *argv) { rb_check_arity(argc, 0, 1); if (argc > 0) { - VALUE rs = argv[0]; - if (!NIL_P(rs)) StringValue(rs); - return rs; + VALUE rs = argv[0]; + if (!NIL_P(rs)) StringValue(rs); + return rs; } else { - return rb_rs; + return rb_rs; } } @@ -9604,7 +9604,7 @@ rb_str_chomp_string(VALUE str, VALUE rs) STR_SET_LEN(str, len); TERM_FILL(&RSTRING_PTR(str)[len], TERM_LEN(str)); if (ENC_CODERANGE(str) != ENC_CODERANGE_7BIT) { - ENC_CODERANGE_CLEAR(str); + ENC_CODERANGE_CLEAR(str); } return str; } @@ -9658,13 +9658,13 @@ lstrip_offset(VALUE str, const char *s, const char *e, rb_encoding *enc) while (s < e && (*s == '\0' || ascii_isspace(*s))) s++; } else { - while (s < e) { - int n; - unsigned int cc = rb_enc_codepoint_len(s, e, &n, enc); + while (s < e) { + int n; + unsigned int cc = rb_enc_codepoint_len(s, e, &n, enc); if (cc && !rb_isspace(cc)) break; - s += n; - } + s += n; + } } return s - start; } @@ -9691,12 +9691,12 @@ rb_str_lstrip_bang(VALUE str) RSTRING_GETMEM(str, start, olen); loffset = lstrip_offset(str, start, start+olen, enc); if (loffset > 0) { - long len = olen-loffset; - s = start + loffset; - memmove(start, s, len); - STR_SET_LEN(str, len); - TERM_FILL(start+len, rb_enc_mbminlen(enc)); - return str; + long len = olen-loffset; + s = start + loffset; + memmove(start, s, len); + STR_SET_LEN(str, len); + TERM_FILL(start+len, rb_enc_mbminlen(enc)); + return str; } return Qnil; } @@ -9739,17 +9739,17 @@ rstrip_offset(VALUE str, const char *s, const char *e, rb_encoding *enc) /* remove trailing spaces or '\0's */ if (single_byte_optimizable(str)) { - unsigned char c; - while (s < t && ((c = *(t-1)) == '\0' || ascii_isspace(c))) t--; + unsigned char c; + while (s < t && ((c = *(t-1)) == '\0' || ascii_isspace(c))) t--; } else { - char *tp; + char *tp; while ((tp = rb_enc_prev_char(s, t, e, enc)) != NULL) { - unsigned int c = rb_enc_codepoint(tp, e, enc); - if (c && !rb_isspace(c)) break; - t = tp; - } + unsigned int c = rb_enc_codepoint(tp, e, enc); + if (c && !rb_isspace(c)) break; + t = tp; + } } return e - t; } @@ -9776,11 +9776,11 @@ rb_str_rstrip_bang(VALUE str) RSTRING_GETMEM(str, start, olen); roffset = rstrip_offset(str, start, start+olen, enc); if (roffset > 0) { - long len = olen - roffset; + long len = olen - roffset; - STR_SET_LEN(str, len); - TERM_FILL(start+len, rb_enc_mbminlen(enc)); - return str; + STR_SET_LEN(str, len); + TERM_FILL(start+len, rb_enc_mbminlen(enc)); + return str; } return Qnil; } @@ -9841,14 +9841,14 @@ rb_str_strip_bang(VALUE str) roffset = rstrip_offset(str, start+loffset, start+olen, enc); if (loffset > 0 || roffset > 0) { - long len = olen-roffset; - if (loffset > 0) { - len -= loffset; - memmove(start, start + loffset, len); - } - STR_SET_LEN(str, len); - TERM_FILL(start+len, rb_enc_mbminlen(enc)); - return str; + long len = olen-roffset; + if (loffset > 0) { + len -= loffset; + memmove(start, start + loffset, len); + } + STR_SET_LEN(str, len); + TERM_FILL(start+len, rb_enc_mbminlen(enc)); + return str; } return Qnil; } @@ -9892,44 +9892,44 @@ scan_once(VALUE str, VALUE pat, long *start, int set_backref_str) int i; long end, pos = rb_pat_search(pat, str, *start, set_backref_str); if (pos >= 0) { - if (BUILTIN_TYPE(pat) == T_STRING) { - regs = NULL; - end = pos + RSTRING_LEN(pat); - } - else { - match = rb_backref_get(); - regs = RMATCH_REGS(match); - pos = BEG(0); - end = END(0); - } - if (pos == end) { - rb_encoding *enc = STR_ENC_GET(str); - /* - * Always consume at least one character of the input string - */ - if (RSTRING_LEN(str) > end) - *start = end + rb_enc_fast_mbclen(RSTRING_PTR(str) + end, - RSTRING_END(str), enc); - else - *start = end + 1; - } - else { - *start = end; - } - if (!regs || regs->num_regs == 1) { - result = rb_str_subseq(str, pos, end - pos); - return result; - } - result = rb_ary_new2(regs->num_regs); - for (i=1; i < regs->num_regs; i++) { - VALUE s = Qnil; - if (BEG(i) >= 0) { - s = rb_str_subseq(str, BEG(i), END(i)-BEG(i)); - } - rb_ary_push(result, s); - } + if (BUILTIN_TYPE(pat) == T_STRING) { + regs = NULL; + end = pos + RSTRING_LEN(pat); + } + else { + match = rb_backref_get(); + regs = RMATCH_REGS(match); + pos = BEG(0); + end = END(0); + } + if (pos == end) { + rb_encoding *enc = STR_ENC_GET(str); + /* + * Always consume at least one character of the input string + */ + if (RSTRING_LEN(str) > end) + *start = end + rb_enc_fast_mbclen(RSTRING_PTR(str) + end, + RSTRING_END(str), enc); + else + *start = end + 1; + } + else { + *start = end; + } + if (!regs || regs->num_regs == 1) { + result = rb_str_subseq(str, pos, end - pos); + return result; + } + result = rb_ary_new2(regs->num_regs); + for (i=1; i < regs->num_regs; i++) { + VALUE s = Qnil; + if (BEG(i) >= 0) { + s = rb_str_subseq(str, BEG(i), END(i)-BEG(i)); + } + rb_ary_push(result, s); + } - return result; + return result; } return Qnil; } @@ -9985,23 +9985,23 @@ rb_str_scan(VALUE str, VALUE pat) pat = get_pat_quoted(pat, 1); mustnot_broken(str); if (!rb_block_given_p()) { - VALUE ary = rb_ary_new(); + VALUE ary = rb_ary_new(); - while (!NIL_P(result = scan_once(str, pat, &start, 0))) { - last = prev; - prev = start; - rb_ary_push(ary, result); - } - if (last >= 0) rb_pat_search(pat, str, last, 1); - else rb_backref_set(Qnil); - return ary; + while (!NIL_P(result = scan_once(str, pat, &start, 0))) { + last = prev; + prev = start; + rb_ary_push(ary, result); + } + if (last >= 0) rb_pat_search(pat, str, last, 1); + else rb_backref_set(Qnil); + return ary; } while (!NIL_P(result = scan_once(str, pat, &start, 1))) { - last = prev; - prev = start; - rb_yield(result); - str_mod_check(str, p, len); + last = prev; + prev = start; + rb_yield(result); + str_mod_check(str, p, len); } if (last >= 0) rb_pat_search(pat, str, last, 1); return str; @@ -10157,15 +10157,15 @@ rb_str_crypt(VALUE str, VALUE salt) s = StringValueCStr(str); saltp = RSTRING_PTR(salt); if (RSTRING_LEN(salt) < 2 || !saltp[0] || !saltp[1]) { - rb_raise(rb_eArgError, "salt too short (need >=2 bytes)"); + rb_raise(rb_eArgError, "salt too short (need >=2 bytes)"); } #ifdef BROKEN_CRYPT if (!ISASCII((unsigned char)saltp[0]) || !ISASCII((unsigned char)saltp[1])) { - salt_8bit_clean[0] = saltp[0] & 0x7f; - salt_8bit_clean[1] = saltp[1] & 0x7f; - salt_8bit_clean[2] = '\0'; - saltp = salt_8bit_clean; + salt_8bit_clean[0] = saltp[0] & 0x7f; + salt_8bit_clean[1] = saltp[1] & 0x7f; + salt_8bit_clean[2] = '\0'; + saltp = salt_8bit_clean; } #endif #ifdef HAVE_CRYPT_R @@ -10180,9 +10180,9 @@ rb_str_crypt(VALUE str, VALUE salt) res = crypt(s, saltp); #endif if (!res) { - int err = errno; - CRYPT_END(); - rb_syserr_fail(err, "crypt"); + int err = errno; + CRYPT_END(); + rb_syserr_fail(err, "crypt"); } result = rb_str_new_cstr(res); CRYPT_END(); @@ -10286,15 +10286,15 @@ rb_str_justify(int argc, VALUE *argv, VALUE str, char jflag) termlen = rb_enc_mbminlen(enc); width = NUM2LONG(w); if (argc == 2) { - StringValue(pad); - enc = rb_enc_check(str, pad); - f = RSTRING_PTR(pad); - flen = RSTRING_LEN(pad); - fclen = str_strlen(pad, enc); /* rb_enc_check */ - singlebyte = single_byte_optimizable(pad); - if (flen == 0 || fclen == 0) { - rb_raise(rb_eArgError, "zero width padding"); - } + StringValue(pad); + enc = rb_enc_check(str, pad); + f = RSTRING_PTR(pad); + flen = RSTRING_LEN(pad); + fclen = str_strlen(pad, enc); /* rb_enc_check */ + singlebyte = single_byte_optimizable(pad); + if (flen == 0 || fclen == 0) { + rb_raise(rb_eArgError, "zero width padding"); + } } len = str_strlen(str, enc); /* rb_enc_check */ if (width < 0 || len >= width) return str_duplicate(rb_cString, str); @@ -10321,14 +10321,14 @@ rb_str_justify(int argc, VALUE *argv, VALUE str, char jflag) } else { while (llen >= fclen) { - memcpy(p,f,flen); - p += flen; - llen -= fclen; - } + memcpy(p,f,flen); + p += flen; + llen -= fclen; + } if (llen > 0) { memcpy(p, f, llen2); p += llen2; - } + } } memcpy(p, RSTRING_PTR(str), size); p += size; @@ -10338,22 +10338,22 @@ rb_str_justify(int argc, VALUE *argv, VALUE str, char jflag) } else { while (rlen >= fclen) { - memcpy(p,f,flen); - p += flen; - rlen -= fclen; - } + memcpy(p,f,flen); + p += flen; + rlen -= fclen; + } if (rlen > 0) { memcpy(p, f, rlen2); p += rlen2; - } + } } TERM_FILL(p, termlen); STR_SET_LEN(res, p-RSTRING_PTR(res)); rb_enc_associate(res, enc); if (argc == 2) - cr = ENC_CODERANGE_AND(cr, ENC_CODERANGE(pad)); + cr = ENC_CODERANGE_AND(cr, ENC_CODERANGE(pad)); if (cr != ENC_CODERANGE_BROKEN) - ENC_CODERANGE_SET(res, cr); + ENC_CODERANGE_SET(res, cr); RB_GC_GUARD(pad); return res; @@ -10424,23 +10424,23 @@ rb_str_partition(VALUE str, VALUE sep) sep = get_pat_quoted(sep, 0); if (RB_TYPE_P(sep, T_REGEXP)) { - if (rb_reg_search(sep, str, 0, 0) < 0) { + if (rb_reg_search(sep, str, 0, 0) < 0) { goto failed; - } - VALUE match = rb_backref_get(); - struct re_registers *regs = RMATCH_REGS(match); + } + VALUE match = rb_backref_get(); + struct re_registers *regs = RMATCH_REGS(match); pos = BEG(0); - sep = rb_str_subseq(str, pos, END(0) - pos); + sep = rb_str_subseq(str, pos, END(0) - pos); } else { - pos = rb_str_index(str, sep, 0); - if (pos < 0) goto failed; + pos = rb_str_index(str, sep, 0); + if (pos < 0) goto failed; } return rb_ary_new3(3, rb_str_subseq(str, 0, pos), - sep, - rb_str_subseq(str, pos+RSTRING_LEN(sep), - RSTRING_LEN(str)-pos-RSTRING_LEN(sep))); + sep, + rb_str_subseq(str, pos+RSTRING_LEN(sep), + RSTRING_LEN(str)-pos-RSTRING_LEN(sep))); failed: return rb_ary_new3(3, str_duplicate(rb_cString, str), str_new_empty_String(str), str_new_empty_String(str)); @@ -10465,14 +10465,14 @@ rb_str_rpartition(VALUE str, VALUE sep) goto failed; } VALUE match = rb_backref_get(); - struct re_registers *regs = RMATCH_REGS(match); + struct re_registers *regs = RMATCH_REGS(match); pos = BEG(0); sep = rb_str_subseq(str, pos, END(0) - pos); } else { - pos = rb_str_sublen(str, pos); - pos = rb_str_rindex(str, sep, pos); + pos = rb_str_sublen(str, pos); + pos = rb_str_rindex(str, sep, pos); if (pos < 0) { goto failed; } @@ -10480,9 +10480,9 @@ rb_str_rpartition(VALUE str, VALUE sep) } return rb_ary_new3(3, rb_str_subseq(str, 0, pos), - sep, - rb_str_subseq(str, pos+RSTRING_LEN(sep), - RSTRING_LEN(str)-pos-RSTRING_LEN(sep))); + sep, + rb_str_subseq(str, pos+RSTRING_LEN(sep), + RSTRING_LEN(str)-pos-RSTRING_LEN(sep))); failed: return rb_ary_new3(3, str_new_empty_String(str), str_new_empty_String(str), str_duplicate(rb_cString, str)); } @@ -10501,18 +10501,18 @@ rb_str_start_with(int argc, VALUE *argv, VALUE str) int i; for (i=0; i= blen || - (e = rb_enc_nth(p, e, len, enc)) - p == blen) { - ret = str; + (e = rb_enc_nth(p, e, len, enc)) - p == blen) { + ret = str; } else if (len <= ellipsislen || - !(e = rb_enc_step_back(p, e, e, len = ellipsislen, enc))) { - if (rb_enc_asciicompat(enc)) { + !(e = rb_enc_step_back(p, e, e, len = ellipsislen, enc))) { + if (rb_enc_asciicompat(enc)) { ret = rb_str_new(ellipsis, len); - rb_enc_associate(ret, enc); - } - else { - estr = rb_usascii_str_new(ellipsis, len); - ret = rb_str_encode(estr, rb_enc_from_encoding(enc), 0, Qnil); - } + rb_enc_associate(ret, enc); + } + else { + estr = rb_usascii_str_new(ellipsis, len); + ret = rb_str_encode(estr, rb_enc_from_encoding(enc), 0, Qnil); + } } else if (ret = rb_str_subseq(str, 0, e - p), rb_enc_asciicompat(enc)) { - rb_str_cat(ret, ellipsis, ellipsislen); + rb_str_cat(ret, ellipsis, ellipsislen); } else { - estr = rb_str_encode(rb_usascii_str_new(ellipsis, ellipsislen), - rb_enc_from_encoding(enc), 0, Qnil); - rb_str_append(ret, estr); + estr = rb_str_encode(rb_usascii_str_new(ellipsis, ellipsislen), + rb_enc_from_encoding(enc), 0, Qnil); + rb_str_append(ret, estr); } return ret; } @@ -10851,14 +10851,14 @@ str_compat_and_valid(VALUE str, rb_encoding *enc) str = StringValue(str); cr = rb_enc_str_coderange(str); if (cr == ENC_CODERANGE_BROKEN) { - rb_raise(rb_eArgError, "replacement must be valid byte sequence '%+"PRIsVALUE"'", str); + rb_raise(rb_eArgError, "replacement must be valid byte sequence '%+"PRIsVALUE"'", str); } else { - rb_encoding *e = STR_ENC_GET(str); - if (cr == ENC_CODERANGE_7BIT ? rb_enc_mbminlen(enc) != 1 : enc != e) { - rb_raise(rb_eEncCompatError, "incompatible character encodings: %s and %s", - rb_enc_name(enc), rb_enc_name(e)); - } + rb_encoding *e = STR_ENC_GET(str); + if (cr == ENC_CODERANGE_7BIT ? rb_enc_mbminlen(enc) != 1 : enc != e) { + rb_raise(rb_eEncCompatError, "incompatible character encodings: %s and %s", + rb_enc_name(enc), rb_enc_name(e)); + } } return str; } @@ -10877,9 +10877,9 @@ rb_enc_str_scrub(rb_encoding *enc, VALUE str, VALUE repl) { int cr = ENC_CODERANGE_UNKNOWN; if (enc == STR_ENC_GET(str)) { - /* cached coderange makes sense only when enc equals the - * actual encoding of str */ - cr = ENC_CODERANGE(str); + /* cached coderange makes sense only when enc equals the + * actual encoding of str */ + cr = ENC_CODERANGE(str); } return enc_str_scrub(enc, str, repl, cr); } @@ -10894,26 +10894,26 @@ enc_str_scrub(rb_encoding *enc, VALUE str, VALUE repl, int cr) long slen; if (rb_block_given_p()) { - if (!NIL_P(repl)) - rb_raise(rb_eArgError, "both of block and replacement given"); - replen = 0; + if (!NIL_P(repl)) + rb_raise(rb_eArgError, "both of block and replacement given"); + replen = 0; } if (ENC_CODERANGE_CLEAN_P(cr)) - return Qnil; + return Qnil; if (!NIL_P(repl)) { - repl = str_compat_and_valid(repl, enc); + repl = str_compat_and_valid(repl, enc); } if (rb_enc_dummy_p(enc)) { - return Qnil; + return Qnil; } encidx = rb_enc_to_index(enc); #define DEFAULT_REPLACE_CHAR(str) do { \ - static const char replace[sizeof(str)-1] = str; \ - rep = replace; replen = (int)sizeof(replace); \ + static const char replace[sizeof(str)-1] = str; \ + rep = replace; replen = (int)sizeof(replace); \ } while (0) slen = RSTRING_LEN(str); @@ -10923,204 +10923,204 @@ enc_str_scrub(rb_encoding *enc, VALUE str, VALUE repl, int cr) sp = p; if (rb_enc_asciicompat(enc)) { - int rep7bit_p; - if (!replen) { - rep = NULL; - rep7bit_p = FALSE; - } - else if (!NIL_P(repl)) { - rep = RSTRING_PTR(repl); - replen = RSTRING_LEN(repl); - rep7bit_p = (ENC_CODERANGE(repl) == ENC_CODERANGE_7BIT); - } - else if (encidx == rb_utf8_encindex()) { - DEFAULT_REPLACE_CHAR("\xEF\xBF\xBD"); - rep7bit_p = FALSE; - } - else { - DEFAULT_REPLACE_CHAR("?"); - rep7bit_p = TRUE; - } - cr = ENC_CODERANGE_7BIT; + int rep7bit_p; + if (!replen) { + rep = NULL; + rep7bit_p = FALSE; + } + else if (!NIL_P(repl)) { + rep = RSTRING_PTR(repl); + replen = RSTRING_LEN(repl); + rep7bit_p = (ENC_CODERANGE(repl) == ENC_CODERANGE_7BIT); + } + else if (encidx == rb_utf8_encindex()) { + DEFAULT_REPLACE_CHAR("\xEF\xBF\xBD"); + rep7bit_p = FALSE; + } + else { + DEFAULT_REPLACE_CHAR("?"); + rep7bit_p = TRUE; + } + cr = ENC_CODERANGE_7BIT; - p = search_nonascii(p, e); - if (!p) { - p = e; - } - while (p < e) { - int ret = rb_enc_precise_mbclen(p, e, enc); - if (MBCLEN_NEEDMORE_P(ret)) { - break; - } - else if (MBCLEN_CHARFOUND_P(ret)) { - cr = ENC_CODERANGE_VALID; - p += MBCLEN_CHARFOUND_LEN(ret); - } - else if (MBCLEN_INVALID_P(ret)) { - /* - * p1~p: valid ascii/multibyte chars - * p ~e: invalid bytes + unknown bytes - */ - long clen = rb_enc_mbmaxlen(enc); - if (NIL_P(buf)) buf = rb_str_buf_new(RSTRING_LEN(str)); - if (p > p1) { - rb_str_buf_cat(buf, p1, p - p1); - } + p = search_nonascii(p, e); + if (!p) { + p = e; + } + while (p < e) { + int ret = rb_enc_precise_mbclen(p, e, enc); + if (MBCLEN_NEEDMORE_P(ret)) { + break; + } + else if (MBCLEN_CHARFOUND_P(ret)) { + cr = ENC_CODERANGE_VALID; + p += MBCLEN_CHARFOUND_LEN(ret); + } + else if (MBCLEN_INVALID_P(ret)) { + /* + * p1~p: valid ascii/multibyte chars + * p ~e: invalid bytes + unknown bytes + */ + long clen = rb_enc_mbmaxlen(enc); + if (NIL_P(buf)) buf = rb_str_buf_new(RSTRING_LEN(str)); + if (p > p1) { + rb_str_buf_cat(buf, p1, p - p1); + } - if (e - p < clen) clen = e - p; - if (clen <= 2) { - clen = 1; - } - else { - const char *q = p; - clen--; - for (; clen > 1; clen--) { - ret = rb_enc_precise_mbclen(q, q + clen, enc); - if (MBCLEN_NEEDMORE_P(ret)) break; - if (MBCLEN_INVALID_P(ret)) continue; - UNREACHABLE; - } - } - if (rep) { - rb_str_buf_cat(buf, rep, replen); - if (!rep7bit_p) cr = ENC_CODERANGE_VALID; - } - else { - repl = rb_yield(rb_enc_str_new(p, clen, enc)); + if (e - p < clen) clen = e - p; + if (clen <= 2) { + clen = 1; + } + else { + const char *q = p; + clen--; + for (; clen > 1; clen--) { + ret = rb_enc_precise_mbclen(q, q + clen, enc); + if (MBCLEN_NEEDMORE_P(ret)) break; + if (MBCLEN_INVALID_P(ret)) continue; + UNREACHABLE; + } + } + if (rep) { + rb_str_buf_cat(buf, rep, replen); + if (!rep7bit_p) cr = ENC_CODERANGE_VALID; + } + else { + repl = rb_yield(rb_enc_str_new(p, clen, enc)); str_mod_check(str, sp, slen); - repl = str_compat_and_valid(repl, enc); - rb_str_buf_cat(buf, RSTRING_PTR(repl), RSTRING_LEN(repl)); - if (ENC_CODERANGE(repl) == ENC_CODERANGE_VALID) - cr = ENC_CODERANGE_VALID; - } - p += clen; - p1 = p; - p = search_nonascii(p, e); - if (!p) { - p = e; - break; - } - } - else { - UNREACHABLE; - } - } - if (NIL_P(buf)) { - if (p == e) { - ENC_CODERANGE_SET(str, cr); - return Qnil; - } - buf = rb_str_buf_new(RSTRING_LEN(str)); - } - if (p1 < p) { - rb_str_buf_cat(buf, p1, p - p1); - } - if (p < e) { - if (rep) { - rb_str_buf_cat(buf, rep, replen); - if (!rep7bit_p) cr = ENC_CODERANGE_VALID; - } - else { - repl = rb_yield(rb_enc_str_new(p, e-p, enc)); + repl = str_compat_and_valid(repl, enc); + rb_str_buf_cat(buf, RSTRING_PTR(repl), RSTRING_LEN(repl)); + if (ENC_CODERANGE(repl) == ENC_CODERANGE_VALID) + cr = ENC_CODERANGE_VALID; + } + p += clen; + p1 = p; + p = search_nonascii(p, e); + if (!p) { + p = e; + break; + } + } + else { + UNREACHABLE; + } + } + if (NIL_P(buf)) { + if (p == e) { + ENC_CODERANGE_SET(str, cr); + return Qnil; + } + buf = rb_str_buf_new(RSTRING_LEN(str)); + } + if (p1 < p) { + rb_str_buf_cat(buf, p1, p - p1); + } + if (p < e) { + if (rep) { + rb_str_buf_cat(buf, rep, replen); + if (!rep7bit_p) cr = ENC_CODERANGE_VALID; + } + else { + repl = rb_yield(rb_enc_str_new(p, e-p, enc)); str_mod_check(str, sp, slen); - repl = str_compat_and_valid(repl, enc); - rb_str_buf_cat(buf, RSTRING_PTR(repl), RSTRING_LEN(repl)); - if (ENC_CODERANGE(repl) == ENC_CODERANGE_VALID) - cr = ENC_CODERANGE_VALID; - } - } + repl = str_compat_and_valid(repl, enc); + rb_str_buf_cat(buf, RSTRING_PTR(repl), RSTRING_LEN(repl)); + if (ENC_CODERANGE(repl) == ENC_CODERANGE_VALID) + cr = ENC_CODERANGE_VALID; + } + } } else { - /* ASCII incompatible */ - long mbminlen = rb_enc_mbminlen(enc); - if (!replen) { - rep = NULL; - } - else if (!NIL_P(repl)) { - rep = RSTRING_PTR(repl); - replen = RSTRING_LEN(repl); - } - else if (encidx == ENCINDEX_UTF_16BE) { - DEFAULT_REPLACE_CHAR("\xFF\xFD"); - } - else if (encidx == ENCINDEX_UTF_16LE) { - DEFAULT_REPLACE_CHAR("\xFD\xFF"); - } - else if (encidx == ENCINDEX_UTF_32BE) { - DEFAULT_REPLACE_CHAR("\x00\x00\xFF\xFD"); - } - else if (encidx == ENCINDEX_UTF_32LE) { - DEFAULT_REPLACE_CHAR("\xFD\xFF\x00\x00"); - } - else { - DEFAULT_REPLACE_CHAR("?"); - } + /* ASCII incompatible */ + long mbminlen = rb_enc_mbminlen(enc); + if (!replen) { + rep = NULL; + } + else if (!NIL_P(repl)) { + rep = RSTRING_PTR(repl); + replen = RSTRING_LEN(repl); + } + else if (encidx == ENCINDEX_UTF_16BE) { + DEFAULT_REPLACE_CHAR("\xFF\xFD"); + } + else if (encidx == ENCINDEX_UTF_16LE) { + DEFAULT_REPLACE_CHAR("\xFD\xFF"); + } + else if (encidx == ENCINDEX_UTF_32BE) { + DEFAULT_REPLACE_CHAR("\x00\x00\xFF\xFD"); + } + else if (encidx == ENCINDEX_UTF_32LE) { + DEFAULT_REPLACE_CHAR("\xFD\xFF\x00\x00"); + } + else { + DEFAULT_REPLACE_CHAR("?"); + } - while (p < e) { - int ret = rb_enc_precise_mbclen(p, e, enc); - if (MBCLEN_NEEDMORE_P(ret)) { - break; - } - else if (MBCLEN_CHARFOUND_P(ret)) { - p += MBCLEN_CHARFOUND_LEN(ret); - } - else if (MBCLEN_INVALID_P(ret)) { - const char *q = p; - long clen = rb_enc_mbmaxlen(enc); - if (NIL_P(buf)) buf = rb_str_buf_new(RSTRING_LEN(str)); - if (p > p1) rb_str_buf_cat(buf, p1, p - p1); + while (p < e) { + int ret = rb_enc_precise_mbclen(p, e, enc); + if (MBCLEN_NEEDMORE_P(ret)) { + break; + } + else if (MBCLEN_CHARFOUND_P(ret)) { + p += MBCLEN_CHARFOUND_LEN(ret); + } + else if (MBCLEN_INVALID_P(ret)) { + const char *q = p; + long clen = rb_enc_mbmaxlen(enc); + if (NIL_P(buf)) buf = rb_str_buf_new(RSTRING_LEN(str)); + if (p > p1) rb_str_buf_cat(buf, p1, p - p1); - if (e - p < clen) clen = e - p; - if (clen <= mbminlen * 2) { - clen = mbminlen; - } - else { - clen -= mbminlen; - for (; clen > mbminlen; clen-=mbminlen) { - ret = rb_enc_precise_mbclen(q, q + clen, enc); - if (MBCLEN_NEEDMORE_P(ret)) break; - if (MBCLEN_INVALID_P(ret)) continue; - UNREACHABLE; - } - } - if (rep) { - rb_str_buf_cat(buf, rep, replen); - } - else { - repl = rb_yield(rb_enc_str_new(p, clen, enc)); + if (e - p < clen) clen = e - p; + if (clen <= mbminlen * 2) { + clen = mbminlen; + } + else { + clen -= mbminlen; + for (; clen > mbminlen; clen-=mbminlen) { + ret = rb_enc_precise_mbclen(q, q + clen, enc); + if (MBCLEN_NEEDMORE_P(ret)) break; + if (MBCLEN_INVALID_P(ret)) continue; + UNREACHABLE; + } + } + if (rep) { + rb_str_buf_cat(buf, rep, replen); + } + else { + repl = rb_yield(rb_enc_str_new(p, clen, enc)); str_mod_check(str, sp, slen); - repl = str_compat_and_valid(repl, enc); - rb_str_buf_cat(buf, RSTRING_PTR(repl), RSTRING_LEN(repl)); - } - p += clen; - p1 = p; - } - else { - UNREACHABLE; - } - } - if (NIL_P(buf)) { - if (p == e) { - ENC_CODERANGE_SET(str, ENC_CODERANGE_VALID); - return Qnil; - } - buf = rb_str_buf_new(RSTRING_LEN(str)); - } - if (p1 < p) { - rb_str_buf_cat(buf, p1, p - p1); - } - if (p < e) { - if (rep) { - rb_str_buf_cat(buf, rep, replen); - } - else { - repl = rb_yield(rb_enc_str_new(p, e-p, enc)); + repl = str_compat_and_valid(repl, enc); + rb_str_buf_cat(buf, RSTRING_PTR(repl), RSTRING_LEN(repl)); + } + p += clen; + p1 = p; + } + else { + UNREACHABLE; + } + } + if (NIL_P(buf)) { + if (p == e) { + ENC_CODERANGE_SET(str, ENC_CODERANGE_VALID); + return Qnil; + } + buf = rb_str_buf_new(RSTRING_LEN(str)); + } + if (p1 < p) { + rb_str_buf_cat(buf, p1, p - p1); + } + if (p < e) { + if (rep) { + rb_str_buf_cat(buf, rep, replen); + } + else { + repl = rb_yield(rb_enc_str_new(p, e-p, enc)); str_mod_check(str, sp, slen); - repl = str_compat_and_valid(repl, enc); - rb_str_buf_cat(buf, RSTRING_PTR(repl), RSTRING_LEN(repl)); - } - } - cr = ENC_CODERANGE_VALID; + repl = str_compat_and_valid(repl, enc); + rb_str_buf_cat(buf, RSTRING_PTR(repl), RSTRING_LEN(repl)); + } + } + cr = ENC_CODERANGE_VALID; } ENCODING_CODERANGE_SET(buf, rb_enc_to_index(enc), cr); return buf; @@ -11171,8 +11171,8 @@ unicode_normalize_common(int argc, VALUE *argv, VALUE str, ID id) VALUE argv2[2]; if (!UnicodeNormalizeRequired) { - rb_require("unicode_normalize/normalize.rb"); - UnicodeNormalizeRequired = 1; + rb_require("unicode_normalize/normalize.rb"); + UnicodeNormalizeRequired = 1; } argv2[0] = str; if (rb_check_arity(argc, 0, 1)) argv2[1] = argv[0]; @@ -11401,14 +11401,14 @@ static int sym_printable(const char *s, const char *send, rb_encoding *enc) { while (s < send) { - int n; - int c = rb_enc_precise_mbclen(s, send, enc); + int n; + int c = rb_enc_precise_mbclen(s, send, enc); - if (!MBCLEN_CHARFOUND_P(c)) return FALSE; - n = MBCLEN_CHARFOUND_LEN(c); - c = rb_enc_mbc_to_codepoint(s, send, enc); - if (!rb_enc_isprint(c, enc)) return FALSE; - s += n; + if (!MBCLEN_CHARFOUND_P(c)) return FALSE; + n = MBCLEN_CHARFOUND_LEN(c); + c = rb_enc_mbc_to_codepoint(s, send, enc); + if (!rb_enc_isprint(c, enc)) return FALSE; + s += n; } return TRUE; } @@ -11426,8 +11426,8 @@ rb_str_symname_p(VALUE sym) ptr = RSTRING_PTR(sym); len = RSTRING_LEN(sym); if ((resenc != enc && !rb_str_is_ascii_only_p(sym)) || len != (long)strlen(ptr) || - !rb_enc_symname2_p(ptr, len, enc) || !sym_printable(ptr, ptr + len, enc)) { - return FALSE; + !rb_enc_symname2_p(ptr, len, enc) || !sym_printable(ptr, ptr + len, enc)) { + return FALSE; } return TRUE; } @@ -11447,8 +11447,8 @@ rb_str_quote_unprintable(VALUE str) ptr = RSTRING_PTR(str); len = RSTRING_LEN(str); if ((resenc != enc && !rb_str_is_ascii_only_p(str)) || - !sym_printable(ptr, ptr + len, enc)) { - return rb_str_escape(str); + !sym_printable(ptr, ptr + len, enc)) { + return rb_str_escape(str); } return str; } @@ -11458,7 +11458,7 @@ rb_id_quote_unprintable(ID id) { VALUE str = rb_id2str(id); if (!rb_str_symname_p(str)) { - return rb_str_escape(str); + return rb_str_escape(str); } return str; } @@ -11484,18 +11484,18 @@ sym_inspect(VALUE sym) char *dest; if (!rb_str_symname_p(str)) { - str = rb_str_inspect(str); - len = RSTRING_LEN(str); - rb_str_resize(str, len + 1); - dest = RSTRING_PTR(str); - memmove(dest + 1, dest, len); + str = rb_str_inspect(str); + len = RSTRING_LEN(str); + rb_str_resize(str, len + 1); + dest = RSTRING_PTR(str); + memmove(dest + 1, dest, len); } else { - rb_encoding *enc = STR_ENC_GET(str); - RSTRING_GETMEM(str, ptr, len); - str = rb_enc_str_new(0, len + 1, enc); - dest = RSTRING_PTR(str); - memcpy(dest + 1, ptr, len); + rb_encoding *enc = STR_ENC_GET(str); + RSTRING_GETMEM(str, ptr, len); + str = rb_enc_str_new(0, len + 1, enc); + dest = RSTRING_PTR(str); + memcpy(dest + 1, ptr, len); } dest[0] = ':'; return str; @@ -11543,7 +11543,7 @@ rb_sym_proc_call(ID mid, int argc, const VALUE *argv, int kw_splat, VALUE passed VALUE obj; if (argc < 1) { - rb_raise(rb_eArgError, "no receiver given"); + rb_raise(rb_eArgError, "no receiver given"); } obj = argv[0]; return rb_funcall_with_block_kw(obj, mid, argc - 1, argv + 1, passed_proc, kw_splat); @@ -11590,7 +11590,7 @@ static VALUE sym_cmp(VALUE sym, VALUE other) { if (!SYMBOL_P(other)) { - return Qnil; + return Qnil; } return rb_str_cmp_m(rb_sym2str(sym), rb_sym2str(other)); } @@ -11607,7 +11607,7 @@ static VALUE sym_casecmp(VALUE sym, VALUE other) { if (!SYMBOL_P(other)) { - return Qnil; + return Qnil; } return str_casecmp(rb_sym2str(sym), rb_sym2str(other)); } @@ -11624,7 +11624,7 @@ static VALUE sym_casecmp_p(VALUE sym, VALUE other) { if (!SYMBOL_P(other)) { - return Qnil; + return Qnil; } return str_casecmp_p(rb_sym2str(sym), rb_sym2str(other)); } @@ -11838,12 +11838,12 @@ static VALUE string_for_symbol(VALUE name) { if (!RB_TYPE_P(name, T_STRING)) { - VALUE tmp = rb_check_string_type(name); - if (NIL_P(tmp)) { - rb_raise(rb_eTypeError, "%+"PRIsVALUE" is not a symbol", - name); - } - name = tmp; + VALUE tmp = rb_check_string_type(name); + if (NIL_P(tmp)) { + rb_raise(rb_eTypeError, "%+"PRIsVALUE" is not a symbol", + name); + } + name = tmp; } return name; } @@ -11852,7 +11852,7 @@ ID rb_to_id(VALUE name) { if (SYMBOL_P(name)) { - return SYM2ID(name); + return SYM2ID(name); } name = string_for_symbol(name); return rb_intern_str(name); @@ -11862,7 +11862,7 @@ VALUE rb_to_symbol(VALUE name) { if (SYMBOL_P(name)) { - return name; + return name; } name = string_for_symbol(name); return rb_str_intern(name); diff --git a/struct.c b/struct.c index c95c88200b..d1c8ae24f2 100644 --- a/struct.c +++ b/struct.c @@ -40,7 +40,7 @@ struct_ivar_get(VALUE c, ID id) VALUE ivar = rb_attr_get(c, id); if (!NIL_P(ivar)) - return ivar; + return ivar; for (;;) { c = rb_class_superclass(c); @@ -66,10 +66,10 @@ rb_struct_s_members(VALUE klass) VALUE members = struct_ivar_get(klass, id_members); if (NIL_P(members)) { - rb_raise(rb_eTypeError, "uninitialized struct"); + rb_raise(rb_eTypeError, "uninitialized struct"); } if (!RB_TYPE_P(members, T_ARRAY)) { - rb_raise(rb_eTypeError, "corrupted struct"); + rb_raise(rb_eTypeError, "corrupted struct"); } return members; } @@ -80,8 +80,8 @@ rb_struct_members(VALUE s) VALUE members = rb_struct_s_members(rb_obj_class(s)); if (RSTRUCT_LEN(s) != RARRAY_LEN(members)) { - rb_raise(rb_eTypeError, "struct size differs (%ld required %ld given)", - RARRAY_LEN(members), RSTRUCT_LEN(s)); + rb_raise(rb_eTypeError, "struct size differs (%ld required %ld given)", + RARRAY_LEN(members), RSTRUCT_LEN(s)); } return members; } @@ -107,33 +107,33 @@ struct_set_members(VALUE klass, VALUE /* frozen hidden array */ members) const long members_length = RARRAY_LEN(members); if (members_length <= AREF_HASH_THRESHOLD) { - back = members; + back = members; } else { - long i, j, mask = 64; - VALUE name; + long i, j, mask = 64; + VALUE name; - while (mask < members_length * AREF_HASH_UNIT) mask *= 2; + while (mask < members_length * AREF_HASH_UNIT) mask *= 2; - back = rb_ary_tmp_new(mask + 1); - rb_ary_store(back, mask, INT2FIX(members_length)); - mask -= 2; /* mask = (2**k-1)*2 */ + back = rb_ary_tmp_new(mask + 1); + rb_ary_store(back, mask, INT2FIX(members_length)); + mask -= 2; /* mask = (2**k-1)*2 */ - for (i=0; i < members_length; i++) { - name = RARRAY_AREF(members, i); + for (i=0; i < members_length; i++) { + name = RARRAY_AREF(members, i); - j = struct_member_pos_ideal(name, mask); + j = struct_member_pos_ideal(name, mask); - for (;;) { - if (!RTEST(RARRAY_AREF(back, j))) { - rb_ary_store(back, j, name); - rb_ary_store(back, j + 1, INT2FIX(i)); - break; - } - j = struct_member_pos_probe(j, mask); - } - } - OBJ_FREEZE_RAW(back); + for (;;) { + if (!RTEST(RARRAY_AREF(back, j))) { + rb_ary_store(back, j, name); + rb_ary_store(back, j + 1, INT2FIX(i)); + break; + } + j = struct_member_pos_probe(j, mask); + } + } + OBJ_FREEZE_RAW(back); } rb_ivar_set(klass, id_members, members); rb_ivar_set(klass, id_back_members, back); @@ -148,30 +148,30 @@ struct_member_pos(VALUE s, VALUE name) long j, mask; if (UNLIKELY(NIL_P(back))) { - rb_raise(rb_eTypeError, "uninitialized struct"); + rb_raise(rb_eTypeError, "uninitialized struct"); } if (UNLIKELY(!RB_TYPE_P(back, T_ARRAY))) { - rb_raise(rb_eTypeError, "corrupted struct"); + rb_raise(rb_eTypeError, "corrupted struct"); } mask = RARRAY_LEN(back); if (mask <= AREF_HASH_THRESHOLD) { - if (UNLIKELY(RSTRUCT_LEN(s) != mask)) { - rb_raise(rb_eTypeError, - "struct size differs (%ld required %ld given)", - mask, RSTRUCT_LEN(s)); - } - for (j = 0; j < mask; j++) { + if (UNLIKELY(RSTRUCT_LEN(s) != mask)) { + rb_raise(rb_eTypeError, + "struct size differs (%ld required %ld given)", + mask, RSTRUCT_LEN(s)); + } + for (j = 0; j < mask; j++) { if (RARRAY_AREF(back, j) == name) - return (int)j; - } - return -1; + return (int)j; + } + return -1; } if (UNLIKELY(RSTRUCT_LEN(s) != FIX2INT(RARRAY_AREF(back, mask-1)))) { - rb_raise(rb_eTypeError, "struct size differs (%d required %ld given)", - FIX2INT(RARRAY_AREF(back, mask-1)), RSTRUCT_LEN(s)); + rb_raise(rb_eTypeError, "struct size differs (%d required %ld given)", + FIX2INT(RARRAY_AREF(back, mask-1)), RSTRUCT_LEN(s)); } mask -= 3; @@ -182,9 +182,9 @@ struct_member_pos(VALUE s, VALUE name) if (e == name) return FIX2INT(RARRAY_AREF(back, j + 1)); if (!RTEST(e)) { - return -1; - } - j = struct_member_pos_probe(j, mask); + return -1; + } + j = struct_member_pos_probe(j, mask); } } @@ -231,7 +231,7 @@ rb_struct_getmember(VALUE obj, ID id) VALUE slot = ID2SYM(id); int i = struct_member_pos(obj, slot); if (i != -1) { - return RSTRUCT_GET(obj, i); + return RSTRUCT_GET(obj, i); } rb_name_err_raise("`%1$s' is not a struct member", obj, ID2SYM(id)); @@ -262,13 +262,13 @@ new_struct(VALUE name, VALUE super) ID id; name = rb_str_to_str(name); if (!rb_is_const_name(name)) { - rb_name_err_raise("identifier %1$s needs to be constant", - super, name); + rb_name_err_raise("identifier %1$s needs to be constant", + super, name); } id = rb_to_id(name); if (rb_const_defined_at(super, id)) { - rb_warn("redefining constant %"PRIsVALUE"::%"PRIsVALUE, super, name); - rb_mod_remove_const(super, ID2SYM(id)); + rb_warn("redefining constant %"PRIsVALUE"::%"PRIsVALUE, super, name); + rb_mod_remove_const(super, ID2SYM(id)); } return rb_define_class_id_under(super, id, super); } @@ -292,7 +292,7 @@ rb_struct_s_inspect(VALUE klass) { VALUE inspect = rb_class_name(klass); if (RTEST(rb_struct_s_keyword_init(klass))) { - rb_str_cat_cstr(inspect, "(keyword_init: true)"); + rb_str_cat_cstr(inspect, "(keyword_init: true)"); } return inspect; } @@ -340,7 +340,7 @@ setup_struct(VALUE nstr, VALUE members) for (i=0; i< len; i++) { VALUE sym = RARRAY_AREF(members, i); ID id = SYM2ID(sym); - VALUE off = LONG2NUM(i); + VALUE off = LONG2NUM(i); define_aref_method(nstr, sym, off); define_aset_method(nstr, ID2SYM(rb_id_attrset(id)), off); @@ -365,10 +365,10 @@ struct_make_members_list(va_list ar) RBASIC_CLEAR_CLASS(list); OBJ_WB_UNPROTECT(list); while ((mem = va_arg(ar, char*)) != 0) { - VALUE sym = rb_sym_intern_ascii_cstr(mem); - if (st_insert(tbl, sym, Qtrue)) { - rb_raise(rb_eArgError, "duplicate member: %s", mem); - } + VALUE sym = rb_sym_intern_ascii_cstr(mem); + if (st_insert(tbl, sym, Qtrue)) { + rb_raise(rb_eArgError, "duplicate member: %s", mem); + } } ary = rb_hash_keys(list); st_clear(tbl); @@ -383,24 +383,24 @@ struct_define_without_accessor(VALUE outer, const char *class_name, VALUE super, VALUE klass; if (class_name) { - if (outer) { - klass = rb_define_class_under(outer, class_name, super); - } - else { - klass = rb_define_class(class_name, super); - } + if (outer) { + klass = rb_define_class_under(outer, class_name, super); + } + else { + klass = rb_define_class(class_name, super); + } } else { - klass = anonymous_struct(super); + klass = anonymous_struct(super); } struct_set_members(klass, members); if (alloc) { - rb_define_alloc_func(klass, alloc); + rb_define_alloc_func(klass, alloc); } else { - rb_define_alloc_func(klass, struct_alloc); + rb_define_alloc_func(klass, struct_alloc); } return klass; @@ -582,19 +582,19 @@ rb_struct_s_def(int argc, VALUE *argv, VALUE klass) argc = rb_scan_args(argc, argv, "1*:", NULL, NULL, &opt); name = argv[0]; if (SYMBOL_P(name)) { - name = Qnil; + name = Qnil; } else { - --argc; - ++argv; + --argc; + ++argv; } if (!NIL_P(opt)) { - static ID keyword_ids[1]; + static ID keyword_ids[1]; - if (!keyword_ids[0]) { - keyword_ids[0] = rb_intern("keyword_init"); - } + if (!keyword_ids[0]) { + keyword_ids[0] = rb_intern("keyword_init"); + } rb_get_kwargs(opt, keyword_ids, 0, 1, &keyword_init); if (keyword_init == Qundef) { keyword_init = Qnil; @@ -609,23 +609,23 @@ rb_struct_s_def(int argc, VALUE *argv, VALUE klass) OBJ_WB_UNPROTECT(rest); tbl = RHASH_TBL_RAW(rest); for (i=0; iself, &key); if (i < 0) { - if (NIL_P(args->unknown_keywords)) { - args->unknown_keywords = rb_ary_new(); - } - rb_ary_push(args->unknown_keywords, key); + if (NIL_P(args->unknown_keywords)) { + args->unknown_keywords = rb_ary_new(); + } + rb_ary_push(args->unknown_keywords, key); } else { - rb_struct_modify(args->self); - RSTRUCT_SET(args->self, i, val); + rb_struct_modify(args->self); + RSTRUCT_SET(args->self, i, val); } return ST_CONTINUE; } @@ -689,41 +689,41 @@ rb_struct_initialize_m(int argc, const VALUE *argv, VALUE self) bool keyword_init = false; switch (rb_struct_s_keyword_init(klass)) { default: - if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) { - rb_raise(rb_eArgError, "wrong number of arguments (given %d, expected 0)", argc); - } - keyword_init = true; - break; + if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) { + rb_raise(rb_eArgError, "wrong number of arguments (given %d, expected 0)", argc); + } + keyword_init = true; + break; case Qfalse: break; case Qnil: - if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) { + if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) { break; } - keyword_init = rb_keyword_given_p(); + keyword_init = rb_keyword_given_p(); break; } if (keyword_init) { - struct struct_hash_set_arg arg; - rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self), n); - arg.self = self; - arg.unknown_keywords = Qnil; - rb_hash_foreach(argv[0], struct_hash_set_i, (VALUE)&arg); - if (arg.unknown_keywords != Qnil) { - rb_raise(rb_eArgError, "unknown keywords: %s", - RSTRING_PTR(rb_ary_join(arg.unknown_keywords, rb_str_new2(", ")))); - } + struct struct_hash_set_arg arg; + rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self), n); + arg.self = self; + arg.unknown_keywords = Qnil; + rb_hash_foreach(argv[0], struct_hash_set_i, (VALUE)&arg); + if (arg.unknown_keywords != Qnil) { + rb_raise(rb_eArgError, "unknown keywords: %s", + RSTRING_PTR(rb_ary_join(arg.unknown_keywords, rb_str_new2(", ")))); + } } else { - if (n < argc) { - rb_raise(rb_eArgError, "struct size differs"); - } + if (n < argc) { + rb_raise(rb_eArgError, "struct size differs"); + } for (long i=0; i argc) { - rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self)+argc, n-argc); - } + RSTRUCT_SET(self, i, argv[i]); + } + if (n > argc) { + rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self)+argc, n-argc); + } } return Qnil; } @@ -784,7 +784,7 @@ struct_alloc(VALUE klass) if (0 < n && n <= RSTRUCT_EMBED_LEN_MAX) { RBASIC(st)->flags &= ~RSTRUCT_EMBED_LEN_MASK; RBASIC(st)->flags |= n << RSTRUCT_EMBED_LEN_SHIFT; - rb_mem_clear((VALUE *)st->as.ary, n); + rb_mem_clear((VALUE *)st->as.ary, n); } else { st->as.heap.ptr = struct_heap_alloc((VALUE)st, n); @@ -810,12 +810,12 @@ rb_struct_new(VALUE klass, ...) size = rb_long2int(num_members(klass)); if (size > numberof(tmpargs)) { - tmpargs[0] = rb_ary_tmp_new(size); - mem = RARRAY_PTR(tmpargs[0]); + tmpargs[0] = rb_ary_tmp_new(size); + mem = RARRAY_PTR(tmpargs[0]); } va_start(args, klass); for (i=0; i"); + return rb_str_cat2(str, ":...>"); } members = rb_struct_members(s); len = RSTRUCT_LEN(s); for (i=0; i 0) { - rb_str_cat2(str, ", "); - } - else if (first != '#') { - rb_str_cat2(str, " "); - } - slot = RARRAY_AREF(members, i); - id = SYM2ID(slot); - if (rb_is_local_id(id) || rb_is_const_id(id)) { - rb_str_append(str, rb_id2str(id)); - } - else { - rb_str_append(str, rb_inspect(slot)); - } - rb_str_cat2(str, "="); - rb_str_append(str, rb_inspect(RSTRUCT_GET(s, i))); + if (i > 0) { + rb_str_cat2(str, ", "); + } + else if (first != '#') { + rb_str_cat2(str, " "); + } + slot = RARRAY_AREF(members, i); + id = SYM2ID(slot); + if (rb_is_local_id(id) || rb_is_const_id(id)) { + rb_str_append(str, rb_id2str(id)); + } + else { + rb_str_append(str, rb_inspect(slot)); + } + rb_str_cat2(str, "="); + rb_str_append(str, rb_inspect(RSTRUCT_GET(s, i))); } rb_str_cat2(str, ">"); @@ -1063,7 +1063,7 @@ rb_struct_deconstruct_keys(VALUE s, VALUE keys) return rb_struct_to_h(s); } if (UNLIKELY(!RB_TYPE_P(keys, T_ARRAY))) { - rb_raise(rb_eTypeError, + rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (expected Array or nil)", rb_obj_class(keys)); @@ -1091,11 +1091,11 @@ rb_struct_init_copy(VALUE copy, VALUE s) if (!OBJ_INIT_COPY(copy, s)) return copy; if (RSTRUCT_LEN(copy) != RSTRUCT_LEN(s)) { - rb_raise(rb_eTypeError, "struct size mismatch"); + rb_raise(rb_eTypeError, "struct size mismatch"); } for (i=0, len=RSTRUCT_LEN(copy); imbc_case_fold(ONIGENC_CASE_FOLD, - &beg, (const OnigUChar *)end, - fold, enc); - if (r > 0 && (r != len || memcmp(fold, name, r))) - return TRUE; + /* fallback to case-folding */ + OnigUChar fold[ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM]; + const OnigUChar *beg = (const OnigUChar *)name; + int r = enc->mbc_case_fold(ONIGENC_CASE_FOLD, + &beg, (const OnigUChar *)end, + fold, enc); + if (r > 0 && (r != len || memcmp(fold, name, r))) + return TRUE; } return FALSE; } @@ -286,7 +286,7 @@ enc_synmane_type_leading_chars(const char *name, long len, rb_encoding *enc, int } case '<': - switch (*++m) { + switch (*++m) { default: return (t) { stophere, ID_JUNK, 1, }; case '<': return (t) { stophere, ID_JUNK, 2, }; case '=': @@ -294,16 +294,16 @@ enc_synmane_type_leading_chars(const char *name, long len, rb_encoding *enc, int default: return (t) { stophere, ID_JUNK, 2, }; case '>': return (t) { stophere, ID_JUNK, 3, }; } - } + } case '>': - switch (*++m) { + switch (*++m) { default: return (t) { stophere, ID_JUNK, 1, }; case '>': case '=': return (t) { stophere, ID_JUNK, 2, }; - } + } case '=': - switch (*++m) { + switch (*++m) { default: return (t) { invalid, 0, 1, }; case '~': return (t) { stophere, ID_JUNK, 2, }; case '=': @@ -311,7 +311,7 @@ enc_synmane_type_leading_chars(const char *name, long len, rb_encoding *enc, int default: return (t) { stophere, ID_JUNK, 2, }; case '=': return (t) { stophere, ID_JUNK, 3, }; } - } + } case '*': switch (*++m) { @@ -339,16 +339,16 @@ enc_synmane_type_leading_chars(const char *name, long len, rb_encoding *enc, int } case '!': - switch (*++m) { + switch (*++m) { case '=': case '~': return (t) { stophere, ID_JUNK, 2, }; - default: + default: if (allowed_attrset & (1U << ID_JUNK)) { return (t) { needmore, ID_JUNK, 1, }; } else { return (t) { stophere, ID_JUNK, 1, }; } - } + } default: if (rb_sym_constant_char_p(name, len, enc)) { @@ -426,8 +426,8 @@ set_id_entry(rb_symbols_t *symbols, rb_id_serial_t num, VALUE str, VALUE sym) VALUE ary, ids = symbols->ids; if (idx >= (size_t)RARRAY_LEN(ids) || NIL_P(ary = rb_ary_entry(ids, (long)idx))) { - ary = rb_ary_tmp_new(ID_ENTRY_UNIT * ID_ENTRY_SIZE); - rb_ary_store(ids, (long)idx, ary); + ary = rb_ary_tmp_new(ID_ENTRY_UNIT * ID_ENTRY_SIZE); + rb_ary_store(ids, (long)idx, ary); } idx = (num % ID_ENTRY_UNIT) * ID_ENTRY_SIZE; rb_ary_store(ary, (long)idx + ID_ENTRY_STR, str); @@ -492,11 +492,11 @@ rb_id_serial_to_id(rb_id_serial_t num) { if (is_notop_id((ID)num)) { VALUE sym = get_id_serial_entry(num, 0, ID_ENTRY_SYM); - if (sym) return SYM2ID(sym); - return ((ID)num << ID_SCOPE_SHIFT) | ID_INTERNAL | ID_STATIC_SYM; + if (sym) return SYM2ID(sym); + return ((ID)num << ID_SCOPE_SHIFT) | ID_INTERNAL | ID_STATIC_SYM; } else { - return (ID)num; + return (ID)num; } } @@ -505,8 +505,8 @@ static int register_sym_update_callback(st_data_t *key, st_data_t *value, st_data_t arg, int existing) { if (existing) { - rb_fatal("symbol :% "PRIsVALUE" is already registered with %"PRIxVALUE, - (VALUE)*key, (VALUE)*value); + rb_fatal("symbol :% "PRIsVALUE" is already registered with %"PRIxVALUE, + (VALUE)*key, (VALUE)*value); } *value = arg; return ST_CONTINUE; @@ -571,10 +571,10 @@ sym_check_asciionly(VALUE str) if (!rb_enc_asciicompat(rb_enc_get(str))) return FALSE; switch (rb_enc_str_coderange(str)) { case ENC_CODERANGE_BROKEN: - rb_raise(rb_eEncodingError, "invalid symbol in encoding %s :%+"PRIsVALUE, - rb_enc_name(rb_enc_get(str)), str); + rb_raise(rb_eEncodingError, "invalid symbol in encoding %s :%+"PRIsVALUE, + rb_enc_name(rb_enc_get(str)), str); case ENC_CODERANGE_7BIT: - return TRUE; + return TRUE; } return FALSE; } @@ -590,19 +590,19 @@ static inline void must_be_dynamic_symbol(VALUE x) { if (UNLIKELY(!DYNAMIC_SYM_P(x))) { - if (STATIC_SYM_P(x)) { - VALUE str = lookup_id_str(RSHIFT((unsigned long)(x),RUBY_SPECIAL_SHIFT)); + if (STATIC_SYM_P(x)) { + VALUE str = lookup_id_str(RSHIFT((unsigned long)(x),RUBY_SPECIAL_SHIFT)); - if (str) { - rb_bug("wrong argument: %s (inappropriate Symbol)", RSTRING_PTR(str)); - } - else { - rb_bug("wrong argument: inappropriate Symbol (%p)", (void *)x); - } - } - else { - rb_bug("wrong argument type %s (expected Symbol)", rb_builtin_class_name(x)); - } + if (str) { + rb_bug("wrong argument: %s (inappropriate Symbol)", RSTRING_PTR(str)); + } + else { + rb_bug("wrong argument: inappropriate Symbol (%p)", (void *)x); + } + } + else { + rb_bug("wrong argument type %s (expected Symbol)", rb_builtin_class_name(x)); + } } } #endif @@ -636,14 +636,14 @@ dsymbol_check(rb_symbols_t *symbols, const VALUE sym) ASSERT_vm_locking(); if (UNLIKELY(rb_objspace_garbage_object_p(sym))) { - const VALUE fstr = RSYMBOL(sym)->fstr; - const ID type = RSYMBOL(sym)->id & ID_SCOPE_MASK; - RSYMBOL(sym)->fstr = 0; + const VALUE fstr = RSYMBOL(sym)->fstr; + const ID type = RSYMBOL(sym)->id & ID_SCOPE_MASK; + RSYMBOL(sym)->fstr = 0; unregister_sym(symbols, fstr, sym); return dsymbol_alloc(symbols, rb_cSymbol, fstr, rb_enc_get(fstr), type); } else { - return sym; + return sym; } } @@ -660,19 +660,19 @@ lookup_str_id(VALUE str) GLOBAL_SYMBOLS_LEAVE(); if (found) { - const VALUE sym = (VALUE)sym_data; + const VALUE sym = (VALUE)sym_data; - if (STATIC_SYM_P(sym)) { - return STATIC_SYM2ID(sym); - } - else if (DYNAMIC_SYM_P(sym)) { - ID id = RSYMBOL(sym)->id; - if (id & ~ID_SCOPE_MASK) return id; - } - else { - rb_bug("non-symbol object %s:%"PRIxVALUE" for %"PRIsVALUE" in symbol table", - rb_builtin_class_name(sym), sym, str); - } + if (STATIC_SYM_P(sym)) { + return STATIC_SYM2ID(sym); + } + else if (DYNAMIC_SYM_P(sym)) { + ID id = RSYMBOL(sym)->id; + if (id & ~ID_SCOPE_MASK) return id; + } + else { + rb_bug("non-symbol object %s:%"PRIxVALUE" for %"PRIsVALUE" in symbol table", + rb_builtin_class_name(sym), sym, str); + } } return (ID)0; } @@ -764,13 +764,13 @@ intern_str(VALUE str, int mutable) id = rb_str_symname_type(str, IDSET_ATTRSET_FOR_INTERN); if (id == (ID)-1) id = ID_JUNK; if (sym_check_asciionly(str)) { - if (!mutable) str = rb_str_dup(str); - rb_enc_associate(str, rb_usascii_encoding()); + if (!mutable) str = rb_str_dup(str); + rb_enc_associate(str, rb_usascii_encoding()); } if ((nid = next_id_base()) == (ID)-1) { - str = rb_str_ellipsize(str, 20); - rb_raise(rb_eRuntimeError, "symbol table overflow (symbol %"PRIsVALUE")", - str); + str = rb_str_ellipsize(str, 20); + rb_raise(rb_eRuntimeError, "symbol table overflow (symbol %"PRIsVALUE")", + str); } id |= nid; id |= ID_STATIC_SYM; @@ -796,7 +796,7 @@ rb_intern_str(VALUE str) VALUE sym = lookup_str_sym(str); if (sym) { - return SYM2ID(sym); + return SYM2ID(sym); } return intern_str(str, 0); @@ -808,7 +808,7 @@ rb_gc_free_dsymbol(VALUE sym) VALUE str = RSYMBOL(sym)->fstr; if (str) { - RSYMBOL(sym)->fstr = 0; + RSYMBOL(sym)->fstr = 0; GLOBAL_SYMBOLS_ENTER(symbols); { @@ -889,7 +889,7 @@ rb_sym2id(VALUE sym) { ID id; if (STATIC_SYM_P(sym)) { - id = STATIC_SYM2ID(sym); + id = STATIC_SYM2ID(sym); } else if (DYNAMIC_SYM_P(sym)) { GLOBAL_SYMBOLS_ENTER(symbols); @@ -907,12 +907,12 @@ rb_sym2id(VALUE sym) set_id_entry(symbols, rb_id_to_serial(num), fstr, sym); rb_hash_delete_entry(symbols->dsymbol_fstr_hash, fstr); } - } + } GLOBAL_SYMBOLS_LEAVE(); } else { - rb_raise(rb_eTypeError, "wrong argument type %s (expected Symbol)", - rb_builtin_class_name(sym)); + rb_raise(rb_eTypeError, "wrong argument type %s (expected Symbol)", + rb_builtin_class_name(sym)); } return id; } @@ -941,10 +941,10 @@ VALUE rb_sym2str(VALUE sym) { if (DYNAMIC_SYM_P(sym)) { - return RSYMBOL(sym)->fstr; + return RSYMBOL(sym)->fstr; } else { - return rb_id2str(STATIC_SYM2ID(sym)); + return rb_id2str(STATIC_SYM2ID(sym)); } } @@ -975,7 +975,7 @@ rb_make_temporary_id(size_t n) const ID max_id = RB_ID_SERIAL_MAX & ~0xffff; const ID id = max_id - (ID)n; if (id <= ruby_global_symbols.last_id) { - rb_raise(rb_eRuntimeError, "too big to make temporary ID: %" PRIdSIZE, n); + rb_raise(rb_eRuntimeError, "too big to make temporary ID: %" PRIdSIZE, n); } return (id << ID_SCOPE_SHIFT) | ID_STATIC_SYM | ID_INTERNAL; } @@ -987,19 +987,19 @@ symbols_i(st_data_t key, st_data_t value, st_data_t arg) VALUE sym = (VALUE)value; if (STATIC_SYM_P(sym)) { - rb_ary_push(ary, sym); - return ST_CONTINUE; + rb_ary_push(ary, sym); + return ST_CONTINUE; } else if (!DYNAMIC_SYM_P(sym)) { - rb_bug("invalid symbol: %s", RSTRING_PTR((VALUE)key)); + rb_bug("invalid symbol: %s", RSTRING_PTR((VALUE)key)); } else if (!SYMBOL_PINNED_P(sym) && rb_objspace_garbage_object_p(sym)) { - RSYMBOL(sym)->fstr = 0; - return ST_DELETE; + RSYMBOL(sym)->fstr = 0; + return ST_DELETE; } else { - rb_ary_push(ary, sym); - return ST_CONTINUE; + rb_ary_push(ary, sym); + return ST_CONTINUE; } } @@ -1086,25 +1086,25 @@ rb_check_id(volatile VALUE *namep) VALUE name = *namep; if (STATIC_SYM_P(name)) { - return STATIC_SYM2ID(name); + return STATIC_SYM2ID(name); } else if (DYNAMIC_SYM_P(name)) { - if (SYMBOL_PINNED_P(name)) { - return RSYMBOL(name)->id; - } - else { - *namep = RSYMBOL(name)->fstr; - return 0; - } + if (SYMBOL_PINNED_P(name)) { + return RSYMBOL(name)->id; + } + else { + *namep = RSYMBOL(name)->fstr; + return 0; + } } else if (!RB_TYPE_P(name, T_STRING)) { - tmp = rb_check_string_type(name); - if (NIL_P(tmp)) { - rb_raise(rb_eTypeError, "%+"PRIsVALUE" is not a symbol nor a string", - name); - } - name = tmp; - *namep = name; + tmp = rb_check_string_type(name); + if (NIL_P(tmp)) { + rb_raise(rb_eTypeError, "%+"PRIsVALUE" is not a symbol nor a string", + name); + } + name = tmp; + *namep = name; } sym_check_asciionly(name); @@ -1120,10 +1120,10 @@ rb_check_symbol(volatile VALUE *namep) VALUE name = *namep; if (STATIC_SYM_P(name)) { - return name; + return name; } else if (DYNAMIC_SYM_P(name)) { - if (!SYMBOL_PINNED_P(name)) { + if (!SYMBOL_PINNED_P(name)) { GLOBAL_SYMBOLS_ENTER(symbols); { name = dsymbol_check(symbols, name); @@ -1131,23 +1131,23 @@ rb_check_symbol(volatile VALUE *namep) GLOBAL_SYMBOLS_LEAVE(); *namep = name; - } - return name; + } + return name; } else if (!RB_TYPE_P(name, T_STRING)) { - tmp = rb_check_string_type(name); - if (NIL_P(tmp)) { - rb_raise(rb_eTypeError, "%+"PRIsVALUE" is not a symbol nor a string", - name); - } - name = tmp; - *namep = name; + tmp = rb_check_string_type(name); + if (NIL_P(tmp)) { + rb_raise(rb_eTypeError, "%+"PRIsVALUE" is not a symbol nor a string", + name); + } + name = tmp; + *namep = name; } sym_check_asciionly(name); if ((sym = lookup_str_sym(name)) != 0) { - return sym; + return sym; } return Qnil; @@ -1174,7 +1174,7 @@ rb_check_symbol_cstr(const char *ptr, long len, rb_encoding *enc) sym_check_asciionly(name); if ((sym = lookup_str_sym(name)) != 0) { - return sym; + return sym; } return Qnil; diff --git a/symbol.h b/symbol.h index e2710ba61b..ffbf7ce198 100644 --- a/symbol.h +++ b/symbol.h @@ -20,7 +20,7 @@ #ifdef HAVE_BUILTIN___BUILTIN_CONSTANT_P #define rb_id2sym(id) \ RB_GNUC_EXTENSION_BLOCK(__builtin_constant_p(id) && !DYNAMIC_ID_P(id) ? \ - STATIC_ID2SYM(id) : rb_id2sym(id)) + STATIC_ID2SYM(id) : rb_id2sym(id)) #endif struct RSymbol { @@ -45,10 +45,10 @@ static inline int id_type(ID id) { if (is_notop_id(id)) { - return (int)(id&ID_SCOPE_MASK); + return (int)(id&ID_SCOPE_MASK); } else { - return -1; + return -1; } } @@ -69,10 +69,10 @@ static inline rb_id_serial_t rb_id_to_serial(ID id) { if (is_notop_id(id)) { - return (rb_id_serial_t)(id >> ID_SCOPE_SHIFT); + return (rb_id_serial_t)(id >> ID_SCOPE_SHIFT); } else { - return (rb_id_serial_t)id; + return (rb_id_serial_t)id; } } @@ -81,13 +81,13 @@ sym_type(VALUE sym) { ID id; if (STATIC_SYM_P(sym)) { - id = RSHIFT(sym, RUBY_SPECIAL_SHIFT); - if (id<=tLAST_OP_ID) { - return -1; - } + id = RSHIFT(sym, RUBY_SPECIAL_SHIFT); + if (id<=tLAST_OP_ID) { + return -1; + } } else { - id = RSYMBOL(sym)->id; + id = RSYMBOL(sym)->id; } return (int)(id&ID_SCOPE_MASK); } diff --git a/template/prelude.c.tmpl b/template/prelude.c.tmpl index 0214d0d659..3d792867f3 100644 --- a/template/prelude.c.tmpl +++ b/template/prelude.c.tmpl @@ -158,8 +158,8 @@ prelude_ast(VALUE name, VALUE code, int line) { rb_ast_t *ast = rb_parser_compile_string_path(rb_parser_new(), name, code, line); if (!ast->body.root) { - rb_ast_dispose(ast); - rb_exc_raise(rb_errinfo()); + rb_ast_dispose(ast); + rb_exc_raise(rb_errinfo()); } return ast; } @@ -196,22 +196,22 @@ static void prelude_eval(VALUE code, VALUE name, int line) { static const rb_compile_option_t optimization = { - TRUE, /* int inline_const_cache; */ - TRUE, /* int peephole_optimization; */ - FALSE,/* int tailcall_optimization; */ - TRUE, /* int specialized_instruction; */ - TRUE, /* int operands_unification; */ - TRUE, /* int instructions_unification; */ - TRUE, /* int stack_caching; */ - TRUE, /* int frozen_string_literal; */ - FALSE, /* int debug_frozen_string_literal; */ - FALSE, /* unsigned int coverage_enabled; */ - 0, /* int debug_level; */ + TRUE, /* int inline_const_cache; */ + TRUE, /* int peephole_optimization; */ + FALSE,/* int tailcall_optimization; */ + TRUE, /* int specialized_instruction; */ + TRUE, /* int operands_unification; */ + TRUE, /* int instructions_unification; */ + TRUE, /* int stack_caching; */ + TRUE, /* int frozen_string_literal; */ + FALSE, /* int debug_frozen_string_literal; */ + FALSE, /* unsigned int coverage_enabled; */ + 0, /* int debug_level; */ }; rb_ast_t *ast = prelude_ast(name, code, line); rb_iseq_eval(rb_iseq_new_with_opt(&ast->body, name, name, Qnil, INT2FIX(line), - NULL, 0, ISEQ_TYPE_TOP, &optimization)); + NULL, 0, ISEQ_TYPE_TOP, &optimization)); rb_ast_dispose(ast); } COMPILER_WARNING_POP @@ -233,14 +233,14 @@ prelude_require(VALUE self, VALUE nth) % @preludes.each_value do |i, prelude, lines, sub, start_line| % if sub == true case <%=i%><%=%>: - code = PRELUDE_CODE(<%=i%><%=%>); - name = PRELUDE_NAME(<%=i%><%=%>); - start_line = <%=start_line%>; - break; + code = PRELUDE_CODE(<%=i%><%=%>); + name = PRELUDE_NAME(<%=i%><%=%>); + start_line = <%=start_line%>; + break; % end % end default: - return Qfalse; + return Qfalse; } prelude_eval(code, name, start_line); return Qtrue; diff --git a/thread.c b/thread.c index b9e9323801..87f82d0a0e 100644 --- a/thread.c +++ b/thread.c @@ -165,7 +165,7 @@ static int unblock_function_set(rb_thread_t *th, rb_unblock_function_t *func, vo static void unblock_function_clear(rb_thread_t *th); static inline int blocking_region_begin(rb_thread_t *th, struct rb_blocking_region_buffer *region, - rb_unblock_function_t *ubf, void *arg, int fail_if_interrupted); + rb_unblock_function_t *ubf, void *arg, int fail_if_interrupted); static inline void blocking_region_end(rb_thread_t *th, struct rb_blocking_region_buffer *region); #define THREAD_BLOCKING_BEGIN(th) do { \ @@ -190,10 +190,10 @@ static inline void blocking_region_end(rb_thread_t *th, struct rb_blocking_regio #define BLOCKING_REGION(th, exec, ubf, ubfarg, fail_if_interrupted) do { \ struct rb_blocking_region_buffer __region; \ if (blocking_region_begin(th, &__region, (ubf), (ubfarg), fail_if_interrupted) || \ - /* always return true unless fail_if_interrupted */ \ - !only_if_constant(fail_if_interrupted, TRUE)) { \ - exec; \ - blocking_region_end(th, &__region); \ + /* always return true unless fail_if_interrupted */ \ + !only_if_constant(fail_if_interrupted, TRUE)) { \ + exec; \ + blocking_region_end(th, &__region); \ }; \ } while(0) @@ -208,11 +208,11 @@ vm_check_ints_blocking(rb_execution_context_t *ec) rb_thread_t *th = rb_ec_thread_ptr(ec); if (LIKELY(rb_threadptr_pending_interrupt_empty_p(th))) { - if (LIKELY(!RUBY_VM_INTERRUPTED_ANY(ec))) return FALSE; + if (LIKELY(!RUBY_VM_INTERRUPTED_ANY(ec))) return FALSE; } else { - th->pending_interrupt_queue_checked = 0; - RUBY_VM_SET_INTERRUPT(ec); + th->pending_interrupt_queue_checked = 0; + RUBY_VM_SET_INTERRUPT(ec); } return rb_threadptr_execute_interrupts(th, 1); } @@ -307,14 +307,14 @@ static int unblock_function_set(rb_thread_t *th, rb_unblock_function_t *func, void *arg, int fail_if_interrupted) { do { - if (fail_if_interrupted) { - if (RUBY_VM_INTERRUPTED_ANY(th->ec)) { - return FALSE; - } - } - else { - RUBY_VM_CHECK_INTS(th->ec); - } + if (fail_if_interrupted) { + if (RUBY_VM_INTERRUPTED_ANY(th->ec)) { + return FALSE; + } + } + else { + RUBY_VM_CHECK_INTS(th->ec); + } rb_native_mutex_lock(&th->interrupt_lock); } while (!th->ec->raised_flag && RUBY_VM_INTERRUPTED_ANY(th->ec) && @@ -343,16 +343,16 @@ rb_threadptr_interrupt_common(rb_thread_t *th, int trap) rb_native_mutex_lock(&th->interrupt_lock); if (trap) { - RUBY_VM_SET_TRAP_INTERRUPT(th->ec); + RUBY_VM_SET_TRAP_INTERRUPT(th->ec); } else { - RUBY_VM_SET_INTERRUPT(th->ec); + RUBY_VM_SET_INTERRUPT(th->ec); } if (th->unblock.func != NULL) { - (th->unblock.func)(th->unblock.arg); + (th->unblock.func)(th->unblock.arg); } else { - /* none */ + /* none */ } rb_native_mutex_unlock(&th->interrupt_lock); } @@ -379,13 +379,13 @@ terminate_all(rb_ractor_t *r, const rb_thread_t *main_thread) RUBY_DEBUG_LOG("terminate start th:%u status:%s", rb_th_serial(th), thread_status_name(th, TRUE)); rb_threadptr_pending_interrupt_enque(th, eTerminateSignal); - rb_threadptr_interrupt(th); + rb_threadptr_interrupt(th); RUBY_DEBUG_LOG("terminate done th:%u status:%s", rb_th_serial(th), thread_status_name(th, TRUE)); } - else { + else { RUBY_DEBUG_LOG("main thread th:%u", rb_th_serial(th)); - } + } } } @@ -453,28 +453,28 @@ rb_thread_terminate_all(rb_thread_t *th) terminate_all(cr, th); - while (rb_ractor_living_thread_num(cr) > 1) { + while (rb_ractor_living_thread_num(cr) > 1) { rb_hrtime_t rel = RB_HRTIME_PER_SEC; - /*q - * Thread exiting routine in thread_start_func_2 notify - * me when the last sub-thread exit. - */ - sleeping = 1; - native_sleep(th, &rel); - RUBY_VM_CHECK_INTS_BLOCKING(ec); - sleeping = 0; - } + /*q + * Thread exiting routine in thread_start_func_2 notify + * me when the last sub-thread exit. + */ + sleeping = 1; + native_sleep(th, &rel); + RUBY_VM_CHECK_INTS_BLOCKING(ec); + sleeping = 0; + } } else { - /* - * When caught an exception (e.g. Ctrl+C), let's broadcast - * kill request again to ensure killing all threads even - * if they are blocked on sleep, mutex, etc. - */ - if (sleeping) { - sleeping = 0; - goto retry; - } + /* + * When caught an exception (e.g. Ctrl+C), let's broadcast + * kill request again to ensure killing all threads even + * if they are blocked on sleep, mutex, etc. + */ + if (sleeping) { + sleeping = 0; + goto retry; + } } EC_POP_TAG(); } @@ -511,7 +511,7 @@ thread_cleanup_func(void *th_ptr, int atfork) * which calls free(3), so there is a small memory leak atfork, here. */ if (atfork) - return; + return; rb_native_mutex_destroy(&th->interrupt_lock); native_thread_destroy(th); @@ -532,10 +532,10 @@ rb_vm_proc_local_ep(VALUE proc) const VALUE *ep = vm_proc_ep(proc); if (ep) { - return rb_vm_ep_local_ep(ep); + return rb_vm_ep_local_ep(ep); } else { - return NULL; + return NULL; } } @@ -805,8 +805,8 @@ thread_create_core(VALUE thval, struct thread_create_params *params) int err; if (OBJ_FROZEN(current_th->thgroup)) { - rb_raise(rb_eThreadError, - "can't start a new thread (frozen ThreadGroup)"); + rb_raise(rb_eThreadError, + "can't start a new thread (frozen ThreadGroup)"); } switch (params->type) { @@ -857,7 +857,7 @@ thread_create_core(VALUE thval, struct thread_create_params *params) /* kick thread */ err = native_thread_create(th); if (err) { - th->status = THREAD_KILLED; + th->status = THREAD_KILLED; rb_ractor_living_threads_remove(th->ractor, th); rb_raise(rb_eThreadError, "can't create Thread: %s", strerror(err)); } @@ -899,8 +899,8 @@ thread_s_new(int argc, VALUE *argv, VALUE klass) rb_obj_call_init_kw(thread, argc, argv, RB_PASS_CALLED_KEYWORDS); th = rb_thread_ptr(thread); if (!threadptr_initialized(th)) { - rb_raise(rb_eThreadError, "uninitialized thread - check `%"PRIsVALUE"#initialize'", - klass); + rb_raise(rb_eThreadError, "uninitialized thread - check `%"PRIsVALUE"#initialize'", + klass); } return thread; } @@ -1261,17 +1261,17 @@ sleep_forever(rb_thread_t *th, unsigned int fl) th->status = status; RUBY_VM_CHECK_INTS_BLOCKING(th->ec); while (th->status == status) { - if (fl & SLEEP_DEADLOCKABLE) { + if (fl & SLEEP_DEADLOCKABLE) { rb_ractor_sleeper_threads_inc(th->ractor); - rb_check_deadlock(th->ractor); - } - native_sleep(th, 0); - if (fl & SLEEP_DEADLOCKABLE) { + rb_check_deadlock(th->ractor); + } + native_sleep(th, 0); + if (fl & SLEEP_DEADLOCKABLE) { rb_ractor_sleeper_threads_dec(th->ractor); - } - woke = vm_check_ints_blocking(th->ec); - if (woke && !(fl & SLEEP_SPURIOUS_CHECK)) - break; + } + woke = vm_check_ints_blocking(th->ec); + if (woke && !(fl & SLEEP_SPURIOUS_CHECK)) + break; } th->status = prev_status; } @@ -1316,12 +1316,12 @@ sleep_hrtime(rb_thread_t *th, rb_hrtime_t rel, unsigned int fl) th->status = THREAD_STOPPED; RUBY_VM_CHECK_INTS_BLOCKING(th->ec); while (th->status == THREAD_STOPPED) { - native_sleep(th, &rel); - woke = vm_check_ints_blocking(th->ec); - if (woke && !(fl & SLEEP_SPURIOUS_CHECK)) - break; - if (hrtime_update_expire(&rel, end)) - break; + native_sleep(th, &rel); + woke = vm_check_ints_blocking(th->ec); + if (woke && !(fl & SLEEP_SPURIOUS_CHECK)) + break; + if (hrtime_update_expire(&rel, end)) + break; woke = 1; } th->status = prev_status; @@ -1415,18 +1415,18 @@ static void rb_thread_schedule_limits(uint32_t limits_us) { if (!rb_thread_alone()) { - rb_thread_t *th = GET_THREAD(); + rb_thread_t *th = GET_THREAD(); RUBY_DEBUG_LOG("us:%u", (unsigned int)limits_us); - if (th->running_time_us >= limits_us) { - RUBY_DEBUG_LOG("switch %s", "start"); + if (th->running_time_us >= limits_us) { + RUBY_DEBUG_LOG("switch %s", "start"); RB_GC_SAVE_MACHINE_CONTEXT(th); - thread_sched_yield(TH_SCHED(th), th); + thread_sched_yield(TH_SCHED(th), th); rb_ractor_thread_switch(th->ractor, th); RUBY_DEBUG_LOG("switch %s", "done"); - } + } } } @@ -1441,7 +1441,7 @@ rb_thread_schedule(void) static inline int blocking_region_begin(rb_thread_t *th, struct rb_blocking_region_buffer *region, - rb_unblock_function_t *ubf, void *arg, int fail_if_interrupted) + rb_unblock_function_t *ubf, void *arg, int fail_if_interrupted) { #ifdef RUBY_VM_CRITICAL_SECTION VM_ASSERT(ruby_assert_critical_section_entered == 0); @@ -1450,18 +1450,18 @@ blocking_region_begin(rb_thread_t *th, struct rb_blocking_region_buffer *region, region->prev_status = th->status; if (unblock_function_set(th, ubf, arg, fail_if_interrupted)) { - th->blocking_region_buffer = region; - th->status = THREAD_STOPPED; + th->blocking_region_buffer = region; + th->status = THREAD_STOPPED; rb_ractor_blocking_threads_inc(th->ractor, __FILE__, __LINE__); RUBY_DEBUG_LOG("%s", ""); RB_GC_SAVE_MACHINE_CONTEXT(th); - thread_sched_to_waiting(TH_SCHED(th)); - return TRUE; + thread_sched_to_waiting(TH_SCHED(th)); + return TRUE; } else { - return FALSE; + return FALSE; } } @@ -1479,7 +1479,7 @@ blocking_region_end(rb_thread_t *th, struct rb_blocking_region_buffer *region) th->blocking_region_buffer = 0; rb_ractor_blocking_threads_dec(th->ractor, __FILE__, __LINE__); if (th->status == THREAD_STOPPED) { - th->status = region->prev_status; + th->status = region->prev_status; } RUBY_DEBUG_LOG("%s", ""); @@ -1500,8 +1500,8 @@ rb_nogvl(void *(*func)(void *), void *data1, VALUE ubf_th = Qfalse; if ((ubf == RUBY_UBF_IO) || (ubf == RUBY_UBF_PROCESS)) { - ubf = ubf_select; - data2 = th; + ubf = ubf_select; + data2 = th; } else if (ubf && rb_ractor_living_thread_num(th->ractor) == 1 && is_main_thread) { if (flags & RB_NOGVL_UBF_ASYNC_SAFE) { @@ -1513,14 +1513,14 @@ rb_nogvl(void *(*func)(void *), void *data1, } BLOCKING_REGION(th, { - val = func(data1); - saved_errno = errno; + val = func(data1); + saved_errno = errno; }, ubf, data2, flags & RB_NOGVL_INTR_FAIL); if (is_main_thread) vm->ubf_async_safe = 0; if ((flags & RB_NOGVL_INTR_FAIL) == 0) { - RUBY_VM_CHECK_INTS_BLOCKING(ec); + RUBY_VM_CHECK_INTS_BLOCKING(ec); } if (ubf_th != Qfalse) { @@ -1619,14 +1619,14 @@ rb_nogvl(void *(*func)(void *), void *data1, */ void * rb_thread_call_without_gvl2(void *(*func)(void *), void *data1, - rb_unblock_function_t *ubf, void *data2) + rb_unblock_function_t *ubf, void *data2) { return rb_nogvl(func, data1, ubf, data2, RB_NOGVL_INTR_FAIL); } void * rb_thread_call_without_gvl(void *(*func)(void *data), void *data1, - rb_unblock_function_t *ubf, void *data2) + rb_unblock_function_t *ubf, void *data2) { return rb_nogvl(func, data1, ubf, data2, 0); } @@ -1717,20 +1717,20 @@ rb_thread_call_with_gvl(void *(*func)(void *), void *data1) void *r; if (th == 0) { - /* Error has occurred, but we can't use rb_bug() - * because this thread is not Ruby's thread. + /* Error has occurred, but we can't use rb_bug() + * because this thread is not Ruby's thread. * What should we do? - */ + */ bp(); - fprintf(stderr, "[BUG] rb_thread_call_with_gvl() is called by non-ruby thread\n"); - exit(EXIT_FAILURE); + fprintf(stderr, "[BUG] rb_thread_call_with_gvl() is called by non-ruby thread\n"); + exit(EXIT_FAILURE); } brb = (struct rb_blocking_region_buffer *)th->blocking_region_buffer; prev_unblock = th->unblock; if (brb == 0) { - rb_bug("rb_thread_call_with_gvl: called by a thread which has GVL."); + rb_bug("rb_thread_call_with_gvl: called by a thread which has GVL."); } blocking_region_end(th, brb); @@ -1757,10 +1757,10 @@ ruby_thread_has_gvl_p(void) rb_thread_t *th = ruby_thread_from_native(); if (th && th->blocking_region_buffer == 0) { - return 1; + return 1; } else { - return 0; + return 0; } } @@ -1814,7 +1814,7 @@ static void threadptr_check_pending_interrupt_queue(rb_thread_t *th) { if (!th->pending_interrupt_queue) { - rb_raise(rb_eThreadError, "uninitialized thread"); + rb_raise(rb_eThreadError, "uninitialized thread"); } } @@ -1835,35 +1835,35 @@ rb_threadptr_pending_interrupt_check_mask(rb_thread_t *th, VALUE err) long i; for (i=0; iklass; - } - else if (mod != RCLASS_ORIGIN(mod)) { - continue; - } + if (BUILTIN_TYPE(mod) == T_ICLASS) { + klass = RBASIC(mod)->klass; + } + else if (mod != RCLASS_ORIGIN(mod)) { + continue; + } - if ((sym = rb_hash_aref(mask, klass)) != Qnil) { - if (sym == sym_immediate) { - return INTERRUPT_IMMEDIATE; - } - else if (sym == sym_on_blocking) { - return INTERRUPT_ON_BLOCKING; - } - else if (sym == sym_never) { - return INTERRUPT_NEVER; - } - else { - rb_raise(rb_eThreadError, "unknown mask signature"); - } - } - } - /* try to next mask */ + if ((sym = rb_hash_aref(mask, klass)) != Qnil) { + if (sym == sym_immediate) { + return INTERRUPT_IMMEDIATE; + } + else if (sym == sym_on_blocking) { + return INTERRUPT_ON_BLOCKING; + } + else if (sym == sym_never) { + return INTERRUPT_NEVER; + } + else { + rb_raise(rb_eThreadError, "unknown mask signature"); + } + } + } + /* try to next mask */ } return INTERRUPT_NONE; } @@ -1879,10 +1879,10 @@ rb_threadptr_pending_interrupt_include_p(rb_thread_t *th, VALUE err) { int i; for (i=0; ipending_interrupt_queue); i++) { - VALUE e = RARRAY_AREF(th->pending_interrupt_queue, i); - if (rb_class_inherited_p(e, err)) { - return TRUE; - } + VALUE e = RARRAY_AREF(th->pending_interrupt_queue, i); + if (rb_class_inherited_p(e, err)) { + return TRUE; + } } return FALSE; } @@ -1894,23 +1894,23 @@ rb_threadptr_pending_interrupt_deque(rb_thread_t *th, enum handle_interrupt_timi int i; for (i=0; ipending_interrupt_queue); i++) { - VALUE err = RARRAY_AREF(th->pending_interrupt_queue, i); + VALUE err = RARRAY_AREF(th->pending_interrupt_queue, i); - enum handle_interrupt_timing mask_timing = rb_threadptr_pending_interrupt_check_mask(th, CLASS_OF(err)); + enum handle_interrupt_timing mask_timing = rb_threadptr_pending_interrupt_check_mask(th, CLASS_OF(err)); - switch (mask_timing) { - case INTERRUPT_ON_BLOCKING: - if (timing != INTERRUPT_ON_BLOCKING) { - break; - } - /* fall through */ - case INTERRUPT_NONE: /* default: IMMEDIATE */ - case INTERRUPT_IMMEDIATE: - rb_ary_delete_at(th->pending_interrupt_queue, i); - return err; - case INTERRUPT_NEVER: - break; - } + switch (mask_timing) { + case INTERRUPT_ON_BLOCKING: + if (timing != INTERRUPT_ON_BLOCKING) { + break; + } + /* fall through */ + case INTERRUPT_NONE: /* default: IMMEDIATE */ + case INTERRUPT_IMMEDIATE: + rb_ary_delete_at(th->pending_interrupt_queue, i); + return err; + case INTERRUPT_NEVER: + break; + } } th->pending_interrupt_queue_checked = 1; @@ -1918,7 +1918,7 @@ rb_threadptr_pending_interrupt_deque(rb_thread_t *th, enum handle_interrupt_timi #else VALUE err = rb_ary_shift(th->pending_interrupt_queue); if (rb_threadptr_pending_interrupt_empty_p(th)) { - th->pending_interrupt_queue_checked = 1; + th->pending_interrupt_queue_checked = 1; } return err; #endif @@ -1933,11 +1933,11 @@ threadptr_pending_interrupt_active_p(rb_thread_t *th) * since last check. */ if (th->pending_interrupt_queue_checked) { - return 0; + return 0; } if (rb_threadptr_pending_interrupt_empty_p(th)) { - return 0; + return 0; } return 1; @@ -1949,11 +1949,11 @@ handle_interrupt_arg_check_i(VALUE key, VALUE val, VALUE args) VALUE *maskp = (VALUE *)args; if (val != sym_immediate && val != sym_on_blocking && val != sym_never) { - rb_raise(rb_eArgError, "unknown mask signature"); + rb_raise(rb_eArgError, "unknown mask signature"); } if (!*maskp) { - *maskp = rb_ident_hash_new(); + *maskp = rb_ident_hash_new(); } rb_hash_aset(*maskp, key, val); @@ -2078,38 +2078,38 @@ rb_thread_s_handle_interrupt(VALUE self, VALUE mask_arg) enum ruby_tag_type state; if (!rb_block_given_p()) { - rb_raise(rb_eArgError, "block is needed."); + rb_raise(rb_eArgError, "block is needed."); } mask = 0; mask_arg = rb_to_hash_type(mask_arg); rb_hash_foreach(mask_arg, handle_interrupt_arg_check_i, (VALUE)&mask); if (!mask) { - return rb_yield(Qnil); + return rb_yield(Qnil); } OBJ_FREEZE_RAW(mask); rb_ary_push(th->pending_interrupt_mask_stack, mask); if (!rb_threadptr_pending_interrupt_empty_p(th)) { - th->pending_interrupt_queue_checked = 0; - RUBY_VM_SET_INTERRUPT(th->ec); + th->pending_interrupt_queue_checked = 0; + RUBY_VM_SET_INTERRUPT(th->ec); } EC_PUSH_TAG(th->ec); if ((state = EC_EXEC_TAG()) == TAG_NONE) { - r = rb_yield(Qnil); + r = rb_yield(Qnil); } EC_POP_TAG(); rb_ary_pop(th->pending_interrupt_mask_stack); if (!rb_threadptr_pending_interrupt_empty_p(th)) { - th->pending_interrupt_queue_checked = 0; - RUBY_VM_SET_INTERRUPT(th->ec); + th->pending_interrupt_queue_checked = 0; + RUBY_VM_SET_INTERRUPT(th->ec); } RUBY_VM_CHECK_INTS(th->ec); if (state) { - EC_JUMP_TAG(th->ec, state); + EC_JUMP_TAG(th->ec, state); } return r; @@ -2131,10 +2131,10 @@ rb_thread_pending_interrupt_p(int argc, VALUE *argv, VALUE target_thread) rb_thread_t *target_th = rb_thread_ptr(target_thread); if (!target_th->pending_interrupt_queue) { - return Qfalse; + return Qfalse; } if (rb_threadptr_pending_interrupt_empty_p(target_th)) { - return Qfalse; + return Qfalse; } if (rb_check_arity(argc, 0, 1)) { VALUE err = argv[0]; @@ -2144,7 +2144,7 @@ rb_thread_pending_interrupt_p(int argc, VALUE *argv, VALUE target_thread) return RBOOL(rb_threadptr_pending_interrupt_include_p(target_th, err)); } else { - return Qtrue; + return Qtrue; } } @@ -2231,8 +2231,8 @@ threadptr_get_interrupts(rb_thread_t *th) rb_atomic_t old; do { - interrupt = ec->interrupt_flag; - old = ATOMIC_CAS(ec->interrupt_flag, interrupt, interrupt & ec->interrupt_mask); + interrupt = ec->interrupt_flag; + old = ATOMIC_CAS(ec->interrupt_flag, interrupt, interrupt & ec->interrupt_mask); } while (old != interrupt); return interrupt & (rb_atomic_t)~ec->interrupt_mask; } @@ -2253,16 +2253,16 @@ rb_threadptr_execute_interrupts(rb_thread_t *th, int blocking_timing) if (th->ec->raised_flag) return ret; while ((interrupt = threadptr_get_interrupts(th)) != 0) { - int sig; - int timer_interrupt; - int pending_interrupt; - int trap_interrupt; + int sig; + int timer_interrupt; + int pending_interrupt; + int trap_interrupt; int terminate_interrupt; - timer_interrupt = interrupt & TIMER_INTERRUPT_MASK; - pending_interrupt = interrupt & PENDING_INTERRUPT_MASK; - postponed_job_interrupt = interrupt & POSTPONED_JOB_INTERRUPT_MASK; - trap_interrupt = interrupt & TRAP_INTERRUPT_MASK; + timer_interrupt = interrupt & TIMER_INTERRUPT_MASK; + pending_interrupt = interrupt & PENDING_INTERRUPT_MASK; + postponed_job_interrupt = interrupt & POSTPONED_JOB_INTERRUPT_MASK; + trap_interrupt = interrupt & TRAP_INTERRUPT_MASK; terminate_interrupt = interrupt & TERMINATE_INTERRUPT_MASK; // request from other ractors if (interrupt & VM_BARRIER_INTERRUPT_MASK) { @@ -2270,26 +2270,26 @@ rb_threadptr_execute_interrupts(rb_thread_t *th, int blocking_timing) RB_VM_LOCK_LEAVE(); } - if (postponed_job_interrupt) { - rb_postponed_job_flush(th->vm); - } + if (postponed_job_interrupt) { + rb_postponed_job_flush(th->vm); + } - /* signal handling */ - if (trap_interrupt && (th == th->vm->ractor.main_thread)) { - enum rb_thread_status prev_status = th->status; - int sigwait_fd = rb_sigwait_fd_get(th); + /* signal handling */ + if (trap_interrupt && (th == th->vm->ractor.main_thread)) { + enum rb_thread_status prev_status = th->status; + int sigwait_fd = rb_sigwait_fd_get(th); - if (sigwait_fd >= 0) { - (void)consume_communication_pipe(sigwait_fd); - ruby_sigchld_handler(th->vm); - rb_sigwait_fd_put(th, sigwait_fd); - rb_sigwait_fd_migrate(th->vm); - } - th->status = THREAD_RUNNABLE; - while ((sig = rb_get_next_signal()) != 0) { - ret |= rb_signal_exec(th, sig); - } - th->status = prev_status; + if (sigwait_fd >= 0) { + (void)consume_communication_pipe(sigwait_fd); + ruby_sigchld_handler(th->vm); + rb_sigwait_fd_put(th, sigwait_fd); + rb_sigwait_fd_migrate(th->vm); + } + th->status = THREAD_RUNNABLE; + while ((sig = rb_get_next_signal()) != 0) { + ret |= rb_signal_exec(th, sig); + } + th->status = prev_status; #if USE_MJIT // Handle waitpid_signal for MJIT issued by ruby_sigchld_handler. This needs to be done @@ -2299,56 +2299,56 @@ rb_threadptr_execute_interrupts(rb_thread_t *th, int blocking_timing) mjit_notify_waitpid(mjit_waitpid_status); } #endif - } + } - /* exception from another thread */ - if (pending_interrupt && threadptr_pending_interrupt_active_p(th)) { - VALUE err = rb_threadptr_pending_interrupt_deque(th, blocking_timing ? INTERRUPT_ON_BLOCKING : INTERRUPT_NONE); + /* exception from another thread */ + if (pending_interrupt && threadptr_pending_interrupt_active_p(th)) { + VALUE err = rb_threadptr_pending_interrupt_deque(th, blocking_timing ? INTERRUPT_ON_BLOCKING : INTERRUPT_NONE); RUBY_DEBUG_LOG("err:%"PRIdVALUE"\n", err); ret = TRUE; - if (err == Qundef) { - /* no error */ - } - else if (err == eKillSignal /* Thread#kill received */ || - err == eTerminateSignal /* Terminate thread */ || - err == INT2FIX(TAG_FATAL) /* Thread.exit etc. */ ) { + if (err == Qundef) { + /* no error */ + } + else if (err == eKillSignal /* Thread#kill received */ || + err == eTerminateSignal /* Terminate thread */ || + err == INT2FIX(TAG_FATAL) /* Thread.exit etc. */ ) { terminate_interrupt = 1; - } - else { - if (err == th->vm->special_exceptions[ruby_error_stream_closed]) { - /* the only special exception to be queued across thread */ - err = ruby_vm_special_exception_copy(err); - } - /* set runnable if th was slept. */ - if (th->status == THREAD_STOPPED || - th->status == THREAD_STOPPED_FOREVER) - th->status = THREAD_RUNNABLE; - rb_exc_raise(err); - } - } + } + else { + if (err == th->vm->special_exceptions[ruby_error_stream_closed]) { + /* the only special exception to be queued across thread */ + err = ruby_vm_special_exception_copy(err); + } + /* set runnable if th was slept. */ + if (th->status == THREAD_STOPPED || + th->status == THREAD_STOPPED_FOREVER) + th->status = THREAD_RUNNABLE; + rb_exc_raise(err); + } + } if (terminate_interrupt) { rb_threadptr_to_kill(th); } if (timer_interrupt) { - uint32_t limits_us = TIME_QUANTUM_USEC; + uint32_t limits_us = TIME_QUANTUM_USEC; - if (th->priority > 0) - limits_us <<= th->priority; - else - limits_us >>= -th->priority; + if (th->priority > 0) + limits_us <<= th->priority; + else + limits_us >>= -th->priority; - if (th->status == THREAD_RUNNABLE) - th->running_time_us += TIME_QUANTUM_USEC; + if (th->status == THREAD_RUNNABLE) + th->running_time_us += TIME_QUANTUM_USEC; VM_ASSERT(th->ec->cfp); - EXEC_EVENT_HOOK(th->ec, RUBY_INTERNAL_EVENT_SWITCH, th->ec->cfp->self, - 0, 0, 0, Qundef); + EXEC_EVENT_HOOK(th->ec, RUBY_INTERNAL_EVENT_SWITCH, th->ec->cfp->self, + 0, 0, 0, Qundef); - rb_thread_schedule_limits(limits_us); - } + rb_thread_schedule_limits(limits_us); + } } return ret; } @@ -2371,20 +2371,20 @@ rb_threadptr_raise(rb_thread_t *target_th, int argc, VALUE *argv) VALUE exc; if (rb_threadptr_dead(target_th)) { - return Qnil; + return Qnil; } if (argc == 0) { - exc = rb_exc_new(rb_eRuntimeError, 0, 0); + exc = rb_exc_new(rb_eRuntimeError, 0, 0); } else { - exc = rb_make_exception(argc, argv); + exc = rb_make_exception(argc, argv); } /* making an exception object can switch thread, so we need to check thread deadness again */ if (rb_threadptr_dead(target_th)) { - return Qnil; + return Qnil; } rb_ec_setup_exception(GET_EC(), exc, Qundef); @@ -2419,7 +2419,7 @@ int rb_ec_set_raised(rb_execution_context_t *ec) { if (ec->raised_flag & RAISED_EXCEPTION) { - return 1; + return 1; } ec->raised_flag |= RAISED_EXCEPTION; return 0; @@ -2429,7 +2429,7 @@ int rb_ec_reset_raised(rb_execution_context_t *ec) { if (!(ec->raised_flag & RAISED_EXCEPTION)) { - return 0; + return 0; } ec->raised_flag &= ~RAISED_EXCEPTION; return 1; @@ -2469,7 +2469,7 @@ rb_thread_fd_close(int fd) ccan_list_head_init(&busy); if (rb_notify_fd_close(fd, &busy)) { - do rb_thread_schedule(); while (!ccan_list_empty(&busy)); + do rb_thread_schedule(); while (!ccan_list_empty(&busy)); } } @@ -2505,7 +2505,7 @@ thread_raise_m(int argc, VALUE *argv, VALUE self) /* To perform Thread.current.raise as Kernel.raise */ if (current_th == target_th) { - RUBY_VM_CHECK_INTS(target_th->ec); + RUBY_VM_CHECK_INTS(target_th->ec); } return Qnil; } @@ -2528,22 +2528,22 @@ rb_thread_kill(VALUE thread) rb_thread_t *target_th = rb_thread_ptr(thread); if (target_th->to_kill || target_th->status == THREAD_KILLED) { - return thread; + return thread; } if (target_th == target_th->vm->ractor.main_thread) { - rb_exit(EXIT_SUCCESS); + rb_exit(EXIT_SUCCESS); } RUBY_DEBUG_LOG("target_th:%u", rb_th_serial(target_th)); if (target_th == GET_THREAD()) { - /* kill myself immediately */ - rb_threadptr_to_kill(target_th); + /* kill myself immediately */ + rb_threadptr_to_kill(target_th); } else { - threadptr_check_pending_interrupt_queue(target_th); - rb_threadptr_pending_interrupt_enque(target_th, eKillSignal); - rb_threadptr_interrupt(target_th); + threadptr_check_pending_interrupt_queue(target_th); + rb_threadptr_pending_interrupt_enque(target_th, eKillSignal); + rb_threadptr_interrupt(target_th); } return thread; @@ -2555,7 +2555,7 @@ rb_thread_to_be_killed(VALUE thread) rb_thread_t *target_th = rb_thread_ptr(thread); if (target_th->to_kill || target_th->status == THREAD_KILLED) { - return TRUE; + return TRUE; } return FALSE; } @@ -2621,7 +2621,7 @@ VALUE rb_thread_wakeup(VALUE thread) { if (!RTEST(rb_thread_wakeup_alive(thread))) { - rb_raise(rb_eThreadError, "killed thread"); + rb_raise(rb_eThreadError, "killed thread"); } return thread; } @@ -2635,8 +2635,8 @@ rb_thread_wakeup_alive(VALUE thread) rb_threadptr_ready(target_th); if (target_th->status == THREAD_STOPPED || - target_th->status == THREAD_STOPPED_FOREVER) { - target_th->status = THREAD_RUNNABLE; + target_th->status == THREAD_STOPPED_FOREVER) { + target_th->status = THREAD_RUNNABLE; } return thread; @@ -3086,15 +3086,15 @@ thread_status_name(rb_thread_t *th, int detail) { switch (th->status) { case THREAD_RUNNABLE: - return th->to_kill ? "aborting" : "run"; + return th->to_kill ? "aborting" : "run"; case THREAD_STOPPED_FOREVER: - if (detail) return "sleep_forever"; + if (detail) return "sleep_forever"; case THREAD_STOPPED: - return "sleep"; + return "sleep"; case THREAD_KILLED: - return "dead"; + return "dead"; default: - return "unknown"; + return "unknown"; } } @@ -3142,16 +3142,16 @@ rb_thread_status(VALUE thread) rb_thread_t *target_th = rb_thread_ptr(thread); if (rb_threadptr_dead(target_th)) { - if (!NIL_P(target_th->ec->errinfo) && - !FIXNUM_P(target_th->ec->errinfo)) { - return Qnil; - } - else { - return Qfalse; - } + if (!NIL_P(target_th->ec->errinfo) && + !FIXNUM_P(target_th->ec->errinfo)) { + return Qnil; + } + else { + return Qfalse; + } } else { - return rb_str_new2(thread_status_name(target_th, FALSE)); + return rb_str_new2(thread_status_name(target_th, FALSE)); } } @@ -3196,7 +3196,7 @@ rb_thread_stop_p(VALUE thread) rb_thread_t *th = rb_thread_ptr(thread); if (rb_threadptr_dead(th)) { - return Qtrue; + return Qtrue; } return RBOOL(th->status == THREAD_STOPPED || th->status == THREAD_STOPPED_FOREVER); } @@ -3228,18 +3228,18 @@ rb_thread_setname(VALUE thread, VALUE name) rb_thread_t *target_th = rb_thread_ptr(thread); if (!NIL_P(name)) { - rb_encoding *enc; - StringValueCStr(name); - enc = rb_enc_get(name); - if (!rb_enc_asciicompat(enc)) { - rb_raise(rb_eArgError, "ASCII incompatible encoding (%s)", - rb_enc_name(enc)); - } - name = rb_str_new_frozen(name); + rb_encoding *enc; + StringValueCStr(name); + enc = rb_enc_get(name); + if (!rb_enc_asciicompat(enc)) { + rb_raise(rb_eArgError, "ASCII incompatible encoding (%s)", + rb_enc_name(enc)); + } + name = rb_str_new_frozen(name); } target_th->name = name; if (threadptr_initialized(target_th)) { - native_set_another_thread_name(target_th->nt->thread_id, name); + native_set_another_thread_name(target_th->nt->thread_id, name); } return name; } @@ -3314,18 +3314,18 @@ static VALUE threadptr_local_aref(rb_thread_t *th, ID id) { if (id == recursive_key) { - return th->ec->local_storage_recursive_hash; + return th->ec->local_storage_recursive_hash; } else { - VALUE val; - struct rb_id_table *local_storage = th->ec->local_storage; + VALUE val; + struct rb_id_table *local_storage = th->ec->local_storage; - if (local_storage != NULL && rb_id_table_lookup(local_storage, id, &val)) { - return val; - } - else { - return Qnil; - } + if (local_storage != NULL && rb_id_table_lookup(local_storage, id, &val)) { + return val; + } + else { + return Qnil; + } } } @@ -3429,26 +3429,26 @@ rb_thread_fetch(int argc, VALUE *argv, VALUE self) block_given = rb_block_given_p(); if (block_given && argc == 2) { - rb_warn("block supersedes default value argument"); + rb_warn("block supersedes default value argument"); } id = rb_check_id(&key); if (id == recursive_key) { - return target_th->ec->local_storage_recursive_hash; + return target_th->ec->local_storage_recursive_hash; } else if (id && target_th->ec->local_storage && - rb_id_table_lookup(target_th->ec->local_storage, id, &val)) { - return val; + rb_id_table_lookup(target_th->ec->local_storage, id, &val)) { + return val; } else if (block_given) { - return rb_yield(key); + return rb_yield(key); } else if (argc == 1) { - rb_key_err_raise(rb_sprintf("key not found: %+"PRIsVALUE, key), self, key); + rb_key_err_raise(rb_sprintf("key not found: %+"PRIsVALUE, key), self, key); } else { - return argv[1]; + return argv[1]; } } @@ -3456,24 +3456,24 @@ static VALUE threadptr_local_aset(rb_thread_t *th, ID id, VALUE val) { if (id == recursive_key) { - th->ec->local_storage_recursive_hash = val; - return val; + th->ec->local_storage_recursive_hash = val; + return val; } else { - struct rb_id_table *local_storage = th->ec->local_storage; + struct rb_id_table *local_storage = th->ec->local_storage; - if (NIL_P(val)) { - if (!local_storage) return Qnil; - rb_id_table_delete(local_storage, id); - return Qnil; - } - else { - if (local_storage == NULL) { - th->ec->local_storage = local_storage = rb_id_table_create(0); - } - rb_id_table_insert(local_storage, id, val); - return val; - } + if (NIL_P(val)) { + if (!local_storage) return Qnil; + rb_id_table_delete(local_storage, id); + return Qnil; + } + else { + if (local_storage == NULL) { + th->ec->local_storage = local_storage = rb_id_table_create(0); + } + rb_id_table_insert(local_storage, id, val); + return val; + } } } @@ -3589,7 +3589,7 @@ rb_thread_key_p(VALUE self, VALUE key) struct rb_id_table *local_storage = rb_thread_ptr(self)->ec->local_storage; if (!id || local_storage == NULL) { - return Qfalse; + return Qfalse; } return RBOOL(rb_id_table_lookup(local_storage, id, &val)); } @@ -3629,7 +3629,7 @@ rb_thread_keys(VALUE self) VALUE ary = rb_ary_new(); if (local_storage) { - rb_id_table_foreach(local_storage, thread_keys_i, (void *)ary); + rb_id_table_foreach(local_storage, thread_keys_i, (void *)ary); } return ary; } @@ -3763,10 +3763,10 @@ rb_thread_priority_set(VALUE thread, VALUE prio) #else priority = NUM2INT(prio); if (priority > RUBY_THREAD_PRIORITY_MAX) { - priority = RUBY_THREAD_PRIORITY_MAX; + priority = RUBY_THREAD_PRIORITY_MAX; } else if (priority < RUBY_THREAD_PRIORITY_MIN) { - priority = RUBY_THREAD_PRIORITY_MIN; + priority = RUBY_THREAD_PRIORITY_MIN; } target_th->priority = (int8_t)priority; #endif @@ -3820,7 +3820,7 @@ rb_fd_init_copy(rb_fdset_t *dst, rb_fdset_t *src) size_t size = howmany(rb_fd_max(src), NFDBITS) * sizeof(fd_mask); if (size < sizeof(fd_set)) - size = sizeof(fd_set); + size = sizeof(fd_set); dst->maxfd = src->maxfd; dst->fdset = xmalloc(size); memcpy(dst->fdset, src->fdset, size); @@ -3838,7 +3838,7 @@ void rb_fd_zero(rb_fdset_t *fds) { if (fds->fdset) - MEMZERO(fds->fdset, fd_mask, howmany(fds->maxfd, NFDBITS)); + MEMZERO(fds->fdset, fd_mask, howmany(fds->maxfd, NFDBITS)); } static void @@ -3851,8 +3851,8 @@ rb_fd_resize(int n, rb_fdset_t *fds) if (o < sizeof(fd_set)) o = sizeof(fd_set); if (m > o) { - fds->fdset = xrealloc(fds->fdset, m); - memset((char *)fds->fdset + o, 0, m - o); + fds->fdset = xrealloc(fds->fdset, m); + memset((char *)fds->fdset + o, 0, m - o); } if (n >= fds->maxfd) fds->maxfd = n + 1; } @@ -3895,7 +3895,7 @@ rb_fd_dup(rb_fdset_t *dst, const rb_fdset_t *src) size_t size = howmany(rb_fd_max(src), NFDBITS) * sizeof(fd_mask); if (size < sizeof(fd_set)) - size = sizeof(fd_set); + size = sizeof(fd_set); dst->maxfd = src->maxfd; dst->fdset = xrealloc(dst->fdset, size); memcpy(dst->fdset, src->fdset, size); @@ -3969,7 +3969,7 @@ rb_fd_set(int fd, rb_fdset_t *set) } } if (set->fdset->fd_count >= (unsigned)set->capa) { - set->capa = (set->fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE; + set->capa = (set->fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE; set->fdset = rb_xrealloc_mul_add( set->fdset, set->capa, sizeof(SOCKET), sizeof(unsigned int)); @@ -4013,7 +4013,7 @@ wait_retryable(int *result, int errnum, rb_hrtime_t *rel, rb_hrtime_t end) return FALSE; } else if (*result == 0) { - /* check for spurious wakeup */ + /* check for spurious wakeup */ if (rel) { return !hrtime_update_expire(rel, end); } @@ -4088,10 +4088,10 @@ do_select(VALUE p) TRUE) do { - int drained; - lerrno = 0; + int drained; + lerrno = 0; - BLOCKING_REGION(set->th, { + BLOCKING_REGION(set->th, { const rb_hrtime_t *sto; struct timeval tv; @@ -4102,7 +4102,7 @@ do_select(VALUE p) rb_hrtime2timeval(&tv, sto), set->th); if (result < 0) lerrno = errno; } - }, set->sigwait_fd >= 0 ? ubf_sigwait : ubf_select, set->th, TRUE); + }, set->sigwait_fd >= 0 ? ubf_sigwait : ubf_select, set->th, TRUE); if (set->sigwait_fd >= 0) { int fd = sigwait_signals_fd(result, @@ -4115,7 +4115,7 @@ do_select(VALUE p) } while (wait_retryable(&result, lerrno, to, end) && do_select_update()); if (result < 0) { - errno = lerrno; + errno = lerrno; } return (VALUE)result; @@ -4125,7 +4125,7 @@ static rb_fdset_t * init_set_fd(int fd, rb_fdset_t *fds) { if (fd < 0) { - return 0; + return 0; } rb_fd_init(fds); rb_fd_set(fd, fds); @@ -4135,7 +4135,7 @@ init_set_fd(int fd, rb_fdset_t *fds) int rb_thread_fd_select(int max, rb_fdset_t * read, rb_fdset_t * write, rb_fdset_t * except, - struct timeval *timeout) + struct timeval *timeout) { struct select_set set; @@ -4276,13 +4276,13 @@ rb_thread_wait_for_single_fd(int fd, int events, struct timeval *timeout) } if (result < 0) { - errno = lerrno; - return -1; + errno = lerrno; + return -1; } if (fds[0].revents & POLLNVAL) { - errno = EBADF; - return -1; + errno = EBADF; + return -1; } /* @@ -4291,23 +4291,23 @@ rb_thread_wait_for_single_fd(int fd, int events, struct timeval *timeout) */ result = 0; if (fds[0].revents & POLLIN_SET) - result |= RB_WAITFD_IN; + result |= RB_WAITFD_IN; if (fds[0].revents & POLLOUT_SET) - result |= RB_WAITFD_OUT; + result |= RB_WAITFD_OUT; if (fds[0].revents & POLLEX_SET) - result |= RB_WAITFD_PRI; + result |= RB_WAITFD_PRI; /* all requested events are ready if there is an error */ if (fds[0].revents & POLLERR_SET) - result |= events; + result |= events; return result; } #else /* ! USE_POLL - implement rb_io_poll_fd() using select() */ struct select_args { union { - int fd; - int error; + int fd; + int error; } as; rb_fdset_t *read; rb_fdset_t *write; @@ -4325,15 +4325,15 @@ select_single(VALUE ptr) r = rb_thread_fd_select(args->as.fd + 1, args->read, args->write, args->except, args->tv); if (r == -1) - args->as.error = errno; + args->as.error = errno; if (r > 0) { - r = 0; - if (args->read && rb_fd_isset(args->as.fd, args->read)) - r |= RB_WAITFD_IN; - if (args->write && rb_fd_isset(args->as.fd, args->write)) - r |= RB_WAITFD_OUT; - if (args->except && rb_fd_isset(args->as.fd, args->except)) - r |= RB_WAITFD_PRI; + r = 0; + if (args->read && rb_fd_isset(args->as.fd, args->read)) + r |= RB_WAITFD_IN; + if (args->write && rb_fd_isset(args->as.fd, args->write)) + r |= RB_WAITFD_OUT; + if (args->except && rb_fd_isset(args->as.fd, args->except)) + r |= RB_WAITFD_PRI; } return (VALUE)r; } @@ -4379,7 +4379,7 @@ rb_thread_wait_for_single_fd(int fd, int events, struct timeval *timeout) r = (int)rb_ensure(select_single, ptr, select_single_cleanup, ptr); if (r == -1) - errno = args.as.error; + errno = args.as.error; return r; } @@ -4407,8 +4407,8 @@ rb_threadptr_check_signal(rb_thread_t *mth) { /* mth must be main_thread */ if (rb_signal_buff_size() > 0) { - /* wakeup main thread */ - threadptr_trap_interrupt(mth); + /* wakeup main thread */ + threadptr_trap_interrupt(mth); } } @@ -4418,7 +4418,7 @@ async_bug_fd(const char *mesg, int errno_arg, int fd) char buff[64]; size_t n = strlcpy(buff, mesg, sizeof(buff)); if (n < sizeof(buff)-3) { - ruby_snprintf(buff+n, sizeof(buff)-n, "(%d)", fd); + ruby_snprintf(buff+n, sizeof(buff)-n, "(%d)", fd); } rb_async_bug_errno(buff, errno_arg); } @@ -4445,30 +4445,30 @@ consume_communication_pipe(int fd) ubf_timer_disarm(); while (1) { - result = read(fd, buff, sizeof(buff)); - if (result > 0) { - ret = TRUE; - if (USE_EVENTFD || result < (ssize_t)sizeof(buff)) { - return ret; - } - } - else if (result == 0) { - return ret; - } - else if (result < 0) { - int e = errno; - switch (e) { - case EINTR: - continue; /* retry */ - case EAGAIN: + result = read(fd, buff, sizeof(buff)); + if (result > 0) { + ret = TRUE; + if (USE_EVENTFD || result < (ssize_t)sizeof(buff)) { + return ret; + } + } + else if (result == 0) { + return ret; + } + else if (result < 0) { + int e = errno; + switch (e) { + case EINTR: + continue; /* retry */ + case EAGAIN: #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN - case EWOULDBLOCK: + case EWOULDBLOCK: #endif - return ret; - default: - async_bug_fd("consume_communication_pipe: read", e, fd); - } - } + return ret; + default: + async_bug_fd("consume_communication_pipe: read", e, fd); + } + } } } @@ -4496,7 +4496,7 @@ void rb_thread_stop_timer_thread(void) { if (TIMER_THREAD_CREATED_P() && native_stop_timer_thread()) { - native_reset_timer_thread(); + native_reset_timer_thread(); } } @@ -4534,10 +4534,10 @@ clear_coverage_i(st_data_t key, st_data_t val, st_data_t dummy) } } if (branches) { - VALUE counters = RARRAY_AREF(branches, 1); - for (i = 0; i < RARRAY_LEN(counters); i++) { - RARRAY_ASET(counters, i, INT2FIX(0)); - } + VALUE counters = RARRAY_AREF(branches, 1); + for (i = 0; i < RARRAY_LEN(counters); i++) { + RARRAY_ASET(counters, i, INT2FIX(0)); + } } return ST_CONTINUE; @@ -4597,9 +4597,9 @@ static void terminate_atfork_i(rb_thread_t *th, const rb_thread_t *current_th) { if (th != current_th) { - rb_mutex_abandon_keeping_mutexes(th); - rb_mutex_abandon_locking_mutex(th); - thread_cleanup_func(th, TRUE); + rb_mutex_abandon_keeping_mutexes(th); + rb_mutex_abandon_locking_mutex(th); + thread_cleanup_func(th, TRUE); } } @@ -4623,7 +4623,7 @@ static void terminate_atfork_before_exec_i(rb_thread_t *th, const rb_thread_t *current_th) { if (th != current_th) { - thread_cleanup_func_before_exec(th); + thread_cleanup_func_before_exec(th); } } @@ -4712,8 +4712,8 @@ thgroup_list(VALUE group) ccan_list_for_each(&r->threads.set, th, lt_node) { if (th->thgroup == group) { - rb_ary_push(ary, th->self); - } + rb_ary_push(ary, th->self); + } } return ary; } @@ -4797,20 +4797,20 @@ thgroup_add(VALUE group, VALUE thread) struct thgroup *data; if (OBJ_FROZEN(group)) { - rb_raise(rb_eThreadError, "can't move to the frozen thread group"); + rb_raise(rb_eThreadError, "can't move to the frozen thread group"); } TypedData_Get_Struct(group, struct thgroup, &thgroup_data_type, data); if (data->enclosed) { - rb_raise(rb_eThreadError, "can't move to the enclosed thread group"); + rb_raise(rb_eThreadError, "can't move to the enclosed thread group"); } if (OBJ_FROZEN(target_th->thgroup)) { - rb_raise(rb_eThreadError, "can't move from the frozen thread group"); + rb_raise(rb_eThreadError, "can't move from the frozen thread group"); } TypedData_Get_Struct(target_th->thgroup, struct thgroup, &thgroup_data_type, data); if (data->enclosed) { - rb_raise(rb_eThreadError, - "can't move from the enclosed thread group"); + rb_raise(rb_eThreadError, + "can't move from the enclosed thread group"); } target_th->thgroup = group; @@ -4855,7 +4855,7 @@ rb_thread_shield_waiting_inc(VALUE b) unsigned int w = rb_thread_shield_waiting(b); w++; if (w > THREAD_SHIELD_WAITING_MAX) - rb_raise(rb_eRuntimeError, "waiting count overflow"); + rb_raise(rb_eRuntimeError, "waiting count overflow"); RBASIC(b)->flags &= ~THREAD_SHIELD_WAITING_MASK; RBASIC(b)->flags |= ((VALUE)w << THREAD_SHIELD_WAITING_SHIFT); } @@ -4908,7 +4908,7 @@ thread_shield_get_mutex(VALUE self) { VALUE mutex = GetThreadShieldPtr(self); if (!mutex) - rb_raise(rb_eThreadError, "destroyed thread shield - %p", (void *)self); + rb_raise(rb_eThreadError, "destroyed thread shield - %p", (void *)self); return mutex; } @@ -4962,16 +4962,16 @@ recursive_list_access(VALUE sym) VALUE hash = threadptr_recursive_hash(th); VALUE list; if (NIL_P(hash) || !RB_TYPE_P(hash, T_HASH)) { - hash = rb_ident_hash_new(); - threadptr_recursive_hash_set(th, hash); - list = Qnil; + hash = rb_ident_hash_new(); + threadptr_recursive_hash_set(th, hash); + list = Qnil; } else { - list = rb_hash_aref(hash, sym); + list = rb_hash_aref(hash, sym); } if (NIL_P(list) || !RB_TYPE_P(list, T_HASH)) { - list = rb_ident_hash_new(); - rb_hash_aset(hash, sym, list); + list = rb_ident_hash_new(); + rb_hash_aset(hash, sym, list); } return list; } @@ -4994,16 +4994,16 @@ recursive_check(VALUE list, VALUE obj, VALUE paired_obj_id) VALUE pair_list = rb_hash_lookup2(list, obj, Qundef); if (pair_list == Qundef) - return Qfalse; + return Qfalse; if (paired_obj_id) { - if (!RB_TYPE_P(pair_list, T_HASH)) { - if (!OBJ_ID_EQL(paired_obj_id, pair_list)) - return Qfalse; - } - else { - if (NIL_P(rb_hash_lookup(pair_list, paired_obj_id))) - return Qfalse; - } + if (!RB_TYPE_P(pair_list, T_HASH)) { + if (!OBJ_ID_EQL(paired_obj_id, pair_list)) + return Qfalse; + } + else { + if (NIL_P(rb_hash_lookup(pair_list, paired_obj_id))) + return Qfalse; + } } return Qtrue; } @@ -5023,19 +5023,19 @@ recursive_push(VALUE list, VALUE obj, VALUE paired_obj) VALUE pair_list; if (!paired_obj) { - rb_hash_aset(list, obj, Qtrue); + rb_hash_aset(list, obj, Qtrue); } else if ((pair_list = rb_hash_lookup2(list, obj, Qundef)) == Qundef) { - rb_hash_aset(list, obj, paired_obj); + rb_hash_aset(list, obj, paired_obj); } else { - if (!RB_TYPE_P(pair_list, T_HASH)){ - VALUE other_paired_obj = pair_list; - pair_list = rb_hash_new(); - rb_hash_aset(pair_list, other_paired_obj, Qtrue); - rb_hash_aset(list, obj, pair_list); - } - rb_hash_aset(pair_list, paired_obj, Qtrue); + if (!RB_TYPE_P(pair_list, T_HASH)){ + VALUE other_paired_obj = pair_list; + pair_list = rb_hash_new(); + rb_hash_aset(pair_list, other_paired_obj, Qtrue); + rb_hash_aset(list, obj, pair_list); + } + rb_hash_aset(pair_list, paired_obj, Qtrue); } } @@ -5051,16 +5051,16 @@ static int recursive_pop(VALUE list, VALUE obj, VALUE paired_obj) { if (paired_obj) { - VALUE pair_list = rb_hash_lookup2(list, obj, Qundef); - if (pair_list == Qundef) { - return 0; - } - if (RB_TYPE_P(pair_list, T_HASH)) { - rb_hash_delete_entry(pair_list, paired_obj); - if (!RHASH_EMPTY_P(pair_list)) { - return 1; /* keep hash until is empty */ - } - } + VALUE pair_list = rb_hash_lookup2(list, obj, Qundef); + if (pair_list == Qundef) { + return 0; + } + if (RB_TYPE_P(pair_list, T_HASH)) { + rb_hash_delete_entry(pair_list, paired_obj); + if (!RHASH_EMPTY_P(pair_list)) { + return 1; /* keep hash until is empty */ + } + } } rb_hash_delete_entry(list, obj); return 1; @@ -5106,41 +5106,41 @@ exec_recursive(VALUE (*func) (VALUE, VALUE, int), VALUE obj, VALUE pairid, VALUE outermost = outer && !recursive_check(p.list, ID2SYM(recursive_key), 0); if (recursive_check(p.list, p.obj, pairid)) { - if (outer && !outermost) { - rb_throw_obj(p.list, p.list); - } - return (*func)(obj, arg, TRUE); + if (outer && !outermost) { + rb_throw_obj(p.list, p.list); + } + return (*func)(obj, arg, TRUE); } else { - enum ruby_tag_type state; + enum ruby_tag_type state; - p.func = func; + p.func = func; - if (outermost) { - recursive_push(p.list, ID2SYM(recursive_key), 0); - recursive_push(p.list, p.obj, p.pairid); - result = rb_catch_protect(p.list, exec_recursive_i, (VALUE)&p, &state); - if (!recursive_pop(p.list, p.obj, p.pairid)) goto invalid; - if (!recursive_pop(p.list, ID2SYM(recursive_key), 0)) goto invalid; - if (state != TAG_NONE) EC_JUMP_TAG(GET_EC(), state); - if (result == p.list) { - result = (*func)(obj, arg, TRUE); - } - } - else { - volatile VALUE ret = Qundef; - recursive_push(p.list, p.obj, p.pairid); - EC_PUSH_TAG(GET_EC()); - if ((state = EC_EXEC_TAG()) == TAG_NONE) { - ret = (*func)(obj, arg, FALSE); - } - EC_POP_TAG(); - if (!recursive_pop(p.list, p.obj, p.pairid)) { + if (outermost) { + recursive_push(p.list, ID2SYM(recursive_key), 0); + recursive_push(p.list, p.obj, p.pairid); + result = rb_catch_protect(p.list, exec_recursive_i, (VALUE)&p, &state); + if (!recursive_pop(p.list, p.obj, p.pairid)) goto invalid; + if (!recursive_pop(p.list, ID2SYM(recursive_key), 0)) goto invalid; + if (state != TAG_NONE) EC_JUMP_TAG(GET_EC(), state); + if (result == p.list) { + result = (*func)(obj, arg, TRUE); + } + } + else { + volatile VALUE ret = Qundef; + recursive_push(p.list, p.obj, p.pairid); + EC_PUSH_TAG(GET_EC()); + if ((state = EC_EXEC_TAG()) == TAG_NONE) { + ret = (*func)(obj, arg, FALSE); + } + EC_POP_TAG(); + if (!recursive_pop(p.list, p.obj, p.pairid)) { goto invalid; - } - if (state != TAG_NONE) EC_JUMP_TAG(GET_EC(), state); - result = ret; - } + } + if (state != TAG_NONE) EC_JUMP_TAG(GET_EC(), state); + result = ret; + } } *(volatile struct exec_recursive_params *)&p; return result; @@ -5328,7 +5328,7 @@ Init_Thread(void) rb_define_alias(rb_cThread, "inspect", "to_s"); rb_vm_register_special_exception(ruby_error_stream_closed, rb_eIOError, - "stream closed in another thread"); + "stream closed in another thread"); cThGroup = rb_define_class("ThreadGroup", rb_cObject); rb_define_alloc_func(cThGroup, thgroup_s_alloc); @@ -5339,23 +5339,23 @@ Init_Thread(void) { th->thgroup = th->ractor->thgroup_default = rb_obj_alloc(cThGroup); - rb_define_const(cThGroup, "Default", th->thgroup); + rb_define_const(cThGroup, "Default", th->thgroup); } rb_eThreadError = rb_define_class("ThreadError", rb_eStandardError); /* init thread core */ { - /* main thread setting */ - { - /* acquire global vm lock */ + /* main thread setting */ + { + /* acquire global vm lock */ struct rb_thread_sched *sched = TH_SCHED(th); thread_sched_to_running(sched, th); - th->pending_interrupt_queue = rb_ary_tmp_new(0); - th->pending_interrupt_queue_checked = 0; - th->pending_interrupt_mask_stack = rb_ary_tmp_new(0); - } + th->pending_interrupt_queue = rb_ary_tmp_new(0); + th->pending_interrupt_queue_checked = 0; + th->pending_interrupt_mask_stack = rb_ary_tmp_new(0); + } } rb_thread_create_timer_thread(); @@ -5384,7 +5384,7 @@ debug_deadlock_check(rb_ractor_t *r, VALUE msg) VALUE sep = rb_str_new_cstr("\n "); rb_str_catf(msg, "\n%d threads, %d sleeps current:%p main thread:%p\n", - rb_ractor_living_thread_num(r), rb_ractor_sleeper_thread_num(r), + rb_ractor_living_thread_num(r), rb_ractor_sleeper_thread_num(r), (void *)GET_THREAD(), (void *)r->threads.main); ccan_list_for_each(&r->threads.set, th, lt_node) { @@ -5440,12 +5440,12 @@ rb_check_deadlock(rb_ractor_t *r) } if (!found) { - VALUE argv[2]; - argv[0] = rb_eFatal; - argv[1] = rb_str_new2("No live threads left. Deadlock?"); - debug_deadlock_check(r, argv[1]); + VALUE argv[2]; + argv[0] = rb_eFatal; + argv[1] = rb_str_new2("No live threads left. Deadlock?"); + debug_deadlock_check(r, argv[1]); rb_ractor_sleeper_threads_dec(GET_RACTOR()); - rb_threadptr_raise(r->threads.main, 2, argv); + rb_threadptr_raise(r->threads.main, 2, argv); } } @@ -5470,27 +5470,27 @@ update_line_coverage(VALUE data, const rb_trace_arg_t *trace_arg) const rb_control_frame_t *cfp = GET_EC()->cfp; VALUE coverage = rb_iseq_coverage(cfp->iseq); if (RB_TYPE_P(coverage, T_ARRAY) && !RBASIC_CLASS(coverage)) { - VALUE lines = RARRAY_AREF(coverage, COVERAGE_INDEX_LINES); - if (lines) { - long line = rb_sourceline() - 1; - long count; - VALUE num; + VALUE lines = RARRAY_AREF(coverage, COVERAGE_INDEX_LINES); + if (lines) { + long line = rb_sourceline() - 1; + long count; + VALUE num; void rb_iseq_clear_event_flags(const rb_iseq_t *iseq, size_t pos, rb_event_flag_t reset); if (GET_VM()->coverage_mode & COVERAGE_TARGET_ONESHOT_LINES) { rb_iseq_clear_event_flags(cfp->iseq, cfp->pc - ISEQ_BODY(cfp->iseq)->iseq_encoded - 1, RUBY_EVENT_COVERAGE_LINE); rb_ary_push(lines, LONG2FIX(line + 1)); return; } - if (line >= RARRAY_LEN(lines)) { /* no longer tracked */ - return; - } - num = RARRAY_AREF(lines, line); - if (!FIXNUM_P(num)) return; - count = FIX2LONG(num) + 1; - if (POSFIXABLE(count)) { - RARRAY_ASET(lines, line, LONG2FIX(count)); - } - } + if (line >= RARRAY_LEN(lines)) { /* no longer tracked */ + return; + } + num = RARRAY_AREF(lines, line); + if (!FIXNUM_P(num)) return; + count = FIX2LONG(num) + 1; + if (POSFIXABLE(count)) { + RARRAY_ASET(lines, line, LONG2FIX(count)); + } + } } } @@ -5500,17 +5500,17 @@ update_branch_coverage(VALUE data, const rb_trace_arg_t *trace_arg) const rb_control_frame_t *cfp = GET_EC()->cfp; VALUE coverage = rb_iseq_coverage(cfp->iseq); if (RB_TYPE_P(coverage, T_ARRAY) && !RBASIC_CLASS(coverage)) { - VALUE branches = RARRAY_AREF(coverage, COVERAGE_INDEX_BRANCHES); - if (branches) { + VALUE branches = RARRAY_AREF(coverage, COVERAGE_INDEX_BRANCHES); + if (branches) { long pc = cfp->pc - ISEQ_BODY(cfp->iseq)->iseq_encoded - 1; long idx = FIX2INT(RARRAY_AREF(ISEQ_PC2BRANCHINDEX(cfp->iseq), pc)), count; - VALUE counters = RARRAY_AREF(branches, 1); - VALUE num = RARRAY_AREF(counters, idx); - count = FIX2LONG(num) + 1; - if (POSFIXABLE(count)) { - RARRAY_ASET(counters, idx, LONG2FIX(count)); - } - } + VALUE counters = RARRAY_AREF(branches, 1); + VALUE num = RARRAY_AREF(counters, idx); + count = FIX2LONG(num) + 1; + if (POSFIXABLE(count)) { + RARRAY_ASET(counters, idx, LONG2FIX(count)); + } + } } } @@ -5524,52 +5524,52 @@ rb_resolve_me_location(const rb_method_entry_t *me, VALUE resolved_location[5]) retry: switch (me->def->type) { case VM_METHOD_TYPE_ISEQ: { - const rb_iseq_t *iseq = me->def->body.iseq.iseqptr; + const rb_iseq_t *iseq = me->def->body.iseq.iseqptr; rb_iseq_location_t *loc = &ISEQ_BODY(iseq)->location; - path = rb_iseq_path(iseq); - beg_pos_lineno = INT2FIX(loc->code_location.beg_pos.lineno); - beg_pos_column = INT2FIX(loc->code_location.beg_pos.column); - end_pos_lineno = INT2FIX(loc->code_location.end_pos.lineno); - end_pos_column = INT2FIX(loc->code_location.end_pos.column); - break; + path = rb_iseq_path(iseq); + beg_pos_lineno = INT2FIX(loc->code_location.beg_pos.lineno); + beg_pos_column = INT2FIX(loc->code_location.beg_pos.column); + end_pos_lineno = INT2FIX(loc->code_location.end_pos.lineno); + end_pos_column = INT2FIX(loc->code_location.end_pos.column); + break; } case VM_METHOD_TYPE_BMETHOD: { const rb_iseq_t *iseq = rb_proc_get_iseq(me->def->body.bmethod.proc, 0); - if (iseq) { - rb_iseq_location_t *loc; - rb_iseq_check(iseq); - path = rb_iseq_path(iseq); + if (iseq) { + rb_iseq_location_t *loc; + rb_iseq_check(iseq); + path = rb_iseq_path(iseq); loc = &ISEQ_BODY(iseq)->location; - beg_pos_lineno = INT2FIX(loc->code_location.beg_pos.lineno); - beg_pos_column = INT2FIX(loc->code_location.beg_pos.column); - end_pos_lineno = INT2FIX(loc->code_location.end_pos.lineno); - end_pos_column = INT2FIX(loc->code_location.end_pos.column); - break; - } - return NULL; + beg_pos_lineno = INT2FIX(loc->code_location.beg_pos.lineno); + beg_pos_column = INT2FIX(loc->code_location.beg_pos.column); + end_pos_lineno = INT2FIX(loc->code_location.end_pos.lineno); + end_pos_column = INT2FIX(loc->code_location.end_pos.column); + break; + } + return NULL; } case VM_METHOD_TYPE_ALIAS: - me = me->def->body.alias.original_me; - goto retry; + me = me->def->body.alias.original_me; + goto retry; case VM_METHOD_TYPE_REFINED: - me = me->def->body.refined.orig_me; - if (!me) return NULL; - goto retry; + me = me->def->body.refined.orig_me; + if (!me) return NULL; + goto retry; default: - return NULL; + return NULL; } /* found */ if (RB_TYPE_P(path, T_ARRAY)) { - path = rb_ary_entry(path, 1); - if (!RB_TYPE_P(path, T_STRING)) return NULL; /* just for the case... */ + path = rb_ary_entry(path, 1); + if (!RB_TYPE_P(path, T_STRING)) return NULL; /* just for the case... */ } if (resolved_location) { - resolved_location[0] = path; - resolved_location[1] = beg_pos_lineno; - resolved_location[2] = beg_pos_column; - resolved_location[3] = end_pos_lineno; - resolved_location[4] = end_pos_column; + resolved_location[0] = path; + resolved_location[1] = beg_pos_lineno; + resolved_location[2] = beg_pos_column; + resolved_location[3] = end_pos_lineno; + resolved_location[4] = end_pos_column; } return me; } @@ -5589,7 +5589,7 @@ update_method_coverage(VALUE me2counter, rb_trace_arg_t *trace_arg) rcount = rb_hash_aref(me2counter, (VALUE) me); count = FIXNUM_P(rcount) ? FIX2LONG(rcount) + 1 : 1; if (POSFIXABLE(count)) { - rb_hash_aset(me2counter, (VALUE) me, LONG2FIX(count)); + rb_hash_aset(me2counter, (VALUE) me, LONG2FIX(count)); } } @@ -5620,10 +5620,10 @@ rb_resume_coverages(void) VALUE me2counter = GET_VM()->me2counter; rb_add_event_hook2((rb_event_hook_func_t) update_line_coverage, RUBY_EVENT_COVERAGE_LINE, Qnil, RUBY_EVENT_HOOK_FLAG_SAFE | RUBY_EVENT_HOOK_FLAG_RAW_ARG); if (mode & COVERAGE_TARGET_BRANCHES) { - rb_add_event_hook2((rb_event_hook_func_t) update_branch_coverage, RUBY_EVENT_COVERAGE_BRANCH, Qnil, RUBY_EVENT_HOOK_FLAG_SAFE | RUBY_EVENT_HOOK_FLAG_RAW_ARG); + rb_add_event_hook2((rb_event_hook_func_t) update_branch_coverage, RUBY_EVENT_COVERAGE_BRANCH, Qnil, RUBY_EVENT_HOOK_FLAG_SAFE | RUBY_EVENT_HOOK_FLAG_RAW_ARG); } if (mode & COVERAGE_TARGET_METHODS) { - rb_add_event_hook2((rb_event_hook_func_t) update_method_coverage, RUBY_EVENT_CALL, me2counter, RUBY_EVENT_HOOK_FLAG_SAFE | RUBY_EVENT_HOOK_FLAG_RAW_ARG); + rb_add_event_hook2((rb_event_hook_func_t) update_method_coverage, RUBY_EVENT_CALL, me2counter, RUBY_EVENT_HOOK_FLAG_SAFE | RUBY_EVENT_HOOK_FLAG_RAW_ARG); } } @@ -5632,10 +5632,10 @@ rb_suspend_coverages(void) { rb_remove_event_hook((rb_event_hook_func_t) update_line_coverage); if (GET_VM()->coverage_mode & COVERAGE_TARGET_BRANCHES) { - rb_remove_event_hook((rb_event_hook_func_t) update_branch_coverage); + rb_remove_event_hook((rb_event_hook_func_t) update_branch_coverage); } if (GET_VM()->coverage_mode & COVERAGE_TARGET_METHODS) { - rb_remove_event_hook((rb_event_hook_func_t) update_method_coverage); + rb_remove_event_hook((rb_event_hook_func_t) update_method_coverage); } } @@ -5656,7 +5656,7 @@ rb_default_coverage(int n) int mode = GET_VM()->coverage_mode; if (mode & COVERAGE_TARGET_LINES) { - lines = n > 0 ? rb_ary_tmp_new_fill(n) : rb_ary_tmp_new(0); + lines = n > 0 ? rb_ary_tmp_new_fill(n) : rb_ary_tmp_new(0); } RARRAY_ASET(coverage, COVERAGE_INDEX_LINES, lines); @@ -5685,9 +5685,9 @@ rb_default_coverage(int n) */ VALUE structure = rb_hash_new(); rb_obj_hide(structure); - RARRAY_ASET(branches, 0, structure); - /* branch execution counters */ - RARRAY_ASET(branches, 1, rb_ary_tmp_new(0)); + RARRAY_ASET(branches, 0, structure); + /* branch execution counters */ + RARRAY_ASET(branches, 1, rb_ary_tmp_new(0)); } RARRAY_ASET(coverage, COVERAGE_INDEX_BRANCHES, branches); diff --git a/thread_pthread.c b/thread_pthread.c index 86ad279d7c..e748797fe7 100644 --- a/thread_pthread.c +++ b/thread_pthread.c @@ -538,12 +538,12 @@ static void mutex_debug(const char *msg, void *lock) { if (NATIVE_MUTEX_LOCK_DEBUG) { - int r; - static pthread_mutex_t dbglock = PTHREAD_MUTEX_INITIALIZER; + int r; + static pthread_mutex_t dbglock = PTHREAD_MUTEX_INITIALIZER; - if ((r = pthread_mutex_lock(&dbglock)) != 0) {exit(EXIT_FAILURE);} - fprintf(stdout, "%s: %p\n", msg, lock); - if ((r = pthread_mutex_unlock(&dbglock)) != 0) {exit(EXIT_FAILURE);} + if ((r = pthread_mutex_lock(&dbglock)) != 0) {exit(EXIT_FAILURE);} + fprintf(stdout, "%s: %p\n", msg, lock); + if ((r = pthread_mutex_unlock(&dbglock)) != 0) {exit(EXIT_FAILURE);} } } @@ -553,7 +553,7 @@ rb_native_mutex_lock(pthread_mutex_t *lock) int r; mutex_debug("lock", lock); if ((r = pthread_mutex_lock(lock)) != 0) { - rb_bug_errno("pthread_mutex_lock", r); + rb_bug_errno("pthread_mutex_lock", r); } } @@ -563,7 +563,7 @@ rb_native_mutex_unlock(pthread_mutex_t *lock) int r; mutex_debug("unlock", lock); if ((r = pthread_mutex_unlock(lock)) != 0) { - rb_bug_errno("pthread_mutex_unlock", r); + rb_bug_errno("pthread_mutex_unlock", r); } } @@ -573,12 +573,12 @@ rb_native_mutex_trylock(pthread_mutex_t *lock) int r; mutex_debug("trylock", lock); if ((r = pthread_mutex_trylock(lock)) != 0) { - if (r == EBUSY) { - return EBUSY; - } - else { - rb_bug_errno("pthread_mutex_trylock", r); - } + if (r == EBUSY) { + return EBUSY; + } + else { + rb_bug_errno("pthread_mutex_trylock", r); + } } return 0; } @@ -589,7 +589,7 @@ rb_native_mutex_initialize(pthread_mutex_t *lock) int r = pthread_mutex_init(lock, 0); mutex_debug("init", lock); if (r != 0) { - rb_bug_errno("pthread_mutex_init", r); + rb_bug_errno("pthread_mutex_init", r); } } @@ -599,7 +599,7 @@ rb_native_mutex_destroy(pthread_mutex_t *lock) int r = pthread_mutex_destroy(lock); mutex_debug("destroy", lock); if (r != 0) { - rb_bug_errno("pthread_mutex_destroy", r); + rb_bug_errno("pthread_mutex_destroy", r); } } @@ -608,7 +608,7 @@ rb_native_cond_initialize(rb_nativethread_cond_t *cond) { int r = pthread_cond_init(cond, condattr_monotonic); if (r != 0) { - rb_bug_errno("pthread_cond_init", r); + rb_bug_errno("pthread_cond_init", r); } } @@ -617,7 +617,7 @@ rb_native_cond_destroy(rb_nativethread_cond_t *cond) { int r = pthread_cond_destroy(cond); if (r != 0) { - rb_bug_errno("pthread_cond_destroy", r); + rb_bug_errno("pthread_cond_destroy", r); } } @@ -636,10 +636,10 @@ rb_native_cond_signal(rb_nativethread_cond_t *cond) { int r; do { - r = pthread_cond_signal(cond); + r = pthread_cond_signal(cond); } while (r == EAGAIN); if (r != 0) { - rb_bug_errno("pthread_cond_signal", r); + rb_bug_errno("pthread_cond_signal", r); } } @@ -648,7 +648,7 @@ rb_native_cond_broadcast(rb_nativethread_cond_t *cond) { int r; do { - r = pthread_cond_broadcast(cond); + r = pthread_cond_broadcast(cond); } while (r == EAGAIN); if (r != 0) { rb_bug_errno("rb_native_cond_broadcast", r); @@ -660,7 +660,7 @@ rb_native_cond_wait(rb_nativethread_cond_t *cond, pthread_mutex_t *mutex) { int r = pthread_cond_wait(cond, mutex); if (r != 0) { - rb_bug_errno("pthread_cond_wait", r); + rb_bug_errno("pthread_cond_wait", r); } } @@ -920,8 +920,8 @@ get_stack(void **addr, size_t *size) char reg[256]; int regsiz=sizeof(reg); CHECK_ERR(pthread_getthrds_np(&th, PTHRDSINFO_QUERY_ALL, - &thinfo, sizeof(thinfo), - ®, ®siz)); + &thinfo, sizeof(thinfo), + ®, ®siz)); *addr = thinfo.__pi_stackaddr; /* Must not use thinfo.__pi_stacksize for size. It is around 3KB smaller than the correct size @@ -963,10 +963,10 @@ space_size(size_t stack_size) { size_t space_size = stack_size / RUBY_STACK_SPACE_RATIO; if (space_size > RUBY_STACK_SPACE_LIMIT) { - return RUBY_STACK_SPACE_LIMIT; + return RUBY_STACK_SPACE_LIMIT; } else { - return space_size; + return space_size; } } @@ -984,42 +984,42 @@ reserve_stack(volatile char *limit, size_t size) STACK_GROW_DIR_DETECTION; if (!getrlimit(RLIMIT_STACK, &rl) && rl.rlim_cur == RLIM_INFINITY) - return; + return; if (size < stack_check_margin) return; size -= stack_check_margin; size -= sizeof(buf); /* margin */ if (IS_STACK_DIR_UPPER()) { - const volatile char *end = buf + sizeof(buf); - limit += size; - if (limit > end) { - /* |<-bottom (=limit(a)) top->| - * | .. |<-buf 256B |<-end | stack check | - * | 256B | =size= | margin (4KB)| - * | =size= limit(b)->| 256B | | - * | | alloca(sz) | | | - * | .. |<-buf |<-limit(c) [sz-1]->0> | | - */ - size_t sz = limit - end; - limit = alloca(sz); - limit[sz-1] = 0; - } + const volatile char *end = buf + sizeof(buf); + limit += size; + if (limit > end) { + /* |<-bottom (=limit(a)) top->| + * | .. |<-buf 256B |<-end | stack check | + * | 256B | =size= | margin (4KB)| + * | =size= limit(b)->| 256B | | + * | | alloca(sz) | | | + * | .. |<-buf |<-limit(c) [sz-1]->0> | | + */ + size_t sz = limit - end; + limit = alloca(sz); + limit[sz-1] = 0; + } } else { - limit -= size; - if (buf > limit) { - /* |<-top (=limit(a)) bottom->| - * | .. | 256B buf->| | stack check | - * | 256B | =size= | margin (4KB)| - * | =size= limit(b)->| 256B | | - * | | alloca(sz) | | | - * | .. | buf->| limit(c)-><0> | | - */ - size_t sz = buf - limit; - limit = alloca(sz); - limit[0] = 0; - } + limit -= size; + if (buf > limit) { + /* |<-top (=limit(a)) bottom->| + * | .. | 256B buf->| | stack check | + * | 256B | =size= | margin (4KB)| + * | =size= limit(b)->| 256B | | + * | | alloca(sz) | | | + * | .. | buf->| limit(c)-><0> | | + */ + size_t sz = buf - limit; + limit = alloca(sz); + limit[0] = 0; + } } } #else @@ -1035,14 +1035,14 @@ ruby_init_stack(volatile VALUE *addr) #if MAINSTACKADDR_AVAILABLE if (native_main_thread.stack_maxsize) return; { - void* stackaddr; - size_t size; - if (get_main_stack(&stackaddr, &size) == 0) { - native_main_thread.stack_maxsize = size; - native_main_thread.stack_start = stackaddr; - reserve_stack(stackaddr, size); - goto bound_check; - } + void* stackaddr; + size_t size; + if (get_main_stack(&stackaddr, &size) == 0) { + native_main_thread.stack_maxsize = size; + native_main_thread.stack_start = stackaddr; + reserve_stack(stackaddr, size); + goto bound_check; + } } #endif #ifdef STACK_END_ADDRESS @@ -1061,25 +1061,25 @@ ruby_init_stack(volatile VALUE *addr) # if PTHREAD_STACK_DEFAULT < RUBY_STACK_SPACE*5 # error "PTHREAD_STACK_DEFAULT is too small" # endif - size_t size = PTHREAD_STACK_DEFAULT; + size_t size = PTHREAD_STACK_DEFAULT; #else - size_t size = RUBY_VM_THREAD_VM_STACK_SIZE; + size_t size = RUBY_VM_THREAD_VM_STACK_SIZE; #endif - size_t space; - int pagesize = getpagesize(); - struct rlimit rlim; + size_t space; + int pagesize = getpagesize(); + struct rlimit rlim; STACK_GROW_DIR_DETECTION; - if (getrlimit(RLIMIT_STACK, &rlim) == 0) { - size = (size_t)rlim.rlim_cur; - } - addr = native_main_thread.stack_start; - if (IS_STACK_DIR_UPPER()) { - space = ((size_t)((char *)addr + size) / pagesize) * pagesize - (size_t)addr; - } - else { - space = (size_t)addr - ((size_t)((char *)addr - size) / pagesize + 1) * pagesize; - } - native_main_thread.stack_maxsize = space; + if (getrlimit(RLIMIT_STACK, &rlim) == 0) { + size = (size_t)rlim.rlim_cur; + } + addr = native_main_thread.stack_start; + if (IS_STACK_DIR_UPPER()) { + space = ((size_t)((char *)addr + size) / pagesize) * pagesize - (size_t)addr; + } + else { + space = (size_t)addr - ((size_t)((char *)addr - size) / pagesize + 1) * pagesize; + } + native_main_thread.stack_maxsize = space; #endif } @@ -1089,23 +1089,23 @@ ruby_init_stack(volatile VALUE *addr) /* If addr is out of range of main-thread stack range estimation, */ /* it should be on co-routine (alternative stack). [Feature #2294] */ { - void *start, *end; - STACK_GROW_DIR_DETECTION; + void *start, *end; + STACK_GROW_DIR_DETECTION; - if (IS_STACK_DIR_UPPER()) { - start = native_main_thread.stack_start; - end = (char *)native_main_thread.stack_start + native_main_thread.stack_maxsize; - } - else { - start = (char *)native_main_thread.stack_start - native_main_thread.stack_maxsize; - end = native_main_thread.stack_start; - } + if (IS_STACK_DIR_UPPER()) { + start = native_main_thread.stack_start; + end = (char *)native_main_thread.stack_start + native_main_thread.stack_maxsize; + } + else { + start = (char *)native_main_thread.stack_start - native_main_thread.stack_maxsize; + end = native_main_thread.stack_start; + } - if ((void *)addr < start || (void *)addr > end) { - /* out of range */ - native_main_thread.stack_start = (VALUE *)addr; - native_main_thread.stack_maxsize = 0; /* unknown */ - } + if ((void *)addr < start || (void *)addr > end) { + /* out of range */ + native_main_thread.stack_start = (VALUE *)addr; + native_main_thread.stack_maxsize = 0; /* unknown */ + } } } @@ -1118,21 +1118,21 @@ native_thread_init_stack(rb_thread_t *th) rb_nativethread_id_t curr = pthread_self(); if (pthread_equal(curr, native_main_thread.id)) { - th->ec->machine.stack_start = native_main_thread.stack_start; - th->ec->machine.stack_maxsize = native_main_thread.stack_maxsize; + th->ec->machine.stack_start = native_main_thread.stack_start; + th->ec->machine.stack_maxsize = native_main_thread.stack_maxsize; } else { #ifdef STACKADDR_AVAILABLE - void *start; - size_t size; + void *start; + size_t size; - if (get_stack(&start, &size) == 0) { - uintptr_t diff = (uintptr_t)start - (uintptr_t)&curr; - th->ec->machine.stack_start = (VALUE *)&curr; - th->ec->machine.stack_maxsize = size - diff; - } + if (get_stack(&start, &size) == 0) { + uintptr_t diff = (uintptr_t)start - (uintptr_t)&curr; + th->ec->machine.stack_start = (VALUE *)&curr; + th->ec->machine.stack_maxsize = size - diff; + } #else - rb_raise(rb_eNotImpError, "ruby engine can initialize only in the main thread"); + rb_raise(rb_eNotImpError, "ruby engine can initialize only in the main thread"); #endif } @@ -1153,11 +1153,11 @@ thread_start_func_1(void *th_ptr) #endif { #if !defined USE_NATIVE_THREAD_INIT - VALUE stack_start; + VALUE stack_start; #endif #if defined USE_NATIVE_THREAD_INIT - native_thread_init_stack(th); + native_thread_init_stack(th); #endif native_thread_init(th->nt); @@ -1302,16 +1302,16 @@ native_thread_create(rb_thread_t *th) RUBY_DEBUG_LOG("use cached nt. th:%u", rb_th_serial(th)); } else { - pthread_attr_t attr; + pthread_attr_t attr; const size_t stack_size = th->vm->default_params.thread_machine_stack_size + th->vm->default_params.thread_vm_stack_size; - const size_t space = space_size(stack_size); + const size_t space = space_size(stack_size); #ifdef USE_SIGALTSTACK th->nt->altstack = rb_allocate_sigaltstack(); #endif th->ec->machine.stack_maxsize = stack_size - space; - CHECK_ERR(pthread_attr_init(&attr)); + CHECK_ERR(pthread_attr_init(&attr)); # ifdef PTHREAD_STACK_MIN RUBY_DEBUG_LOG("stack size: %lu", (unsigned long)stack_size); @@ -1319,16 +1319,16 @@ native_thread_create(rb_thread_t *th) # endif # ifdef HAVE_PTHREAD_ATTR_SETINHERITSCHED - CHECK_ERR(pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED)); + CHECK_ERR(pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED)); # endif - CHECK_ERR(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)); + CHECK_ERR(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)); err = pthread_create(&th->nt->thread_id, &attr, thread_start_func_1, th); RUBY_DEBUG_LOG("th:%u err:%d", rb_th_serial(th), err); /* should be done in the created thread */ - CHECK_ERR(pthread_attr_destroy(&attr)); + CHECK_ERR(pthread_attr_destroy(&attr)); } return err; } @@ -1348,10 +1348,10 @@ native_thread_apply_priority(rb_thread_t *th) min = sched_get_priority_min(policy); if (min > priority) { - priority = min; + priority = min; } else if (max < priority) { - priority = max; + priority = max; } sp.sched_priority = priority; @@ -1396,17 +1396,17 @@ native_cond_sleep(rb_thread_t *th, rb_hrtime_t *rel) THREAD_BLOCKING_BEGIN(th); { rb_native_mutex_lock(lock); - th->unblock.func = ubf_pthread_cond_signal; - th->unblock.arg = th; + th->unblock.func = ubf_pthread_cond_signal; + th->unblock.arg = th; - if (RUBY_VM_INTERRUPTED(th->ec)) { - /* interrupted. return immediate */ + if (RUBY_VM_INTERRUPTED(th->ec)) { + /* interrupted. return immediate */ RUBY_DEBUG_LOG("interrupted before sleep th:%u", rb_th_serial(th)); - } - else { - if (!rel) { - rb_native_cond_wait(cond, lock); - } + } + else { + if (!rel) { + rb_native_cond_wait(cond, lock); + } else { rb_hrtime_t end; @@ -1417,10 +1417,10 @@ native_cond_sleep(rb_thread_t *th, rb_hrtime_t *rel) end = native_cond_timeout(cond, *rel); native_cond_timedwait(cond, lock, &end); } - } - th->unblock.func = 0; + } + th->unblock.func = 0; - rb_native_mutex_unlock(lock); + rb_native_mutex_unlock(lock); } THREAD_BLOCKING_END(th); @@ -1446,7 +1446,7 @@ register_ubf_list(rb_thread_t *th) if (ccan_list_empty((struct ccan_list_head*)node)) { rb_native_mutex_lock(&ubf_list_lock); - ccan_list_add(&ubf_list_head, node); + ccan_list_add(&ubf_list_head, node); rb_native_mutex_unlock(&ubf_list_lock); } } @@ -1531,8 +1531,8 @@ ubf_wakeup_all_threads(void) rb_thread_t *th; ccan_list_for_each(&ubf_list_head, th, sched.node.ubf) { - ubf_wakeup_thread(th); - } + ubf_wakeup_thread(th); + } rb_native_mutex_unlock(&ubf_list_lock); } } @@ -1575,23 +1575,23 @@ rb_thread_wakeup_timer_thread_fd(int fd) /* already opened */ if (fd >= 0) { retry: - if ((result = write(fd, &buff, sizeof(buff))) <= 0) { - int e = errno; - switch (e) { - case EINTR: goto retry; - case EAGAIN: + if ((result = write(fd, &buff, sizeof(buff))) <= 0) { + int e = errno; + switch (e) { + case EINTR: goto retry; + case EAGAIN: #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN - case EWOULDBLOCK: + case EWOULDBLOCK: #endif - break; - default: - async_bug_fd("rb_thread_wakeup_timer_thread: write", e, fd); - } - } - if (TT_DEBUG) WRITE_CONST(2, "rb_thread_wakeup_timer_thread: write\n"); + break; + default: + async_bug_fd("rb_thread_wakeup_timer_thread: write", e, fd); + } + } + if (TT_DEBUG) WRITE_CONST(2, "rb_thread_wakeup_timer_thread: write\n"); } else { - /* ignore wakeup */ + /* ignore wakeup */ } } @@ -1705,7 +1705,7 @@ close_invalidate(int *fdp, const char *msg) *fdp = -1; if (close(fd) < 0) { - async_bug_fd(msg, errno, fd); + async_bug_fd(msg, errno, fd); } } @@ -1730,11 +1730,11 @@ set_nonblock(int fd) oflags = fcntl(fd, F_GETFL); if (oflags == -1) - rb_sys_fail(0); + rb_sys_fail(0); oflags |= O_NONBLOCK; err = fcntl(fd, F_SETFL, oflags); if (err == -1) - rb_sys_fail(0); + rb_sys_fail(0); } /* communication pipe with timer thread and signal handler */ @@ -1763,9 +1763,9 @@ setup_communication_pipe_internal(int pipes[2]) err = rb_cloexec_pipe(pipes); if (err != 0) { - rb_warn("pipe creation failed for timer: %s, scheduling broken", - strerror(errno)); - return -1; + rb_warn("pipe creation failed for timer: %s, scheduling broken", + strerror(errno)); + return -1; } rb_update_max_fd(pipes[0]); rb_update_max_fd(pipes[1]); @@ -1942,7 +1942,7 @@ ubf_timer_create(rb_pid_t current) timer_posix.owner = current; } else { - rb_warn("timer_create failed: %s, signals racy", strerror(errno)); + rb_warn("timer_create failed: %s, signals racy", strerror(errno)); } #endif if (UBF_TIMER == UBF_TIMER_PTHREAD) @@ -2089,33 +2089,33 @@ ruby_stack_overflowed_p(const rb_thread_t *th, const void *addr) #ifdef STACKADDR_AVAILABLE if (get_stack(&base, &size) == 0) { # ifdef __APPLE__ - if (pthread_equal(th->nt->thread_id, native_main_thread.id)) { - struct rlimit rlim; - if (getrlimit(RLIMIT_STACK, &rlim) == 0 && rlim.rlim_cur > size) { - size = (size_t)rlim.rlim_cur; - } - } + if (pthread_equal(th->nt->thread_id, native_main_thread.id)) { + struct rlimit rlim; + if (getrlimit(RLIMIT_STACK, &rlim) == 0 && rlim.rlim_cur > size) { + size = (size_t)rlim.rlim_cur; + } + } # endif - base = (char *)base + STACK_DIR_UPPER(+size, -size); + base = (char *)base + STACK_DIR_UPPER(+size, -size); } else #endif if (th) { - size = th->ec->machine.stack_maxsize; - base = (char *)th->ec->machine.stack_start - STACK_DIR_UPPER(0, size); + size = th->ec->machine.stack_maxsize; + base = (char *)th->ec->machine.stack_start - STACK_DIR_UPPER(0, size); } else { - return 0; + return 0; } size /= RUBY_STACK_SPACE_RATIO; if (size > water_mark) size = water_mark; if (IS_STACK_DIR_UPPER()) { - if (size > ~(size_t)base+1) size = ~(size_t)base+1; - if (addr > base && addr <= (void *)((char *)base + size)) return 1; + if (size > ~(size_t)base+1) size = ~(size_t)base+1; + if (addr > base && addr <= (void *)((char *)base + size)) return 1; } else { - if (size > (size_t)base) size = (size_t)base; - if (addr > (void *)((char *)base - size) && addr <= base) return 1; + if (size > (size_t)base) size = (size_t)base; + if (addr > (void *)((char *)base - size) && addr <= base) return 1; } return 0; } @@ -2139,7 +2139,7 @@ rb_reserved_fd_p(int fd) return 0; check_pid: if (signal_self_pipe.owner_process == getpid()) /* async-signal-safe */ - return 1; + return 1; return 0; } @@ -2186,22 +2186,22 @@ ruby_ppoll(struct pollfd *fds, nfds_t nfds, int timeout_ms; if (ts) { - int tmp, tmp2; + int tmp, tmp2; - if (ts->tv_sec > INT_MAX/1000) - timeout_ms = INT_MAX; - else { - tmp = (int)(ts->tv_sec * 1000); - /* round up 1ns to 1ms to avoid excessive wakeups for <1ms sleep */ - tmp2 = (int)((ts->tv_nsec + 999999L) / (1000L * 1000L)); - if (INT_MAX - tmp < tmp2) - timeout_ms = INT_MAX; - else - timeout_ms = (int)(tmp + tmp2); - } + if (ts->tv_sec > INT_MAX/1000) + timeout_ms = INT_MAX; + else { + tmp = (int)(ts->tv_sec * 1000); + /* round up 1ns to 1ms to avoid excessive wakeups for <1ms sleep */ + tmp2 = (int)((ts->tv_nsec + 999999L) / (1000L * 1000L)); + if (INT_MAX - tmp < tmp2) + timeout_ms = INT_MAX; + else + timeout_ms = (int)(tmp + tmp2); + } } else - timeout_ms = -1; + timeout_ms = -1; return poll(fds, nfds, timeout_ms); } diff --git a/thread_sync.c b/thread_sync.c index 9b466e6670..09f824c622 100644 --- a/thread_sync.c +++ b/thread_sync.c @@ -96,7 +96,7 @@ rb_mutex_num_waiting(rb_mutex_t *mutex) size_t n = 0; ccan_list_for_each(&mutex->waitq, w, node) { - n++; + n++; } return n; @@ -109,9 +109,9 @@ mutex_free(void *ptr) { rb_mutex_t *mutex = ptr; if (mutex->fiber) { - /* rb_warn("free locked mutex"); */ - const char *err = rb_mutex_unlock_th(mutex, rb_fiber_threadptr(mutex->fiber), mutex->fiber); - if (err) rb_bug("%s", err); + /* rb_warn("free locked mutex"); */ + const char *err = rb_mutex_unlock_th(mutex, rb_fiber_threadptr(mutex->fiber), mutex->fiber); + if (err) rb_bug("%s", err); } ruby_xfree(ptr); } @@ -235,12 +235,12 @@ rb_mutex_trylock(VALUE self) rb_mutex_t *mutex = mutex_ptr(self); if (mutex->fiber == 0) { - rb_fiber_t *fiber = GET_EC()->fiber_ptr; - rb_thread_t *th = GET_THREAD(); - mutex->fiber = fiber; + rb_fiber_t *fiber = GET_EC()->fiber_ptr; + rb_thread_t *th = GET_THREAD(); + mutex->fiber = fiber; - mutex_locked(th, self); - return Qtrue; + mutex_locked(th, self); + return Qtrue; } return Qfalse; @@ -284,8 +284,8 @@ do_mutex_lock(VALUE self, int interruptible_p) /* When running trap handler */ if (!FL_TEST_RAW(self, MUTEX_ALLOW_TRAP) && - th->ec->interrupt_mask & TRAP_INTERRUPT_MASK) { - rb_raise(rb_eThreadError, "can't be called from trap context"); + th->ec->interrupt_mask & TRAP_INTERRUPT_MASK) { + rb_raise(rb_eThreadError, "can't be called from trap context"); } if (rb_mutex_trylock(self) == Qfalse) { @@ -502,11 +502,11 @@ rb_mutex_abandon_all(rb_mutex_t *mutexes) rb_mutex_t *mutex; while (mutexes) { - mutex = mutexes; - mutexes = mutex->next_mutex; - mutex->fiber = 0; - mutex->next_mutex = 0; - ccan_list_head_init(&mutex->waitq); + mutex = mutexes; + mutexes = mutex->next_mutex; + mutex->fiber = 0; + mutex->next_mutex = 0; + ccan_list_head_init(&mutex->waitq); } } #endif @@ -611,7 +611,7 @@ static VALUE rb_mutex_synchronize_m(VALUE self) { if (!rb_block_given_p()) { - rb_raise(rb_eThreadError, "must be called with a block"); + rb_raise(rb_eThreadError, "must be called with a block"); } return rb_mutex_synchronize(self, rb_yield, Qundef); @@ -622,9 +622,9 @@ void rb_mutex_allow_trap(VALUE self, int val) Check_TypedStruct(self, &mutex_data_type); if (val) - FL_SET_RAW(self, MUTEX_ALLOW_TRAP); + FL_SET_RAW(self, MUTEX_ALLOW_TRAP); else - FL_UNSET_RAW(self, MUTEX_ALLOW_TRAP); + FL_UNSET_RAW(self, MUTEX_ALLOW_TRAP); } /* Queue */ @@ -731,7 +731,7 @@ szqueue_alloc(VALUE klass) { struct rb_szqueue *sq; VALUE obj = TypedData_Make_Struct(klass, struct rb_szqueue, - &szqueue_data_type, sq); + &szqueue_data_type, sq); ccan_list_head_init(szqueue_waitq(sq)); ccan_list_head_init(szqueue_pushq(sq)); return obj; @@ -761,7 +761,7 @@ static VALUE check_array(VALUE obj, VALUE ary) { if (!RB_TYPE_P(ary, T_ARRAY)) { - rb_raise(rb_eTypeError, "%+"PRIsVALUE" not initialized", obj); + rb_raise(rb_eTypeError, "%+"PRIsVALUE" not initialized", obj); } return ary; } @@ -880,7 +880,7 @@ static VALUE queue_do_push(VALUE self, struct rb_queue *q, VALUE obj) { if (queue_closed_p(self)) { - raise_closed_queue_error(self); + raise_closed_queue_error(self); } rb_ary_push(check_array(self, q->que), obj); wakeup_one(queue_waitq(q)); @@ -926,9 +926,9 @@ rb_queue_close(VALUE self) struct rb_queue *q = queue_ptr(self); if (!queue_closed_p(self)) { - FL_SET(self, QUEUE_CLOSED); + FL_SET(self, QUEUE_CLOSED); - wakeup_all(queue_waitq(q)); + wakeup_all(queue_waitq(q)); } return self; @@ -973,8 +973,8 @@ queue_sleep(VALUE self) struct queue_waiter { struct sync_waiter w; union { - struct rb_queue *q; - struct rb_szqueue *sq; + struct rb_queue *q; + struct rb_szqueue *sq; } as; }; @@ -1041,7 +1041,7 @@ queue_pop_should_block(int argc, const VALUE *argv) int should_block = 1; rb_check_arity(argc, 0, 1); if (argc > 0) { - should_block = !RTEST(argv[0]); + should_block = !RTEST(argv[0]); } return should_block; } @@ -1148,7 +1148,7 @@ rb_szqueue_initialize(VALUE self, VALUE vmax) max = NUM2LONG(vmax); if (max <= 0) { - rb_raise(rb_eArgError, "queue size must be positive"); + rb_raise(rb_eArgError, "queue size must be positive"); } RB_OBJ_WRITE(self, &sq->q.que, ary_buf_new()); @@ -1175,11 +1175,11 @@ static VALUE rb_szqueue_close(VALUE self) { if (!queue_closed_p(self)) { - struct rb_szqueue *sq = szqueue_ptr(self); + struct rb_szqueue *sq = szqueue_ptr(self); - FL_SET(self, QUEUE_CLOSED); - wakeup_all(szqueue_waitq(sq)); - wakeup_all(szqueue_pushq(sq)); + FL_SET(self, QUEUE_CLOSED); + wakeup_all(szqueue_waitq(sq)); + wakeup_all(szqueue_pushq(sq)); } return self; } @@ -1211,10 +1211,10 @@ rb_szqueue_max_set(VALUE self, VALUE vmax) struct rb_szqueue *sq = szqueue_ptr(self); if (max <= 0) { - rb_raise(rb_eArgError, "queue size must be positive"); + rb_raise(rb_eArgError, "queue size must be positive"); } if (max > sq->max) { - diff = max - sq->max; + diff = max - sq->max; } sq->max = max; sync_wakeup(szqueue_pushq(sq), diff); @@ -1227,7 +1227,7 @@ szqueue_push_should_block(int argc, const VALUE *argv) int should_block = 1; rb_check_arity(argc, 1, 2); if (argc > 1) { - should_block = !RTEST(argv[1]); + should_block = !RTEST(argv[1]); } return should_block; } @@ -1289,7 +1289,7 @@ szqueue_do_pop(VALUE self, int should_block) VALUE retval = queue_do_pop(self, &sq->q, should_block); if (queue_length(self, &sq->q) < sq->max) { - wakeup_one(szqueue_pushq(sq)); + wakeup_one(szqueue_pushq(sq)); } return retval; diff --git a/thread_win32.c b/thread_win32.c index 81fea585ac..cbb01d5d84 100644 --- a/thread_win32.c +++ b/thread_win32.c @@ -50,19 +50,19 @@ w32_error(const char *func) LPVOID lpMsgBuf; DWORD err = GetLastError(); if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - err, - MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), - (LPTSTR) & lpMsgBuf, 0, NULL) == 0) - FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - err, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPTSTR) & lpMsgBuf, 0, NULL); + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + err, + MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), + (LPTSTR) & lpMsgBuf, 0, NULL) == 0) + FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + err, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPTSTR) & lpMsgBuf, 0, NULL); rb_bug("%s: %s", func, (char*)lpMsgBuf); UNREACHABLE; } @@ -84,30 +84,30 @@ w32_mutex_lock(HANDLE lock, bool try) w32_event_debug("lock:%p\n", lock); result = w32_wait_events(&lock, 1, try ? 0 : INFINITE, 0); - switch (result) { - case WAIT_OBJECT_0: - /* get mutex object */ + switch (result) { + case WAIT_OBJECT_0: + /* get mutex object */ w32_event_debug("locked lock:%p\n", lock); - return 0; + return 0; case WAIT_OBJECT_0 + 1: - /* interrupt */ - errno = EINTR; + /* interrupt */ + errno = EINTR; w32_event_debug("interrupted lock:%p\n", lock); - return 0; + return 0; case WAIT_TIMEOUT: w32_event_debug("timeout locK:%p\n", lock); return EBUSY; case WAIT_ABANDONED: - rb_bug("win32_mutex_lock: WAIT_ABANDONED"); - break; + rb_bug("win32_mutex_lock: WAIT_ABANDONED"); + break; default: rb_bug("win32_mutex_lock: unknown result (%ld)", result); - break; - } + break; + } } return 0; } @@ -192,9 +192,9 @@ Init_native_thread(rb_thread_t *main_th) main_th->nt->interrupt_event = CreateEvent(0, TRUE, FALSE, 0); DuplicateHandle(GetCurrentProcess(), - GetCurrentThread(), - GetCurrentProcess(), - &main_th->nt->thread_id, 0, FALSE, DUPLICATE_SAME_ACCESS); + GetCurrentThread(), + GetCurrentProcess(), + &main_th->nt->thread_id, 0, FALSE, DUPLICATE_SAME_ACCESS); RUBY_DEBUG_LOG("initial thread th:%u thid:%p, event: %p", rb_th_serial(main_th), @@ -214,16 +214,16 @@ w32_wait_events(HANDLE *events, int count, DWORD timeout, rb_thread_t *th) events, count, timeout, th ? rb_th_serial(th) : UINT_MAX); if (th && (intr = th->nt->interrupt_event)) { - if (ResetEvent(intr) && (!RUBY_VM_INTERRUPTED(th->ec) || SetEvent(intr))) { - targets = ALLOCA_N(HANDLE, count + 1); - memcpy(targets, events, sizeof(HANDLE) * count); + if (ResetEvent(intr) && (!RUBY_VM_INTERRUPTED(th->ec) || SetEvent(intr))) { + targets = ALLOCA_N(HANDLE, count + 1); + memcpy(targets, events, sizeof(HANDLE) * count); - targets[count++] = intr; + targets[count++] = intr; w32_event_debug("handle:%p (count:%d, intr)\n", intr, count); } - else if (intr == th->nt->interrupt_event) { - w32_error("w32_wait_events"); - } + else if (intr == th->nt->interrupt_event) { + w32_error("w32_wait_events"); + } } w32_event_debug("WaitForMultipleObjects start count:%d\n", count); @@ -231,14 +231,14 @@ w32_wait_events(HANDLE *events, int count, DWORD timeout, rb_thread_t *th) w32_event_debug("WaitForMultipleObjects end ret:%lu\n", ret); if (ret == (DWORD)(WAIT_OBJECT_0 + initcount) && th) { - errno = EINTR; + errno = EINTR; } if (ret == WAIT_FAILED && W32_EVENT_DEBUG) { - int i; + int i; DWORD dmy; for (i = 0; i < count; i++) { w32_event_debug("i:%d %s\n", i, GetHandleInformation(targets[i], &dmy) ? "OK" : "NG"); - } + } } return ret; } @@ -259,7 +259,7 @@ rb_w32_wait_events(HANDLE *events, int num, DWORD timeout) rb_thread_t *th = GET_THREAD(); BLOCKING_REGION(th, ret = rb_w32_wait_events_blocking(events, num, timeout), - ubf_handle, ruby_thread_from_native(), FALSE); + ubf_handle, ruby_thread_from_native(), FALSE); return ret; } @@ -267,7 +267,7 @@ static void w32_close_handle(HANDLE handle) { if (CloseHandle(handle) == 0) { - w32_error("w32_close_handle"); + w32_error("w32_close_handle"); } } @@ -275,7 +275,7 @@ static void w32_resume_thread(HANDLE handle) { if (ResumeThread(handle) == (DWORD)-1) { - w32_error("w32_resume_thread"); + w32_error("w32_resume_thread"); } } @@ -314,7 +314,7 @@ rb_w32_Sleep(unsigned long msec) rb_thread_t *th = GET_THREAD(); BLOCKING_REGION(th, ret = rb_w32_sleep(msec), - ubf_handle, ruby_thread_from_native(), FALSE); + ubf_handle, ruby_thread_from_native(), FALSE); return ret; } @@ -331,26 +331,26 @@ native_sleep(rb_thread_t *th, rb_hrtime_t *rel) THREAD_BLOCKING_BEGIN(th); { - DWORD ret; + DWORD ret; rb_native_mutex_lock(&th->interrupt_lock); - th->unblock.func = ubf_handle; - th->unblock.arg = th; + th->unblock.func = ubf_handle; + th->unblock.arg = th; rb_native_mutex_unlock(&th->interrupt_lock); - if (RUBY_VM_INTERRUPTED(th->ec)) { - /* interrupted. return immediate */ - } - else { - RUBY_DEBUG_LOG("start msec:%lu", msec); - ret = w32_wait_events(0, 0, msec, th); - RUBY_DEBUG_LOG("done ret:%lu", ret); - (void)ret; - } + if (RUBY_VM_INTERRUPTED(th->ec)) { + /* interrupted. return immediate */ + } + else { + RUBY_DEBUG_LOG("start msec:%lu", msec); + ret = w32_wait_events(0, 0, msec, th); + RUBY_DEBUG_LOG("done ret:%lu", ret); + (void)ret; + } rb_native_mutex_lock(&th->interrupt_lock); - th->unblock.func = 0; - th->unblock.arg = 0; + th->unblock.func = 0; + th->unblock.arg = 0; rb_native_mutex_unlock(&th->interrupt_lock); } THREAD_BLOCKING_END(th); @@ -422,14 +422,14 @@ rb_native_cond_signal(rb_nativethread_cond_t *cond) struct cond_event_entry *head = (struct cond_event_entry*)cond; if (e != head) { - struct cond_event_entry *next = e->next; - struct cond_event_entry *prev = e->prev; + struct cond_event_entry *next = e->next; + struct cond_event_entry *prev = e->prev; - prev->next = next; - next->prev = prev; - e->next = e->prev = e; + prev->next = next; + next->prev = prev; + e->next = e->prev = e; - SetEvent(e->event); + SetEvent(e->event); } } @@ -441,16 +441,16 @@ rb_native_cond_broadcast(rb_nativethread_cond_t *cond) struct cond_event_entry *head = (struct cond_event_entry*)cond; while (e != head) { - struct cond_event_entry *next = e->next; - struct cond_event_entry *prev = e->prev; + struct cond_event_entry *next = e->next; + struct cond_event_entry *prev = e->prev; - SetEvent(e->event); + SetEvent(e->event); - prev->next = next; - next->prev = prev; - e->next = e->prev = e; + prev->next = next; + next->prev = prev; + e->next = e->prev = e; - e = next; + e = next; } } @@ -471,10 +471,10 @@ native_cond_timedwait_ms(rb_nativethread_cond_t *cond, rb_nativethread_lock_t *m rb_native_mutex_unlock(mutex); { - r = WaitForSingleObject(entry.event, msec); - if ((r != WAIT_OBJECT_0) && (r != WAIT_TIMEOUT)) { + r = WaitForSingleObject(entry.event, msec); + if ((r != WAIT_OBJECT_0) && (r != WAIT_TIMEOUT)) { rb_bug("rb_native_cond_wait: WaitForSingleObject returns %lu", r); - } + } } rb_native_mutex_lock(mutex); @@ -502,7 +502,7 @@ abs_timespec_to_timeout_ms(const struct timespec *ts) tv.tv_usec = ts->tv_nsec / 1000; if (!rb_w32_time_subtract(&tv, &now)) - return 0; + return 0; return (tv.tv_sec * 1000) + (tv.tv_usec / 1000); } @@ -514,7 +514,7 @@ native_cond_timedwait(rb_nativethread_cond_t *cond, rb_nativethread_lock_t *mute timeout_ms = abs_timespec_to_timeout_ms(ts); if (!timeout_ms) - return ETIMEDOUT; + return ETIMEDOUT; return native_cond_timedwait_ms(cond, mutex, timeout_ms); } @@ -542,7 +542,7 @@ native_cond_timeout(rb_nativethread_cond_t *cond, struct timespec timeout_rel) ret = gettimeofday(&tv, 0); if (ret != 0) - rb_sys_fail(0); + rb_sys_fail(0); now.tv_sec = tv.tv_sec; now.tv_nsec = tv.tv_usec * 1000; @@ -552,12 +552,12 @@ native_cond_timeout(rb_nativethread_cond_t *cond, struct timespec timeout_rel) timeout.tv_nsec += timeout_rel.tv_nsec; if (timeout.tv_nsec >= 1000*1000*1000) { - timeout.tv_sec++; - timeout.tv_nsec -= 1000*1000*1000; + timeout.tv_sec++; + timeout.tv_nsec -= 1000*1000*1000; } if (timeout.tv_sec < now.tv_sec) - timeout.tv_sec = TIMET_MAX; + timeout.tv_sec = TIMET_MAX; return timeout; } @@ -652,7 +652,7 @@ native_thread_create(rb_thread_t *th) th->nt->thread_id = w32_create_thread(stack_size, thread_start_func_1, th); if ((th->nt->thread_id) == 0) { - return thread_errno; + return thread_errno; } w32_resume_thread(th->nt->thread_id); @@ -679,13 +679,13 @@ native_thread_apply_priority(rb_thread_t *th) { int priority = th->priority; if (th->priority > 0) { - priority = THREAD_PRIORITY_ABOVE_NORMAL; + priority = THREAD_PRIORITY_ABOVE_NORMAL; } else if (th->priority < 0) { - priority = THREAD_PRIORITY_BELOW_NORMAL; + priority = THREAD_PRIORITY_BELOW_NORMAL; } else { - priority = THREAD_PRIORITY_NORMAL; + priority = THREAD_PRIORITY_NORMAL; } SetThreadPriority(th->nt->thread_id, priority); @@ -728,7 +728,7 @@ ubf_handle(void *ptr) RUBY_DEBUG_LOG("th:%u\n", rb_th_serial(th)); if (!SetEvent(th->nt->interrupt_event)) { - w32_error("ubf_handle"); + w32_error("ubf_handle"); } } @@ -751,8 +751,8 @@ timer_thread_func(void *dummy) while (WaitForSingleObject(timer_thread.lock, TIME_QUANTUM_USEC/1000) == WAIT_TIMEOUT) { vm->clock++; - ruby_sigchld_handler(vm); /* probably no-op */ - rb_threadptr_check_signal(vm->ractor.main_thread); + ruby_sigchld_handler(vm); /* probably no-op */ + rb_threadptr_check_signal(vm->ractor.main_thread); } RUBY_DEBUG_LOG("%s", "end"); return 0; @@ -774,12 +774,12 @@ static void rb_thread_create_timer_thread(void) { if (timer_thread.id == 0) { - if (!timer_thread.lock) { - timer_thread.lock = CreateEvent(0, TRUE, FALSE, 0); - } + if (!timer_thread.lock) { + timer_thread.lock = CreateEvent(0, TRUE, FALSE, 0); + } timer_thread.id = w32_create_thread(1024 + (USE_RUBY_DEBUG_LOG ? BUFSIZ : 0), timer_thread_func, 0); - w32_resume_thread(timer_thread.id); + w32_resume_thread(timer_thread.id); } } @@ -788,10 +788,10 @@ native_stop_timer_thread(void) { int stopped = --system_working <= 0; if (stopped) { - SetEvent(timer_thread.lock); - native_thread_join(timer_thread.id); - CloseHandle(timer_thread.lock); - timer_thread.lock = 0; + SetEvent(timer_thread.lock); + native_thread_join(timer_thread.id); + CloseHandle(timer_thread.lock); + timer_thread.lock = 0; } return stopped; } @@ -800,8 +800,8 @@ static void native_reset_timer_thread(void) { if (timer_thread.id) { - CloseHandle(timer_thread.id); - timer_thread.id = 0; + CloseHandle(timer_thread.id); + timer_thread.id = 0; } } @@ -816,8 +816,8 @@ LONG WINAPI rb_w32_stack_overflow_handler(struct _EXCEPTION_POINTERS *exception) { if (exception->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW) { - rb_ec_raised_set(GET_EC(), RAISED_STACKOVERFLOW); - raise(SIGSEGV); + rb_ec_raised_set(GET_EC(), RAISED_STACKOVERFLOW); + raise(SIGSEGV); } return EXCEPTION_CONTINUE_SEARCH; } @@ -828,11 +828,11 @@ void ruby_alloca_chkstk(size_t len, void *sp) { if (ruby_stack_length(NULL) * sizeof(VALUE) >= len) { - rb_execution_context_t *ec = GET_EC(); - if (!rb_ec_raised_p(ec, RAISED_STACKOVERFLOW)) { - rb_ec_raised_set(ec, RAISED_STACKOVERFLOW); - rb_exc_raise(sysstack_error); - } + rb_execution_context_t *ec = GET_EC(); + if (!rb_ec_raised_p(ec, RAISED_STACKOVERFLOW)) { + rb_ec_raised_set(ec, RAISED_STACKOVERFLOW); + rb_exc_raise(sysstack_error); + } } } #endif diff --git a/time.c b/time.c index b03baa2c22..a7a4c5dc1a 100644 --- a/time.c +++ b/time.c @@ -121,7 +121,7 @@ static VALUE mulv(VALUE x, VALUE y) { if (FIXNUM_P(x) && FIXNUM_P(y)) { - return rb_fix_mul_fix(x, y); + return rb_fix_mul_fix(x, y); } if (RB_BIGNUM_TYPE_P(x)) return rb_big_mul(x, y); @@ -132,7 +132,7 @@ static VALUE divv(VALUE x, VALUE y) { if (FIXNUM_P(x) && FIXNUM_P(y)) { - return rb_fix_div_fix(x, y); + return rb_fix_div_fix(x, y); } if (RB_BIGNUM_TYPE_P(x)) return rb_big_div(x, y); @@ -143,8 +143,8 @@ static VALUE modv(VALUE x, VALUE y) { if (FIXNUM_P(y)) { - if (FIX2LONG(y) == 0) rb_num_zerodiv(); - if (FIXNUM_P(x)) return rb_fix_mod_fix(x, y); + if (FIX2LONG(y) == 0) rb_num_zerodiv(); + if (FIXNUM_P(x)) return rb_fix_mod_fix(x, y); } if (RB_BIGNUM_TYPE_P(x)) return rb_big_modulo(x, y); return rb_funcall(x, '%', 1, y); @@ -187,17 +187,17 @@ divmodv(VALUE n, VALUE d, VALUE *q, VALUE *r) { VALUE tmp, ary; if (FIXNUM_P(d)) { - if (FIX2LONG(d) == 0) rb_num_zerodiv(); - if (FIXNUM_P(n)) { - rb_fix_divmod_fix(n, d, q, r); - return; - } + if (FIX2LONG(d) == 0) rb_num_zerodiv(); + if (FIXNUM_P(n)) { + rb_fix_divmod_fix(n, d, q, r); + return; + } } tmp = rb_funcall(n, id_divmod, 1, d); ary = rb_check_array_type(tmp); if (NIL_P(ary)) { - rb_raise(rb_eTypeError, "unexpected divmod result: into %"PRIsVALUE, - rb_obj_class(tmp)); + rb_raise(rb_eTypeError, "unexpected divmod result: into %"PRIsVALUE, + rb_obj_class(tmp)); } *q = rb_ary_entry(ary, 0); *r = rb_ary_entry(ary, 1); @@ -399,8 +399,8 @@ wmul(wideval_t wx, wideval_t wy) { #if WIDEVALUE_IS_WIDER if (FIXWV_P(wx) && FIXWV_P(wy)) { - if (!MUL_OVERFLOW_FIXWV_P(FIXWV2WINT(wx), FIXWV2WINT(wy))) - return WINT2WV(FIXWV2WINT(wx) * FIXWV2WINT(wy)); + if (!MUL_OVERFLOW_FIXWV_P(FIXWV2WINT(wx), FIXWV2WINT(wy))) + return WINT2WV(FIXWV2WINT(wx) * FIXWV2WINT(wy)); } #endif return v2w(mulv(w2v(wx), w2v(wy))); @@ -542,8 +542,8 @@ num_exact(VALUE v) case T_NIL: case T_STRING: - rb_raise(rb_eTypeError, "can't convert %"PRIsVALUE" into an exact number", - rb_obj_class(v)); + rb_raise(rb_eTypeError, "can't convert %"PRIsVALUE" into an exact number", + rb_obj_class(v)); } } @@ -702,8 +702,8 @@ rb_localtime_r(const time_t *t, struct tm *result) result = localtime_r(t, result); #else { - struct tm *tmp = localtime(t); - if (tmp) *result = *tmp; + struct tm *tmp = localtime(t); + if (tmp) *result = *tmp; } #endif #if defined(HAVE_MKTIME) && defined(LOCALTIME_OVERFLOW_PROBLEM) @@ -737,7 +737,7 @@ rb_gmtime_r(const time_t *t, struct tm *result) #endif #if defined(HAVE_TIMEGM) && defined(LOCALTIME_OVERFLOW_PROBLEM) if (result && *t != timegm(result)) { - return NULL; + return NULL; } #endif return result; @@ -855,9 +855,9 @@ calc_tm_yday(long tm_year, int tm_mon, int tm_mday) int tm_yday = tm_mday; if (leap_year_p(tm_year_mod400 + 1900)) - tm_yday += leap_year_yday_offset[tm_mon]; + tm_yday += leap_year_yday_offset[tm_mon]; else - tm_yday += common_year_yday_offset[tm_mon]; + tm_yday += common_year_yday_offset[tm_mon]; return tm_yday; } @@ -1601,27 +1601,27 @@ localtime_with_gmtoff_zone(const time_t *t, struct tm *result, long *gmtoff, VAL if (LOCALTIME(t, tm)) { #if defined(HAVE_STRUCT_TM_TM_GMTOFF) - *gmtoff = tm.tm_gmtoff; + *gmtoff = tm.tm_gmtoff; #else - struct tm *u, *l; - long off; - struct tm tmbuf; - l = &tm; - u = GMTIME(t, tmbuf); - if (!u) - return NULL; - if (l->tm_year != u->tm_year) - off = l->tm_year < u->tm_year ? -1 : 1; - else if (l->tm_mon != u->tm_mon) - off = l->tm_mon < u->tm_mon ? -1 : 1; - else if (l->tm_mday != u->tm_mday) - off = l->tm_mday < u->tm_mday ? -1 : 1; - else - off = 0; - off = off * 24 + l->tm_hour - u->tm_hour; - off = off * 60 + l->tm_min - u->tm_min; - off = off * 60 + l->tm_sec - u->tm_sec; - *gmtoff = off; + struct tm *u, *l; + long off; + struct tm tmbuf; + l = &tm; + u = GMTIME(t, tmbuf); + if (!u) + return NULL; + if (l->tm_year != u->tm_year) + off = l->tm_year < u->tm_year ? -1 : 1; + else if (l->tm_mon != u->tm_mon) + off = l->tm_mon < u->tm_mon ? -1 : 1; + else if (l->tm_mday != u->tm_mday) + off = l->tm_mday < u->tm_mday ? -1 : 1; + else + off = 0; + off = off * 24 + l->tm_hour - u->tm_hour; + off = off * 60 + l->tm_min - u->tm_min; + off = off * 60 + l->tm_sec - u->tm_sec; + *gmtoff = off; #endif if (zone) { @@ -1644,7 +1644,7 @@ localtime_with_gmtoff_zone(const time_t *t, struct tm *result, long *gmtoff, VAL } *result = tm; - return result; + return result; } return NULL; } @@ -1692,7 +1692,7 @@ localtimew(wideval_t timew, struct vtm *result) if (!timew_out_of_timet_range(timew)) { time_t t; struct tm tm; - long gmtoff; + long gmtoff; wideval_t timew2; split_second(timew, &timew2, &subsecx); @@ -1769,7 +1769,7 @@ static VALUE time_get_tm(VALUE, struct time_object *); #define MAKE_TM(time, tobj) \ do { \ if ((tobj)->tm_got == 0) { \ - time_get_tm((time), (tobj)); \ + time_get_tm((time), (tobj)); \ } \ } while (0) #define MAKE_TM_ENSURE(time, tobj, cond) \ @@ -1827,7 +1827,7 @@ get_timeval(VALUE obj) struct time_object *tobj; TypedData_Get_Struct(obj, struct time_object, &time_data_type, tobj); if (!TIME_INIT_P(tobj)) { - rb_raise(rb_eTypeError, "uninitialized %"PRIsVALUE, rb_obj_class(obj)); + rb_raise(rb_eTypeError, "uninitialized %"PRIsVALUE, rb_obj_class(obj)); } return tobj; } @@ -1838,7 +1838,7 @@ get_new_timeval(VALUE obj) struct time_object *tobj; TypedData_Get_Struct(obj, struct time_object, &time_data_type, tobj); if (TIME_INIT_P(tobj)) { - rb_raise(rb_eTypeError, "already initialized %"PRIsVALUE, rb_obj_class(obj)); + rb_raise(rb_eTypeError, "already initialized %"PRIsVALUE, rb_obj_class(obj)); } return tobj; } @@ -1898,7 +1898,7 @@ rb_timespec_now(struct timespec *ts) { #ifdef HAVE_CLOCK_GETTIME if (clock_gettime(CLOCK_REALTIME, ts) == -1) { - rb_sys_fail("clock_gettime"); + rb_sys_fail("clock_gettime"); } #else { @@ -2108,8 +2108,8 @@ utc_offset_arg(VALUE arg) const char *s = RSTRING_PTR(tmp), *min = NULL, *sec = NULL; if (!rb_enc_str_asciicompat_p(tmp)) { goto invalid_utc_offset; - } - switch (RSTRING_LEN(tmp)) { + } + switch (RSTRING_LEN(tmp)) { case 1: if (s[0] == 'Z') { return UTC_ZONE; @@ -2148,9 +2148,9 @@ utc_offset_arg(VALUE arg) sec = s+7; min = s+4; break; - default: - goto invalid_utc_offset; - } + default: + goto invalid_utc_offset; + } if (sec) { if (sec == s+7 && *(sec-1) != ':') goto invalid_utc_offset; if (!ISDIGIT(sec[0]) || !ISDIGIT(sec[1])) goto invalid_utc_offset; @@ -2439,23 +2439,23 @@ subsec_normalize(time_t *secp, long *subsecp, const long maxsubsec) if (UNLIKELY(subsec >= maxsubsec)) { /* subsec positive overflow */ sec2 = subsec / maxsubsec; - if (TIMET_MAX - sec2 < sec) { - rb_raise(rb_eRangeError, "out of Time range"); - } - subsec -= sec2 * maxsubsec; - sec += sec2; + if (TIMET_MAX - sec2 < sec) { + rb_raise(rb_eRangeError, "out of Time range"); + } + subsec -= sec2 * maxsubsec; + sec += sec2; } else if (UNLIKELY(subsec < 0)) { /* subsec negative overflow */ - sec2 = NDIV(subsec, maxsubsec); /* negative div */ - if (sec < TIMET_MIN - sec2) { - rb_raise(rb_eRangeError, "out of Time range"); - } - subsec -= sec2 * maxsubsec; - sec += sec2; + sec2 = NDIV(subsec, maxsubsec); /* negative div */ + if (sec < TIMET_MIN - sec2) { + rb_raise(rb_eRangeError, "out of Time range"); + } + subsec -= sec2 * maxsubsec; + sec += sec2; } #ifndef NEGATIVE_TIME_T if (sec < 0) - rb_raise(rb_eArgError, "time must be positive"); + rb_raise(rb_eArgError, "time must be positive"); #endif *secp = sec; *subsecp = subsec; @@ -2505,17 +2505,17 @@ rb_time_timespec_new(const struct timespec *ts, int offset) VALUE time = time_new_timew(rb_cTime, nsec2timew(ts->tv_sec, ts->tv_nsec)); if (-86400 < offset && offset < 86400) { /* fixoff */ - GetTimeval(time, tobj); - TZMODE_SET_FIXOFF(tobj, INT2FIX(offset)); + GetTimeval(time, tobj); + TZMODE_SET_FIXOFF(tobj, INT2FIX(offset)); } else if (offset == INT_MAX) { /* localtime */ } else if (offset == INT_MAX-1) { /* UTC */ - GetTimeval(time, tobj); - TZMODE_SET_UTC(tobj); + GetTimeval(time, tobj); + TZMODE_SET_UTC(tobj); } else { - rb_raise(rb_eArgError, "utc_offset out of range"); + rb_raise(rb_eArgError, "utc_offset out of range"); } return time; @@ -2572,43 +2572,43 @@ time_timespec(VALUE num, int interval) #endif if (FIXNUM_P(num)) { - t.tv_sec = NUM2TIMET(num); + t.tv_sec = NUM2TIMET(num); arg_range_check(t.tv_sec); - t.tv_nsec = 0; + t.tv_nsec = 0; } else if (RB_FLOAT_TYPE_P(num)) { double x = RFLOAT_VALUE(num); arg_range_check(x); { - double f, d; + double f, d; d = modf(x, &f); - if (d >= 0) { - t.tv_nsec = (int)(d*1e9+0.5); - if (t.tv_nsec >= 1000000000) { - t.tv_nsec -= 1000000000; - f += 1; - } - } - else if ((t.tv_nsec = (int)(-d*1e9+0.5)) > 0) { - t.tv_nsec = 1000000000 - t.tv_nsec; - f -= 1; - } - t.tv_sec = (time_t)f; - if (f != t.tv_sec) { + if (d >= 0) { + t.tv_nsec = (int)(d*1e9+0.5); + if (t.tv_nsec >= 1000000000) { + t.tv_nsec -= 1000000000; + f += 1; + } + } + else if ((t.tv_nsec = (int)(-d*1e9+0.5)) > 0) { + t.tv_nsec = 1000000000 - t.tv_nsec; + f -= 1; + } + t.tv_sec = (time_t)f; + if (f != t.tv_sec) { rb_raise(rb_eRangeError, "%f out of Time range", x); - } - } + } + } } else if (RB_BIGNUM_TYPE_P(num)) { - t.tv_sec = NUM2TIMET(num); + t.tv_sec = NUM2TIMET(num); arg_range_check(t.tv_sec); - t.tv_nsec = 0; + t.tv_nsec = 0; } else { - i = INT2FIX(1); - ary = rb_check_funcall(num, id_divmod, 1, &i); - if (ary != Qundef && !NIL_P(ary = rb_check_array_type(ary))) { + i = INT2FIX(1); + ary = rb_check_funcall(num, id_divmod, 1, &i); + if (ary != Qundef && !NIL_P(ary = rb_check_array_type(ary))) { i = rb_ary_entry(ary, 0); f = rb_ary_entry(ary, 1); t.tv_sec = NUM2TIMET(i); @@ -2617,8 +2617,8 @@ time_timespec(VALUE num, int interval) t.tv_nsec = NUM2LONG(f); } else { - rb_raise(rb_eTypeError, "can't convert %"PRIsVALUE" into %s", - rb_obj_class(num), tstr); + rb_raise(rb_eTypeError, "can't convert %"PRIsVALUE" into %s", + rb_obj_class(num), tstr); } } return t; @@ -2652,11 +2652,11 @@ rb_time_timeval(VALUE time) struct timespec ts; if (IsTimeval(time)) { - GetTimeval(time, tobj); + GetTimeval(time, tobj); ts = timew2timespec(tobj->timew); t.tv_sec = (TYPEOF_TIMEVAL_TV_SEC)ts.tv_sec; t.tv_usec = (TYPEOF_TIMEVAL_TV_USEC)(ts.tv_nsec / 1000); - return t; + return t; } return time_timeval(time, FALSE); } @@ -2668,9 +2668,9 @@ rb_time_timespec(VALUE time) struct timespec t; if (IsTimeval(time)) { - GetTimeval(time, tobj); + GetTimeval(time, tobj); t = timew2timespec(tobj->timew); - return t; + return t; } return time_timespec(time, FALSE); } @@ -2712,10 +2712,10 @@ time_s_at(rb_execution_context_t *ec, VALUE klass, VALUE time, VALUE subsec, VAL t = time_new_timew(klass, timew); } else if (IsTimeval(time)) { - struct time_object *tobj, *tobj2; + struct time_object *tobj, *tobj2; GetTimeval(time, tobj); t = time_new_timew(klass, tobj->timew); - GetTimeval(t, tobj2); + GetTimeval(t, tobj2); TZMODE_COPY(tobj2, tobj); } else { @@ -2744,7 +2744,7 @@ static int obj2int(VALUE obj) { if (RB_TYPE_P(obj, T_STRING)) { - obj = rb_str_to_inum(obj, 10, TRUE); + obj = rb_str_to_inum(obj, 10, TRUE); } return NUM2INT(obj); @@ -2758,7 +2758,7 @@ obj2ubits(VALUE obj, unsigned int bits) unsigned int rv = (unsigned int)obj2int(obj); if ((rv & usable_mask) != rv) - rb_raise(rb_eArgError, "argument out of range"); + rb_raise(rb_eArgError, "argument out of range"); return (uint32_t)rv; } @@ -2766,7 +2766,7 @@ static VALUE obj2vint(VALUE obj) { if (RB_TYPE_P(obj, T_STRING)) { - obj = rb_str_to_inum(obj, 10, TRUE); + obj = rb_str_to_inum(obj, 10, TRUE); } else { obj = rb_to_int(obj); @@ -2781,7 +2781,7 @@ obj2subsecx(VALUE obj, VALUE *subsecx) VALUE subsec; if (RB_TYPE_P(obj, T_STRING)) { - obj = rb_str_to_inum(obj, 10, TRUE); + obj = rb_str_to_inum(obj, 10, TRUE); *subsecx = INT2FIX(0); } else { @@ -2795,7 +2795,7 @@ static VALUE usec2subsecx(VALUE obj) { if (RB_TYPE_P(obj, T_STRING)) { - obj = rb_str_to_inum(obj, 10, TRUE); + obj = rb_str_to_inum(obj, 10, TRUE); } return mulquov(num_exact(obj), INT2FIX(TIME_SCALE), INT2FIX(1000000)); @@ -2832,7 +2832,7 @@ static VALUE validate_utc_offset(VALUE utc_offset) { if (le(utc_offset, INT2FIX(-86400)) || ge(utc_offset, INT2FIX(86400))) - rb_raise(rb_eArgError, "utc_offset out of range"); + rb_raise(rb_eArgError, "utc_offset out of range"); return utc_offset; } @@ -2855,7 +2855,7 @@ validate_vtm(struct vtm *vtm) validate_vtm_range(min, 0, (vtm->hour == 24 ? 0 : 59)); validate_vtm_range(sec, 0, (vtm->hour == 24 ? 0 : 60)); if (lt(vtm->subsecx, INT2FIX(0)) || ge(vtm->subsecx, INT2FIX(TIME_SCALE))) - rb_raise(rb_eArgError, "subsecx out of range"); + rb_raise(rb_eArgError, "subsecx out of range"); if (!NIL_P(vtm->utc_offset)) validate_utc_offset(vtm->utc_offset); #undef validate_vtm_range } @@ -2880,21 +2880,21 @@ time_arg(int argc, const VALUE *argv, struct vtm *vtm) vtm->zone = str_empty; if (argc == 10) { - v[0] = argv[5]; - v[1] = argv[4]; - v[2] = argv[3]; - v[3] = argv[2]; - v[4] = argv[1]; - v[5] = argv[0]; - v[6] = Qnil; - vtm->isdst = RTEST(argv[8]) ? 1 : 0; + v[0] = argv[5]; + v[1] = argv[4]; + v[2] = argv[3]; + v[3] = argv[2]; + v[4] = argv[1]; + v[5] = argv[0]; + v[6] = Qnil; + vtm->isdst = RTEST(argv[8]) ? 1 : 0; } else { - rb_scan_args(argc, argv, "17", &v[0],&v[1],&v[2],&v[3],&v[4],&v[5],&v[6],&v[7]); - /* v[6] may be usec or zone (parsedate) */ - /* v[7] is wday (parsedate; ignored) */ - vtm->wday = VTM_WDAY_INITVAL; - vtm->isdst = VTM_ISDST_INITVAL; + rb_scan_args(argc, argv, "17", &v[0],&v[1],&v[2],&v[3],&v[4],&v[5],&v[6],&v[7]); + /* v[6] may be usec or zone (parsedate) */ + /* v[7] is wday (parsedate; ignored) */ + vtm->wday = VTM_WDAY_INITVAL; + vtm->isdst = VTM_ISDST_INITVAL; } vtm->year = obj2vint(v[0]); @@ -2907,10 +2907,10 @@ time_arg(int argc, const VALUE *argv, struct vtm *vtm) } if (NIL_P(v[2])) { - vtm->mday = 1; + vtm->mday = 1; } else { - vtm->mday = obj2ubits(v[2], 5); + vtm->mday = obj2ubits(v[2], 5); } /* normalize month-mday */ @@ -2945,7 +2945,7 @@ time_arg(int argc, const VALUE *argv, struct vtm *vtm) subsecx = usec2subsecx(v[6]); } else { - /* when argc == 8, v[6] is timezone, but ignored */ + /* when argc == 8, v[6] is timezone, but ignored */ if (NIL_P(v[5])) { vtm->sec = 0; } @@ -2987,11 +2987,11 @@ timegm_noleapsecond(struct tm *tm) * ((tm_year-1)/100)*86400 + ((tm_year+299)/400)*86400 */ return tm->tm_sec + tm->tm_min*60 + tm->tm_hour*3600 + - (time_t)(tm_yday + - (tm_year-70)*365 + - DIV(tm_year-69,4) - - DIV(tm_year-1,100) + - DIV(tm_year+299,400))*86400; + (time_t)(tm_yday + + (tm_year-70)*365 + + DIV(tm_year-69,4) - + DIV(tm_year-1,100) + + DIV(tm_year+299,400))*86400; } #if 0 @@ -3059,80 +3059,80 @@ find_time_t(struct tm *tptr, int utc_p, time_t *tp) tm0 = *tptr; if (tm0.tm_mon < 0) { - tm0.tm_mon = 0; - tm0.tm_mday = 1; - tm0.tm_hour = 0; - tm0.tm_min = 0; - tm0.tm_sec = 0; + tm0.tm_mon = 0; + tm0.tm_mday = 1; + tm0.tm_hour = 0; + tm0.tm_min = 0; + tm0.tm_sec = 0; } else if (11 < tm0.tm_mon) { - tm0.tm_mon = 11; - tm0.tm_mday = 31; - tm0.tm_hour = 23; - tm0.tm_min = 59; - tm0.tm_sec = 60; + tm0.tm_mon = 11; + tm0.tm_mday = 31; + tm0.tm_hour = 23; + tm0.tm_min = 59; + tm0.tm_sec = 60; } else if (tm0.tm_mday < 1) { - tm0.tm_mday = 1; - tm0.tm_hour = 0; - tm0.tm_min = 0; - tm0.tm_sec = 0; + tm0.tm_mday = 1; + tm0.tm_hour = 0; + tm0.tm_min = 0; + tm0.tm_sec = 0; } else if ((d = days_in_month_in(1900 + tm0.tm_year)[tm0.tm_mon]) < tm0.tm_mday) { - tm0.tm_mday = d; - tm0.tm_hour = 23; - tm0.tm_min = 59; - tm0.tm_sec = 60; + tm0.tm_mday = d; + tm0.tm_hour = 23; + tm0.tm_min = 59; + tm0.tm_sec = 60; } else if (tm0.tm_hour < 0) { - tm0.tm_hour = 0; - tm0.tm_min = 0; - tm0.tm_sec = 0; + tm0.tm_hour = 0; + tm0.tm_min = 0; + tm0.tm_sec = 0; } else if (23 < tm0.tm_hour) { - tm0.tm_hour = 23; - tm0.tm_min = 59; - tm0.tm_sec = 60; + tm0.tm_hour = 23; + tm0.tm_min = 59; + tm0.tm_sec = 60; } else if (tm0.tm_min < 0) { - tm0.tm_min = 0; - tm0.tm_sec = 0; + tm0.tm_min = 0; + tm0.tm_sec = 0; } else if (59 < tm0.tm_min) { - tm0.tm_min = 59; - tm0.tm_sec = 60; + tm0.tm_min = 59; + tm0.tm_sec = 60; } else if (tm0.tm_sec < 0) { - tm0.tm_sec = 0; + tm0.tm_sec = 0; } else if (60 < tm0.tm_sec) { - tm0.tm_sec = 60; + tm0.tm_sec = 60; } DEBUG_REPORT_GUESSRANGE; guess0 = guess = timegm_noleapsecond(&tm0); tm = GUESS(&guess); if (tm) { - d = tmcmp(tptr, tm); - if (d == 0) { goto found; } - if (d < 0) { - guess_hi = guess; - guess -= 24 * 60 * 60; - } - else { - guess_lo = guess; - guess += 24 * 60 * 60; - } + d = tmcmp(tptr, tm); + if (d == 0) { goto found; } + if (d < 0) { + guess_hi = guess; + guess -= 24 * 60 * 60; + } + else { + guess_lo = guess; + guess += 24 * 60 * 60; + } DEBUG_REPORT_GUESSRANGE; - if (guess_lo < guess && guess < guess_hi && (tm = GUESS(&guess)) != NULL) { - d = tmcmp(tptr, tm); - if (d == 0) { goto found; } - if (d < 0) - guess_hi = guess; - else - guess_lo = guess; + if (guess_lo < guess && guess < guess_hi && (tm = GUESS(&guess)) != NULL) { + d = tmcmp(tptr, tm); + if (d == 0) { goto found; } + if (d < 0) + guess_hi = guess; + else + guess_lo = guess; DEBUG_REPORT_GUESSRANGE; - } + } } tm = GUESS(&guess_lo); @@ -3195,10 +3195,10 @@ find_time_t(struct tm *tptr, int utc_p, time_t *tp) } } - tm = GUESS(&guess); - if (!tm) goto error; + tm = GUESS(&guess); + if (!tm) goto error; - d = tmcmp(tptr, tm); + d = tmcmp(tptr, tm); if (d < 0) { guess_hi = guess; @@ -3310,19 +3310,19 @@ static int vtmcmp(struct vtm *a, struct vtm *b) { if (ne(a->year, b->year)) - return lt(a->year, b->year) ? -1 : 1; + return lt(a->year, b->year) ? -1 : 1; else if (a->mon != b->mon) - return a->mon < b->mon ? -1 : 1; + return a->mon < b->mon ? -1 : 1; else if (a->mday != b->mday) - return a->mday < b->mday ? -1 : 1; + return a->mday < b->mday ? -1 : 1; else if (a->hour != b->hour) - return a->hour < b->hour ? -1 : 1; + return a->hour < b->hour ? -1 : 1; else if (a->min != b->min) - return a->min < b->min ? -1 : 1; + return a->min < b->min ? -1 : 1; else if (a->sec != b->sec) - return a->sec < b->sec ? -1 : 1; + return a->sec < b->sec ? -1 : 1; else if (ne(a->subsecx, b->subsecx)) - return lt(a->subsecx, b->subsecx) ? -1 : 1; + return lt(a->subsecx, b->subsecx) ? -1 : 1; else return 0; } @@ -3331,17 +3331,17 @@ static int tmcmp(struct tm *a, struct tm *b) { if (a->tm_year != b->tm_year) - return a->tm_year < b->tm_year ? -1 : 1; + return a->tm_year < b->tm_year ? -1 : 1; else if (a->tm_mon != b->tm_mon) - return a->tm_mon < b->tm_mon ? -1 : 1; + return a->tm_mon < b->tm_mon ? -1 : 1; else if (a->tm_mday != b->tm_mday) - return a->tm_mday < b->tm_mday ? -1 : 1; + return a->tm_mday < b->tm_mday ? -1 : 1; else if (a->tm_hour != b->tm_hour) - return a->tm_hour < b->tm_hour ? -1 : 1; + return a->tm_hour < b->tm_hour ? -1 : 1; else if (a->tm_min != b->tm_min) - return a->tm_min < b->tm_min ? -1 : 1; + return a->tm_min < b->tm_min ? -1 : 1; else if (a->tm_sec != b->tm_sec) - return a->tm_sec < b->tm_sec ? -1 : 1; + return a->tm_sec < b->tm_sec ? -1 : 1; else return 0; } @@ -3625,11 +3625,11 @@ time_cmp(VALUE time1, VALUE time2) GetTimeval(time1, tobj1); if (IsTimeval(time2)) { - GetTimeval(time2, tobj2); - n = wcmp(tobj1->timew, tobj2->timew); + GetTimeval(time2, tobj2); + n = wcmp(tobj1->timew, tobj2->timew); } else { - return rb_invcmp(time1, time2); + return rb_invcmp(time1, time2); } if (n == 0) return INT2FIX(0); if (n > 0) return INT2FIX(1); @@ -3651,7 +3651,7 @@ time_eql(VALUE time1, VALUE time2) GetTimeval(time1, tobj1); if (IsTimeval(time2)) { - GetTimeval(time2, tobj2); + GetTimeval(time2, tobj2); return rb_equal(w2v(tobj1->timew), w2v(tobj2->timew)); } return Qfalse; @@ -3733,11 +3733,11 @@ time_localtime(VALUE time) GetTimeval(time, tobj); if (TZMODE_LOCALTIME_P(tobj)) { - if (tobj->tm_got) - return time; + if (tobj->tm_got) + return time; } else { - time_modify(time); + time_modify(time); } zone = tobj->vtm.zone; @@ -3746,7 +3746,7 @@ time_localtime(VALUE time) } if (!localtimew(tobj->timew, &vtm)) - rb_raise(rb_eArgError, "localtime error"); + rb_raise(rb_eArgError, "localtime error"); tobj->vtm = vtm; tobj->tm_got = 1; @@ -3836,11 +3836,11 @@ time_gmtime(VALUE time) GetTimeval(time, tobj); if (TZMODE_UTC_P(tobj)) { - if (tobj->tm_got) - return time; + if (tobj->tm_got) + return time; } else { - time_modify(time); + time_modify(time); } vtm.zone = str_utc; @@ -4116,7 +4116,7 @@ time_plus(VALUE time1, VALUE time2) GetTimeval(time1, tobj); if (IsTimeval(time2)) { - rb_raise(rb_eTypeError, "time + time?"); + rb_raise(rb_eTypeError, "time + time?"); } return time_add(tobj, time1, time2, 1); } @@ -4143,9 +4143,9 @@ time_minus(VALUE time1, VALUE time2) GetTimeval(time1, tobj); if (IsTimeval(time2)) { - struct time_object *tobj2; + struct time_object *tobj2; - GetTimeval(time2, tobj2); + GetTimeval(time2, tobj2); return rb_Float(rb_time_unmagnify_to_float(wsub(tobj->timew, tobj2->timew))); } return time_add(tobj, time1, time2, -1); @@ -4662,7 +4662,7 @@ time_zone(VALUE time) MAKE_TM(time, tobj); if (TZMODE_UTC_P(tobj)) { - return rb_usascii_str_new_cstr("UTC"); + return rb_usascii_str_new_cstr("UTC"); } zone = tobj->vtm.zone; if (NIL_P(zone)) @@ -4696,11 +4696,11 @@ rb_time_utc_offset(VALUE time) GetTimeval(time, tobj); if (TZMODE_UTC_P(tobj)) { - return INT2FIX(0); + return INT2FIX(0); } else { - MAKE_TM(time, tobj); - return tobj->vtm.utc_offset; + MAKE_TM(time, tobj); + return tobj->vtm.utc_offset; } } @@ -4729,16 +4729,16 @@ time_to_a(VALUE time) GetTimeval(time, tobj); MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0); return rb_ary_new3(10, - INT2FIX(tobj->vtm.sec), - INT2FIX(tobj->vtm.min), - INT2FIX(tobj->vtm.hour), - INT2FIX(tobj->vtm.mday), - INT2FIX(tobj->vtm.mon), - tobj->vtm.year, - INT2FIX(tobj->vtm.wday), - INT2FIX(tobj->vtm.yday), - RBOOL(tobj->vtm.isdst), - time_zone(time)); + INT2FIX(tobj->vtm.sec), + INT2FIX(tobj->vtm.min), + INT2FIX(tobj->vtm.hour), + INT2FIX(tobj->vtm.mday), + INT2FIX(tobj->vtm.mon), + tobj->vtm.year, + INT2FIX(tobj->vtm.wday), + INT2FIX(tobj->vtm.yday), + RBOOL(tobj->vtm.isdst), + time_zone(time)); } static VALUE @@ -4749,7 +4749,7 @@ rb_strftime_alloc(const char *format, size_t format_len, rb_encoding *enc, struct timespec ts; if (!timew2timespec_exact(timew, &ts)) - timev = w2v(rb_time_unmagnify(timew)); + timev = w2v(rb_time_unmagnify(timew)); if (NIL_P(timev)) { return rb_strftime_timespec(format, format_len, enc, time, vtm, &ts, gmt); @@ -4972,22 +4972,22 @@ time_strftime(VALUE time, VALUE format) MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0); StringValue(format); if (!rb_enc_str_asciicompat_p(format)) { - rb_raise(rb_eArgError, "format should have ASCII compatible encoding"); + rb_raise(rb_eArgError, "format should have ASCII compatible encoding"); } tmp = rb_str_tmp_frozen_acquire(format); fmt = RSTRING_PTR(tmp); len = RSTRING_LEN(tmp); enc = rb_enc_get(format); if (len == 0) { - rb_warning("strftime called with empty format string"); - return rb_enc_str_new(0, 0, enc); + rb_warning("strftime called with empty format string"); + return rb_enc_str_new(0, 0, enc); } else { VALUE str = rb_strftime_alloc(fmt, len, enc, time, &tobj->vtm, tobj->timew, - TZMODE_UTC_P(tobj)); - rb_str_tmp_frozen_release(format, tmp); - if (!str) rb_raise(rb_eArgError, "invalid format: %"PRIsVALUE, format); - return str; + TZMODE_UTC_P(tobj)); + rb_str_tmp_frozen_release(format, tmp); + if (!str) rb_raise(rb_eArgError, "invalid format: %"PRIsVALUE, format); + return str; } } @@ -5050,22 +5050,22 @@ time_mdump(VALUE time) nano = addv(LONG2FIX(nsec), subnano); p = 0x1UL << 31 | /* 1 */ - TZMODE_UTC_P(tobj) << 30 | /* 1 */ - (year-1900) << 14 | /* 16 */ - (vtm.mon-1) << 10 | /* 4 */ - vtm.mday << 5 | /* 5 */ - vtm.hour; /* 5 */ + TZMODE_UTC_P(tobj) << 30 | /* 1 */ + (year-1900) << 14 | /* 16 */ + (vtm.mon-1) << 10 | /* 4 */ + vtm.mday << 5 | /* 5 */ + vtm.hour; /* 5 */ s = (unsigned long)vtm.min << 26 | /* 6 */ - vtm.sec << 20 | /* 6 */ - usec; /* 20 */ + vtm.sec << 20 | /* 6 */ + usec; /* 20 */ for (i=0; i<4; i++) { - buf[i] = (unsigned char)p; - p = RSHIFT(p, 8); + buf[i] = (unsigned char)p; + p = RSHIFT(p, 8); } for (i=4; i<8; i++) { - buf[i] = (unsigned char)s; - s = RSHIFT(s, 8); + buf[i] = (unsigned char)s; + s = RSHIFT(s, 8); } if (!NIL_P(year_extend)) { @@ -5123,11 +5123,11 @@ time_mdump(VALUE time) rb_ivar_set(str, id_submicro, rb_str_new(buf, len)); } if (!TZMODE_UTC_P(tobj)) { - VALUE off = rb_time_utc_offset(time), div, mod; - divmodv(off, INT2FIX(1), &div, &mod); - if (rb_equal(mod, INT2FIX(0))) - off = rb_Integer(div); - rb_ivar_set(str, id_offset, off); + VALUE off = rb_time_utc_offset(time), div, mod; + divmodv(off, INT2FIX(1), &div, &mod); + if (rb_equal(mod, INT2FIX(0))) + off = rb_Integer(div); + rb_ivar_set(str, id_offset, off); } zone = tobj->vtm.zone; if (maybe_tzobj_p(zone)) { @@ -5191,7 +5191,7 @@ time_mload(VALUE time, VALUE str) #define get_attr(attr, iffound) \ attr = rb_attr_delete(str, id_##attr); \ if (!NIL_P(attr)) { \ - iffound; \ + iffound; \ } get_attr(nano_num, {}); @@ -5213,23 +5213,23 @@ time_mload(VALUE time, VALUE str) p = s = 0; for (i=0; i<4; i++) { - p |= (unsigned long)buf[i]<<(8*i); + p |= (unsigned long)buf[i]<<(8*i); } for (i=4; i<8; i++) { - s |= (unsigned long)buf[i]<<(8*(i-4)); + s |= (unsigned long)buf[i]<<(8*(i-4)); } if ((p & (1UL<<31)) == 0) { gmt = 0; - offset = Qnil; - sec = p; - usec = s; + offset = Qnil; + sec = p; + usec = s; nsec = usec * 1000; timew = wadd(rb_time_magnify(TIMET2WV(sec)), wmulquoll(WINT2FIXWV(usec), TIME_SCALE, 1000000)); } else { - p &= ~(1UL<<31); - gmt = (int)((p >> 30) & 0x1); + p &= ~(1UL<<31); + gmt = (int)((p >> 30) & 0x1); if (NIL_P(year)) { year = INT2FIX(((int)(p >> 14) & 0xffff) + 1900); @@ -5256,17 +5256,17 @@ time_mload(VALUE time, VALUE str) year = addv(year, LONG2FIX(1)); } vtm.year = year; - vtm.mon = mon + 1; - vtm.mday = (int)(p >> 5) & 0x1f; - vtm.hour = (int) p & 0x1f; - vtm.min = (int)(s >> 26) & 0x3f; - vtm.sec = (int)(s >> 20) & 0x3f; + vtm.mon = mon + 1; + vtm.mday = (int)(p >> 5) & 0x1f; + vtm.hour = (int) p & 0x1f; + vtm.min = (int)(s >> 26) & 0x3f; + vtm.sec = (int)(s >> 20) & 0x3f; vtm.utc_offset = INT2FIX(0); - vtm.yday = vtm.wday = 0; - vtm.isdst = 0; - vtm.zone = str_empty; + vtm.yday = vtm.wday = 0; + vtm.isdst = 0; + vtm.zone = str_empty; - usec = (long)(s & 0xfffff); + usec = (long)(s & 0xfffff); nsec = usec * 1000; @@ -5303,15 +5303,15 @@ end_submicro: ; tobj->tm_got = 0; tobj->timew = timew; if (gmt) { - TZMODE_SET_UTC(tobj); + TZMODE_SET_UTC(tobj); } else if (!NIL_P(offset)) { - time_set_utc_offset(time, offset); - time_fixoff(time); + time_set_utc_offset(time, offset); + time_fixoff(time); } if (!NIL_P(zone)) { zone = mload_zone(time, zone); - tobj->vtm.zone = zone; + tobj->vtm.zone = zone; zone_localtime(zone, time); } diff --git a/tool/ruby_vm/views/optinsn.inc.erb b/tool/ruby_vm/views/optinsn.inc.erb index 676f1edaba..0190f9e07a 100644 --- a/tool/ruby_vm/views/optinsn.inc.erb +++ b/tool/ruby_vm/views/optinsn.inc.erb @@ -55,12 +55,12 @@ rb_insn_unified_local_var_level(VALUE insn) /* optimize rule */ switch (insn) { default: - return -1; /* do nothing */; + return -1; /* do nothing */; % RubyVM::OperandsUnifications.each_group do |orig, unifs| % unifs.each do|insn| case <%= insn.bin %>: % insn.spec.map{|(var,val)|val}.reject{|i| i == '*' }.each do |val| - return <%= val %>; + return <%= val %>; % break % end % end diff --git a/transcode.c b/transcode.c index e6e585e901..939e9567f9 100644 --- a/transcode.c +++ b/transcode.c @@ -229,8 +229,8 @@ rb_register_transcoder(const rb_transcoder *tr) entry = make_transcoder_entry(sname, dname); if (entry->transcoder) { - rb_raise(rb_eArgError, "transcoder from %s to %s has been already registered", - sname, dname); + rb_raise(rb_eArgError, "transcoder from %s to %s has been already registered", + sname, dname); } entry->transcoder = tr; @@ -251,7 +251,7 @@ void rb_declare_transcoder(const char *enc1, const char *enc2, const char *lib) { if (!lib) { - rb_raise(rb_eArgError, "invalid library name - (null)"); + rb_raise(rb_eArgError, "invalid library name - (null)"); } declare_transcoder(enc1, enc2, lib); } @@ -535,7 +535,7 @@ transcode_restartable0(const unsigned char **in_pos, unsigned char **out_pos, while (1) { inchar_start = in_p; tc->recognized_len = 0; - next_table = tr->conv_tree_start; + next_table = tr->conv_tree_start; SUSPEND_AFTER_OUTPUT(24); @@ -555,7 +555,7 @@ transcode_restartable0(const unsigned char **in_pos, unsigned char **out_pos, #define BL_OFFSET(byte) (BL_BASE[2+(byte)-BL_MIN_BYTE]) #define BL_ACTION(byte) (BL_INFO[BL_OFFSET((byte))]) - next_byte = (unsigned char)*in_p++; + next_byte = (unsigned char)*in_p++; follow_byte: if (next_byte < BL_MIN_BYTE || BL_MAX_BYTE < next_byte) next_info = INVALID; @@ -563,8 +563,8 @@ transcode_restartable0(const unsigned char **in_pos, unsigned char **out_pos, next_info = (VALUE)BL_ACTION(next_byte); } follow_info: - switch (next_info & 0x1F) { - case NOMAP: + switch (next_info & 0x1F) { + case NOMAP: { const unsigned char *p = inchar_start; writebuf_off = 0; @@ -579,43 +579,43 @@ transcode_restartable0(const unsigned char **in_pos, unsigned char **out_pos, } } continue; - case 0x00: case 0x04: case 0x08: case 0x0C: - case 0x10: case 0x14: case 0x18: case 0x1C: + case 0x00: case 0x04: case 0x08: case 0x0C: + case 0x10: case 0x14: case 0x18: case 0x1C: SUSPEND_AFTER_OUTPUT(25); - while (in_p >= in_stop) { + while (in_p >= in_stop) { if (!(opt & ECONV_PARTIAL_INPUT)) goto incomplete; SUSPEND(econv_source_buffer_empty, 5); - } - next_byte = (unsigned char)*in_p++; - next_table = (unsigned int)next_info; - goto follow_byte; - case ZERObt: /* drop input */ - continue; - case ONEbt: + } + next_byte = (unsigned char)*in_p++; + next_table = (unsigned int)next_info; + goto follow_byte; + case ZERObt: /* drop input */ + continue; + case ONEbt: SUSPEND_OBUF(9); *out_p++ = getBT1(next_info); - continue; - case TWObt: + continue; + case TWObt: SUSPEND_OBUF(10); *out_p++ = getBT1(next_info); SUSPEND_OBUF(21); *out_p++ = getBT2(next_info); - continue; - case THREEbt: + continue; + case THREEbt: SUSPEND_OBUF(11); *out_p++ = getBT1(next_info); SUSPEND_OBUF(15); *out_p++ = getBT2(next_info); SUSPEND_OBUF(16); *out_p++ = getBT3(next_info); - continue; - case FOURbt: + continue; + case FOURbt: SUSPEND_OBUF(12); *out_p++ = getBT0(next_info); SUSPEND_OBUF(17); *out_p++ = getBT1(next_info); SUSPEND_OBUF(18); *out_p++ = getBT2(next_info); SUSPEND_OBUF(19); *out_p++ = getBT3(next_info); - continue; - case GB4bt: + continue; + case GB4bt: SUSPEND_OBUF(29); *out_p++ = getGB4bt0(next_info); SUSPEND_OBUF(30); *out_p++ = getGB4bt1(next_info); SUSPEND_OBUF(31); *out_p++ = getGB4bt2(next_info); SUSPEND_OBUF(32); *out_p++ = getGB4bt3(next_info); - continue; + continue; case STR1: tc->output_index = 0; while (tc->output_index < STR1_LENGTH(BYTE_ADDR(STR1_BYTEINDEX(next_info)))) { @@ -623,10 +623,10 @@ transcode_restartable0(const unsigned char **in_pos, unsigned char **out_pos, tc->output_index++; } continue; - case FUNii: - next_info = (VALUE)(*tr->func_ii)(TRANSCODING_STATE(tc), next_info); - goto follow_info; - case FUNsi: + case FUNii: + next_info = (VALUE)(*tr->func_ii)(TRANSCODING_STATE(tc), next_info); + goto follow_info; + case FUNsi: { const unsigned char *char_start; size_t char_len; @@ -634,7 +634,7 @@ transcode_restartable0(const unsigned char **in_pos, unsigned char **out_pos, next_info = (VALUE)(*tr->func_si)(TRANSCODING_STATE(tc), char_start, (size_t)char_len); goto follow_info; } - case FUNio: + case FUNio: SUSPEND_OBUF(13); if (tr->max_output <= out_stop - out_p) out_p += tr->func_io(TRANSCODING_STATE(tc), @@ -649,8 +649,8 @@ transcode_restartable0(const unsigned char **in_pos, unsigned char **out_pos, *out_p++ = TRANSCODING_WRITEBUF(tc)[writebuf_off++]; } } - break; - case FUNso: + break; + case FUNso: { const unsigned char *char_start; size_t char_len; @@ -698,7 +698,7 @@ transcode_restartable0(const unsigned char **in_pos, unsigned char **out_pos, } break; } - case INVALID: + case INVALID: if (tc->recognized_len + (in_p - inchar_start) <= unitlen) { if (tc->recognized_len + (in_p - inchar_start) < unitlen) SUSPEND_AFTER_OUTPUT(26); @@ -721,12 +721,12 @@ transcode_restartable0(const unsigned char **in_pos, unsigned char **out_pos, readagain_len = invalid_len - discard_len; } goto invalid; - case UNDEF: - goto undef; - default: - rb_raise(rb_eRuntimeError, "unknown transcoding instruction"); - } - continue; + case UNDEF: + goto undef; + default: + rb_raise(rb_eRuntimeError, "unknown transcoding instruction"); + } + continue; invalid: SUSPEND(econv_invalid_byte_sequence, 1); @@ -856,13 +856,13 @@ rb_transcoding_memsize(rb_transcoding *tc) const rb_transcoder *tr = tc->transcoder; if (TRANSCODING_STATE_EMBED_MAX < tr->state_size) { - size += tr->state_size; + size += tr->state_size; } if ((int)sizeof(tc->readbuf.ary) < tr->max_input) { - size += tr->max_input; + size += tr->max_input; } if ((int)sizeof(tc->writebuf.ary) < tr->max_output) { - size += tr->max_output; + size += tr->max_output; } return size; } @@ -1002,7 +1002,7 @@ rb_econv_open0(const char *sname, const char *dname, int ecflags) if (*sname == '\0' && *dname == '\0') { num_trans = 0; entries = NULL; - sname = dname = ""; + sname = dname = ""; } else { struct trans_open_t toarg; @@ -1040,7 +1040,7 @@ decorator_names(int ecflags, const char **decorators_ret) case ECONV_CRLF_NEWLINE_DECORATOR: case ECONV_CR_NEWLINE_DECORATOR: case 0: - break; + break; default: return -1; } @@ -1473,22 +1473,22 @@ rb_econv_convert(rb_econv_t *ec, if (ret == econv_invalid_byte_sequence || ret == econv_incomplete_input) { - /* deal with invalid byte sequence */ - /* todo: add more alternative behaviors */ + /* deal with invalid byte sequence */ + /* todo: add more alternative behaviors */ switch (ec->flags & ECONV_INVALID_MASK) { case ECONV_INVALID_REPLACE: - if (output_replacement_character(ec) == 0) + if (output_replacement_character(ec) == 0) goto resume; - } + } } if (ret == econv_undefined_conversion) { - /* valid character in source encoding - * but no related character(s) in destination encoding */ - /* todo: add more alternative behaviors */ + /* valid character in source encoding + * but no related character(s) in destination encoding */ + /* todo: add more alternative behaviors */ switch (ec->flags & ECONV_UNDEF_MASK) { case ECONV_UNDEF_REPLACE: - if (output_replacement_character(ec) == 0) + if (output_replacement_character(ec) == 0) goto resume; break; @@ -1726,14 +1726,14 @@ rb_econv_memsize(rb_econv_t *ec) int i; if (ec->replacement_allocated) { - size += ec->replacement_len; + size += ec->replacement_len; } for (i = 0; i < ec->num_trans; i++) { - size += rb_transcoding_memsize(ec->elems[i].tc); + size += rb_transcoding_memsize(ec->elems[i].tc); - if (ec->elems[i].out_buf_start) { + if (ec->elems[i].out_buf_start) { size += ec->elems[i].out_buf_end - ec->elems[i].out_buf_start; - } + } } size += ec->in_buf_end - ec->in_buf_start; size += sizeof(rb_econv_elem_t) * ec->num_allocated; @@ -1948,30 +1948,30 @@ rb_econv_binmode(rb_econv_t *ec) switch (ec->flags & ECONV_NEWLINE_DECORATOR_MASK) { case ECONV_UNIVERSAL_NEWLINE_DECORATOR: - dname = "universal_newline"; - break; + dname = "universal_newline"; + break; case ECONV_CRLF_NEWLINE_DECORATOR: - dname = "crlf_newline"; - break; + dname = "crlf_newline"; + break; case ECONV_CR_NEWLINE_DECORATOR: - dname = "cr_newline"; - break; + dname = "cr_newline"; + break; } if (dname) { const rb_transcoder *transcoder = get_transcoder_entry("", dname)->transcoder; int num_trans = ec->num_trans; - int i, j = 0; + int i, j = 0; - for (i=0; i < num_trans; i++) { - if (transcoder == ec->elems[i].tc->transcoder) { - rb_transcoding_close(ec->elems[i].tc); - xfree(ec->elems[i].out_buf_start); - ec->num_trans--; - } - else - ec->elems[j++] = ec->elems[i]; - } + for (i=0; i < num_trans; i++) { + if (transcoder == ec->elems[i].tc->transcoder) { + rb_transcoding_close(ec->elems[i].tc); + xfree(ec->elems[i].out_buf_start); + ec->num_trans--; + } + else + ec->elems[j++] = ec->elems[i]; + } } ec->flags &= ~ECONV_NEWLINE_DECORATOR_MASK; @@ -2267,7 +2267,7 @@ aref_fallback(VALUE fallback, VALUE c) static void transcode_loop(const unsigned char **in_pos, unsigned char **out_pos, - const unsigned char *in_stop, unsigned char *out_stop, + const unsigned char *in_stop, unsigned char *out_stop, VALUE destination, unsigned char *(*resize_destination)(VALUE, size_t, size_t), const char *src_encoding, @@ -2289,19 +2289,19 @@ transcode_loop(const unsigned char **in_pos, unsigned char **out_pos, rb_exc_raise(rb_econv_open_exc(src_encoding, dst_encoding, ecflags)); if (!NIL_P(ecopts) && RB_TYPE_P(ecopts, T_HASH)) { - fallback = rb_hash_aref(ecopts, sym_fallback); - if (RB_TYPE_P(fallback, T_HASH)) { - fallback_func = hash_fallback; - } - else if (rb_obj_is_proc(fallback)) { - fallback_func = proc_fallback; - } - else if (rb_obj_is_method(fallback)) { - fallback_func = method_fallback; - } - else { - fallback_func = aref_fallback; - } + fallback = rb_hash_aref(ecopts, sym_fallback); + if (RB_TYPE_P(fallback, T_HASH)) { + fallback_func = hash_fallback; + } + else if (rb_obj_is_proc(fallback)) { + fallback_func = proc_fallback; + } + else if (rb_obj_is_method(fallback)) { + fallback_func = method_fallback; + } + else { + fallback_func = aref_fallback; + } } last_tc = ec->last_tc; max_output = last_tc ? last_tc->transcoder->max_output : 1; @@ -2310,20 +2310,20 @@ transcode_loop(const unsigned char **in_pos, unsigned char **out_pos, ret = rb_econv_convert(ec, in_pos, in_stop, out_pos, out_stop, 0); if (!NIL_P(fallback) && ret == econv_undefined_conversion) { - VALUE rep = rb_enc_str_new( - (const char *)ec->last_error.error_bytes_start, - ec->last_error.error_bytes_len, - rb_enc_find(ec->last_error.source_encoding)); - rep = (*fallback_func)(fallback, rep); - if (rep != Qundef && !NIL_P(rep)) { - StringValue(rep); - ret = rb_econv_insert_output(ec, (const unsigned char *)RSTRING_PTR(rep), - RSTRING_LEN(rep), rb_enc_name(rb_enc_get(rep))); - if ((int)ret == -1) { - rb_raise(rb_eArgError, "too big fallback string"); - } - goto resume; - } + VALUE rep = rb_enc_str_new( + (const char *)ec->last_error.error_bytes_start, + ec->last_error.error_bytes_len, + rb_enc_find(ec->last_error.source_encoding)); + rep = (*fallback_func)(fallback, rep); + if (rep != Qundef && !NIL_P(rep)) { + StringValue(rep); + ret = rb_econv_insert_output(ec, (const unsigned char *)RSTRING_PTR(rep), + RSTRING_LEN(rep), rb_enc_name(rb_enc_get(rep))); + if ((int)ret == -1) { + rb_raise(rb_eArgError, "too big fallback string"); + } + goto resume; + } } if (ret == econv_invalid_byte_sequence || @@ -2331,7 +2331,7 @@ transcode_loop(const unsigned char **in_pos, unsigned char **out_pos, ret == econv_undefined_conversion) { exc = make_econv_exception(ec); rb_econv_close(ec); - rb_exc_raise(exc); + rb_exc_raise(exc); } if (ret == econv_destination_buffer_full) { @@ -2346,7 +2346,7 @@ transcode_loop(const unsigned char **in_pos, unsigned char **out_pos, /* sample transcode_loop implementation in byte-by-byte stream style */ static void transcode_loop(const unsigned char **in_pos, unsigned char **out_pos, - const unsigned char *in_stop, unsigned char *out_stop, + const unsigned char *in_stop, unsigned char *out_stop, VALUE destination, unsigned char *(*resize_destination)(VALUE, size_t, size_t), const char *src_encoding, @@ -2478,56 +2478,56 @@ econv_opts(VALUE opt, int ecflags) v = rb_hash_aref(opt, sym_newline); if (!NIL_P(v)) { newlineflag = 2; - ecflags &= ~ECONV_NEWLINE_DECORATOR_MASK; - if (v == sym_universal) { - ecflags |= ECONV_UNIVERSAL_NEWLINE_DECORATOR; - } - else if (v == sym_crlf) { - ecflags |= ECONV_CRLF_NEWLINE_DECORATOR; - } - else if (v == sym_cr) { - ecflags |= ECONV_CR_NEWLINE_DECORATOR; - } - else if (v == sym_lf) { - /* ecflags |= ECONV_LF_NEWLINE_DECORATOR; */ - } - else if (SYMBOL_P(v)) { - rb_raise(rb_eArgError, "unexpected value for newline option: %"PRIsVALUE, - rb_sym2str(v)); - } - else { - rb_raise(rb_eArgError, "unexpected value for newline option"); - } + ecflags &= ~ECONV_NEWLINE_DECORATOR_MASK; + if (v == sym_universal) { + ecflags |= ECONV_UNIVERSAL_NEWLINE_DECORATOR; + } + else if (v == sym_crlf) { + ecflags |= ECONV_CRLF_NEWLINE_DECORATOR; + } + else if (v == sym_cr) { + ecflags |= ECONV_CR_NEWLINE_DECORATOR; + } + else if (v == sym_lf) { + /* ecflags |= ECONV_LF_NEWLINE_DECORATOR; */ + } + else if (SYMBOL_P(v)) { + rb_raise(rb_eArgError, "unexpected value for newline option: %"PRIsVALUE, + rb_sym2str(v)); + } + else { + rb_raise(rb_eArgError, "unexpected value for newline option"); + } } #endif { int setflags = 0; - v = rb_hash_aref(opt, sym_universal_newline); - if (RTEST(v)) - setflags |= ECONV_UNIVERSAL_NEWLINE_DECORATOR; - newlineflag |= !NIL_P(v); + v = rb_hash_aref(opt, sym_universal_newline); + if (RTEST(v)) + setflags |= ECONV_UNIVERSAL_NEWLINE_DECORATOR; + newlineflag |= !NIL_P(v); - v = rb_hash_aref(opt, sym_crlf_newline); - if (RTEST(v)) - setflags |= ECONV_CRLF_NEWLINE_DECORATOR; - newlineflag |= !NIL_P(v); + v = rb_hash_aref(opt, sym_crlf_newline); + if (RTEST(v)) + setflags |= ECONV_CRLF_NEWLINE_DECORATOR; + newlineflag |= !NIL_P(v); - v = rb_hash_aref(opt, sym_cr_newline); - if (RTEST(v)) - setflags |= ECONV_CR_NEWLINE_DECORATOR; - newlineflag |= !NIL_P(v); + v = rb_hash_aref(opt, sym_cr_newline); + if (RTEST(v)) + setflags |= ECONV_CR_NEWLINE_DECORATOR; + newlineflag |= !NIL_P(v); switch (newlineflag) { case 1: - ecflags &= ~ECONV_NEWLINE_DECORATOR_MASK; - ecflags |= setflags; + ecflags &= ~ECONV_NEWLINE_DECORATOR_MASK; + ecflags |= setflags; break; case 3: rb_warning(":newline option precedes other newline options"); break; - } + } } return ecflags; @@ -2547,28 +2547,28 @@ rb_econv_prepare_options(VALUE opthash, VALUE *opts, int ecflags) v = rb_hash_aref(opthash, sym_replace); if (!NIL_P(v)) { - StringValue(v); - if (rb_enc_str_coderange(v) == ENC_CODERANGE_BROKEN) { - VALUE dumped = rb_str_dump(v); - rb_raise(rb_eArgError, "replacement string is broken: %s as %s", - StringValueCStr(dumped), - rb_enc_name(rb_enc_get(v))); - } - v = rb_str_new_frozen(v); - newhash = rb_hash_new(); - rb_hash_aset(newhash, sym_replace, v); + StringValue(v); + if (rb_enc_str_coderange(v) == ENC_CODERANGE_BROKEN) { + VALUE dumped = rb_str_dump(v); + rb_raise(rb_eArgError, "replacement string is broken: %s as %s", + StringValueCStr(dumped), + rb_enc_name(rb_enc_get(v))); + } + v = rb_str_new_frozen(v); + newhash = rb_hash_new(); + rb_hash_aset(newhash, sym_replace, v); } v = rb_hash_aref(opthash, sym_fallback); if (!NIL_P(v)) { - VALUE h = rb_check_hash_type(v); - if (NIL_P(h) - ? (rb_obj_is_proc(v) || rb_obj_is_method(v) || rb_respond_to(v, idAREF)) - : (v = h, 1)) { - if (NIL_P(newhash)) - newhash = rb_hash_new(); - rb_hash_aset(newhash, sym_fallback, v); - } + VALUE h = rb_check_hash_type(v); + if (NIL_P(h) + ? (rb_obj_is_proc(v) || rb_obj_is_method(v) || rb_respond_to(v, idAREF)) + : (v = h, 1)) { + if (NIL_P(newhash)) + newhash = rb_hash_new(); + rb_hash_aset(newhash, sym_fallback, v); + } } if (!NIL_P(newhash)) @@ -2628,13 +2628,13 @@ enc_arg(VALUE *arg, const char **name_p, rb_encoding **enc_p) VALUE encval; if (((encidx = rb_to_encoding_index(encval = *arg)) < 0) || - !(enc = rb_enc_from_index(encidx))) { - enc = NULL; - encidx = 0; - n = StringValueCStr(*arg); + !(enc = rb_enc_from_index(encidx))) { + enc = NULL; + encidx = 0; + n = StringValueCStr(*arg); } else { - n = rb_enc_name(enc); + n = rb_enc_name(enc); } *name_p = n; @@ -2655,9 +2655,9 @@ str_transcode_enc_args(VALUE str, VALUE *arg1, VALUE *arg2, dencidx = enc_arg(arg1, &dname, &denc); if (NIL_P(*arg2)) { - sencidx = rb_enc_get_index(str); - senc = rb_enc_from_index(sencidx); - sname = rb_enc_name(senc); + sencidx = rb_enc_get_index(str); + senc = rb_enc_from_index(sencidx); + sname = rb_enc_name(senc); } else { sencidx = enc_arg(arg2, &sname, &senc); @@ -2687,18 +2687,18 @@ str_transcode0(int argc, VALUE *argv, VALUE *self, int ecflags, VALUE ecopts) rb_check_arity(argc, 0, 2); if (argc == 0) { - arg1 = rb_enc_default_internal(); - if (NIL_P(arg1)) { - if (!ecflags) return -1; - arg1 = rb_obj_encoding(str); - } - if (!(ecflags & ECONV_INVALID_MASK)) { - explicitly_invalid_replace = FALSE; - } - ecflags |= ECONV_INVALID_REPLACE | ECONV_UNDEF_REPLACE; + arg1 = rb_enc_default_internal(); + if (NIL_P(arg1)) { + if (!ecflags) return -1; + arg1 = rb_obj_encoding(str); + } + if (!(ecflags & ECONV_INVALID_MASK)) { + explicitly_invalid_replace = FALSE; + } + ecflags |= ECONV_INVALID_REPLACE | ECONV_UNDEF_REPLACE; } else { - arg1 = argv[0]; + arg1 = argv[0]; } arg2 = argc<=1 ? Qnil : argv[1]; dencidx = str_transcode_enc_args(str, &arg1, &arg2, &sname, &senc, &dname, &denc); @@ -2708,16 +2708,16 @@ str_transcode0(int argc, VALUE *argv, VALUE *self, int ecflags, VALUE ecopts) ECONV_XML_ATTR_CONTENT_DECORATOR| ECONV_XML_ATTR_QUOTE_DECORATOR)) == 0) { if (senc && senc == denc) { - if ((ecflags & ECONV_INVALID_MASK) && explicitly_invalid_replace) { - VALUE rep = Qnil; - if (!NIL_P(ecopts)) { - rep = rb_hash_aref(ecopts, sym_replace); - } - dest = rb_enc_str_scrub(senc, str, rep); - if (NIL_P(dest)) dest = str; - *self = dest; - return dencidx; - } + if ((ecflags & ECONV_INVALID_MASK) && explicitly_invalid_replace) { + VALUE rep = Qnil; + if (!NIL_P(ecopts)) { + rep = rb_hash_aref(ecopts, sym_replace); + } + dest = rb_enc_str_scrub(senc, str, rep); + if (NIL_P(dest)) dest = str; + *self = dest; + return dencidx; + } return NIL_P(arg2) ? -1 : dencidx; } if (senc && denc && rb_enc_asciicompat(senc) && rb_enc_asciicompat(denc)) { @@ -2758,9 +2758,9 @@ str_transcode0(int argc, VALUE *argv, VALUE *self, int ecflags, VALUE ecopts) /* set encoding */ if (!denc) { - dencidx = rb_define_dummy_encoding(dname); - RB_GC_GUARD(arg1); - RB_GC_GUARD(arg2); + dencidx = rb_define_dummy_encoding(dname); + RB_GC_GUARD(arg1); + RB_GC_GUARD(arg2); } *self = dest; @@ -2776,7 +2776,7 @@ str_transcode(int argc, VALUE *argv, VALUE *self) argc = rb_scan_args(argc, argv, "02:", NULL, NULL, &opt); if (!NIL_P(opt)) { - ecflags = rb_econv_prepare_opts(opt, &ecopts); + ecflags = rb_econv_prepare_opts(opt, &ecopts); } return str_transcode0(argc, argv, self, ecflags, ecopts); } @@ -2790,10 +2790,10 @@ str_encode_associate(VALUE str, int encidx) /* transcoded string never be broken. */ if (rb_enc_asciicompat(rb_enc_from_index(encidx))) { - rb_str_coderange_scan_restartable(RSTRING_PTR(str), RSTRING_END(str), 0, &cr); + rb_str_coderange_scan_restartable(RSTRING_PTR(str), RSTRING_END(str), 0, &cr); } else { - cr = ENC_CODERANGE_VALID; + cr = ENC_CODERANGE_VALID; } ENC_CODERANGE_SET(str, cr); return str; @@ -2821,8 +2821,8 @@ str_encode_bang(int argc, VALUE *argv, VALUE str) if (encidx < 0) return str; if (newstr == str) { - rb_enc_associate_index(str, encidx); - return str; + rb_enc_associate_index(str, encidx); + return str; } rb_str_shared_replace(str, newstr); return str_encode_associate(str, encidx); @@ -2853,12 +2853,12 @@ encoded_dup(VALUE newstr, VALUE str, int encidx) { if (encidx < 0) return rb_str_dup(str); if (newstr == str) { - newstr = rb_str_dup(str); - rb_enc_associate_index(newstr, encidx); - return newstr; + newstr = rb_str_dup(str); + rb_enc_associate_index(newstr, encidx); + return newstr; } else { - RBASIC_SET_CLASS(newstr, rb_obj_class(str)); + RBASIC_SET_CLASS(newstr, rb_obj_class(str)); } return str_encode_associate(newstr, encidx); } @@ -2972,9 +2972,9 @@ econv_args(int argc, VALUE *argv, argc = rb_scan_args(argc, argv, "21:", snamev_p, dnamev_p, &flags_v, &opt); if (!NIL_P(flags_v)) { - if (!NIL_P(opt)) { - rb_error_arity(argc + 1, 2, 3); - } + if (!NIL_P(opt)) { + rb_error_arity(argc + 1, 2, 3); + } ecflags = NUM2INT(rb_to_int(flags_v)); ecopts = Qnil; } @@ -3030,22 +3030,22 @@ decorate_convpath(VALUE convpath, int ecflags) len = n = RARRAY_LENINT(convpath); if (n != 0) { VALUE pair = RARRAY_AREF(convpath, n-1); - if (RB_TYPE_P(pair, T_ARRAY)) { - const char *sname = rb_enc_name(rb_to_encoding(RARRAY_AREF(pair, 0))); - const char *dname = rb_enc_name(rb_to_encoding(RARRAY_AREF(pair, 1))); - transcoder_entry_t *entry = get_transcoder_entry(sname, dname); - const rb_transcoder *tr = load_transcoder_entry(entry); - if (!tr) - return -1; - if (!DECORATOR_P(tr->src_encoding, tr->dst_encoding) && - tr->asciicompat_type == asciicompat_encoder) { - n--; - rb_ary_store(convpath, len + num_decorators - 1, pair); - } - } - else { - rb_ary_store(convpath, len + num_decorators - 1, pair); - } + if (RB_TYPE_P(pair, T_ARRAY)) { + const char *sname = rb_enc_name(rb_to_encoding(RARRAY_AREF(pair, 0))); + const char *dname = rb_enc_name(rb_to_encoding(RARRAY_AREF(pair, 1))); + transcoder_entry_t *entry = get_transcoder_entry(sname, dname); + const rb_transcoder *tr = load_transcoder_entry(entry); + if (!tr) + return -1; + if (!DECORATOR_P(tr->src_encoding, tr->dst_encoding) && + tr->asciicompat_type == asciicompat_encoder) { + n--; + rb_ary_store(convpath, len + num_decorators - 1, pair); + } + } + else { + rb_ary_store(convpath, len + num_decorators - 1, pair); + } } for (i = 0; i < num_decorators; i++) @@ -3121,10 +3121,10 @@ econv_s_search_convpath(int argc, VALUE *argv, VALUE klass) } if (decorate_convpath(convpath, ecflags) == -1) { - VALUE exc = rb_econv_open_exc(sname, dname, ecflags); - RB_GC_GUARD(snamev); - RB_GC_GUARD(dnamev); - rb_exc_raise(exc); + VALUE exc = rb_econv_open_exc(sname, dname, ecflags); + RB_GC_GUARD(snamev); + RB_GC_GUARD(dnamev); + rb_exc_raise(exc); } return convpath; @@ -3140,7 +3140,7 @@ rb_econv_has_convpath_p(const char* from_encoding, const char* to_encoding) { VALUE convpath = Qnil; transcode_search_path(from_encoding, to_encoding, search_convpath_i, - &convpath); + &convpath); return RTEST(convpath); } @@ -3198,12 +3198,12 @@ rb_econv_init_by_convpath(VALUE self, VALUE convpath, } if (DECORATOR_P(sname, dname)) { ret = rb_econv_add_converter(ec, sname, dname, ec->num_trans); - if (ret == -1) { - VALUE msg = rb_sprintf("decoration failed: %s", dname); - RB_GC_GUARD(snamev); - RB_GC_GUARD(dnamev); - rb_exc_raise(rb_exc_new_str(rb_eArgError, msg)); - } + if (ret == -1) { + VALUE msg = rb_sprintf("decoration failed: %s", dname); + RB_GC_GUARD(snamev); + RB_GC_GUARD(dnamev); + rb_exc_raise(rb_exc_new_str(rb_eArgError, msg)); + } } else { int j = ec->num_trans; @@ -3212,12 +3212,12 @@ rb_econv_init_by_convpath(VALUE self, VALUE convpath, arg.index = ec->num_trans; arg.ret = 0; ret = transcode_search_path(sname, dname, rb_econv_init_by_convpath_i, &arg); - if (ret == -1 || arg.ret == -1) { - VALUE msg = rb_sprintf("adding conversion failed: %s to %s", sname, dname); - RB_GC_GUARD(snamev); - RB_GC_GUARD(dnamev); + if (ret == -1 || arg.ret == -1) { + VALUE msg = rb_sprintf("adding conversion failed: %s to %s", sname, dname); + RB_GC_GUARD(snamev); + RB_GC_GUARD(dnamev); rb_exc_raise(rb_exc_new_str(rb_eArgError, msg)); - } + } if (first) { first = 0; *senc_p = senc; @@ -3229,10 +3229,10 @@ rb_econv_init_by_convpath(VALUE self, VALUE convpath, } if (first) { - *senc_p = NULL; - *denc_p = NULL; - *sname_p = ""; - *dname_p = ""; + *senc_p = NULL; + *denc_p = NULL; + *sname_p = ""; + *dname_p = ""; } ec->source_encoding_name = *sname_p; @@ -3373,10 +3373,10 @@ econv_init(int argc, VALUE *argv, VALUE self) } if (!ec) { - VALUE exc = rb_econv_open_exc(sname, dname, ecflags); - RB_GC_GUARD(snamev); - RB_GC_GUARD(dnamev); - rb_exc_raise(exc); + VALUE exc = rb_econv_open_exc(sname, dname, ecflags); + RB_GC_GUARD(snamev); + RB_GC_GUARD(dnamev); + rb_exc_raise(exc); } if (!DECORATOR_P(sname, dname)) { @@ -3384,8 +3384,8 @@ econv_init(int argc, VALUE *argv, VALUE self) senc = make_dummy_encoding(sname); if (!denc) denc = make_dummy_encoding(dname); - RB_GC_GUARD(snamev); - RB_GC_GUARD(dnamev); + RB_GC_GUARD(snamev); + RB_GC_GUARD(dnamev); } ec->source_encoding = senc; @@ -3526,29 +3526,29 @@ econv_equal(VALUE self, VALUE other) int i; if (!rb_typeddata_is_kind_of(other, &econv_data_type)) { - return Qnil; + return Qnil; } ec2 = DATA_PTR(other); if (!ec2) return Qfalse; if (ec1->source_encoding_name != ec2->source_encoding_name && - strcmp(ec1->source_encoding_name, ec2->source_encoding_name)) - return Qfalse; + strcmp(ec1->source_encoding_name, ec2->source_encoding_name)) + return Qfalse; if (ec1->destination_encoding_name != ec2->destination_encoding_name && - strcmp(ec1->destination_encoding_name, ec2->destination_encoding_name)) - return Qfalse; + strcmp(ec1->destination_encoding_name, ec2->destination_encoding_name)) + return Qfalse; if (ec1->flags != ec2->flags) return Qfalse; if (ec1->replacement_enc != ec2->replacement_enc && - strcmp(ec1->replacement_enc, ec2->replacement_enc)) - return Qfalse; + strcmp(ec1->replacement_enc, ec2->replacement_enc)) + return Qfalse; if (ec1->replacement_len != ec2->replacement_len) return Qfalse; if (ec1->replacement_str != ec2->replacement_str && - memcmp(ec1->replacement_str, ec2->replacement_str, ec2->replacement_len)) - return Qfalse; + memcmp(ec1->replacement_str, ec2->replacement_str, ec2->replacement_len)) + return Qfalse; if (ec1->num_trans != ec2->num_trans) return Qfalse; for (i = 0; i < ec1->num_trans; i++) { if (ec1->elems[i].tc->transcoder != ec2->elems[i].tc->transcoder) - return Qfalse; + return Qfalse; } return Qtrue; } @@ -3687,10 +3687,10 @@ econv_primitive_convert(int argc, VALUE *argv, VALUE self) output_bytesize = NUM2LONG(output_bytesize_v); if (!NIL_P(flags_v)) { - if (!NIL_P(opt)) { - rb_error_arity(argc + 1, 2, 5); - } - flags = NUM2INT(rb_to_int(flags_v)); + if (!NIL_P(opt)) { + rb_error_arity(argc + 1, 2, 5); + } + flags = NUM2INT(rb_to_int(flags_v)); } else if (!NIL_P(opt)) { VALUE v; @@ -4042,7 +4042,7 @@ econv_insert_output(VALUE self, VALUE string) ret = rb_econv_insert_output(ec, (const unsigned char *)RSTRING_PTR(string), RSTRING_LEN(string), insert_enc); if (ret == -1) { - rb_raise(rb_eArgError, "too big string"); + rb_raise(rb_eArgError, "too big string"); } return Qnil; diff --git a/transcode_data.h b/transcode_data.h index 9455ec93c9..416e50d3cc 100644 --- a/transcode_data.h +++ b/transcode_data.h @@ -46,25 +46,25 @@ RUBY_SYMBOL_EXPORT_BEGIN #define o1(b1) (PType((((unsigned char)(b1))<<8)|ONEbt)) #define o2(b1,b2) (PType((((unsigned char)(b1))<<8)|\ - (((unsigned char)(b2))<<16)|\ - TWObt)) + (((unsigned char)(b2))<<16)|\ + TWObt)) #define o3(b1,b2,b3) (PType(((((unsigned char)(b1))<<8)|\ - (((unsigned char)(b2))<<16)|\ - (((unsigned int)(unsigned char)(b3))<<24)|\ - THREEbt)&\ - 0xffffffffU)) + (((unsigned char)(b2))<<16)|\ + (((unsigned int)(unsigned char)(b3))<<24)|\ + THREEbt)&\ + 0xffffffffU)) #define o4(b0,b1,b2,b3) (PType(((((unsigned char)(b1))<<8)|\ - (((unsigned char)(b2))<<16)|\ - (((unsigned int)(unsigned char)(b3))<<24)|\ - ((((unsigned char)(b0))&0x07)<<5)|\ - FOURbt)&\ - 0xffffffffU)) + (((unsigned char)(b2))<<16)|\ + (((unsigned int)(unsigned char)(b3))<<24)|\ + ((((unsigned char)(b0))&0x07)<<5)|\ + FOURbt)&\ + 0xffffffffU)) #define g4(b0,b1,b2,b3) (PType(((((unsigned char)(b0))<<8)|\ - (((unsigned char)(b2))<<16)|\ - ((((unsigned char)(b1))&0x0f)<<24)|\ - ((((unsigned int)(unsigned char)(b3))&0x0f)<<28)|\ - GB4bt)&\ - 0xffffffffU)) + (((unsigned char)(b2))<<16)|\ + ((((unsigned char)(b1))&0x0f)<<24)|\ + ((((unsigned int)(unsigned char)(b3))&0x0f)<<28)|\ + GB4bt)&\ + 0xffffffffU)) #define funsio(diff) (PType((((unsigned int)(diff))<<8)|FUNsio)) #define getBT1(a) ((unsigned char)((a)>> 8)) diff --git a/util.c b/util.c index 1b11ecb3f5..c7fb0998a8 100644 --- a/util.c +++ b/util.c @@ -45,8 +45,8 @@ ruby_scan_oct(const char *start, size_t len, size_t *retlen) if ((s[0] < '0') || ('7' < s[0])) { break; } - retval <<= 3; - retval |= *s++ - '0'; + retval <<= 3; + retval |= *s++ - '0'; } *retlen = (size_t)(s - start); return retval; @@ -65,9 +65,9 @@ ruby_scan_hex(const char *start, size_t len, size_t *retlen) if (d < 0 || 15 < d) { break; } - retval <<= 4; - retval |= d; - s++; + retval <<= 4; + retval |= d; + s++; } *retlen = (size_t)(s - start); return retval; @@ -107,15 +107,15 @@ ruby_scan_digits(const char *str, ssize_t len, int base, size_t *retlen, int *ov *overflow = 0; if (!len) { - *retlen = 0; - return 0; + *retlen = 0; + return 0; } do { - int d = ruby_digit36_to_number_table[(unsigned char)*str++]; + int d = ruby_digit36_to_number_table[(unsigned char)*str++]; if (d == -1 || base <= d) { - --str; - break; + --str; + break; } if (mul_overflow < ret) *overflow = 1; @@ -416,57 +416,57 @@ ruby_qsort(void* base, const size_t nel, const size_t size, cmpfunc_t *cmp, void register char *m1; register char *m3; if (n >= 200) { - n = size*(n>>3); /* number of bytes in splitting 8 */ - { - register char *p1 = l + n; - register char *p2 = p1 + n; - register char *p3 = p2 + n; - m1 = med3(p1, p2, p3); - p1 = m + n; - p2 = p1 + n; - p3 = p2 + n; - m3 = med3(p1, p2, p3); - } + n = size*(n>>3); /* number of bytes in splitting 8 */ + { + register char *p1 = l + n; + register char *p2 = p1 + n; + register char *p3 = p2 + n; + m1 = med3(p1, p2, p3); + p1 = m + n; + p2 = p1 + n; + p3 = p2 + n; + m3 = med3(p1, p2, p3); + } } else { - n = size*(n>>2); /* number of bytes in splitting 4 */ - m1 = l + n; - m3 = m + n; + n = size*(n>>2); /* number of bytes in splitting 4 */ + m1 = l + n; + m3 = m + n; } m = med3(m1, m, m3); } if ((t = (*cmp)(l,m,d)) < 0) { /*3-5-?*/ if ((t = (*cmp)(m,r,d)) < 0) { /*3-5-7*/ - if (chklim && nel >= chklim) { /* check if already ascending order */ - char *p; - chklim = 0; - for (p=l; p 0) goto fail; - goto nxt; - } - fail: goto loopA; /*3-5-7*/ + if (chklim && nel >= chklim) { /* check if already ascending order */ + char *p; + chklim = 0; + for (p=l; p 0) goto fail; + goto nxt; + } + fail: goto loopA; /*3-5-7*/ } if (t > 0) { - if ((*cmp)(l,r,d) <= 0) {mmswap(m,r); goto loopA;} /*3-5-4*/ - mmrot3(r,m,l); goto loopA; /*3-5-2*/ + if ((*cmp)(l,r,d) <= 0) {mmswap(m,r); goto loopA;} /*3-5-4*/ + mmrot3(r,m,l); goto loopA; /*3-5-2*/ } goto loopB; /*3-5-5*/ } if (t > 0) { /*7-5-?*/ if ((t = (*cmp)(m,r,d)) > 0) { /*7-5-3*/ - if (chklim && nel >= chklim) { /* check if already ascending order */ - char *p; - chklim = 0; - for (p=l; p= chklim) { /* check if already ascending order */ + char *p; + chklim = 0; + for (p=l; p 0) {eq_r = 0; break;} - if (t < 0) eq_l = 0; + if ((l += size) == r) + {l -= size; if (l != m) mmswap(m,l); l -= size; goto fin;} + if (l == m) continue; + if ((t = (*cmp)(l,m,d)) > 0) {eq_r = 0; break;} + if (t < 0) eq_l = 0; } for (;;) { - if (l == (r -= size)) - {l -= size; if (l != m) mmswap(m,l); l -= size; goto fin;} - if (r == m) {m = l; break;} - if ((t = (*cmp)(r,m,d)) < 0) {eq_l = 0; break;} - if (t == 0) break; + if (l == (r -= size)) + {l -= size; if (l != m) mmswap(m,l); l -= size; goto fin;} + if (r == m) {m = l; break;} + if ((t = (*cmp)(r,m,d)) < 0) {eq_l = 0; break;} + if (t == 0) break; } mmswap(l,r); /* swap left and right */ } @@ -504,18 +504,18 @@ ruby_qsort(void* base, const size_t nel, const size_t size, cmpfunc_t *cmp, void loopB: eq_l = 1; eq_r = 1; /* splitting type B */ /* left < median <= right */ for (;;) { for (;;) { - if (l == (r -= size)) - {r += size; if (r != m) mmswap(r,m); r += size; goto fin;} - if (r == m) continue; - if ((t = (*cmp)(r,m,d)) < 0) {eq_l = 0; break;} - if (t > 0) eq_r = 0; + if (l == (r -= size)) + {r += size; if (r != m) mmswap(r,m); r += size; goto fin;} + if (r == m) continue; + if ((t = (*cmp)(r,m,d)) < 0) {eq_l = 0; break;} + if (t > 0) eq_r = 0; } for (;;) { - if ((l += size) == r) - {r += size; if (r != m) mmswap(r,m); r += size; goto fin;} - if (l == m) {m = r; break;} - if ((t = (*cmp)(l,m,d)) > 0) {eq_r = 0; break;} - if (t == 0) break; + if ((l += size) == r) + {r += size; if (r != m) mmswap(r,m); r += size; goto fin;} + if (l == m) {m = r; break;} + if ((t = (*cmp)(l,m,d)) > 0) {eq_r = 0; break;} + if (t == 0) break; } mmswap(l,r); /* swap left and right */ } @@ -523,8 +523,8 @@ ruby_qsort(void* base, const size_t nel, const size_t size, cmpfunc_t *cmp, void fin: if (eq_l == 0) /* need to sort left side */ if (eq_r == 0) /* need to sort right side */ - if (l-L < R-r) {PUSH(r,R); R = l;} /* sort left side first */ - else {PUSH(L,l); L = r;} /* sort right side first */ + if (l-L < R-r) {PUSH(r,R); R = l;} /* sort left side first */ + else {PUSH(L,l); L = r;} /* sort right side first */ else R = l; /* need to sort left side only */ else if (eq_r == 0) L = r; /* need to sort right side only */ else goto nxt; /* need not to sort both sides */ @@ -556,15 +556,15 @@ ruby_getcwd(void) char *buf = xmalloc(size); while (!getcwd(buf, size)) { - int e = errno; - if (e != ERANGE) { - xfree(buf); - DATA_PTR(guard) = NULL; - rb_syserr_fail(e, "getcwd"); - } - size *= 2; - DATA_PTR(guard) = buf; - buf = xrealloc(buf, size); + int e = errno; + if (e != ERANGE) { + xfree(buf); + DATA_PTR(guard) = NULL; + rb_syserr_fail(e, "getcwd"); + } + size *= 2; + DATA_PTR(guard) = buf; + buf = xrealloc(buf, size); } # else VALUE guard = Data_Wrap_Struct((VALUE)0, NULL, free, NULL); @@ -582,9 +582,9 @@ ruby_getcwd(void) char *buf = xmalloc(PATH_MAX+1); if (!getwd(buf)) { - int e = errno; - xfree(buf); - rb_syserr_fail(e, "getwd"); + int e = errno; + xfree(buf); + rb_syserr_fail(e, "getwd"); } #endif return buf; @@ -598,12 +598,12 @@ ruby_each_words(const char *str, void (*func)(const char*, int, void*), void *ar if (!str) return; for (; *str; str = end) { - while (ISSPACE(*str) || *str == ',') str++; - if (!*str) break; - end = str; - while (*end && !ISSPACE(*end) && *end != ',') end++; - len = (int)(end - str); /* assume no string exceeds INT_MAX */ - (*func)(str, len, arg); + while (ISSPACE(*str) || *str == ',') str++; + if (!*str) break; + end = str; + while (*end && !ISSPACE(*end) && *end != ',') end++; + len = (int)(end - str); /* assume no string exceeds INT_MAX */ + (*func)(str, len, arg); } } diff --git a/variable.c b/variable.c index 81258cb47b..a3512adc99 100644 --- a/variable.c +++ b/variable.c @@ -64,8 +64,8 @@ static st_table *generic_iv_tbl_; struct ivar_update { union { - st_table *iv_index_tbl; - struct gen_ivtbl *ivtbl; + st_table *iv_index_tbl; + struct gen_ivtbl *ivtbl; } u; st_data_t index; int iv_extended; @@ -147,14 +147,14 @@ make_temporary_path(VALUE obj, VALUE klass) VALUE path; switch (klass) { case Qnil: - path = rb_sprintf("#", (void*)obj); - break; + path = rb_sprintf("#", (void*)obj); + break; case Qfalse: - path = rb_sprintf("#", (void*)obj); - break; + path = rb_sprintf("#", (void*)obj); + break; default: - path = rb_sprintf("#<%"PRIsVALUE":%p>", klass, (void*)obj); - break; + path = rb_sprintf("#<%"PRIsVALUE":%p>", klass, (void*)obj); + break; } OBJ_FREEZE(path); return path; @@ -168,20 +168,20 @@ rb_tmp_class_path(VALUE klass, int *permanent, fallback_func fallback) VALUE path = classname(klass, permanent); if (!NIL_P(path)) { - return path; + return path; } else { - if (RB_TYPE_P(klass, T_MODULE)) { - if (rb_obj_class(klass) == rb_cModule) { - path = Qfalse; - } - else { - int perm; - path = rb_tmp_class_path(RBASIC(klass)->klass, &perm, fallback); - } - } - *permanent = 0; - return fallback(klass, path); + if (RB_TYPE_P(klass, T_MODULE)) { + if (rb_obj_class(klass) == rb_cModule) { + path = Qfalse; + } + else { + int perm; + path = rb_tmp_class_path(RBASIC(klass)->klass, &perm, fallback); + } + } + *permanent = 0; + return fallback(klass, path); } } @@ -235,15 +235,15 @@ rb_set_class_path_string(VALUE klass, VALUE under, VALUE name) ID pathid = classpath; if (under == rb_cObject) { - str = rb_str_new_frozen(name); + str = rb_str_new_frozen(name); } else { - int permanent; + int permanent; str = rb_tmp_class_path(under, &permanent, make_temporary_path); str = build_const_pathname(str, name); - if (!permanent) { - pathid = tmp_classpath; - } + if (!permanent) { + pathid = tmp_classpath; + } } rb_ivar_set(klass, pathid, str); } @@ -265,31 +265,31 @@ rb_path_to_class(VALUE pathname) VALUE c = rb_cObject; if (!rb_enc_asciicompat(enc)) { - rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)"); + rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)"); } pbeg = p = path; pend = path + RSTRING_LEN(pathname); if (path == pend || path[0] == '#') { - rb_raise(rb_eArgError, "can't retrieve anonymous class %"PRIsVALUE, - QUOTE(pathname)); + rb_raise(rb_eArgError, "can't retrieve anonymous class %"PRIsVALUE, + QUOTE(pathname)); } while (p < pend) { - while (p < pend && *p != ':') p++; - id = rb_check_id_cstr(pbeg, p-pbeg, enc); - if (p < pend && p[0] == ':') { - if ((size_t)(pend - p) < 2 || p[1] != ':') goto undefined_class; - p += 2; - pbeg = p; - } - if (!id) { + while (p < pend && *p != ':') p++; + id = rb_check_id_cstr(pbeg, p-pbeg, enc); + if (p < pend && p[0] == ':') { + if ((size_t)(pend - p) < 2 || p[1] != ':') goto undefined_class; + p += 2; + pbeg = p; + } + if (!id) { goto undefined_class; - } - c = rb_const_search(c, id, TRUE, FALSE, FALSE); - if (c == Qundef) goto undefined_class; + } + c = rb_const_search(c, id, TRUE, FALSE, FALSE); + if (c == Qundef) goto undefined_class; if (!rb_namespace_p(c)) { - rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module", - pathname); - } + rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module", + pathname); + } } RB_GC_GUARD(pathname); @@ -390,22 +390,22 @@ rb_global_entry(ID id) { struct rb_global_entry *entry = rb_find_global_entry(id); if (!entry) { - struct rb_global_variable *var; - entry = ALLOC(struct rb_global_entry); - var = ALLOC(struct rb_global_variable); - entry->id = id; - entry->var = var; + struct rb_global_variable *var; + entry = ALLOC(struct rb_global_entry); + var = ALLOC(struct rb_global_variable); + entry->id = id; + entry->var = var; entry->ractor_local = false; - var->counter = 1; - var->data = 0; - var->getter = rb_gvar_undef_getter; - var->setter = rb_gvar_undef_setter; - var->marker = rb_gvar_undef_marker; - var->compactor = rb_gvar_undef_compactor; + var->counter = 1; + var->data = 0; + var->getter = rb_gvar_undef_getter; + var->setter = rb_gvar_undef_setter; + var->marker = rb_gvar_undef_marker; + var->compactor = rb_gvar_undef_compactor; - var->block_trace = 0; - var->trace = 0; - rb_id_table_insert(rb_global_tbl, id, (VALUE)entry); + var->block_trace = 0; + var->trace = 0; + rb_id_table_insert(rb_global_tbl, id, (VALUE)entry); } return entry; } @@ -505,8 +505,8 @@ mark_global_entry(VALUE v, void *ignored) (*var->marker)(var->data); trace = var->trace; while (trace) { - if (trace->data) rb_gc_mark_maybe(trace->data); - trace = trace->next; + if (trace->data) rb_gc_mark_maybe(trace->data); + trace = trace->next; } return ID_TABLE_CONTINUE; } @@ -544,12 +544,12 @@ global_id(const char *name) if (name[0] == '$') id = rb_intern(name); else { - size_t len = strlen(name); + size_t len = strlen(name); VALUE vbuf = 0; char *buf = ALLOCV_N(char, vbuf, len+1); - buf[0] = '$'; - memcpy(buf+1, name, len); - id = rb_intern2(buf, len+1); + buf[0] = '$'; + memcpy(buf+1, name, len); + id = rb_intern2(buf, len+1); ALLOCV_END(vbuf); } return id; @@ -632,10 +632,10 @@ rb_f_trace_var(int argc, const VALUE *argv) struct trace_var *trace; if (rb_scan_args(argc, argv, "11", &var, &cmd) == 1) { - cmd = rb_block_proc(); + cmd = rb_block_proc(); } if (NIL_P(cmd)) { - return rb_f_untrace_var(argc, argv); + return rb_f_untrace_var(argc, argv); } entry = rb_global_entry(rb_to_id(var)); trace = ALLOC(struct trace_var); @@ -658,14 +658,14 @@ remove_trace(struct rb_global_variable *var) t.next = trace; trace = &t; while (trace->next) { - next = trace->next; - if (next->removed) { - trace->next = next->next; - xfree(next); - } - else { - trace = next; - } + next = trace->next; + if (next->removed) { + trace->next = next->next; + xfree(next); + } + else { + trace = next; + } } var->trace = t.next; } @@ -681,35 +681,35 @@ rb_f_untrace_var(int argc, const VALUE *argv) rb_scan_args(argc, argv, "11", &var, &cmd); id = rb_check_id(&var); if (!id) { - rb_name_error_str(var, "undefined global variable %"PRIsVALUE"", QUOTE(var)); + rb_name_error_str(var, "undefined global variable %"PRIsVALUE"", QUOTE(var)); } if ((entry = rb_find_global_entry(id)) == NULL) { - rb_name_error(id, "undefined global variable %"PRIsVALUE"", QUOTE_ID(id)); + rb_name_error(id, "undefined global variable %"PRIsVALUE"", QUOTE_ID(id)); } trace = entry->var->trace; if (NIL_P(cmd)) { - VALUE ary = rb_ary_new(); + VALUE ary = rb_ary_new(); - while (trace) { - struct trace_var *next = trace->next; - rb_ary_push(ary, (VALUE)trace->data); - trace->removed = 1; - trace = next; - } + while (trace) { + struct trace_var *next = trace->next; + rb_ary_push(ary, (VALUE)trace->data); + trace->removed = 1; + trace = next; + } - if (!entry->var->block_trace) remove_trace(entry->var); - return ary; + if (!entry->var->block_trace) remove_trace(entry->var); + return ary; } else { - while (trace) { - if (trace->data == cmd) { - trace->removed = 1; - if (!entry->var->block_trace) remove_trace(entry->var); - return rb_ary_new3(1, cmd); - } - trace = trace->next; - } + while (trace) { + if (trace->data == cmd) { + trace->removed = 1; + if (!entry->var->block_trace) remove_trace(entry->var); + return rb_ary_new3(1, cmd); + } + trace = trace->next; + } } return Qnil; } @@ -726,8 +726,8 @@ trace_ev(VALUE v) struct trace_var *trace = data->trace; while (trace) { - (*trace->func)(trace->data, data->val); - trace = trace->next; + (*trace->func)(trace->data, data->val); + trace = trace->next; } return Qnil; @@ -751,10 +751,10 @@ rb_gvar_set_entry(struct rb_global_entry *entry, VALUE val) (*var->setter)(val, entry->id, var->data); if (var->trace && !var->block_trace) { - var->block_trace = 1; - trace.trace = var->trace; - trace.val = val; - rb_ensure(trace_ev, (VALUE)&trace, trace_en, (VALUE)var); + var->block_trace = 1; + trace.trace = var->trace; + trace.val = val; + rb_ensure(trace_ev, (VALUE)&trace, trace_en, (VALUE)var); } return val; } @@ -836,22 +836,22 @@ rb_f_global_variables(void) rb_id_table_foreach(rb_global_tbl, gvar_i, (void *)ary); if (!NIL_P(backref)) { - char buf[2]; - int i, nmatch = rb_match_count(backref); - buf[0] = '$'; - for (i = 1; i <= nmatch; ++i) { - if (!rb_match_nth_defined(i, backref)) continue; - if (i < 10) { - /* probably reused, make static ID */ - buf[1] = (char)(i + '0'); - sym = ID2SYM(rb_intern2(buf, 2)); - } - else { - /* dynamic symbol */ - sym = rb_str_intern(rb_sprintf("$%d", i)); - } - rb_ary_push(ary, sym); - } + char buf[2]; + int i, nmatch = rb_match_count(backref); + buf[0] = '$'; + for (i = 1; i <= nmatch; ++i) { + if (!rb_match_nth_defined(i, backref)) continue; + if (i < 10) { + /* probably reused, make static ID */ + buf[1] = (char)(i + '0'); + sym = ID2SYM(rb_intern2(buf, 2)); + } + else { + /* dynamic symbol */ + sym = rb_str_intern(rb_sprintf("$%d", i)); + } + rb_ary_push(ary, sym); + } } return ary; } @@ -869,28 +869,28 @@ rb_alias_variable(ID name1, ID name2) entry2 = rb_global_entry(name2); if (!rb_id_table_lookup(gtbl, name1, &data1)) { - entry1 = ALLOC(struct rb_global_entry); - entry1->id = name1; - rb_id_table_insert(gtbl, name1, (VALUE)entry1); + entry1 = ALLOC(struct rb_global_entry); + entry1->id = name1; + rb_id_table_insert(gtbl, name1, (VALUE)entry1); } else if ((entry1 = (struct rb_global_entry *)data1)->var != entry2->var) { - struct rb_global_variable *var = entry1->var; - if (var->block_trace) { - rb_raise(rb_eRuntimeError, "can't alias in tracer"); - } - var->counter--; - if (var->counter == 0) { - struct trace_var *trace = var->trace; - while (trace) { - struct trace_var *next = trace->next; - xfree(trace); - trace = next; - } - xfree(var); - } + struct rb_global_variable *var = entry1->var; + if (var->block_trace) { + rb_raise(rb_eRuntimeError, "can't alias in tracer"); + } + var->counter--; + if (var->counter == 0) { + struct trace_var *trace = var->trace; + while (trace) { + struct trace_var *next = trace->next; + xfree(trace); + trace = next; + } + xfree(var); + } } else { - return; + return; } entry2->var->counter++; entry1->var = entry2->var; @@ -1001,17 +1001,17 @@ generic_ivar_delete(VALUE obj, ID id, VALUE undef) struct gen_ivtbl *ivtbl; if (gen_ivtbl_get(obj, id, &ivtbl)) { - st_table *iv_index_tbl = RCLASS_IV_INDEX_TBL(rb_obj_class(obj)); + st_table *iv_index_tbl = RCLASS_IV_INDEX_TBL(rb_obj_class(obj)); uint32_t index; if (iv_index_tbl && iv_index_tbl_lookup(iv_index_tbl, id, &index)) { - if (index < ivtbl->numiv) { - VALUE ret = ivtbl->ivptr[index]; + if (index < ivtbl->numiv) { + VALUE ret = ivtbl->ivptr[index]; - ivtbl->ivptr[index] = Qundef; - return ret == Qundef ? undef : ret; - } - } + ivtbl->ivptr[index] = Qundef; + return ret == Qundef ? undef : ret; + } + } } return undef; } @@ -1022,16 +1022,16 @@ generic_ivar_get(VALUE obj, ID id, VALUE undef) struct gen_ivtbl *ivtbl; if (gen_ivtbl_get(obj, id, &ivtbl)) { - st_table *iv_index_tbl = RCLASS_IV_INDEX_TBL(rb_obj_class(obj)); + st_table *iv_index_tbl = RCLASS_IV_INDEX_TBL(rb_obj_class(obj)); uint32_t index; - if (iv_index_tbl && iv_index_tbl_lookup(iv_index_tbl, id, &index)) { - if (index < ivtbl->numiv) { - VALUE ret = ivtbl->ivptr[index]; + if (iv_index_tbl && iv_index_tbl_lookup(iv_index_tbl, id, &index)) { + if (index < ivtbl->numiv) { + VALUE ret = ivtbl->ivptr[index]; - return ret == Qundef ? undef : ret; - } - } + return ret == Qundef ? undef : ret; + } + } } return undef; } @@ -1050,7 +1050,7 @@ gen_ivtbl_resize(struct gen_ivtbl *old, uint32_t n) ivtbl->numiv = n; for (; len < n; len++) { - ivtbl->ivptr[len] = Qundef; + ivtbl->ivptr[len] = Qundef; } return ivtbl; @@ -1090,7 +1090,7 @@ generic_ivar_update(st_data_t *k, st_data_t *v, st_data_t u, int existing) struct gen_ivtbl *ivtbl = 0; if (existing) { - ivtbl = (struct gen_ivtbl *)*v; + ivtbl = (struct gen_ivtbl *)*v; if (ivup->index < ivtbl->numiv) { ivup->u.ivtbl = ivtbl; return ST_STOP; @@ -1129,11 +1129,11 @@ generic_ivar_remove(VALUE obj, ID id, VALUE *valp) if (!gen_ivtbl_get(obj, id, &ivtbl)) return 0; if (index < ivtbl->numiv) { - if (ivtbl->ivptr[index] != Qundef) { - *valp = ivtbl->ivptr[index]; - ivtbl->ivptr[index] = Qundef; - return 1; - } + if (ivtbl->ivptr[index] != Qundef) { + *valp = ivtbl->ivptr[index]; + ivtbl->ivptr[index] = Qundef; + return 1; + } } return 0; } @@ -1144,7 +1144,7 @@ gen_ivtbl_mark(const struct gen_ivtbl *ivtbl) uint32_t i; for (i = 0; i < ivtbl->numiv; i++) { - rb_gc_mark(ivtbl->ivptr[i]); + rb_gc_mark(ivtbl->ivptr[i]); } } @@ -1154,7 +1154,7 @@ rb_mark_generic_ivar(VALUE obj) struct gen_ivtbl *ivtbl; if (gen_ivtbl_get(obj, 0, &ivtbl)) { - gen_ivtbl_mark(ivtbl); + gen_ivtbl_mark(ivtbl); } } @@ -1174,7 +1174,7 @@ rb_free_generic_ivar(VALUE obj) st_data_t key = (st_data_t)obj, ivtbl; if (st_delete(generic_ivtbl_no_ractor_check(obj), &key, &ivtbl)) - xfree((struct gen_ivtbl *)ivtbl); + xfree((struct gen_ivtbl *)ivtbl); } RUBY_FUNC_EXPORTED size_t @@ -1183,7 +1183,7 @@ rb_generic_ivar_memsize(VALUE obj) struct gen_ivtbl *ivtbl; if (gen_ivtbl_get(obj, 0, &ivtbl)) - return gen_ivtbl_bytes(ivtbl->numiv); + return gen_ivtbl_bytes(ivtbl->numiv); return 0; } @@ -1194,9 +1194,9 @@ gen_ivtbl_count(const struct gen_ivtbl *ivtbl) size_t n = 0; for (i = 0; i < ivtbl->numiv; i++) { - if (ivtbl->ivptr[i] != Qundef) { - n++; - } + if (ivtbl->ivptr[i] != Qundef) { + n++; + } } return n; @@ -1291,9 +1291,9 @@ rb_ivar_lookup(VALUE obj, ID id, VALUE undef) } } default: - if (FL_TEST(obj, FL_EXIVAR)) - return generic_ivar_get(obj, id, undef); - break; + if (FL_TEST(obj, FL_EXIVAR)) + return generic_ivar_get(obj, id, undef); + break; } return undef; } @@ -1338,17 +1338,17 @@ rb_ivar_delete(VALUE obj, ID id, VALUE undef) case T_CLASS: case T_MODULE: IVAR_ACCESSOR_SHOULD_BE_MAIN_RACTOR(id); - if (RCLASS_IV_TBL(obj)) { + if (RCLASS_IV_TBL(obj)) { st_data_t id_data = (st_data_t)id, val; if (lock_st_delete(RCLASS_IV_TBL(obj), &id_data, &val)) { return (VALUE)val; } } - break; + break; default: - if (FL_TEST(obj, FL_EXIVAR)) - return generic_ivar_delete(obj, id, undef); - break; + if (FL_TEST(obj, FL_EXIVAR)) + return generic_ivar_delete(obj, id, undef); + break; } return undef; } @@ -1389,10 +1389,10 @@ iv_index_tbl_extend(struct ivar_update *ivup, ID id, VALUE klass) if (st_lookup(ivup->u.iv_index_tbl, (st_data_t)id, &ent_data)) { ent = (void *)ent_data; ivup->index = ent->index; - return; + return; } if (ivup->u.iv_index_tbl->num_entries >= INT_MAX) { - rb_raise(rb_eArgError, "too many instance variables"); + rb_raise(rb_eArgError, "too many instance variables"); } ent = ALLOC(struct rb_iv_index_tbl_entry); ent->index = ivup->index = (uint32_t)ivup->u.iv_index_tbl->num_entries; @@ -1627,16 +1627,16 @@ rb_ivar_defined(VALUE obj, ID id) (val = ROBJECT_IVPTR(obj)[index]) != Qundef) { return Qtrue; } - break; + break; case T_CLASS: case T_MODULE: if (RCLASS_IV_TBL(obj) && lock_st_is_member(RCLASS_IV_TBL(obj), (st_data_t)id)) - return Qtrue; - break; + return Qtrue; + break; default: - if (FL_TEST(obj, FL_EXIVAR)) - return generic_ivar_defined(obj, id); - break; + if (FL_TEST(obj, FL_EXIVAR)) + return generic_ivar_defined(obj, id); + break; } return Qfalse; } @@ -1728,8 +1728,8 @@ gen_ivar_copy(ID id, VALUE val, st_data_t arg) RB_VM_LOCK_LEAVE(); if (ivup.index >= c->ivtbl->numiv) { - uint32_t newsize = iv_index_tbl_newsize(&ivup); - c->ivtbl = gen_ivtbl_resize(c->ivtbl, newsize); + uint32_t newsize = iv_index_tbl_newsize(&ivup); + c->ivtbl = gen_ivtbl_resize(c->ivtbl, newsize); } c->ivtbl->ivptr[ivup.index] = val; @@ -1749,30 +1749,30 @@ rb_copy_generic_ivar(VALUE clone, VALUE obj) goto clear; } if (gen_ivtbl_get(obj, 0, &ivtbl)) { - struct givar_copy c; - uint32_t i; + struct givar_copy c; + uint32_t i; - if (gen_ivtbl_count(ivtbl) == 0) - goto clear; + if (gen_ivtbl_count(ivtbl) == 0) + goto clear; - if (gen_ivtbl_get(clone, 0, &c.ivtbl)) { - for (i = 0; i < c.ivtbl->numiv; i++) - c.ivtbl->ivptr[i] = Qundef; - } - else { - c.ivtbl = gen_ivtbl_resize(0, ivtbl->numiv); - FL_SET(clone, FL_EXIVAR); - } + if (gen_ivtbl_get(clone, 0, &c.ivtbl)) { + for (i = 0; i < c.ivtbl->numiv; i++) + c.ivtbl->ivptr[i] = Qundef; + } + else { + c.ivtbl = gen_ivtbl_resize(0, ivtbl->numiv); + FL_SET(clone, FL_EXIVAR); + } VALUE klass = rb_obj_class(clone); - c.iv_index_tbl = iv_index_tbl_make(clone, klass); + c.iv_index_tbl = iv_index_tbl_make(clone, klass); c.obj = clone; c.klass = klass; - gen_ivar_each(obj, gen_ivar_copy, (st_data_t)&c); - /* - * c.ivtbl may change in gen_ivar_copy due to realloc, - * no need to free - */ + gen_ivar_each(obj, gen_ivar_copy, (st_data_t)&c); + /* + * c.ivtbl may change in gen_ivar_copy due to realloc, + * no need to free + */ RB_VM_LOCK_ENTER(); { generic_ivtbl_no_ractor_check(clone); @@ -1817,23 +1817,23 @@ rb_ivar_foreach(VALUE obj, rb_ivar_foreach_callback_func *func, st_data_t arg) switch (BUILTIN_TYPE(obj)) { case T_OBJECT: obj_ivar_each(obj, func, arg); - break; + break; case T_CLASS: case T_MODULE: IVAR_ACCESSOR_SHOULD_BE_MAIN_RACTOR(0); - if (RCLASS_IV_TBL(obj)) { + if (RCLASS_IV_TBL(obj)) { RB_VM_LOCK_ENTER(); { st_foreach_safe(RCLASS_IV_TBL(obj), func, arg); } RB_VM_LOCK_LEAVE(); - } - break; + } + break; default: - if (FL_TEST(obj, FL_EXIVAR)) { - gen_ivar_each(obj, func, arg); - } - break; + if (FL_TEST(obj, FL_EXIVAR)) { + gen_ivar_each(obj, func, arg); + } + break; } } @@ -1846,32 +1846,32 @@ rb_ivar_count(VALUE obj) switch (BUILTIN_TYPE(obj)) { case T_OBJECT: - if (ROBJECT_IV_INDEX_TBL(obj) != 0) { - st_index_t i, count, num = ROBJECT_NUMIV(obj); - const VALUE *const ivptr = ROBJECT_IVPTR(obj); - for (i = count = 0; i < num; ++i) { - if (ivptr[i] != Qundef) { - count++; - } - } - return count; - } - break; + if (ROBJECT_IV_INDEX_TBL(obj) != 0) { + st_index_t i, count, num = ROBJECT_NUMIV(obj); + const VALUE *const ivptr = ROBJECT_IVPTR(obj); + for (i = count = 0; i < num; ++i) { + if (ivptr[i] != Qundef) { + count++; + } + } + return count; + } + break; case T_CLASS: case T_MODULE: - if ((tbl = RCLASS_IV_TBL(obj)) != 0) { - return tbl->num_entries; - } - break; + if ((tbl = RCLASS_IV_TBL(obj)) != 0) { + return tbl->num_entries; + } + break; default: - if (FL_TEST(obj, FL_EXIVAR)) { - struct gen_ivtbl *ivtbl; + if (FL_TEST(obj, FL_EXIVAR)) { + struct gen_ivtbl *ivtbl; - if (gen_ivtbl_get(obj, 0, &ivtbl)) { - return gen_ivtbl_count(ivtbl); - } - } - break; + if (gen_ivtbl_get(obj, 0, &ivtbl)) { + return gen_ivtbl_count(ivtbl); + } + } + break; } return 0; } @@ -1883,7 +1883,7 @@ ivar_i(st_data_t k, st_data_t v, st_data_t a) VALUE ary = (VALUE)a; if (rb_is_instance_id(key)) { - rb_ary_push(ary, ID2SYM(key)); + rb_ary_push(ary, ID2SYM(key)); } return ST_CONTINUE; } @@ -1923,15 +1923,15 @@ rb_obj_instance_variables(VALUE obj) check_id_type(obj, &(name), rb_is_##type##_id, rb_is_##type##_name, message, strlen(message)) static ID check_id_type(VALUE obj, VALUE *pname, - int (*valid_id_p)(ID), int (*valid_name_p)(VALUE), - const char *message, size_t message_len) + int (*valid_id_p)(ID), int (*valid_name_p)(VALUE), + const char *message, size_t message_len) { ID id = rb_check_id(pname); VALUE name = *pname; if (id ? !valid_id_p(id) : !valid_name_p(name)) { - rb_name_err_raise_str(rb_fstring_new(message, message_len), - obj, name); + rb_name_err_raise_str(rb_fstring_new(message, message_len), + obj, name); } return id; } @@ -1971,7 +1971,7 @@ rb_obj_remove_instance_variable(VALUE obj, VALUE name) rb_check_frozen(obj); if (!id) { - goto not_defined; + goto not_defined; } switch (BUILTIN_TYPE(obj)) { @@ -1983,27 +1983,27 @@ rb_obj_remove_instance_variable(VALUE obj, VALUE name) ROBJECT_IVPTR(obj)[index] = Qundef; return val; } - break; + break; case T_CLASS: case T_MODULE: IVAR_ACCESSOR_SHOULD_BE_MAIN_RACTOR(id); - n = id; - if (RCLASS_IV_TBL(obj) && lock_st_delete(RCLASS_IV_TBL(obj), &n, &v)) { - return (VALUE)v; - } - break; + n = id; + if (RCLASS_IV_TBL(obj) && lock_st_delete(RCLASS_IV_TBL(obj), &n, &v)) { + return (VALUE)v; + } + break; default: - if (FL_TEST(obj, FL_EXIVAR)) { - if (generic_ivar_remove(obj, id, &val)) { - return val; - } - } - break; + if (FL_TEST(obj, FL_EXIVAR)) { + if (generic_ivar_remove(obj, id, &val)) { + return val; + } + } + break; } not_defined: rb_name_err_raise("instance variable %1$s not defined", - obj, name); + obj, name); UNREACHABLE_RETURN(Qnil); } @@ -2012,11 +2012,11 @@ static void uninitialized_constant(VALUE klass, VALUE name) { if (klass && rb_class_real(klass) != rb_cObject) - rb_name_err_raise("uninitialized constant %2$s::%1$s", - klass, name); + rb_name_err_raise("uninitialized constant %2$s::%1$s", + klass, name); else - rb_name_err_raise("uninitialized constant %1$s", - klass, name); + rb_name_err_raise("uninitialized constant %1$s", + klass, name); } VALUE @@ -2070,8 +2070,8 @@ rb_mod_const_missing(VALUE klass, VALUE name) VALUE ref = GET_EC()->private_const_reference; rb_vm_pop_cfunc_frame(); if (ref) { - rb_name_err_raise("private constant %2$s::%1$s referenced", - ref, name); + rb_name_err_raise("private constant %2$s::%1$s referenced", + ref, name); } uninitialized_constant(klass, name); @@ -2755,8 +2755,8 @@ rb_autoload_at_p(VALUE mod, ID id, int recur) while (!autoload_defined_p(mod, id)) { if (!recur) return Qnil; - mod = RCLASS_SUPER(mod); - if (!mod) return Qnil; + mod = RCLASS_SUPER(mod); + if (!mod) return Qnil; } load = check_autoload_required(mod, id, 0); if (!load) return Qnil; @@ -2768,13 +2768,13 @@ rb_const_warn_if_deprecated(const rb_const_entry_t *ce, VALUE klass, ID id) { if (RB_CONST_DEPRECATED_P(ce) && rb_warning_category_enabled_p(RB_WARN_CATEGORY_DEPRECATED)) { - if (klass == rb_cObject) { + if (klass == rb_cObject) { rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "constant ::%"PRIsVALUE" is deprecated", QUOTE_ID(id)); - } - else { + } + else { rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "constant %"PRIsVALUE"::%"PRIsVALUE" is deprecated", - rb_class_name(klass), QUOTE_ID(id)); - } + rb_class_name(klass), QUOTE_ID(id)); + } } } @@ -3017,7 +3017,7 @@ sv_i(ID key, VALUE v, void *a) st_table *tbl = a; if (rb_is_const_id(key)) { - st_update(tbl, (st_data_t)key, cv_i_update, (st_data_t)ce); + st_update(tbl, (st_data_t)key, cv_i_update, (st_data_t)ce); } return ID_TABLE_CONTINUE; } @@ -3026,7 +3026,7 @@ static enum rb_id_table_iterator_result rb_local_constants_i(ID const_name, VALUE const_value, void *ary) { if (rb_is_const_id(const_name) && !RB_CONST_PRIVATE_P((rb_const_entry_t *)const_value)) { - rb_ary_push((VALUE)ary, ID2SYM(const_name)); + rb_ary_push((VALUE)ary, ID2SYM(const_name)); } return ID_TABLE_CONTINUE; } @@ -3054,7 +3054,7 @@ rb_mod_const_at(VALUE mod, void *data) { st_table *tbl = data; if (!tbl) { - tbl = st_init_numtable(); + tbl = st_init_numtable(); } if (RCLASS_CONST_TBL(mod)) { RB_VM_LOCK_ENTER(); @@ -3071,10 +3071,10 @@ rb_mod_const_of(VALUE mod, void *data) { VALUE tmp = mod; for (;;) { - data = rb_mod_const_at(tmp, data); - tmp = RCLASS_SUPER(tmp); - if (!tmp) break; - if (tmp == rb_cObject && mod != rb_cObject) break; + data = rb_mod_const_at(tmp, data); + tmp = RCLASS_SUPER(tmp); + if (!tmp) break; + if (tmp == rb_cObject && mod != rb_cObject) break; } return data; } @@ -3128,10 +3128,10 @@ rb_mod_constants(int argc, const VALUE *argv, VALUE mod) if (rb_check_arity(argc, 0, 1)) inherit = RTEST(argv[0]); if (inherit) { - return rb_const_list(rb_mod_const_of(mod, 0)); + return rb_const_list(rb_mod_const_of(mod, 0)); } else { - return rb_local_constants(mod); + return rb_local_constants(mod); } } @@ -3145,27 +3145,27 @@ rb_const_defined_0(VALUE klass, ID id, int exclude, int recurse, int visibility) tmp = klass; retry: while (tmp) { - if ((ce = rb_const_lookup(tmp, id))) { - if (visibility && RB_CONST_PRIVATE_P(ce)) { - return (int)Qfalse; - } - if (ce->value == Qundef && !check_autoload_required(tmp, id, 0) && - !rb_autoloading_value(tmp, id, NULL, NULL)) - return (int)Qfalse; + if ((ce = rb_const_lookup(tmp, id))) { + if (visibility && RB_CONST_PRIVATE_P(ce)) { + return (int)Qfalse; + } + if (ce->value == Qundef && !check_autoload_required(tmp, id, 0) && + !rb_autoloading_value(tmp, id, NULL, NULL)) + return (int)Qfalse; - if (exclude && tmp == rb_cObject && klass != rb_cObject) { - return (int)Qfalse; - } + if (exclude && tmp == rb_cObject && klass != rb_cObject) { + return (int)Qfalse; + } - return (int)Qtrue; - } - if (!recurse) break; - tmp = RCLASS_SUPER(tmp); + return (int)Qtrue; + } + if (!recurse) break; + tmp = RCLASS_SUPER(tmp); } if (!exclude && !mod_retry && BUILTIN_TYPE(klass) == T_MODULE) { - mod_retry = 1; - tmp = rb_cObject; - goto retry; + mod_retry = 1; + tmp = rb_cObject; + goto retry; } return (int)Qfalse; } @@ -3408,7 +3408,7 @@ const_tbl_update(struct autoload_const *ac, int autoload_force) static void setup_const_entry(rb_const_entry_t *ce, VALUE klass, VALUE val, - rb_const_flag_t visibility) + rb_const_flag_t visibility) { ce->flag = visibility; RB_OBJ_WRITE(klass, &ce->value, val); @@ -3435,7 +3435,7 @@ rb_define_global_const(const char *name, VALUE val) static void set_const_visibility(VALUE mod, int argc, const VALUE *argv, - rb_const_flag_t flag, rb_const_flag_t mask) + rb_const_flag_t flag, rb_const_flag_t mask) { int i; rb_const_entry_t *ce; @@ -3443,35 +3443,35 @@ set_const_visibility(VALUE mod, int argc, const VALUE *argv, rb_class_modify_check(mod); if (argc == 0) { - rb_warning("%"PRIsVALUE" with no argument is just ignored", - QUOTE_ID(rb_frame_callee())); - return; + rb_warning("%"PRIsVALUE" with no argument is just ignored", + QUOTE_ID(rb_frame_callee())); + return; } for (i = 0; i < argc; i++) { - struct autoload_const *ac; - VALUE val = argv[i]; - id = rb_check_id(&val); - if (!id) { + struct autoload_const *ac; + VALUE val = argv[i]; + id = rb_check_id(&val); + if (!id) { undefined_constant(mod, val); - } - if ((ce = rb_const_lookup(mod, id))) { - ce->flag &= ~mask; - ce->flag |= flag; - if (ce->value == Qundef) { - struct autoload_data *ele; + } + if ((ce = rb_const_lookup(mod, id))) { + ce->flag &= ~mask; + ce->flag |= flag; + if (ce->value == Qundef) { + struct autoload_data *ele; - ele = autoload_data_for_named_constant(mod, id, &ac); - if (ele) { - ac->flag &= ~mask; - ac->flag |= flag; - } - } + ele = autoload_data_for_named_constant(mod, id, &ac); + if (ele) { + ac->flag &= ~mask; + ac->flag |= flag; + } + } rb_clear_constant_cache_for_id(id); - } - else { + } + else { undefined_constant(mod, ID2SYM(id)); - } + } } } @@ -3550,7 +3550,7 @@ static VALUE original_module(VALUE c) { if (RB_TYPE_P(c, T_ICLASS)) - return RBASIC(c)->klass; + return RBASIC(c)->klass; return c; } @@ -3565,10 +3565,10 @@ static VALUE cvar_front_klass(VALUE klass) { if (FL_TEST(klass, FL_SINGLETON)) { - VALUE obj = rb_ivar_get(klass, id__attached__); + VALUE obj = rb_ivar_get(klass, id__attached__); if (rb_namespace_p(obj)) { - return obj; - } + return obj; + } } return RCLASS_SUPER(klass); } @@ -3577,17 +3577,17 @@ static void cvar_overtaken(VALUE front, VALUE target, ID id) { if (front && target != front) { - st_data_t did = (st_data_t)id; + st_data_t did = (st_data_t)id; if (original_module(front) != original_module(target)) { rb_raise(rb_eRuntimeError, "class variable % "PRIsVALUE" of %"PRIsVALUE" is overtaken by %"PRIsVALUE"", - ID2SYM(id), rb_class_name(original_module(front)), - rb_class_name(original_module(target))); - } - if (BUILTIN_TYPE(front) == T_CLASS) { - st_delete(RCLASS_IV_TBL(front), &did, 0); - } + ID2SYM(id), rb_class_name(original_module(front)), + rb_class_name(original_module(target))); + } + if (BUILTIN_TYPE(front) == T_CLASS) { + st_delete(RCLASS_IV_TBL(front), &did, 0); + } } } @@ -3604,7 +3604,7 @@ find_cvar(VALUE klass, VALUE * front, VALUE * target, ID id) } for (klass = cvar_front_klass(klass); klass; klass = RCLASS_SUPER(klass)) { - if (cvar_lookup_at(klass, id, (&v))) { + if (cvar_lookup_at(klass, id, (&v))) { if (!*front) { *front = klass; } @@ -3617,9 +3617,9 @@ find_cvar(VALUE klass, VALUE * front, VALUE * target, ID id) #define CVAR_FOREACH_ANCESTORS(klass, v, r) \ for (klass = cvar_front_klass(klass); klass; klass = RCLASS_SUPER(klass)) { \ - if (cvar_lookup_at(klass, id, (v))) { \ - r; \ - } \ + if (cvar_lookup_at(klass, id, (v))) { \ + r; \ + } \ } #define CVAR_LOOKUP(v,r) do {\ @@ -3650,10 +3650,10 @@ rb_cvar_set(VALUE klass, ID id, VALUE val) tmp = klass; CVAR_LOOKUP(0, {if (!front) front = klass; target = klass;}); if (target) { - cvar_overtaken(front, target, id); + cvar_overtaken(front, target, id); } else { - target = tmp; + target = tmp; } if (RB_TYPE_P(target, T_ICLASS)) { @@ -3704,8 +3704,8 @@ rb_cvar_find(VALUE klass, ID id, VALUE *front) value = find_cvar(klass, front, &target, id); if (!target) { - rb_name_err_raise("uninitialized class variable %1$s in %2$s", - klass, ID2SYM(id)); + rb_name_err_raise("uninitialized class variable %1$s in %2$s", + klass, ID2SYM(id)); } cvar_overtaken(*front, target, id); return (VALUE)value; @@ -3731,8 +3731,8 @@ cv_intern(VALUE klass, const char *name) { ID id = rb_intern(name); if (!rb_is_class_id(id)) { - rb_name_err_raise("wrong class variable name %1$s", - klass, rb_str_new_cstr(name)); + rb_name_err_raise("wrong class variable name %1$s", + klass, rb_str_new_cstr(name)); } return id; } @@ -3764,7 +3764,7 @@ cv_i(st_data_t k, st_data_t v, st_data_t a) st_table *tbl = (st_table *)a; if (rb_is_class_id(key)) { - st_update(tbl, (st_data_t)key, cv_i_update, 0); + st_update(tbl, (st_data_t)key, cv_i_update, 0); } return ST_CONTINUE; } @@ -3774,10 +3774,10 @@ mod_cvar_at(VALUE mod, void *data) { st_table *tbl = data; if (!tbl) { - tbl = st_init_numtable(); + tbl = st_init_numtable(); } if (RCLASS_IV_TBL(mod)) { - st_foreach_safe(RCLASS_IV_TBL(mod), cv_i, (st_data_t)tbl); + st_foreach_safe(RCLASS_IV_TBL(mod), cv_i, (st_data_t)tbl); } return tbl; } @@ -3793,9 +3793,9 @@ mod_cvar_of(VALUE mod, void *data) } } for (;;) { - data = mod_cvar_at(tmp, data); - tmp = RCLASS_SUPER(tmp); - if (!tmp) break; + data = mod_cvar_at(tmp, data); + tmp = RCLASS_SUPER(tmp); + if (!tmp) break; } return data; } @@ -3850,10 +3850,10 @@ rb_mod_class_variables(int argc, const VALUE *argv, VALUE mod) if (rb_check_arity(argc, 0, 1)) inherit = RTEST(argv[0]); if (inherit) { - tbl = mod_cvar_of(mod, 0); + tbl = mod_cvar_of(mod, 0); } else { - tbl = mod_cvar_at(mod, 0); + tbl = mod_cvar_at(mod, 0); } return cvar_list(tbl); } @@ -3888,10 +3888,10 @@ rb_mod_remove_cvar(VALUE mod, VALUE name) } rb_check_frozen(mod); if (RCLASS_IV_TBL(mod) && st_delete(RCLASS_IV_TBL(mod), &n, &val)) { - return (VALUE)val; + return (VALUE)val; } if (rb_cvar_defined(mod, id)) { - rb_name_err_raise("cannot remove %1$s for %2$s", mod, ID2SYM(id)); + rb_name_err_raise("cannot remove %1$s for %2$s", mod, ID2SYM(id)); } not_defined: rb_name_err_raise("class variable %1$s not defined for %2$s", diff --git a/vm.c b/vm.c index 4538c8b607..0004a2676d 100644 --- a/vm.c +++ b/vm.c @@ -70,7 +70,7 @@ static inline const VALUE * VM_EP_LEP(const VALUE *ep) { while (!VM_ENV_LOCAL_P(ep)) { - ep = VM_ENV_PREV_EP(ep); + ep = VM_ENV_PREV_EP(ep); } return ep; } @@ -79,19 +79,19 @@ static inline const rb_control_frame_t * rb_vm_search_cf_from_ep(const rb_execution_context_t *ec, const rb_control_frame_t *cfp, const VALUE * const ep) { if (!ep) { - return NULL; + return NULL; } else { - const rb_control_frame_t * const eocfp = RUBY_VM_END_CONTROL_FRAME(ec); /* end of control frame pointer */ + const rb_control_frame_t * const eocfp = RUBY_VM_END_CONTROL_FRAME(ec); /* end of control frame pointer */ - while (cfp < eocfp) { - if (cfp->ep == ep) { - return cfp; - } - cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); - } + while (cfp < eocfp) { + if (cfp->ep == ep) { + return cfp; + } + cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); + } - return NULL; + return NULL; } } @@ -143,10 +143,10 @@ VM_CFP_IN_HEAP_P(const rb_execution_context_t *ec, const rb_control_frame_t *cfp VM_ASSERT(start != NULL); if (start <= (VALUE *)cfp && (VALUE *)cfp < end) { - return FALSE; + return FALSE; } else { - return TRUE; + return TRUE; } } @@ -158,10 +158,10 @@ VM_EP_IN_HEAP_P(const rb_execution_context_t *ec, const VALUE *ep) VM_ASSERT(start != NULL); if (start <= ep && ep < end) { - return FALSE; + return FALSE; } else { - return TRUE; + return TRUE; } } @@ -169,19 +169,19 @@ static int vm_ep_in_heap_p_(const rb_execution_context_t *ec, const VALUE *ep) { if (VM_EP_IN_HEAP_P(ec, ep)) { - VALUE envval = ep[VM_ENV_DATA_INDEX_ENV]; /* VM_ENV_ENVVAL(ep); */ + VALUE envval = ep[VM_ENV_DATA_INDEX_ENV]; /* VM_ENV_ENVVAL(ep); */ - if (envval != Qundef) { - const rb_env_t *env = (const rb_env_t *)envval; + if (envval != Qundef) { + const rb_env_t *env = (const rb_env_t *)envval; - VM_ASSERT(vm_assert_env(envval)); - VM_ASSERT(VM_ENV_FLAGS(ep, VM_ENV_FLAG_ESCAPED)); - VM_ASSERT(env->ep == ep); - } - return TRUE; + VM_ASSERT(vm_assert_env(envval)); + VM_ASSERT(VM_ENV_FLAGS(ep, VM_ENV_FLAG_ESCAPED)); + VM_ASSERT(env->ep == ep); + } + return TRUE; } else { - return FALSE; + return FALSE; } } @@ -235,8 +235,8 @@ vm_cref_new0(VALUE klass, rb_method_visibility_t visi, int module_func, rb_cref_ /* scope */ union { - rb_scope_visibility_t visi; - VALUE value; + rb_scope_visibility_t visi; + VALUE value; } scope_visi; scope_visi.visi.method_visi = visi; @@ -244,12 +244,12 @@ vm_cref_new0(VALUE klass, rb_method_visibility_t visi, int module_func, rb_cref_ /* refinements */ if (prev_cref != NULL && prev_cref != (void *)1 /* TODO: why CREF_NEXT(cref) is 1? */) { - refinements = CREF_REFINEMENTS(prev_cref); + refinements = CREF_REFINEMENTS(prev_cref); - if (!NIL_P(refinements)) { - omod_shared = TRUE; - CREF_OMOD_SHARED_SET(prev_cref); - } + if (!NIL_P(refinements)) { + omod_shared = TRUE; + CREF_OMOD_SHARED_SET(prev_cref); + } } VM_ASSERT(singleton || klass); @@ -327,7 +327,7 @@ vm_cref_new_toplevel(rb_execution_context_t *ec) VALUE top_wrapper = rb_ec_thread_ptr(ec)->top_wrapper; if (top_wrapper) { - cref = vm_cref_new(top_wrapper, METHOD_VISI_PRIVATE, FALSE, cref, FALSE, FALSE); + cref = vm_cref_new(top_wrapper, METHOD_VISI_PRIVATE, FALSE, cref, FALSE, FALSE); } return cref; @@ -345,8 +345,8 @@ vm_cref_dump(const char *mesg, const rb_cref_t *cref) ruby_debug_printf("vm_cref_dump: %s (%p)\n", mesg, (void *)cref); while (cref) { - ruby_debug_printf("= cref| klass: %s\n", RSTRING_PTR(rb_class_path(CREF_CLASS(cref)))); - cref = CREF_NEXT(cref); + ruby_debug_printf("= cref| klass: %s\n", RSTRING_PTR(rb_class_path(CREF_CLASS(cref)))); + cref = CREF_NEXT(cref); } } @@ -467,36 +467,36 @@ rb_vm_inc_const_missing_count(void) MJIT_FUNC_EXPORTED int rb_dtrace_setup(rb_execution_context_t *ec, VALUE klass, ID id, - struct ruby_dtrace_method_hook_args *args) + struct ruby_dtrace_method_hook_args *args) { enum ruby_value_type type; if (!klass) { - if (!ec) ec = GET_EC(); - if (!rb_ec_frame_method_id_and_class(ec, &id, 0, &klass) || !klass) - return FALSE; + if (!ec) ec = GET_EC(); + if (!rb_ec_frame_method_id_and_class(ec, &id, 0, &klass) || !klass) + return FALSE; } if (RB_TYPE_P(klass, T_ICLASS)) { - klass = RBASIC(klass)->klass; + klass = RBASIC(klass)->klass; } else if (FL_TEST(klass, FL_SINGLETON)) { - klass = rb_attr_get(klass, id__attached__); - if (NIL_P(klass)) return FALSE; + klass = rb_attr_get(klass, id__attached__); + if (NIL_P(klass)) return FALSE; } type = BUILTIN_TYPE(klass); if (type == T_CLASS || type == T_ICLASS || type == T_MODULE) { - VALUE name = rb_class_path(klass); - const char *classname, *filename; - const char *methodname = rb_id2name(id); - if (methodname && (filename = rb_source_location_cstr(&args->line_no)) != 0) { - if (NIL_P(name) || !(classname = StringValuePtr(name))) - classname = ""; - args->classname = classname; - args->methodname = methodname; - args->filename = filename; - args->klass = klass; - args->name = name; - return TRUE; - } + VALUE name = rb_class_path(klass); + const char *classname, *filename; + const char *methodname = rb_id2name(id); + if (methodname && (filename = rb_source_location_cstr(&args->line_no)) != 0) { + if (NIL_P(name) || !(classname = StringValuePtr(name))) + classname = ""; + args->classname = classname; + args->methodname = methodname; + args->filename = filename; + args->klass = klass; + args->name = name; + return TRUE; + } } return FALSE; } @@ -532,29 +532,29 @@ vm_stat(int argc, VALUE *argv, VALUE self) if (rb_check_arity(argc, 0, 1) == 1) { arg = argv[0]; - if (SYMBOL_P(arg)) - key = arg; - else if (RB_TYPE_P(arg, T_HASH)) - hash = arg; - else - rb_raise(rb_eTypeError, "non-hash or symbol given"); + if (SYMBOL_P(arg)) + key = arg; + else if (RB_TYPE_P(arg, T_HASH)) + hash = arg; + else + rb_raise(rb_eTypeError, "non-hash or symbol given"); } else { - hash = rb_hash_new(); + hash = rb_hash_new(); } #define S(s) sym_##s = ID2SYM(rb_intern_const(#s)) S(constant_cache_invalidations); S(constant_cache_misses); - S(class_serial); - S(global_cvar_state); + S(class_serial); + S(global_cvar_state); #undef S #define SET(name, attr) \ if (key == sym_##name) \ - return SERIALT2NUM(attr); \ + return SERIALT2NUM(attr); \ else if (hash != Qnil) \ - rb_hash_aset(hash, sym_##name, SERIALT2NUM(attr)); + rb_hash_aset(hash, sym_##name, SERIALT2NUM(attr)); SET(constant_cache_invalidations, ruby_vm_constant_cache_invalidations); SET(constant_cache_misses, ruby_vm_constant_cache_misses); @@ -563,7 +563,7 @@ vm_stat(int argc, VALUE *argv, VALUE self) #undef SET if (!NIL_P(key)) { /* matched key should return above */ - rb_raise(rb_eArgError, "unknown key: %"PRIsVALUE, rb_sym2str(key)); + rb_raise(rb_eArgError, "unknown key: %"PRIsVALUE, rb_sym2str(key)); } return hash; @@ -575,13 +575,13 @@ static void vm_set_top_stack(rb_execution_context_t *ec, const rb_iseq_t *iseq) { if (ISEQ_BODY(iseq)->type != ISEQ_TYPE_TOP) { - rb_raise(rb_eTypeError, "Not a toplevel InstructionSequence"); + rb_raise(rb_eTypeError, "Not a toplevel InstructionSequence"); } /* for return */ vm_push_frame(ec, iseq, VM_FRAME_MAGIC_TOP | VM_ENV_FLAG_LOCAL | VM_FRAME_FLAG_FINISH, rb_ec_thread_ptr(ec)->top_self, - VM_BLOCK_HANDLER_NONE, - (VALUE)vm_cref_new_toplevel(ec), /* cref or me */ + VM_BLOCK_HANDLER_NONE, + (VALUE)vm_cref_new_toplevel(ec), /* cref or me */ ISEQ_BODY(iseq)->iseq_encoded, ec->cfp->sp, ISEQ_BODY(iseq)->local_table_size, ISEQ_BODY(iseq)->stack_max); } @@ -590,8 +590,8 @@ static void vm_set_eval_stack(rb_execution_context_t *ec, const rb_iseq_t *iseq, const rb_cref_t *cref, const struct rb_block *base_block) { vm_push_frame(ec, iseq, VM_FRAME_MAGIC_EVAL | VM_FRAME_FLAG_FINISH, - vm_block_self(base_block), VM_GUARDED_PREV_EP(vm_block_ep(base_block)), - (VALUE)cref, /* cref or me */ + vm_block_self(base_block), VM_GUARDED_PREV_EP(vm_block_ep(base_block)), + (VALUE)cref, /* cref or me */ ISEQ_BODY(iseq)->iseq_encoded, ec->cfp->sp, ISEQ_BODY(iseq)->local_table_size, ISEQ_BODY(iseq)->stack_max); @@ -610,7 +610,7 @@ vm_set_main_stack(rb_execution_context_t *ec, const rb_iseq_t *iseq) /* save binding */ if (ISEQ_BODY(iseq)->local_table_size > 0) { - vm_bind_update_env(toplevel_binding, bind, vm_make_env_object(ec, ec->cfp)); + vm_bind_update_env(toplevel_binding, bind, vm_make_env_object(ec, ec->cfp)); } } @@ -618,10 +618,10 @@ rb_control_frame_t * rb_vm_get_binding_creatable_next_cfp(const rb_execution_context_t *ec, const rb_control_frame_t *cfp) { while (!RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(ec, cfp)) { - if (cfp->iseq) { - return (rb_control_frame_t *)cfp; - } - cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); + if (cfp->iseq) { + return (rb_control_frame_t *)cfp; + } + cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); } return 0; } @@ -630,10 +630,10 @@ MJIT_FUNC_EXPORTED rb_control_frame_t * rb_vm_get_ruby_level_next_cfp(const rb_execution_context_t *ec, const rb_control_frame_t *cfp) { while (!RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(ec, cfp)) { - if (VM_FRAME_RUBYFRAME_P(cfp)) { - return (rb_control_frame_t *)cfp; - } - cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); + if (VM_FRAME_RUBYFRAME_P(cfp)) { + return (rb_control_frame_t *)cfp; + } + cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); } return 0; } @@ -644,20 +644,20 @@ static rb_control_frame_t * vm_get_ruby_level_caller_cfp(const rb_execution_context_t *ec, const rb_control_frame_t *cfp) { if (VM_FRAME_RUBYFRAME_P(cfp)) { - return (rb_control_frame_t *)cfp; + return (rb_control_frame_t *)cfp; } cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); while (!RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(ec, cfp)) { - if (VM_FRAME_RUBYFRAME_P(cfp)) { - return (rb_control_frame_t *)cfp; - } + if (VM_FRAME_RUBYFRAME_P(cfp)) { + return (rb_control_frame_t *)cfp; + } - if (VM_ENV_FLAGS(cfp->ep, VM_FRAME_FLAG_PASSED) == FALSE) { - break; - } - cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); + if (VM_ENV_FLAGS(cfp->ep, VM_FRAME_FLAG_PASSED) == FALSE) { + break; + } + cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); } return 0; } @@ -682,14 +682,14 @@ rb_vm_rewind_cfp(rb_execution_context_t *ec, rb_control_frame_t *cfp) /* check skipped frame */ while (ec->cfp != cfp) { #if VMDEBUG - printf("skipped frame: %s\n", vm_frametype_name(ec->cfp)); + printf("skipped frame: %s\n", vm_frametype_name(ec->cfp)); #endif - if (VM_FRAME_TYPE(ec->cfp) != VM_FRAME_MAGIC_CFUNC) { - rb_vm_pop_frame(ec); - } - else { /* unlikely path */ - rb_vm_pop_cfunc_frame(); - } + if (VM_FRAME_TYPE(ec->cfp) != VM_FRAME_MAGIC_CFUNC) { + rb_vm_pop_frame(ec); + } + else { /* unlikely path */ + rb_vm_pop_cfunc_frame(); + } } } @@ -711,11 +711,11 @@ ruby_vm_run_at_exit_hooks(rb_vm_t *vm) rb_at_exit_list *l = vm->at_exit; while (l) { - rb_at_exit_list* t = l->next; - rb_vm_at_exit_func *func = l->func; - ruby_xfree(l); - l = t; - (*func)(vm); + rb_at_exit_list* t = l->next; + rb_vm_at_exit_func *func = l->func; + ruby_xfree(l); + l = t; + (*func)(vm); } } @@ -732,9 +732,9 @@ check_env(const rb_env_t *env) dp(env->ep[1]); ruby_debug_printf("ep: %10p\n", (void *)env->ep); if (rb_vm_env_prev_env(env)) { - fputs(">>\n", stderr); - check_env_value(rb_vm_env_prev_env(env)); - fputs("<<\n", stderr); + fputs(">>\n", stderr); + check_env_value(rb_vm_env_prev_env(env)); + fputs("<<\n", stderr); } return 1; } @@ -743,7 +743,7 @@ static VALUE check_env_value(const rb_env_t *env) { if (check_env(env)) { - return (VALUE)env; + return (VALUE)env; } rb_bug("invalid env"); return Qnil; /* unreachable */ @@ -775,11 +775,11 @@ vm_make_env_each(const rb_execution_context_t * const ec, rb_control_frame_t *co int local_size, env_size; if (VM_ENV_ESCAPED_P(ep)) { - return VM_ENV_ENVVAL(ep); + return VM_ENV_ENVVAL(ep); } if (!VM_ENV_LOCAL_P(ep)) { - const VALUE *prev_ep = VM_ENV_PREV_EP(ep); + const VALUE *prev_ep = VM_ENV_PREV_EP(ep); if (!VM_ENV_ESCAPED_P(prev_ep)) { rb_control_frame_t *prev_cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); @@ -793,16 +793,16 @@ vm_make_env_each(const rb_execution_context_t * const ec, rb_control_frame_t *co } } else { - VALUE block_handler = VM_ENV_BLOCK_HANDLER(ep); + VALUE block_handler = VM_ENV_BLOCK_HANDLER(ep); - if (block_handler != VM_BLOCK_HANDLER_NONE) { + if (block_handler != VM_BLOCK_HANDLER_NONE) { VALUE blockprocval = vm_block_handler_escape(ec, block_handler); - VM_STACK_ENV_WRITE(ep, VM_ENV_DATA_INDEX_SPECVAL, blockprocval); - } + VM_STACK_ENV_WRITE(ep, VM_ENV_DATA_INDEX_SPECVAL, blockprocval); + } } if (!VM_FRAME_RUBYFRAME_P(cfp)) { - local_size = VM_ENV_DATA_SIZE; + local_size = VM_ENV_DATA_SIZE; } else { local_size = ISEQ_BODY(cfp->iseq)->local_table_size + VM_ENV_DATA_SIZE; @@ -821,16 +821,16 @@ vm_make_env_each(const rb_execution_context_t * const ec, rb_control_frame_t *co */ env_size = local_size + - 1 /* envval */; + 1 /* envval */; env_body = ALLOC_N(VALUE, env_size); MEMCPY(env_body, ep - (local_size - 1 /* specval */), VALUE, local_size); #if 0 for (i = 0; i < local_size; i++) { - if (VM_FRAME_RUBYFRAME_P(cfp)) { - /* clear value stack for GC */ - ep[-local_size + i] = 0; - } + if (VM_FRAME_RUBYFRAME_P(cfp)) { + /* clear value stack for GC */ + ep[-local_size + i] = 0; + } } #endif @@ -851,7 +851,7 @@ vm_make_env_object(const rb_execution_context_t *ec, rb_control_frame_t *cfp) VALUE envval = vm_make_env_each(ec, cfp); if (PROCDEBUG) { - check_env_value((const rb_env_t *)envval); + check_env_value((const rb_env_t *)envval); } return envval; @@ -862,8 +862,8 @@ rb_vm_stack_to_heap(rb_execution_context_t *ec) { rb_control_frame_t *cfp = ec->cfp; while ((cfp = rb_vm_get_binding_creatable_next_cfp(ec, cfp)) != 0) { - vm_make_env_object(ec, cfp); - cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); + vm_make_env_object(ec, cfp); + cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); } } @@ -873,7 +873,7 @@ rb_vm_env_prev_env(const rb_env_t *env) const VALUE *ep = env->ep; if (VM_ENV_LOCAL_P(ep)) { - return NULL; + return NULL; } else { const VALUE *prev_ep = VM_ENV_PREV_EP(ep); @@ -897,7 +897,7 @@ collect_local_variables_in_env(const rb_env_t *env, const struct local_var_list { do { if (VM_ENV_FLAGS(env->ep, VM_ENV_FLAG_ISOLATED)) break; - collect_local_variables_in_iseq(env->iseq, vars); + collect_local_variables_in_iseq(env->iseq, vars); } while ((env = rb_vm_env_prev_env(env)) != NULL); } @@ -905,11 +905,11 @@ static int vm_collect_local_variables_in_heap(const VALUE *ep, const struct local_var_list *vars) { if (VM_ENV_ESCAPED_P(ep)) { - collect_local_variables_in_env(VM_ENV_ENVVAL_PTR(ep), vars); - return 1; + collect_local_variables_in_env(VM_ENV_ENVVAL_PTR(ep), vars); + return 1; } else { - return 0; + return 0; } } @@ -937,9 +937,9 @@ rb_iseq_local_variables(const rb_iseq_t *iseq) static VALUE vm_proc_create_from_captured(VALUE klass, - const struct rb_captured_block *captured, - enum rb_block_type block_type, - int8_t is_from_method, int8_t is_lambda) + const struct rb_captured_block *captured, + enum rb_block_type block_type, + int8_t is_from_method, int8_t is_lambda) { VALUE procval = rb_proc_alloc(klass); rb_proc_t *proc = RTYPEDDATA_DATA(procval); @@ -965,16 +965,16 @@ rb_vm_block_copy(VALUE obj, const struct rb_block *dst, const struct rb_block *s switch (vm_block_type(src)) { case block_type_iseq: case block_type_ifunc: - RB_OBJ_WRITE(obj, &dst->as.captured.self, src->as.captured.self); - RB_OBJ_WRITE(obj, &dst->as.captured.code.val, src->as.captured.code.val); - rb_vm_block_ep_update(obj, dst, src->as.captured.ep); - break; + RB_OBJ_WRITE(obj, &dst->as.captured.self, src->as.captured.self); + RB_OBJ_WRITE(obj, &dst->as.captured.code.val, src->as.captured.code.val); + rb_vm_block_ep_update(obj, dst, src->as.captured.ep); + break; case block_type_symbol: - RB_OBJ_WRITE(obj, &dst->as.symbol, src->as.symbol); - break; + RB_OBJ_WRITE(obj, &dst->as.symbol, src->as.symbol); + break; case block_type_proc: - RB_OBJ_WRITE(obj, &dst->as.proc, src->as.proc); - break; + RB_OBJ_WRITE(obj, &dst->as.proc, src->as.proc); + break; } } @@ -1214,15 +1214,15 @@ rb_vm_make_proc_lambda(const rb_execution_context_t *ec, const struct rb_capture VALUE procval; if (!VM_ENV_ESCAPED_P(captured->ep)) { - rb_control_frame_t *cfp = VM_CAPTURED_BLOCK_TO_CFP(captured); - vm_make_env_object(ec, cfp); + rb_control_frame_t *cfp = VM_CAPTURED_BLOCK_TO_CFP(captured); + vm_make_env_object(ec, cfp); } VM_ASSERT(VM_EP_IN_HEAP_P(ec, captured->ep)); VM_ASSERT(imemo_type_p(captured->code.val, imemo_iseq) || - imemo_type_p(captured->code.val, imemo_ifunc)); + imemo_type_p(captured->code.val, imemo_ifunc)); procval = vm_proc_create_from_captured(klass, captured, - imemo_type(captured->code.val) == imemo_iseq ? block_type_iseq : block_type_ifunc, FALSE, is_lambda); + imemo_type(captured->code.val) == imemo_iseq ? block_type_iseq : block_type_ifunc, FALSE, is_lambda); return procval; } @@ -1237,7 +1237,7 @@ rb_vm_make_binding(const rb_execution_context_t *ec, const rb_control_frame_t *s rb_binding_t *bind; if (cfp == 0 || ruby_level_cfp == 0) { - rb_raise(rb_eRuntimeError, "Can't create Binding Object on top of Fiber."); + rb_raise(rb_eRuntimeError, "Can't create Binding Object on top of Fiber."); } if (!VM_FRAME_RUBYFRAME_P(src_cfp) && !VM_FRAME_RUBYFRAME_P(RUBY_VM_PREVIOUS_CONTROL_FRAME(src_cfp))) { @@ -1288,8 +1288,8 @@ rb_binding_add_dynavars(VALUE bindval, rb_binding_t *bind, int dyncount, const I iseq = rb_iseq_new(&ast, ISEQ_BODY(base_iseq)->location.label, path, realpath, base_iseq, ISEQ_TYPE_EVAL); } else { - VALUE tempstr = rb_fstring_lit(""); - iseq = rb_iseq_new_top(&ast, tempstr, tempstr, tempstr, NULL); + VALUE tempstr = rb_fstring_lit(""); + iseq = rb_iseq_new_top(&ast, tempstr, tempstr, tempstr, NULL); } tmp_node.nd_tbl = 0; /* reset table */ ALLOCV_END(idtmp); @@ -1310,10 +1310,10 @@ invoke_block(rb_execution_context_t *ec, const rb_iseq_t *iseq, VALUE self, cons int arg_size = ISEQ_BODY(iseq)->param.size; vm_push_frame(ec, iseq, type | VM_FRAME_FLAG_FINISH, self, - VM_GUARDED_PREV_EP(captured->ep), - (VALUE)cref, /* cref or method */ + VM_GUARDED_PREV_EP(captured->ep), + (VALUE)cref, /* cref or method */ ISEQ_BODY(iseq)->iseq_encoded + opt_pc, - ec->cfp->sp + arg_size, + ec->cfp->sp + arg_size, ISEQ_BODY(iseq)->local_table_size - arg_size, ISEQ_BODY(iseq)->stack_max); return vm_exec(ec, true); @@ -1329,10 +1329,10 @@ invoke_bmethod(rb_execution_context_t *ec, const rb_iseq_t *iseq, VALUE self, co VM_ASSERT(me->def->type == VM_METHOD_TYPE_BMETHOD); vm_push_frame(ec, iseq, type | VM_FRAME_FLAG_BMETHOD, self, - VM_GUARDED_PREV_EP(captured->ep), - (VALUE)me, + VM_GUARDED_PREV_EP(captured->ep), + (VALUE)me, ISEQ_BODY(iseq)->iseq_encoded + opt_pc, - ec->cfp->sp + arg_size, + ec->cfp->sp + arg_size, ISEQ_BODY(iseq)->local_table_size - arg_size, ISEQ_BODY(iseq)->stack_max); @@ -1349,7 +1349,7 @@ ALWAYS_INLINE(static VALUE static inline VALUE invoke_iseq_block_from_c(rb_execution_context_t *ec, const struct rb_captured_block *captured, - VALUE self, int argc, const VALUE *argv, int kw_splat, VALUE passed_block_handler, + VALUE self, int argc, const VALUE *argv, int kw_splat, VALUE passed_block_handler, const rb_cref_t *cref, int is_lambda, const rb_callable_method_entry_t *me) { const rb_iseq_t *iseq = rb_iseq_check(captured->code.iseq); @@ -1364,49 +1364,49 @@ invoke_iseq_block_from_c(rb_execution_context_t *ec, const struct rb_captured_bl vm_check_canary(ec, sp); cfp->sp = sp + argc; for (i=0; isp = sp; if (me == NULL) { - return invoke_block(ec, iseq, self, captured, cref, type, opt_pc); + return invoke_block(ec, iseq, self, captured, cref, type, opt_pc); } else { - return invoke_bmethod(ec, iseq, self, captured, me, type, opt_pc); + return invoke_bmethod(ec, iseq, self, captured, me, type, opt_pc); } } static inline VALUE invoke_block_from_c_bh(rb_execution_context_t *ec, VALUE block_handler, - int argc, const VALUE *argv, - int kw_splat, VALUE passed_block_handler, const rb_cref_t *cref, - int is_lambda, int force_blockarg) + int argc, const VALUE *argv, + int kw_splat, VALUE passed_block_handler, const rb_cref_t *cref, + int is_lambda, int force_blockarg) { again: switch (vm_block_handler_type(block_handler)) { case block_handler_type_iseq: - { - const struct rb_captured_block *captured = VM_BH_TO_ISEQ_BLOCK(block_handler); - return invoke_iseq_block_from_c(ec, captured, captured->self, - argc, argv, kw_splat, passed_block_handler, + { + const struct rb_captured_block *captured = VM_BH_TO_ISEQ_BLOCK(block_handler); + return invoke_iseq_block_from_c(ec, captured, captured->self, + argc, argv, kw_splat, passed_block_handler, cref, is_lambda, NULL); - } + } case block_handler_type_ifunc: - return vm_yield_with_cfunc(ec, VM_BH_TO_IFUNC_BLOCK(block_handler), - VM_BH_TO_IFUNC_BLOCK(block_handler)->self, + return vm_yield_with_cfunc(ec, VM_BH_TO_IFUNC_BLOCK(block_handler), + VM_BH_TO_IFUNC_BLOCK(block_handler)->self, argc, argv, kw_splat, passed_block_handler, NULL); case block_handler_type_symbol: - return vm_yield_with_symbol(ec, VM_BH_TO_SYMBOL(block_handler), - argc, argv, kw_splat, passed_block_handler); + return vm_yield_with_symbol(ec, VM_BH_TO_SYMBOL(block_handler), + argc, argv, kw_splat, passed_block_handler); case block_handler_type_proc: - if (force_blockarg == FALSE) { - is_lambda = block_proc_is_lambda(VM_BH_TO_PROC(block_handler)); - } - block_handler = vm_proc_to_block_handler(VM_BH_TO_PROC(block_handler)); - goto again; + if (force_blockarg == FALSE) { + is_lambda = block_proc_is_lambda(VM_BH_TO_PROC(block_handler)); + } + block_handler = vm_proc_to_block_handler(VM_BH_TO_PROC(block_handler)); + goto again; } VM_UNREACHABLE(invoke_block_from_c_splattable); return Qundef; @@ -1418,7 +1418,7 @@ check_block_handler(rb_execution_context_t *ec) VALUE block_handler = VM_CF_BLOCK_HANDLER(ec->cfp); vm_block_handler_verify(block_handler); if (UNLIKELY(block_handler == VM_BLOCK_HANDLER_NONE)) { - rb_vm_localjump_error("no block given", Qnil, 0); + rb_vm_localjump_error("no block given", Qnil, 0); } return block_handler; @@ -1429,7 +1429,7 @@ vm_yield_with_cref(rb_execution_context_t *ec, int argc, const VALUE *argv, int { return invoke_block_from_c_bh(ec, check_block_handler(ec), argc, argv, kw_splat, VM_BLOCK_HANDLER_NONE, - cref, is_lambda, FALSE); + cref, is_lambda, FALSE); } static VALUE @@ -1443,7 +1443,7 @@ vm_yield_with_block(rb_execution_context_t *ec, int argc, const VALUE *argv, VAL { return invoke_block_from_c_bh(ec, check_block_handler(ec), argc, argv, kw_splat, block_handler, - NULL, FALSE, FALSE); + NULL, FALSE, FALSE); } static VALUE @@ -1461,7 +1461,7 @@ ALWAYS_INLINE(static VALUE static inline VALUE invoke_block_from_c_proc(rb_execution_context_t *ec, const rb_proc_t *proc, - VALUE self, int argc, const VALUE *argv, + VALUE self, int argc, const VALUE *argv, int kw_splat, VALUE passed_block_handler, int is_lambda, const rb_callable_method_entry_t *me) { @@ -1486,11 +1486,11 @@ invoke_block_from_c_proc(rb_execution_context_t *ec, const rb_proc_t *proc, } return vm_yield_with_cfunc(ec, &block->as.captured, self, argc, argv, kw_splat, passed_block_handler, me); case block_type_symbol: - return vm_yield_with_symbol(ec, block->as.symbol, argc, argv, kw_splat, passed_block_handler); + return vm_yield_with_symbol(ec, block->as.symbol, argc, argv, kw_splat, passed_block_handler); case block_type_proc: - is_lambda = block_proc_is_lambda(block->as.proc); - block = vm_proc_block(block->as.proc); - goto again; + is_lambda = block_proc_is_lambda(block->as.proc); + block = vm_proc_block(block->as.proc); + goto again; } VM_UNREACHABLE(invoke_block_from_c_proc); return Qundef; @@ -1498,7 +1498,7 @@ invoke_block_from_c_proc(rb_execution_context_t *ec, const rb_proc_t *proc, static VALUE vm_invoke_proc(rb_execution_context_t *ec, rb_proc_t *proc, VALUE self, - int argc, const VALUE *argv, int kw_splat, VALUE passed_block_handler) + int argc, const VALUE *argv, int kw_splat, VALUE passed_block_handler) { return invoke_block_from_c_proc(ec, proc, self, argc, argv, kw_splat, passed_block_handler, proc->is_lambda, NULL); } @@ -1512,7 +1512,7 @@ rb_vm_invoke_bmethod(rb_execution_context_t *ec, rb_proc_t *proc, VALUE self, MJIT_FUNC_EXPORTED VALUE rb_vm_invoke_proc(rb_execution_context_t *ec, rb_proc_t *proc, - int argc, const VALUE *argv, int kw_splat, VALUE passed_block_handler) + int argc, const VALUE *argv, int kw_splat, VALUE passed_block_handler) { VALUE self = vm_block_self(&proc->block); vm_block_handler_verify(passed_block_handler); @@ -1521,7 +1521,7 @@ rb_vm_invoke_proc(rb_execution_context_t *ec, rb_proc_t *proc, return rb_vm_invoke_bmethod(ec, proc, self, argc, argv, kw_splat, passed_block_handler, NULL); } else { - return vm_invoke_proc(ec, proc, self, argc, argv, kw_splat, passed_block_handler); + return vm_invoke_proc(ec, proc, self, argc, argv, kw_splat, passed_block_handler); } } @@ -1535,7 +1535,7 @@ rb_vm_invoke_proc_with_self(rb_execution_context_t *ec, rb_proc_t *proc, VALUE s return rb_vm_invoke_bmethod(ec, proc, self, argc, argv, kw_splat, passed_block_handler, NULL); } else { - return vm_invoke_proc(ec, proc, self, argc, argv, kw_splat, passed_block_handler); + return vm_invoke_proc(ec, proc, self, argc, argv, kw_splat, passed_block_handler); } } @@ -1545,10 +1545,10 @@ static rb_control_frame_t * vm_normal_frame(const rb_execution_context_t *ec, rb_control_frame_t *cfp) { while (cfp->pc == 0) { - cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); - if (RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(ec, cfp)) { - return 0; - } + cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); + if (RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(ec, cfp)) { + return 0; + } } return cfp; } @@ -1612,10 +1612,10 @@ rb_sourcefile(void) const rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(ec, ec->cfp); if (cfp) { - return RSTRING_PTR(rb_iseq_path(cfp->iseq)); + return RSTRING_PTR(rb_iseq_path(cfp->iseq)); } else { - return 0; + return 0; } } @@ -1626,10 +1626,10 @@ rb_sourceline(void) const rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(ec, ec->cfp); if (cfp) { - return rb_vm_get_sourceline(cfp); + return rb_vm_get_sourceline(cfp); } else { - return 0; + return 0; } } @@ -1640,12 +1640,12 @@ rb_source_location(int *pline) const rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(ec, ec->cfp); if (cfp && VM_FRAME_RUBYFRAME_P(cfp)) { - if (pline) *pline = rb_vm_get_sourceline(cfp); - return rb_iseq_path(cfp->iseq); + if (pline) *pline = rb_vm_get_sourceline(cfp); + return rb_iseq_path(cfp->iseq); } else { - if (pline) *pline = 0; - return Qnil; + if (pline) *pline = 0; + return Qnil; } } @@ -1692,9 +1692,9 @@ void debug_cref(rb_cref_t *cref) { while (cref) { - dp(CREF_CLASS(cref)); - printf("%ld\n", CREF_VISI(cref)); - cref = CREF_NEXT(cref); + dp(CREF_CLASS(cref)); + printf("%ld\n", CREF_VISI(cref)); + cref = CREF_NEXT(cref); } } #endif @@ -1706,7 +1706,7 @@ rb_vm_cbase(void) const rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(ec, ec->cfp); if (cfp == 0) { - rb_raise(rb_eRuntimeError, "Can't call on top of Fiber or Thread"); + rb_raise(rb_eRuntimeError, "Can't call on top of Fiber or Thread"); } return vm_get_cbase(cfp->ep); } @@ -1722,23 +1722,23 @@ make_localjump_error(const char *mesg, VALUE value, int reason) switch (reason) { case TAG_BREAK: - CONST_ID(id, "break"); - break; + CONST_ID(id, "break"); + break; case TAG_REDO: - CONST_ID(id, "redo"); - break; + CONST_ID(id, "redo"); + break; case TAG_RETRY: - CONST_ID(id, "retry"); - break; + CONST_ID(id, "retry"); + break; case TAG_NEXT: - CONST_ID(id, "next"); - break; + CONST_ID(id, "next"); + break; case TAG_RETURN: - CONST_ID(id, "return"); - break; + CONST_ID(id, "return"); + break; default: - CONST_ID(id, "noreason"); - break; + CONST_ID(id, "noreason"); + break; } rb_iv_set(exc, "@exit_value", value); rb_iv_set(exc, "@reason", ID2SYM(id)); @@ -1759,27 +1759,27 @@ rb_vm_make_jump_tag_but_local_jump(int state, VALUE val) switch (state) { case TAG_RETURN: - mesg = "unexpected return"; - break; + mesg = "unexpected return"; + break; case TAG_BREAK: - mesg = "unexpected break"; - break; + mesg = "unexpected break"; + break; case TAG_NEXT: - mesg = "unexpected next"; - break; + mesg = "unexpected next"; + break; case TAG_REDO: - mesg = "unexpected redo"; - val = Qnil; - break; + mesg = "unexpected redo"; + val = Qnil; + break; case TAG_RETRY: - mesg = "retry outside of rescue clause"; - val = Qnil; - break; + mesg = "retry outside of rescue clause"; + val = Qnil; + break; default: - return Qnil; + return Qnil; } if (val == Qundef) { - val = GET_EC()->tag->retval; + val = GET_EC()->tag->retval; } return make_localjump_error(mesg, val, state); } @@ -1796,7 +1796,7 @@ static rb_control_frame_t * next_not_local_frame(rb_control_frame_t *cfp) { while (VM_ENV_LOCAL_P(cfp->ep)) { - cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); + cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); } return cfp; } @@ -1811,7 +1811,7 @@ vm_iter_break(rb_execution_context_t *ec, VALUE val) const rb_control_frame_t *target_cfp = rb_vm_search_cf_from_ep(ec, cfp, ep); if (!target_cfp) { - rb_vm_localjump_error("unexpected break", val, TAG_BREAK); + rb_vm_localjump_error("unexpected break", val, TAG_BREAK); } ec->errinfo = (VALUE)THROW_DATA_NEW(val, target_cfp, TAG_BREAK); @@ -1876,9 +1876,9 @@ vm_redefinition_check_method_type(const rb_method_entry_t *me) switch (def->type) { case VM_METHOD_TYPE_CFUNC: case VM_METHOD_TYPE_OPTIMIZED: - return TRUE; + return TRUE; default: - return FALSE; + return FALSE; } } @@ -1926,11 +1926,11 @@ add_opt_method(VALUE klass, ID mid, VALUE bop) const rb_method_entry_t *me = rb_method_entry_at(klass, mid); if (me && vm_redefinition_check_method_type(me)) { - st_insert(vm_opt_method_def_table, (st_data_t)me->def, (st_data_t)bop); - st_insert(vm_opt_mid_table, (st_data_t)mid, (st_data_t)Qtrue); + st_insert(vm_opt_method_def_table, (st_data_t)me->def, (st_data_t)bop); + st_insert(vm_opt_mid_table, (st_data_t)mid, (st_data_t)Qtrue); } else { - rb_bug("undefined optimized method: %s", rb_id2name(mid)); + rb_bug("undefined optimized method: %s", rb_id2name(mid)); } } @@ -1952,7 +1952,7 @@ vm_init_redefined_flag(void) OP(MOD, MOD), (C(Integer), C(Float)); OP(Eq, EQ), (C(Integer), C(Float), C(String), C(Symbol)); OP(Eqq, EQQ), (C(Integer), C(Float), C(Symbol), C(String), - C(NilClass), C(TrueClass), C(FalseClass)); + C(NilClass), C(TrueClass), C(FalseClass)); OP(LT, LT), (C(Integer), C(Float)); OP(LE, LE), (C(Integer), C(Float)); OP(GT, GT), (C(Integer), C(Float)); @@ -1993,7 +1993,7 @@ vm_frametype_name(const rb_control_frame_t *cfp) case VM_FRAME_MAGIC_EVAL: return "eval"; case VM_FRAME_MAGIC_RESCUE: return "rescue"; default: - rb_bug("unknown frame"); + rb_bug("unknown frame"); } } #endif @@ -2002,12 +2002,12 @@ static VALUE frame_return_value(const struct vm_throw_data *err) { if (THROW_DATA_P(err) && - THROW_DATA_STATE(err) == TAG_BREAK && - THROW_DATA_CONSUMED_P(err) == FALSE) { - return THROW_DATA_VAL(err); + THROW_DATA_STATE(err) == TAG_BREAK && + THROW_DATA_CONSUMED_P(err) == FALSE) { + return THROW_DATA_VAL(err); } else { - return Qnil; + return Qnil; } } @@ -2041,7 +2041,7 @@ hook_before_rewind(rb_execution_context_t *ec, const rb_control_frame_t *cfp, bool cfp_returning_with_value, int state, struct vm_throw_data *err) { if (state == TAG_RAISE && RBASIC(err)->klass == rb_eSysStackError) { - return; + return; } else { const rb_iseq_t *iseq = cfp->iseq; @@ -2293,17 +2293,17 @@ vm_exec(rb_execution_context_t *ec, bool mjit_enable_p) goto vm_loop_start; /* fallback to the VM */ } else { - result = ec->errinfo; + result = ec->errinfo; rb_ec_raised_reset(ec, RAISED_STACKOVERFLOW | RAISED_NOMEMORY); while ((result = vm_exec_handle_exception(ec, state, result, &initial)) == Qundef) { /* caught a jump, exec the handler */ result = vm_exec_core(ec, initial); - vm_loop_start: - VM_ASSERT(ec->tag == &_tag); - /* when caught `throw`, `tag.state` is set. */ - if ((state = _tag.state) == TAG_NONE) break; - _tag.state = TAG_NONE; - } + vm_loop_start: + VM_ASSERT(ec->tag == &_tag); + /* when caught `throw`, `tag.state` is set. */ + if ((state = _tag.state) == TAG_NONE) break; + _tag.state = TAG_NONE; + } } EC_POP_TAG(); return result; @@ -2317,121 +2317,121 @@ vm_exec_handle_exception(rb_execution_context_t *ec, enum ruby_tag_type state, struct vm_throw_data *err = (struct vm_throw_data *)errinfo; for (;;) { - unsigned int i; - const struct iseq_catch_table_entry *entry; - const struct iseq_catch_table *ct; - unsigned long epc, cont_pc, cont_sp; - const rb_iseq_t *catch_iseq; - rb_control_frame_t *cfp; - VALUE type; - const rb_control_frame_t *escape_cfp; + unsigned int i; + const struct iseq_catch_table_entry *entry; + const struct iseq_catch_table *ct; + unsigned long epc, cont_pc, cont_sp; + const rb_iseq_t *catch_iseq; + rb_control_frame_t *cfp; + VALUE type; + const rb_control_frame_t *escape_cfp; - cont_pc = cont_sp = 0; - catch_iseq = NULL; + cont_pc = cont_sp = 0; + catch_iseq = NULL; - while (ec->cfp->pc == 0 || ec->cfp->iseq == 0) { - if (UNLIKELY(VM_FRAME_TYPE(ec->cfp) == VM_FRAME_MAGIC_CFUNC)) { - EXEC_EVENT_HOOK_AND_POP_FRAME(ec, RUBY_EVENT_C_RETURN, ec->cfp->self, - rb_vm_frame_method_entry(ec->cfp)->def->original_id, - rb_vm_frame_method_entry(ec->cfp)->called_id, - rb_vm_frame_method_entry(ec->cfp)->owner, Qnil); - RUBY_DTRACE_CMETHOD_RETURN_HOOK(ec, - rb_vm_frame_method_entry(ec->cfp)->owner, - rb_vm_frame_method_entry(ec->cfp)->def->original_id); - } - rb_vm_pop_frame(ec); - } + while (ec->cfp->pc == 0 || ec->cfp->iseq == 0) { + if (UNLIKELY(VM_FRAME_TYPE(ec->cfp) == VM_FRAME_MAGIC_CFUNC)) { + EXEC_EVENT_HOOK_AND_POP_FRAME(ec, RUBY_EVENT_C_RETURN, ec->cfp->self, + rb_vm_frame_method_entry(ec->cfp)->def->original_id, + rb_vm_frame_method_entry(ec->cfp)->called_id, + rb_vm_frame_method_entry(ec->cfp)->owner, Qnil); + RUBY_DTRACE_CMETHOD_RETURN_HOOK(ec, + rb_vm_frame_method_entry(ec->cfp)->owner, + rb_vm_frame_method_entry(ec->cfp)->def->original_id); + } + rb_vm_pop_frame(ec); + } - cfp = ec->cfp; + cfp = ec->cfp; epc = cfp->pc - ISEQ_BODY(cfp->iseq)->iseq_encoded; - escape_cfp = NULL; - if (state == TAG_BREAK || state == TAG_RETURN) { - escape_cfp = THROW_DATA_CATCH_FRAME(err); + escape_cfp = NULL; + if (state == TAG_BREAK || state == TAG_RETURN) { + escape_cfp = THROW_DATA_CATCH_FRAME(err); - if (cfp == escape_cfp) { - if (state == TAG_RETURN) { - if (!VM_FRAME_FINISHED_P(cfp)) { - THROW_DATA_CATCH_FRAME_SET(err, cfp + 1); - THROW_DATA_STATE_SET(err, state = TAG_BREAK); - } - else { + if (cfp == escape_cfp) { + if (state == TAG_RETURN) { + if (!VM_FRAME_FINISHED_P(cfp)) { + THROW_DATA_CATCH_FRAME_SET(err, cfp + 1); + THROW_DATA_STATE_SET(err, state = TAG_BREAK); + } + else { ct = ISEQ_BODY(cfp->iseq)->catch_table; - if (ct) for (i = 0; i < ct->size; i++) { - entry = UNALIGNED_MEMBER_PTR(ct, entries[i]); - if (entry->start < epc && entry->end >= epc) { - if (entry->type == CATCH_TYPE_ENSURE) { - catch_iseq = entry->iseq; - cont_pc = entry->cont; - cont_sp = entry->sp; - break; - } - } - } - if (catch_iseq == NULL) { - ec->errinfo = Qnil; - THROW_DATA_CATCH_FRAME_SET(err, cfp + 1); + if (ct) for (i = 0; i < ct->size; i++) { + entry = UNALIGNED_MEMBER_PTR(ct, entries[i]); + if (entry->start < epc && entry->end >= epc) { + if (entry->type == CATCH_TYPE_ENSURE) { + catch_iseq = entry->iseq; + cont_pc = entry->cont; + cont_sp = entry->sp; + break; + } + } + } + if (catch_iseq == NULL) { + ec->errinfo = Qnil; + THROW_DATA_CATCH_FRAME_SET(err, cfp + 1); // cfp == escape_cfp here so calling with cfp_returning_with_value = true hook_before_rewind(ec, ec->cfp, true, state, err); - rb_vm_pop_frame(ec); - return THROW_DATA_VAL(err); - } - } - /* through */ - } - else { - /* TAG_BREAK */ + rb_vm_pop_frame(ec); + return THROW_DATA_VAL(err); + } + } + /* through */ + } + else { + /* TAG_BREAK */ #if OPT_STACK_CACHING - *initial = THROW_DATA_VAL(err); + *initial = THROW_DATA_VAL(err); #else - *ec->cfp->sp++ = THROW_DATA_VAL(err); + *ec->cfp->sp++ = THROW_DATA_VAL(err); #endif - ec->errinfo = Qnil; - return Qundef; - } - } - } + ec->errinfo = Qnil; + return Qundef; + } + } + } - if (state == TAG_RAISE) { + if (state == TAG_RAISE) { ct = ISEQ_BODY(cfp->iseq)->catch_table; - if (ct) for (i = 0; i < ct->size; i++) { - entry = UNALIGNED_MEMBER_PTR(ct, entries[i]); - if (entry->start < epc && entry->end >= epc) { + if (ct) for (i = 0; i < ct->size; i++) { + entry = UNALIGNED_MEMBER_PTR(ct, entries[i]); + if (entry->start < epc && entry->end >= epc) { - if (entry->type == CATCH_TYPE_RESCUE || - entry->type == CATCH_TYPE_ENSURE) { - catch_iseq = entry->iseq; - cont_pc = entry->cont; - cont_sp = entry->sp; - break; - } - } - } - } - else if (state == TAG_RETRY) { + if (entry->type == CATCH_TYPE_RESCUE || + entry->type == CATCH_TYPE_ENSURE) { + catch_iseq = entry->iseq; + cont_pc = entry->cont; + cont_sp = entry->sp; + break; + } + } + } + } + else if (state == TAG_RETRY) { ct = ISEQ_BODY(cfp->iseq)->catch_table; - if (ct) for (i = 0; i < ct->size; i++) { - entry = UNALIGNED_MEMBER_PTR(ct, entries[i]); - if (entry->start < epc && entry->end >= epc) { + if (ct) for (i = 0; i < ct->size; i++) { + entry = UNALIGNED_MEMBER_PTR(ct, entries[i]); + if (entry->start < epc && entry->end >= epc) { - if (entry->type == CATCH_TYPE_ENSURE) { - catch_iseq = entry->iseq; - cont_pc = entry->cont; - cont_sp = entry->sp; - break; - } - else if (entry->type == CATCH_TYPE_RETRY) { - const rb_control_frame_t *escape_cfp; - escape_cfp = THROW_DATA_CATCH_FRAME(err); - if (cfp == escape_cfp) { + if (entry->type == CATCH_TYPE_ENSURE) { + catch_iseq = entry->iseq; + cont_pc = entry->cont; + cont_sp = entry->sp; + break; + } + else if (entry->type == CATCH_TYPE_RETRY) { + const rb_control_frame_t *escape_cfp; + escape_cfp = THROW_DATA_CATCH_FRAME(err); + if (cfp == escape_cfp) { cfp->pc = ISEQ_BODY(cfp->iseq)->iseq_encoded + entry->cont; - ec->errinfo = Qnil; - return Qundef; - } - } - } - } - } + ec->errinfo = Qnil; + return Qundef; + } + } + } + } + } else if ((state == TAG_BREAK && !escape_cfp) || (state == TAG_REDO) || (state == TAG_NEXT)) { @@ -2443,88 +2443,88 @@ vm_exec_handle_exception(rb_execution_context_t *ec, enum ruby_tag_type state, }[state]; ct = ISEQ_BODY(cfp->iseq)->catch_table; - if (ct) for (i = 0; i < ct->size; i++) { - entry = UNALIGNED_MEMBER_PTR(ct, entries[i]); + if (ct) for (i = 0; i < ct->size; i++) { + entry = UNALIGNED_MEMBER_PTR(ct, entries[i]); - if (entry->start < epc && entry->end >= epc) { - if (entry->type == CATCH_TYPE_ENSURE) { - catch_iseq = entry->iseq; - cont_pc = entry->cont; - cont_sp = entry->sp; - break; - } - else if (entry->type == type) { + if (entry->start < epc && entry->end >= epc) { + if (entry->type == CATCH_TYPE_ENSURE) { + catch_iseq = entry->iseq; + cont_pc = entry->cont; + cont_sp = entry->sp; + break; + } + else if (entry->type == type) { cfp->pc = ISEQ_BODY(cfp->iseq)->iseq_encoded + entry->cont; - cfp->sp = vm_base_ptr(cfp) + entry->sp; + cfp->sp = vm_base_ptr(cfp) + entry->sp; - if (state != TAG_REDO) { + if (state != TAG_REDO) { #if OPT_STACK_CACHING - *initial = THROW_DATA_VAL(err); + *initial = THROW_DATA_VAL(err); #else - *ec->cfp->sp++ = THROW_DATA_VAL(err); + *ec->cfp->sp++ = THROW_DATA_VAL(err); #endif - } - ec->errinfo = Qnil; - VM_ASSERT(ec->tag->state == TAG_NONE); - return Qundef; - } - } - } - } - else { + } + ec->errinfo = Qnil; + VM_ASSERT(ec->tag->state == TAG_NONE); + return Qundef; + } + } + } + } + else { ct = ISEQ_BODY(cfp->iseq)->catch_table; - if (ct) for (i = 0; i < ct->size; i++) { - entry = UNALIGNED_MEMBER_PTR(ct, entries[i]); - if (entry->start < epc && entry->end >= epc) { + if (ct) for (i = 0; i < ct->size; i++) { + entry = UNALIGNED_MEMBER_PTR(ct, entries[i]); + if (entry->start < epc && entry->end >= epc) { - if (entry->type == CATCH_TYPE_ENSURE) { - catch_iseq = entry->iseq; - cont_pc = entry->cont; - cont_sp = entry->sp; - break; - } - } - } - } + if (entry->type == CATCH_TYPE_ENSURE) { + catch_iseq = entry->iseq; + cont_pc = entry->cont; + cont_sp = entry->sp; + break; + } + } + } + } - if (catch_iseq != NULL) { /* found catch table */ - /* enter catch scope */ - const int arg_size = 1; + if (catch_iseq != NULL) { /* found catch table */ + /* enter catch scope */ + const int arg_size = 1; - rb_iseq_check(catch_iseq); - cfp->sp = vm_base_ptr(cfp) + cont_sp; + rb_iseq_check(catch_iseq); + cfp->sp = vm_base_ptr(cfp) + cont_sp; cfp->pc = ISEQ_BODY(cfp->iseq)->iseq_encoded + cont_pc; - /* push block frame */ - cfp->sp[0] = (VALUE)err; - vm_push_frame(ec, catch_iseq, VM_FRAME_MAGIC_RESCUE, - cfp->self, - VM_GUARDED_PREV_EP(cfp->ep), - 0, /* cref or me */ + /* push block frame */ + cfp->sp[0] = (VALUE)err; + vm_push_frame(ec, catch_iseq, VM_FRAME_MAGIC_RESCUE, + cfp->self, + VM_GUARDED_PREV_EP(cfp->ep), + 0, /* cref or me */ ISEQ_BODY(catch_iseq)->iseq_encoded, - cfp->sp + arg_size /* push value */, + cfp->sp + arg_size /* push value */, ISEQ_BODY(catch_iseq)->local_table_size - arg_size, ISEQ_BODY(catch_iseq)->stack_max); - state = 0; - ec->tag->state = TAG_NONE; - ec->errinfo = Qnil; + state = 0; + ec->tag->state = TAG_NONE; + ec->errinfo = Qnil; - return Qundef; - } - else { - hook_before_rewind(ec, ec->cfp, (cfp == escape_cfp), state, err); + return Qundef; + } + else { + hook_before_rewind(ec, ec->cfp, (cfp == escape_cfp), state, err); - if (VM_FRAME_FINISHED_P(ec->cfp)) { - rb_vm_pop_frame(ec); - ec->errinfo = (VALUE)err; - ec->tag = ec->tag->prev; - EC_JUMP_TAG(ec, state); - } - else { - rb_vm_pop_frame(ec); - } - } + if (VM_FRAME_FINISHED_P(ec->cfp)) { + rb_vm_pop_frame(ec); + ec->errinfo = (VALUE)err; + ec->tag = ec->tag->prev; + EC_JUMP_TAG(ec, state); + } + else { + rb_vm_pop_frame(ec); + } + } } } @@ -2557,13 +2557,13 @@ rb_vm_control_frame_id_and_class(const rb_control_frame_t *cfp, ID *idp, ID *cal const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(cfp); if (me) { - if (idp) *idp = me->def->original_id; - if (called_idp) *called_idp = me->called_id; - if (klassp) *klassp = me->owner; - return TRUE; + if (idp) *idp = me->def->original_id; + if (called_idp) *called_idp = me->called_id; + if (klassp) *klassp = me->owner; + return TRUE; } else { - return FALSE; + return FALSE; } } @@ -2581,7 +2581,7 @@ rb_frame_method_id_and_class(ID *idp, VALUE *klassp) VALUE rb_vm_call_cfunc(VALUE recv, VALUE (*func)(VALUE), VALUE arg, - VALUE block_handler, VALUE filename) + VALUE block_handler, VALUE filename) { rb_execution_context_t *ec = GET_EC(); const rb_control_frame_t *reg_cfp = ec->cfp; @@ -2589,9 +2589,9 @@ rb_vm_call_cfunc(VALUE recv, VALUE (*func)(VALUE), VALUE arg, VALUE val; vm_push_frame(ec, iseq, VM_FRAME_MAGIC_TOP | VM_ENV_FLAG_LOCAL | VM_FRAME_FLAG_FINISH, - recv, block_handler, - (VALUE)vm_cref_new_toplevel(ec), /* cref or me */ - 0, reg_cfp->sp, 0, 0); + recv, block_handler, + (VALUE)vm_cref_new_toplevel(ec), /* cref or me */ + 0, reg_cfp->sp, 0, 0); val = (*func)(arg); @@ -2675,17 +2675,17 @@ rb_vm_mark(void *ptr) RUBY_MARK_ENTER("vm"); RUBY_GC_INFO("-------------------------------------------------\n"); if (ptr) { - rb_vm_t *vm = ptr; + rb_vm_t *vm = ptr; rb_ractor_t *r = 0; long i, len; const VALUE *obj_ary; - ccan_list_for_each(&vm->ractor.set, r, vmlr_node) { + ccan_list_for_each(&vm->ractor.set, r, vmlr_node) { // ractor.set only contains blocking or running ractors VM_ASSERT(rb_ractor_status_p(r, ractor_blocking) || rb_ractor_status_p(r, ractor_running)); rb_gc_mark(rb_ractor_self(r)); - } + } rb_gc_mark_movable(vm->mark_object_ary); @@ -2718,9 +2718,9 @@ rb_vm_mark(void *ptr) /* Prevent classes from moving */ rb_mark_tbl(vm->defined_module_hash); - if (vm->loading_table) { - rb_mark_tbl(vm->loading_table); - } + if (vm->loading_table) { + rb_mark_tbl(vm->loading_table); + } rb_gc_mark_values(RUBY_NSIG, vm->trap_list.cmd); @@ -2779,34 +2779,34 @@ ruby_vm_destruct(rb_vm_t *vm) RUBY_FREE_ENTER("vm"); if (vm) { - rb_thread_t *th = vm->ractor.main_thread; - struct rb_objspace *objspace = vm->objspace; + rb_thread_t *th = vm->ractor.main_thread; + struct rb_objspace *objspace = vm->objspace; vm->ractor.main_thread = NULL; if (th) { rb_fiber_reset_root_local_storage(th); - thread_free(th); - } - rb_vm_living_threads_init(vm); - ruby_vm_run_at_exit_hooks(vm); - if (vm->loading_table) { - st_foreach(vm->loading_table, free_loading_table_entry, 0); - st_free_table(vm->loading_table); - vm->loading_table = 0; - } - if (vm->frozen_strings) { - st_free_table(vm->frozen_strings); - vm->frozen_strings = 0; - } - RB_ALTSTACK_FREE(vm->main_altstack); - if (objspace) { - rb_objspace_free(objspace); - } + thread_free(th); + } + rb_vm_living_threads_init(vm); + ruby_vm_run_at_exit_hooks(vm); + if (vm->loading_table) { + st_foreach(vm->loading_table, free_loading_table_entry, 0); + st_free_table(vm->loading_table); + vm->loading_table = 0; + } + if (vm->frozen_strings) { + st_free_table(vm->frozen_strings); + vm->frozen_strings = 0; + } + RB_ALTSTACK_FREE(vm->main_altstack); + if (objspace) { + rb_objspace_free(objspace); + } rb_native_mutex_destroy(&vm->waitpid_lock); rb_native_mutex_destroy(&vm->workqueue_lock); - /* after freeing objspace, you *can't* use ruby_xfree() */ - ruby_mimfree(vm); - ruby_current_vm_ptr = NULL; + /* after freeing objspace, you *can't* use ruby_xfree() */ + ruby_mimfree(vm); + ruby_current_vm_ptr = NULL; } RUBY_FREE_LEAVE("vm"); return 0; @@ -2920,11 +2920,11 @@ get_param(const char *name, size_t default_value, size_t min_value) const char *envval; size_t result = default_value; if ((envval = getenv(name)) != 0) { - long val = atol(envval); - if (val < (long)min_value) { - val = (long)min_value; - } - result = (size_t)(((val -1 + RUBY_VM_SIZE_ALIGN) / RUBY_VM_SIZE_ALIGN) * RUBY_VM_SIZE_ALIGN); + long val = atol(envval); + if (val < (long)min_value) { + val = (long)min_value; + } + result = (size_t)(((val -1 + RUBY_VM_SIZE_ALIGN) / RUBY_VM_SIZE_ALIGN) * RUBY_VM_SIZE_ALIGN); } if (0) ruby_debug_printf("%s: %"PRIuSIZE"\n", name, result); /* debug print */ @@ -2940,7 +2940,7 @@ check_machine_stack_size(size_t *sizep) #ifdef PTHREAD_STACK_MIN if (size < (size_t)PTHREAD_STACK_MIN) { - *sizep = (size_t)PTHREAD_STACK_MIN * 2; + *sizep = (size_t)PTHREAD_STACK_MIN * 2; } #endif } @@ -2950,23 +2950,23 @@ vm_default_params_setup(rb_vm_t *vm) { vm->default_params.thread_vm_stack_size = get_param("RUBY_THREAD_VM_STACK_SIZE", - RUBY_VM_THREAD_VM_STACK_SIZE, - RUBY_VM_THREAD_VM_STACK_SIZE_MIN); + RUBY_VM_THREAD_VM_STACK_SIZE, + RUBY_VM_THREAD_VM_STACK_SIZE_MIN); vm->default_params.thread_machine_stack_size = get_param("RUBY_THREAD_MACHINE_STACK_SIZE", - RUBY_VM_THREAD_MACHINE_STACK_SIZE, - RUBY_VM_THREAD_MACHINE_STACK_SIZE_MIN); + RUBY_VM_THREAD_MACHINE_STACK_SIZE, + RUBY_VM_THREAD_MACHINE_STACK_SIZE_MIN); vm->default_params.fiber_vm_stack_size = get_param("RUBY_FIBER_VM_STACK_SIZE", - RUBY_VM_FIBER_VM_STACK_SIZE, - RUBY_VM_FIBER_VM_STACK_SIZE_MIN); + RUBY_VM_FIBER_VM_STACK_SIZE, + RUBY_VM_FIBER_VM_STACK_SIZE_MIN); vm->default_params.fiber_machine_stack_size = get_param("RUBY_FIBER_MACHINE_STACK_SIZE", - RUBY_VM_FIBER_MACHINE_STACK_SIZE, - RUBY_VM_FIBER_MACHINE_STACK_SIZE_MIN); + RUBY_VM_FIBER_MACHINE_STACK_SIZE, + RUBY_VM_FIBER_MACHINE_STACK_SIZE_MIN); /* environment dependent check */ check_machine_stack_size(&vm->default_params.thread_machine_stack_size); @@ -3040,17 +3040,17 @@ rb_execution_context_mark(const rb_execution_context_t *ec) /* mark VM stack */ if (ec->vm_stack) { VM_ASSERT(ec->cfp); - VALUE *p = ec->vm_stack; - VALUE *sp = ec->cfp->sp; - rb_control_frame_t *cfp = ec->cfp; - rb_control_frame_t *limit_cfp = (void *)(ec->vm_stack + ec->vm_stack_size); + VALUE *p = ec->vm_stack; + VALUE *sp = ec->cfp->sp; + rb_control_frame_t *cfp = ec->cfp; + rb_control_frame_t *limit_cfp = (void *)(ec->vm_stack + ec->vm_stack_size); VM_ASSERT(sp == ec->cfp->sp); rb_gc_mark_vm_stack_values((long)(sp - p), p); - while (cfp != limit_cfp) { - const VALUE *ep = cfp->ep; - VM_ASSERT(!!VM_ENV_FLAGS(ep, VM_ENV_FLAG_ESCAPED) == vm_ep_in_heap_p_(ec, ep)); + while (cfp != limit_cfp) { + const VALUE *ep = cfp->ep; + VM_ASSERT(!!VM_ENV_FLAGS(ep, VM_ENV_FLAG_ESCAPED) == vm_ep_in_heap_p_(ec, ep)); rb_gc_mark_movable(cfp->self); rb_gc_mark_movable((VALUE)cfp->iseq); rb_gc_mark_movable((VALUE)cfp->block_code); @@ -3061,24 +3061,24 @@ rb_execution_context_mark(const rb_execution_context_t *ec) rb_gc_mark_movable(prev_ep[VM_ENV_DATA_INDEX_ENV]); } - if (VM_ENV_FLAGS(ep, VM_ENV_FLAG_ESCAPED)) { + if (VM_ENV_FLAGS(ep, VM_ENV_FLAG_ESCAPED)) { rb_gc_mark_movable(ep[VM_ENV_DATA_INDEX_ENV]); rb_gc_mark(ep[VM_ENV_DATA_INDEX_ME_CREF]); - } + } } - cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); - } + cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); + } } /* mark machine stack */ if (ec->machine.stack_start && ec->machine.stack_end && - ec != GET_EC() /* marked for current ec at the first stage of marking */ - ) { - rb_gc_mark_machine_stack(ec); - rb_gc_mark_locations((VALUE *)&ec->machine.regs, - (VALUE *)(&ec->machine.regs) + - sizeof(ec->machine.regs) / (sizeof(VALUE))); + ec != GET_EC() /* marked for current ec at the first stage of marking */ + ) { + rb_gc_mark_machine_stack(ec); + rb_gc_mark_locations((VALUE *)&ec->machine.regs, + (VALUE *)(&ec->machine.regs) + + sizeof(ec->machine.regs) / (sizeof(VALUE))); } RUBY_MARK_UNLESS_NULL(ec->errinfo); @@ -3156,20 +3156,20 @@ thread_free(void *ptr) RUBY_FREE_ENTER("thread"); if (th->locking_mutex != Qfalse) { - rb_bug("thread_free: locking_mutex must be NULL (%p:%p)", (void *)th, (void *)th->locking_mutex); + rb_bug("thread_free: locking_mutex must be NULL (%p:%p)", (void *)th, (void *)th->locking_mutex); } if (th->keeping_mutexes != NULL) { - rb_bug("thread_free: keeping_mutexes must be NULL (%p:%p)", (void *)th, (void *)th->keeping_mutexes); + rb_bug("thread_free: keeping_mutexes must be NULL (%p:%p)", (void *)th, (void *)th->keeping_mutexes); } rb_threadptr_root_fiber_release(th); if (th->vm && th->vm->ractor.main_thread == th) { - RUBY_GC_INFO("MRI main thread\n"); + RUBY_GC_INFO("MRI main thread\n"); } else { ruby_xfree(th->nt); // TODO - ruby_xfree(th); + ruby_xfree(th); } RUBY_FREE_LEAVE("thread"); @@ -3182,10 +3182,10 @@ thread_memsize(const void *ptr) size_t size = sizeof(rb_thread_t); if (!th->root_fiber) { - size += th->ec->vm_stack_size * sizeof(VALUE); + size += th->ec->vm_stack_size * sizeof(VALUE); } if (th->ec->local_storage) { - size += rb_id_table_memsize(th->ec->local_storage); + size += rb_id_table_memsize(th->ec->local_storage); } return size; } @@ -3194,9 +3194,9 @@ thread_memsize(const void *ptr) const rb_data_type_t ruby_threadptr_data_type = { "VM/thread", { - thread_mark, - thread_free, - thread_memsize, + thread_mark, + thread_free, + thread_memsize, thread_compact, }, 0, 0, RUBY_TYPED_FREE_IMMEDIATELY @@ -3315,7 +3315,7 @@ static VALUE m_core_set_method_alias(VALUE self, VALUE cbase, VALUE sym1, VALUE sym2) { REWIND_CFP({ - rb_alias(cbase, SYM2ID(sym1), SYM2ID(sym2)); + rb_alias(cbase, SYM2ID(sym1), SYM2ID(sym2)); }); return Qnil; } @@ -3324,7 +3324,7 @@ static VALUE m_core_set_variable_alias(VALUE self, VALUE sym1, VALUE sym2) { REWIND_CFP({ - rb_alias_variable(SYM2ID(sym1), SYM2ID(sym2)); + rb_alias_variable(SYM2ID(sym1), SYM2ID(sym2)); }); return Qnil; } @@ -3334,8 +3334,8 @@ m_core_undef_method(VALUE self, VALUE cbase, VALUE sym) { REWIND_CFP({ ID mid = SYM2ID(sym); - rb_undef(cbase, mid); - rb_clear_method_cache(self, mid); + rb_undef(cbase, mid); + rb_clear_method_cache(self, mid); }); return Qnil; } @@ -3434,11 +3434,11 @@ nsdr(VALUE self) int i; if (syms == 0) { - rb_memerror(); + rb_memerror(); } for (i=0; i"); - const rb_iseq_t *iseq = rb_iseq_new(0, filename, filename, Qnil, 0, ISEQ_TYPE_TOP); + rb_vm_t *vm = ruby_current_vm_ptr; + rb_thread_t *th = GET_THREAD(); + VALUE filename = rb_fstring_lit("
"); + const rb_iseq_t *iseq = rb_iseq_new(0, filename, filename, Qnil, 0, ISEQ_TYPE_TOP); // Ractor setup rb_ractor_main_setup(vm, th->ractor, th); - /* create vm object */ - vm->self = TypedData_Wrap_Struct(rb_cRubyVM, &vm_data_type, vm); + /* create vm object */ + vm->self = TypedData_Wrap_Struct(rb_cRubyVM, &vm_data_type, vm); - /* create main thread */ + /* create main thread */ th->self = TypedData_Wrap_Struct(rb_cThread, &thread_data_type, th); - vm->ractor.main_thread = th; + vm->ractor.main_thread = th; vm->ractor.main_ractor = th->ractor; - th->vm = vm; - th->top_wrapper = 0; - th->top_self = rb_vm_top_self(); + th->vm = vm; + th->top_wrapper = 0; + th->top_self = rb_vm_top_self(); rb_gc_register_mark_object((VALUE)iseq); - th->ec->cfp->iseq = iseq; + th->ec->cfp->iseq = iseq; th->ec->cfp->pc = ISEQ_BODY(iseq)->iseq_encoded; - th->ec->cfp->self = th->top_self; + th->ec->cfp->self = th->top_self; - VM_ENV_FLAGS_UNSET(th->ec->cfp->ep, VM_FRAME_FLAG_CFRAME); - VM_STACK_ENV_WRITE(th->ec->cfp->ep, VM_ENV_DATA_INDEX_ME_CREF, (VALUE)vm_cref_new(rb_cObject, METHOD_VISI_PRIVATE, FALSE, NULL, FALSE, FALSE)); + VM_ENV_FLAGS_UNSET(th->ec->cfp->ep, VM_FRAME_FLAG_CFRAME); + VM_STACK_ENV_WRITE(th->ec->cfp->ep, VM_ENV_DATA_INDEX_ME_CREF, (VALUE)vm_cref_new(rb_cObject, METHOD_VISI_PRIVATE, FALSE, NULL, FALSE, FALSE)); - /* - * The Binding of the top level scope - */ - rb_define_global_const("TOPLEVEL_BINDING", rb_binding_new()); + /* + * The Binding of the top level scope + */ + rb_define_global_const("TOPLEVEL_BINDING", rb_binding_new()); rb_objspace_gc_enable(vm->objspace); } @@ -3894,8 +3894,8 @@ Init_BareVM(void) rb_vm_t * vm = ruby_mimmalloc(sizeof(*vm)); rb_thread_t * th = ruby_mimmalloc(sizeof(*th)); if (!vm || !th) { - fputs("[FATAL] failed to allocate memory\n", stderr); - exit(EXIT_FAILURE); + fputs("[FATAL] failed to allocate memory\n", stderr); + exit(EXIT_FAILURE); } // setup the VM @@ -3982,8 +3982,8 @@ rb_ruby_debug_ptr(void) /* iseq.c */ VALUE rb_insn_operand_intern(const rb_iseq_t *iseq, - VALUE insn, int op_no, VALUE op, - int len, size_t pos, VALUE *pnop, VALUE child); + VALUE insn, int op_no, VALUE op, + int len, size_t pos, VALUE *pnop, VALUE child); st_table * rb_vm_fstring_table(void) @@ -4021,29 +4021,29 @@ vm_analysis_insn(int insn) CONST_ID(bigram_hash, "USAGE_ANALYSIS_INSN_BIGRAM"); uh = rb_const_get(rb_cRubyVM, usage_hash); if (NIL_P(ihash = rb_hash_aref(uh, INT2FIX(insn)))) { - ihash = rb_hash_new(); - HASH_ASET(uh, INT2FIX(insn), ihash); + ihash = rb_hash_new(); + HASH_ASET(uh, INT2FIX(insn), ihash); } if (NIL_P(cv = rb_hash_aref(ihash, INT2FIX(-1)))) { - cv = INT2FIX(0); + cv = INT2FIX(0); } HASH_ASET(ihash, INT2FIX(-1), INT2FIX(FIX2INT(cv) + 1)); /* calc bigram */ if (prev_insn != -1) { - VALUE bi; - VALUE ary[2]; - VALUE cv; + VALUE bi; + VALUE ary[2]; + VALUE cv; - ary[0] = INT2FIX(prev_insn); - ary[1] = INT2FIX(insn); - bi = rb_ary_new4(2, &ary[0]); + ary[0] = INT2FIX(prev_insn); + ary[1] = INT2FIX(insn); + bi = rb_ary_new4(2, &ary[0]); - uh = rb_const_get(rb_cRubyVM, bigram_hash); - if (NIL_P(cv = rb_hash_aref(uh, bi))) { - cv = INT2FIX(0); - } - HASH_ASET(uh, bi, INT2FIX(FIX2INT(cv) + 1)); + uh = rb_const_get(rb_cRubyVM, bigram_hash); + if (NIL_P(cv = rb_hash_aref(uh, bi))) { + cv = INT2FIX(0); + } + HASH_ASET(uh, bi, INT2FIX(FIX2INT(cv) + 1)); } prev_insn = insn; } @@ -4063,19 +4063,19 @@ vm_analysis_operand(int insn, int n, VALUE op) uh = rb_const_get(rb_cRubyVM, usage_hash); if (NIL_P(ihash = rb_hash_aref(uh, INT2FIX(insn)))) { - ihash = rb_hash_new(); - HASH_ASET(uh, INT2FIX(insn), ihash); + ihash = rb_hash_new(); + HASH_ASET(uh, INT2FIX(insn), ihash); } if (NIL_P(ophash = rb_hash_aref(ihash, INT2FIX(n)))) { - ophash = rb_hash_new(); - HASH_ASET(ihash, INT2FIX(n), ophash); + ophash = rb_hash_new(); + HASH_ASET(ihash, INT2FIX(n), ophash); } /* intern */ valstr = rb_insn_operand_intern(GET_EC()->cfp->iseq, insn, n, op, 0, 0, 0, 0); /* set count */ if (NIL_P(cv = rb_hash_aref(ophash, valstr))) { - cv = INT2FIX(0); + cv = INT2FIX(0); } HASH_ASET(ophash, valstr, INT2FIX(FIX2INT(cv) + 1)); } @@ -4087,16 +4087,16 @@ vm_analysis_register(int reg, int isset) VALUE uh; VALUE valstr; static const char regstrs[][5] = { - "pc", /* 0 */ - "sp", /* 1 */ - "ep", /* 2 */ - "cfp", /* 3 */ - "self", /* 4 */ - "iseq", /* 5 */ + "pc", /* 0 */ + "sp", /* 1 */ + "ep", /* 2 */ + "cfp", /* 3 */ + "self", /* 4 */ + "iseq", /* 5 */ }; static const char getsetstr[][4] = { - "get", - "set", + "get", + "set", }; static VALUE syms[sizeof(regstrs) / sizeof(regstrs[0])][2]; @@ -4104,22 +4104,22 @@ vm_analysis_register(int reg, int isset) CONST_ID(usage_hash, "USAGE_ANALYSIS_REGS"); if (syms[0] == 0) { - char buff[0x10]; - int i; + char buff[0x10]; + int i; - for (i = 0; i < (int)(sizeof(regstrs) / sizeof(regstrs[0])); i++) { - int j; - for (j = 0; j < 2; j++) { - snprintf(buff, 0x10, "%d %s %-4s", i, getsetstr[j], regstrs[i]); - syms[i][j] = ID2SYM(rb_intern(buff)); - } - } + for (i = 0; i < (int)(sizeof(regstrs) / sizeof(regstrs[0])); i++) { + int j; + for (j = 0; j < 2; j++) { + snprintf(buff, 0x10, "%d %s %-4s", i, getsetstr[j], regstrs[i]); + syms[i][j] = ID2SYM(rb_intern(buff)); + } + } } valstr = syms[reg][isset]; uh = rb_const_get(rb_cRubyVM, usage_hash); if (NIL_P(cv = rb_hash_aref(uh, valstr))) { - cv = INT2FIX(0); + cv = INT2FIX(0); } HASH_ASET(uh, valstr, INT2FIX(FIX2INT(cv) + 1)); } @@ -4260,10 +4260,10 @@ static void vm_collect_usage_insn(int insn) { if (RUBY_DTRACE_INSN_ENABLED()) { - RUBY_DTRACE_INSN(rb_insns_name(insn)); + RUBY_DTRACE_INSN(rb_insns_name(insn)); } if (ruby_vm_collect_usage_func_insn) - (*ruby_vm_collect_usage_func_insn)(insn); + (*ruby_vm_collect_usage_func_insn)(insn); } /* @param insn instruction number @@ -4274,15 +4274,15 @@ static void vm_collect_usage_operand(int insn, int n, VALUE op) { if (RUBY_DTRACE_INSN_OPERAND_ENABLED()) { - VALUE valstr; + VALUE valstr; - valstr = rb_insn_operand_intern(GET_EC()->cfp->iseq, insn, n, op, 0, 0, 0, 0); + valstr = rb_insn_operand_intern(GET_EC()->cfp->iseq, insn, n, op, 0, 0, 0, 0); - RUBY_DTRACE_INSN_OPERAND(RSTRING_PTR(valstr), rb_insns_name(insn)); - RB_GC_GUARD(valstr); + RUBY_DTRACE_INSN_OPERAND(RSTRING_PTR(valstr), rb_insns_name(insn)); + RB_GC_GUARD(valstr); } if (ruby_vm_collect_usage_func_operand) - (*ruby_vm_collect_usage_func_operand)(insn, n, op); + (*ruby_vm_collect_usage_func_operand)(insn, n, op); } /* @param reg register id. see code of vm_analysis_register() */ @@ -4291,7 +4291,7 @@ static void vm_collect_usage_register(int reg, int isset) { if (ruby_vm_collect_usage_func_register) - (*ruby_vm_collect_usage_func_register)(reg, isset); + (*ruby_vm_collect_usage_func_register)(reg, isset); } #endif diff --git a/vm_args.c b/vm_args.c index 09137df908..197fdd4b95 100644 --- a/vm_args.c +++ b/vm_args.c @@ -50,10 +50,10 @@ static inline int args_argc(struct args_info *args) { if (args->rest == Qfalse) { - return args->argc; + return args->argc; } else { - return args->argc + RARRAY_LENINT(args->rest) - args->rest_index; + return args->argc + RARRAY_LENINT(args->rest) - args->rest_index; } } @@ -64,15 +64,15 @@ args_extend(struct args_info *args, const int min_argc) if (args->rest) { arg_rest_dup(args); - VM_ASSERT(args->rest_index == 0); - for (i=args->argc + RARRAY_LENINT(args->rest); irest, Qnil); - } + VM_ASSERT(args->rest_index == 0); + for (i=args->argc + RARRAY_LENINT(args->rest); irest, Qnil); + } } else { - for (i=args->argc; iargv[args->argc++] = Qnil; - } + for (i=args->argc; iargv[args->argc++] = Qnil; + } } } @@ -80,17 +80,17 @@ static inline void args_reduce(struct args_info *args, int over_argc) { if (args->rest) { - const long len = RARRAY_LEN(args->rest); + const long len = RARRAY_LEN(args->rest); - if (len > over_argc) { - arg_rest_dup(args); - rb_ary_resize(args->rest, len - over_argc); - return; - } - else { - args->rest = Qfalse; - over_argc -= len; - } + if (len > over_argc) { + arg_rest_dup(args); + rb_ary_resize(args->rest, len - over_argc); + return; + } + else { + args->rest = Qfalse; + over_argc -= len; + } } VM_ASSERT(args->argc >= over_argc); @@ -103,20 +103,20 @@ args_check_block_arg0(struct args_info *args) VALUE ary = Qnil; if (args->rest && RARRAY_LEN(args->rest) == 1) { - VALUE arg0 = RARRAY_AREF(args->rest, 0); - ary = rb_check_array_type(arg0); + VALUE arg0 = RARRAY_AREF(args->rest, 0); + ary = rb_check_array_type(arg0); } else if (args->argc == 1) { - VALUE arg0 = args->argv[0]; - ary = rb_check_array_type(arg0); - args->argv[0] = arg0; /* see: https://bugs.ruby-lang.org/issues/8484 */ + VALUE arg0 = args->argv[0]; + ary = rb_check_array_type(arg0); + args->argv[0] = arg0; /* see: https://bugs.ruby-lang.org/issues/8484 */ } if (!NIL_P(ary)) { - args->rest = ary; - args->rest_index = 0; - args->argc = 0; - return TRUE; + args->rest = ary; + args->rest_index = 0; + args->argc = 0; + return TRUE; } return FALSE; @@ -126,42 +126,42 @@ static inline void args_copy(struct args_info *args) { if (args->rest != Qfalse) { - int argc = args->argc; - args->argc = 0; + int argc = args->argc; + args->argc = 0; arg_rest_dup(args); - /* - * argv: [m0, m1, m2, m3] - * rest: [a0, a1, a2, a3, a4, a5] - * ^ - * rest_index - * - * #=> first loop - * - * argv: [m0, m1] - * rest: [m2, m3, a2, a3, a4, a5] - * ^ - * rest_index - * - * #=> 2nd loop - * - * argv: [] (argc == 0) - * rest: [m0, m1, m2, m3, a2, a3, a4, a5] - * ^ - * rest_index - */ - while (args->rest_index > 0 && argc > 0) { - RARRAY_ASET(args->rest, --args->rest_index, args->argv[--argc]); - } - while (argc > 0) { - rb_ary_unshift(args->rest, args->argv[--argc]); - } + /* + * argv: [m0, m1, m2, m3] + * rest: [a0, a1, a2, a3, a4, a5] + * ^ + * rest_index + * + * #=> first loop + * + * argv: [m0, m1] + * rest: [m2, m3, a2, a3, a4, a5] + * ^ + * rest_index + * + * #=> 2nd loop + * + * argv: [] (argc == 0) + * rest: [m0, m1, m2, m3, a2, a3, a4, a5] + * ^ + * rest_index + */ + while (args->rest_index > 0 && argc > 0) { + RARRAY_ASET(args->rest, --args->rest_index, args->argv[--argc]); + } + while (argc > 0) { + rb_ary_unshift(args->rest, args->argv[--argc]); + } } else if (args->argc > 0) { - args->rest = rb_ary_new_from_values(args->argc, args->argv); - args->rest_index = 0; + args->rest = rb_ary_new_from_values(args->argc, args->argv); + args->rest_index = 0; args->rest_dupped = TRUE; - args->argc = 0; + args->argc = 0; } } @@ -179,10 +179,10 @@ args_rest_array(struct args_info *args) if (args->rest) { ary = rb_ary_behead(args->rest, args->rest_index); args->rest_index = 0; - args->rest = 0; + args->rest = 0; } else { - ary = rb_ary_new(); + ary = rb_ary_new(); } return ary; } @@ -200,7 +200,7 @@ args_kw_argv_to_hash(struct args_info *args) args->argc = kw_start + 1; for (i=0; iargv[args->argc - 1] = h; @@ -212,19 +212,19 @@ static inline void args_setup_lead_parameters(struct args_info *args, int argc, VALUE *locals) { if (args->argc >= argc) { - /* do noting */ - args->argc -= argc; - args->argv += argc; + /* do noting */ + args->argc -= argc; + args->argv += argc; } else { - int i, j; - const VALUE *argv = args_rest_argv(args); + int i, j; + const VALUE *argv = args_rest_argv(args); - for (i=args->argc, j=0; irest_index += argc - args->argc; - args->argc = 0; + for (i=args->argc, j=0; irest_index += argc - args->argc; + args->argc = 0; } } @@ -243,16 +243,16 @@ args_setup_opt_parameters(struct args_info *args, int opt_max, VALUE *locals) int i; if (args->argc >= opt_max) { - args->argc -= opt_max; - args->argv += opt_max; - i = opt_max; + args->argc -= opt_max; + args->argv += opt_max; + i = opt_max; } else { - int j; - i = args->argc; - args->argc = 0; + int j; + i = args->argc; + args->argc = 0; - if (args->rest) { + if (args->rest) { int len = RARRAY_LENINT(args->rest); const VALUE *argv = RARRAY_CONST_PTR_TRANSIENT(args->rest); @@ -261,10 +261,10 @@ args_setup_opt_parameters(struct args_info *args, int opt_max, VALUE *locals) } } - /* initialize by nil */ - for (j=i; jparam.keyword->table; const int req_key_num = ISEQ_BODY(iseq)->param.keyword->required_num; @@ -338,63 +338,63 @@ args_setup_kw_parameters(rb_execution_context_t *const ec, const rb_iseq_t *cons VALUE unspecified_bits_value = Qnil; for (i=0; i hash */ - int j; - unspecified_bits_value = rb_hash_new(); + if (LIKELY(i < KW_SPECIFIED_BITS_MAX)) { + unspecified_bits |= 0x01 << di; + } + else { + if (NIL_P(unspecified_bits_value)) { + /* fixnum -> hash */ + int j; + unspecified_bits_value = rb_hash_new(); - for (j=0; jparam.flags.has_kwrest) { - const int rest_hash_index = key_num + 1; - locals[rest_hash_index] = make_rest_kw_hash(passed_keywords, passed_keyword_len, passed_values); + const int rest_hash_index = key_num + 1; + locals[rest_hash_index] = make_rest_kw_hash(passed_keywords, passed_keyword_len, passed_values); } else { - if (found != passed_keyword_len) { - VALUE keys = make_unknown_kw_hash(passed_keywords, passed_keyword_len, passed_values); - argument_kw_error(ec, iseq, "unknown", keys); - } + if (found != passed_keyword_len) { + VALUE keys = make_unknown_kw_hash(passed_keywords, passed_keyword_len, passed_values); + argument_kw_error(ec, iseq, "unknown", keys); + } } if (NIL_P(unspecified_bits_value)) { - unspecified_bits_value = INT2FIX(unspecified_bits); + unspecified_bits_value = INT2FIX(unspecified_bits); } locals[key_num] = unspecified_bits_value; } @@ -454,7 +454,7 @@ ignore_keyword_hash_p(VALUE keyword_hash, const rb_iseq_t * const iseq, unsigned static int setup_parameters_complex(rb_execution_context_t * const ec, const rb_iseq_t * const iseq, - struct rb_calling_info *const calling, + struct rb_calling_info *const calling, const struct rb_callinfo *ci, VALUE * const locals, const enum arg_setup_type arg_setup_type) { @@ -488,7 +488,7 @@ setup_parameters_complex(rb_execution_context_t * const ec, const rb_iseq_t * co * ^ locals ^ sp */ for (i=calling->argc; iparam.size; i++) { - locals[i] = Qnil; + locals[i] = Qnil; } ec->cfp->sp = &locals[i]; @@ -499,31 +499,31 @@ setup_parameters_complex(rb_execution_context_t * const ec, const rb_iseq_t * co args->rest_dupped = FALSE; if (kw_flag & VM_CALL_KWARG) { - args->kw_arg = vm_ci_kwarg(ci); + args->kw_arg = vm_ci_kwarg(ci); if (ISEQ_BODY(iseq)->param.flags.has_kw) { - int kw_len = args->kw_arg->keyword_len; - /* copy kw_argv */ - args->kw_argv = ALLOCA_N(VALUE, kw_len); - args->argc -= kw_len; - given_argc -= kw_len; - MEMCPY(args->kw_argv, locals + args->argc, VALUE, kw_len); - } - else { - args->kw_argv = NULL; - given_argc = args_kw_argv_to_hash(args); + int kw_len = args->kw_arg->keyword_len; + /* copy kw_argv */ + args->kw_argv = ALLOCA_N(VALUE, kw_len); + args->argc -= kw_len; + given_argc -= kw_len; + MEMCPY(args->kw_argv, locals + args->argc, VALUE, kw_len); + } + else { + args->kw_argv = NULL; + given_argc = args_kw_argv_to_hash(args); kw_flag |= VM_CALL_KW_SPLAT | VM_CALL_KW_SPLAT_MUT; - } + } } else { - args->kw_arg = NULL; - args->kw_argv = NULL; + args->kw_arg = NULL; + args->kw_argv = NULL; } if (vm_ci_flag(ci) & VM_CALL_ARGS_SPLAT) { int len; - args->rest = locals[--args->argc]; - args->rest_index = 0; + args->rest = locals[--args->argc]; + args->rest_index = 0; len = RARRAY_LENINT(args->rest); given_argc += len - 1; rest_last = RARRAY_AREF(args->rest, len - 1); @@ -546,7 +546,7 @@ setup_parameters_complex(rb_execution_context_t * const ec, const rb_iseq_t * co rb_ary_pop(args->rest); given_argc--; kw_flag &= ~(VM_CALL_KW_SPLAT | VM_CALL_KW_SPLAT_MUT); - } + } else { if (rest_last != converted_keyword_hash) { rest_last = converted_keyword_hash; @@ -573,7 +573,7 @@ setup_parameters_complex(rb_execution_context_t * const ec, const rb_iseq_t * co args->argc--; given_argc--; kw_flag &= ~(VM_CALL_KW_SPLAT | VM_CALL_KW_SPLAT_MUT); - } + } else { if (last_arg != converted_keyword_hash) { last_arg = converted_keyword_hash; @@ -590,7 +590,7 @@ setup_parameters_complex(rb_execution_context_t * const ec, const rb_iseq_t * co } } } - args->rest = Qfalse; + args->rest = Qfalse; } if (flag_keyword_hash && RB_TYPE_P(flag_keyword_hash, T_HASH)) { @@ -598,12 +598,12 @@ setup_parameters_complex(rb_execution_context_t * const ec, const rb_iseq_t * co } if (kw_flag && ISEQ_BODY(iseq)->param.flags.accepts_no_kwarg) { - rb_raise(rb_eArgError, "no keywords accepted"); + rb_raise(rb_eArgError, "no keywords accepted"); } switch (arg_setup_type) { case arg_setup_method: - break; /* do nothing special */ + break; /* do nothing special */ case arg_setup_block: if (given_argc == (NIL_P(keyword_hash) ? 1 : 2) && allow_autosplat && @@ -612,10 +612,10 @@ setup_parameters_complex(rb_execution_context_t * const ec, const rb_iseq_t * co !((ISEQ_BODY(iseq)->param.flags.has_kw || ISEQ_BODY(iseq)->param.flags.has_kwrest) && max_argc == 1) && - args_check_block_arg0(args)) { - given_argc = RARRAY_LENINT(args->rest); - } - break; + args_check_block_arg0(args)) { + given_argc = RARRAY_LENINT(args->rest); + } + break; } /* argc check */ @@ -631,14 +631,14 @@ setup_parameters_complex(rb_execution_context_t * const ec, const rb_iseq_t * co } if (given_argc > max_argc && max_argc != UNLIMITED_ARGUMENTS) { - if (arg_setup_type == arg_setup_block) { - /* truncate */ - args_reduce(args, given_argc - max_argc); - given_argc = max_argc; - } - else { - argument_arity_error(ec, iseq, given_argc, min_argc, max_argc); - } + if (arg_setup_type == arg_setup_block) { + /* truncate */ + args_reduce(args, given_argc - max_argc); + given_argc = max_argc; + } + else { + argument_arity_error(ec, iseq, given_argc, min_argc, max_argc); + } } if (ISEQ_BODY(iseq)->param.flags.has_lead) { @@ -675,48 +675,48 @@ setup_parameters_complex(rb_execution_context_t * const ec, const rb_iseq_t * co if (ISEQ_BODY(iseq)->param.flags.has_kw) { VALUE * const klocals = locals + ISEQ_BODY(iseq)->param.keyword->bits_start - ISEQ_BODY(iseq)->param.keyword->num; - if (args->kw_argv != NULL) { - const struct rb_callinfo_kwarg *kw_arg = args->kw_arg; - args_setup_kw_parameters(ec, iseq, args->kw_argv, kw_arg->keyword_len, kw_arg->keywords, klocals); - } - else if (!NIL_P(keyword_hash)) { - int kw_len = rb_long2int(RHASH_SIZE(keyword_hash)); - struct fill_values_arg arg; - /* copy kw_argv */ - arg.keys = args->kw_argv = ALLOCA_N(VALUE, kw_len * 2); - arg.vals = arg.keys + kw_len; - arg.argc = 0; - rb_hash_foreach(keyword_hash, fill_keys_values, (VALUE)&arg); - VM_ASSERT(arg.argc == kw_len); - args_setup_kw_parameters(ec, iseq, arg.vals, kw_len, arg.keys, klocals); - } - else { - VM_ASSERT(args_argc(args) == 0); - args_setup_kw_parameters(ec, iseq, NULL, 0, NULL, klocals); - } + if (args->kw_argv != NULL) { + const struct rb_callinfo_kwarg *kw_arg = args->kw_arg; + args_setup_kw_parameters(ec, iseq, args->kw_argv, kw_arg->keyword_len, kw_arg->keywords, klocals); + } + else if (!NIL_P(keyword_hash)) { + int kw_len = rb_long2int(RHASH_SIZE(keyword_hash)); + struct fill_values_arg arg; + /* copy kw_argv */ + arg.keys = args->kw_argv = ALLOCA_N(VALUE, kw_len * 2); + arg.vals = arg.keys + kw_len; + arg.argc = 0; + rb_hash_foreach(keyword_hash, fill_keys_values, (VALUE)&arg); + VM_ASSERT(arg.argc == kw_len); + args_setup_kw_parameters(ec, iseq, arg.vals, kw_len, arg.keys, klocals); + } + else { + VM_ASSERT(args_argc(args) == 0); + args_setup_kw_parameters(ec, iseq, NULL, 0, NULL, klocals); + } } else if (ISEQ_BODY(iseq)->param.flags.has_kwrest) { args_setup_kw_rest_parameter(keyword_hash, locals + ISEQ_BODY(iseq)->param.keyword->rest_start, kw_flag); } else if (!NIL_P(keyword_hash) && RHASH_SIZE(keyword_hash) > 0 && arg_setup_type == arg_setup_method) { - argument_kw_error(ec, iseq, "unknown", rb_hash_keys(keyword_hash)); + argument_kw_error(ec, iseq, "unknown", rb_hash_keys(keyword_hash)); } if (ISEQ_BODY(iseq)->param.flags.has_block) { if (ISEQ_BODY(iseq)->local_iseq == iseq) { - /* Do nothing */ - } - else { + /* Do nothing */ + } + else { args_setup_block_parameter(ec, calling, locals + ISEQ_BODY(iseq)->param.block_start); - } + } } #if 0 { - int i; + int i; for (i=0; iparam.size; i++) { - ruby_debug_printf("local[%d] = %p\n", i, (void *)locals[i]); - } + ruby_debug_printf("local[%d] = %p\n", i, (void *)locals[i]); + } } #endif @@ -730,16 +730,16 @@ raise_argument_error(rb_execution_context_t *ec, const rb_iseq_t *iseq, const VA VALUE at; if (iseq) { - vm_push_frame(ec, iseq, VM_FRAME_MAGIC_DUMMY | VM_ENV_FLAG_LOCAL, Qnil /* self */, - VM_BLOCK_HANDLER_NONE /* specval*/, Qfalse /* me or cref */, + vm_push_frame(ec, iseq, VM_FRAME_MAGIC_DUMMY | VM_ENV_FLAG_LOCAL, Qnil /* self */, + VM_BLOCK_HANDLER_NONE /* specval*/, Qfalse /* me or cref */, ISEQ_BODY(iseq)->iseq_encoded, - ec->cfp->sp, 0, 0 /* stack_max */); - at = rb_ec_backtrace_object(ec); - rb_backtrace_use_iseq_first_lineno_for_last_location(at); - rb_vm_pop_frame(ec); + ec->cfp->sp, 0, 0 /* stack_max */); + at = rb_ec_backtrace_object(ec); + rb_backtrace_use_iseq_first_lineno_for_last_location(at); + rb_vm_pop_frame(ec); } else { - at = rb_ec_backtrace_object(ec); + at = rb_ec_backtrace_object(ec); } rb_ivar_set(exc, idBt_locations, at); @@ -753,21 +753,21 @@ argument_arity_error(rb_execution_context_t *ec, const rb_iseq_t *iseq, const in VALUE exc = rb_arity_error_new(miss_argc, min_argc, max_argc); if (ISEQ_BODY(iseq)->param.flags.has_kw) { const struct rb_iseq_param_keyword *const kw = ISEQ_BODY(iseq)->param.keyword; - const ID *keywords = kw->table; - int req_key_num = kw->required_num; - if (req_key_num > 0) { - static const char required[] = "; required keywords"; - VALUE mesg = rb_attr_get(exc, idMesg); - rb_str_resize(mesg, RSTRING_LEN(mesg)-1); - rb_str_cat(mesg, required, sizeof(required) - 1 - (req_key_num == 1)); - rb_str_cat_cstr(mesg, ":"); - do { - rb_str_cat_cstr(mesg, " "); - rb_str_append(mesg, rb_id2str(*keywords++)); - rb_str_cat_cstr(mesg, ","); - } while (--req_key_num); - RSTRING_PTR(mesg)[RSTRING_LEN(mesg)-1] = ')'; - } + const ID *keywords = kw->table; + int req_key_num = kw->required_num; + if (req_key_num > 0) { + static const char required[] = "; required keywords"; + VALUE mesg = rb_attr_get(exc, idMesg); + rb_str_resize(mesg, RSTRING_LEN(mesg)-1); + rb_str_cat(mesg, required, sizeof(required) - 1 - (req_key_num == 1)); + rb_str_cat_cstr(mesg, ":"); + do { + rb_str_cat_cstr(mesg, " "); + rb_str_append(mesg, rb_id2str(*keywords++)); + rb_str_cat_cstr(mesg, ","); + } while (--req_key_num); + RSTRING_PTR(mesg)[RSTRING_LEN(mesg)-1] = ')'; + } } raise_argument_error(ec, iseq, exc); } @@ -811,7 +811,7 @@ vm_caller_setup_arg_kw(rb_control_frame_t *cfp, struct rb_calling_info *calling, int i; for (i=0; isp); + VALUE block_code = *(--reg_cfp->sp); - if (NIL_P(block_code)) { + if (NIL_P(block_code)) { return VM_BLOCK_HANDLER_NONE; } - else if (block_code == rb_block_param_proxy) { + else if (block_code == rb_block_param_proxy) { VM_ASSERT(!VM_CFP_IN_HEAP_P(GET_EC(), reg_cfp)); VALUE handler = VM_CF_BLOCK_HANDLER(reg_cfp); reg_cfp->block_code = (const void *) handler; return handler; } - else if (SYMBOL_P(block_code) && rb_method_basic_definition_p(rb_cSymbol, idTo_proc)) { - const rb_cref_t *cref = vm_env_cref(reg_cfp->ep); - if (cref && !NIL_P(cref->refinements)) { - VALUE ref = cref->refinements; - VALUE func = rb_hash_lookup(ref, block_code); - if (NIL_P(func)) { - /* TODO: limit cached funcs */ + else if (SYMBOL_P(block_code) && rb_method_basic_definition_p(rb_cSymbol, idTo_proc)) { + const rb_cref_t *cref = vm_env_cref(reg_cfp->ep); + if (cref && !NIL_P(cref->refinements)) { + VALUE ref = cref->refinements; + VALUE func = rb_hash_lookup(ref, block_code); + if (NIL_P(func)) { + /* TODO: limit cached funcs */ VALUE callback_arg = rb_ary_tmp_new(2); rb_ary_push(callback_arg, block_code); rb_ary_push(callback_arg, ref); OBJ_FREEZE_RAW(callback_arg); func = rb_func_lambda_new(refine_sym_proc_call, callback_arg, 1, UNLIMITED_ARGUMENTS); - rb_hash_aset(ref, block_code, func); - } - block_code = func; - } + rb_hash_aset(ref, block_code, func); + } + block_code = func; + } return block_code; } else { @@ -923,12 +923,12 @@ vm_caller_setup_arg_block(const rb_execution_context_t *ec, rb_control_frame_t * } } else if (blockiseq != NULL) { /* likely */ - struct rb_captured_block *captured = VM_CFP_TO_CAPTURED_BLOCK(reg_cfp); - captured->code.iseq = blockiseq; + struct rb_captured_block *captured = VM_CFP_TO_CAPTURED_BLOCK(reg_cfp); + captured->code.iseq = blockiseq; return VM_BH_FROM_ISEQ_BLOCK(captured); } else { - if (is_super) { + if (is_super) { return GET_BLOCK_HANDLER(); } else { diff --git a/vm_backtrace.c b/vm_backtrace.c index 814dc1a345..ee749deb14 100644 --- a/vm_backtrace.c +++ b/vm_backtrace.c @@ -99,24 +99,24 @@ int rb_vm_get_sourceline(const rb_control_frame_t *cfp) { if (VM_FRAME_RUBYFRAME_P(cfp) && cfp->iseq) { - const rb_iseq_t *iseq = cfp->iseq; - int line = calc_lineno(iseq, cfp->pc); - if (line != 0) { - return line; - } - else { - return FIX2INT(rb_iseq_first_lineno(iseq)); - } + const rb_iseq_t *iseq = cfp->iseq; + int line = calc_lineno(iseq, cfp->pc); + if (line != 0) { + return line; + } + else { + return FIX2INT(rb_iseq_first_lineno(iseq)); + } } else { - return 0; + return 0; } } typedef struct rb_backtrace_location_struct { enum LOCATION_TYPE { - LOCATION_TYPE_ISEQ = 1, - LOCATION_TYPE_CFUNC, + LOCATION_TYPE_ISEQ = 1, + LOCATION_TYPE_CFUNC, } type; const rb_iseq_t *iseq; @@ -142,14 +142,14 @@ location_mark_entry(rb_backtrace_location_t *fi) switch (fi->type) { case LOCATION_TYPE_ISEQ: rb_gc_mark_movable((VALUE)fi->iseq); - break; + break; case LOCATION_TYPE_CFUNC: if (fi->iseq) { rb_gc_mark_movable((VALUE)fi->iseq); } break; default: - break; + break; } } @@ -189,11 +189,11 @@ location_lineno(rb_backtrace_location_t *loc) case LOCATION_TYPE_CFUNC: if (loc->iseq && loc->pc) { return calc_lineno(loc->iseq, loc->pc); - } - return 0; + } + return 0; default: - rb_bug("location_lineno: unreachable"); - UNREACHABLE; + rb_bug("location_lineno: unreachable"); + UNREACHABLE; } } @@ -220,8 +220,8 @@ location_label(rb_backtrace_location_t *loc) case LOCATION_TYPE_CFUNC: return rb_id2str(loc->mid); default: - rb_bug("location_label: unreachable"); - UNREACHABLE; + rb_bug("location_label: unreachable"); + UNREACHABLE; } } @@ -267,8 +267,8 @@ location_base_label(rb_backtrace_location_t *loc) case LOCATION_TYPE_CFUNC: return rb_id2str(loc->mid); default: - rb_bug("location_base_label: unreachable"); - UNREACHABLE; + rb_bug("location_base_label: unreachable"); + UNREACHABLE; } } @@ -292,8 +292,8 @@ location_iseq(rb_backtrace_location_t *loc) case LOCATION_TYPE_CFUNC: return loc->iseq; default: - rb_bug("location_iseq: unreachable"); - UNREACHABLE; + rb_bug("location_iseq: unreachable"); + UNREACHABLE; } } @@ -361,11 +361,11 @@ location_realpath(rb_backtrace_location_t *loc) case LOCATION_TYPE_CFUNC: if (loc->iseq) { return rb_iseq_realpath(loc->iseq); - } - return Qnil; + } + return Qnil; default: - rb_bug("location_realpath: unreachable"); - UNREACHABLE; + rb_bug("location_realpath: unreachable"); + UNREACHABLE; } } @@ -386,14 +386,14 @@ location_format(VALUE file, int lineno, VALUE name) { VALUE s = rb_enc_sprintf(rb_enc_compatible(file, name), "%s", RSTRING_PTR(file)); if (lineno != 0) { - rb_str_catf(s, ":%d", lineno); + rb_str_catf(s, ":%d", lineno); } rb_str_cat_cstr(s, ":in "); if (NIL_P(name)) { - rb_str_cat_cstr(s, "unknown method"); + rb_str_cat_cstr(s, "unknown method"); } else { - rb_str_catf(s, "`%s'", RSTRING_PTR(name)); + rb_str_catf(s, "`%s'", RSTRING_PTR(name)); } return s; } @@ -410,20 +410,20 @@ location_to_str(rb_backtrace_location_t *loc) name = ISEQ_BODY(loc->iseq)->location.label; lineno = calc_lineno(loc->iseq, loc->pc); - break; + break; case LOCATION_TYPE_CFUNC: if (loc->iseq && loc->pc) { file = rb_iseq_path(loc->iseq); lineno = calc_lineno(loc->iseq, loc->pc); - } - else { - file = GET_VM()->progname; + } + else { + file = GET_VM()->progname; lineno = 0; - } + } name = rb_id2str(loc->mid); - break; + break; default: - rb_bug("location_to_str: unreachable"); + rb_bug("location_to_str: unreachable"); } return location_format(file, lineno, name); @@ -462,7 +462,7 @@ backtrace_mark(void *ptr) size_t i, s = bt->backtrace_size; for (i=0; ibacktrace[i]); + location_mark_entry(&bt->backtrace[i]); } rb_gc_mark_movable(bt->strary); rb_gc_mark_movable(bt->locary); @@ -482,14 +482,14 @@ location_update_entry(rb_backtrace_location_t *fi) switch (fi->type) { case LOCATION_TYPE_ISEQ: fi->iseq = (rb_iseq_t*)rb_gc_location((VALUE)fi->iseq); - break; + break; case LOCATION_TYPE_CFUNC: if (fi->iseq) { fi->iseq = (rb_iseq_t*)rb_gc_location((VALUE)fi->iseq); } break; default: - break; + break; } } @@ -500,7 +500,7 @@ backtrace_update(void *ptr) size_t i, s = bt->backtrace_size; for (i=0; ibacktrace[i]); + location_update_entry(&bt->backtrace[i]); } bt->strary = rb_gc_location(bt->strary); bt->locary = rb_gc_location(bt->locary); @@ -696,7 +696,7 @@ backtrace_collect(rb_backtrace_t *bt, VALUE (*func)(rb_backtrace_location_t *, v for (i=0; ibacktrace_size; i++) { rb_backtrace_location_t *loc = &bt->backtrace[i]; - rb_ary_push(btary, func(loc, arg)); + rb_ary_push(btary, func(loc, arg)); } return btary; @@ -973,12 +973,12 @@ oldbt_print(void *data, VALUE file, int lineno, VALUE name) FILE *fp = (FILE *)data; if (NIL_P(name)) { - fprintf(fp, "\tfrom %s:%d:in unknown method\n", - RSTRING_PTR(file), lineno); + fprintf(fp, "\tfrom %s:%d:in unknown method\n", + RSTRING_PTR(file), lineno); } else { - fprintf(fp, "\tfrom %s:%d:in `%s'\n", - RSTRING_PTR(file), lineno, RSTRING_PTR(name)); + fprintf(fp, "\tfrom %s:%d:in `%s'\n", + RSTRING_PTR(file), lineno, RSTRING_PTR(name)); } } @@ -990,10 +990,10 @@ vm_backtrace_print(FILE *fp) arg.func = oldbt_print; arg.data = (void *)fp; backtrace_each(GET_EC(), - oldbt_init, - oldbt_iter_iseq, - oldbt_iter_cfunc, - &arg); + oldbt_init, + oldbt_iter_iseq, + oldbt_iter_cfunc, + &arg); } static void @@ -1001,15 +1001,15 @@ oldbt_bugreport(void *arg, VALUE file, int line, VALUE method) { const char *filename = NIL_P(file) ? "ruby" : RSTRING_PTR(file); if (!*(int *)arg) { - fprintf(stderr, "-- Ruby level backtrace information " - "----------------------------------------\n"); - *(int *)arg = 1; + fprintf(stderr, "-- Ruby level backtrace information " + "----------------------------------------\n"); + *(int *)arg = 1; } if (NIL_P(method)) { - fprintf(stderr, "%s:%d:in unknown method\n", filename, line); + fprintf(stderr, "%s:%d:in unknown method\n", filename, line); } else { - fprintf(stderr, "%s:%d:in `%s'\n", filename, line, RSTRING_PTR(method)); + fprintf(stderr, "%s:%d:in `%s'\n", filename, line, RSTRING_PTR(method)); } } @@ -1023,10 +1023,10 @@ rb_backtrace_print_as_bugreport(void) arg.data = (int *)&i; backtrace_each(GET_EC(), - oldbt_init, - oldbt_iter_iseq, - oldbt_iter_cfunc, - &arg); + oldbt_init, + oldbt_iter_iseq, + oldbt_iter_cfunc, + &arg); } void @@ -1047,10 +1047,10 @@ oldbt_print_to(void *data, VALUE file, int lineno, VALUE name) VALUE str = rb_sprintf("\tfrom %"PRIsVALUE":%d:in ", file, lineno); if (NIL_P(name)) { - rb_str_cat2(str, "unknown method\n"); + rb_str_cat2(str, "unknown method\n"); } else { - rb_str_catf(str, " `%"PRIsVALUE"'\n", name); + rb_str_catf(str, " `%"PRIsVALUE"'\n", name); } (*arg->iter)(arg->output, str); } @@ -1066,10 +1066,10 @@ rb_backtrace_each(VALUE (*iter)(VALUE recv, VALUE str), VALUE output) arg.func = oldbt_print_to; arg.data = &parg; backtrace_each(GET_EC(), - oldbt_init, - oldbt_iter_iseq, - oldbt_iter_cfunc, - &arg); + oldbt_init, + oldbt_iter_iseq, + oldbt_iter_cfunc, + &arg); } VALUE @@ -1093,48 +1093,48 @@ ec_backtrace_to_ary(const rb_execution_context_t *ec, int argc, const VALUE *arg switch (argc) { case 0: - lev = lev_default + lev_plus; + lev = lev_default + lev_plus; n = ALL_BACKTRACE_LINES; - break; + break; case 1: - { + { long beg, len, bt_size = backtrace_size(ec); switch (rb_range_beg_len(level, &beg, &len, bt_size - lev_plus, 0)) { - case Qfalse: - lev = NUM2LONG(level); - if (lev < 0) { - rb_raise(rb_eArgError, "negative level (%ld)", lev); - } - lev += lev_plus; + case Qfalse: + lev = NUM2LONG(level); + if (lev < 0) { + rb_raise(rb_eArgError, "negative level (%ld)", lev); + } + lev += lev_plus; n = ALL_BACKTRACE_LINES; - break; - case Qnil: - return Qnil; - default: - lev = beg + lev_plus; - n = len; - break; - } - break; - } + break; + case Qnil: + return Qnil; + default: + lev = beg + lev_plus; + n = len; + break; + } + break; + } case 2: - lev = NUM2LONG(level); - n = NUM2LONG(vn); - if (lev < 0) { - rb_raise(rb_eArgError, "negative level (%ld)", lev); - } - if (n < 0) { - rb_raise(rb_eArgError, "negative size (%ld)", n); - } - lev += lev_plus; - break; + lev = NUM2LONG(level); + n = NUM2LONG(vn); + if (lev < 0) { + rb_raise(rb_eArgError, "negative level (%ld)", lev); + } + if (n < 0) { + rb_raise(rb_eArgError, "negative size (%ld)", n); + } + lev += lev_plus; + break; default: - lev = n = 0; /* to avoid warning */ - break; + lev = n = 0; /* to avoid warning */ + break; } if (n == 0) { - return rb_ary_new(); + return rb_ary_new(); } btval = rb_ec_partial_backtrace_object(ec, lev, n, &too_large, FALSE, FALSE); @@ -1388,15 +1388,15 @@ get_klass(const rb_control_frame_t *cfp) { VALUE klass; if (rb_vm_control_frame_id_and_class(cfp, 0, 0, &klass)) { - if (RB_TYPE_P(klass, T_ICLASS)) { - return RBASIC(klass)->klass; - } - else { - return klass; - } + if (RB_TYPE_P(klass, T_ICLASS)) { + return RBASIC(klass)->klass; + } + else { + return klass; + } } else { - return Qnil; + return Qnil; } } @@ -1440,22 +1440,22 @@ collect_caller_bindings(const rb_execution_context_t *ec) data.ary = rb_ary_new(); backtrace_each(ec, - collect_caller_bindings_init, - collect_caller_bindings_iseq, - collect_caller_bindings_cfunc, - &data); + collect_caller_bindings_init, + collect_caller_bindings_iseq, + collect_caller_bindings_cfunc, + &data); result = rb_ary_reverse(data.ary); /* bindings should be created from top of frame */ for (i=0; i= dc->backtrace_size) { - rb_raise(rb_eArgError, "no such frame"); + rb_raise(rb_eArgError, "no such frame"); } return rb_ary_entry(dc->contexts, index); } @@ -1553,33 +1553,33 @@ rb_profile_frames(int start, int limit, VALUE *buff, int *lines) for (i=0; i 0) { - start--; - continue; - } + if (start > 0) { + start--; + continue; + } - /* record frame info */ - cme = rb_vm_frame_method_entry(cfp); - if (cme && cme->def->type == VM_METHOD_TYPE_ISEQ) { - buff[i] = (VALUE)cme; - } - else { - buff[i] = (VALUE)cfp->iseq; - } + /* record frame info */ + cme = rb_vm_frame_method_entry(cfp); + if (cme && cme->def->type == VM_METHOD_TYPE_ISEQ) { + buff[i] = (VALUE)cme; + } + else { + buff[i] = (VALUE)cfp->iseq; + } - if (lines) lines[i] = calc_lineno(cfp->iseq, cfp->pc); + if (lines) lines[i] = calc_lineno(cfp->iseq, cfp->pc); - i++; - } + i++; + } else { - cme = rb_vm_frame_method_entry(cfp); - if (cme && cme->def->type == VM_METHOD_TYPE_CFUNC) { - buff[i] = (VALUE)cme; + cme = rb_vm_frame_method_entry(cfp); + if (cme && cme->def->type == VM_METHOD_TYPE_CFUNC) { + buff[i] = (VALUE)cme; if (lines) lines[i] = 0; i++; } } - cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); + cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); } return i; @@ -1591,22 +1591,22 @@ frame2iseq(VALUE frame) if (NIL_P(frame)) return NULL; if (RB_TYPE_P(frame, T_IMEMO)) { - switch (imemo_type(frame)) { - case imemo_iseq: - return (const rb_iseq_t *)frame; - case imemo_ment: - { - const rb_callable_method_entry_t *cme = (rb_callable_method_entry_t *)frame; - switch (cme->def->type) { - case VM_METHOD_TYPE_ISEQ: - return cme->def->body.iseq.iseqptr; - default: - return NULL; - } - } - default: - break; - } + switch (imemo_type(frame)) { + case imemo_iseq: + return (const rb_iseq_t *)frame; + case imemo_ment: + { + const rb_callable_method_entry_t *cme = (rb_callable_method_entry_t *)frame; + switch (cme->def->type) { + case VM_METHOD_TYPE_ISEQ: + return cme->def->body.iseq.iseqptr; + default: + return NULL; + } + } + default: + break; + } } rb_bug("frame2iseq: unreachable"); } @@ -1624,16 +1624,16 @@ cframe(VALUE frame) if (NIL_P(frame)) return NULL; if (RB_TYPE_P(frame, T_IMEMO)) { - switch (imemo_type(frame)) { - case imemo_ment: + switch (imemo_type(frame)) { + case imemo_ment: { - const rb_callable_method_entry_t *cme = (rb_callable_method_entry_t *)frame; - switch (cme->def->type) { - case VM_METHOD_TYPE_CFUNC: - return cme; - default: - return NULL; - } + const rb_callable_method_entry_t *cme = (rb_callable_method_entry_t *)frame; + switch (cme->def->type) { + case VM_METHOD_TYPE_CFUNC: + return cme; + default: + return NULL; + } } default: return NULL; @@ -1685,11 +1685,11 @@ frame2klass(VALUE frame) if (NIL_P(frame)) return Qnil; if (RB_TYPE_P(frame, T_IMEMO)) { - const rb_callable_method_entry_t *cme = (rb_callable_method_entry_t *)frame; + const rb_callable_method_entry_t *cme = (rb_callable_method_entry_t *)frame; - if (imemo_type(frame) == imemo_ment) { - return cme->defined_class; - } + if (imemo_type(frame) == imemo_ment) { + return cme->defined_class; + } } return Qnil; } @@ -1700,18 +1700,18 @@ rb_profile_frame_classpath(VALUE frame) VALUE klass = frame2klass(frame); if (klass && !NIL_P(klass)) { - if (RB_TYPE_P(klass, T_ICLASS)) { - klass = RBASIC(klass)->klass; - } - else if (FL_TEST(klass, FL_SINGLETON)) { - klass = rb_ivar_get(klass, id__attached__); - if (!RB_TYPE_P(klass, T_CLASS) && !RB_TYPE_P(klass, T_MODULE)) - return rb_sprintf("#<%s:%p>", rb_class2name(rb_obj_class(klass)), (void*)klass); - } - return rb_class_path(klass); + if (RB_TYPE_P(klass, T_ICLASS)) { + klass = RBASIC(klass)->klass; + } + else if (FL_TEST(klass, FL_SINGLETON)) { + klass = rb_ivar_get(klass, id__attached__); + if (!RB_TYPE_P(klass, T_CLASS) && !RB_TYPE_P(klass, T_MODULE)) + return rb_sprintf("#<%s:%p>", rb_class2name(rb_obj_class(klass)), (void*)klass); + } + return rb_class_path(klass); } else { - return Qnil; + return Qnil; } } @@ -1739,19 +1739,19 @@ static VALUE qualified_method_name(VALUE frame, VALUE method_name) { if (method_name != Qnil) { - VALUE classpath = rb_profile_frame_classpath(frame); - VALUE singleton_p = rb_profile_frame_singleton_method_p(frame); + VALUE classpath = rb_profile_frame_classpath(frame); + VALUE singleton_p = rb_profile_frame_singleton_method_p(frame); - if (classpath != Qnil) { - return rb_sprintf("%"PRIsVALUE"%s%"PRIsVALUE, - classpath, singleton_p == Qtrue ? "." : "#", method_name); - } - else { - return method_name; - } + if (classpath != Qnil) { + return rb_sprintf("%"PRIsVALUE"%s%"PRIsVALUE, + classpath, singleton_p == Qtrue ? "." : "#", method_name); + } + else { + return method_name; + } } else { - return Qnil; + return Qnil; } } @@ -1778,13 +1778,13 @@ rb_profile_frame_full_label(VALUE frame) VALUE qualified_method_name = rb_profile_frame_qualified_method_name(frame); if (NIL_P(qualified_method_name) || base_label == qualified_method_name) { - return label; + return label; } else { - long label_length = RSTRING_LEN(label); - long base_label_length = RSTRING_LEN(base_label); - int prefix_len = rb_long2int(label_length - base_label_length); + long label_length = RSTRING_LEN(label); + long base_label_length = RSTRING_LEN(base_label); + int prefix_len = rb_long2int(label_length - base_label_length); - return rb_sprintf("%.*s%"PRIsVALUE, prefix_len, RSTRING_PTR(label), qualified_method_name); + return rb_sprintf("%.*s%"PRIsVALUE, prefix_len, RSTRING_PTR(label), qualified_method_name); } } diff --git a/vm_core.h b/vm_core.h index 2a6d15bfbc..025dc76798 100644 --- a/vm_core.h +++ b/vm_core.h @@ -252,7 +252,7 @@ struct iseq_inline_constant_cache_entry { }; STATIC_ASSERT(sizeof_iseq_inline_constant_cache_entry, (offsetof(struct iseq_inline_constant_cache_entry, ic_cref) + - sizeof(const rb_cref_t *)) <= sizeof(struct RObject)); + sizeof(const rb_cref_t *)) <= sizeof(struct RObject)); struct iseq_inline_constant_cache { struct iseq_inline_constant_cache_entry *entry; @@ -271,8 +271,8 @@ struct iseq_inline_cvar_cache_entry { union iseq_inline_storage_entry { struct { - struct rb_thread_struct *running_thread; - VALUE value; + struct rb_thread_struct *running_thread; + VALUE value; } once; struct iseq_inline_constant_cache ic_cache; struct iseq_inline_iv_cache_entry iv_cache; @@ -312,11 +312,11 @@ static inline VALUE pathobj_path(VALUE pathobj) { if (RB_TYPE_P(pathobj, T_STRING)) { - return pathobj; + return pathobj; } else { - VM_ASSERT(RB_TYPE_P(pathobj, T_ARRAY)); - return RARRAY_AREF(pathobj, PATHOBJ_PATH); + VM_ASSERT(RB_TYPE_P(pathobj, T_ARRAY)); + return RARRAY_AREF(pathobj, PATHOBJ_PATH); } } @@ -324,11 +324,11 @@ static inline VALUE pathobj_realpath(VALUE pathobj) { if (RB_TYPE_P(pathobj, T_STRING)) { - return pathobj; + return pathobj; } else { - VM_ASSERT(RB_TYPE_P(pathobj, T_ARRAY)); - return RARRAY_AREF(pathobj, PATHOBJ_REALPATH); + VM_ASSERT(RB_TYPE_P(pathobj, T_ARRAY)); + return RARRAY_AREF(pathobj, PATHOBJ_REALPATH); } } @@ -341,15 +341,15 @@ typedef uintptr_t iseq_bits_t; struct rb_iseq_constant_body { enum iseq_type { - ISEQ_TYPE_TOP, - ISEQ_TYPE_METHOD, - ISEQ_TYPE_BLOCK, - ISEQ_TYPE_CLASS, - ISEQ_TYPE_RESCUE, - ISEQ_TYPE_ENSURE, - ISEQ_TYPE_EVAL, - ISEQ_TYPE_MAIN, - ISEQ_TYPE_PLAIN + ISEQ_TYPE_TOP, + ISEQ_TYPE_METHOD, + ISEQ_TYPE_BLOCK, + ISEQ_TYPE_CLASS, + ISEQ_TYPE_RESCUE, + ISEQ_TYPE_ENSURE, + ISEQ_TYPE_EVAL, + ISEQ_TYPE_MAIN, + ISEQ_TYPE_PLAIN } type; /* instruction sequence type */ unsigned int iseq_size; @@ -379,63 +379,63 @@ struct rb_iseq_constant_body { */ struct { - struct { - unsigned int has_lead : 1; - unsigned int has_opt : 1; - unsigned int has_rest : 1; - unsigned int has_post : 1; - unsigned int has_kw : 1; - unsigned int has_kwrest : 1; - unsigned int has_block : 1; + struct { + unsigned int has_lead : 1; + unsigned int has_opt : 1; + unsigned int has_rest : 1; + unsigned int has_post : 1; + unsigned int has_kw : 1; + unsigned int has_kwrest : 1; + unsigned int has_block : 1; - unsigned int ambiguous_param0 : 1; /* {|a|} */ - unsigned int accepts_no_kwarg : 1; + unsigned int ambiguous_param0 : 1; /* {|a|} */ + unsigned int accepts_no_kwarg : 1; unsigned int ruby2_keywords: 1; - } flags; + } flags; - unsigned int size; + unsigned int size; - int lead_num; - int opt_num; - int rest_start; - int post_start; - int post_num; - int block_start; + int lead_num; + int opt_num; + int rest_start; + int post_start; + int post_num; + int block_start; - const VALUE *opt_table; /* (opt_num + 1) entries. */ - /* opt_num and opt_table: - * - * def foo o1=e1, o2=e2, ..., oN=eN - * #=> - * # prologue code - * A1: e1 - * A2: e2 - * ... - * AN: eN - * AL: body - * opt_num = N - * opt_table = [A1, A2, ..., AN, AL] - */ + const VALUE *opt_table; /* (opt_num + 1) entries. */ + /* opt_num and opt_table: + * + * def foo o1=e1, o2=e2, ..., oN=eN + * #=> + * # prologue code + * A1: e1 + * A2: e2 + * ... + * AN: eN + * AL: body + * opt_num = N + * opt_table = [A1, A2, ..., AN, AL] + */ - const struct rb_iseq_param_keyword { - int num; - int required_num; - int bits_start; - int rest_start; - const ID *table; + const struct rb_iseq_param_keyword { + int num; + int required_num; + int bits_start; + int rest_start; + const ID *table; VALUE *default_values; - } *keyword; + } *keyword; } param; rb_iseq_location_t location; /* insn info, must be freed */ struct iseq_insn_info { - const struct iseq_insn_info_entry *body; - unsigned int *positions; - unsigned int size; + const struct iseq_insn_info_entry *body; + unsigned int *positions; + unsigned int size; #if VM_INSN_INFO_TABLE_IMPL == 2 - struct succ_index_table *succ_index_table; + struct succ_index_table *succ_index_table; #endif } insns_info; @@ -452,11 +452,11 @@ struct rb_iseq_constant_body { struct rb_call_data *call_data; //struct rb_call_data calls[ci_size]; struct { - rb_snum_t flip_count; + rb_snum_t flip_count; VALUE script_lines; - VALUE coverage; + VALUE coverage; VALUE pc2branchindex; - VALUE *original_iseq; + VALUE *original_iseq; } variable; unsigned int local_table_size; @@ -506,12 +506,12 @@ struct rb_iseq_struct { struct rb_iseq_constant_body *body; /* 3 */ union { /* 4, 5 words */ - struct iseq_compile_data *compile_data; /* used at compile time */ + struct iseq_compile_data *compile_data; /* used at compile time */ - struct { - VALUE obj; - int index; - } loader; + struct { + VALUE obj; + int index; + } loader; struct { struct rb_hook_list_struct *local_hooks; @@ -535,7 +535,7 @@ rb_iseq_check(const rb_iseq_t *iseq) { #if USE_LAZY_LOAD if (ISEQ_BODY(iseq) == NULL) { - rb_iseq_complete((rb_iseq_t *)iseq); + rb_iseq_complete((rb_iseq_t *)iseq); } #endif return iseq; @@ -686,7 +686,7 @@ typedef struct rb_vm_struct { /* signal */ struct { - VALUE cmd[RUBY_NSIG]; + VALUE cmd[RUBY_NSIG]; } trap_list; /* relation table of ensure - rollback for callcc */ @@ -737,10 +737,10 @@ typedef struct rb_vm_struct { /* params */ struct { /* size in byte */ - size_t thread_vm_stack_size; - size_t thread_machine_stack_size; - size_t fiber_vm_stack_size; - size_t fiber_machine_stack_size; + size_t thread_vm_stack_size; + size_t thread_machine_stack_size; + size_t fiber_vm_stack_size; + size_t fiber_machine_stack_size; } default_params; short redefined_flag[BOP_LAST_]; @@ -805,9 +805,9 @@ struct rb_captured_block { VALUE self; const VALUE *ep; union { - const rb_iseq_t *iseq; - const struct vm_ifunc *ifunc; - VALUE val; + const rb_iseq_t *iseq; + const struct vm_ifunc *ifunc; + VALUE val; } code; }; @@ -827,9 +827,9 @@ enum rb_block_type { struct rb_block { union { - struct rb_captured_block captured; - VALUE symbol; - VALUE proc; + struct rb_captured_block captured; + VALUE symbol; + VALUE proc; } as; enum rb_block_type type; }; @@ -886,8 +886,8 @@ struct rb_vm_tag { STATIC_ASSERT(rb_vm_tag_buf_offset, offsetof(struct rb_vm_tag, buf) > 0); STATIC_ASSERT(rb_vm_tag_buf_end, - offsetof(struct rb_vm_tag, buf) + sizeof(rb_jmpbuf_t) < - sizeof(struct rb_vm_tag)); + offsetof(struct rb_vm_tag, buf) + sizeof(rb_jmpbuf_t) < + sizeof(struct rb_vm_tag)); struct rb_unblock_callback { rb_unblock_function_t *func; @@ -961,10 +961,10 @@ struct rb_execution_context_struct { /* for GC */ struct { - VALUE *stack_start; - VALUE *stack_end; - size_t stack_maxsize; - RUBY_ALIGNAS(SIZEOF_VALUE) jmp_buf regs; + VALUE *stack_start; + VALUE *stack_end; + size_t stack_maxsize; + RUBY_ALIGNAS(SIZEOF_VALUE) jmp_buf regs; } machine; }; @@ -1481,13 +1481,13 @@ VM_BH_ISEQ_BLOCK_P(VALUE block_handler) { if ((block_handler & 0x03) == 0x01) { #if VM_CHECK_MODE > 0 - struct rb_captured_block *captured = VM_TAGGED_PTR_REF(block_handler, 0x03); - VM_ASSERT(imemo_type_p(captured->code.val, imemo_iseq)); + struct rb_captured_block *captured = VM_TAGGED_PTR_REF(block_handler, 0x03); + VM_ASSERT(imemo_type_p(captured->code.val, imemo_iseq)); #endif - return 1; + return 1; } else { - return 0; + return 0; } } @@ -1512,13 +1512,13 @@ VM_BH_IFUNC_P(VALUE block_handler) { if ((block_handler & 0x03) == 0x03) { #if VM_CHECK_MODE > 0 - struct rb_captured_block *captured = (void *)(block_handler & ~0x03); - VM_ASSERT(imemo_type_p(captured->code.val, imemo_ifunc)); + struct rb_captured_block *captured = (void *)(block_handler & ~0x03); + VM_ASSERT(imemo_type_p(captured->code.val, imemo_ifunc)); #endif - return 1; + return 1; } else { - return 0; + return 0; } } @@ -1550,17 +1550,17 @@ static inline enum rb_block_handler_type vm_block_handler_type(VALUE block_handler) { if (VM_BH_ISEQ_BLOCK_P(block_handler)) { - return block_handler_type_iseq; + return block_handler_type_iseq; } else if (VM_BH_IFUNC_P(block_handler)) { - return block_handler_type_ifunc; + return block_handler_type_ifunc; } else if (SYMBOL_P(block_handler)) { - return block_handler_type_symbol; + return block_handler_type_symbol; } else { - VM_ASSERT(rb_obj_is_proc(block_handler)); - return block_handler_type_proc; + VM_ASSERT(rb_obj_is_proc(block_handler)); + return block_handler_type_proc; } } @@ -1568,7 +1568,7 @@ static inline void vm_block_handler_verify(MAYBE_UNUSED(VALUE block_handler)) { VM_ASSERT(block_handler == VM_BLOCK_HANDLER_NONE || - (vm_block_handler_type(block_handler), 1)); + (vm_block_handler_type(block_handler), 1)); } static inline int @@ -1583,17 +1583,17 @@ vm_block_type(const struct rb_block *block) #if VM_CHECK_MODE > 0 switch (block->type) { case block_type_iseq: - VM_ASSERT(imemo_type_p(block->as.captured.code.val, imemo_iseq)); - break; + VM_ASSERT(imemo_type_p(block->as.captured.code.val, imemo_iseq)); + break; case block_type_ifunc: - VM_ASSERT(imemo_type_p(block->as.captured.code.val, imemo_ifunc)); - break; + VM_ASSERT(imemo_type_p(block->as.captured.code.val, imemo_ifunc)); + break; case block_type_symbol: - VM_ASSERT(SYMBOL_P(block->as.symbol)); - break; + VM_ASSERT(SYMBOL_P(block->as.symbol)); + break; case block_type_proc: - VM_ASSERT(rb_obj_is_proc(block->as.proc)); - break; + VM_ASSERT(rb_obj_is_proc(block->as.proc)); + break; } #endif return block->type; @@ -1660,11 +1660,11 @@ vm_block_self(const struct rb_block *block) switch (vm_block_type(block)) { case block_type_iseq: case block_type_ifunc: - return block->as.captured.self; + return block->as.captured.self; case block_type_proc: - return vm_block_self(vm_proc_block(block->as.proc)); + return vm_block_self(vm_proc_block(block->as.proc)); case block_type_symbol: - return Qundef; + return Qundef; } VM_UNREACHABLE(vm_block_self); return Qundef; @@ -1844,7 +1844,7 @@ rb_ec_ractor_ptr(const rb_execution_context_t *ec) const rb_thread_t *th = rb_ec_thread_ptr(ec); if (th) { VM_ASSERT(th->ractor != NULL); - return th->ractor; + return th->ractor; } else { return NULL; @@ -1856,10 +1856,10 @@ rb_ec_vm_ptr(const rb_execution_context_t *ec) { const rb_thread_t *th = rb_ec_thread_ptr(ec); if (th) { - return th->vm; + return th->vm; } else { - return NULL; + return NULL; } } @@ -1903,10 +1903,10 @@ rb_current_vm(void) { #if 0 // TODO: reconsider the assertions VM_ASSERT(ruby_current_vm_ptr == NULL || - ruby_current_execution_context_ptr == NULL || - rb_ec_thread_ptr(GET_EC()) == NULL || + ruby_current_execution_context_ptr == NULL || + rb_ec_thread_ptr(GET_EC()) == NULL || rb_ec_thread_ptr(GET_EC())->status == THREAD_KILLED || - rb_ec_vm_ptr(GET_EC()) == ruby_current_vm_ptr); + rb_ec_vm_ptr(GET_EC()) == ruby_current_vm_ptr); #endif return ruby_current_vm_ptr; @@ -1949,7 +1949,7 @@ enum { #define RUBY_VM_SET_TERMINATE_INTERRUPT(ec) ATOMIC_OR((ec)->interrupt_flag, TERMINATE_INTERRUPT_MASK) #define RUBY_VM_SET_VM_BARRIER_INTERRUPT(ec) ATOMIC_OR((ec)->interrupt_flag, VM_BARRIER_INTERRUPT_MASK) #define RUBY_VM_INTERRUPTED(ec) ((ec)->interrupt_flag & ~(ec)->interrupt_mask & \ - (PENDING_INTERRUPT_MASK|TRAP_INTERRUPT_MASK)) + (PENDING_INTERRUPT_MASK|TRAP_INTERRUPT_MASK)) static inline bool RUBY_VM_INTERRUPTED_ANY(rb_execution_context_t *ec) diff --git a/vm_dump.c b/vm_dump.c index 9c7227b3d7..607488388a 100644 --- a/vm_dump.c +++ b/vm_dump.c @@ -60,100 +60,100 @@ control_frame_dump(const rb_execution_context_t *ec, const rb_control_frame_t *c const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(cfp); if (ep < 0 || (size_t)ep > ec->vm_stack_size) { - ep = (ptrdiff_t)cfp->ep; - ep_in_heap = 'p'; + ep = (ptrdiff_t)cfp->ep; + ep_in_heap = 'p'; } switch (VM_FRAME_TYPE(cfp)) { case VM_FRAME_MAGIC_TOP: - magic = "TOP"; - break; + magic = "TOP"; + break; case VM_FRAME_MAGIC_METHOD: - magic = "METHOD"; - break; + magic = "METHOD"; + break; case VM_FRAME_MAGIC_CLASS: - magic = "CLASS"; - break; + magic = "CLASS"; + break; case VM_FRAME_MAGIC_BLOCK: - magic = "BLOCK"; - break; + magic = "BLOCK"; + break; case VM_FRAME_MAGIC_CFUNC: - magic = "CFUNC"; - break; + magic = "CFUNC"; + break; case VM_FRAME_MAGIC_IFUNC: - magic = "IFUNC"; - break; + magic = "IFUNC"; + break; case VM_FRAME_MAGIC_EVAL: - magic = "EVAL"; - break; + magic = "EVAL"; + break; case VM_FRAME_MAGIC_RESCUE: - magic = "RESCUE"; - break; + magic = "RESCUE"; + break; case 0: - magic = "------"; - break; + magic = "------"; + break; default: - magic = "(none)"; - break; + magic = "(none)"; + break; } if (0) { - tmp = rb_inspect(cfp->self); - selfstr = StringValueCStr(tmp); + tmp = rb_inspect(cfp->self); + selfstr = StringValueCStr(tmp); } else { - selfstr = ""; + selfstr = ""; } if (cfp->iseq != 0) { #define RUBY_VM_IFUNC_P(ptr) IMEMO_TYPE_P(ptr, imemo_ifunc) - if (RUBY_VM_IFUNC_P(cfp->iseq)) { - iseq_name = ""; - } + if (RUBY_VM_IFUNC_P(cfp->iseq)) { + iseq_name = ""; + } else if (SYMBOL_P((VALUE)cfp->iseq)) { - tmp = rb_sym2str((VALUE)cfp->iseq); - iseq_name = RSTRING_PTR(tmp); - snprintf(posbuf, MAX_POSBUF, ":%s", iseq_name); - line = -1; - } - else { + tmp = rb_sym2str((VALUE)cfp->iseq); + iseq_name = RSTRING_PTR(tmp); + snprintf(posbuf, MAX_POSBUF, ":%s", iseq_name); + line = -1; + } + else { iseq = cfp->iseq; pc = cfp->pc - ISEQ_BODY(iseq)->iseq_encoded; iseq_name = RSTRING_PTR(ISEQ_BODY(iseq)->location.label); - line = rb_vm_get_sourceline(cfp); - if (line) { - snprintf(posbuf, MAX_POSBUF, "%s:%d", RSTRING_PTR(rb_iseq_path(iseq)), line); - } - } + line = rb_vm_get_sourceline(cfp); + if (line) { + snprintf(posbuf, MAX_POSBUF, "%s:%d", RSTRING_PTR(rb_iseq_path(iseq)), line); + } + } } else if (me != NULL) { - iseq_name = rb_id2name(me->def->original_id); - snprintf(posbuf, MAX_POSBUF, ":%s", iseq_name); - line = -1; + iseq_name = rb_id2name(me->def->original_id); + snprintf(posbuf, MAX_POSBUF, ":%s", iseq_name); + line = -1; } fprintf(stderr, "c:%04"PRIdPTRDIFF" ", - ((rb_control_frame_t *)(ec->vm_stack + ec->vm_stack_size) - cfp)); + ((rb_control_frame_t *)(ec->vm_stack + ec->vm_stack_size) - cfp)); if (pc == -1) { - fprintf(stderr, "p:---- "); + fprintf(stderr, "p:---- "); } else { - fprintf(stderr, "p:%04"PRIdPTRDIFF" ", pc); + fprintf(stderr, "p:%04"PRIdPTRDIFF" ", pc); } fprintf(stderr, "s:%04"PRIdPTRDIFF" ", cfp->sp - ec->vm_stack); fprintf(stderr, ep_in_heap == ' ' ? "e:%06"PRIdPTRDIFF" " : "E:%06"PRIxPTRDIFF" ", ep % 10000); fprintf(stderr, "%-6s", magic); if (line) { - fprintf(stderr, " %s", posbuf); + fprintf(stderr, " %s", posbuf); } if (VM_FRAME_FINISHED_P(cfp)) { - fprintf(stderr, " [FINISH]"); + fprintf(stderr, " [FINISH]"); } if (0) { - fprintf(stderr, " \t"); - fprintf(stderr, "iseq: %-24s ", iseq_name); - fprintf(stderr, "self: %-24s ", selfstr); - fprintf(stderr, "%-1s ", biseq_name); + fprintf(stderr, " \t"); + fprintf(stderr, "iseq: %-24s ", iseq_name); + fprintf(stderr, "self: %-24s ", selfstr); + fprintf(stderr, "%-1s ", biseq_name); } fprintf(stderr, "\n"); @@ -201,25 +201,25 @@ rb_vmdebug_stack_dump_raw(const rb_execution_context_t *ec, const rb_control_fra fprintf(stderr, "-- stack frame ------------\n"); for (p = st = ec->vm_stack; p < sp; p++) { - fprintf(stderr, "%04ld (%p): %08"PRIxVALUE, (long)(p - st), p, *p); + fprintf(stderr, "%04ld (%p): %08"PRIxVALUE, (long)(p - st), p, *p); - t = (VALUE *)*p; - if (ec->vm_stack <= t && t < sp) { - fprintf(stderr, " (= %ld)", (long)((VALUE *)GC_GUARDED_PTR_REF((VALUE)t) - ec->vm_stack)); - } + t = (VALUE *)*p; + if (ec->vm_stack <= t && t < sp) { + fprintf(stderr, " (= %ld)", (long)((VALUE *)GC_GUARDED_PTR_REF((VALUE)t) - ec->vm_stack)); + } - if (p == ep) - fprintf(stderr, " <- ep"); + if (p == ep) + fprintf(stderr, " <- ep"); - fprintf(stderr, "\n"); + fprintf(stderr, "\n"); } #endif fprintf(stderr, "-- Control frame information " - "-----------------------------------------------\n"); + "-----------------------------------------------\n"); while ((void *)cfp < (void *)(ec->vm_stack + ec->vm_stack_size)) { - control_frame_dump(ec, cfp); - cfp++; + control_frame_dump(ec, cfp); + cfp++; } fprintf(stderr, "\n"); } @@ -238,14 +238,14 @@ rb_vmdebug_env_dump_raw(const rb_env_t *env, const VALUE *ep) fprintf(stderr, "-- env --------------------\n"); while (env) { - fprintf(stderr, "--\n"); - for (i = 0; i < env->env_size; i++) { - fprintf(stderr, "%04d: %08"PRIxVALUE" (%p)", i, env->env[i], (void *)&env->env[i]); - if (&env->env[i] == ep) fprintf(stderr, " <- ep"); - fprintf(stderr, "\n"); - } + fprintf(stderr, "--\n"); + for (i = 0; i < env->env_size; i++) { + fprintf(stderr, "%04d: %08"PRIxVALUE" (%p)", i, env->env[i], (void *)&env->env[i]); + if (&env->env[i] == ep) fprintf(stderr, " <- ep"); + fprintf(stderr, "\n"); + } - env = rb_vm_env_prev_env(env); + env = rb_vm_env_prev_env(env); } fprintf(stderr, "---------------------------\n"); } @@ -281,7 +281,7 @@ vm_base_ptr(const rb_control_frame_t *cfp) const VALUE *bp = prev_cfp->sp + ISEQ_BODY(cfp->iseq)->local_table_size + VM_ENV_DATA_SIZE; if (ISEQ_BODY(cfp->iseq)->type == ISEQ_TYPE_METHOD) { - bp += 1; + bp += 1; } return bp; } @@ -295,7 +295,7 @@ vm_stack_dump_each(const rb_execution_context_t *ec, const rb_control_frame_t *c const VALUE *ep = cfp->ep; if (VM_FRAME_RUBYFRAME_P(cfp)) { - const rb_iseq_t *iseq = cfp->iseq; + const rb_iseq_t *iseq = cfp->iseq; argc = ISEQ_BODY(iseq)->param.lead_num; local_table_size = ISEQ_BODY(iseq)->local_table_size; } @@ -303,56 +303,56 @@ vm_stack_dump_each(const rb_execution_context_t *ec, const rb_control_frame_t *c /* stack trace header */ if (VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_METHOD|| - VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_TOP || - VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_BLOCK || - VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_CLASS || - VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_CFUNC || - VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_IFUNC || - VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_EVAL || - VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_RESCUE) + VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_TOP || + VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_BLOCK || + VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_CLASS || + VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_CFUNC || + VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_IFUNC || + VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_EVAL || + VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_RESCUE) { - const VALUE *ptr = ep - local_table_size; + const VALUE *ptr = ep - local_table_size; - control_frame_dump(ec, cfp); + control_frame_dump(ec, cfp); - for (i = 0; i < argc; i++) { - rstr = rb_inspect(*ptr); - fprintf(stderr, " arg %2d: %8s (%p)\n", i, StringValueCStr(rstr), - (void *)ptr++); - } - for (; i < local_table_size - 1; i++) { - rstr = rb_inspect(*ptr); - fprintf(stderr, " local %2d: %8s (%p)\n", i, StringValueCStr(rstr), - (void *)ptr++); - } + for (i = 0; i < argc; i++) { + rstr = rb_inspect(*ptr); + fprintf(stderr, " arg %2d: %8s (%p)\n", i, StringValueCStr(rstr), + (void *)ptr++); + } + for (; i < local_table_size - 1; i++) { + rstr = rb_inspect(*ptr); + fprintf(stderr, " local %2d: %8s (%p)\n", i, StringValueCStr(rstr), + (void *)ptr++); + } - ptr = vm_base_ptr(cfp); - for (; ptr < sp; ptr++, i++) { - switch (TYPE(*ptr)) { - case T_UNDEF: - rstr = rb_str_new2("undef"); - break; - case T_IMEMO: - rstr = rb_str_new2("imemo"); /* TODO: can put mode detail information */ - break; - default: - rstr = rb_inspect(*ptr); - break; - } - fprintf(stderr, " stack %2d: %8s (%"PRIdPTRDIFF")\n", i, StringValueCStr(rstr), - (ptr - ec->vm_stack)); - } + ptr = vm_base_ptr(cfp); + for (; ptr < sp; ptr++, i++) { + switch (TYPE(*ptr)) { + case T_UNDEF: + rstr = rb_str_new2("undef"); + break; + case T_IMEMO: + rstr = rb_str_new2("imemo"); /* TODO: can put mode detail information */ + break; + default: + rstr = rb_inspect(*ptr); + break; + } + fprintf(stderr, " stack %2d: %8s (%"PRIdPTRDIFF")\n", i, StringValueCStr(rstr), + (ptr - ec->vm_stack)); + } } else if (VM_FRAME_FINISHED_P(cfp)) { - if (ec->vm_stack + ec->vm_stack_size > (VALUE *)(cfp + 1)) { - vm_stack_dump_each(ec, cfp + 1); - } - else { - /* SDR(); */ - } + if (ec->vm_stack + ec->vm_stack_size > (VALUE *)(cfp + 1)) { + vm_stack_dump_each(ec, cfp + 1); + } + else { + /* SDR(); */ + } } else { - rb_bug("unsupported frame type: %08lx", VM_FRAME_TYPE(cfp)); + rb_bug("unsupported frame type: %08lx", VM_FRAME_TYPE(cfp)); } } #endif @@ -370,12 +370,12 @@ rb_vmdebug_debug_print_register(const rb_execution_context_t *ec) } if (ep < 0 || (size_t)ep > ec->vm_stack_size) { - ep = -1; + ep = -1; } cfpi = ((rb_control_frame_t *)(ec->vm_stack + ec->vm_stack_size)) - cfp; fprintf(stderr, " [PC] %04"PRIdPTRDIFF", [SP] %04"PRIdPTRDIFF", [EP] %04"PRIdPTRDIFF", [CFP] %04"PRIdPTRDIFF"\n", - pc, (cfp->sp - ec->vm_stack), ep, cfpi); + pc, (cfp->sp - ec->vm_stack), ep, cfpi); } void @@ -391,20 +391,20 @@ rb_vmdebug_debug_print_pre(const rb_execution_context_t *ec, const rb_control_fr if (iseq != 0) { ptrdiff_t pc = _pc - ISEQ_BODY(iseq)->iseq_encoded; - int i; + int i; - for (i=0; i<(int)VM_CFP_CNT(ec, cfp); i++) { - printf(" "); - } - printf("| "); - if(0)printf("[%03ld] ", (long)(cfp->sp - ec->vm_stack)); + for (i=0; i<(int)VM_CFP_CNT(ec, cfp); i++) { + printf(" "); + } + printf("| "); + if(0)printf("[%03ld] ", (long)(cfp->sp - ec->vm_stack)); - /* printf("%3"PRIdPTRDIFF" ", VM_CFP_CNT(ec, cfp)); */ - if (pc >= 0) { - const VALUE *iseq_original = rb_iseq_original_iseq((rb_iseq_t *)iseq); + /* printf("%3"PRIdPTRDIFF" ", VM_CFP_CNT(ec, cfp)); */ + if (pc >= 0) { + const VALUE *iseq_original = rb_iseq_original_iseq((rb_iseq_t *)iseq); - rb_iseq_disasm_insn(0, iseq_original, (size_t)pc, iseq, 0); - } + rb_iseq_disasm_insn(0, iseq_original, (size_t)pc, iseq, 0); + } } #if VMDEBUG > 3 @@ -416,7 +416,7 @@ rb_vmdebug_debug_print_pre(const rb_execution_context_t *ec, const rb_control_fr void rb_vmdebug_debug_print_post(const rb_execution_context_t *ec, const rb_control_frame_t *cfp #if OPT_STACK_CACHING - , VALUE reg_a, VALUE reg_b + , VALUE reg_a, VALUE reg_b #endif ) { @@ -436,15 +436,15 @@ rb_vmdebug_debug_print_post(const rb_execution_context_t *ec, const rb_control_f #if OPT_STACK_CACHING { - VALUE rstr; - rstr = rb_inspect(reg_a); - fprintf(stderr, " sc reg A: %s\n", StringValueCStr(rstr)); - rstr = rb_inspect(reg_b); - fprintf(stderr, " sc reg B: %s\n", StringValueCStr(rstr)); + VALUE rstr; + rstr = rb_inspect(reg_a); + fprintf(stderr, " sc reg A: %s\n", StringValueCStr(rstr)); + rstr = rb_inspect(reg_b); + fprintf(stderr, " sc reg B: %s\n", StringValueCStr(rstr)); } #endif printf - ("--------------------------------------------------------------\n"); + ("--------------------------------------------------------------\n"); #endif } @@ -489,89 +489,89 @@ backtrace(void **trace, int size) unw_getcontext(&uc); unw_init_local(&cursor, &uc); while (unw_step(&cursor) > 0) { - unw_get_reg(&cursor, UNW_REG_IP, &ip); - trace[n++] = (void *)ip; - { - char buf[256]; - unw_get_proc_name(&cursor, buf, 256, &ip); - if (strncmp("_sigtramp", buf, sizeof("_sigtramp")) == 0) { - goto darwin_sigtramp; - } - } + unw_get_reg(&cursor, UNW_REG_IP, &ip); + trace[n++] = (void *)ip; + { + char buf[256]; + unw_get_proc_name(&cursor, buf, 256, &ip); + if (strncmp("_sigtramp", buf, sizeof("_sigtramp")) == 0) { + goto darwin_sigtramp; + } + } } return n; darwin_sigtramp: /* darwin's bundled libunwind doesn't support signal trampoline */ { #if defined(__x86_64__) - ucontext_t *uctx; - char vec[1]; - int r; - /* get previous frame information from %rbx at _sigtramp and set values to cursor - * https://www.opensource.apple.com/source/Libc/Libc-825.25/i386/sys/_sigtramp.s - * https://www.opensource.apple.com/source/libunwind/libunwind-35.1/src/unw_getcontext.s - */ - unw_get_reg(&cursor, UNW_X86_64_RBX, &ip); - uctx = (ucontext_t *)ip; - unw_set_reg(&cursor, UNW_X86_64_RAX, uctx->uc_mcontext->MCTX_SS_REG(rax)); - unw_set_reg(&cursor, UNW_X86_64_RBX, uctx->uc_mcontext->MCTX_SS_REG(rbx)); - unw_set_reg(&cursor, UNW_X86_64_RCX, uctx->uc_mcontext->MCTX_SS_REG(rcx)); - unw_set_reg(&cursor, UNW_X86_64_RDX, uctx->uc_mcontext->MCTX_SS_REG(rdx)); - unw_set_reg(&cursor, UNW_X86_64_RDI, uctx->uc_mcontext->MCTX_SS_REG(rdi)); - unw_set_reg(&cursor, UNW_X86_64_RSI, uctx->uc_mcontext->MCTX_SS_REG(rsi)); - unw_set_reg(&cursor, UNW_X86_64_RBP, uctx->uc_mcontext->MCTX_SS_REG(rbp)); - unw_set_reg(&cursor, UNW_X86_64_RSP, 8+(uctx->uc_mcontext->MCTX_SS_REG(rsp))); - unw_set_reg(&cursor, UNW_X86_64_R8, uctx->uc_mcontext->MCTX_SS_REG(r8)); - unw_set_reg(&cursor, UNW_X86_64_R9, uctx->uc_mcontext->MCTX_SS_REG(r9)); - unw_set_reg(&cursor, UNW_X86_64_R10, uctx->uc_mcontext->MCTX_SS_REG(r10)); - unw_set_reg(&cursor, UNW_X86_64_R11, uctx->uc_mcontext->MCTX_SS_REG(r11)); - unw_set_reg(&cursor, UNW_X86_64_R12, uctx->uc_mcontext->MCTX_SS_REG(r12)); - unw_set_reg(&cursor, UNW_X86_64_R13, uctx->uc_mcontext->MCTX_SS_REG(r13)); - unw_set_reg(&cursor, UNW_X86_64_R14, uctx->uc_mcontext->MCTX_SS_REG(r14)); - unw_set_reg(&cursor, UNW_X86_64_R15, uctx->uc_mcontext->MCTX_SS_REG(r15)); - ip = uctx->uc_mcontext->MCTX_SS_REG(rip); + ucontext_t *uctx; + char vec[1]; + int r; + /* get previous frame information from %rbx at _sigtramp and set values to cursor + * https://www.opensource.apple.com/source/Libc/Libc-825.25/i386/sys/_sigtramp.s + * https://www.opensource.apple.com/source/libunwind/libunwind-35.1/src/unw_getcontext.s + */ + unw_get_reg(&cursor, UNW_X86_64_RBX, &ip); + uctx = (ucontext_t *)ip; + unw_set_reg(&cursor, UNW_X86_64_RAX, uctx->uc_mcontext->MCTX_SS_REG(rax)); + unw_set_reg(&cursor, UNW_X86_64_RBX, uctx->uc_mcontext->MCTX_SS_REG(rbx)); + unw_set_reg(&cursor, UNW_X86_64_RCX, uctx->uc_mcontext->MCTX_SS_REG(rcx)); + unw_set_reg(&cursor, UNW_X86_64_RDX, uctx->uc_mcontext->MCTX_SS_REG(rdx)); + unw_set_reg(&cursor, UNW_X86_64_RDI, uctx->uc_mcontext->MCTX_SS_REG(rdi)); + unw_set_reg(&cursor, UNW_X86_64_RSI, uctx->uc_mcontext->MCTX_SS_REG(rsi)); + unw_set_reg(&cursor, UNW_X86_64_RBP, uctx->uc_mcontext->MCTX_SS_REG(rbp)); + unw_set_reg(&cursor, UNW_X86_64_RSP, 8+(uctx->uc_mcontext->MCTX_SS_REG(rsp))); + unw_set_reg(&cursor, UNW_X86_64_R8, uctx->uc_mcontext->MCTX_SS_REG(r8)); + unw_set_reg(&cursor, UNW_X86_64_R9, uctx->uc_mcontext->MCTX_SS_REG(r9)); + unw_set_reg(&cursor, UNW_X86_64_R10, uctx->uc_mcontext->MCTX_SS_REG(r10)); + unw_set_reg(&cursor, UNW_X86_64_R11, uctx->uc_mcontext->MCTX_SS_REG(r11)); + unw_set_reg(&cursor, UNW_X86_64_R12, uctx->uc_mcontext->MCTX_SS_REG(r12)); + unw_set_reg(&cursor, UNW_X86_64_R13, uctx->uc_mcontext->MCTX_SS_REG(r13)); + unw_set_reg(&cursor, UNW_X86_64_R14, uctx->uc_mcontext->MCTX_SS_REG(r14)); + unw_set_reg(&cursor, UNW_X86_64_R15, uctx->uc_mcontext->MCTX_SS_REG(r15)); + ip = uctx->uc_mcontext->MCTX_SS_REG(rip); - /* There are 4 cases for SEGV: - * (1) called invalid address - * (2) read or write invalid address - * (3) received signal - * - * Detail: - * (1) called invalid address - * In this case, saved ip is invalid address. - * It needs to just save the address for the information, - * skip the frame, and restore the frame calling the - * invalid address from %rsp. - * The problem is how to check whether the ip is valid or not. - * This code uses mincore(2) and assume the address's page is - * incore/referenced or not reflects the problem. - * Note that High Sierra's mincore(2) may return -128. - * (2) read or write invalid address - * saved ip is valid. just restart backtracing. - * (3) received signal in user space - * Same as (2). - * (4) received signal in kernel - * In this case saved ip points just after syscall, but registers are - * already overwritten by kernel. To fix register consistency, - * skip libc's kernel wrapper. - * To detect this case, just previous two bytes of ip is "\x0f\x05", - * syscall instruction of x86_64. - */ - r = mincore((const void *)ip, 1, vec); - if (r || vec[0] <= 0 || memcmp((const char *)ip-2, "\x0f\x05", 2) == 0) { - /* if segv is caused by invalid call or signal received in syscall */ - /* the frame is invalid; skip */ - trace[n++] = (void *)ip; - ip = *(unw_word_t*)uctx->uc_mcontext->MCTX_SS_REG(rsp); - } + /* There are 4 cases for SEGV: + * (1) called invalid address + * (2) read or write invalid address + * (3) received signal + * + * Detail: + * (1) called invalid address + * In this case, saved ip is invalid address. + * It needs to just save the address for the information, + * skip the frame, and restore the frame calling the + * invalid address from %rsp. + * The problem is how to check whether the ip is valid or not. + * This code uses mincore(2) and assume the address's page is + * incore/referenced or not reflects the problem. + * Note that High Sierra's mincore(2) may return -128. + * (2) read or write invalid address + * saved ip is valid. just restart backtracing. + * (3) received signal in user space + * Same as (2). + * (4) received signal in kernel + * In this case saved ip points just after syscall, but registers are + * already overwritten by kernel. To fix register consistency, + * skip libc's kernel wrapper. + * To detect this case, just previous two bytes of ip is "\x0f\x05", + * syscall instruction of x86_64. + */ + r = mincore((const void *)ip, 1, vec); + if (r || vec[0] <= 0 || memcmp((const char *)ip-2, "\x0f\x05", 2) == 0) { + /* if segv is caused by invalid call or signal received in syscall */ + /* the frame is invalid; skip */ + trace[n++] = (void *)ip; + ip = *(unw_word_t*)uctx->uc_mcontext->MCTX_SS_REG(rsp); + } #endif - trace[n++] = (void *)ip; - unw_set_reg(&cursor, UNW_REG_IP, ip); + trace[n++] = (void *)ip; + unw_set_reg(&cursor, UNW_REG_IP, ip); } while (unw_step(&cursor) > 0) { - unw_get_reg(&cursor, UNW_REG_IP, &ip); - trace[n++] = (void *)ip; + unw_get_reg(&cursor, UNW_REG_IP, &ip); + trace[n++] = (void *)ip; } return n; } @@ -679,75 +679,75 @@ dump_thread(void *arg) pSymGetLineFromAddr64 = (BOOL (WINAPI *)(HANDLE, DWORD64, DWORD *, IMAGEHLP_LINE64 *))GetProcAddress(dbghelp, "SymGetLineFromAddr64"); pOpenThread = (HANDLE (WINAPI *)(DWORD, BOOL, DWORD))GetProcAddress(GetModuleHandle("kernel32.dll"), "OpenThread"); if (pSymInitialize && pSymCleanup && pStackWalk64 && pSymGetModuleBase64 && - pSymFromAddr && pSymGetLineFromAddr64 && pOpenThread) { - SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_DEBUG | SYMOPT_LOAD_LINES); - ph = GetCurrentProcess(); - pSymInitialize(ph, NULL, TRUE); - th = pOpenThread(THREAD_SUSPEND_RESUME|THREAD_GET_CONTEXT, FALSE, tid); - if (th) { - if (SuspendThread(th) != (DWORD)-1) { - CONTEXT context; - memset(&context, 0, sizeof(context)); - context.ContextFlags = CONTEXT_FULL; - if (GetThreadContext(th, &context)) { - char libpath[MAX_PATH]; - char buf[sizeof(SYMBOL_INFO) + MAX_SYM_NAME]; - SYMBOL_INFO *info = (SYMBOL_INFO *)buf; - DWORD mac; - STACKFRAME64 frame; - memset(&frame, 0, sizeof(frame)); + pSymFromAddr && pSymGetLineFromAddr64 && pOpenThread) { + SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_DEBUG | SYMOPT_LOAD_LINES); + ph = GetCurrentProcess(); + pSymInitialize(ph, NULL, TRUE); + th = pOpenThread(THREAD_SUSPEND_RESUME|THREAD_GET_CONTEXT, FALSE, tid); + if (th) { + if (SuspendThread(th) != (DWORD)-1) { + CONTEXT context; + memset(&context, 0, sizeof(context)); + context.ContextFlags = CONTEXT_FULL; + if (GetThreadContext(th, &context)) { + char libpath[MAX_PATH]; + char buf[sizeof(SYMBOL_INFO) + MAX_SYM_NAME]; + SYMBOL_INFO *info = (SYMBOL_INFO *)buf; + DWORD mac; + STACKFRAME64 frame; + memset(&frame, 0, sizeof(frame)); #if defined(_M_AMD64) || defined(__x86_64__) - mac = IMAGE_FILE_MACHINE_AMD64; - frame.AddrPC.Mode = AddrModeFlat; - frame.AddrPC.Offset = context.Rip; - frame.AddrFrame.Mode = AddrModeFlat; - frame.AddrFrame.Offset = context.Rbp; - frame.AddrStack.Mode = AddrModeFlat; - frame.AddrStack.Offset = context.Rsp; + mac = IMAGE_FILE_MACHINE_AMD64; + frame.AddrPC.Mode = AddrModeFlat; + frame.AddrPC.Offset = context.Rip; + frame.AddrFrame.Mode = AddrModeFlat; + frame.AddrFrame.Offset = context.Rbp; + frame.AddrStack.Mode = AddrModeFlat; + frame.AddrStack.Offset = context.Rsp; #else /* i386 */ - mac = IMAGE_FILE_MACHINE_I386; - frame.AddrPC.Mode = AddrModeFlat; - frame.AddrPC.Offset = context.Eip; - frame.AddrFrame.Mode = AddrModeFlat; - frame.AddrFrame.Offset = context.Ebp; - frame.AddrStack.Mode = AddrModeFlat; - frame.AddrStack.Offset = context.Esp; + mac = IMAGE_FILE_MACHINE_I386; + frame.AddrPC.Mode = AddrModeFlat; + frame.AddrPC.Offset = context.Eip; + frame.AddrFrame.Mode = AddrModeFlat; + frame.AddrFrame.Offset = context.Ebp; + frame.AddrStack.Mode = AddrModeFlat; + frame.AddrStack.Offset = context.Esp; #endif - while (pStackWalk64(mac, ph, th, &frame, &context, NULL, - NULL, NULL, NULL)) { - DWORD64 addr = frame.AddrPC.Offset; - IMAGEHLP_LINE64 line; - DWORD64 displacement; - DWORD tmp; + while (pStackWalk64(mac, ph, th, &frame, &context, NULL, + NULL, NULL, NULL)) { + DWORD64 addr = frame.AddrPC.Offset; + IMAGEHLP_LINE64 line; + DWORD64 displacement; + DWORD tmp; - if (addr == frame.AddrReturn.Offset || addr == 0 || - frame.AddrReturn.Offset == 0) - break; + if (addr == frame.AddrReturn.Offset || addr == 0 || + frame.AddrReturn.Offset == 0) + break; - memset(buf, 0, sizeof(buf)); - info->SizeOfStruct = sizeof(SYMBOL_INFO); - info->MaxNameLen = MAX_SYM_NAME; - if (pSymFromAddr(ph, addr, &displacement, info)) { - if (GetModuleFileName((HANDLE)(uintptr_t)pSymGetModuleBase64(ph, addr), libpath, sizeof(libpath))) - fprintf(stderr, "%s", libpath); - fprintf(stderr, "(%s+0x%"PRI_64_PREFIX"x)", - info->Name, displacement); - } - fprintf(stderr, " [0x%p]", (void *)(VALUE)addr); - memset(&line, 0, sizeof(line)); - line.SizeOfStruct = sizeof(line); - if (pSymGetLineFromAddr64(ph, addr, &tmp, &line)) - fprintf(stderr, " %s:%lu", line.FileName, line.LineNumber); - fprintf(stderr, "\n"); - } - } + memset(buf, 0, sizeof(buf)); + info->SizeOfStruct = sizeof(SYMBOL_INFO); + info->MaxNameLen = MAX_SYM_NAME; + if (pSymFromAddr(ph, addr, &displacement, info)) { + if (GetModuleFileName((HANDLE)(uintptr_t)pSymGetModuleBase64(ph, addr), libpath, sizeof(libpath))) + fprintf(stderr, "%s", libpath); + fprintf(stderr, "(%s+0x%"PRI_64_PREFIX"x)", + info->Name, displacement); + } + fprintf(stderr, " [0x%p]", (void *)(VALUE)addr); + memset(&line, 0, sizeof(line)); + line.SizeOfStruct = sizeof(line); + if (pSymGetLineFromAddr64(ph, addr, &tmp, &line)) + fprintf(stderr, " %s:%lu", line.FileName, line.LineNumber); + fprintf(stderr, "\n"); + } + } - ResumeThread(th); - } - CloseHandle(th); - } - pSymCleanup(ph); + ResumeThread(th); + } + CloseHandle(th); + } + pSymCleanup(ph); } FreeLibrary(dbghelp); } @@ -765,18 +765,18 @@ rb_print_backtrace(void) #else char **syms = backtrace_symbols(trace, n); if (syms) { - int i; - for (i=0; i max_col) { - fputs("\n", stderr); - col_count = 0; + fputs("\n", stderr); + col_count = 0; } col_count += ret; fputs(buf, stderr); @@ -832,173 +832,173 @@ rb_dump_machine_register(const ucontext_t *ctx) if (!ctx) return; fprintf(stderr, "-- Machine register context " - "------------------------------------------------\n"); + "------------------------------------------------\n"); # if defined __linux__ { - const mcontext_t *const mctx = &ctx->uc_mcontext; + const mcontext_t *const mctx = &ctx->uc_mcontext; # if defined __x86_64__ - dump_machine_register(RIP); - dump_machine_register(RBP); - dump_machine_register(RSP); - dump_machine_register(RAX); - dump_machine_register(RBX); - dump_machine_register(RCX); - dump_machine_register(RDX); - dump_machine_register(RDI); - dump_machine_register(RSI); - dump_machine_register(R8); - dump_machine_register(R9); - dump_machine_register(R10); - dump_machine_register(R11); - dump_machine_register(R12); - dump_machine_register(R13); - dump_machine_register(R14); - dump_machine_register(R15); - dump_machine_register(EFL); + dump_machine_register(RIP); + dump_machine_register(RBP); + dump_machine_register(RSP); + dump_machine_register(RAX); + dump_machine_register(RBX); + dump_machine_register(RCX); + dump_machine_register(RDX); + dump_machine_register(RDI); + dump_machine_register(RSI); + dump_machine_register(R8); + dump_machine_register(R9); + dump_machine_register(R10); + dump_machine_register(R11); + dump_machine_register(R12); + dump_machine_register(R13); + dump_machine_register(R14); + dump_machine_register(R15); + dump_machine_register(EFL); # elif defined __i386__ - dump_machine_register(GS); - dump_machine_register(FS); - dump_machine_register(ES); - dump_machine_register(DS); - dump_machine_register(EDI); - dump_machine_register(ESI); - dump_machine_register(EBP); - dump_machine_register(ESP); - dump_machine_register(EBX); - dump_machine_register(EDX); - dump_machine_register(ECX); - dump_machine_register(EAX); - dump_machine_register(TRAPNO); - dump_machine_register(ERR); - dump_machine_register(EIP); - dump_machine_register(CS); - dump_machine_register(EFL); - dump_machine_register(UESP); - dump_machine_register(SS); + dump_machine_register(GS); + dump_machine_register(FS); + dump_machine_register(ES); + dump_machine_register(DS); + dump_machine_register(EDI); + dump_machine_register(ESI); + dump_machine_register(EBP); + dump_machine_register(ESP); + dump_machine_register(EBX); + dump_machine_register(EDX); + dump_machine_register(ECX); + dump_machine_register(EAX); + dump_machine_register(TRAPNO); + dump_machine_register(ERR); + dump_machine_register(EIP); + dump_machine_register(CS); + dump_machine_register(EFL); + dump_machine_register(UESP); + dump_machine_register(SS); # elif defined __aarch64__ - dump_machine_register(mctx->regs[0], "x0"); - dump_machine_register(mctx->regs[1], "x1"); - dump_machine_register(mctx->regs[2], "x2"); - dump_machine_register(mctx->regs[3], "x3"); - dump_machine_register(mctx->regs[4], "x4"); - dump_machine_register(mctx->regs[5], "x5"); - dump_machine_register(mctx->regs[6], "x6"); - dump_machine_register(mctx->regs[7], "x7"); - dump_machine_register(mctx->regs[18], "x18"); - dump_machine_register(mctx->regs[19], "x19"); - dump_machine_register(mctx->regs[20], "x20"); - dump_machine_register(mctx->regs[21], "x21"); - dump_machine_register(mctx->regs[22], "x22"); - dump_machine_register(mctx->regs[23], "x23"); - dump_machine_register(mctx->regs[24], "x24"); - dump_machine_register(mctx->regs[25], "x25"); - dump_machine_register(mctx->regs[26], "x26"); - dump_machine_register(mctx->regs[27], "x27"); - dump_machine_register(mctx->regs[28], "x28"); - dump_machine_register(mctx->regs[29], "x29"); - dump_machine_register(mctx->sp, "sp"); - dump_machine_register(mctx->fault_address, "fault_address"); + dump_machine_register(mctx->regs[0], "x0"); + dump_machine_register(mctx->regs[1], "x1"); + dump_machine_register(mctx->regs[2], "x2"); + dump_machine_register(mctx->regs[3], "x3"); + dump_machine_register(mctx->regs[4], "x4"); + dump_machine_register(mctx->regs[5], "x5"); + dump_machine_register(mctx->regs[6], "x6"); + dump_machine_register(mctx->regs[7], "x7"); + dump_machine_register(mctx->regs[18], "x18"); + dump_machine_register(mctx->regs[19], "x19"); + dump_machine_register(mctx->regs[20], "x20"); + dump_machine_register(mctx->regs[21], "x21"); + dump_machine_register(mctx->regs[22], "x22"); + dump_machine_register(mctx->regs[23], "x23"); + dump_machine_register(mctx->regs[24], "x24"); + dump_machine_register(mctx->regs[25], "x25"); + dump_machine_register(mctx->regs[26], "x26"); + dump_machine_register(mctx->regs[27], "x27"); + dump_machine_register(mctx->regs[28], "x28"); + dump_machine_register(mctx->regs[29], "x29"); + dump_machine_register(mctx->sp, "sp"); + dump_machine_register(mctx->fault_address, "fault_address"); # elif defined __arm__ - dump_machine_register(mctx->arm_r0, "r0"); - dump_machine_register(mctx->arm_r1, "r1"); - dump_machine_register(mctx->arm_r2, "r2"); - dump_machine_register(mctx->arm_r3, "r3"); - dump_machine_register(mctx->arm_r4, "r4"); - dump_machine_register(mctx->arm_r5, "r5"); - dump_machine_register(mctx->arm_r6, "r6"); - dump_machine_register(mctx->arm_r7, "r7"); - dump_machine_register(mctx->arm_r8, "r8"); - dump_machine_register(mctx->arm_r9, "r9"); - dump_machine_register(mctx->arm_r10, "r10"); - dump_machine_register(mctx->arm_sp, "sp"); - dump_machine_register(mctx->fault_address, "fault_address"); + dump_machine_register(mctx->arm_r0, "r0"); + dump_machine_register(mctx->arm_r1, "r1"); + dump_machine_register(mctx->arm_r2, "r2"); + dump_machine_register(mctx->arm_r3, "r3"); + dump_machine_register(mctx->arm_r4, "r4"); + dump_machine_register(mctx->arm_r5, "r5"); + dump_machine_register(mctx->arm_r6, "r6"); + dump_machine_register(mctx->arm_r7, "r7"); + dump_machine_register(mctx->arm_r8, "r8"); + dump_machine_register(mctx->arm_r9, "r9"); + dump_machine_register(mctx->arm_r10, "r10"); + dump_machine_register(mctx->arm_sp, "sp"); + dump_machine_register(mctx->fault_address, "fault_address"); # elif defined __riscv - dump_machine_register(mctx->__gregs[REG_SP], "sp"); - dump_machine_register(mctx->__gregs[REG_S0], "s0"); - dump_machine_register(mctx->__gregs[REG_S1], "s1"); - dump_machine_register(mctx->__gregs[REG_A0], "a0"); - dump_machine_register(mctx->__gregs[REG_A0+1], "a1"); - dump_machine_register(mctx->__gregs[REG_A0+2], "a2"); - dump_machine_register(mctx->__gregs[REG_A0+3], "a3"); - dump_machine_register(mctx->__gregs[REG_A0+4], "a4"); - dump_machine_register(mctx->__gregs[REG_A0+5], "a5"); - dump_machine_register(mctx->__gregs[REG_A0+6], "a6"); - dump_machine_register(mctx->__gregs[REG_A0+7], "a7"); - dump_machine_register(mctx->__gregs[REG_S2], "s2"); - dump_machine_register(mctx->__gregs[REG_S2+1], "s3"); - dump_machine_register(mctx->__gregs[REG_S2+2], "s4"); - dump_machine_register(mctx->__gregs[REG_S2+3], "s5"); - dump_machine_register(mctx->__gregs[REG_S2+4], "s6"); - dump_machine_register(mctx->__gregs[REG_S2+5], "s7"); - dump_machine_register(mctx->__gregs[REG_S2+6], "s8"); - dump_machine_register(mctx->__gregs[REG_S2+7], "s9"); - dump_machine_register(mctx->__gregs[REG_S2+8], "s10"); - dump_machine_register(mctx->__gregs[REG_S2+9], "s11"); + dump_machine_register(mctx->__gregs[REG_SP], "sp"); + dump_machine_register(mctx->__gregs[REG_S0], "s0"); + dump_machine_register(mctx->__gregs[REG_S1], "s1"); + dump_machine_register(mctx->__gregs[REG_A0], "a0"); + dump_machine_register(mctx->__gregs[REG_A0+1], "a1"); + dump_machine_register(mctx->__gregs[REG_A0+2], "a2"); + dump_machine_register(mctx->__gregs[REG_A0+3], "a3"); + dump_machine_register(mctx->__gregs[REG_A0+4], "a4"); + dump_machine_register(mctx->__gregs[REG_A0+5], "a5"); + dump_machine_register(mctx->__gregs[REG_A0+6], "a6"); + dump_machine_register(mctx->__gregs[REG_A0+7], "a7"); + dump_machine_register(mctx->__gregs[REG_S2], "s2"); + dump_machine_register(mctx->__gregs[REG_S2+1], "s3"); + dump_machine_register(mctx->__gregs[REG_S2+2], "s4"); + dump_machine_register(mctx->__gregs[REG_S2+3], "s5"); + dump_machine_register(mctx->__gregs[REG_S2+4], "s6"); + dump_machine_register(mctx->__gregs[REG_S2+5], "s7"); + dump_machine_register(mctx->__gregs[REG_S2+6], "s8"); + dump_machine_register(mctx->__gregs[REG_S2+7], "s9"); + dump_machine_register(mctx->__gregs[REG_S2+8], "s10"); + dump_machine_register(mctx->__gregs[REG_S2+9], "s11"); # endif } # elif defined __APPLE__ { - const mcontext_t mctx = ctx->uc_mcontext; + const mcontext_t mctx = ctx->uc_mcontext; # if defined __x86_64__ - dump_machine_register(rax); - dump_machine_register(rbx); - dump_machine_register(rcx); - dump_machine_register(rdx); - dump_machine_register(rdi); - dump_machine_register(rsi); - dump_machine_register(rbp); - dump_machine_register(rsp); - dump_machine_register(r8); - dump_machine_register(r9); - dump_machine_register(r10); - dump_machine_register(r11); - dump_machine_register(r12); - dump_machine_register(r13); - dump_machine_register(r14); - dump_machine_register(r15); - dump_machine_register(rip); - dump_machine_register(rflags); + dump_machine_register(rax); + dump_machine_register(rbx); + dump_machine_register(rcx); + dump_machine_register(rdx); + dump_machine_register(rdi); + dump_machine_register(rsi); + dump_machine_register(rbp); + dump_machine_register(rsp); + dump_machine_register(r8); + dump_machine_register(r9); + dump_machine_register(r10); + dump_machine_register(r11); + dump_machine_register(r12); + dump_machine_register(r13); + dump_machine_register(r14); + dump_machine_register(r15); + dump_machine_register(rip); + dump_machine_register(rflags); # elif defined __i386__ - dump_machine_register(eax); - dump_machine_register(ebx); - dump_machine_register(ecx); - dump_machine_register(edx); - dump_machine_register(edi); - dump_machine_register(esi); - dump_machine_register(ebp); - dump_machine_register(esp); - dump_machine_register(ss); - dump_machine_register(eflags); - dump_machine_register(eip); - dump_machine_register(cs); - dump_machine_register(ds); - dump_machine_register(es); - dump_machine_register(fs); - dump_machine_register(gs); + dump_machine_register(eax); + dump_machine_register(ebx); + dump_machine_register(ecx); + dump_machine_register(edx); + dump_machine_register(edi); + dump_machine_register(esi); + dump_machine_register(ebp); + dump_machine_register(esp); + dump_machine_register(ss); + dump_machine_register(eflags); + dump_machine_register(eip); + dump_machine_register(cs); + dump_machine_register(ds); + dump_machine_register(es); + dump_machine_register(fs); + dump_machine_register(gs); # elif defined __aarch64__ - dump_machine_register(x[0], "x0"); - dump_machine_register(x[1], "x1"); - dump_machine_register(x[2], "x2"); - dump_machine_register(x[3], "x3"); - dump_machine_register(x[4], "x4"); - dump_machine_register(x[5], "x5"); - dump_machine_register(x[6], "x6"); - dump_machine_register(x[7], "x7"); - dump_machine_register(x[18], "x18"); - dump_machine_register(x[19], "x19"); - dump_machine_register(x[20], "x20"); - dump_machine_register(x[21], "x21"); - dump_machine_register(x[22], "x22"); - dump_machine_register(x[23], "x23"); - dump_machine_register(x[24], "x24"); - dump_machine_register(x[25], "x25"); - dump_machine_register(x[26], "x26"); - dump_machine_register(x[27], "x27"); - dump_machine_register(x[28], "x28"); - dump_machine_register(lr, "lr"); - dump_machine_register(fp, "fp"); - dump_machine_register(sp, "sp"); + dump_machine_register(x[0], "x0"); + dump_machine_register(x[1], "x1"); + dump_machine_register(x[2], "x2"); + dump_machine_register(x[3], "x3"); + dump_machine_register(x[4], "x4"); + dump_machine_register(x[5], "x5"); + dump_machine_register(x[6], "x6"); + dump_machine_register(x[7], "x7"); + dump_machine_register(x[18], "x18"); + dump_machine_register(x[19], "x19"); + dump_machine_register(x[20], "x20"); + dump_machine_register(x[21], "x21"); + dump_machine_register(x[22], "x22"); + dump_machine_register(x[23], "x23"); + dump_machine_register(x[24], "x24"); + dump_machine_register(x[25], "x25"); + dump_machine_register(x[26], "x26"); + dump_machine_register(x[27], "x27"); + dump_machine_register(x[28], "x28"); + dump_machine_register(lr, "lr"); + dump_machine_register(fp, "fp"); + dump_machine_register(sp, "sp"); # endif } # endif @@ -1044,16 +1044,16 @@ rb_vm_bugreport(const void *ctx) const rb_execution_context_t *ec = rb_current_execution_context(false); if (vm && ec) { - SDR(); - rb_backtrace_print_as_bugreport(); - fputs("\n", stderr); + SDR(); + rb_backtrace_print_as_bugreport(); + fputs("\n", stderr); } rb_dump_machine_register(ctx); #if USE_BACKTRACE || defined(_WIN32) fprintf(stderr, "-- C level backtrace information " - "-------------------------------------------\n"); + "-------------------------------------------\n"); rb_print_backtrace(); @@ -1061,22 +1061,22 @@ rb_vm_bugreport(const void *ctx) #endif /* USE_BACKTRACE */ if (other_runtime_info || vm) { - fprintf(stderr, "-- Other runtime information " - "-----------------------------------------------\n\n"); + fprintf(stderr, "-- Other runtime information " + "-----------------------------------------------\n\n"); } if (vm && !rb_during_gc()) { - int i; - VALUE name; - long len; - const int max_name_length = 1024; + int i; + VALUE name; + long len; + const int max_name_length = 1024; # define LIMITED_NAME_LENGTH(s) \ - (((len = RSTRING_LEN(s)) > max_name_length) ? max_name_length : (int)len) + (((len = RSTRING_LEN(s)) > max_name_length) ? max_name_length : (int)len) - name = vm->progname; + name = vm->progname; if (name) { - fprintf(stderr, "* Loaded script: %.*s\n", - LIMITED_NAME_LENGTH(name), RSTRING_PTR(name)); - fprintf(stderr, "\n"); + fprintf(stderr, "* Loaded script: %.*s\n", + LIMITED_NAME_LENGTH(name), RSTRING_PTR(name)); + fprintf(stderr, "\n"); } if (vm->loaded_features) { fprintf(stderr, "* Loaded features:\n\n"); @@ -1110,47 +1110,47 @@ rb_vm_bugreport(const void *ctx) } } } - fprintf(stderr, "\n"); + fprintf(stderr, "\n"); } { #ifdef PROC_MAPS_NAME - { - FILE *fp = fopen(PROC_MAPS_NAME, "r"); - if (fp) { - fprintf(stderr, "* Process memory map:\n\n"); + { + FILE *fp = fopen(PROC_MAPS_NAME, "r"); + if (fp) { + fprintf(stderr, "* Process memory map:\n\n"); - while (!feof(fp)) { - char buff[0x100]; - size_t rn = fread(buff, 1, 0x100, fp); - if (fwrite(buff, 1, rn, stderr) != rn) - break; - } + while (!feof(fp)) { + char buff[0x100]; + size_t rn = fread(buff, 1, 0x100, fp); + if (fwrite(buff, 1, rn, stderr) != rn) + break; + } - fclose(fp); - fprintf(stderr, "\n\n"); - } - } + fclose(fp); + fprintf(stderr, "\n\n"); + } + } #endif /* __linux__ */ #ifdef HAVE_LIBPROCSTAT # define MIB_KERN_PROC_PID_LEN 4 - int mib[MIB_KERN_PROC_PID_LEN]; - struct kinfo_proc kp; - size_t len = sizeof(struct kinfo_proc); - mib[0] = CTL_KERN; - mib[1] = KERN_PROC; - mib[2] = KERN_PROC_PID; - mib[3] = getpid(); - if (sysctl(mib, MIB_KERN_PROC_PID_LEN, &kp, &len, NULL, 0) == -1) { - perror("sysctl"); - } - else { - struct procstat *prstat = procstat_open_sysctl(); - fprintf(stderr, "* Process memory map:\n\n"); - procstat_vm(prstat, &kp); - procstat_close(prstat); - fprintf(stderr, "\n"); - } + int mib[MIB_KERN_PROC_PID_LEN]; + struct kinfo_proc kp; + size_t len = sizeof(struct kinfo_proc); + mib[0] = CTL_KERN; + mib[1] = KERN_PROC; + mib[2] = KERN_PROC_PID; + mib[3] = getpid(); + if (sysctl(mib, MIB_KERN_PROC_PID_LEN, &kp, &len, NULL, 0) == -1) { + perror("sysctl"); + } + else { + struct procstat *prstat = procstat_open_sysctl(); + fprintf(stderr, "* Process memory map:\n\n"); + procstat_vm(prstat, &kp); + procstat_close(prstat); + fprintf(stderr, "\n"); + } #endif /* __FreeBSD__ */ #ifdef __APPLE__ vm_address_t addr = 0; @@ -1200,10 +1200,10 @@ rb_vmdebug_stack_dump_all_threads(void) // TODO: now it only shows current ractor ccan_list_for_each(&r->threads.set, th, lt_node) { #ifdef NON_SCALAR_THREAD_ID - fprintf(stderr, "th: %p, native_id: N/A\n", th); + fprintf(stderr, "th: %p, native_id: N/A\n", th); #else fprintf(stderr, "th: %p, native_id: %p\n", (void *)th, (void *)(uintptr_t)th->nt->thread_id); #endif - rb_vmdebug_stack_dump_raw(th->ec, th->ec->cfp); + rb_vmdebug_stack_dump_raw(th->ec, th->ec->cfp); } } diff --git a/vm_eval.c b/vm_eval.c index 5313267b44..e490e4e32d 100644 --- a/vm_eval.c +++ b/vm_eval.c @@ -138,18 +138,18 @@ vm_call0_cfunc_with_frame(rb_execution_context_t* ec, struct rb_calling_info *ca RUBY_DTRACE_CMETHOD_ENTRY_HOOK(ec, me->owner, me->def->original_id); EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_CALL, recv, me->def->original_id, mid, me->owner, Qnil); { - rb_control_frame_t *reg_cfp = ec->cfp; + rb_control_frame_t *reg_cfp = ec->cfp; vm_push_frame(ec, 0, frame_flags, recv, - block_handler, (VALUE)me, - 0, reg_cfp->sp, 0, 0); + block_handler, (VALUE)me, + 0, reg_cfp->sp, 0, 0); - if (len >= 0) rb_check_arity(argc, len, len); + if (len >= 0) rb_check_arity(argc, len, len); val = (*cfunc->invoker)(recv, argc, argv, cfunc->func); - CHECK_CFP_CONSISTENCY("vm_call0_cfunc_with_frame"); - rb_vm_pop_frame(ec); + CHECK_CFP_CONSISTENCY("vm_call0_cfunc_with_frame"); + rb_vm_pop_frame(ec); } EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_RETURN, recv, me->def->original_id, mid, me->owner, val); RUBY_DTRACE_CMETHOD_RETURN_HOOK(ec, me->owner, me->def->original_id); @@ -188,48 +188,48 @@ vm_call0_body(rb_execution_context_t *ec, struct rb_calling_info *calling, const switch (vm_cc_cme(cc)->def->type) { case VM_METHOD_TYPE_ISEQ: - { - rb_control_frame_t *reg_cfp = ec->cfp; - int i; + { + rb_control_frame_t *reg_cfp = ec->cfp; + int i; - CHECK_VM_STACK_OVERFLOW(reg_cfp, calling->argc + 1); + CHECK_VM_STACK_OVERFLOW(reg_cfp, calling->argc + 1); vm_check_canary(ec, reg_cfp->sp); - *reg_cfp->sp++ = calling->recv; - for (i = 0; i < calling->argc; i++) { - *reg_cfp->sp++ = argv[i]; - } + *reg_cfp->sp++ = calling->recv; + for (i = 0; i < calling->argc; i++) { + *reg_cfp->sp++ = argv[i]; + } vm_call_iseq_setup(ec, reg_cfp, calling); - VM_ENV_FLAGS_SET(ec->cfp->ep, VM_FRAME_FLAG_FINISH); + VM_ENV_FLAGS_SET(ec->cfp->ep, VM_FRAME_FLAG_FINISH); return vm_exec(ec, true); /* CHECK_INTS in this function */ - } + } case VM_METHOD_TYPE_NOTIMPLEMENTED: case VM_METHOD_TYPE_CFUNC: ret = vm_call0_cfunc(ec, calling, argv); - goto success; + goto success; case VM_METHOD_TYPE_ATTRSET: vm_call_check_arity(calling, 1, argv); VM_CALL_METHOD_ATTR(ret, rb_ivar_set(calling->recv, vm_cc_cme(cc)->def->body.attr.id, argv[0]), (void)0); - goto success; + goto success; case VM_METHOD_TYPE_IVAR: vm_call_check_arity(calling, 0, argv); VM_CALL_METHOD_ATTR(ret, rb_attr_get(calling->recv, vm_cc_cme(cc)->def->body.attr.id), (void)0); - goto success; + goto success; case VM_METHOD_TYPE_BMETHOD: ret = vm_call_bmethod_body(ec, calling, argv); - goto success; + goto success; case VM_METHOD_TYPE_ZSUPER: { VALUE klass = RCLASS_ORIGIN(vm_cc_cme(cc)->defined_class); return vm_call0_super(ec, calling, argv, klass, MISSING_SUPER); } case VM_METHOD_TYPE_REFINED: - { + { const rb_callable_method_entry_t *cme = vm_cc_cme(cc); if (cme->def->body.refined.orig_me) { @@ -239,7 +239,7 @@ vm_call0_body(rb_execution_context_t *ec, struct rb_calling_info *calling, const VALUE klass = cme->defined_class; return vm_call0_super(ec, calling, argv, klass, 0); - } + } case VM_METHOD_TYPE_ALIAS: { const rb_callable_method_entry_t *cme = vm_cc_cme(cc); @@ -256,23 +256,23 @@ vm_call0_body(rb_execution_context_t *ec, struct rb_calling_info *calling, const } } case VM_METHOD_TYPE_MISSING: - { + { vm_passed_block_handler_set(ec, calling->block_handler); - return method_missing(ec, calling->recv, vm_ci_mid(ci), calling->argc, + return method_missing(ec, calling->recv, vm_ci_mid(ci), calling->argc, argv, MISSING_NOENTRY, calling->kw_splat); - } + } case VM_METHOD_TYPE_OPTIMIZED: - switch (vm_cc_cme(cc)->def->body.optimized.type) { - case OPTIMIZED_METHOD_TYPE_SEND: + switch (vm_cc_cme(cc)->def->body.optimized.type) { + case OPTIMIZED_METHOD_TYPE_SEND: ret = send_internal(calling->argc, argv, calling->recv, calling->kw_splat ? CALL_FCALL_KW : CALL_FCALL); - goto success; - case OPTIMIZED_METHOD_TYPE_CALL: - { - rb_proc_t *proc; - GetProcPtr(calling->recv, proc); - ret = rb_vm_invoke_proc(ec, proc, calling->argc, argv, calling->kw_splat, calling->block_handler); - goto success; - } + goto success; + case OPTIMIZED_METHOD_TYPE_CALL: + { + rb_proc_t *proc; + GetProcPtr(calling->recv, proc); + ret = rb_vm_invoke_proc(ec, proc, calling->argc, argv, calling->kw_splat, calling->block_handler); + goto success; + } case OPTIMIZED_METHOD_TYPE_STRUCT_AREF: vm_call_check_arity(calling, 0, argv); ret = vm_call_opt_struct_aref0(ec, calling); @@ -281,12 +281,12 @@ vm_call0_body(rb_execution_context_t *ec, struct rb_calling_info *calling, const vm_call_check_arity(calling, 1, argv); ret = vm_call_opt_struct_aset0(ec, calling, argv[0]); goto success; - default: - rb_bug("vm_call0: unsupported optimized method type (%d)", vm_cc_cme(cc)->def->body.optimized.type); - } - break; + default: + rb_bug("vm_call0: unsupported optimized method type (%d)", vm_cc_cme(cc)->def->body.optimized.type); + } + break; case VM_METHOD_TYPE_UNDEF: - break; + break; } rb_bug("vm_call0: unsupported method type (%d)", vm_cc_cme(cc)->def->type); return Qundef; @@ -312,7 +312,7 @@ vm_call_super(rb_execution_context_t *ec, int argc, const VALUE *argv, int kw_sp const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(cfp); if (VM_FRAME_RUBYFRAME_P(cfp)) { - rb_bug("vm_call_super: should not be reached"); + rb_bug("vm_call_super: should not be reached"); } klass = RCLASS_ORIGIN(me->defined_class); @@ -346,7 +346,7 @@ rb_current_receiver(void) const rb_execution_context_t *ec = GET_EC(); rb_control_frame_t *cfp; if (!ec || !(cfp = ec->cfp)) { - rb_raise(rb_eRuntimeError, "no self, no life"); + rb_raise(rb_eRuntimeError, "no self, no life"); } return cfp->self; } @@ -357,9 +357,9 @@ static inline void stack_check(rb_execution_context_t *ec) { if (!rb_ec_raised_p(ec, RAISED_STACKOVERFLOW) && - rb_ec_stack_check(ec)) { - rb_ec_raised_set(ec, RAISED_STACKOVERFLOW); - rb_ec_stack_overflow(ec, FALSE); + rb_ec_stack_check(ec)) { + rb_ec_raised_set(ec, RAISED_STACKOVERFLOW); + rb_ec_stack_overflow(ec, FALSE); } } @@ -500,7 +500,7 @@ gccct_method_search(rb_execution_context_t *ec, VALUE recv, ID mid, int argc) */ static inline VALUE rb_call0(rb_execution_context_t *ec, - VALUE recv, ID mid, int argc, const VALUE *argv, + VALUE recv, ID mid, int argc, const VALUE *argv, call_type call_scope, VALUE self) { enum method_missing_reason call_status; @@ -568,7 +568,7 @@ check_funcall_exec(VALUE v) { struct rescue_funcall_args *args = (void *)v; return call_method_entry(args->ec, args->defined_class, - args->recv, idMethodMissing, + args->recv, idMethodMissing, args->cme, args->argc, args->argv, args->kw_splat); } @@ -578,21 +578,21 @@ check_funcall_failed(VALUE v, VALUE e) struct rescue_funcall_args *args = (void *)v; int ret = args->respond; if (!ret) { - switch (method_boundp(args->defined_class, args->mid, + switch (method_boundp(args->defined_class, args->mid, BOUND_PRIVATE|BOUND_RESPONDS)) { - case 2: - ret = TRUE; - break; - case 0: - ret = args->respond_to_missing; - break; - default: - ret = FALSE; - break; - } + case 2: + ret = TRUE; + break; + case 0: + ret = args->respond_to_missing; + break; + default: + ret = FALSE; + break; + } } if (ret) { - rb_exc_raise(e); + rb_exc_raise(e); } return Qundef; } @@ -617,7 +617,7 @@ check_funcall_missing(rb_execution_context_t *ec, VALUE klass, VALUE recv, ID mi VALUE ret = Qundef; ret = basic_obj_respond_to_missing(ec, klass, recv, - ID2SYM(mid), Qtrue); + ID2SYM(mid), Qtrue); if (!RTEST(ret)) return def; args.respond = respond > 0; args.respond_to_missing = (ret != Qundef); @@ -625,9 +625,9 @@ check_funcall_missing(rb_execution_context_t *ec, VALUE klass, VALUE recv, ID mi cme = callable_method_entry(klass, idMethodMissing, &args.defined_class); if (cme && !METHOD_ENTRY_BASIC(cme)) { - VALUE argbuf, *new_args = ALLOCV_N(VALUE, argbuf, argc+1); + VALUE argbuf, *new_args = ALLOCV_N(VALUE, argbuf, argc+1); - new_args[0] = ID2SYM(mid); + new_args[0] = ID2SYM(mid); #ifdef __GLIBC__ if (!argv) { static const VALUE buf = Qfalse; @@ -635,19 +635,19 @@ check_funcall_missing(rb_execution_context_t *ec, VALUE klass, VALUE recv, ID mi argv = &buf; } #endif - MEMCPY(new_args+1, argv, VALUE, argc); - ec->method_missing_reason = MISSING_NOENTRY; - args.ec = ec; - args.recv = recv; - args.cme = cme; - args.mid = mid; - args.argc = argc + 1; - args.argv = new_args; + MEMCPY(new_args+1, argv, VALUE, argc); + ec->method_missing_reason = MISSING_NOENTRY; + args.ec = ec; + args.recv = recv; + args.cme = cme; + args.mid = mid; + args.argc = argc + 1; + args.argv = new_args; args.kw_splat = kw_splat; - ret = rb_rescue2(check_funcall_exec, (VALUE)&args, - check_funcall_failed, (VALUE)&args, - rb_eNoMethodError, (VALUE)0); - ALLOCV_END(argbuf); + ret = rb_rescue2(check_funcall_exec, (VALUE)&args, + check_funcall_failed, (VALUE)&args, + rb_eNoMethodError, (VALUE)0); + ALLOCV_END(argbuf); } return ret; } @@ -677,14 +677,14 @@ rb_check_funcall_default_kw(VALUE recv, ID mid, int argc, const VALUE *argv, VAL int respond = check_funcall_respond_to(ec, klass, recv, mid); if (!respond) - return def; + return def; me = rb_search_method_entry(recv, mid); if (!check_funcall_callable(ec, me)) { VALUE ret = check_funcall_missing(ec, klass, recv, mid, argc, argv, respond, def, kw_splat); - if (ret == Qundef) ret = def; - return ret; + if (ret == Qundef) ret = def; + return ret; } stack_check(ec); return rb_vm_call_kw(ec, recv, mid, argc, argv, me, kw_splat); @@ -706,16 +706,16 @@ rb_check_funcall_with_hook_kw(VALUE recv, ID mid, int argc, const VALUE *argv, int respond = check_funcall_respond_to(ec, klass, recv, mid); if (!respond) { - (*hook)(FALSE, recv, mid, argc, argv, arg); - return Qundef; + (*hook)(FALSE, recv, mid, argc, argv, arg); + return Qundef; } me = rb_search_method_entry(recv, mid); if (!check_funcall_callable(ec, me)) { VALUE ret = check_funcall_missing(ec, klass, recv, mid, argc, argv, respond, Qundef, kw_splat); - (*hook)(ret != Qundef, recv, mid, argc, argv, arg); - return ret; + (*hook)(ret != Qundef, recv, mid, argc, argv, arg); + return ret; } stack_check(ec); (*hook)(TRUE, recv, mid, argc, argv, arg); @@ -776,32 +776,32 @@ uncallable_object(VALUE recv, ID mid) VALUE mname = rb_id2str(mid); if (SPECIAL_CONST_P(recv)) { - rb_raise(rb_eNotImpError, - "method `%"PRIsVALUE"' called on unexpected immediate object (%p)", - mname, (void *)recv); + rb_raise(rb_eNotImpError, + "method `%"PRIsVALUE"' called on unexpected immediate object (%p)", + mname, (void *)recv); } else if ((flags = RBASIC(recv)->flags) == 0) { - rb_raise(rb_eNotImpError, - "method `%"PRIsVALUE"' called on terminated object (%p)", - mname, (void *)recv); + rb_raise(rb_eNotImpError, + "method `%"PRIsVALUE"' called on terminated object (%p)", + mname, (void *)recv); } else if (!(typestr = rb_type_str(type = BUILTIN_TYPE(recv)))) { - rb_raise(rb_eNotImpError, - "method `%"PRIsVALUE"' called on broken T_?""?""?(0x%02x) object" - " (%p flags=0x%"PRIxVALUE")", - mname, type, (void *)recv, flags); + rb_raise(rb_eNotImpError, + "method `%"PRIsVALUE"' called on broken T_?""?""?(0x%02x) object" + " (%p flags=0x%"PRIxVALUE")", + mname, type, (void *)recv, flags); } else if (T_OBJECT <= type && type < T_NIL) { - rb_raise(rb_eNotImpError, - "method `%"PRIsVALUE"' called on hidden %s object" - " (%p flags=0x%"PRIxVALUE")", - mname, typestr, (void *)recv, flags); + rb_raise(rb_eNotImpError, + "method `%"PRIsVALUE"' called on hidden %s object" + " (%p flags=0x%"PRIxVALUE")", + mname, typestr, (void *)recv, flags); } else { - rb_raise(rb_eNotImpError, - "method `%"PRIsVALUE"' called on unexpected %s object" - " (%p flags=0x%"PRIxVALUE")", - mname, typestr, (void *)recv, flags); + rb_raise(rb_eNotImpError, + "method `%"PRIsVALUE"' called on unexpected %s object" + " (%p flags=0x%"PRIxVALUE")", + mname, typestr, (void *)recv, flags); } } @@ -877,7 +877,7 @@ rb_call(VALUE recv, ID mid, int argc, const VALUE *argv, call_type scope) } NORETURN(static void raise_method_missing(rb_execution_context_t *ec, int argc, const VALUE *argv, - VALUE obj, enum method_missing_reason call_status)); + VALUE obj, enum method_missing_reason call_status)); /* * call-seq: @@ -928,19 +928,19 @@ rb_method_missing(int argc, const VALUE *argv, VALUE obj) MJIT_FUNC_EXPORTED VALUE rb_make_no_method_exception(VALUE exc, VALUE format, VALUE obj, - int argc, const VALUE *argv, int priv) + int argc, const VALUE *argv, int priv) { VALUE name = argv[0]; if (!format) { - format = rb_fstring_lit("undefined method `%s' for %s%s%s"); + format = rb_fstring_lit("undefined method `%s' for %s%s%s"); } if (exc == rb_eNoMethodError) { - VALUE args = rb_ary_new4(argc - 1, argv + 1); - return rb_nomethod_err_new(format, obj, name, args, priv); + VALUE args = rb_ary_new4(argc - 1, argv + 1); + return rb_nomethod_err_new(format, obj, name, args, priv); } else { - return rb_name_err_new(format, obj, name); + return rb_name_err_new(format, obj, name); } } @@ -948,49 +948,49 @@ rb_make_no_method_exception(VALUE exc, VALUE format, VALUE obj, static void raise_method_missing(rb_execution_context_t *ec, int argc, const VALUE *argv, VALUE obj, - enum method_missing_reason last_call_status) + enum method_missing_reason last_call_status) { VALUE exc = rb_eNoMethodError; VALUE format = 0; if (UNLIKELY(argc == 0)) { - rb_raise(rb_eArgError, "no method name given"); + rb_raise(rb_eArgError, "no method name given"); } else if (UNLIKELY(!SYMBOL_P(argv[0]))) { - const VALUE e = rb_eArgError; /* TODO: TypeError? */ - rb_raise(e, "method name must be a Symbol but %"PRIsVALUE" is given", - rb_obj_class(argv[0])); + const VALUE e = rb_eArgError; /* TODO: TypeError? */ + rb_raise(e, "method name must be a Symbol but %"PRIsVALUE" is given", + rb_obj_class(argv[0])); } stack_check(ec); if (last_call_status & MISSING_PRIVATE) { - format = rb_fstring_lit("private method `%s' called for %s%s%s"); + format = rb_fstring_lit("private method `%s' called for %s%s%s"); } else if (last_call_status & MISSING_PROTECTED) { - format = rb_fstring_lit("protected method `%s' called for %s%s%s"); + format = rb_fstring_lit("protected method `%s' called for %s%s%s"); } else if (last_call_status & MISSING_VCALL) { - format = rb_fstring_lit("undefined local variable or method `%s' for %s%s%s"); - exc = rb_eNameError; + format = rb_fstring_lit("undefined local variable or method `%s' for %s%s%s"); + exc = rb_eNameError; } else if (last_call_status & MISSING_SUPER) { - format = rb_fstring_lit("super: no superclass method `%s' for %s%s%s"); + format = rb_fstring_lit("super: no superclass method `%s' for %s%s%s"); } { - exc = rb_make_no_method_exception(exc, format, obj, argc, argv, - last_call_status & (MISSING_FCALL|MISSING_VCALL)); - if (!(last_call_status & MISSING_MISSING)) { - rb_vm_pop_cfunc_frame(); - } - rb_exc_raise(exc); + exc = rb_make_no_method_exception(exc, format, obj, argc, argv, + last_call_status & (MISSING_FCALL|MISSING_VCALL)); + if (!(last_call_status & MISSING_MISSING)) { + rb_vm_pop_cfunc_frame(); + } + rb_exc_raise(exc); } } static void vm_raise_method_missing(rb_execution_context_t *ec, int argc, const VALUE *argv, - VALUE obj, int call_status) + VALUE obj, int call_status) { vm_passed_block_handler_set(ec, VM_BLOCK_HANDLER_NONE); raise_method_missing(ec, argc, argv, obj, call_status | MISSING_MISSING); @@ -1081,12 +1081,12 @@ rb_apply(VALUE recv, ID mid, VALUE args) argc = RARRAY_LENINT(args); if (argc >= 0x100) { - args = rb_ary_subseq(args, 0, argc); - RBASIC_CLEAR_CLASS(args); - OBJ_FREEZE(args); - ret = rb_call(recv, mid, argc, RARRAY_CONST_PTR(args), CALL_FCALL); - RB_GC_GUARD(args); - return ret; + args = rb_ary_subseq(args, 0, argc); + RBASIC_CLEAR_CLASS(args); + OBJ_FREEZE(args); + ret = rb_call(recv, mid, argc, RARRAY_CONST_PTR(args), CALL_FCALL); + RB_GC_GUARD(args); + return ret; } argv = ALLOCA_N(VALUE, argc); MEMCPY(argv, RARRAY_CONST_PTR_TRANSIENT(args), VALUE, argc); @@ -1105,19 +1105,19 @@ rb_funcall(VALUE recv, ID mid, int n, ...) va_list ar; if (n > 0) { - long i; + long i; va_start(ar, n); - argv = ALLOCA_N(VALUE, n); + argv = ALLOCA_N(VALUE, n); - for (i = 0; i < n; i++) { - argv[i] = va_arg(ar, VALUE); - } - va_end(ar); + for (i = 0; i < n; i++) { + argv[i] = va_arg(ar, VALUE); + } + va_end(ar); } else { - argv = 0; + argv = 0; } return rb_funcallv(recv, mid, n, argv); } @@ -1142,8 +1142,8 @@ rb_check_funcall_basic_kw(VALUE recv, ID mid, VALUE ancestor, int argc, const VA cme = rb_callable_method_entry(klass, mid); if (cme && METHOD_ENTRY_BASIC(cme) && RBASIC_CLASS(cme->defined_class) == ancestor) { - ec = GET_EC(); - return rb_vm_call0(ec, recv, mid, argc, argv, cme, kw_splat); + ec = GET_EC(); + return rb_vm_call0(ec, recv, mid, argc, argv, cme, kw_splat); } return Qundef; @@ -1179,7 +1179,7 @@ VALUE rb_funcall_with_block(VALUE recv, ID mid, int argc, const VALUE *argv, VALUE passed_procval) { if (!NIL_P(passed_procval)) { - vm_passed_block_handler_set(GET_EC(), passed_procval); + vm_passed_block_handler_set(GET_EC(), passed_procval); } return rb_funcallv_public(recv, mid, argc, argv); @@ -1215,47 +1215,47 @@ send_internal(int argc, const VALUE *argv, VALUE recv, call_type scope) int public = scope == CALL_PUBLIC || scope == CALL_PUBLIC_KW; if (public) { - self = Qundef; + self = Qundef; } else { - self = RUBY_VM_PREVIOUS_CONTROL_FRAME(ec->cfp)->self; + self = RUBY_VM_PREVIOUS_CONTROL_FRAME(ec->cfp)->self; } if (argc == 0) { - rb_raise(rb_eArgError, "no method name given"); + rb_raise(rb_eArgError, "no method name given"); } vid = *argv; id = rb_check_id(&vid); if (!id) { - if (rb_method_basic_definition_p(CLASS_OF(recv), idMethodMissing)) { - VALUE exc = rb_make_no_method_exception(rb_eNoMethodError, 0, - recv, argc, argv, + if (rb_method_basic_definition_p(CLASS_OF(recv), idMethodMissing)) { + VALUE exc = rb_make_no_method_exception(rb_eNoMethodError, 0, + recv, argc, argv, !public); - rb_exc_raise(exc); - } - if (!SYMBOL_P(*argv)) { - VALUE *tmp_argv = current_vm_stack_arg(ec, argv); - vid = rb_str_intern(vid); - if (tmp_argv) { - tmp_argv[0] = vid; - } - else if (argc > 1) { - tmp_argv = ALLOCV_N(VALUE, vargv, argc); - tmp_argv[0] = vid; - MEMCPY(tmp_argv+1, argv+1, VALUE, argc-1); - argv = tmp_argv; - } - else { - argv = &vid; - } - } - id = idMethodMissing; - ec->method_missing_reason = MISSING_NOENTRY; + rb_exc_raise(exc); + } + if (!SYMBOL_P(*argv)) { + VALUE *tmp_argv = current_vm_stack_arg(ec, argv); + vid = rb_str_intern(vid); + if (tmp_argv) { + tmp_argv[0] = vid; + } + else if (argc > 1) { + tmp_argv = ALLOCV_N(VALUE, vargv, argc); + tmp_argv[0] = vid; + MEMCPY(tmp_argv+1, argv+1, VALUE, argc-1); + argv = tmp_argv; + } + else { + argv = &vid; + } + } + id = idMethodMissing; + ec->method_missing_reason = MISSING_NOENTRY; } else { - argv++; argc--; + argv++; argc--; } PASS_PASSED_BLOCK_HANDLER_EC(ec); ret = rb_call0(ec, recv, id, argc, argv, scope, self); @@ -1357,10 +1357,10 @@ VALUE rb_yield(VALUE val) { if (val == Qundef) { - return rb_yield_0(0, NULL); + return rb_yield_0(0, NULL); } else { - return rb_yield_0(1, &val); + return rb_yield_0(1, &val); } } @@ -1369,21 +1369,21 @@ VALUE rb_yield_values(int n, ...) { if (n == 0) { - return rb_yield_0(0, 0); + return rb_yield_0(0, 0); } else { - int i; - VALUE *argv; - va_list args; - argv = ALLOCA_N(VALUE, n); + int i; + VALUE *argv; + va_list args; + argv = ALLOCA_N(VALUE, n); va_start(args, n); - for (i=0; icode.ifunc = ifunc; - block_handler = VM_BH_FROM_IFUNC_BLOCK(captured); - } - else { - block_handler = VM_CF_BLOCK_HANDLER(cfp); - } - vm_passed_block_handler_set(ec, block_handler); - } - retval = (*it_proc) (data1); + if (ifunc) { + struct rb_captured_block *captured = VM_CFP_TO_CAPTURED_BLOCK(cfp); + captured->code.ifunc = ifunc; + block_handler = VM_BH_FROM_IFUNC_BLOCK(captured); + } + else { + block_handler = VM_CF_BLOCK_HANDLER(cfp); + } + vm_passed_block_handler_set(ec, block_handler); + } + retval = (*it_proc) (data1); } else if (state == TAG_BREAK || state == TAG_RETRY) { - const struct vm_throw_data *const err = (struct vm_throw_data *)ec->errinfo; - const rb_control_frame_t *const escape_cfp = THROW_DATA_CATCH_FRAME(err); + const struct vm_throw_data *const err = (struct vm_throw_data *)ec->errinfo; + const rb_control_frame_t *const escape_cfp = THROW_DATA_CATCH_FRAME(err); - if (cfp == escape_cfp) { - rb_vm_rewind_cfp(ec, cfp); + if (cfp == escape_cfp) { + rb_vm_rewind_cfp(ec, cfp); - state = 0; - ec->tag->state = TAG_NONE; - ec->errinfo = Qnil; + state = 0; + ec->tag->state = TAG_NONE; + ec->errinfo = Qnil; - if (state == TAG_RETRY) goto iter_retry; - retval = THROW_DATA_VAL(err); - } - else if (0) { - SDR(); fprintf(stderr, "%p, %p\n", (void *)cfp, (void *)escape_cfp); - } + if (state == TAG_RETRY) goto iter_retry; + retval = THROW_DATA_VAL(err); + } + else if (0) { + SDR(); fprintf(stderr, "%p, %p\n", (void *)cfp, (void *)escape_cfp); + } } EC_POP_TAG(); if (state) { - EC_JUMP_TAG(ec, state); + EC_JUMP_TAG(ec, state); } return retval; } @@ -1561,8 +1561,8 @@ rb_iterate_internal(VALUE (* it_proc)(VALUE), VALUE data1, rb_block_call_func_t bl_proc, VALUE data2) { return rb_iterate0(it_proc, data1, - bl_proc ? rb_vm_ifunc_proc_new(bl_proc, (void *)data2) : 0, - GET_EC()); + bl_proc ? rb_vm_ifunc_proc_new(bl_proc, (void *)data2) : 0, + GET_EC()); } VALUE @@ -1593,7 +1593,7 @@ VALUE rb_block_call_kw(VALUE obj, ID mid, int argc, const VALUE * argv, rb_block VALUE rb_block_call(VALUE obj, ID mid, int argc, const VALUE * argv, - rb_block_call_func_t bl_proc, VALUE data2) + rb_block_call_func_t bl_proc, VALUE data2) { return rb_block_call_kw(obj, mid, argc, argv, bl_proc, data2, RB_NO_KEYWORDS); } @@ -1614,8 +1614,8 @@ rb_block_call_kw(VALUE obj, ID mid, int argc, const VALUE * argv, VALUE rb_lambda_call(VALUE obj, ID mid, int argc, const VALUE *argv, - rb_block_call_func_t bl_proc, int min_argc, int max_argc, - VALUE data2) + rb_block_call_func_t bl_proc, int min_argc, int max_argc, + VALUE data2) { struct iter_method_arg arg; struct vm_ifunc *block; @@ -1641,7 +1641,7 @@ iterate_check_method(VALUE obj) VALUE rb_check_block_call(VALUE obj, ID mid, int argc, const VALUE *argv, - rb_block_call_func_t bl_proc, VALUE data2) + rb_block_call_func_t bl_proc, VALUE data2) { struct iter_method_arg arg; @@ -1665,7 +1665,7 @@ static VALUE eval_default_path; static const rb_iseq_t * eval_make_iseq(VALUE src, VALUE fname, int line, const rb_binding_t *bind, - const struct rb_block *base_block) + const struct rb_block *base_block) { const VALUE parser = rb_parser_new(); const rb_iseq_t *const parent = vm_block_iseq(base_block); @@ -1690,7 +1690,7 @@ eval_make_iseq(VALUE src, VALUE fname, int line, const rb_binding_t *bind, } if (!fname) { - fname = rb_source_location(&line); + fname = rb_source_location(&line); } if (fname != Qundef) { @@ -1735,7 +1735,7 @@ eval_string_with_cref(VALUE self, VALUE src, rb_cref_t *cref, VALUE file, int li const rb_iseq_t *iseq; rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(ec, ec->cfp); if (!cfp) { - rb_raise(rb_eRuntimeError, "Can't eval on top of Fiber or Thread"); + rb_raise(rb_eRuntimeError, "Can't eval on top of Fiber or Thread"); } block.as.captured = *VM_CFP_TO_CAPTURED_BLOCK(cfp); @@ -1745,13 +1745,13 @@ eval_string_with_cref(VALUE self, VALUE src, rb_cref_t *cref, VALUE file, int li iseq = eval_make_iseq(src, file, line, NULL, &block); if (!iseq) { - rb_exc_raise(ec->errinfo); + rb_exc_raise(ec->errinfo); } /* TODO: what the code checking? */ if (!cref && block.as.captured.code.val) { rb_cref_t *orig_cref = vm_get_cref(vm_block_ep(&block)); - cref = vm_cref_dup(orig_cref); + cref = vm_cref_dup(orig_cref); } vm_set_eval_stack(ec, iseq, cref, &block); @@ -1766,14 +1766,14 @@ eval_string_with_scope(VALUE scope, VALUE src, VALUE file, int line) rb_binding_t *bind = Check_TypedStruct(scope, &ruby_binding_data_type); const rb_iseq_t *iseq = eval_make_iseq(src, file, line, bind, &bind->block); if (!iseq) { - rb_exc_raise(ec->errinfo); + rb_exc_raise(ec->errinfo); } vm_set_eval_stack(ec, iseq, NULL, &bind->block); /* save new env */ if (ISEQ_BODY(iseq)->local_table_size > 0) { - vm_bind_update_env(scope, bind, vm_make_env_object(ec, ec->cfp)); + vm_bind_update_env(scope, bind, vm_make_env_object(ec, ec->cfp)); } /* kick */ @@ -1808,19 +1808,19 @@ rb_f_eval(int argc, const VALUE *argv, VALUE self) rb_scan_args(argc, argv, "13", &src, &scope, &vfile, &vline); SafeStringValue(src); if (argc >= 3) { - StringValue(vfile); + StringValue(vfile); } if (argc >= 4) { - line = NUM2INT(vline); + line = NUM2INT(vline); } if (!NIL_P(vfile)) - file = vfile; + file = vfile; if (NIL_P(scope)) - return eval_string_with_cref(self, src, NULL, file, line); + return eval_string_with_cref(self, src, NULL, file, line); else - return eval_string_with_scope(scope, src, file, line); + return eval_string_with_scope(scope, src, file, line); } /** @note This function name is not stable. */ @@ -1888,10 +1888,10 @@ rb_eval_string_wrap(const char *str, int *pstate) th->top_wrapper = wrapper; if (pstate) { - *pstate = state; + *pstate = state; } else if (state != TAG_NONE) { - EC_JUMP_TAG(th->ec, state); + EC_JUMP_TAG(th->ec, state); } return val; } @@ -1905,13 +1905,13 @@ rb_eval_cmd_kw(VALUE cmd, VALUE arg, int kw_splat) EC_PUSH_TAG(ec); if ((state = EC_EXEC_TAG()) == TAG_NONE) { - if (!RB_TYPE_P(cmd, T_STRING)) { + if (!RB_TYPE_P(cmd, T_STRING)) { val = rb_funcallv_kw(cmd, idCall, RARRAY_LENINT(arg), RARRAY_CONST_PTR(arg), kw_splat); - } - else { - val = eval_string_with_cref(rb_vm_top_self(), cmd, NULL, 0, 0); - } + } + else { + val = eval_string_with_cref(rb_vm_top_self(), cmd, NULL, 0, 0); + } } EC_POP_TAG(); @@ -1936,31 +1936,31 @@ yield_under(VALUE self, int singleton, int argc, const VALUE *argv, int kw_splat if (block_handler != VM_BLOCK_HANDLER_NONE) { again: - switch (vm_block_handler_type(block_handler)) { - case block_handler_type_iseq: - captured = VM_BH_TO_CAPT_BLOCK(block_handler); - new_captured = *captured; - new_block_handler = VM_BH_FROM_ISEQ_BLOCK(&new_captured); - break; - case block_handler_type_ifunc: - captured = VM_BH_TO_CAPT_BLOCK(block_handler); - new_captured = *captured; - new_block_handler = VM_BH_FROM_IFUNC_BLOCK(&new_captured); - break; - case block_handler_type_proc: - is_lambda = rb_proc_lambda_p(block_handler) != Qfalse; - block_handler = vm_proc_to_block_handler(VM_BH_TO_PROC(block_handler)); - goto again; - case block_handler_type_symbol: + switch (vm_block_handler_type(block_handler)) { + case block_handler_type_iseq: + captured = VM_BH_TO_CAPT_BLOCK(block_handler); + new_captured = *captured; + new_block_handler = VM_BH_FROM_ISEQ_BLOCK(&new_captured); + break; + case block_handler_type_ifunc: + captured = VM_BH_TO_CAPT_BLOCK(block_handler); + new_captured = *captured; + new_block_handler = VM_BH_FROM_IFUNC_BLOCK(&new_captured); + break; + case block_handler_type_proc: + is_lambda = rb_proc_lambda_p(block_handler) != Qfalse; + block_handler = vm_proc_to_block_handler(VM_BH_TO_PROC(block_handler)); + goto again; + case block_handler_type_symbol: return rb_sym_proc_call(SYM2ID(VM_BH_TO_SYMBOL(block_handler)), argc, argv, kw_splat, VM_BLOCK_HANDLER_NONE); - } + } - new_captured.self = self; - ep = captured->ep; + new_captured.self = self; + ep = captured->ep; - VM_FORCE_WRITE_SPECIAL_CONST(&VM_CF_LEP(ec->cfp)[VM_ENV_DATA_INDEX_SPECVAL], new_block_handler); + VM_FORCE_WRITE_SPECIAL_CONST(&VM_CF_LEP(ec->cfp)[VM_ENV_DATA_INDEX_SPECVAL], new_block_handler); } VM_ASSERT(singleton || RB_TYPE_P(self, T_MODULE) || RB_TYPE_P(self, T_CLASS)); @@ -1976,17 +1976,17 @@ rb_yield_refine_block(VALUE refinement, VALUE refinements) VALUE block_handler = VM_CF_BLOCK_HANDLER(ec->cfp); if (vm_block_handler_type(block_handler) != block_handler_type_iseq) { - rb_bug("rb_yield_refine_block: an iseq block is required"); + rb_bug("rb_yield_refine_block: an iseq block is required"); } else { - const struct rb_captured_block *captured = VM_BH_TO_ISEQ_BLOCK(block_handler); - struct rb_captured_block new_captured = *captured; - VALUE new_block_handler = VM_BH_FROM_ISEQ_BLOCK(&new_captured); - const VALUE *ep = captured->ep; - rb_cref_t *cref = vm_cref_push(ec, refinement, ep, TRUE, FALSE); - CREF_REFINEMENTS_SET(cref, refinements); - VM_FORCE_WRITE_SPECIAL_CONST(&VM_CF_LEP(ec->cfp)[VM_ENV_DATA_INDEX_SPECVAL], new_block_handler); - new_captured.self = refinement; + const struct rb_captured_block *captured = VM_BH_TO_ISEQ_BLOCK(block_handler); + struct rb_captured_block new_captured = *captured; + VALUE new_block_handler = VM_BH_FROM_ISEQ_BLOCK(&new_captured); + const VALUE *ep = captured->ep; + rb_cref_t *cref = vm_cref_push(ec, refinement, ep, TRUE, FALSE); + CREF_REFINEMENTS_SET(cref, refinements); + VM_FORCE_WRITE_SPECIAL_CONST(&VM_CF_LEP(ec->cfp)[VM_ENV_DATA_INDEX_SPECVAL], new_block_handler); + new_captured.self = refinement; return vm_yield_with_cref(ec, 0, NULL, RB_NO_KEYWORDS, cref, FALSE); } } @@ -2005,24 +2005,24 @@ static VALUE specific_eval(int argc, const VALUE *argv, VALUE self, int singleton, int kw_splat) { if (rb_block_given_p()) { - rb_check_arity(argc, 0, 0); + rb_check_arity(argc, 0, 0); return yield_under(self, singleton, 1, &self, kw_splat); } else { - VALUE file = Qundef; - int line = 1; - VALUE code; + VALUE file = Qundef; + int line = 1; + VALUE code; - rb_check_arity(argc, 1, 3); - code = argv[0]; - SafeStringValue(code); - if (argc > 2) - line = NUM2INT(argv[2]); - if (argc > 1) { - file = argv[1]; - if (!NIL_P(file)) StringValue(file); - } - return eval_under(self, singleton, code, file, line); + rb_check_arity(argc, 1, 3); + code = argv[0]; + SafeStringValue(code); + if (argc > 2) + line = NUM2INT(argv[2]); + if (argc > 1) { + file = argv[1]; + if (!NIL_P(file)) StringValue(file); + } + return eval_under(self, singleton, code, file, line); } } @@ -2267,18 +2267,18 @@ rb_throw_obj(VALUE tag, VALUE value) struct rb_vm_tag *tt = ec->tag; while (tt) { - if (tt->tag == tag) { - tt->retval = value; - break; - } - tt = tt->prev; + if (tt->tag == tag) { + tt->retval = value; + break; + } + tt = tt->prev; } if (!tt) { - VALUE desc[3]; - desc[0] = tag; - desc[1] = value; - desc[2] = rb_str_new_cstr("uncaught throw %p"); - rb_exc_raise(rb_class_new_instance(numberof(desc), desc, rb_eUncaughtThrow)); + VALUE desc[3]; + desc[0] = tag; + desc[1] = value; + desc[2] = rb_str_new_cstr("uncaught throw %p"); + rb_exc_raise(rb_class_new_instance(numberof(desc), desc, rb_eUncaughtThrow)); } ec->errinfo = (VALUE)THROW_DATA_NEW(tag, NULL, TAG_THROW); @@ -2364,7 +2364,7 @@ rb_catch(const char *tag, rb_block_call_func_t func, VALUE data) static VALUE vm_catch_protect(VALUE tag, rb_block_call_func *func, VALUE data, - enum ruby_tag_type *stateptr, rb_execution_context_t *volatile ec) + enum ruby_tag_type *stateptr, rb_execution_context_t *volatile ec) { enum ruby_tag_type state; VALUE val = Qnil; /* OK */ @@ -2375,18 +2375,18 @@ vm_catch_protect(VALUE tag, rb_block_call_func *func, VALUE data, _tag.tag = tag; if ((state = EC_EXEC_TAG()) == TAG_NONE) { - /* call with argc=1, argv = [tag], block = Qnil to insure compatibility */ - val = (*func)(tag, data, 1, (const VALUE *)&tag, Qnil); + /* call with argc=1, argv = [tag], block = Qnil to insure compatibility */ + val = (*func)(tag, data, 1, (const VALUE *)&tag, Qnil); } else if (state == TAG_THROW && THROW_DATA_VAL((struct vm_throw_data *)ec->errinfo) == tag) { - rb_vm_rewind_cfp(ec, saved_cfp); - val = ec->tag->retval; - ec->errinfo = Qnil; - state = 0; + rb_vm_rewind_cfp(ec, saved_cfp); + val = ec->tag->retval; + ec->errinfo = Qnil; + state = 0; } EC_POP_TAG(); if (stateptr) - *stateptr = state; + *stateptr = state; return val; } @@ -2465,27 +2465,27 @@ rb_f_local_variables(VALUE _) local_var_list_init(&vars); while (cfp) { - if (cfp->iseq) { + if (cfp->iseq) { for (i = 0; i < ISEQ_BODY(cfp->iseq)->local_table_size; i++) { local_var_list_add(&vars, ISEQ_BODY(cfp->iseq)->local_table[i]); - } - } - if (!VM_ENV_LOCAL_P(cfp->ep)) { - /* block */ - const VALUE *ep = VM_CF_PREV_EP(cfp); + } + } + if (!VM_ENV_LOCAL_P(cfp->ep)) { + /* block */ + const VALUE *ep = VM_CF_PREV_EP(cfp); - if (vm_collect_local_variables_in_heap(ep, &vars)) { - break; - } - else { - while (cfp->ep != ep) { - cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); - } - } - } - else { - break; - } + if (vm_collect_local_variables_in_heap(ep, &vars)) { + break; + } + else { + while (cfp->ep != ep) { + cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); + } + } + } + else { + break; + } } return local_var_list_finish(&vars); } @@ -2574,9 +2574,9 @@ Init_vm_eval(void) #if 1 rb_add_method(rb_cBasicObject, id__send__, - VM_METHOD_TYPE_OPTIMIZED, (void *)OPTIMIZED_METHOD_TYPE_SEND, METHOD_VISI_PUBLIC); + VM_METHOD_TYPE_OPTIMIZED, (void *)OPTIMIZED_METHOD_TYPE_SEND, METHOD_VISI_PUBLIC); rb_add_method(rb_mKernel, idSend, - VM_METHOD_TYPE_OPTIMIZED, (void *)OPTIMIZED_METHOD_TYPE_SEND, METHOD_VISI_PUBLIC); + VM_METHOD_TYPE_OPTIMIZED, (void *)OPTIMIZED_METHOD_TYPE_SEND, METHOD_VISI_PUBLIC); #else rb_define_method(rb_cBasicObject, "__send__", rb_f_send, -1); rb_define_method(rb_mKernel, "send", rb_f_send, -1); diff --git a/vm_exec.c b/vm_exec.c index 8931799c2e..591a0de57b 100644 --- a/vm_exec.c +++ b/vm_exec.c @@ -129,7 +129,7 @@ vm_exec_core(rb_execution_context_t *ec, VALUE initial) #if OPT_TOKEN_THREADED_CODE || OPT_DIRECT_THREADED_CODE #include "vmtc.inc" if (UNLIKELY(ec == 0)) { - return (VALUE)insns_address_table; + return (VALUE)insns_address_table; } #endif reg_cfp = ec->cfp; @@ -176,22 +176,22 @@ vm_exec_core(rb_execution_context_t *ec, VALUE initial) rb_thread_t *th; while (1) { - reg_cfp = ((rb_insn_func_t) (*GET_PC()))(ec, reg_cfp); + reg_cfp = ((rb_insn_func_t) (*GET_PC()))(ec, reg_cfp); - if (UNLIKELY(reg_cfp == 0)) { - break; - } + if (UNLIKELY(reg_cfp == 0)) { + break; + } } if ((th = rb_ec_thread_ptr(ec))->retval != Qundef) { - VALUE ret = th->retval; - th->retval = Qundef; - return ret; + VALUE ret = th->retval; + th->retval = Qundef; + return ret; } else { - VALUE err = ec->errinfo; - ec->errinfo = Qnil; - return err; + VALUE err = ec->errinfo; + ec->errinfo = Qnil; + return err; } } #endif diff --git a/vm_insnhelper.c b/vm_insnhelper.c index 3c81544ba9..2fb1ecb5f7 100644 --- a/vm_insnhelper.c +++ b/vm_insnhelper.c @@ -61,10 +61,10 @@ ec_stack_overflow(rb_execution_context_t *ec, int setup) VALUE mesg = rb_ec_vm_ptr(ec)->special_exceptions[ruby_error_sysstack]; ec->raised_flag = RAISED_STACKOVERFLOW; if (setup) { - VALUE at = rb_ec_backtrace_object(ec); - mesg = ruby_vm_special_exception_copy(mesg); - rb_ivar_set(mesg, idBt, at); - rb_ivar_set(mesg, idBt_locations, at); + VALUE at = rb_ec_backtrace_object(ec); + mesg = ruby_vm_special_exception_copy(mesg); + rb_ivar_set(mesg, idBt, at); + rb_ivar_set(mesg, idBt_locations, at); } ec->errinfo = mesg; EC_JUMP_TAG(ec, TAG_RAISE); @@ -89,9 +89,9 @@ rb_ec_stack_overflow(rb_execution_context_t *ec, int crit) rb_bug("system stack overflow during GC. Faulty native extension?"); } if (crit) { - ec->raised_flag = RAISED_STACKOVERFLOW; - ec->errinfo = rb_ec_vm_ptr(ec)->special_exceptions[ruby_error_stackfatal]; - EC_JUMP_TAG(ec, TAG_RAISE); + ec->raised_flag = RAISED_STACKOVERFLOW; + ec->errinfo = rb_ec_vm_ptr(ec)->special_exceptions[ruby_error_stackfatal]; + EC_JUMP_TAG(ec, TAG_RAISE); } #ifdef USE_SIGALTSTACK ec_stack_overflow(ec, TRUE); @@ -111,15 +111,15 @@ callable_class_p(VALUE klass) default: break; case T_ICLASS: - if (!RB_TYPE_P(RCLASS_SUPER(klass), T_MODULE)) break; + if (!RB_TYPE_P(RCLASS_SUPER(klass), T_MODULE)) break; case T_MODULE: - return TRUE; + return TRUE; } while (klass) { - if (klass == rb_cBasicObject) { - return TRUE; - } - klass = RCLASS_SUPER(klass); + if (klass == rb_cBasicObject) { + return TRUE; + } + klass = RCLASS_SUPER(klass); } return FALSE; #else @@ -152,62 +152,62 @@ vm_check_frame_detail(VALUE type, int req_block, int req_me, int req_cref, VALUE enum imemo_type cref_or_me_type = imemo_env; /* impossible value */ if (RB_TYPE_P(cref_or_me, T_IMEMO)) { - cref_or_me_type = imemo_type(cref_or_me); + cref_or_me_type = imemo_type(cref_or_me); } if (type & VM_FRAME_FLAG_BMETHOD) { - req_me = TRUE; + req_me = TRUE; } if (req_block && (type & VM_ENV_FLAG_LOCAL) == 0) { - rb_bug("vm_push_frame: specval (%p) should be a block_ptr on %x frame", (void *)specval, magic); + rb_bug("vm_push_frame: specval (%p) should be a block_ptr on %x frame", (void *)specval, magic); } if (!req_block && (type & VM_ENV_FLAG_LOCAL) != 0) { - rb_bug("vm_push_frame: specval (%p) should not be a block_ptr on %x frame", (void *)specval, magic); + rb_bug("vm_push_frame: specval (%p) should not be a block_ptr on %x frame", (void *)specval, magic); } if (req_me) { - if (cref_or_me_type != imemo_ment) { - rb_bug("vm_push_frame: (%s) should be method entry on %x frame", rb_obj_info(cref_or_me), magic); - } + if (cref_or_me_type != imemo_ment) { + rb_bug("vm_push_frame: (%s) should be method entry on %x frame", rb_obj_info(cref_or_me), magic); + } } else { - if (req_cref && cref_or_me_type != imemo_cref) { - rb_bug("vm_push_frame: (%s) should be CREF on %x frame", rb_obj_info(cref_or_me), magic); - } - else { /* cref or Qfalse */ - if (cref_or_me != Qfalse && cref_or_me_type != imemo_cref) { - if (((type & VM_FRAME_FLAG_LAMBDA) || magic == VM_FRAME_MAGIC_IFUNC) && (cref_or_me_type == imemo_ment)) { - /* ignore */ - } - else { - rb_bug("vm_push_frame: (%s) should be false or cref on %x frame", rb_obj_info(cref_or_me), magic); - } - } - } + if (req_cref && cref_or_me_type != imemo_cref) { + rb_bug("vm_push_frame: (%s) should be CREF on %x frame", rb_obj_info(cref_or_me), magic); + } + else { /* cref or Qfalse */ + if (cref_or_me != Qfalse && cref_or_me_type != imemo_cref) { + if (((type & VM_FRAME_FLAG_LAMBDA) || magic == VM_FRAME_MAGIC_IFUNC) && (cref_or_me_type == imemo_ment)) { + /* ignore */ + } + else { + rb_bug("vm_push_frame: (%s) should be false or cref on %x frame", rb_obj_info(cref_or_me), magic); + } + } + } } if (cref_or_me_type == imemo_ment) { - const rb_callable_method_entry_t *me = (const rb_callable_method_entry_t *)cref_or_me; + const rb_callable_method_entry_t *me = (const rb_callable_method_entry_t *)cref_or_me; - if (!callable_method_entry_p(me)) { - rb_bug("vm_push_frame: ment (%s) should be callable on %x frame.", rb_obj_info(cref_or_me), magic); - } + if (!callable_method_entry_p(me)) { + rb_bug("vm_push_frame: ment (%s) should be callable on %x frame.", rb_obj_info(cref_or_me), magic); + } } if ((type & VM_FRAME_MAGIC_MASK) == VM_FRAME_MAGIC_DUMMY) { - VM_ASSERT(iseq == NULL || - RUBY_VM_NORMAL_ISEQ_P(iseq) /* argument error. it should be fixed */); + VM_ASSERT(iseq == NULL || + RUBY_VM_NORMAL_ISEQ_P(iseq) /* argument error. it should be fixed */); } else { - VM_ASSERT(is_cframe == !RUBY_VM_NORMAL_ISEQ_P(iseq)); + VM_ASSERT(is_cframe == !RUBY_VM_NORMAL_ISEQ_P(iseq)); } } static void vm_check_frame(VALUE type, - VALUE specval, - VALUE cref_or_me, - const rb_iseq_t *iseq) + VALUE specval, + VALUE cref_or_me, + const rb_iseq_t *iseq) { VALUE given_magic = type & VM_FRAME_MAGIC_MASK; VM_ASSERT(FIXNUM_P(type)); @@ -215,21 +215,21 @@ vm_check_frame(VALUE type, #define CHECK(magic, req_block, req_me, req_cref, is_cframe) \ case magic: \ vm_check_frame_detail(type, req_block, req_me, req_cref, \ - specval, cref_or_me, is_cframe, iseq); \ + specval, cref_or_me, is_cframe, iseq); \ break switch (given_magic) { - /* BLK ME CREF CFRAME */ - CHECK(VM_FRAME_MAGIC_METHOD, TRUE, TRUE, FALSE, FALSE); - CHECK(VM_FRAME_MAGIC_CLASS, TRUE, FALSE, TRUE, FALSE); - CHECK(VM_FRAME_MAGIC_TOP, TRUE, FALSE, TRUE, FALSE); - CHECK(VM_FRAME_MAGIC_CFUNC, TRUE, TRUE, FALSE, TRUE); - CHECK(VM_FRAME_MAGIC_BLOCK, FALSE, FALSE, FALSE, FALSE); - CHECK(VM_FRAME_MAGIC_IFUNC, FALSE, FALSE, FALSE, TRUE); - CHECK(VM_FRAME_MAGIC_EVAL, FALSE, FALSE, FALSE, FALSE); - CHECK(VM_FRAME_MAGIC_RESCUE, FALSE, FALSE, FALSE, FALSE); - CHECK(VM_FRAME_MAGIC_DUMMY, TRUE, FALSE, FALSE, FALSE); + /* BLK ME CREF CFRAME */ + CHECK(VM_FRAME_MAGIC_METHOD, TRUE, TRUE, FALSE, FALSE); + CHECK(VM_FRAME_MAGIC_CLASS, TRUE, FALSE, TRUE, FALSE); + CHECK(VM_FRAME_MAGIC_TOP, TRUE, FALSE, TRUE, FALSE); + CHECK(VM_FRAME_MAGIC_CFUNC, TRUE, TRUE, FALSE, TRUE); + CHECK(VM_FRAME_MAGIC_BLOCK, FALSE, FALSE, FALSE, FALSE); + CHECK(VM_FRAME_MAGIC_IFUNC, FALSE, FALSE, FALSE, TRUE); + CHECK(VM_FRAME_MAGIC_EVAL, FALSE, FALSE, FALSE, FALSE); + CHECK(VM_FRAME_MAGIC_RESCUE, FALSE, FALSE, FALSE, FALSE); + CHECK(VM_FRAME_MAGIC_DUMMY, TRUE, FALSE, FALSE, FALSE); default: - rb_bug("vm_push_frame: unknown type (%x)", (unsigned int)given_magic); + rb_bug("vm_push_frame: unknown type (%x)", (unsigned int)given_magic); } #undef CHECK } @@ -349,15 +349,15 @@ STATIC_ASSERT(VM_ENV_DATA_INDEX_FLAGS, VM_ENV_DATA_INDEX_FLAGS == -0); static void vm_push_frame(rb_execution_context_t *ec, - const rb_iseq_t *iseq, - VALUE type, - VALUE self, - VALUE specval, - VALUE cref_or_me, - const VALUE *pc, - VALUE *sp, - int local_size, - int stack_max) + const rb_iseq_t *iseq, + VALUE type, + VALUE self, + VALUE specval, + VALUE cref_or_me, + const VALUE *pc, + VALUE *sp, + int local_size, + int stack_max) { rb_control_frame_t *const cfp = RUBY_VM_NEXT_CONTROL_FRAME(ec->cfp); @@ -372,7 +372,7 @@ vm_push_frame(rb_execution_context_t *ec, /* initialize local variables */ for (int i=0; i < local_size; i++) { - *sp++ = Qnil; + *sp++ = Qnil; } /* setup ep with managing data */ @@ -398,7 +398,7 @@ vm_push_frame(rb_execution_context_t *ec, ec->cfp = cfp; if (VMDEBUG == 2) { - SDR(); + SDR(); } vm_push_frame_debug_counter_inc(ec, cfp, type); } @@ -430,13 +430,13 @@ rb_arity_error_new(int argc, int min, int max) { VALUE err_mess = 0; if (min == max) { - err_mess = rb_sprintf("wrong number of arguments (given %d, expected %d)", argc, min); + err_mess = rb_sprintf("wrong number of arguments (given %d, expected %d)", argc, min); } else if (max == UNLIMITED_ARGUMENTS) { - err_mess = rb_sprintf("wrong number of arguments (given %d, expected %d+)", argc, min); + err_mess = rb_sprintf("wrong number of arguments (given %d, expected %d+)", argc, min); } else { - err_mess = rb_sprintf("wrong number of arguments (given %d, expected %d..%d)", argc, min, max); + err_mess = rb_sprintf("wrong number of arguments (given %d, expected %d..%d)", argc, min, max); } return rb_exc_new3(rb_eArgError, err_mess); } @@ -466,10 +466,10 @@ vm_env_write(const VALUE *ep, int index, VALUE v) { VALUE flags = ep[VM_ENV_DATA_INDEX_FLAGS]; if (LIKELY((flags & VM_ENV_FLAG_WB_REQUIRED) == 0)) { - VM_STACK_ENV_WRITE(ep, index, v); + VM_STACK_ENV_WRITE(ep, index, v); } else { - vm_env_write_slowpath(ep, index, v); + vm_env_write_slowpath(ep, index, v); } } @@ -477,20 +477,20 @@ MJIT_STATIC VALUE rb_vm_bh_to_procval(const rb_execution_context_t *ec, VALUE block_handler) { if (block_handler == VM_BLOCK_HANDLER_NONE) { - return Qnil; + return Qnil; } else { - switch (vm_block_handler_type(block_handler)) { - case block_handler_type_iseq: - case block_handler_type_ifunc: - return rb_vm_make_proc(ec, VM_BH_TO_CAPT_BLOCK(block_handler), rb_cProc); - case block_handler_type_symbol: - return rb_sym_to_proc(VM_BH_TO_SYMBOL(block_handler)); - case block_handler_type_proc: - return VM_BH_TO_PROC(block_handler); - default: - VM_UNREACHABLE(rb_vm_bh_to_procval); - } + switch (vm_block_handler_type(block_handler)) { + case block_handler_type_iseq: + case block_handler_type_ifunc: + return rb_vm_make_proc(ec, VM_BH_TO_CAPT_BLOCK(block_handler), rb_cProc); + case block_handler_type_symbol: + return rb_sym_to_proc(VM_BH_TO_SYMBOL(block_handler)); + case block_handler_type_proc: + return VM_BH_TO_PROC(block_handler); + default: + VM_UNREACHABLE(rb_vm_bh_to_procval); + } } } @@ -501,14 +501,14 @@ static int vm_svar_valid_p(VALUE svar) { if (RB_TYPE_P((VALUE)svar, T_IMEMO)) { - switch (imemo_type(svar)) { - case imemo_svar: - case imemo_cref: - case imemo_ment: - return TRUE; - default: - break; - } + switch (imemo_type(svar)) { + case imemo_svar: + case imemo_cref: + case imemo_ment: + return TRUE; + default: + break; + } } rb_bug("vm_svar_valid_p: unknown type: %s", rb_obj_info(svar)); return FALSE; @@ -521,10 +521,10 @@ lep_svar(const rb_execution_context_t *ec, const VALUE *lep) VALUE svar; if (lep && (ec == NULL || ec->root_lep != lep)) { - svar = lep[VM_ENV_DATA_INDEX_ME_CREF]; + svar = lep[VM_ENV_DATA_INDEX_ME_CREF]; } else { - svar = ec->root_svar; + svar = ec->root_svar; } VM_ASSERT(svar == Qfalse || vm_svar_valid_p(svar)); @@ -538,10 +538,10 @@ lep_svar_write(const rb_execution_context_t *ec, const VALUE *lep, const struct VM_ASSERT(vm_svar_valid_p((VALUE)svar)); if (lep && (ec == NULL || ec->root_lep != lep)) { - vm_env_write(lep, VM_ENV_DATA_INDEX_ME_CREF, (VALUE)svar); + vm_env_write(lep, VM_ENV_DATA_INDEX_ME_CREF, (VALUE)svar); } else { - RB_OBJ_WRITE(rb_ec_thread_ptr(ec)->self, &ec->root_svar, svar); + RB_OBJ_WRITE(rb_ec_thread_ptr(ec)->self, &ec->root_svar, svar); } } @@ -554,18 +554,18 @@ lep_svar_get(const rb_execution_context_t *ec, const VALUE *lep, rb_num_t key) switch (key) { case VM_SVAR_LASTLINE: - return svar->lastline; + return svar->lastline; case VM_SVAR_BACKREF: - return svar->backref; + return svar->backref; default: { - const VALUE ary = svar->others; + const VALUE ary = svar->others; - if (NIL_P(ary)) { - return Qnil; - } - else { - return rb_ary_entry(ary, key - VM_SVAR_EXTRA_START); - } + if (NIL_P(ary)) { + return Qnil; + } + else { + return rb_ary_entry(ary, key - VM_SVAR_EXTRA_START); + } } } } @@ -582,23 +582,23 @@ lep_svar_set(const rb_execution_context_t *ec, const VALUE *lep, rb_num_t key, V struct vm_svar *svar = lep_svar(ec, lep); if ((VALUE)svar == Qfalse || imemo_type((VALUE)svar) != imemo_svar) { - lep_svar_write(ec, lep, svar = svar_new((VALUE)svar)); + lep_svar_write(ec, lep, svar = svar_new((VALUE)svar)); } switch (key) { case VM_SVAR_LASTLINE: - RB_OBJ_WRITE(svar, &svar->lastline, val); - return; + RB_OBJ_WRITE(svar, &svar->lastline, val); + return; case VM_SVAR_BACKREF: - RB_OBJ_WRITE(svar, &svar->backref, val); - return; + RB_OBJ_WRITE(svar, &svar->backref, val); + return; default: { - VALUE ary = svar->others; + VALUE ary = svar->others; - if (NIL_P(ary)) { - RB_OBJ_WRITE(svar, &svar->others, ary = rb_ary_new()); - } - rb_ary_store(ary, key - VM_SVAR_EXTRA_START, val); + if (NIL_P(ary)) { + RB_OBJ_WRITE(svar, &svar->others, ary = rb_ary_new()); + } + rb_ary_store(ary, key - VM_SVAR_EXTRA_START, val); } } } @@ -609,32 +609,32 @@ vm_getspecial(const rb_execution_context_t *ec, const VALUE *lep, rb_num_t key, VALUE val; if (type == 0) { - val = lep_svar_get(ec, lep, key); + val = lep_svar_get(ec, lep, key); } else { - VALUE backref = lep_svar_get(ec, lep, VM_SVAR_BACKREF); + VALUE backref = lep_svar_get(ec, lep, VM_SVAR_BACKREF); - if (type & 0x01) { - switch (type >> 1) { - case '&': - val = rb_reg_last_match(backref); - break; - case '`': - val = rb_reg_match_pre(backref); - break; - case '\'': - val = rb_reg_match_post(backref); - break; - case '+': - val = rb_reg_match_last(backref); - break; - default: - rb_bug("unexpected back-ref"); - } - } - else { - val = rb_reg_nth_match((int)(type >> 1), backref); - } + if (type & 0x01) { + switch (type >> 1) { + case '&': + val = rb_reg_last_match(backref); + break; + case '`': + val = rb_reg_match_pre(backref); + break; + case '\'': + val = rb_reg_match_post(backref); + break; + case '+': + val = rb_reg_match_last(backref); + break; + default: + rb_bug("unexpected back-ref"); + } + } + else { + val = rb_reg_nth_match((int)(type >> 1), backref); + } } return val; } @@ -651,18 +651,18 @@ check_method_entry(VALUE obj, int can_be_svar) switch (imemo_type(obj)) { case imemo_ment: - return (rb_callable_method_entry_t *)obj; + return (rb_callable_method_entry_t *)obj; case imemo_cref: - return NULL; + return NULL; case imemo_svar: - if (can_be_svar) { - return check_method_entry(((struct vm_svar *)obj)->cref_or_me, FALSE); - } + if (can_be_svar) { + return check_method_entry(((struct vm_svar *)obj)->cref_or_me, FALSE); + } default: #if VM_CHECK_MODE > 0 - rb_bug("check_method_entry: svar should not be there:"); + rb_bug("check_method_entry: svar should not be there:"); #endif - return NULL; + return NULL; } } @@ -673,8 +673,8 @@ rb_vm_frame_method_entry(const rb_control_frame_t *cfp) rb_callable_method_entry_t *me; while (!VM_ENV_LOCAL_P(ep)) { - if ((me = check_method_entry(ep[VM_ENV_DATA_INDEX_ME_CREF], FALSE)) != NULL) return me; - ep = VM_ENV_PREV_EP(ep); + if ((me = check_method_entry(ep[VM_ENV_DATA_INDEX_ME_CREF], FALSE)) != NULL) return me; + ep = VM_ENV_PREV_EP(ep); } return check_method_entry(ep[VM_ENV_DATA_INDEX_ME_CREF], TRUE); @@ -696,9 +696,9 @@ method_entry_cref(const rb_callable_method_entry_t *me) { switch (me->def->type) { case VM_METHOD_TYPE_ISEQ: - return me->def->body.iseq.cref; + return me->def->body.iseq.cref; default: - return NULL; + return NULL; } } @@ -716,18 +716,18 @@ check_cref(VALUE obj, int can_be_svar) switch (imemo_type(obj)) { case imemo_ment: - return method_entry_cref((rb_callable_method_entry_t *)obj); + return method_entry_cref((rb_callable_method_entry_t *)obj); case imemo_cref: - return (rb_cref_t *)obj; + return (rb_cref_t *)obj; case imemo_svar: - if (can_be_svar) { - return check_cref(((struct vm_svar *)obj)->cref_or_me, FALSE); - } + if (can_be_svar) { + return check_cref(((struct vm_svar *)obj)->cref_or_me, FALSE); + } default: #if VM_CHECK_MODE > 0 - rb_bug("check_method_entry: svar should not be there:"); + rb_bug("check_method_entry: svar should not be there:"); #endif - return NULL; + return NULL; } } @@ -737,8 +737,8 @@ vm_env_cref(const VALUE *ep) rb_cref_t *cref; while (!VM_ENV_LOCAL_P(ep)) { - if ((cref = check_cref(ep[VM_ENV_DATA_INDEX_ME_CREF], FALSE)) != NULL) return cref; - ep = VM_ENV_PREV_EP(ep); + if ((cref = check_cref(ep[VM_ENV_DATA_INDEX_ME_CREF], FALSE)) != NULL) return cref; + ep = VM_ENV_PREV_EP(ep); } return check_cref(ep[VM_ENV_DATA_INDEX_ME_CREF], TRUE); @@ -748,14 +748,14 @@ static int is_cref(const VALUE v, int can_be_svar) { if (RB_TYPE_P(v, T_IMEMO)) { - switch (imemo_type(v)) { - case imemo_cref: - return TRUE; - case imemo_svar: - if (can_be_svar) return is_cref(((struct vm_svar *)v)->cref_or_me, FALSE); - default: - break; - } + switch (imemo_type(v)) { + case imemo_cref: + return TRUE; + case imemo_svar: + if (can_be_svar) return is_cref(((struct vm_svar *)v)->cref_or_me, FALSE); + default: + break; + } } return FALSE; } @@ -764,8 +764,8 @@ static int vm_env_cref_by_cref(const VALUE *ep) { while (!VM_ENV_LOCAL_P(ep)) { - if (is_cref(ep[VM_ENV_DATA_INDEX_ME_CREF], FALSE)) return TRUE; - ep = VM_ENV_PREV_EP(ep); + if (is_cref(ep[VM_ENV_DATA_INDEX_ME_CREF], FALSE)) return TRUE; + ep = VM_ENV_PREV_EP(ep); } return is_cref(ep[VM_ENV_DATA_INDEX_ME_CREF], TRUE); } @@ -777,27 +777,27 @@ cref_replace_with_duplicated_cref_each_frame(const VALUE *vptr, int can_be_svar, rb_cref_t *cref, *new_cref; if (RB_TYPE_P(v, T_IMEMO)) { - switch (imemo_type(v)) { - case imemo_cref: - cref = (rb_cref_t *)v; - new_cref = vm_cref_dup(cref); - if (parent) { - RB_OBJ_WRITE(parent, vptr, new_cref); - } - else { - VM_FORCE_WRITE(vptr, (VALUE)new_cref); - } - return (rb_cref_t *)new_cref; - case imemo_svar: - if (can_be_svar) { - return cref_replace_with_duplicated_cref_each_frame(&((struct vm_svar *)v)->cref_or_me, FALSE, v); - } + switch (imemo_type(v)) { + case imemo_cref: + cref = (rb_cref_t *)v; + new_cref = vm_cref_dup(cref); + if (parent) { + RB_OBJ_WRITE(parent, vptr, new_cref); + } + else { + VM_FORCE_WRITE(vptr, (VALUE)new_cref); + } + return (rb_cref_t *)new_cref; + case imemo_svar: + if (can_be_svar) { + return cref_replace_with_duplicated_cref_each_frame(&((struct vm_svar *)v)->cref_or_me, FALSE, v); + } /* fall through */ - case imemo_ment: - rb_bug("cref_replace_with_duplicated_cref_each_frame: unreachable"); - default: - break; - } + case imemo_ment: + rb_bug("cref_replace_with_duplicated_cref_each_frame: unreachable"); + default: + break; + } } return FALSE; } @@ -806,21 +806,21 @@ static rb_cref_t * vm_cref_replace_with_duplicated_cref(const VALUE *ep) { if (vm_env_cref_by_cref(ep)) { - rb_cref_t *cref; - VALUE envval; + rb_cref_t *cref; + VALUE envval; - while (!VM_ENV_LOCAL_P(ep)) { - envval = VM_ENV_ESCAPED_P(ep) ? VM_ENV_ENVVAL(ep) : Qfalse; - if ((cref = cref_replace_with_duplicated_cref_each_frame(&ep[VM_ENV_DATA_INDEX_ME_CREF], FALSE, envval)) != NULL) { - return cref; - } - ep = VM_ENV_PREV_EP(ep); - } - envval = VM_ENV_ESCAPED_P(ep) ? VM_ENV_ENVVAL(ep) : Qfalse; - return cref_replace_with_duplicated_cref_each_frame(&ep[VM_ENV_DATA_INDEX_ME_CREF], TRUE, envval); + while (!VM_ENV_LOCAL_P(ep)) { + envval = VM_ENV_ESCAPED_P(ep) ? VM_ENV_ENVVAL(ep) : Qfalse; + if ((cref = cref_replace_with_duplicated_cref_each_frame(&ep[VM_ENV_DATA_INDEX_ME_CREF], FALSE, envval)) != NULL) { + return cref; + } + ep = VM_ENV_PREV_EP(ep); + } + envval = VM_ENV_ESCAPED_P(ep) ? VM_ENV_ENVVAL(ep) : Qfalse; + return cref_replace_with_duplicated_cref_each_frame(&ep[VM_ENV_DATA_INDEX_ME_CREF], TRUE, envval); } else { - rb_bug("vm_cref_dup: unreachable"); + rb_bug("vm_cref_dup: unreachable"); } } @@ -830,7 +830,7 @@ vm_get_cref(const VALUE *ep) rb_cref_t *cref = vm_env_cref(ep); if (cref != NULL) { - return cref; + return cref; } else { rb_bug("vm_get_cref: unreachable"); @@ -864,8 +864,8 @@ vm_get_const_key_cref(const VALUE *ep) if (FL_TEST(CREF_CLASS(cref), FL_SINGLETON) || FL_TEST(CREF_CLASS(cref), RCLASS_CLONED)) { return key_cref; - } - cref = CREF_NEXT(cref); + } + cref = CREF_NEXT(cref); } /* does not include singleton class */ @@ -878,15 +878,15 @@ rb_vm_rewrite_cref(rb_cref_t *cref, VALUE old_klass, VALUE new_klass, rb_cref_t rb_cref_t *new_cref; while (cref) { - if (CREF_CLASS(cref) == old_klass) { - new_cref = vm_cref_new_use_prev(new_klass, METHOD_VISI_UNDEF, FALSE, cref, FALSE); - *new_cref_ptr = new_cref; - return; - } - new_cref = vm_cref_new_use_prev(CREF_CLASS(cref), METHOD_VISI_UNDEF, FALSE, cref, FALSE); - cref = CREF_NEXT(cref); - *new_cref_ptr = new_cref; - new_cref_ptr = &new_cref->next; + if (CREF_CLASS(cref) == old_klass) { + new_cref = vm_cref_new_use_prev(new_klass, METHOD_VISI_UNDEF, FALSE, cref, FALSE); + *new_cref_ptr = new_cref; + return; + } + new_cref = vm_cref_new_use_prev(CREF_CLASS(cref), METHOD_VISI_UNDEF, FALSE, cref, FALSE); + cref = CREF_NEXT(cref); + *new_cref_ptr = new_cref; + new_cref_ptr = &new_cref->next; } *new_cref_ptr = NULL; } @@ -897,14 +897,14 @@ vm_cref_push(const rb_execution_context_t *ec, VALUE klass, const VALUE *ep, int rb_cref_t *prev_cref = NULL; if (ep) { - prev_cref = vm_env_cref(ep); + prev_cref = vm_env_cref(ep); } else { - rb_control_frame_t *cfp = vm_get_ruby_level_caller_cfp(ec, ec->cfp); + rb_control_frame_t *cfp = vm_get_ruby_level_caller_cfp(ec, ec->cfp); - if (cfp) { - prev_cref = vm_env_cref(cfp->ep); - } + if (cfp) { + prev_cref = vm_env_cref(cfp->ep); + } } return vm_cref_new(klass, METHOD_VISI_PUBLIC, FALSE, prev_cref, pushed_by_eval, singleton); @@ -937,7 +937,7 @@ static inline void vm_check_if_namespace(VALUE klass) { if (!RB_TYPE_P(klass, T_CLASS) && !RB_TYPE_P(klass, T_MODULE)) { - rb_raise(rb_eTypeError, "%+"PRIsVALUE" is not a class/module", klass); + rb_raise(rb_eTypeError, "%+"PRIsVALUE" is not a class/module", klass); } } @@ -945,7 +945,7 @@ static inline void vm_ensure_not_refinement_module(VALUE self) { if (RB_TYPE_P(self, T_MODULE) && FL_TEST(self, RMODULE_IS_REFINEMENT)) { - rb_warn("not defined at the refinement, but at the outer class/module"); + rb_warn("not defined at the refinement, but at the outer class/module"); } } @@ -962,43 +962,43 @@ vm_get_ev_const(rb_execution_context_t *ec, VALUE orig_klass, ID id, bool allow_ VALUE val; if (NIL_P(orig_klass) && allow_nil) { - /* in current lexical scope */ + /* in current lexical scope */ const rb_cref_t *root_cref = vm_get_cref(ec->cfp->ep); - const rb_cref_t *cref; - VALUE klass = Qnil; + const rb_cref_t *cref; + VALUE klass = Qnil; - while (root_cref && CREF_PUSHED_BY_EVAL(root_cref)) { - root_cref = CREF_NEXT(root_cref); - } - cref = root_cref; - while (cref && CREF_NEXT(cref)) { - if (CREF_PUSHED_BY_EVAL(cref)) { - klass = Qnil; - } - else { - klass = CREF_CLASS(cref); - } - cref = CREF_NEXT(cref); + while (root_cref && CREF_PUSHED_BY_EVAL(root_cref)) { + root_cref = CREF_NEXT(root_cref); + } + cref = root_cref; + while (cref && CREF_NEXT(cref)) { + if (CREF_PUSHED_BY_EVAL(cref)) { + klass = Qnil; + } + else { + klass = CREF_CLASS(cref); + } + cref = CREF_NEXT(cref); - if (!NIL_P(klass)) { - VALUE av, am = 0; - rb_const_entry_t *ce; - search_continue: - if ((ce = rb_const_lookup(klass, id))) { - rb_const_warn_if_deprecated(ce, klass, id); - val = ce->value; - if (val == Qundef) { - if (am == klass) break; - am = klass; - if (is_defined) return 1; - if (rb_autoloading_value(klass, id, &av, NULL)) return av; - rb_autoload_load(klass, id); - goto search_continue; - } - else { - if (is_defined) { - return 1; - } + if (!NIL_P(klass)) { + VALUE av, am = 0; + rb_const_entry_t *ce; + search_continue: + if ((ce = rb_const_lookup(klass, id))) { + rb_const_warn_if_deprecated(ce, klass, id); + val = ce->value; + if (val == Qundef) { + if (am == klass) break; + am = klass; + if (is_defined) return 1; + if (rb_autoloading_value(klass, id, &av, NULL)) return av; + rb_autoload_load(klass, id); + goto search_continue; + } + else { + if (is_defined) { + return 1; + } else { if (UNLIKELY(!rb_ractor_main_p())) { if (!rb_ractor_shareable_p(val)) { @@ -1006,36 +1006,36 @@ vm_get_ev_const(rb_execution_context_t *ec, VALUE orig_klass, ID id, bool allow_ "can not access non-shareable objects in constant %"PRIsVALUE"::%s by non-main ractor.", rb_class_path(klass), rb_id2name(id)); } } - return val; - } - } - } - } - } + return val; + } + } + } + } + } - /* search self */ - if (root_cref && !NIL_P(CREF_CLASS(root_cref))) { - klass = vm_get_iclass(ec->cfp, CREF_CLASS(root_cref)); - } - else { - klass = CLASS_OF(ec->cfp->self); - } + /* search self */ + if (root_cref && !NIL_P(CREF_CLASS(root_cref))) { + klass = vm_get_iclass(ec->cfp, CREF_CLASS(root_cref)); + } + else { + klass = CLASS_OF(ec->cfp->self); + } - if (is_defined) { - return rb_const_defined(klass, id); - } - else { - return rb_const_get(klass, id); - } + if (is_defined) { + return rb_const_defined(klass, id); + } + else { + return rb_const_get(klass, id); + } } else { - vm_check_if_namespace(orig_klass); - if (is_defined) { - return rb_public_const_defined_from(orig_klass, id); - } - else { - return rb_public_const_get_from(orig_klass, id); - } + vm_check_if_namespace(orig_klass); + if (is_defined) { + return rb_public_const_defined_from(orig_klass, id); + } + else { + return rb_public_const_get_from(orig_klass, id); + } } } @@ -1045,13 +1045,13 @@ vm_get_cvar_base(const rb_cref_t *cref, const rb_control_frame_t *cfp, int top_l VALUE klass; if (!cref) { - rb_bug("vm_get_cvar_base: no cref"); + rb_bug("vm_get_cvar_base: no cref"); } while (CREF_NEXT(cref) && - (NIL_P(CREF_CLASS(cref)) || FL_TEST(CREF_CLASS(cref), FL_SINGLETON) || - CREF_PUSHED_BY_EVAL(cref) || CREF_SINGLETON(cref))) { - cref = CREF_NEXT(cref); + (NIL_P(CREF_CLASS(cref)) || FL_TEST(CREF_CLASS(cref), FL_SINGLETON) || + CREF_PUSHED_BY_EVAL(cref) || CREF_SINGLETON(cref))) { + cref = CREF_NEXT(cref); } if (top_level_raise && !CREF_NEXT(cref)) { rb_raise(rb_eRuntimeError, "class variable access from toplevel"); @@ -1060,7 +1060,7 @@ vm_get_cvar_base(const rb_cref_t *cref, const rb_control_frame_t *cfp, int top_l klass = vm_get_iclass(cfp, CREF_CLASS(cref)); if (NIL_P(klass)) { - rb_raise(rb_eTypeError, "no class variables available"); + rb_raise(rb_eTypeError, "no class variables available"); } return klass; } @@ -1239,8 +1239,8 @@ vm_setivar(VALUE obj, ID id, VALUE val, const rb_iseq_t *iseq, IVC ic, const str VM_ASSERT(!rb_ractor_shareable_p(obj)); - if (LIKELY( - (!is_attr && RB_DEBUG_COUNTER_INC_UNLESS(ivar_set_ic_miss_serial, vm_ic_entry_p(ic) && ic->entry->class_serial == RCLASS_SERIAL(RBASIC(obj)->klass))) || + if (LIKELY( + (!is_attr && RB_DEBUG_COUNTER_INC_UNLESS(ivar_set_ic_miss_serial, vm_ic_entry_p(ic) && ic->entry->class_serial == RCLASS_SERIAL(RBASIC(obj)->klass))) || ( is_attr && RB_DEBUG_COUNTER_INC_UNLESS(ivar_set_ic_miss_unset, vm_cc_attr_index_p(cc))))) { uint32_t index = !is_attr ? vm_ic_entry_index(ic) : vm_cc_attr_index(cc); @@ -1251,10 +1251,10 @@ vm_setivar(VALUE obj, ID id, VALUE val, const rb_iseq_t *iseq, IVC ic, const str RB_OBJ_WRITE(obj, &ptr[index], val); RB_DEBUG_COUNTER_INC(ivar_set_ic_hit); return val; /* inline cache hit */ - } + } } else { - RB_DEBUG_COUNTER_INC(ivar_set_ic_miss_noobject); + RB_DEBUG_COUNTER_INC(ivar_set_ic_miss_noobject); } #endif /* OPT_IC_FOR_IVAR */ if (is_attr) { @@ -1394,16 +1394,16 @@ vm_throw_continue(const rb_execution_context_t *ec, VALUE err) /* continue throw */ if (FIXNUM_P(err)) { - ec->tag->state = FIX2INT(err); + ec->tag->state = FIX2INT(err); } else if (SYMBOL_P(err)) { - ec->tag->state = TAG_THROW; + ec->tag->state = TAG_THROW; } else if (THROW_DATA_P(err)) { - ec->tag->state = THROW_DATA_STATE((struct vm_throw_data *)err); + ec->tag->state = THROW_DATA_STATE((struct vm_throw_data *)err); } else { - ec->tag->state = TAG_RAISE; + ec->tag->state = TAG_RAISE; } return err; } @@ -1416,79 +1416,79 @@ vm_throw_start(const rb_execution_context_t *ec, rb_control_frame_t *const reg_c const rb_control_frame_t * const eocfp = RUBY_VM_END_CONTROL_FRAME(ec); /* end of control frame pointer */ if (flag != 0) { - /* do nothing */ + /* do nothing */ } else if (state == TAG_BREAK) { - int is_orphan = 1; - const VALUE *ep = GET_EP(); - const rb_iseq_t *base_iseq = GET_ISEQ(); - escape_cfp = reg_cfp; + int is_orphan = 1; + const VALUE *ep = GET_EP(); + const rb_iseq_t *base_iseq = GET_ISEQ(); + escape_cfp = reg_cfp; while (ISEQ_BODY(base_iseq)->type != ISEQ_TYPE_BLOCK) { if (ISEQ_BODY(escape_cfp->iseq)->type == ISEQ_TYPE_CLASS) { - escape_cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(escape_cfp); - ep = escape_cfp->ep; - base_iseq = escape_cfp->iseq; - } - else { - ep = VM_ENV_PREV_EP(ep); + escape_cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(escape_cfp); + ep = escape_cfp->ep; + base_iseq = escape_cfp->iseq; + } + else { + ep = VM_ENV_PREV_EP(ep); base_iseq = ISEQ_BODY(base_iseq)->parent_iseq; - escape_cfp = rb_vm_search_cf_from_ep(ec, escape_cfp, ep); - VM_ASSERT(escape_cfp->iseq == base_iseq); - } - } + escape_cfp = rb_vm_search_cf_from_ep(ec, escape_cfp, ep); + VM_ASSERT(escape_cfp->iseq == base_iseq); + } + } - if (VM_FRAME_LAMBDA_P(escape_cfp)) { - /* lambda{... break ...} */ - is_orphan = 0; - state = TAG_RETURN; - } - else { - ep = VM_ENV_PREV_EP(ep); + if (VM_FRAME_LAMBDA_P(escape_cfp)) { + /* lambda{... break ...} */ + is_orphan = 0; + state = TAG_RETURN; + } + else { + ep = VM_ENV_PREV_EP(ep); - while (escape_cfp < eocfp) { - if (escape_cfp->ep == ep) { - const rb_iseq_t *const iseq = escape_cfp->iseq; + while (escape_cfp < eocfp) { + if (escape_cfp->ep == ep) { + const rb_iseq_t *const iseq = escape_cfp->iseq; const VALUE epc = escape_cfp->pc - ISEQ_BODY(iseq)->iseq_encoded; const struct iseq_catch_table *const ct = ISEQ_BODY(iseq)->catch_table; - unsigned int i; + unsigned int i; - if (!ct) break; - for (i=0; i < ct->size; i++) { - const struct iseq_catch_table_entry *const entry = - UNALIGNED_MEMBER_PTR(ct, entries[i]); + if (!ct) break; + for (i=0; i < ct->size; i++) { + const struct iseq_catch_table_entry *const entry = + UNALIGNED_MEMBER_PTR(ct, entries[i]); - if (entry->type == CATCH_TYPE_BREAK && - entry->iseq == base_iseq && - entry->start < epc && entry->end >= epc) { - if (entry->cont == epc) { /* found! */ - is_orphan = 0; - } - break; - } - } - break; - } + if (entry->type == CATCH_TYPE_BREAK && + entry->iseq == base_iseq && + entry->start < epc && entry->end >= epc) { + if (entry->cont == epc) { /* found! */ + is_orphan = 0; + } + break; + } + } + break; + } - escape_cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(escape_cfp); - } - } + escape_cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(escape_cfp); + } + } - if (is_orphan) { - rb_vm_localjump_error("break from proc-closure", throwobj, TAG_BREAK); - } + if (is_orphan) { + rb_vm_localjump_error("break from proc-closure", throwobj, TAG_BREAK); + } } else if (state == TAG_RETRY) { - const VALUE *ep = VM_ENV_PREV_EP(GET_EP()); + const VALUE *ep = VM_ENV_PREV_EP(GET_EP()); - escape_cfp = rb_vm_search_cf_from_ep(ec, reg_cfp, ep); + escape_cfp = rb_vm_search_cf_from_ep(ec, reg_cfp, ep); } else if (state == TAG_RETURN) { - const VALUE *current_ep = GET_EP(); + const VALUE *current_ep = GET_EP(); const VALUE *target_ep = NULL, *target_lep, *ep = current_ep; - int in_class_frame = 0; - int toplevel = 1; - escape_cfp = reg_cfp; + int in_class_frame = 0; + int toplevel = 1; + escape_cfp = reg_cfp; // find target_lep, target_ep while (!VM_ENV_LOCAL_P(ep)) { @@ -1502,45 +1502,45 @@ vm_throw_start(const rb_execution_context_t *ec, rb_control_frame_t *const reg_c while (escape_cfp < eocfp) { const VALUE *lep = VM_CF_LEP(escape_cfp); - if (!target_lep) { - target_lep = lep; - } + if (!target_lep) { + target_lep = lep; + } - if (lep == target_lep && - VM_FRAME_RUBYFRAME_P(escape_cfp) && + if (lep == target_lep && + VM_FRAME_RUBYFRAME_P(escape_cfp) && ISEQ_BODY(escape_cfp->iseq)->type == ISEQ_TYPE_CLASS) { - in_class_frame = 1; - target_lep = 0; - } + in_class_frame = 1; + target_lep = 0; + } - if (lep == target_lep) { - if (VM_FRAME_LAMBDA_P(escape_cfp)) { - toplevel = 0; - if (in_class_frame) { - /* lambda {class A; ... return ...; end} */ + if (lep == target_lep) { + if (VM_FRAME_LAMBDA_P(escape_cfp)) { + toplevel = 0; + if (in_class_frame) { + /* lambda {class A; ... return ...; end} */ goto valid_return; - } - else { - const VALUE *tep = current_ep; + } + else { + const VALUE *tep = current_ep; - while (target_lep != tep) { - if (escape_cfp->ep == tep) { - /* in lambda */ + while (target_lep != tep) { + if (escape_cfp->ep == tep) { + /* in lambda */ if (tep == target_ep) { goto valid_return; } else { goto unexpected_return; } - } - tep = VM_ENV_PREV_EP(tep); - } - } - } - else if (VM_FRAME_RUBYFRAME_P(escape_cfp)) { + } + tep = VM_ENV_PREV_EP(tep); + } + } + } + else if (VM_FRAME_RUBYFRAME_P(escape_cfp)) { switch (ISEQ_BODY(escape_cfp->iseq)->type) { - case ISEQ_TYPE_TOP: - case ISEQ_TYPE_MAIN: + case ISEQ_TYPE_TOP: + case ISEQ_TYPE_MAIN: if (toplevel) { if (in_class_frame) goto unexpected_return; if (target_ep == NULL) { @@ -1550,16 +1550,16 @@ vm_throw_start(const rb_execution_context_t *ec, rb_control_frame_t *const reg_c goto unexpected_return; } } - break; - case ISEQ_TYPE_EVAL: - case ISEQ_TYPE_CLASS: - toplevel = 0; - break; - default: - break; - } - } - } + break; + case ISEQ_TYPE_EVAL: + case ISEQ_TYPE_CLASS: + toplevel = 0; + break; + default: + break; + } + } + } if (escape_cfp->ep == target_lep && ISEQ_BODY(escape_cfp->iseq)->type == ISEQ_TYPE_METHOD) { if (target_ep == NULL) { @@ -1568,18 +1568,18 @@ vm_throw_start(const rb_execution_context_t *ec, rb_control_frame_t *const reg_c else { goto unexpected_return; } - } + } - escape_cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(escape_cfp); - } + escape_cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(escape_cfp); + } unexpected_return:; - rb_vm_localjump_error("unexpected return", throwobj, TAG_RETURN); + rb_vm_localjump_error("unexpected return", throwobj, TAG_RETURN); valid_return:; - /* do nothing */ + /* do nothing */ } else { - rb_bug("isns(throw): unsupported throw type"); + rb_bug("isns(throw): unsupported throw type"); } ec->tag->state = state; @@ -1588,7 +1588,7 @@ vm_throw_start(const rb_execution_context_t *ec, rb_control_frame_t *const reg_c static VALUE vm_throw(const rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, - rb_num_t throw_state, VALUE throwobj) + rb_num_t throw_state, VALUE throwobj) { const int state = (int)(throw_state & VM_THROW_STATE_MASK); const int flag = (int)(throw_state & VM_THROW_NO_ESCAPE_FLAG); @@ -1597,7 +1597,7 @@ vm_throw(const rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, return vm_throw_start(ec, reg_cfp, state, flag, throwobj); } else { - return vm_throw_continue(ec, throwobj); + return vm_throw_continue(ec, throwobj); } } @@ -1612,57 +1612,57 @@ vm_expandarray(VALUE *sp, VALUE ary, rb_num_t num, int flag) const VALUE obj = ary; if (!RB_TYPE_P(ary, T_ARRAY) && NIL_P(ary = rb_check_array_type(ary))) { - ary = obj; - ptr = &ary; - len = 1; + ary = obj; + ptr = &ary; + len = 1; } else { ptr = RARRAY_CONST_PTR_TRANSIENT(ary); - len = (rb_num_t)RARRAY_LEN(ary); + len = (rb_num_t)RARRAY_LEN(ary); } if (space_size == 0) { /* no space left on stack */ } else if (flag & 0x02) { - /* post: ..., nil ,ary[-1], ..., ary[0..-num] # top */ - rb_num_t i = 0, j; + /* post: ..., nil ,ary[-1], ..., ary[0..-num] # top */ + rb_num_t i = 0, j; - if (len < num) { - for (i=0; i len) { - *bptr = rb_ary_new(); - } - else { - *bptr = rb_ary_new4(len - num, ptr + num); - } - } + for (i=0; i len) { + *bptr = rb_ary_new(); + } + else { + *bptr = rb_ary_new4(len - num, ptr + num); + } + } } RB_GC_GUARD(ary); } @@ -2132,17 +2132,17 @@ check_match(rb_execution_context_t *ec, VALUE pattern, VALUE target, enum vm_che { switch (type) { case VM_CHECKMATCH_TYPE_WHEN: - return pattern; + return pattern; case VM_CHECKMATCH_TYPE_RESCUE: - if (!rb_obj_is_kind_of(pattern, rb_cModule)) { - rb_raise(rb_eTypeError, "class or module required for rescue clause"); - } - /* fall through */ + if (!rb_obj_is_kind_of(pattern, rb_cModule)) { + rb_raise(rb_eTypeError, "class or module required for rescue clause"); + } + /* fall through */ case VM_CHECKMATCH_TYPE_CASE: { return rb_vm_call_with_refinements(ec, pattern, idEqq, 1, &target, RB_NO_KEYWORDS); } default: - rb_bug("check_match: unreachable"); + rb_bug("check_match: unreachable"); } } @@ -2190,21 +2190,21 @@ vm_base_ptr(const rb_control_frame_t *cfp) if (cfp->iseq && VM_FRAME_RUBYFRAME_P(cfp)) { VALUE *bp = prev_cfp->sp + ISEQ_BODY(cfp->iseq)->local_table_size + VM_ENV_DATA_SIZE; if (ISEQ_BODY(cfp->iseq)->type == ISEQ_TYPE_METHOD) { - /* adjust `self' */ - bp += 1; - } + /* adjust `self' */ + bp += 1; + } #if VM_DEBUG_BP_CHECK - if (bp != cfp->bp_check) { - ruby_debug_printf("bp_check: %ld, bp: %ld\n", - (long)(cfp->bp_check - GET_EC()->vm_stack), - (long)(bp - GET_EC()->vm_stack)); - rb_bug("vm_base_ptr: unreachable"); - } + if (bp != cfp->bp_check) { + ruby_debug_printf("bp_check: %ld, bp: %ld\n", + (long)(cfp->bp_check - GET_EC()->vm_stack), + (long)(bp - GET_EC()->vm_stack)); + rb_bug("vm_base_ptr: unreachable"); + } #endif - return bp; + return bp; } else { - return NULL; + return NULL; } #else return cfp->__bp__; @@ -2479,7 +2479,7 @@ vm_call_iseq_setup_kwparm_nokwarg(rb_execution_context_t *ec, rb_control_frame_t static inline int vm_callee_setup_arg(rb_execution_context_t *ec, struct rb_calling_info *calling, - const rb_iseq_t *iseq, VALUE *argv, int param_size, int local_size) + const rb_iseq_t *iseq, VALUE *argv, int param_size, int local_size) { const struct rb_callinfo *ci = calling->ci; const struct rb_callcache *cc = calling->cc; @@ -2632,15 +2632,15 @@ vm_call_iseq_setup_tailcall(rb_execution_context_t *ec, rb_control_frame_t *cfp, VALUE finish_flag = VM_FRAME_FINISHED_P(cfp) ? VM_FRAME_FLAG_FINISH : 0; if (VM_BH_FROM_CFP_P(calling->block_handler, cfp)) { - struct rb_captured_block *dst_captured = VM_CFP_TO_CAPTURED_BLOCK(RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp)); - const struct rb_captured_block *src_captured = VM_BH_TO_CAPT_BLOCK(calling->block_handler); - dst_captured->code.val = src_captured->code.val; - if (VM_BH_ISEQ_BLOCK_P(calling->block_handler)) { - calling->block_handler = VM_BH_FROM_ISEQ_BLOCK(dst_captured); - } - else { - calling->block_handler = VM_BH_FROM_IFUNC_BLOCK(dst_captured); - } + struct rb_captured_block *dst_captured = VM_CFP_TO_CAPTURED_BLOCK(RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp)); + const struct rb_captured_block *src_captured = VM_BH_TO_CAPT_BLOCK(calling->block_handler); + dst_captured->code.val = src_captured->code.val; + if (VM_BH_ISEQ_BLOCK_P(calling->block_handler)) { + calling->block_handler = VM_BH_FROM_ISEQ_BLOCK(dst_captured); + } + else { + calling->block_handler = VM_BH_FROM_IFUNC_BLOCK(dst_captured); + } } vm_pop_frame(ec, cfp, cfp->ep); @@ -2654,7 +2654,7 @@ vm_call_iseq_setup_tailcall(rb_execution_context_t *ec, rb_control_frame_t *cfp, /* copy arguments */ for (i=0; i < ISEQ_BODY(iseq)->param.size; i++) { - *sp++ = src_argv[i]; + *sp++ = src_argv[i]; } vm_push_frame(ec, iseq, VM_FRAME_MAGIC_METHOD | VM_ENV_FLAG_LOCAL | finish_flag, @@ -2948,8 +2948,8 @@ vm_cfp_consistent_p(rb_execution_context_t *ec, const rb_control_frame_t *reg_cf const int ov_flags = RAISED_STACKOVERFLOW; if (LIKELY(reg_cfp == ec->cfp + 1)) return TRUE; if (rb_ec_raised_p(ec, ov_flags)) { - rb_ec_raised_reset(ec, ov_flags); - return TRUE; + rb_ec_raised_reset(ec, ov_flags); + return TRUE; } return FALSE; } @@ -2966,21 +2966,21 @@ vm_method_cfunc_entry(const rb_callable_method_entry_t *me) switch (me->def->type) { case VM_METHOD_TYPE_CFUNC: case VM_METHOD_TYPE_NOTIMPLEMENTED: - break; + break; # define METHOD_BUG(t) case VM_METHOD_TYPE_##t: rb_bug("wrong method type: " #t) - METHOD_BUG(ISEQ); - METHOD_BUG(ATTRSET); - METHOD_BUG(IVAR); - METHOD_BUG(BMETHOD); - METHOD_BUG(ZSUPER); - METHOD_BUG(UNDEF); - METHOD_BUG(OPTIMIZED); - METHOD_BUG(MISSING); - METHOD_BUG(REFINED); - METHOD_BUG(ALIAS); + METHOD_BUG(ISEQ); + METHOD_BUG(ATTRSET); + METHOD_BUG(IVAR); + METHOD_BUG(BMETHOD); + METHOD_BUG(ZSUPER); + METHOD_BUG(UNDEF); + METHOD_BUG(OPTIMIZED); + METHOD_BUG(MISSING); + METHOD_BUG(REFINED); + METHOD_BUG(ALIAS); # undef METHOD_BUG default: - rb_bug("wrong method type: %d", me->def->type); + rb_bug("wrong method type: %d", me->def->type); } #endif return UNALIGNED_MEMBER_PTR(me->def, body.cfunc); @@ -3011,8 +3011,8 @@ vm_call_cfunc_with_frame(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_CALL, recv, me->def->original_id, vm_ci_mid(ci), me->owner, Qundef); vm_push_frame(ec, NULL, frame_type, recv, - block_handler, (VALUE)me, - 0, ec->cfp->sp, 0, 0); + block_handler, (VALUE)me, + 0, ec->cfp->sp, 0, 0); if (len >= 0) rb_check_arity(argc, len, len); @@ -3117,11 +3117,11 @@ rb_find_defined_class_by_owner(VALUE current_class, VALUE target_owner) } while (RTEST(klass)) { - VALUE owner = RB_TYPE_P(klass, T_ICLASS) ? RBASIC_CLASS(klass) : klass; - if (owner == target_owner) { - return klass; - } - klass = RCLASS_SUPER(klass); + VALUE owner = RB_TYPE_P(klass, T_ICLASS) ? RBASIC_CLASS(klass) : klass; + if (owner == target_owner) { + return klass; + } + klass = RCLASS_SUPER(klass); } return current_class; /* maybe module function */ @@ -3135,20 +3135,20 @@ aliased_callable_method_entry(const rb_callable_method_entry_t *me) if (orig_me->defined_class == 0) { VALUE defined_class = rb_find_defined_class_by_owner(me->defined_class, orig_me->owner); - VM_ASSERT(RB_TYPE_P(orig_me->owner, T_MODULE)); - cme = rb_method_entry_complement_defined_class(orig_me, me->called_id, defined_class); + VM_ASSERT(RB_TYPE_P(orig_me->owner, T_MODULE)); + cme = rb_method_entry_complement_defined_class(orig_me, me->called_id, defined_class); - if (me->def->alias_count + me->def->complemented_count == 0) { - RB_OBJ_WRITE(me, &me->def->body.alias.original_me, cme); - } - else { - rb_method_definition_t *def = - rb_method_definition_create(VM_METHOD_TYPE_ALIAS, me->def->original_id); - rb_method_definition_set((rb_method_entry_t *)me, def, (void *)cme); - } + if (me->def->alias_count + me->def->complemented_count == 0) { + RB_OBJ_WRITE(me, &me->def->body.alias.original_me, cme); + } + else { + rb_method_definition_t *def = + rb_method_definition_create(VM_METHOD_TYPE_ALIAS, me->def->original_id); + rb_method_definition_set((rb_method_entry_t *)me, def, (void *)cme); + } } else { - cme = (const rb_callable_method_entry_t *)orig_me; + cme = (const rb_callable_method_entry_t *)orig_me; } VM_ASSERT(callable_method_entry_p(cme)); @@ -3259,7 +3259,7 @@ vm_call_opt_send(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct i = calling->argc - 1; if (calling->argc == 0) { - rb_raise(rb_eArgError, "no method name given"); + rb_raise(rb_eArgError, "no method name given"); } else { sym = TOPN(i); @@ -3276,12 +3276,12 @@ vm_call_opt_send(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct * | recv | | recv | 3 * --+------+--------+------+------ */ - /* shift arguments */ - if (i > 0) { - MEMMOVE(&TOPN(i), &TOPN(i-1), VALUE, i); - } - calling->argc -= 1; - DEC_SP(1); + /* shift arguments */ + if (i > 0) { + MEMMOVE(&TOPN(i), &TOPN(i-1), VALUE, i); + } + calling->argc -= 1; + DEC_SP(1); return vm_call_symbol(ec, reg_cfp, calling, calling->ci, sym); } @@ -3306,7 +3306,7 @@ vm_call_method_missing_body(rb_execution_context_t *ec, rb_control_frame_t *reg_ CHECK_VM_STACK_OVERFLOW(reg_cfp, 1); vm_check_canary(ec, reg_cfp->sp); if (argc > 1) { - MEMMOVE(argv+1, argv, VALUE, argc-1); + MEMMOVE(argv+1, argv, VALUE, argc-1); } argv[0] = ID2SYM(vm_ci_mid(orig_ci)); INC_SP(1); @@ -3348,7 +3348,7 @@ static inline VALUE find_refinement(VALUE refinements, VALUE klass) { if (NIL_P(refinements)) { - return Qnil; + return Qnil; } return rb_hash_lookup(refinements, klass); } @@ -3362,13 +3362,13 @@ current_method_entry(const rb_execution_context_t *ec, rb_control_frame_t *cfp) if (cfp->iseq && ISEQ_BODY(cfp->iseq)->type == ISEQ_TYPE_BLOCK) { const rb_iseq_t *local_iseq = ISEQ_BODY(cfp->iseq)->local_iseq; - do { - cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); - if (RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(ec, cfp)) { - /* TODO: orphan block */ - return top_cfp; - } - } while (cfp->iseq != local_iseq); + do { + cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); + if (RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(ec, cfp)) { + /* TODO: orphan block */ + return top_cfp; + } + } while (cfp->iseq != local_iseq); } return cfp; } @@ -3380,17 +3380,17 @@ refined_method_callable_without_refinement(const rb_callable_method_entry_t *me) const rb_callable_method_entry_t *cme; if (orig_me->defined_class == 0) { - cme = NULL; - rb_notimplement(); + cme = NULL; + rb_notimplement(); } else { - cme = (const rb_callable_method_entry_t *)orig_me; + cme = (const rb_callable_method_entry_t *)orig_me; } VM_ASSERT(callable_method_entry_p(cme)); if (UNDEFINED_METHOD_ENTRY_P(cme)) { - cme = NULL; + cme = NULL; } return cme; @@ -3461,12 +3461,12 @@ vm_call_refined(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_c static inline VALUE vm_invoke_block(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling, const struct rb_callinfo *ci, bool is_lambda, VALUE block_handler); NOINLINE(static VALUE - vm_invoke_block_opt_call(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, - struct rb_calling_info *calling, const struct rb_callinfo *ci, VALUE block_handler)); + vm_invoke_block_opt_call(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, + struct rb_calling_info *calling, const struct rb_callinfo *ci, VALUE block_handler)); static VALUE vm_invoke_block_opt_call(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, - struct rb_calling_info *calling, const struct rb_callinfo *ci, VALUE block_handler) + struct rb_calling_info *calling, const struct rb_callinfo *ci, VALUE block_handler) { int argc = calling->argc; @@ -3496,10 +3496,10 @@ vm_call_opt_block_call(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, const struct rb_callinfo *ci = calling->ci; if (BASIC_OP_UNREDEFINED_P(BOP_CALL, PROC_REDEFINED_OP_FLAG)) { - return vm_invoke_block_opt_call(ec, reg_cfp, calling, ci, block_handler); + return vm_invoke_block_opt_call(ec, reg_cfp, calling, ci, block_handler); } else { - calling->recv = rb_vm_bh_to_procval(ec, block_handler); + calling->recv = rb_vm_bh_to_procval(ec, block_handler); calling->cc = rb_vm_search_method_slowpath(ci, CLASS_OF(calling->recv)); return vm_call_general(ec, reg_cfp, calling); } @@ -3625,8 +3625,8 @@ vm_call_method_each_type(rb_execution_context_t *ec, rb_control_frame_t *cfp, st CALLER_SETUP_ARG(cfp, calling, ci); CALLER_REMOVE_EMPTY_KW_SPLAT(cfp, calling, ci); - rb_check_arity(calling->argc, 1, 1); - vm_cc_attr_index_initialize(cc); + rb_check_arity(calling->argc, 1, 1); + vm_cc_attr_index_initialize(cc); const unsigned int aset_mask = (VM_CALL_ARGS_SPLAT | VM_CALL_KW_SPLAT | VM_CALL_KWARG); VM_CALL_METHOD_ATTR(v, vm_call_attrset(ec, cfp, calling), @@ -3636,8 +3636,8 @@ vm_call_method_each_type(rb_execution_context_t *ec, rb_control_frame_t *cfp, st case VM_METHOD_TYPE_IVAR: CALLER_SETUP_ARG(cfp, calling, ci); CALLER_REMOVE_EMPTY_KW_SPLAT(cfp, calling, ci); - rb_check_arity(calling->argc, 0, 0); - vm_cc_attr_index_initialize(cc); + rb_check_arity(calling->argc, 0, 0); + vm_cc_attr_index_initialize(cc); const unsigned int ivar_mask = (VM_CALL_ARGS_SPLAT | VM_CALL_KW_SPLAT); VM_CALL_METHOD_ATTR(v, vm_call_ivar(ec, cfp, calling), @@ -3661,7 +3661,7 @@ vm_call_method_each_type(rb_execution_context_t *ec, rb_control_frame_t *cfp, st return vm_call_optimized(ec, cfp, calling, ci, cc); case VM_METHOD_TYPE_UNDEF: - break; + break; case VM_METHOD_TYPE_ZSUPER: return vm_call_zsuper(ec, cfp, calling, RCLASS_ORIGIN(vm_cc_cme(cc)->defined_class)); @@ -3685,9 +3685,9 @@ vm_call_method_nome(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct const int stat = ci_missing_reason(ci); if (vm_ci_mid(ci) == idMethodMissing) { - rb_control_frame_t *reg_cfp = cfp; - VALUE *argv = STACK_ADDR_FROM_TOP(calling->argc); - vm_raise_method_missing(ec, calling->argc, argv, calling->recv, stat); + rb_control_frame_t *reg_cfp = cfp; + VALUE *argv = STACK_ADDR_FROM_TOP(calling->argc); + vm_raise_method_missing(ec, calling->argc, argv, calling->recv, stat); } else { return vm_call_method_missing_body(ec, cfp, calling, ci, stat); @@ -3716,42 +3716,42 @@ vm_call_method(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_ca VM_ASSERT(callable_method_entry_p(vm_cc_cme(cc))); if (vm_cc_cme(cc) != NULL) { - switch (METHOD_ENTRY_VISI(vm_cc_cme(cc))) { - case METHOD_VISI_PUBLIC: /* likely */ + switch (METHOD_ENTRY_VISI(vm_cc_cme(cc))) { + case METHOD_VISI_PUBLIC: /* likely */ return vm_call_method_each_type(ec, cfp, calling); - case METHOD_VISI_PRIVATE: - if (!(vm_ci_flag(ci) & VM_CALL_FCALL)) { - enum method_missing_reason stat = MISSING_PRIVATE; - if (vm_ci_flag(ci) & VM_CALL_VCALL) stat |= MISSING_VCALL; + case METHOD_VISI_PRIVATE: + if (!(vm_ci_flag(ci) & VM_CALL_FCALL)) { + enum method_missing_reason stat = MISSING_PRIVATE; + if (vm_ci_flag(ci) & VM_CALL_VCALL) stat |= MISSING_VCALL; vm_cc_method_missing_reason_set(cc, stat); CC_SET_FASTPATH(cc, vm_call_method_missing, TRUE); return vm_call_method_missing(ec, cfp, calling); - } + } return vm_call_method_each_type(ec, cfp, calling); - case METHOD_VISI_PROTECTED: - if (!(vm_ci_flag(ci) & (VM_CALL_OPT_SEND | VM_CALL_FCALL))) { + case METHOD_VISI_PROTECTED: + if (!(vm_ci_flag(ci) & (VM_CALL_OPT_SEND | VM_CALL_FCALL))) { VALUE defined_class = vm_defined_class_for_protected_call(vm_cc_cme(cc)); if (!rb_obj_is_kind_of(cfp->self, defined_class)) { vm_cc_method_missing_reason_set(cc, MISSING_PROTECTED); return vm_call_method_missing(ec, cfp, calling); - } - else { - /* caching method info to dummy cc */ - VM_ASSERT(vm_cc_cme(cc) != NULL); + } + else { + /* caching method info to dummy cc */ + VM_ASSERT(vm_cc_cme(cc) != NULL); struct rb_callcache cc_on_stack = *cc; FL_SET_RAW((VALUE)&cc_on_stack, VM_CALLCACHE_UNMARKABLE); calling->cc = &cc_on_stack; return vm_call_method_each_type(ec, cfp, calling); - } - } + } + } return vm_call_method_each_type(ec, cfp, calling); - default: - rb_bug("unreachable"); - } + default: + rb_bug("unreachable"); + } } else { return vm_call_method_nome(ec, cfp, calling); @@ -3796,8 +3796,8 @@ vm_search_normal_superclass(VALUE klass) { if (BUILTIN_TYPE(klass) == T_ICLASS && RB_TYPE_P(RBASIC(klass)->klass, T_MODULE) && - FL_TEST_RAW(RBASIC(klass)->klass, RMODULE_IS_REFINEMENT)) { - klass = RBASIC(klass)->klass; + FL_TEST_RAW(RBASIC(klass)->klass, RMODULE_IS_REFINEMENT)) { + klass = RBASIC(klass)->klass; } klass = RCLASS_ORIGIN(klass); return RCLASS_SUPER(klass); @@ -3828,7 +3828,7 @@ vm_search_super_method(const rb_control_frame_t *reg_cfp, struct rb_call_data *c const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(reg_cfp); if (!me) { - vm_super_outside(); + vm_super_outside(); } current_defined_class = vm_defined_class_for_protected_call(me); @@ -3836,7 +3836,7 @@ vm_search_super_method(const rb_control_frame_t *reg_cfp, struct rb_call_data *c if (BUILTIN_TYPE(current_defined_class) != T_MODULE && reg_cfp->iseq != method_entry_iseqptr(me) && !rb_obj_is_kind_of(recv, current_defined_class)) { - VALUE m = RB_TYPE_P(current_defined_class, T_ICLASS) ? + VALUE m = RB_TYPE_P(current_defined_class, T_ICLASS) ? RCLASS_INCLUDER(current_defined_class) : current_defined_class; if (m) { /* not bound UnboundMethod */ @@ -3848,10 +3848,10 @@ vm_search_super_method(const rb_control_frame_t *reg_cfp, struct rb_call_data *c } if (me->def->type == VM_METHOD_TYPE_BMETHOD && (vm_ci_flag(cd->ci) & VM_CALL_ZSUPER)) { - rb_raise(rb_eRuntimeError, - "implicit argument passing of super from method defined" - " by define_method() is not supported." - " Specify all arguments explicitly."); + rb_raise(rb_eRuntimeError, + "implicit argument passing of super from method defined" + " by define_method() is not supported." + " Specify all arguments explicitly."); } ID mid = me->def->original_id; @@ -3869,7 +3869,7 @@ vm_search_super_method(const rb_control_frame_t *reg_cfp, struct rb_call_data *c VALUE klass = vm_search_normal_superclass(me->defined_class); if (!klass) { - /* bound instance method of module */ + /* bound instance method of module */ cc = vm_cc_new(klass, NULL, vm_call_method_missing); RB_OBJ_WRITE(reg_cfp->iseq, &cd->cc, cc); } @@ -3920,17 +3920,17 @@ block_proc_is_lambda(const VALUE procval) rb_proc_t *proc; if (procval) { - GetProcPtr(procval, proc); - return proc->is_lambda; + GetProcPtr(procval, proc); + return proc->is_lambda; } else { - return 0; + return 0; } } static VALUE vm_yield_with_cfunc(rb_execution_context_t *ec, - const struct rb_captured_block *captured, + const struct rb_captured_block *captured, VALUE self, int argc, const VALUE *argv, int kw_splat, VALUE block_handler, const rb_callable_method_entry_t *me) { @@ -3940,13 +3940,13 @@ vm_yield_with_cfunc(rb_execution_context_t *ec, const struct vm_ifunc *ifunc = captured->code.ifunc; if (is_lambda) { - arg = rb_ary_new4(argc, argv); + arg = rb_ary_new4(argc, argv); } else if (argc == 0) { - arg = Qnil; + arg = Qnil; } else { - arg = argv[0]; + arg = argv[0]; } blockarg = rb_vm_bh_to_procval(ec, block_handler); @@ -3958,10 +3958,10 @@ vm_yield_with_cfunc(rb_execution_context_t *ec, vm_push_frame(ec, (const rb_iseq_t *)captured->code.ifunc, frame_flag, - self, - VM_GUARDED_PREV_EP(captured->ep), + self, + VM_GUARDED_PREV_EP(captured->ep), (VALUE)me, - 0, ec->cfp->sp, 0, 0); + 0, ec->cfp->sp, 0, 0); val = (*ifunc->func)(arg, (VALUE)ifunc->data, argc, argv, blockarg); rb_vm_pop_frame(ec); @@ -3983,7 +3983,7 @@ vm_callee_setup_block_arg_arg0_splat(rb_control_frame_t *cfp, const rb_iseq_t *i CHECK_VM_STACK_OVERFLOW(cfp, ISEQ_BODY(iseq)->param.lead_num); for (i=0; iparam.lead_num; i++) { - argv[i] = RARRAY_AREF(ary, i); + argv[i] = RARRAY_AREF(ary, i); } return i; @@ -4006,41 +4006,41 @@ static int vm_callee_setup_block_arg(rb_execution_context_t *ec, struct rb_calling_info *calling, const struct rb_callinfo *ci, const rb_iseq_t *iseq, VALUE *argv, const enum arg_setup_type arg_setup_type) { if (rb_simple_iseq_p(iseq)) { - rb_control_frame_t *cfp = ec->cfp; - VALUE arg0; + rb_control_frame_t *cfp = ec->cfp; + VALUE arg0; CALLER_SETUP_ARG(cfp, calling, ci); CALLER_REMOVE_EMPTY_KW_SPLAT(cfp, calling, ci); - if (arg_setup_type == arg_setup_block && - calling->argc == 1 && + if (arg_setup_type == arg_setup_block && + calling->argc == 1 && ISEQ_BODY(iseq)->param.flags.has_lead && !ISEQ_BODY(iseq)->param.flags.ambiguous_param0 && - !NIL_P(arg0 = vm_callee_setup_block_arg_arg0_check(argv))) { - calling->argc = vm_callee_setup_block_arg_arg0_splat(cfp, iseq, argv, arg0); - } + !NIL_P(arg0 = vm_callee_setup_block_arg_arg0_check(argv))) { + calling->argc = vm_callee_setup_block_arg_arg0_splat(cfp, iseq, argv, arg0); + } if (calling->argc != ISEQ_BODY(iseq)->param.lead_num) { - if (arg_setup_type == arg_setup_block) { + if (arg_setup_type == arg_setup_block) { if (calling->argc < ISEQ_BODY(iseq)->param.lead_num) { - int i; + int i; CHECK_VM_STACK_OVERFLOW(cfp, ISEQ_BODY(iseq)->param.lead_num); for (i=calling->argc; iparam.lead_num; i++) argv[i] = Qnil; calling->argc = ISEQ_BODY(iseq)->param.lead_num; /* fill rest parameters */ - } + } else if (calling->argc > ISEQ_BODY(iseq)->param.lead_num) { calling->argc = ISEQ_BODY(iseq)->param.lead_num; /* simply truncate arguments */ - } - } - else { + } + } + else { argument_arity_error(ec, iseq, calling->argc, ISEQ_BODY(iseq)->param.lead_num, ISEQ_BODY(iseq)->param.lead_num); - } - } + } + } - return 0; + return 0; } else { - return setup_parameters_complex(ec, iseq, calling, ci, argv, arg_setup_type); + return setup_parameters_complex(ec, iseq, calling, ci, argv, arg_setup_type); } } @@ -4063,7 +4063,7 @@ vm_yield_setup_args(rb_execution_context_t *ec, const rb_iseq_t *iseq, const int static VALUE vm_invoke_iseq_block(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, - struct rb_calling_info *calling, const struct rb_callinfo *ci, + struct rb_calling_info *calling, const struct rb_callinfo *ci, bool is_lambda, VALUE block_handler) { const struct rb_captured_block *captured = VM_BH_TO_ISEQ_BLOCK(block_handler); @@ -4075,11 +4075,11 @@ vm_invoke_iseq_block(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, SET_SP(rsp); vm_push_frame(ec, iseq, - VM_FRAME_MAGIC_BLOCK | (is_lambda ? VM_FRAME_FLAG_LAMBDA : 0), - captured->self, - VM_GUARDED_PREV_EP(captured->ep), 0, + VM_FRAME_MAGIC_BLOCK | (is_lambda ? VM_FRAME_FLAG_LAMBDA : 0), + captured->self, + VM_GUARDED_PREV_EP(captured->ep), 0, ISEQ_BODY(iseq)->iseq_encoded + opt_pc, - rsp + arg_size, + rsp + arg_size, ISEQ_BODY(iseq)->local_table_size - arg_size, ISEQ_BODY(iseq)->stack_max); return Qundef; @@ -4087,7 +4087,7 @@ vm_invoke_iseq_block(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, static VALUE vm_invoke_symbol_block(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, - struct rb_calling_info *calling, const struct rb_callinfo *ci, + struct rb_calling_info *calling, const struct rb_callinfo *ci, MAYBE_UNUSED(bool is_lambda), VALUE block_handler) { if (calling->argc < 1) { @@ -4103,7 +4103,7 @@ vm_invoke_symbol_block(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, static VALUE vm_invoke_ifunc_block(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, - struct rb_calling_info *calling, const struct rb_callinfo *ci, + struct rb_calling_info *calling, const struct rb_callinfo *ci, MAYBE_UNUSED(bool is_lambda), VALUE block_handler) { VALUE val; @@ -4124,13 +4124,13 @@ vm_proc_to_block_handler(VALUE procval) switch (vm_block_type(block)) { case block_type_iseq: - return VM_BH_FROM_ISEQ_BLOCK(&block->as.captured); + return VM_BH_FROM_ISEQ_BLOCK(&block->as.captured); case block_type_ifunc: - return VM_BH_FROM_IFUNC_BLOCK(&block->as.captured); + return VM_BH_FROM_IFUNC_BLOCK(&block->as.captured); case block_type_symbol: - return VM_BH_FROM_SYMBOL(block->as.symbol); + return VM_BH_FROM_SYMBOL(block->as.symbol); case block_type_proc: - return VM_BH_FROM_PROC(block->as.proc); + return VM_BH_FROM_PROC(block->as.proc); } VM_UNREACHABLE(vm_yield_with_proc); return Qundef; @@ -4178,7 +4178,7 @@ vm_make_proc_with_iseq(const rb_iseq_t *blockiseq) struct rb_captured_block *captured; if (cfp == 0) { - rb_bug("vm_make_proc_with_iseq: unreachable"); + rb_bug("vm_make_proc_with_iseq: unreachable"); } captured = VM_CFP_TO_CAPTURED_BLOCK(cfp); @@ -4213,10 +4213,10 @@ check_respond_to_missing(VALUE obj, VALUE v) args[0] = obj; args[1] = Qfalse; r = rb_check_funcall(v, idRespond_to_missing, 2, args); if (r != Qundef && RTEST(r)) { - return true; + return true; } else { - return false; + return false; } } @@ -4229,75 +4229,75 @@ vm_defined(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, rb_num_t op_ switch (type) { case DEFINED_IVAR: return rb_ivar_defined(GET_SELF(), SYM2ID(obj)); - break; + break; case DEFINED_GVAR: return rb_gvar_defined(SYM2ID(obj)); - break; + break; case DEFINED_CVAR: { const rb_cref_t *cref = vm_get_cref(GET_EP()); klass = vm_get_cvar_base(cref, GET_CFP(), 0); return rb_cvar_defined(klass, SYM2ID(obj)); - break; + break; } case DEFINED_CONST: case DEFINED_CONST_FROM: { - bool allow_nil = type == DEFINED_CONST; - klass = v; + bool allow_nil = type == DEFINED_CONST; + klass = v; return vm_get_ev_const(ec, klass, SYM2ID(obj), allow_nil, true); - break; + break; } case DEFINED_FUNC: - klass = CLASS_OF(v); + klass = CLASS_OF(v); return rb_ec_obj_respond_to(ec, v, SYM2ID(obj), TRUE); - break; + break; case DEFINED_METHOD:{ - VALUE klass = CLASS_OF(v); - const rb_method_entry_t *me = rb_method_entry_with_refinements(klass, SYM2ID(obj), NULL); + VALUE klass = CLASS_OF(v); + const rb_method_entry_t *me = rb_method_entry_with_refinements(klass, SYM2ID(obj), NULL); - if (me) { - switch (METHOD_ENTRY_VISI(me)) { - case METHOD_VISI_PRIVATE: - break; - case METHOD_VISI_PROTECTED: - if (!rb_obj_is_kind_of(GET_SELF(), rb_class_real(me->defined_class))) { - break; - } - case METHOD_VISI_PUBLIC: + if (me) { + switch (METHOD_ENTRY_VISI(me)) { + case METHOD_VISI_PRIVATE: + break; + case METHOD_VISI_PROTECTED: + if (!rb_obj_is_kind_of(GET_SELF(), rb_class_real(me->defined_class))) { + break; + } + case METHOD_VISI_PUBLIC: return true; - break; - default: - rb_bug("vm_defined: unreachable: %u", (unsigned int)METHOD_ENTRY_VISI(me)); - } - } - else { - return check_respond_to_missing(obj, v); - } - break; + break; + default: + rb_bug("vm_defined: unreachable: %u", (unsigned int)METHOD_ENTRY_VISI(me)); + } + } + else { + return check_respond_to_missing(obj, v); + } + break; } case DEFINED_YIELD: - if (GET_BLOCK_HANDLER() != VM_BLOCK_HANDLER_NONE) { + if (GET_BLOCK_HANDLER() != VM_BLOCK_HANDLER_NONE) { return true; - } - break; + } + break; case DEFINED_ZSUPER: - { - const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(GET_CFP()); + { + const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(GET_CFP()); - if (me) { - VALUE klass = vm_search_normal_superclass(me->defined_class); - ID id = me->def->original_id; + if (me) { + VALUE klass = vm_search_normal_superclass(me->defined_class); + ID id = me->def->original_id; - return rb_method_boundp(klass, id, 0); - } - } - break; + return rb_method_boundp(klass, id, 0); + } + } + break; case DEFINED_REF:{ - return vm_getspecial(ec, GET_LEP(), Qfalse, FIX2INT(obj)) != Qnil; - break; + return vm_getspecial(ec, GET_LEP(), Qfalse, FIX2INT(obj)) != Qnil; + break; } default: - rb_bug("unimplemented defined? type (VM)"); - break; + rb_bug("unimplemented defined? type (VM)"); + break; } return false; @@ -4315,24 +4315,24 @@ vm_get_ep(const VALUE *const reg_ep, rb_num_t lv) rb_num_t i; const VALUE *ep = reg_ep; for (i = 0; i < lv; i++) { - ep = GET_PREV_EP(ep); + ep = GET_PREV_EP(ep); } return ep; } static VALUE vm_get_special_object(const VALUE *const reg_ep, - enum vm_special_object_type type) + enum vm_special_object_type type) { switch (type) { case VM_SPECIAL_OBJECT_VMCORE: - return rb_mRubyVMFrozenCore; + return rb_mRubyVMFrozenCore; case VM_SPECIAL_OBJECT_CBASE: - return vm_get_cbase(reg_ep); + return vm_get_cbase(reg_ep); case VM_SPECIAL_OBJECT_CONST_BASE: - return vm_get_const_base(reg_ep); + return vm_get_const_base(reg_ep); default: - rb_bug("putspecialobject insn: unknown value_type %d", type); + rb_bug("putspecialobject insn: unknown value_type %d", type); } } @@ -4344,15 +4344,15 @@ vm_concat_array(VALUE ary1, VALUE ary2st) VALUE tmp2 = rb_check_to_array(ary2); if (NIL_P(tmp1)) { - tmp1 = rb_ary_new3(1, ary1); + tmp1 = rb_ary_new3(1, ary1); } if (NIL_P(tmp2)) { - tmp2 = rb_ary_new3(1, ary2); + tmp2 = rb_ary_new3(1, ary2); } if (tmp1 == ary1) { - tmp1 = rb_ary_dup(ary1); + tmp1 = rb_ary_dup(ary1); } return rb_ary_concat(tmp1, tmp2); } @@ -4362,13 +4362,13 @@ vm_splat_array(VALUE flag, VALUE ary) { VALUE tmp = rb_check_to_array(ary); if (NIL_P(tmp)) { - return rb_ary_new3(1, ary); + return rb_ary_new3(1, ary); } else if (RTEST(flag)) { - return rb_ary_dup(tmp); + return rb_ary_dup(tmp); } else { - return tmp; + return tmp; } } @@ -4384,21 +4384,21 @@ vm_check_match(rb_execution_context_t *ec, VALUE target, VALUE pattern, rb_num_t enum vm_check_match_type type = ((int)flag) & VM_CHECKMATCH_TYPE_MASK; if (flag & VM_CHECKMATCH_ARRAY) { - long i; - const long n = RARRAY_LEN(pattern); + long i; + const long n = RARRAY_LEN(pattern); - for (i = 0; i < n; i++) { - VALUE v = RARRAY_AREF(pattern, i); - VALUE c = check_match(ec, v, target, type); + for (i = 0; i < n; i++) { + VALUE v = RARRAY_AREF(pattern, i); + VALUE c = check_match(ec, v, target, type); - if (RTEST(c)) { - return c; - } - } - return Qfalse; + if (RTEST(c)) { + return c; + } + } + return Qfalse; } else { - return check_match(ec, pattern, target, type); + return check_match(ec, pattern, target, type); } } @@ -4408,13 +4408,13 @@ vm_check_keyword(lindex_t bits, lindex_t idx, const VALUE *ep) const VALUE kw_bits = *(ep - bits); if (FIXNUM_P(kw_bits)) { - unsigned int b = (unsigned int)FIX2ULONG(kw_bits); - if ((idx < KW_SPECIFIED_BITS_MAX) && (b & (0x01 << idx))) - return Qfalse; + unsigned int b = (unsigned int)FIX2ULONG(kw_bits); + if ((idx < KW_SPECIFIED_BITS_MAX) && (b & (0x01 << idx))) + return Qfalse; } else { - VM_ASSERT(RB_TYPE_P(kw_bits, T_HASH)); - if (rb_hash_has_key(kw_bits, INT2FIX(idx))) return Qfalse; + VM_ASSERT(RB_TYPE_P(kw_bits, T_HASH)); + if (rb_hash_has_key(kw_bits, INT2FIX(idx))) return Qfalse; } return Qtrue; } @@ -4423,24 +4423,24 @@ static void vm_dtrace(rb_event_flag_t flag, rb_execution_context_t *ec) { if (RUBY_DTRACE_METHOD_ENTRY_ENABLED() || - RUBY_DTRACE_METHOD_RETURN_ENABLED() || - RUBY_DTRACE_CMETHOD_ENTRY_ENABLED() || - RUBY_DTRACE_CMETHOD_RETURN_ENABLED()) { + RUBY_DTRACE_METHOD_RETURN_ENABLED() || + RUBY_DTRACE_CMETHOD_ENTRY_ENABLED() || + RUBY_DTRACE_CMETHOD_RETURN_ENABLED()) { - switch (flag) { - case RUBY_EVENT_CALL: - RUBY_DTRACE_METHOD_ENTRY_HOOK(ec, 0, 0); - return; - case RUBY_EVENT_C_CALL: - RUBY_DTRACE_CMETHOD_ENTRY_HOOK(ec, 0, 0); - return; - case RUBY_EVENT_RETURN: - RUBY_DTRACE_METHOD_RETURN_HOOK(ec, 0, 0); - return; - case RUBY_EVENT_C_RETURN: - RUBY_DTRACE_CMETHOD_RETURN_HOOK(ec, 0, 0); - return; - } + switch (flag) { + case RUBY_EVENT_CALL: + RUBY_DTRACE_METHOD_ENTRY_HOOK(ec, 0, 0); + return; + case RUBY_EVENT_C_CALL: + RUBY_DTRACE_CMETHOD_ENTRY_HOOK(ec, 0, 0); + return; + case RUBY_EVENT_RETURN: + RUBY_DTRACE_METHOD_RETURN_HOOK(ec, 0, 0); + return; + case RUBY_EVENT_C_RETURN: + RUBY_DTRACE_CMETHOD_RETURN_HOOK(ec, 0, 0); + return; + } } } @@ -4465,19 +4465,19 @@ vm_check_if_class(ID id, rb_num_t flags, VALUE super, VALUE klass) return 0; } else if (VM_DEFINECLASS_HAS_SUPERCLASS_P(flags)) { - VALUE tmp = rb_class_real(RCLASS_SUPER(klass)); + VALUE tmp = rb_class_real(RCLASS_SUPER(klass)); - if (tmp != super) { - rb_raise(rb_eTypeError, - "superclass mismatch for class %"PRIsVALUE"", - rb_id2str(id)); - } - else { - return klass; - } + if (tmp != super) { + rb_raise(rb_eTypeError, + "superclass mismatch for class %"PRIsVALUE"", + rb_id2str(id)); + } + else { + return klass; + } } else { - return klass; + return klass; } } @@ -4488,7 +4488,7 @@ vm_check_if_module(ID id, VALUE mod) return 0; } else { - return mod; + return mod; } } @@ -4540,9 +4540,9 @@ vm_define_class(ID id, rb_num_t flags, VALUE cbase, VALUE super) VALUE klass; if (VM_DEFINECLASS_HAS_SUPERCLASS_P(flags) && !RB_TYPE_P(super, T_CLASS)) { - rb_raise(rb_eTypeError, + rb_raise(rb_eTypeError, "superclass must be an instance of Class (given an instance of %"PRIsVALUE")", - rb_obj_class(super)); + rb_obj_class(super)); } vm_check_if_namespace(cbase); @@ -4555,7 +4555,7 @@ vm_define_class(ID id, rb_num_t flags, VALUE cbase, VALUE super) return klass; } else { - return vm_declare_class(id, flags, cbase, super); + return vm_declare_class(id, flags, cbase, super); } } @@ -4571,33 +4571,33 @@ vm_define_module(ID id, rb_num_t flags, VALUE cbase) return mod; } else { - return vm_declare_module(id, cbase); + return vm_declare_module(id, cbase); } } static VALUE vm_find_or_create_class_by_id(ID id, - rb_num_t flags, - VALUE cbase, - VALUE super) + rb_num_t flags, + VALUE cbase, + VALUE super) { rb_vm_defineclass_type_t type = VM_DEFINECLASS_TYPE(flags); switch (type) { case VM_DEFINECLASS_TYPE_CLASS: - /* classdef returns class scope value */ - return vm_define_class(id, flags, cbase, super); + /* classdef returns class scope value */ + return vm_define_class(id, flags, cbase, super); case VM_DEFINECLASS_TYPE_SINGLETON_CLASS: - /* classdef returns class scope value */ - return rb_singleton_class(cbase); + /* classdef returns class scope value */ + return rb_singleton_class(cbase); case VM_DEFINECLASS_TYPE_MODULE: - /* classdef returns class scope value */ - return vm_define_module(id, flags, cbase); + /* classdef returns class scope value */ + return vm_define_module(id, flags, cbase); default: - rb_bug("unknown defineclass type: %d", (int)type); + rb_bug("unknown defineclass type: %d", (int)type); } } @@ -4853,10 +4853,10 @@ static VALUE vm_opt_str_freeze(VALUE str, int bop, ID id) { if (BASIC_OP_UNREDEFINED_P(bop, STRING_REDEFINED_OP_FLAG)) { - return str; + return str; } else { - return Qundef; + return Qundef; } } @@ -4867,21 +4867,21 @@ static VALUE vm_opt_newarray_max(rb_execution_context_t *ec, rb_num_t num, const VALUE *ptr) { if (BASIC_OP_UNREDEFINED_P(BOP_MAX, ARRAY_REDEFINED_OP_FLAG)) { - if (num == 0) { - return Qnil; - } - else { - struct cmp_opt_data cmp_opt = { 0, 0 }; - VALUE result = *ptr; + if (num == 0) { + return Qnil; + } + else { + struct cmp_opt_data cmp_opt = { 0, 0 }; + VALUE result = *ptr; rb_snum_t i = num - 1; - while (i-- > 0) { - const VALUE v = *++ptr; - if (OPTIMIZED_CMP(v, result, cmp_opt) > 0) { - result = v; - } - } - return result; - } + while (i-- > 0) { + const VALUE v = *++ptr; + if (OPTIMIZED_CMP(v, result, cmp_opt) > 0) { + result = v; + } + } + return result; + } } else { return rb_vm_call_with_refinements(ec, rb_ary_new4(num, ptr), idMax, 0, NULL, RB_NO_KEYWORDS); @@ -4892,21 +4892,21 @@ static VALUE vm_opt_newarray_min(rb_execution_context_t *ec, rb_num_t num, const VALUE *ptr) { if (BASIC_OP_UNREDEFINED_P(BOP_MIN, ARRAY_REDEFINED_OP_FLAG)) { - if (num == 0) { - return Qnil; - } - else { - struct cmp_opt_data cmp_opt = { 0, 0 }; - VALUE result = *ptr; + if (num == 0) { + return Qnil; + } + else { + struct cmp_opt_data cmp_opt = { 0, 0 }; + VALUE result = *ptr; rb_snum_t i = num - 1; - while (i-- > 0) { - const VALUE v = *++ptr; - if (OPTIMIZED_CMP(v, result, cmp_opt) < 0) { - result = v; - } - } - return result; - } + while (i-- > 0) { + const VALUE v = *++ptr; + if (OPTIMIZED_CMP(v, result, cmp_opt) < 0) { + result = v; + } + } + return result; + } } else { return rb_vm_call_with_refinements(ec, rb_ary_new4(num, ptr), idMin, 0, NULL, RB_NO_KEYWORDS); @@ -5023,26 +5023,26 @@ vm_once_dispatch(rb_execution_context_t *ec, ISEQ iseq, ISE is) again: if (is->once.running_thread == RUNNING_THREAD_ONCE_DONE) { - return is->once.value; + return is->once.value; } else if (is->once.running_thread == NULL) { - VALUE val; - is->once.running_thread = th; - val = rb_ensure(vm_once_exec, (VALUE)iseq, vm_once_clear, (VALUE)is); - RB_OBJ_WRITE(ec->cfp->iseq, &is->once.value, val); - /* is->once.running_thread is cleared by vm_once_clear() */ - is->once.running_thread = RUNNING_THREAD_ONCE_DONE; /* success */ - return val; + VALUE val; + is->once.running_thread = th; + val = rb_ensure(vm_once_exec, (VALUE)iseq, vm_once_clear, (VALUE)is); + RB_OBJ_WRITE(ec->cfp->iseq, &is->once.value, val); + /* is->once.running_thread is cleared by vm_once_clear() */ + is->once.running_thread = RUNNING_THREAD_ONCE_DONE; /* success */ + return val; } else if (is->once.running_thread == th) { - /* recursive once */ - return vm_once_exec((VALUE)iseq); + /* recursive once */ + return vm_once_exec((VALUE)iseq); } else { - /* waiting for finish */ - RUBY_VM_CHECK_INTS(ec); - rb_thread_schedule(); - goto again; + /* waiting for finish */ + RUBY_VM_CHECK_INTS(ec); + rb_thread_schedule(); + goto again; } } @@ -5055,45 +5055,45 @@ vm_case_dispatch(CDHASH hash, OFFSET else_offset, VALUE key) case T_SYMBOL: case T_BIGNUM: case T_STRING: - if (BASIC_OP_UNREDEFINED_P(BOP_EQQ, - SYMBOL_REDEFINED_OP_FLAG | - INTEGER_REDEFINED_OP_FLAG | - FLOAT_REDEFINED_OP_FLAG | - NIL_REDEFINED_OP_FLAG | - TRUE_REDEFINED_OP_FLAG | - FALSE_REDEFINED_OP_FLAG | - STRING_REDEFINED_OP_FLAG)) { - st_data_t val; - if (RB_FLOAT_TYPE_P(key)) { - double kval = RFLOAT_VALUE(key); - if (!isinf(kval) && modf(kval, &kval) == 0.0) { - key = FIXABLE(kval) ? LONG2FIX((long)kval) : rb_dbl2big(kval); - } - } + if (BASIC_OP_UNREDEFINED_P(BOP_EQQ, + SYMBOL_REDEFINED_OP_FLAG | + INTEGER_REDEFINED_OP_FLAG | + FLOAT_REDEFINED_OP_FLAG | + NIL_REDEFINED_OP_FLAG | + TRUE_REDEFINED_OP_FLAG | + FALSE_REDEFINED_OP_FLAG | + STRING_REDEFINED_OP_FLAG)) { + st_data_t val; + if (RB_FLOAT_TYPE_P(key)) { + double kval = RFLOAT_VALUE(key); + if (!isinf(kval) && modf(kval, &kval) == 0.0) { + key = FIXABLE(kval) ? LONG2FIX((long)kval) : rb_dbl2big(kval); + } + } if (rb_hash_stlike_lookup(hash, key, &val)) { - return FIX2LONG((VALUE)val); - } - else { - return else_offset; - } - } + return FIX2LONG((VALUE)val); + } + else { + return else_offset; + } + } } return 0; } NORETURN(static void - vm_stack_consistency_error(const rb_execution_context_t *ec, - const rb_control_frame_t *, - const VALUE *)); + vm_stack_consistency_error(const rb_execution_context_t *ec, + const rb_control_frame_t *, + const VALUE *)); static void vm_stack_consistency_error(const rb_execution_context_t *ec, - const rb_control_frame_t *cfp, - const VALUE *bp) + const rb_control_frame_t *cfp, + const VALUE *bp) { const ptrdiff_t nsp = VM_SP_CNT(ec, cfp->sp); const ptrdiff_t nbp = VM_SP_CNT(ec, bp); static const char stack_consistency_error[] = - "Stack consistency error (sp: %"PRIdPTRDIFF", bp: %"PRIdPTRDIFF")"; + "Stack consistency error (sp: %"PRIdPTRDIFF", bp: %"PRIdPTRDIFF")"; #if defined RUBY_DEVEL VALUE mesg = rb_sprintf(stack_consistency_error, nsp, nbp); rb_str_cat_cstr(mesg, "\n"); @@ -5108,33 +5108,33 @@ static VALUE vm_opt_plus(VALUE recv, VALUE obj) { if (FIXNUM_2_P(recv, obj) && - BASIC_OP_UNREDEFINED_P(BOP_PLUS, INTEGER_REDEFINED_OP_FLAG)) { - return rb_fix_plus_fix(recv, obj); + BASIC_OP_UNREDEFINED_P(BOP_PLUS, INTEGER_REDEFINED_OP_FLAG)) { + return rb_fix_plus_fix(recv, obj); } else if (FLONUM_2_P(recv, obj) && - BASIC_OP_UNREDEFINED_P(BOP_PLUS, FLOAT_REDEFINED_OP_FLAG)) { - return DBL2NUM(RFLOAT_VALUE(recv) + RFLOAT_VALUE(obj)); + BASIC_OP_UNREDEFINED_P(BOP_PLUS, FLOAT_REDEFINED_OP_FLAG)) { + return DBL2NUM(RFLOAT_VALUE(recv) + RFLOAT_VALUE(obj)); } else if (SPECIAL_CONST_P(recv) || SPECIAL_CONST_P(obj)) { - return Qundef; + return Qundef; } else if (RBASIC_CLASS(recv) == rb_cFloat && - RBASIC_CLASS(obj) == rb_cFloat && - BASIC_OP_UNREDEFINED_P(BOP_PLUS, FLOAT_REDEFINED_OP_FLAG)) { - return DBL2NUM(RFLOAT_VALUE(recv) + RFLOAT_VALUE(obj)); + RBASIC_CLASS(obj) == rb_cFloat && + BASIC_OP_UNREDEFINED_P(BOP_PLUS, FLOAT_REDEFINED_OP_FLAG)) { + return DBL2NUM(RFLOAT_VALUE(recv) + RFLOAT_VALUE(obj)); } else if (RBASIC_CLASS(recv) == rb_cString && - RBASIC_CLASS(obj) == rb_cString && - BASIC_OP_UNREDEFINED_P(BOP_PLUS, STRING_REDEFINED_OP_FLAG)) { + RBASIC_CLASS(obj) == rb_cString && + BASIC_OP_UNREDEFINED_P(BOP_PLUS, STRING_REDEFINED_OP_FLAG)) { return rb_str_opt_plus(recv, obj); } else if (RBASIC_CLASS(recv) == rb_cArray && RBASIC_CLASS(obj) == rb_cArray && - BASIC_OP_UNREDEFINED_P(BOP_PLUS, ARRAY_REDEFINED_OP_FLAG)) { - return rb_ary_plus(recv, obj); + BASIC_OP_UNREDEFINED_P(BOP_PLUS, ARRAY_REDEFINED_OP_FLAG)) { + return rb_ary_plus(recv, obj); } else { - return Qundef; + return Qundef; } } @@ -5142,23 +5142,23 @@ static VALUE vm_opt_minus(VALUE recv, VALUE obj) { if (FIXNUM_2_P(recv, obj) && - BASIC_OP_UNREDEFINED_P(BOP_MINUS, INTEGER_REDEFINED_OP_FLAG)) { - return rb_fix_minus_fix(recv, obj); + BASIC_OP_UNREDEFINED_P(BOP_MINUS, INTEGER_REDEFINED_OP_FLAG)) { + return rb_fix_minus_fix(recv, obj); } else if (FLONUM_2_P(recv, obj) && - BASIC_OP_UNREDEFINED_P(BOP_MINUS, FLOAT_REDEFINED_OP_FLAG)) { - return DBL2NUM(RFLOAT_VALUE(recv) - RFLOAT_VALUE(obj)); + BASIC_OP_UNREDEFINED_P(BOP_MINUS, FLOAT_REDEFINED_OP_FLAG)) { + return DBL2NUM(RFLOAT_VALUE(recv) - RFLOAT_VALUE(obj)); } else if (SPECIAL_CONST_P(recv) || SPECIAL_CONST_P(obj)) { - return Qundef; + return Qundef; } else if (RBASIC_CLASS(recv) == rb_cFloat && - RBASIC_CLASS(obj) == rb_cFloat && - BASIC_OP_UNREDEFINED_P(BOP_MINUS, FLOAT_REDEFINED_OP_FLAG)) { - return DBL2NUM(RFLOAT_VALUE(recv) - RFLOAT_VALUE(obj)); + RBASIC_CLASS(obj) == rb_cFloat && + BASIC_OP_UNREDEFINED_P(BOP_MINUS, FLOAT_REDEFINED_OP_FLAG)) { + return DBL2NUM(RFLOAT_VALUE(recv) - RFLOAT_VALUE(obj)); } else { - return Qundef; + return Qundef; } } @@ -5166,23 +5166,23 @@ static VALUE vm_opt_mult(VALUE recv, VALUE obj) { if (FIXNUM_2_P(recv, obj) && - BASIC_OP_UNREDEFINED_P(BOP_MULT, INTEGER_REDEFINED_OP_FLAG)) { - return rb_fix_mul_fix(recv, obj); + BASIC_OP_UNREDEFINED_P(BOP_MULT, INTEGER_REDEFINED_OP_FLAG)) { + return rb_fix_mul_fix(recv, obj); } else if (FLONUM_2_P(recv, obj) && - BASIC_OP_UNREDEFINED_P(BOP_MULT, FLOAT_REDEFINED_OP_FLAG)) { - return DBL2NUM(RFLOAT_VALUE(recv) * RFLOAT_VALUE(obj)); + BASIC_OP_UNREDEFINED_P(BOP_MULT, FLOAT_REDEFINED_OP_FLAG)) { + return DBL2NUM(RFLOAT_VALUE(recv) * RFLOAT_VALUE(obj)); } else if (SPECIAL_CONST_P(recv) || SPECIAL_CONST_P(obj)) { - return Qundef; + return Qundef; } else if (RBASIC_CLASS(recv) == rb_cFloat && - RBASIC_CLASS(obj) == rb_cFloat && - BASIC_OP_UNREDEFINED_P(BOP_MULT, FLOAT_REDEFINED_OP_FLAG)) { - return DBL2NUM(RFLOAT_VALUE(recv) * RFLOAT_VALUE(obj)); + RBASIC_CLASS(obj) == rb_cFloat && + BASIC_OP_UNREDEFINED_P(BOP_MULT, FLOAT_REDEFINED_OP_FLAG)) { + return DBL2NUM(RFLOAT_VALUE(recv) * RFLOAT_VALUE(obj)); } else { - return Qundef; + return Qundef; } } @@ -5190,23 +5190,23 @@ static VALUE vm_opt_div(VALUE recv, VALUE obj) { if (FIXNUM_2_P(recv, obj) && - BASIC_OP_UNREDEFINED_P(BOP_DIV, INTEGER_REDEFINED_OP_FLAG)) { - return (FIX2LONG(obj) == 0) ? Qundef : rb_fix_div_fix(recv, obj); + BASIC_OP_UNREDEFINED_P(BOP_DIV, INTEGER_REDEFINED_OP_FLAG)) { + return (FIX2LONG(obj) == 0) ? Qundef : rb_fix_div_fix(recv, obj); } else if (FLONUM_2_P(recv, obj) && - BASIC_OP_UNREDEFINED_P(BOP_DIV, FLOAT_REDEFINED_OP_FLAG)) { + BASIC_OP_UNREDEFINED_P(BOP_DIV, FLOAT_REDEFINED_OP_FLAG)) { return rb_flo_div_flo(recv, obj); } else if (SPECIAL_CONST_P(recv) || SPECIAL_CONST_P(obj)) { - return Qundef; + return Qundef; } else if (RBASIC_CLASS(recv) == rb_cFloat && - RBASIC_CLASS(obj) == rb_cFloat && - BASIC_OP_UNREDEFINED_P(BOP_DIV, FLOAT_REDEFINED_OP_FLAG)) { + RBASIC_CLASS(obj) == rb_cFloat && + BASIC_OP_UNREDEFINED_P(BOP_DIV, FLOAT_REDEFINED_OP_FLAG)) { return rb_flo_div_flo(recv, obj); } else { - return Qundef; + return Qundef; } } @@ -5214,23 +5214,23 @@ static VALUE vm_opt_mod(VALUE recv, VALUE obj) { if (FIXNUM_2_P(recv, obj) && - BASIC_OP_UNREDEFINED_P(BOP_MOD, INTEGER_REDEFINED_OP_FLAG)) { - return (FIX2LONG(obj) == 0) ? Qundef : rb_fix_mod_fix(recv, obj); + BASIC_OP_UNREDEFINED_P(BOP_MOD, INTEGER_REDEFINED_OP_FLAG)) { + return (FIX2LONG(obj) == 0) ? Qundef : rb_fix_mod_fix(recv, obj); } else if (FLONUM_2_P(recv, obj) && - BASIC_OP_UNREDEFINED_P(BOP_MOD, FLOAT_REDEFINED_OP_FLAG)) { - return DBL2NUM(ruby_float_mod(RFLOAT_VALUE(recv), RFLOAT_VALUE(obj))); + BASIC_OP_UNREDEFINED_P(BOP_MOD, FLOAT_REDEFINED_OP_FLAG)) { + return DBL2NUM(ruby_float_mod(RFLOAT_VALUE(recv), RFLOAT_VALUE(obj))); } else if (SPECIAL_CONST_P(recv) || SPECIAL_CONST_P(obj)) { - return Qundef; + return Qundef; } else if (RBASIC_CLASS(recv) == rb_cFloat && - RBASIC_CLASS(obj) == rb_cFloat && - BASIC_OP_UNREDEFINED_P(BOP_MOD, FLOAT_REDEFINED_OP_FLAG)) { - return DBL2NUM(ruby_float_mod(RFLOAT_VALUE(recv), RFLOAT_VALUE(obj))); + RBASIC_CLASS(obj) == rb_cFloat && + BASIC_OP_UNREDEFINED_P(BOP_MOD, FLOAT_REDEFINED_OP_FLAG)) { + return DBL2NUM(ruby_float_mod(RFLOAT_VALUE(recv), RFLOAT_VALUE(obj))); } else { - return Qundef; + return Qundef; } } @@ -5240,9 +5240,9 @@ vm_opt_neq(const rb_iseq_t *iseq, CALL_DATA cd, CALL_DATA cd_eq, VALUE recv, VAL if (vm_method_cfunc_is(iseq, cd, recv, rb_obj_not_equal)) { VALUE val = opt_equality(iseq, recv, obj, cd_eq); - if (val != Qundef) { - return RBOOL(!RTEST(val)); - } + if (val != Qundef) { + return RBOOL(!RTEST(val)); + } } return Qundef; @@ -5252,24 +5252,24 @@ static VALUE vm_opt_lt(VALUE recv, VALUE obj) { if (FIXNUM_2_P(recv, obj) && - BASIC_OP_UNREDEFINED_P(BOP_LT, INTEGER_REDEFINED_OP_FLAG)) { - return RBOOL((SIGNED_VALUE)recv < (SIGNED_VALUE)obj); + BASIC_OP_UNREDEFINED_P(BOP_LT, INTEGER_REDEFINED_OP_FLAG)) { + return RBOOL((SIGNED_VALUE)recv < (SIGNED_VALUE)obj); } else if (FLONUM_2_P(recv, obj) && - BASIC_OP_UNREDEFINED_P(BOP_LT, FLOAT_REDEFINED_OP_FLAG)) { - return RBOOL(RFLOAT_VALUE(recv) < RFLOAT_VALUE(obj)); + BASIC_OP_UNREDEFINED_P(BOP_LT, FLOAT_REDEFINED_OP_FLAG)) { + return RBOOL(RFLOAT_VALUE(recv) < RFLOAT_VALUE(obj)); } else if (SPECIAL_CONST_P(recv) || SPECIAL_CONST_P(obj)) { - return Qundef; + return Qundef; } else if (RBASIC_CLASS(recv) == rb_cFloat && - RBASIC_CLASS(obj) == rb_cFloat && - BASIC_OP_UNREDEFINED_P(BOP_LT, FLOAT_REDEFINED_OP_FLAG)) { - CHECK_CMP_NAN(RFLOAT_VALUE(recv), RFLOAT_VALUE(obj)); - return RBOOL(RFLOAT_VALUE(recv) < RFLOAT_VALUE(obj)); + RBASIC_CLASS(obj) == rb_cFloat && + BASIC_OP_UNREDEFINED_P(BOP_LT, FLOAT_REDEFINED_OP_FLAG)) { + CHECK_CMP_NAN(RFLOAT_VALUE(recv), RFLOAT_VALUE(obj)); + return RBOOL(RFLOAT_VALUE(recv) < RFLOAT_VALUE(obj)); } else { - return Qundef; + return Qundef; } } @@ -5277,24 +5277,24 @@ static VALUE vm_opt_le(VALUE recv, VALUE obj) { if (FIXNUM_2_P(recv, obj) && - BASIC_OP_UNREDEFINED_P(BOP_LE, INTEGER_REDEFINED_OP_FLAG)) { - return RBOOL((SIGNED_VALUE)recv <= (SIGNED_VALUE)obj); + BASIC_OP_UNREDEFINED_P(BOP_LE, INTEGER_REDEFINED_OP_FLAG)) { + return RBOOL((SIGNED_VALUE)recv <= (SIGNED_VALUE)obj); } else if (FLONUM_2_P(recv, obj) && - BASIC_OP_UNREDEFINED_P(BOP_LE, FLOAT_REDEFINED_OP_FLAG)) { - return RBOOL(RFLOAT_VALUE(recv) <= RFLOAT_VALUE(obj)); + BASIC_OP_UNREDEFINED_P(BOP_LE, FLOAT_REDEFINED_OP_FLAG)) { + return RBOOL(RFLOAT_VALUE(recv) <= RFLOAT_VALUE(obj)); } else if (SPECIAL_CONST_P(recv) || SPECIAL_CONST_P(obj)) { - return Qundef; + return Qundef; } else if (RBASIC_CLASS(recv) == rb_cFloat && - RBASIC_CLASS(obj) == rb_cFloat && - BASIC_OP_UNREDEFINED_P(BOP_LE, FLOAT_REDEFINED_OP_FLAG)) { - CHECK_CMP_NAN(RFLOAT_VALUE(recv), RFLOAT_VALUE(obj)); - return RBOOL(RFLOAT_VALUE(recv) <= RFLOAT_VALUE(obj)); + RBASIC_CLASS(obj) == rb_cFloat && + BASIC_OP_UNREDEFINED_P(BOP_LE, FLOAT_REDEFINED_OP_FLAG)) { + CHECK_CMP_NAN(RFLOAT_VALUE(recv), RFLOAT_VALUE(obj)); + return RBOOL(RFLOAT_VALUE(recv) <= RFLOAT_VALUE(obj)); } else { - return Qundef; + return Qundef; } } @@ -5302,24 +5302,24 @@ static VALUE vm_opt_gt(VALUE recv, VALUE obj) { if (FIXNUM_2_P(recv, obj) && - BASIC_OP_UNREDEFINED_P(BOP_GT, INTEGER_REDEFINED_OP_FLAG)) { - return RBOOL((SIGNED_VALUE)recv > (SIGNED_VALUE)obj); + BASIC_OP_UNREDEFINED_P(BOP_GT, INTEGER_REDEFINED_OP_FLAG)) { + return RBOOL((SIGNED_VALUE)recv > (SIGNED_VALUE)obj); } else if (FLONUM_2_P(recv, obj) && - BASIC_OP_UNREDEFINED_P(BOP_GT, FLOAT_REDEFINED_OP_FLAG)) { - return RBOOL(RFLOAT_VALUE(recv) > RFLOAT_VALUE(obj)); + BASIC_OP_UNREDEFINED_P(BOP_GT, FLOAT_REDEFINED_OP_FLAG)) { + return RBOOL(RFLOAT_VALUE(recv) > RFLOAT_VALUE(obj)); } else if (SPECIAL_CONST_P(recv) || SPECIAL_CONST_P(obj)) { - return Qundef; + return Qundef; } else if (RBASIC_CLASS(recv) == rb_cFloat && - RBASIC_CLASS(obj) == rb_cFloat && - BASIC_OP_UNREDEFINED_P(BOP_GT, FLOAT_REDEFINED_OP_FLAG)) { - CHECK_CMP_NAN(RFLOAT_VALUE(recv), RFLOAT_VALUE(obj)); - return RBOOL(RFLOAT_VALUE(recv) > RFLOAT_VALUE(obj)); + RBASIC_CLASS(obj) == rb_cFloat && + BASIC_OP_UNREDEFINED_P(BOP_GT, FLOAT_REDEFINED_OP_FLAG)) { + CHECK_CMP_NAN(RFLOAT_VALUE(recv), RFLOAT_VALUE(obj)); + return RBOOL(RFLOAT_VALUE(recv) > RFLOAT_VALUE(obj)); } else { - return Qundef; + return Qundef; } } @@ -5327,24 +5327,24 @@ static VALUE vm_opt_ge(VALUE recv, VALUE obj) { if (FIXNUM_2_P(recv, obj) && - BASIC_OP_UNREDEFINED_P(BOP_GE, INTEGER_REDEFINED_OP_FLAG)) { - return RBOOL((SIGNED_VALUE)recv >= (SIGNED_VALUE)obj); + BASIC_OP_UNREDEFINED_P(BOP_GE, INTEGER_REDEFINED_OP_FLAG)) { + return RBOOL((SIGNED_VALUE)recv >= (SIGNED_VALUE)obj); } else if (FLONUM_2_P(recv, obj) && - BASIC_OP_UNREDEFINED_P(BOP_GE, FLOAT_REDEFINED_OP_FLAG)) { - return RBOOL(RFLOAT_VALUE(recv) >= RFLOAT_VALUE(obj)); + BASIC_OP_UNREDEFINED_P(BOP_GE, FLOAT_REDEFINED_OP_FLAG)) { + return RBOOL(RFLOAT_VALUE(recv) >= RFLOAT_VALUE(obj)); } else if (SPECIAL_CONST_P(recv) || SPECIAL_CONST_P(obj)) { - return Qundef; + return Qundef; } else if (RBASIC_CLASS(recv) == rb_cFloat && - RBASIC_CLASS(obj) == rb_cFloat && - BASIC_OP_UNREDEFINED_P(BOP_GE, FLOAT_REDEFINED_OP_FLAG)) { - CHECK_CMP_NAN(RFLOAT_VALUE(recv), RFLOAT_VALUE(obj)); - return RBOOL(RFLOAT_VALUE(recv) >= RFLOAT_VALUE(obj)); + RBASIC_CLASS(obj) == rb_cFloat && + BASIC_OP_UNREDEFINED_P(BOP_GE, FLOAT_REDEFINED_OP_FLAG)) { + CHECK_CMP_NAN(RFLOAT_VALUE(recv), RFLOAT_VALUE(obj)); + return RBOOL(RFLOAT_VALUE(recv) >= RFLOAT_VALUE(obj)); } else { - return Qundef; + return Qundef; } } @@ -5353,22 +5353,22 @@ static VALUE vm_opt_ltlt(VALUE recv, VALUE obj) { if (SPECIAL_CONST_P(recv)) { - return Qundef; + return Qundef; } else if (RBASIC_CLASS(recv) == rb_cString && - BASIC_OP_UNREDEFINED_P(BOP_LTLT, STRING_REDEFINED_OP_FLAG)) { - if (LIKELY(RB_TYPE_P(obj, T_STRING))) { - return rb_str_buf_append(recv, obj); - } else { - return rb_str_concat(recv, obj); - } + BASIC_OP_UNREDEFINED_P(BOP_LTLT, STRING_REDEFINED_OP_FLAG)) { + if (LIKELY(RB_TYPE_P(obj, T_STRING))) { + return rb_str_buf_append(recv, obj); + } else { + return rb_str_concat(recv, obj); + } } else if (RBASIC_CLASS(recv) == rb_cArray && - BASIC_OP_UNREDEFINED_P(BOP_LTLT, ARRAY_REDEFINED_OP_FLAG)) { - return rb_ary_push(recv, obj); + BASIC_OP_UNREDEFINED_P(BOP_LTLT, ARRAY_REDEFINED_OP_FLAG)) { + return rb_ary_push(recv, obj); } else { - return Qundef; + return Qundef; } } @@ -5410,10 +5410,10 @@ vm_opt_aref(VALUE recv, VALUE obj) BASIC_OP_UNREDEFINED_P(BOP_AREF, INTEGER_REDEFINED_OP_FLAG)) { return rb_fix_aref(recv, obj); } - return Qundef; + return Qundef; } else if (RBASIC_CLASS(recv) == rb_cArray && - BASIC_OP_UNREDEFINED_P(BOP_AREF, ARRAY_REDEFINED_OP_FLAG)) { + BASIC_OP_UNREDEFINED_P(BOP_AREF, ARRAY_REDEFINED_OP_FLAG)) { if (FIXNUM_P(obj)) { return rb_ary_entry_internal(recv, FIX2LONG(obj)); } @@ -5422,11 +5422,11 @@ vm_opt_aref(VALUE recv, VALUE obj) } } else if (RBASIC_CLASS(recv) == rb_cHash && - BASIC_OP_UNREDEFINED_P(BOP_AREF, HASH_REDEFINED_OP_FLAG)) { - return rb_hash_aref(recv, obj); + BASIC_OP_UNREDEFINED_P(BOP_AREF, HASH_REDEFINED_OP_FLAG)) { + return rb_hash_aref(recv, obj); } else { - return Qundef; + return Qundef; } } @@ -5434,21 +5434,21 @@ static VALUE vm_opt_aset(VALUE recv, VALUE obj, VALUE set) { if (SPECIAL_CONST_P(recv)) { - return Qundef; + return Qundef; } else if (RBASIC_CLASS(recv) == rb_cArray && - BASIC_OP_UNREDEFINED_P(BOP_ASET, ARRAY_REDEFINED_OP_FLAG) && - FIXNUM_P(obj)) { - rb_ary_store(recv, FIX2LONG(obj), set); - return set; + BASIC_OP_UNREDEFINED_P(BOP_ASET, ARRAY_REDEFINED_OP_FLAG) && + FIXNUM_P(obj)) { + rb_ary_store(recv, FIX2LONG(obj), set); + return set; } else if (RBASIC_CLASS(recv) == rb_cHash && - BASIC_OP_UNREDEFINED_P(BOP_ASET, HASH_REDEFINED_OP_FLAG)) { - rb_hash_aset(recv, obj, set); - return set; + BASIC_OP_UNREDEFINED_P(BOP_ASET, HASH_REDEFINED_OP_FLAG)) { + rb_hash_aset(recv, obj, set); + return set; } else { - return Qundef; + return Qundef; } } @@ -5456,12 +5456,12 @@ static VALUE vm_opt_aref_with(VALUE recv, VALUE key) { if (!SPECIAL_CONST_P(recv) && RBASIC_CLASS(recv) == rb_cHash && - BASIC_OP_UNREDEFINED_P(BOP_AREF, HASH_REDEFINED_OP_FLAG) && - rb_hash_compare_by_id_p(recv) == Qfalse) { - return rb_hash_aref(recv, key); + BASIC_OP_UNREDEFINED_P(BOP_AREF, HASH_REDEFINED_OP_FLAG) && + rb_hash_compare_by_id_p(recv) == Qfalse) { + return rb_hash_aref(recv, key); } else { - return Qundef; + return Qundef; } } @@ -5469,12 +5469,12 @@ static VALUE vm_opt_aset_with(VALUE recv, VALUE key, VALUE val) { if (!SPECIAL_CONST_P(recv) && RBASIC_CLASS(recv) == rb_cHash && - BASIC_OP_UNREDEFINED_P(BOP_ASET, HASH_REDEFINED_OP_FLAG) && - rb_hash_compare_by_id_p(recv) == Qfalse) { - return rb_hash_aset(recv, key, val); + BASIC_OP_UNREDEFINED_P(BOP_ASET, HASH_REDEFINED_OP_FLAG) && + rb_hash_compare_by_id_p(recv) == Qfalse) { + return rb_hash_aset(recv, key, val); } else { - return Qundef; + return Qundef; } } @@ -5482,27 +5482,27 @@ static VALUE vm_opt_length(VALUE recv, int bop) { if (SPECIAL_CONST_P(recv)) { - return Qundef; + return Qundef; } else if (RBASIC_CLASS(recv) == rb_cString && - BASIC_OP_UNREDEFINED_P(bop, STRING_REDEFINED_OP_FLAG)) { - if (bop == BOP_EMPTY_P) { - return LONG2NUM(RSTRING_LEN(recv)); - } - else { - return rb_str_length(recv); - } + BASIC_OP_UNREDEFINED_P(bop, STRING_REDEFINED_OP_FLAG)) { + if (bop == BOP_EMPTY_P) { + return LONG2NUM(RSTRING_LEN(recv)); + } + else { + return rb_str_length(recv); + } } else if (RBASIC_CLASS(recv) == rb_cArray && - BASIC_OP_UNREDEFINED_P(bop, ARRAY_REDEFINED_OP_FLAG)) { - return LONG2NUM(RARRAY_LEN(recv)); + BASIC_OP_UNREDEFINED_P(bop, ARRAY_REDEFINED_OP_FLAG)) { + return LONG2NUM(RARRAY_LEN(recv)); } else if (RBASIC_CLASS(recv) == rb_cHash && - BASIC_OP_UNREDEFINED_P(bop, HASH_REDEFINED_OP_FLAG)) { - return INT2FIX(RHASH_SIZE(recv)); + BASIC_OP_UNREDEFINED_P(bop, HASH_REDEFINED_OP_FLAG)) { + return INT2FIX(RHASH_SIZE(recv)); } else { - return Qundef; + return Qundef; } } @@ -5565,18 +5565,18 @@ static VALUE vm_opt_succ(VALUE recv) { if (FIXNUM_P(recv) && - BASIC_OP_UNREDEFINED_P(BOP_SUCC, INTEGER_REDEFINED_OP_FLAG)) { + BASIC_OP_UNREDEFINED_P(BOP_SUCC, INTEGER_REDEFINED_OP_FLAG)) { return fix_succ(recv); } else if (SPECIAL_CONST_P(recv)) { - return Qundef; + return Qundef; } else if (RBASIC_CLASS(recv) == rb_cString && - BASIC_OP_UNREDEFINED_P(BOP_SUCC, STRING_REDEFINED_OP_FLAG)) { - return rb_str_succ(recv); + BASIC_OP_UNREDEFINED_P(BOP_SUCC, STRING_REDEFINED_OP_FLAG)) { + return rb_str_succ(recv); } else { - return Qundef; + return Qundef; } } @@ -5584,10 +5584,10 @@ static VALUE vm_opt_not(const rb_iseq_t *iseq, CALL_DATA cd, VALUE recv) { if (vm_method_cfunc_is(iseq, cd, recv, rb_obj_not)) { - return RBOOL(!RTEST(recv)); + return RBOOL(!RTEST(recv)); } else { - return Qundef; + return Qundef; } } @@ -5599,15 +5599,15 @@ vm_opt_regexpmatch2(VALUE recv, VALUE obj) } else if (RBASIC_CLASS(recv) == rb_cString && CLASS_OF(obj) == rb_cRegexp && - BASIC_OP_UNREDEFINED_P(BOP_MATCH, STRING_REDEFINED_OP_FLAG)) { - return rb_reg_match(obj, recv); + BASIC_OP_UNREDEFINED_P(BOP_MATCH, STRING_REDEFINED_OP_FLAG)) { + return rb_reg_match(obj, recv); } else if (RBASIC_CLASS(recv) == rb_cRegexp && BASIC_OP_UNREDEFINED_P(BOP_MATCH, REGEXP_REDEFINED_OP_FLAG)) { - return rb_reg_match(recv, obj); + return rb_reg_match(recv, obj); } else { - return Qundef; + return Qundef; } } @@ -5678,7 +5678,7 @@ vm_trace(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp) return; } else { - const rb_iseq_t *iseq = reg_cfp->iseq; + const rb_iseq_t *iseq = reg_cfp->iseq; VALUE iseq_val = (VALUE)iseq; size_t pos = pc - ISEQ_BODY(iseq)->iseq_encoded; rb_event_flag_t pc_events = rb_iseq_event_flags(iseq, pos); @@ -5706,15 +5706,15 @@ vm_trace(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp) if ((pc_events & enabled_flags) == 0 && !bmethod_frame) { #if 0 - /* disable trace */ + /* disable trace */ /* TODO: incomplete */ - rb_iseq_trace_set(iseq, vm_event_flags & ISEQ_TRACE_EVENTS); + rb_iseq_trace_set(iseq, vm_event_flags & ISEQ_TRACE_EVENTS); #else - /* do not disable trace because of performance problem - * (re-enable overhead) - */ + /* do not disable trace because of performance problem + * (re-enable overhead) + */ #endif - return; + return; } else if (ec->trace_arg != NULL) { /* already tracing */ diff --git a/vm_insnhelper.h b/vm_insnhelper.h index 2199ee37cc..fdf47159e8 100644 --- a/vm_insnhelper.h +++ b/vm_insnhelper.h @@ -241,8 +241,8 @@ static inline void THROW_DATA_CONSUMED_SET(struct vm_throw_data *obj) { if (THROW_DATA_P(obj) && - THROW_DATA_STATE(obj) == TAG_BREAK) { - obj->flags |= THROW_DATA_CONSUMED; + THROW_DATA_STATE(obj) == TAG_BREAK) { + obj->flags |= THROW_DATA_CONSUMED; } } diff --git a/vm_method.c b/vm_method.c index 7cd9fee754..e88a30c5f3 100644 --- a/vm_method.c +++ b/vm_method.c @@ -373,13 +373,13 @@ rb_add_method_cfunc(VALUE klass, ID mid, VALUE (*func)(ANYARGS), int argc, rb_me { if (argc < -2 || 15 < argc) rb_raise(rb_eArgError, "arity out of range: %d for -2..15", argc); if (func != rb_f_notimplement) { - rb_method_cfunc_t opt; - opt.func = func; - opt.argc = argc; + rb_method_cfunc_t opt; + opt.func = func; + opt.argc = argc; rb_add_method(klass, mid, VM_METHOD_TYPE_CFUNC, &opt, visi); } else { - rb_define_notimplement_method_id(klass, mid, visi); + rb_define_notimplement_method_id(klass, mid, visi); } } @@ -397,20 +397,20 @@ static void rb_method_definition_release(rb_method_definition_t *def, int complemented) { if (def != NULL) { - const int alias_count = def->alias_count; - const int complemented_count = def->complemented_count; - VM_ASSERT(alias_count >= 0); - VM_ASSERT(complemented_count >= 0); + const int alias_count = def->alias_count; + const int complemented_count = def->complemented_count; + VM_ASSERT(alias_count >= 0); + VM_ASSERT(complemented_count >= 0); - if (alias_count + complemented_count == 0) { + if (alias_count + complemented_count == 0) { if (METHOD_DEBUG) fprintf(stderr, "-%p-%s:%d,%d (remove)\n", (void *)def, rb_id2name(def->original_id), alias_count, complemented_count); if (def->type == VM_METHOD_TYPE_BMETHOD && def->body.bmethod.hooks) { xfree(def->body.bmethod.hooks); } - xfree(def); - } - else { + xfree(def); + } + else { if (complemented) { VM_ASSERT(def->complemented_count > 0); def->complemented_count--; @@ -419,9 +419,9 @@ rb_method_definition_release(rb_method_definition_t *def, int complemented) def->alias_count--; } - if (METHOD_DEBUG) fprintf(stderr, "-%p-%s:%d->%d,%d->%d (dec)\n", (void *)def, rb_id2name(def->original_id), - alias_count, def->alias_count, complemented_count, def->complemented_count); - } + if (METHOD_DEBUG) fprintf(stderr, "-%p-%s:%d->%d,%d->%d (dec)\n", (void *)def, rb_id2name(def->original_id), + alias_count, def->alias_count, complemented_count, def->complemented_count); + } } } @@ -506,81 +506,81 @@ rb_method_definition_set(const rb_method_entry_t *me, rb_method_definition_t *de *(rb_method_definition_t **)&me->def = def; if (opts != NULL) { - switch (def->type) { - case VM_METHOD_TYPE_ISEQ: - { - rb_method_iseq_t *iseq_body = (rb_method_iseq_t *)opts; + switch (def->type) { + case VM_METHOD_TYPE_ISEQ: + { + rb_method_iseq_t *iseq_body = (rb_method_iseq_t *)opts; const rb_iseq_t *iseq = iseq_body->iseqptr; - rb_cref_t *method_cref, *cref = iseq_body->cref; + rb_cref_t *method_cref, *cref = iseq_body->cref; - /* setup iseq first (before invoking GC) */ - RB_OBJ_WRITE(me, &def->body.iseq.iseqptr, iseq); + /* setup iseq first (before invoking GC) */ + RB_OBJ_WRITE(me, &def->body.iseq.iseqptr, iseq); if (ISEQ_BODY(iseq)->mandatory_only_iseq) def->iseq_overload = 1; - if (0) vm_cref_dump("rb_method_definition_create", cref); + if (0) vm_cref_dump("rb_method_definition_create", cref); - if (cref) { - method_cref = cref; - } - else { - method_cref = vm_cref_new_toplevel(GET_EC()); /* TODO: can we reuse? */ - } + if (cref) { + method_cref = cref; + } + else { + method_cref = vm_cref_new_toplevel(GET_EC()); /* TODO: can we reuse? */ + } - RB_OBJ_WRITE(me, &def->body.iseq.cref, method_cref); - return; - } - case VM_METHOD_TYPE_CFUNC: - { - rb_method_cfunc_t *cfunc = (rb_method_cfunc_t *)opts; - setup_method_cfunc_struct(UNALIGNED_MEMBER_PTR(def, body.cfunc), cfunc->func, cfunc->argc); - return; - } - case VM_METHOD_TYPE_ATTRSET: - case VM_METHOD_TYPE_IVAR: - { - const rb_execution_context_t *ec = GET_EC(); - rb_control_frame_t *cfp; - int line; + RB_OBJ_WRITE(me, &def->body.iseq.cref, method_cref); + return; + } + case VM_METHOD_TYPE_CFUNC: + { + rb_method_cfunc_t *cfunc = (rb_method_cfunc_t *)opts; + setup_method_cfunc_struct(UNALIGNED_MEMBER_PTR(def, body.cfunc), cfunc->func, cfunc->argc); + return; + } + case VM_METHOD_TYPE_ATTRSET: + case VM_METHOD_TYPE_IVAR: + { + const rb_execution_context_t *ec = GET_EC(); + rb_control_frame_t *cfp; + int line; - def->body.attr.id = (ID)(VALUE)opts; + def->body.attr.id = (ID)(VALUE)opts; - cfp = rb_vm_get_ruby_level_next_cfp(ec, ec->cfp); + cfp = rb_vm_get_ruby_level_next_cfp(ec, ec->cfp); - if (cfp && (line = rb_vm_get_sourceline(cfp))) { - VALUE location = rb_ary_new3(2, rb_iseq_path(cfp->iseq), INT2FIX(line)); - RB_OBJ_WRITE(me, &def->body.attr.location, rb_ary_freeze(location)); - } - else { - VM_ASSERT(def->body.attr.location == 0); - } - return; - } - case VM_METHOD_TYPE_BMETHOD: + if (cfp && (line = rb_vm_get_sourceline(cfp))) { + VALUE location = rb_ary_new3(2, rb_iseq_path(cfp->iseq), INT2FIX(line)); + RB_OBJ_WRITE(me, &def->body.attr.location, rb_ary_freeze(location)); + } + else { + VM_ASSERT(def->body.attr.location == 0); + } + return; + } + case VM_METHOD_TYPE_BMETHOD: RB_OBJ_WRITE(me, &def->body.bmethod.proc, (VALUE)opts); RB_OBJ_WRITE(me, &def->body.bmethod.defined_ractor, rb_ractor_self(GET_RACTOR())); - return; - case VM_METHOD_TYPE_NOTIMPLEMENTED: - setup_method_cfunc_struct(UNALIGNED_MEMBER_PTR(def, body.cfunc), rb_f_notimplement_internal, -1); - return; - case VM_METHOD_TYPE_OPTIMIZED: + return; + case VM_METHOD_TYPE_NOTIMPLEMENTED: + setup_method_cfunc_struct(UNALIGNED_MEMBER_PTR(def, body.cfunc), rb_f_notimplement_internal, -1); + return; + case VM_METHOD_TYPE_OPTIMIZED: def->body.optimized = *(rb_method_optimized_t *)opts; - return; - case VM_METHOD_TYPE_REFINED: - { - const rb_method_refined_t *refined = (rb_method_refined_t *)opts; - RB_OBJ_WRITE(me, &def->body.refined.orig_me, refined->orig_me); - RB_OBJ_WRITE(me, &def->body.refined.owner, refined->owner); - return; - } - case VM_METHOD_TYPE_ALIAS: - RB_OBJ_WRITE(me, &def->body.alias.original_me, (rb_method_entry_t *)opts); - return; - case VM_METHOD_TYPE_ZSUPER: - case VM_METHOD_TYPE_UNDEF: - case VM_METHOD_TYPE_MISSING: - return; - } + return; + case VM_METHOD_TYPE_REFINED: + { + const rb_method_refined_t *refined = (rb_method_refined_t *)opts; + RB_OBJ_WRITE(me, &def->body.refined.orig_me, refined->orig_me); + RB_OBJ_WRITE(me, &def->body.refined.owner, refined->owner); + return; + } + case VM_METHOD_TYPE_ALIAS: + RB_OBJ_WRITE(me, &def->body.alias.original_me, (rb_method_entry_t *)opts); + return; + case VM_METHOD_TYPE_ZSUPER: + case VM_METHOD_TYPE_UNDEF: + case VM_METHOD_TYPE_MISSING: + return; + } } } @@ -591,33 +591,33 @@ method_definition_reset(const rb_method_entry_t *me) switch (def->type) { case VM_METHOD_TYPE_ISEQ: - RB_OBJ_WRITTEN(me, Qundef, def->body.iseq.iseqptr); - RB_OBJ_WRITTEN(me, Qundef, def->body.iseq.cref); + RB_OBJ_WRITTEN(me, Qundef, def->body.iseq.iseqptr); + RB_OBJ_WRITTEN(me, Qundef, def->body.iseq.cref); break; case VM_METHOD_TYPE_ATTRSET: case VM_METHOD_TYPE_IVAR: - RB_OBJ_WRITTEN(me, Qundef, def->body.attr.location); - break; + RB_OBJ_WRITTEN(me, Qundef, def->body.attr.location); + break; case VM_METHOD_TYPE_BMETHOD: RB_OBJ_WRITTEN(me, Qundef, def->body.bmethod.proc); RB_OBJ_WRITTEN(me, Qundef, def->body.bmethod.defined_ractor); /* give up to check all in a list */ if (def->body.bmethod.hooks) rb_gc_writebarrier_remember((VALUE)me); - break; + break; case VM_METHOD_TYPE_REFINED: - RB_OBJ_WRITTEN(me, Qundef, def->body.refined.orig_me); - RB_OBJ_WRITTEN(me, Qundef, def->body.refined.owner); - break; + RB_OBJ_WRITTEN(me, Qundef, def->body.refined.orig_me); + RB_OBJ_WRITTEN(me, Qundef, def->body.refined.owner); + break; case VM_METHOD_TYPE_ALIAS: - RB_OBJ_WRITTEN(me, Qundef, def->body.alias.original_me); - break; + RB_OBJ_WRITTEN(me, Qundef, def->body.alias.original_me); + break; case VM_METHOD_TYPE_CFUNC: case VM_METHOD_TYPE_ZSUPER: case VM_METHOD_TYPE_MISSING: case VM_METHOD_TYPE_OPTIMIZED: case VM_METHOD_TYPE_UNDEF: case VM_METHOD_TYPE_NOTIMPLEMENTED: - break; + break; } } @@ -661,11 +661,11 @@ filter_defined_class(VALUE klass) { switch (BUILTIN_TYPE(klass)) { case T_CLASS: - return klass; + return klass; case T_MODULE: - return 0; + return 0; case T_ICLASS: - break; + break; default: break; } @@ -700,29 +700,29 @@ rb_method_entry_complement_defined_class(const rb_method_entry_t *src_me, ID cal rb_method_definition_t *def = src_me->def; rb_method_entry_t *me; struct { - const struct rb_method_entry_struct *orig_me; - VALUE owner; + const struct rb_method_entry_struct *orig_me; + VALUE owner; } refined = {0}; if (!src_me->defined_class && - def->type == VM_METHOD_TYPE_REFINED && - def->body.refined.orig_me) { - const rb_method_entry_t *orig_me = - rb_method_entry_clone(def->body.refined.orig_me); - RB_OBJ_WRITE((VALUE)orig_me, &orig_me->defined_class, defined_class); - refined.orig_me = orig_me; - refined.owner = orig_me->owner; - def = NULL; + def->type == VM_METHOD_TYPE_REFINED && + def->body.refined.orig_me) { + const rb_method_entry_t *orig_me = + rb_method_entry_clone(def->body.refined.orig_me); + RB_OBJ_WRITE((VALUE)orig_me, &orig_me->defined_class, defined_class); + refined.orig_me = orig_me; + refined.owner = orig_me->owner; + def = NULL; } else { - def = method_definition_addref_complement(def); + def = method_definition_addref_complement(def); } me = rb_method_entry_alloc(called_id, src_me->owner, defined_class, def); METHOD_ENTRY_FLAGS_COPY(me, src_me); METHOD_ENTRY_COMPLEMENTED_SET(me); if (!def) { - def = rb_method_definition_create(VM_METHOD_TYPE_REFINED, called_id); - rb_method_definition_set(me, def, &refined); + def = rb_method_definition_create(VM_METHOD_TYPE_REFINED, called_id); + rb_method_definition_set(me, def, &refined); } VM_ASSERT(RB_TYPE_P(me->owner, T_MODULE)); @@ -745,28 +745,28 @@ static void make_method_entry_refined(VALUE owner, rb_method_entry_t *me) { if (me->def->type == VM_METHOD_TYPE_REFINED) { - return; + return; } else { - struct { - struct rb_method_entry_struct *orig_me; - VALUE owner; - } refined; - rb_method_definition_t *def; + struct { + struct rb_method_entry_struct *orig_me; + VALUE owner; + } refined; + rb_method_definition_t *def; - rb_vm_check_redefinition_opt_method(me, me->owner); + rb_vm_check_redefinition_opt_method(me, me->owner); - refined.orig_me = - rb_method_entry_alloc(me->called_id, me->owner, - me->defined_class ? - me->defined_class : owner, - method_definition_addref(me->def)); - METHOD_ENTRY_FLAGS_COPY(refined.orig_me, me); - refined.owner = owner; + refined.orig_me = + rb_method_entry_alloc(me->called_id, me->owner, + me->defined_class ? + me->defined_class : owner, + method_definition_addref(me->def)); + METHOD_ENTRY_FLAGS_COPY(refined.orig_me, me); + refined.owner = owner; - def = rb_method_definition_create(VM_METHOD_TYPE_REFINED, me->called_id); - rb_method_definition_set(me, def, (void *)&refined); - METHOD_ENTRY_VISI_SET(me, METHOD_VISI_PUBLIC); + def = rb_method_definition_create(VM_METHOD_TYPE_REFINED, me->called_id); + rb_method_definition_set(me, def, (void *)&refined); + METHOD_ENTRY_VISI_SET(me, METHOD_VISI_PUBLIC); } } @@ -777,10 +777,10 @@ lookup_method_table(VALUE klass, ID id) struct rb_id_table *m_tbl = RCLASS_M_TBL(klass); if (rb_id_table_lookup(m_tbl, id, &body)) { - return (rb_method_entry_t *) body; + return (rb_method_entry_t *) body; } else { - return 0; + return 0; } } @@ -790,11 +790,11 @@ rb_add_refined_method_entry(VALUE refined_class, ID mid) rb_method_entry_t *me = lookup_method_table(refined_class, mid); if (me) { - make_method_entry_refined(refined_class, me); - rb_clear_method_cache(refined_class, mid); + make_method_entry_refined(refined_class, me); + rb_clear_method_cache(refined_class, mid); } else { - rb_add_method(refined_class, mid, VM_METHOD_TYPE_REFINED, 0, METHOD_VISI_PUBLIC); + rb_add_method(refined_class, mid, VM_METHOD_TYPE_REFINED, 0, METHOD_VISI_PUBLIC); } } @@ -805,11 +805,11 @@ check_override_opt_method_i(VALUE klass, VALUE arg) const rb_method_entry_t *me, *newme; if (vm_redefinition_check_flag(klass)) { - me = lookup_method_table(RCLASS_ORIGIN(klass), mid); - if (me) { - newme = rb_method_entry(klass, mid); - if (newme != me) rb_vm_check_redefinition_opt_method(me, me->owner); - } + me = lookup_method_table(RCLASS_ORIGIN(klass), mid); + if (me) { + newme = rb_method_entry(klass, mid); + if (newme != me) rb_vm_check_redefinition_opt_method(me, me->owner); + } } rb_class_foreach_subclass(klass, check_override_opt_method_i, (VALUE)mid); } @@ -830,7 +830,7 @@ check_override_opt_method(VALUE klass, VALUE mid) */ static rb_method_entry_t * rb_method_entry_make(VALUE klass, ID mid, VALUE defined_class, rb_method_visibility_t visi, - rb_method_type_t type, rb_method_definition_t *def, ID original_id, void *opts) + rb_method_type_t type, rb_method_definition_t *def, ID original_id, void *opts) { rb_method_entry_t *me; struct rb_id_table *mtbl; @@ -839,21 +839,21 @@ rb_method_entry_make(VALUE klass, ID mid, VALUE defined_class, rb_method_visibil VALUE orig_klass; if (NIL_P(klass)) { - klass = rb_cObject; + klass = rb_cObject; } orig_klass = klass; if (!FL_TEST(klass, FL_SINGLETON) && - type != VM_METHOD_TYPE_NOTIMPLEMENTED && - type != VM_METHOD_TYPE_ZSUPER) { - switch (mid) { - case idInitialize: - case idInitialize_copy: - case idInitialize_clone: - case idInitialize_dup: - case idRespond_to_missing: - visi = METHOD_VISI_PRIVATE; - } + type != VM_METHOD_TYPE_NOTIMPLEMENTED && + type != VM_METHOD_TYPE_ZSUPER) { + switch (mid) { + case idInitialize: + case idInitialize_copy: + case idInitialize_clone: + case idInitialize_dup: + case idRespond_to_missing: + visi = METHOD_VISI_PRIVATE; + } } if (type != VM_METHOD_TYPE_REFINED) { @@ -861,15 +861,15 @@ rb_method_entry_make(VALUE klass, ID mid, VALUE defined_class, rb_method_visibil } if (RB_TYPE_P(klass, T_MODULE) && FL_TEST(klass, RMODULE_IS_REFINEMENT)) { - VALUE refined_class = rb_refinement_module_get_refined_class(klass); - rb_add_refined_method_entry(refined_class, mid); + VALUE refined_class = rb_refinement_module_get_refined_class(klass); + rb_add_refined_method_entry(refined_class, mid); } if (type == VM_METHOD_TYPE_REFINED) { - rb_method_entry_t *old_me = lookup_method_table(RCLASS_ORIGIN(klass), mid); - if (old_me) rb_vm_check_redefinition_opt_method(old_me, klass); + rb_method_entry_t *old_me = lookup_method_table(RCLASS_ORIGIN(klass), mid); + if (old_me) rb_vm_check_redefinition_opt_method(old_me, klass); } else { - klass = RCLASS_ORIGIN(klass); + klass = RCLASS_ORIGIN(klass); if (klass != orig_klass) { rb_clear_method_cache(orig_klass, mid); } @@ -878,42 +878,42 @@ rb_method_entry_make(VALUE klass, ID mid, VALUE defined_class, rb_method_visibil /* check re-definition */ if (rb_id_table_lookup(mtbl, mid, &data)) { - rb_method_entry_t *old_me = (rb_method_entry_t *)data; - rb_method_definition_t *old_def = old_me->def; + rb_method_entry_t *old_me = (rb_method_entry_t *)data; + rb_method_definition_t *old_def = old_me->def; - if (rb_method_definition_eq(old_def, def)) return old_me; - rb_vm_check_redefinition_opt_method(old_me, klass); + if (rb_method_definition_eq(old_def, def)) return old_me; + rb_vm_check_redefinition_opt_method(old_me, klass); - if (old_def->type == VM_METHOD_TYPE_REFINED) make_refined = 1; + if (old_def->type == VM_METHOD_TYPE_REFINED) make_refined = 1; - if (RTEST(ruby_verbose) && - type != VM_METHOD_TYPE_UNDEF && - (old_def->alias_count == 0) && - (!old_def->no_redef_warning) && - !make_refined && - old_def->type != VM_METHOD_TYPE_UNDEF && - old_def->type != VM_METHOD_TYPE_ZSUPER && - old_def->type != VM_METHOD_TYPE_ALIAS) { - const rb_iseq_t *iseq = 0; + if (RTEST(ruby_verbose) && + type != VM_METHOD_TYPE_UNDEF && + (old_def->alias_count == 0) && + (!old_def->no_redef_warning) && + !make_refined && + old_def->type != VM_METHOD_TYPE_UNDEF && + old_def->type != VM_METHOD_TYPE_ZSUPER && + old_def->type != VM_METHOD_TYPE_ALIAS) { + const rb_iseq_t *iseq = 0; - rb_warning("method redefined; discarding old %"PRIsVALUE, rb_id2str(mid)); - switch (old_def->type) { - case VM_METHOD_TYPE_ISEQ: - iseq = def_iseq_ptr(old_def); - break; - case VM_METHOD_TYPE_BMETHOD: + rb_warning("method redefined; discarding old %"PRIsVALUE, rb_id2str(mid)); + switch (old_def->type) { + case VM_METHOD_TYPE_ISEQ: + iseq = def_iseq_ptr(old_def); + break; + case VM_METHOD_TYPE_BMETHOD: iseq = rb_proc_get_iseq(old_def->body.bmethod.proc, 0); - break; - default: - break; - } - if (iseq) { - rb_compile_warning(RSTRING_PTR(rb_iseq_path(iseq)), + break; + default: + break; + } + if (iseq) { + rb_compile_warning(RSTRING_PTR(rb_iseq_path(iseq)), FIX2INT(ISEQ_BODY(iseq)->location.first_lineno), - "previous definition of %"PRIsVALUE" was here", - rb_id2str(old_def->original_id)); - } - } + "previous definition of %"PRIsVALUE" was here", + rb_id2str(old_def->original_id)); + } + } } /* create method entry */ @@ -935,13 +935,13 @@ rb_method_entry_make(VALUE klass, ID mid, VALUE defined_class, rb_method_visibil } /* check mid */ if (mid == object_id || mid == id__send__) { - if (type == VM_METHOD_TYPE_ISEQ && search_method(klass, mid, 0)) { - rb_warn("redefining `%s' may cause serious problems", rb_id2name(mid)); - } + if (type == VM_METHOD_TYPE_ISEQ && search_method(klass, mid, 0)) { + rb_warn("redefining `%s' may cause serious problems", rb_id2name(mid)); + } } if (make_refined) { - make_method_entry_refined(klass, me); + make_method_entry_refined(klass, me); } rb_method_table_insert(klass, mtbl, mid, me); @@ -950,7 +950,7 @@ rb_method_entry_make(VALUE klass, ID mid, VALUE defined_class, rb_method_visibil /* check optimized method override by a prepended module */ if (RB_TYPE_P(orig_klass, T_MODULE)) { - check_override_opt_method(klass, (VALUE)mid); + check_override_opt_method(klass, (VALUE)mid); } return me; @@ -1074,21 +1074,21 @@ check_overloaded_cme(const rb_callable_method_entry_t *cme, const struct rb_call } #define CALL_METHOD_HOOK(klass, hook, mid) do { \ - const VALUE arg = ID2SYM(mid); \ - VALUE recv_class = (klass); \ - ID hook_id = (hook); \ - if (FL_TEST((klass), FL_SINGLETON)) { \ - recv_class = rb_ivar_get((klass), attached); \ - hook_id = singleton_##hook; \ - } \ - rb_funcallv(recv_class, hook_id, 1, &arg); \ + const VALUE arg = ID2SYM(mid); \ + VALUE recv_class = (klass); \ + ID hook_id = (hook); \ + if (FL_TEST((klass), FL_SINGLETON)) { \ + recv_class = rb_ivar_get((klass), attached); \ + hook_id = singleton_##hook; \ + } \ + rb_funcallv(recv_class, hook_id, 1, &arg); \ } while (0) static void method_added(VALUE klass, ID mid) { if (ruby_running) { - CALL_METHOD_HOOK(klass, added, mid); + CALL_METHOD_HOOK(klass, added, mid); } } @@ -1098,7 +1098,7 @@ rb_add_method(VALUE klass, ID mid, rb_method_type_t type, void *opts, rb_method_ rb_method_entry_make(klass, mid, klass, visi, type, NULL, mid, opts); if (type != VM_METHOD_TYPE_UNDEF && type != VM_METHOD_TYPE_REFINED) { - method_added(klass, mid); + method_added(klass, mid); } } @@ -1118,10 +1118,10 @@ rb_add_method_iseq(VALUE klass, ID mid, const rb_iseq_t *iseq, rb_cref_t *cref, static rb_method_entry_t * method_entry_set(VALUE klass, ID mid, const rb_method_entry_t *me, - rb_method_visibility_t visi, VALUE defined_class) + rb_method_visibility_t visi, VALUE defined_class) { rb_method_entry_t *newme = rb_method_entry_make(klass, mid, defined_class, visi, - me->def->type, me->def, 0, NULL); + me->def->type, me->def, 0, NULL); if (newme == me) { me->def->no_redef_warning = TRUE; } @@ -1159,9 +1159,9 @@ rb_get_alloc_func(VALUE klass) Check_Type(klass, T_CLASS); for (; klass; klass = RCLASS_SUPER(klass)) { - rb_alloc_func_t allocator = RCLASS_ALLOCATOR(klass); - if (allocator == UNDEF_ALLOC_FUNC) break; - if (allocator) return allocator; + rb_alloc_func_t allocator = RCLASS_ALLOCATOR(klass); + if (allocator == UNDEF_ALLOC_FUNC) break; + if (allocator) return allocator; } return 0; } @@ -1180,7 +1180,7 @@ search_method0(VALUE klass, ID id, VALUE *defined_class_ptr, bool skip_refined) RB_DEBUG_COUNTER_INC(mc_search); for (; klass; klass = RCLASS_SUPER(klass)) { - RB_DEBUG_COUNTER_INC(mc_search_super); + RB_DEBUG_COUNTER_INC(mc_search_super); if ((me = lookup_method_table(klass, id)) != 0) { if (!skip_refined || me->def->type != VM_METHOD_TYPE_REFINED || me->def->body.refined.orig_me) { @@ -1393,18 +1393,18 @@ method_entry_resolve_refinement(VALUE klass, ID id, int with_refinement, VALUE * const rb_method_entry_t *me = search_method_protect(klass, id, defined_class_ptr); if (me) { - if (me->def->type == VM_METHOD_TYPE_REFINED) { - if (with_refinement) { - const rb_cref_t *cref = rb_vm_cref(); - VALUE refinements = cref ? CREF_REFINEMENTS(cref) : Qnil; - me = resolve_refined_method(refinements, me, defined_class_ptr); - } - else { - me = resolve_refined_method(Qnil, me, defined_class_ptr); - } + if (me->def->type == VM_METHOD_TYPE_REFINED) { + if (with_refinement) { + const rb_cref_t *cref = rb_vm_cref(); + VALUE refinements = cref ? CREF_REFINEMENTS(cref) : Qnil; + me = resolve_refined_method(refinements, me, defined_class_ptr); + } + else { + me = resolve_refined_method(Qnil, me, defined_class_ptr); + } - if (UNDEFINED_METHOD_ENTRY_P(me)) me = NULL; - } + if (UNDEFINED_METHOD_ENTRY_P(me)) me = NULL; + } } return me; @@ -1467,18 +1467,18 @@ static const rb_method_entry_t * resolve_refined_method(VALUE refinements, const rb_method_entry_t *me, VALUE *defined_class_ptr) { while (me && me->def->type == VM_METHOD_TYPE_REFINED) { - VALUE refinement; + VALUE refinement; const rb_method_entry_t *tmp_me; VALUE super; - refinement = find_refinement(refinements, me->owner); + refinement = find_refinement(refinements, me->owner); if (!NIL_P(refinement)) { - tmp_me = search_method_protect(refinement, me->called_id, defined_class_ptr); + tmp_me = search_method_protect(refinement, me->called_id, defined_class_ptr); - if (tmp_me && tmp_me->def->type != VM_METHOD_TYPE_REFINED) { - return tmp_me; - } - } + if (tmp_me && tmp_me->def->type != VM_METHOD_TYPE_REFINED) { + return tmp_me; + } + } tmp_me = me->def->body.refined.orig_me; if (tmp_me) { @@ -1510,10 +1510,10 @@ rb_resolve_refined_method_callable(VALUE refinements, const rb_callable_method_e const rb_method_entry_t *resolved_me = resolve_refined_method(refinements, (const rb_method_entry_t *)me, &defined_class); if (resolved_me && resolved_me->defined_class == 0) { - return rb_method_entry_complement_defined_class(resolved_me, me->called_id, defined_class); + return rb_method_entry_complement_defined_class(resolved_me, me->called_id, defined_class); } else { - return (const rb_callable_method_entry_t *)resolved_me; + return (const rb_callable_method_entry_t *)resolved_me; } } @@ -1527,15 +1527,15 @@ remove_method(VALUE klass, ID mid) klass = RCLASS_ORIGIN(klass); rb_class_modify_check(klass); if (mid == object_id || mid == id__send__ || mid == idInitialize) { - rb_warn("removing `%s' may cause serious problems", rb_id2name(mid)); + rb_warn("removing `%s' may cause serious problems", rb_id2name(mid)); } if (!rb_id_table_lookup(RCLASS_M_TBL(klass), mid, &data) || - !(me = (rb_method_entry_t *)data) || - (!me->def || me->def->type == VM_METHOD_TYPE_UNDEF) || + !(me = (rb_method_entry_t *)data) || + (!me->def || me->def->type == VM_METHOD_TYPE_UNDEF) || UNDEFINED_REFINED_METHOD_P(me->def)) { - rb_name_err_raise("method `%1$s' not defined in %2$s", - klass, ID2SYM(mid)); + rb_name_err_raise("method `%1$s' not defined in %2$s", + klass, ID2SYM(mid)); } if (klass != self) { @@ -1547,7 +1547,7 @@ remove_method(VALUE klass, ID mid) rb_vm_check_redefinition_opt_method(me, klass); if (me->def->type == VM_METHOD_TYPE_REFINED) { - rb_add_refined_method_entry(klass, mid); + rb_add_refined_method_entry(klass, mid); } CALL_METHOD_HOOK(self, removed, mid); @@ -1581,13 +1581,13 @@ rb_mod_remove_method(int argc, VALUE *argv, VALUE mod) int i; for (i = 0; i < argc; i++) { - VALUE v = argv[i]; - ID id = rb_check_id(&v); - if (!id) { - rb_name_err_raise("method `%1$s' not defined in %2$s", - mod, v); - } - remove_method(mod, id); + VALUE v = argv[i]; + ID id = rb_check_id(&v); + if (!id) { + rb_name_err_raise("method `%1$s' not defined in %2$s", + mod, v); + } + remove_method(mod, id); } return mod; } @@ -1602,18 +1602,18 @@ rb_export_method(VALUE klass, ID name, rb_method_visibility_t visi) me = search_method0(origin_class, name, &defined_class, true); if (!me && RB_TYPE_P(klass, T_MODULE)) { - me = search_method(rb_cObject, name, &defined_class); + me = search_method(rb_cObject, name, &defined_class); } if (UNDEFINED_METHOD_ENTRY_P(me) || - UNDEFINED_REFINED_METHOD_P(me->def)) { - rb_print_undef(klass, name, METHOD_VISI_UNDEF); + UNDEFINED_REFINED_METHOD_P(me->def)) { + rb_print_undef(klass, name, METHOD_VISI_UNDEF); } if (METHOD_ENTRY_VISI(me) != visi) { - rb_vm_check_redefinition_opt_method(me, klass); + rb_vm_check_redefinition_opt_method(me, klass); - if (klass == defined_class || origin_class == defined_class) { + if (klass == defined_class || origin_class == defined_class) { if (me->def->type == VM_METHOD_TYPE_REFINED) { // Refinement method entries should always be public because the refinement // search is always performed. @@ -1625,10 +1625,10 @@ rb_export_method(VALUE klass, ID name, rb_method_visibility_t visi) METHOD_ENTRY_VISI_SET(me, visi); } rb_clear_method_cache(klass, name); - } - else { - rb_add_method(klass, name, VM_METHOD_TYPE_ZSUPER, 0, visi); - } + } + else { + rb_add_method(klass, name, VM_METHOD_TYPE_ZSUPER, 0, visi); + } } } @@ -1659,13 +1659,13 @@ method_boundp(VALUE klass, ID id, int ex) default: break; } - } + } - if (cme->def->type == VM_METHOD_TYPE_NOTIMPLEMENTED) { - if (ex & BOUND_RESPONDS) return 2; - return 0; - } - return 1; + if (cme->def->type == VM_METHOD_TYPE_NOTIMPLEMENTED) { + if (ex & BOUND_RESPONDS) return 2; + return 0; + } + return 1; } return 0; } @@ -1719,31 +1719,31 @@ rb_attr(VALUE klass, ID id, int read, int write, int ex) const rb_cref_t *cref = rb_vm_cref_in_context(klass, klass); if (!ex || !cref) { - visi = METHOD_VISI_PUBLIC; + visi = METHOD_VISI_PUBLIC; } else { switch (vm_scope_visibility_get(ec)) { - case METHOD_VISI_PRIVATE: + case METHOD_VISI_PRIVATE: if (vm_scope_module_func_check(ec)) { - rb_warning("attribute accessor as module_function"); - } - visi = METHOD_VISI_PRIVATE; - break; - case METHOD_VISI_PROTECTED: - visi = METHOD_VISI_PROTECTED; - break; - default: - visi = METHOD_VISI_PUBLIC; - break; - } + rb_warning("attribute accessor as module_function"); + } + visi = METHOD_VISI_PRIVATE; + break; + case METHOD_VISI_PROTECTED: + visi = METHOD_VISI_PROTECTED; + break; + default: + visi = METHOD_VISI_PUBLIC; + break; + } } attriv = rb_intern_str(rb_sprintf("@%"PRIsVALUE, rb_id2str(id))); if (read) { - rb_add_method(klass, id, VM_METHOD_TYPE_IVAR, (void *)attriv, visi); + rb_add_method(klass, id, VM_METHOD_TYPE_IVAR, (void *)attriv, visi); } if (write) { - rb_add_method(klass, rb_id_attrset(id), VM_METHOD_TYPE_ATTRSET, (void *)attriv, visi); + rb_add_method(klass, rb_id_attrset(id), VM_METHOD_TYPE_ATTRSET, (void *)attriv, visi); } } @@ -1753,21 +1753,21 @@ rb_undef(VALUE klass, ID id) const rb_method_entry_t *me; if (NIL_P(klass)) { - rb_raise(rb_eTypeError, "no class to undef method"); + rb_raise(rb_eTypeError, "no class to undef method"); } rb_class_modify_check(klass); if (id == object_id || id == id__send__ || id == idInitialize) { - rb_warn("undefining `%s' may cause serious problems", rb_id2name(id)); + rb_warn("undefining `%s' may cause serious problems", rb_id2name(id)); } me = search_method(klass, id, 0); if (me && me->def->type == VM_METHOD_TYPE_REFINED) { - me = rb_resolve_refined_method(Qnil, me); + me = rb_resolve_refined_method(Qnil, me); } if (UNDEFINED_METHOD_ENTRY_P(me) || - UNDEFINED_REFINED_METHOD_P(me->def)) { - rb_method_name_error(klass, rb_id2str(id)); + UNDEFINED_REFINED_METHOD_P(me->def)) { + rb_method_name_error(klass, rb_id2str(id)); } rb_add_method(klass, id, VM_METHOD_TYPE_UNDEF, 0, METHOD_VISI_PUBLIC); @@ -1825,12 +1825,12 @@ rb_mod_undef_method(int argc, VALUE *argv, VALUE mod) { int i; for (i = 0; i < argc; i++) { - VALUE v = argv[i]; - ID id = rb_check_id(&v); - if (!id) { - rb_method_name_error(mod, v); - } - rb_undef(mod, id); + VALUE v = argv[i]; + ID id = rb_check_id(&v); + if (!id) { + rb_method_name_error(mod, v); + } + rb_undef(mod, id); } return mod; } @@ -1848,20 +1848,20 @@ check_definition_visibility(VALUE mod, int argc, VALUE *argv) if (!id) return METHOD_VISI_UNDEF; if (argc == 1) { - inc_super = 1; + inc_super = 1; } else { - inc_super = RTEST(include_super); - if (!inc_super) { - lookup_mod = RCLASS_ORIGIN(mod); - } + inc_super = RTEST(include_super); + if (!inc_super) { + lookup_mod = RCLASS_ORIGIN(mod); + } } me = rb_method_entry_without_refinements(lookup_mod, id, NULL); if (me) { - if (me->def->type == VM_METHOD_TYPE_NOTIMPLEMENTED) return METHOD_VISI_UNDEF; - if (!inc_super && me->owner != mod) return METHOD_VISI_UNDEF; - return METHOD_ENTRY_VISI(me); + if (me->def->type == VM_METHOD_TYPE_NOTIMPLEMENTED) return METHOD_VISI_UNDEF; + if (!inc_super && me->owner != mod) return METHOD_VISI_UNDEF; + return METHOD_ENTRY_VISI(me); } return METHOD_VISI_UNDEF; } @@ -2034,19 +2034,19 @@ original_method_definition(const rb_method_definition_t *def) { again: if (def) { - switch (def->type) { - case VM_METHOD_TYPE_REFINED: - if (def->body.refined.orig_me) { - def = def->body.refined.orig_me->def; - goto again; - } - break; - case VM_METHOD_TYPE_ALIAS: - def = def->body.alias.original_me->def; - goto again; - default: - break; - } + switch (def->type) { + case VM_METHOD_TYPE_REFINED: + if (def->body.refined.orig_me) { + def = def->body.refined.orig_me->def; + goto again; + } + break; + case VM_METHOD_TYPE_ALIAS: + def = def->body.alias.original_me->def; + goto again; + default: + break; + } } return def; } @@ -2065,26 +2065,26 @@ rb_method_definition_eq(const rb_method_definition_t *d1, const rb_method_defini case VM_METHOD_TYPE_ISEQ: return d1->body.iseq.iseqptr == d2->body.iseq.iseqptr; case VM_METHOD_TYPE_CFUNC: - return - d1->body.cfunc.func == d2->body.cfunc.func && - d1->body.cfunc.argc == d2->body.cfunc.argc; + return + d1->body.cfunc.func == d2->body.cfunc.func && + d1->body.cfunc.argc == d2->body.cfunc.argc; case VM_METHOD_TYPE_ATTRSET: case VM_METHOD_TYPE_IVAR: - return d1->body.attr.id == d2->body.attr.id; + return d1->body.attr.id == d2->body.attr.id; case VM_METHOD_TYPE_BMETHOD: return RTEST(rb_equal(d1->body.bmethod.proc, d2->body.bmethod.proc)); case VM_METHOD_TYPE_MISSING: - return d1->original_id == d2->original_id; + return d1->original_id == d2->original_id; case VM_METHOD_TYPE_ZSUPER: case VM_METHOD_TYPE_NOTIMPLEMENTED: case VM_METHOD_TYPE_UNDEF: - return 1; + return 1; case VM_METHOD_TYPE_OPTIMIZED: - return (d1->body.optimized.type == d2->body.optimized.type) && + return (d1->body.optimized.type == d2->body.optimized.type) && (d1->body.optimized.index == d2->body.optimized.index); case VM_METHOD_TYPE_REFINED: case VM_METHOD_TYPE_ALIAS: - break; + break; } rb_bug("rb_method_definition_eq: unsupported type: %d\n", d1->type); } @@ -2099,27 +2099,27 @@ rb_hash_method_definition(st_index_t hash, const rb_method_definition_t *def) switch (def->type) { case VM_METHOD_TYPE_ISEQ: - return rb_hash_uint(hash, (st_index_t)def->body.iseq.iseqptr); + return rb_hash_uint(hash, (st_index_t)def->body.iseq.iseqptr); case VM_METHOD_TYPE_CFUNC: - hash = rb_hash_uint(hash, (st_index_t)def->body.cfunc.func); - return rb_hash_uint(hash, def->body.cfunc.argc); + hash = rb_hash_uint(hash, (st_index_t)def->body.cfunc.func); + return rb_hash_uint(hash, def->body.cfunc.argc); case VM_METHOD_TYPE_ATTRSET: case VM_METHOD_TYPE_IVAR: - return rb_hash_uint(hash, def->body.attr.id); + return rb_hash_uint(hash, def->body.attr.id); case VM_METHOD_TYPE_BMETHOD: return rb_hash_proc(hash, def->body.bmethod.proc); case VM_METHOD_TYPE_MISSING: - return rb_hash_uint(hash, def->original_id); + return rb_hash_uint(hash, def->original_id); case VM_METHOD_TYPE_ZSUPER: case VM_METHOD_TYPE_NOTIMPLEMENTED: case VM_METHOD_TYPE_UNDEF: - return hash; + return hash; case VM_METHOD_TYPE_OPTIMIZED: hash = rb_hash_uint(hash, def->body.optimized.index); - return rb_hash_uint(hash, def->body.optimized.type); + return rb_hash_uint(hash, def->body.optimized.type); case VM_METHOD_TYPE_REFINED: case VM_METHOD_TYPE_ALIAS: - break; /* unreachable */ + break; /* unreachable */ } rb_bug("rb_hash_method_definition: unsupported method type (%d)\n", def->type); } @@ -2139,7 +2139,7 @@ rb_alias(VALUE klass, ID alias_name, ID original_name) rb_method_visibility_t visi = METHOD_VISI_UNDEF; if (NIL_P(klass)) { - rb_raise(rb_eTypeError, "no class to make alias"); + rb_raise(rb_eTypeError, "no class to make alias"); } rb_class_modify_check(klass); @@ -2148,24 +2148,24 @@ rb_alias(VALUE klass, ID alias_name, ID original_name) orig_me = search_method(klass, original_name, &defined_class); if (orig_me && orig_me->def->type == VM_METHOD_TYPE_REFINED) { - orig_me = rb_resolve_refined_method(Qnil, orig_me); + orig_me = rb_resolve_refined_method(Qnil, orig_me); } if (UNDEFINED_METHOD_ENTRY_P(orig_me) || - UNDEFINED_REFINED_METHOD_P(orig_me->def)) { - if ((!RB_TYPE_P(klass, T_MODULE)) || - (orig_me = search_method(rb_cObject, original_name, &defined_class), - UNDEFINED_METHOD_ENTRY_P(orig_me))) { - rb_print_undef(klass, original_name, METHOD_VISI_UNDEF); - } + UNDEFINED_REFINED_METHOD_P(orig_me->def)) { + if ((!RB_TYPE_P(klass, T_MODULE)) || + (orig_me = search_method(rb_cObject, original_name, &defined_class), + UNDEFINED_METHOD_ENTRY_P(orig_me))) { + rb_print_undef(klass, original_name, METHOD_VISI_UNDEF); + } } switch (orig_me->def->type) { case VM_METHOD_TYPE_ZSUPER: - klass = RCLASS_SUPER(klass); - original_name = orig_me->def->original_id; - visi = METHOD_ENTRY_VISI(orig_me); - goto again; + klass = RCLASS_SUPER(klass); + original_name = orig_me->def->original_id; + visi = METHOD_ENTRY_VISI(orig_me); + goto again; case VM_METHOD_TYPE_ALIAS: visi = METHOD_ENTRY_VISI(orig_me); orig_me = orig_me->def->body.alias.original_me; @@ -2177,16 +2177,16 @@ rb_alias(VALUE klass, ID alias_name, ID original_name) if (visi == METHOD_VISI_UNDEF) visi = METHOD_ENTRY_VISI(orig_me); if (orig_me->defined_class == 0) { - rb_method_entry_make(target_klass, alias_name, target_klass, visi, - VM_METHOD_TYPE_ALIAS, NULL, orig_me->called_id, - (void *)rb_method_entry_clone(orig_me)); - method_added(target_klass, alias_name); + rb_method_entry_make(target_klass, alias_name, target_klass, visi, + VM_METHOD_TYPE_ALIAS, NULL, orig_me->called_id, + (void *)rb_method_entry_clone(orig_me)); + method_added(target_klass, alias_name); } else { - rb_method_entry_t *alias_me; + rb_method_entry_t *alias_me; - alias_me = method_entry_set(target_klass, alias_name, orig_me, visi, orig_me->owner); - RB_OBJ_WRITE(alias_me, &alias_me->owner, target_klass); + alias_me = method_entry_set(target_klass, alias_name, orig_me, visi, orig_me->owner); + RB_OBJ_WRITE(alias_me, &alias_me->owner, target_klass); RB_OBJ_WRITE(alias_me, &alias_me->defined_class, orig_me->defined_class); } } @@ -2218,7 +2218,7 @@ rb_mod_alias_method(VALUE mod, VALUE newname, VALUE oldname) { ID oldid = rb_check_id(&oldname); if (!oldid) { - rb_print_undef_str(mod, oldname); + rb_print_undef_str(mod, oldname); } VALUE id = rb_to_id(newname); rb_alias(mod, id, oldid); @@ -2230,7 +2230,7 @@ check_and_export_method(VALUE self, VALUE name, rb_method_visibility_t visi) { ID id = rb_check_id(&name); if (!id) { - rb_print_undef_str(self, name); + rb_print_undef_str(self, name); } rb_export_method(self, id, visi); } @@ -2242,9 +2242,9 @@ set_method_visibility(VALUE self, int argc, const VALUE *argv, rb_method_visibil rb_check_frozen(self); if (argc == 0) { - rb_warning("%"PRIsVALUE" with no argument is just ignored", - QUOTE_ID(rb_frame_callee())); - return; + rb_warning("%"PRIsVALUE" with no argument is just ignored", + QUOTE_ID(rb_frame_callee())); + return; } @@ -2253,9 +2253,9 @@ set_method_visibility(VALUE self, int argc, const VALUE *argv, rb_method_visibil if (argc == 1 && (v = rb_check_array_type(argv[0])) != Qnil) { long j; - for (j = 0; j < RARRAY_LEN(v); j++) { - check_and_export_method(self, RARRAY_AREF(v, j), visi); - } + for (j = 0; j < RARRAY_LEN(v); j++) { + check_and_export_method(self, RARRAY_AREF(v, j), visi); + } } else { for (i = 0; i < argc; i++) { @@ -2632,36 +2632,36 @@ rb_mod_modfunc(int argc, VALUE *argv, VALUE module) const rb_method_entry_t *me; if (!RB_TYPE_P(module, T_MODULE)) { - rb_raise(rb_eTypeError, "module_function must be called for modules"); + rb_raise(rb_eTypeError, "module_function must be called for modules"); } if (argc == 0) { - rb_scope_module_func_set(); + rb_scope_module_func_set(); return Qnil; } set_method_visibility(module, argc, argv, METHOD_VISI_PRIVATE); for (i = 0; i < argc; i++) { - VALUE m = module; + VALUE m = module; - id = rb_to_id(argv[i]); - for (;;) { - me = search_method(m, id, 0); - if (me == 0) { - me = search_method(rb_cObject, id, 0); - } - if (UNDEFINED_METHOD_ENTRY_P(me)) { - rb_print_undef(module, id, METHOD_VISI_UNDEF); - } - if (me->def->type != VM_METHOD_TYPE_ZSUPER) { - break; /* normal case: need not to follow 'super' link */ - } - m = RCLASS_SUPER(m); - if (!m) - break; - } - rb_method_entry_set(rb_singleton_class(module), id, me, METHOD_VISI_PUBLIC); + id = rb_to_id(argv[i]); + for (;;) { + me = search_method(m, id, 0); + if (me == 0) { + me = search_method(rb_cObject, id, 0); + } + if (UNDEFINED_METHOD_ENTRY_P(me)) { + rb_print_undef(module, id, METHOD_VISI_UNDEF); + } + if (me->def->type != VM_METHOD_TYPE_ZSUPER) { + break; /* normal case: need not to follow 'super' link */ + } + m = RCLASS_SUPER(m); + if (!m) + break; + } + rb_method_entry_set(rb_singleton_class(module), id, me, METHOD_VISI_PUBLIC); } if (argc == 1) { return argv[0]; @@ -2697,7 +2697,7 @@ call_method_entry(rb_execution_context_t *ec, VALUE defined_class, VALUE obj, ID static VALUE basic_obj_respond_to_missing(rb_execution_context_t *ec, VALUE klass, VALUE obj, - VALUE mid, VALUE priv) + VALUE mid, VALUE priv) { VALUE defined_class, args[2]; const ID rtmid = idRespond_to_missing; @@ -2717,13 +2717,13 @@ basic_obj_respond_to(rb_execution_context_t *ec, VALUE obj, ID id, int pub) switch (method_boundp(klass, id, pub|BOUND_RESPONDS)) { case 2: - return FALSE; + return FALSE; case 0: - ret = basic_obj_respond_to_missing(ec, klass, obj, ID2SYM(id), - RBOOL(!pub)); - return RTEST(ret) && ret != Qundef; + ret = basic_obj_respond_to_missing(ec, klass, obj, ID2SYM(id), + RBOOL(!pub)); + return RTEST(ret) && ret != Qundef; default: - return TRUE; + return TRUE; } } @@ -2736,46 +2736,46 @@ vm_respond_to(rb_execution_context_t *ec, VALUE klass, VALUE obj, ID id, int pri if (!cme) return -1; if (METHOD_ENTRY_BASIC(cme)) { - return -1; + return -1; } else { - int argc = 1; - VALUE args[2]; - VALUE result; + int argc = 1; + VALUE args[2]; + VALUE result; - args[0] = ID2SYM(id); - args[1] = Qtrue; - if (priv) { + args[0] = ID2SYM(id); + args[1] = Qtrue; + if (priv) { argc = rb_method_entry_arity((const rb_method_entry_t *)cme); - if (argc > 2) { - rb_raise(rb_eArgError, - "respond_to? must accept 1 or 2 arguments (requires %d)", - argc); - } - if (argc != 1) { - argc = 2; - } - else if (!NIL_P(ruby_verbose)) { - VALUE location = rb_method_entry_location((const rb_method_entry_t *)cme); + if (argc > 2) { + rb_raise(rb_eArgError, + "respond_to? must accept 1 or 2 arguments (requires %d)", + argc); + } + if (argc != 1) { + argc = 2; + } + else if (!NIL_P(ruby_verbose)) { + VALUE location = rb_method_entry_location((const rb_method_entry_t *)cme); rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "%"PRIsVALUE"%c""respond_to?(:%"PRIsVALUE") uses" - " the deprecated method signature, which takes one parameter", - (FL_TEST(klass, FL_SINGLETON) ? obj : klass), - (FL_TEST(klass, FL_SINGLETON) ? '.' : '#'), - QUOTE_ID(id)); - if (!NIL_P(location)) { - VALUE path = RARRAY_AREF(location, 0); - VALUE line = RARRAY_AREF(location, 1); - if (!NIL_P(path)) { - rb_category_compile_warn(RB_WARN_CATEGORY_DEPRECATED, - RSTRING_PTR(path), NUM2INT(line), - "respond_to? is defined here"); - } - } - } - } + " the deprecated method signature, which takes one parameter", + (FL_TEST(klass, FL_SINGLETON) ? obj : klass), + (FL_TEST(klass, FL_SINGLETON) ? '.' : '#'), + QUOTE_ID(id)); + if (!NIL_P(location)) { + VALUE path = RARRAY_AREF(location, 0); + VALUE line = RARRAY_AREF(location, 1); + if (!NIL_P(path)) { + rb_category_compile_warn(RB_WARN_CATEGORY_DEPRECATED, + RSTRING_PTR(path), NUM2INT(line), + "respond_to? is defined here"); + } + } + } + } result = call_method_entry(ec, defined_class, obj, resid, cme, argc, args, RB_NO_KEYWORDS); - return RTEST(result); + return RTEST(result); } } @@ -2831,10 +2831,10 @@ obj_respond_to(int argc, VALUE *argv, VALUE obj) rb_scan_args(argc, argv, "11", &mid, &priv); if (!(id = rb_check_id(&mid))) { - VALUE ret = basic_obj_respond_to_missing(ec, CLASS_OF(obj), obj, - rb_to_symbol(mid), priv); - if (ret == Qundef) ret = Qfalse; - return ret; + VALUE ret = basic_obj_respond_to_missing(ec, CLASS_OF(obj), obj, + rb_to_symbol(mid), priv); + if (ret == Qundef) ret = Qfalse; + return ret; } return RBOOL(basic_obj_respond_to(ec, obj, id, !RTEST(priv))); } @@ -2889,20 +2889,20 @@ Init_eval_method(void) rb_define_method(rb_cModule, "private_class_method", rb_mod_private_method, -1); rb_define_private_method(rb_singleton_class(rb_vm_top_self()), - "public", top_public, -1); + "public", top_public, -1); rb_define_private_method(rb_singleton_class(rb_vm_top_self()), - "private", top_private, -1); + "private", top_private, -1); rb_define_private_method(rb_singleton_class(rb_vm_top_self()), - "ruby2_keywords", top_ruby2_keywords, -1); + "ruby2_keywords", top_ruby2_keywords, -1); { #define REPLICATE_METHOD(klass, id) do { \ - const rb_method_entry_t *me = rb_method_entry((klass), (id)); \ - rb_method_entry_set((klass), (id), me, METHOD_ENTRY_VISI(me)); \ - } while (0) + const rb_method_entry_t *me = rb_method_entry((klass), (id)); \ + rb_method_entry_set((klass), (id), me, METHOD_ENTRY_VISI(me)); \ + } while (0) - REPLICATE_METHOD(rb_eException, idMethodMissing); - REPLICATE_METHOD(rb_eException, idRespond_to); - REPLICATE_METHOD(rb_eException, idRespond_to_missing); + REPLICATE_METHOD(rb_eException, idMethodMissing); + REPLICATE_METHOD(rb_eException, idRespond_to); + REPLICATE_METHOD(rb_eException, idRespond_to_missing); } } diff --git a/vm_trace.c b/vm_trace.c index 51b815c54a..93a8c1a4ed 100644 --- a/vm_trace.c +++ b/vm_trace.c @@ -46,7 +46,7 @@ typedef struct rb_event_hook_struct { struct rb_event_hook_struct *next; struct { - rb_thread_t *th; + rb_thread_t *th; unsigned int target_line; } filter; } rb_event_hook_t; @@ -61,8 +61,8 @@ rb_hook_list_mark(rb_hook_list_t *hooks) rb_event_hook_t *hook = hooks->hooks; while (hook) { - rb_gc_mark(hook->data); - hook = hook->next; + rb_gc_mark(hook->data); + hook = hook->next; } } @@ -96,8 +96,8 @@ update_global_event_hook(rb_event_flag_t prev_events, rb_event_flag_t new_events mjit_cancel_all("TracePoint is enabled"); } - /* write all ISeqs if and only if new events are added */ - rb_iseq_trace_set_all(new_iseq_events | enabled_iseq_events); + /* write all ISeqs if and only if new events are added */ + rb_iseq_trace_set_all(new_iseq_events | enabled_iseq_events); } else { // if c_call or c_return is activated: @@ -127,7 +127,7 @@ alloc_event_hook(rb_event_hook_func_t func, rb_event_flag_t events, VALUE data, rb_event_hook_t *hook; if ((events & RUBY_INTERNAL_EVENT_MASK) && (events & ~RUBY_INTERNAL_EVENT_MASK)) { - rb_raise(rb_eTypeError, "Can not specify normal event and internal event simultaneously."); + rb_raise(rb_eTypeError, "Can not specify normal event and internal event simultaneously."); } hook = ALLOC(rb_event_hook_t); @@ -169,7 +169,7 @@ connect_event_hook(const rb_execution_context_t *ec, rb_event_hook_t *hook) static void rb_threadptr_add_event_hook(const rb_execution_context_t *ec, rb_thread_t *th, - rb_event_hook_func_t func, rb_event_flag_t events, VALUE data, rb_event_hook_flag_t hook_flags) + rb_event_hook_func_t func, rb_event_flag_t events, VALUE data, rb_event_hook_flag_t hook_flags) { rb_event_hook_t *hook = alloc_event_hook(func, events, data, hook_flags); hook->filter.th = th; @@ -214,14 +214,14 @@ clean_hooks(const rb_execution_context_t *ec, rb_hook_list_t *list) list->need_clean = false; while ((hook = *nextp) != 0) { - if (hook->hook_flags & RUBY_EVENT_HOOK_FLAG_DELETED) { - *nextp = hook->next; - xfree(hook); - } - else { - list->events |= hook->events; /* update active events */ - nextp = &hook->next; - } + if (hook->hook_flags & RUBY_EVENT_HOOK_FLAG_DELETED) { + *nextp = hook->next; + xfree(hook); + } + else { + list->events |= hook->events; /* update active events */ + nextp = &hook->next; + } } if (list->is_local) { @@ -256,16 +256,16 @@ remove_event_hook(const rb_execution_context_t *ec, const rb_thread_t *filter_th rb_event_hook_t *hook = list->hooks; while (hook) { - if (func == 0 || hook->func == func) { - if (hook->filter.th == filter_th || filter_th == MATCH_ANY_FILTER_TH) { - if (data == Qundef || hook->data == data) { - hook->hook_flags |= RUBY_EVENT_HOOK_FLAG_DELETED; - ret+=1; - list->need_clean = true; - } - } - } - hook = hook->next; + if (func == 0 || hook->func == func) { + if (hook->filter.th == filter_th || filter_th == MATCH_ANY_FILTER_TH) { + if (data == Qundef || hook->data == data) { + hook->hook_flags |= RUBY_EVENT_HOOK_FLAG_DELETED; + ret+=1; + list->need_clean = true; + } + } + } + hook = hook->next; } clean_hooks_check(ec, list); @@ -322,17 +322,17 @@ exec_hooks_body(const rb_execution_context_t *ec, rb_hook_list_t *list, const rb rb_event_hook_t *hook; for (hook = list->hooks; hook; hook = hook->next) { - if (!(hook->hook_flags & RUBY_EVENT_HOOK_FLAG_DELETED) && - (trace_arg->event & hook->events) && + if (!(hook->hook_flags & RUBY_EVENT_HOOK_FLAG_DELETED) && + (trace_arg->event & hook->events) && (LIKELY(hook->filter.th == 0) || hook->filter.th == rb_ec_thread_ptr(ec)) && (LIKELY(hook->filter.target_line == 0) || (hook->filter.target_line == (unsigned int)rb_vm_get_sourceline(ec->cfp)))) { - if (!(hook->hook_flags & RUBY_EVENT_HOOK_FLAG_RAW_ARG)) { - (*hook->func)(trace_arg->event, hook->data, trace_arg->self, trace_arg->id, trace_arg->klass); - } - else { - (*((rb_event_hook_raw_arg_func_t)hook->func))(hook->data, trace_arg); - } - } + if (!(hook->hook_flags & RUBY_EVENT_HOOK_FLAG_RAW_ARG)) { + (*hook->func)(trace_arg->event, hook->data, trace_arg->self, trace_arg->id, trace_arg->klass); + } + else { + (*((rb_event_hook_raw_arg_func_t)hook->func))(hook->data, trace_arg); + } + } } } @@ -341,10 +341,10 @@ exec_hooks_precheck(const rb_execution_context_t *ec, rb_hook_list_t *list, cons { if (list->events & trace_arg->event) { list->running++; - return TRUE; + return TRUE; } else { - return FALSE; + return FALSE; } } @@ -377,14 +377,14 @@ exec_hooks_protected(rb_execution_context_t *ec, rb_hook_list_t *list, const rb_ EC_PUSH_TAG(ec); if ((state = EC_EXEC_TAG()) == TAG_NONE) { - exec_hooks_body(ec, list, trace_arg); + exec_hooks_body(ec, list, trace_arg); } EC_POP_TAG(); exec_hooks_postcheck(ec, list); if (raised) { - rb_ec_set_raised(ec); + rb_ec_set_raised(ec); } return state; @@ -399,27 +399,27 @@ rb_exec_event_hooks(rb_trace_arg_t *trace_arg, rb_hook_list_t *hooks, int pop_p) if (UNLIKELY(trace_arg->event & RUBY_INTERNAL_EVENT_MASK)) { if (ec->trace_arg && (ec->trace_arg->event & RUBY_INTERNAL_EVENT_MASK)) { /* skip hooks because this thread doing INTERNAL_EVENT */ - } - else { - rb_trace_arg_t *prev_trace_arg = ec->trace_arg; + } + else { + rb_trace_arg_t *prev_trace_arg = ec->trace_arg; ec->trace_arg = trace_arg; /* only global hooks */ exec_hooks_unprotected(ec, rb_ec_ractor_hooks(ec), trace_arg); ec->trace_arg = prev_trace_arg; - } + } } else { - if (ec->trace_arg == NULL && /* check reentrant */ - trace_arg->self != rb_mRubyVMFrozenCore /* skip special methods. TODO: remove it. */) { - const VALUE errinfo = ec->errinfo; - const VALUE old_recursive = ec->local_storage_recursive_hash; - int state = 0; + if (ec->trace_arg == NULL && /* check reentrant */ + trace_arg->self != rb_mRubyVMFrozenCore /* skip special methods. TODO: remove it. */) { + const VALUE errinfo = ec->errinfo; + const VALUE old_recursive = ec->local_storage_recursive_hash; + int state = 0; /* setup */ - ec->local_storage_recursive_hash = ec->local_storage_recursive_hash_for_trace; - ec->errinfo = Qnil; - ec->trace_arg = trace_arg; + ec->local_storage_recursive_hash = ec->local_storage_recursive_hash_for_trace; + ec->errinfo = Qnil; + ec->trace_arg = trace_arg; /* kick hooks */ if ((state = exec_hooks_protected(ec, hooks, trace_arg)) == TAG_NONE) { @@ -428,19 +428,19 @@ rb_exec_event_hooks(rb_trace_arg_t *trace_arg, rb_hook_list_t *hooks, int pop_p) /* cleanup */ ec->trace_arg = NULL; - ec->local_storage_recursive_hash_for_trace = ec->local_storage_recursive_hash; - ec->local_storage_recursive_hash = old_recursive; + ec->local_storage_recursive_hash_for_trace = ec->local_storage_recursive_hash; + ec->local_storage_recursive_hash = old_recursive; - if (state) { - if (pop_p) { - if (VM_FRAME_FINISHED_P(ec->cfp)) { - ec->tag = ec->tag->prev; - } - rb_vm_pop_frame(ec); - } - EC_JUMP_TAG(ec, state); - } - } + if (state) { + if (pop_p) { + if (VM_FRAME_FINISHED_P(ec->cfp)) { + ec->tag = ec->tag->prev; + } + rb_vm_pop_frame(ec); + } + EC_JUMP_TAG(ec, state); + } + } } } @@ -456,33 +456,33 @@ rb_suppress_tracing(VALUE (*func)(VALUE), VALUE arg) dummy_trace_arg.event = 0; if (!ec->trace_arg) { - ec->trace_arg = &dummy_trace_arg; + ec->trace_arg = &dummy_trace_arg; } raised = rb_ec_reset_raised(ec); EC_PUSH_TAG(ec); if (LIKELY((state = EC_EXEC_TAG()) == TAG_NONE)) { - result = (*func)(arg); + result = (*func)(arg); } else { - (void)*&vm; /* suppress "clobbered" warning */ + (void)*&vm; /* suppress "clobbered" warning */ } EC_POP_TAG(); if (raised) { - rb_ec_reset_raised(ec); + rb_ec_reset_raised(ec); } if (ec->trace_arg == &dummy_trace_arg) { - ec->trace_arg = NULL; + ec->trace_arg = NULL; } if (state) { #if defined RUBY_USE_SETJMPEX && RUBY_USE_SETJMPEX - RB_GC_GUARD(result); + RB_GC_GUARD(result); #endif - EC_JUMP_TAG(ec, state); + EC_JUMP_TAG(ec, state); } return result; @@ -561,11 +561,11 @@ set_trace_func(VALUE obj, VALUE trace) rb_remove_event_hook(call_trace_func); if (NIL_P(trace)) { - return Qnil; + return Qnil; } if (!rb_obj_is_proc(trace)) { - rb_raise(rb_eTypeError, "trace_func needs to be Proc"); + rb_raise(rb_eTypeError, "trace_func needs to be Proc"); } rb_add_event_hook(call_trace_func, RUBY_EVENT_ALL, trace); @@ -576,7 +576,7 @@ static void thread_add_trace_func(rb_execution_context_t *ec, rb_thread_t *filter_th, VALUE trace) { if (!rb_obj_is_proc(trace)) { - rb_raise(rb_eTypeError, "trace_func needs to be Proc"); + rb_raise(rb_eTypeError, "trace_func needs to be Proc"); } rb_threadptr_add_event_hook(ec, filter_th, call_trace_func, RUBY_EVENT_ALL, trace, RUBY_EVENT_HOOK_FLAG_SAFE); @@ -618,11 +618,11 @@ thread_set_trace_func_m(VALUE target_thread, VALUE trace) rb_threadptr_remove_event_hook(ec, target_th, call_trace_func, Qundef); if (NIL_P(trace)) { - return Qnil; + return Qnil; } else { - thread_add_trace_func(ec, target_th, trace); - return trace; + thread_add_trace_func(ec, target_th, trace); + return trace; } } @@ -639,7 +639,7 @@ get_event_name(rb_event_flag_t event) case RUBY_EVENT_C_RETURN: return "c-return"; case RUBY_EVENT_RAISE: return "raise"; default: - return "unknown"; + return "unknown"; } } @@ -650,23 +650,23 @@ get_event_id(rb_event_flag_t event) switch (event) { #define C(name, NAME) case RUBY_EVENT_##NAME: CONST_ID(id, #name); return id; - C(line, LINE); - C(class, CLASS); - C(end, END); - C(call, CALL); - C(return, RETURN); - C(c_call, C_CALL); - C(c_return, C_RETURN); - C(raise, RAISE); - C(b_call, B_CALL); - C(b_return, B_RETURN); - C(thread_begin, THREAD_BEGIN); - C(thread_end, THREAD_END); - C(fiber_switch, FIBER_SWITCH); + C(line, LINE); + C(class, CLASS); + C(end, END); + C(call, CALL); + C(return, RETURN); + C(c_call, C_CALL); + C(c_return, C_RETURN); + C(raise, RAISE); + C(b_call, B_CALL); + C(b_return, B_RETURN); + C(thread_begin, THREAD_BEGIN); + C(thread_end, THREAD_END); + C(fiber_switch, FIBER_SWITCH); C(script_compiled, SCRIPT_COMPILED); #undef C default: - return 0; + return 0; } } @@ -676,21 +676,21 @@ get_path_and_lineno(const rb_execution_context_t *ec, const rb_control_frame_t * cfp = rb_vm_get_ruby_level_next_cfp(ec, cfp); if (cfp) { - const rb_iseq_t *iseq = cfp->iseq; - *pathp = rb_iseq_path(iseq); + const rb_iseq_t *iseq = cfp->iseq; + *pathp = rb_iseq_path(iseq); - if (event & (RUBY_EVENT_CLASS | - RUBY_EVENT_CALL | - RUBY_EVENT_B_CALL)) { - *linep = FIX2INT(rb_iseq_first_lineno(iseq)); - } - else { - *linep = rb_vm_get_sourceline(cfp); - } + if (event & (RUBY_EVENT_CLASS | + RUBY_EVENT_CALL | + RUBY_EVENT_B_CALL)) { + *linep = FIX2INT(rb_iseq_first_lineno(iseq)); + } + else { + *linep = rb_vm_get_sourceline(cfp); + } } else { - *pathp = Qnil; - *linep = 0; + *pathp = Qnil; + *linep = 0; } } @@ -706,16 +706,16 @@ call_trace_func(rb_event_flag_t event, VALUE proc, VALUE self, ID id, VALUE klas get_path_and_lineno(ec, ec->cfp, event, &filename, &line); if (!klass) { - rb_ec_frame_method_id_and_class(ec, &id, 0, &klass); + rb_ec_frame_method_id_and_class(ec, &id, 0, &klass); } if (klass) { - if (RB_TYPE_P(klass, T_ICLASS)) { - klass = RBASIC(klass)->klass; - } - else if (FL_TEST(klass, FL_SINGLETON)) { - klass = rb_ivar_get(klass, id__attached__); - } + if (RB_TYPE_P(klass, T_ICLASS)) { + klass = RBASIC(klass)->klass; + } + else if (FL_TEST(klass, FL_SINGLETON)) { + klass = rb_ivar_get(klass, id__attached__); + } } argv[0] = eventname; @@ -787,9 +787,9 @@ symbol2event_flag(VALUE v) ID id; VALUE sym = rb_to_symbol_type(v); const rb_event_flag_t RUBY_EVENT_A_CALL = - RUBY_EVENT_CALL | RUBY_EVENT_B_CALL | RUBY_EVENT_C_CALL; + RUBY_EVENT_CALL | RUBY_EVENT_B_CALL | RUBY_EVENT_C_CALL; const rb_event_flag_t RUBY_EVENT_A_RETURN = - RUBY_EVENT_RETURN | RUBY_EVENT_B_RETURN | RUBY_EVENT_C_RETURN; + RUBY_EVENT_RETURN | RUBY_EVENT_B_RETURN | RUBY_EVENT_C_RETURN; #define C(name, NAME) CONST_ID(id, #name); if (sym == ID2SYM(id)) return RUBY_EVENT_##NAME C(line, LINE); @@ -827,7 +827,7 @@ get_trace_arg(void) { rb_trace_arg_t *trace_arg = GET_EC()->trace_arg; if (trace_arg == 0) { - rb_raise(rb_eRuntimeError, "access from outside"); + rb_raise(rb_eRuntimeError, "access from outside"); } return trace_arg; } @@ -854,7 +854,7 @@ static void fill_path_and_lineno(rb_trace_arg_t *trace_arg) { if (trace_arg->path == Qundef) { - get_path_and_lineno(trace_arg->ec, trace_arg->cfp, trace_arg->event, &trace_arg->path, &trace_arg->lineno); + get_path_and_lineno(trace_arg->ec, trace_arg->cfp, trace_arg->event, &trace_arg->path, &trace_arg->lineno); } } @@ -875,20 +875,20 @@ static void fill_id_and_klass(rb_trace_arg_t *trace_arg) { if (!trace_arg->klass_solved) { - if (!trace_arg->klass) { - rb_vm_control_frame_id_and_class(trace_arg->cfp, &trace_arg->id, &trace_arg->called_id, &trace_arg->klass); - } + if (!trace_arg->klass) { + rb_vm_control_frame_id_and_class(trace_arg->cfp, &trace_arg->id, &trace_arg->called_id, &trace_arg->klass); + } - if (trace_arg->klass) { - if (RB_TYPE_P(trace_arg->klass, T_ICLASS)) { - trace_arg->klass = RBASIC(trace_arg->klass)->klass; - } - } - else { - trace_arg->klass = Qnil; - } + if (trace_arg->klass) { + if (RB_TYPE_P(trace_arg->klass, T_ICLASS)) { + trace_arg->klass = RBASIC(trace_arg->klass)->klass; + } + } + else { + trace_arg->klass = Qnil; + } - trace_arg->klass_solved = 1; + trace_arg->klass_solved = 1; } } @@ -900,34 +900,34 @@ rb_tracearg_parameters(rb_trace_arg_t *trace_arg) case RUBY_EVENT_RETURN: case RUBY_EVENT_B_CALL: case RUBY_EVENT_B_RETURN: { - const rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(trace_arg->ec, trace_arg->cfp); - if (cfp) { + const rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(trace_arg->ec, trace_arg->cfp); + if (cfp) { int is_proc = 0; if (VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_BLOCK && !VM_FRAME_LAMBDA_P(cfp)) { is_proc = 1; } - return rb_iseq_parameters(cfp->iseq, is_proc); - } - break; + return rb_iseq_parameters(cfp->iseq, is_proc); + } + break; } case RUBY_EVENT_C_CALL: case RUBY_EVENT_C_RETURN: { - fill_id_and_klass(trace_arg); - if (trace_arg->klass && trace_arg->id) { - const rb_method_entry_t *me; - VALUE iclass = Qnil; - me = rb_method_entry_without_refinements(trace_arg->klass, trace_arg->id, &iclass); - return rb_unnamed_parameters(rb_method_entry_arity(me)); - } - break; + fill_id_and_klass(trace_arg); + if (trace_arg->klass && trace_arg->id) { + const rb_method_entry_t *me; + VALUE iclass = Qnil; + me = rb_method_entry_without_refinements(trace_arg->klass, trace_arg->id, &iclass); + return rb_unnamed_parameters(rb_method_entry_arity(me)); + } + break; } case RUBY_EVENT_RAISE: case RUBY_EVENT_LINE: case RUBY_EVENT_CLASS: case RUBY_EVENT_END: case RUBY_EVENT_SCRIPT_COMPILED: - rb_raise(rb_eRuntimeError, "not supported by this event"); - break; + rb_raise(rb_eRuntimeError, "not supported by this event"); + break; } return Qnil; } @@ -960,10 +960,10 @@ rb_tracearg_binding(rb_trace_arg_t *trace_arg) cfp = rb_vm_get_binding_creatable_next_cfp(trace_arg->ec, trace_arg->cfp); if (cfp && imemo_type_p((VALUE)cfp->iseq, imemo_iseq)) { - return rb_vm_make_binding(trace_arg->ec, cfp); + return rb_vm_make_binding(trace_arg->ec, cfp); } else { - return Qnil; + return Qnil; } } @@ -977,10 +977,10 @@ VALUE rb_tracearg_return_value(rb_trace_arg_t *trace_arg) { if (trace_arg->event & (RUBY_EVENT_RETURN | RUBY_EVENT_C_RETURN | RUBY_EVENT_B_RETURN)) { - /* ok */ + /* ok */ } else { - rb_raise(rb_eRuntimeError, "not supported by this event"); + rb_raise(rb_eRuntimeError, "not supported by this event"); } if (trace_arg->data == Qundef) { rb_bug("rb_tracearg_return_value: unreachable"); @@ -992,10 +992,10 @@ VALUE rb_tracearg_raised_exception(rb_trace_arg_t *trace_arg) { if (trace_arg->event & (RUBY_EVENT_RAISE)) { - /* ok */ + /* ok */ } else { - rb_raise(rb_eRuntimeError, "not supported by this event"); + rb_raise(rb_eRuntimeError, "not supported by this event"); } if (trace_arg->data == Qundef) { rb_bug("rb_tracearg_raised_exception: unreachable"); @@ -1058,10 +1058,10 @@ VALUE rb_tracearg_object(rb_trace_arg_t *trace_arg) { if (trace_arg->event & (RUBY_INTERNAL_EVENT_NEWOBJ | RUBY_INTERNAL_EVENT_FREEOBJ)) { - /* ok */ + /* ok */ } else { - rb_raise(rb_eRuntimeError, "not supported by this event"); + rb_raise(rb_eRuntimeError, "not supported by this event"); } if (trace_arg->data == Qundef) { rb_bug("rb_tracearg_object: unreachable"); @@ -1152,7 +1152,7 @@ tp_call_trace(VALUE tpval, rb_trace_arg_t *trace_arg) rb_tp_t *tp = tpptr(tpval); if (tp->func) { - (*tp->func)(tpval, tp->data); + (*tp->func)(tpval, tp->data); } else { if (tp->ractor == NULL || tp->ractor == GET_RACTOR()) { @@ -1172,12 +1172,12 @@ rb_tracepoint_enable(VALUE tpval) } if (tp->target_th) { - rb_thread_add_event_hook2(tp->target_th->self, (rb_event_hook_func_t)tp_call_trace, tp->events, tpval, - RUBY_EVENT_HOOK_FLAG_SAFE | RUBY_EVENT_HOOK_FLAG_RAW_ARG); + rb_thread_add_event_hook2(tp->target_th->self, (rb_event_hook_func_t)tp_call_trace, tp->events, tpval, + RUBY_EVENT_HOOK_FLAG_SAFE | RUBY_EVENT_HOOK_FLAG_RAW_ARG); } else { - rb_add_event_hook2((rb_event_hook_func_t)tp_call_trace, tp->events, tpval, - RUBY_EVENT_HOOK_FLAG_SAFE | RUBY_EVENT_HOOK_FLAG_RAW_ARG); + rb_add_event_hook2((rb_event_hook_func_t)tp_call_trace, tp->events, tpval, + RUBY_EVENT_HOOK_FLAG_SAFE | RUBY_EVENT_HOOK_FLAG_RAW_ARG); } tp->tracing = 1; return Qundef; @@ -1369,12 +1369,12 @@ tracepoint_enable_m(rb_execution_context_t *ec, VALUE tpval, VALUE target, VALUE } if (rb_block_given_p()) { - return rb_ensure(rb_yield, Qundef, - previous_tracing ? rb_tracepoint_enable : rb_tracepoint_disable, - tpval); + return rb_ensure(rb_yield, Qundef, + previous_tracing ? rb_tracepoint_enable : rb_tracepoint_disable, + tpval); } else { - return RBOOL(previous_tracing); + return RBOOL(previous_tracing); } } @@ -1391,12 +1391,12 @@ tracepoint_disable_m(rb_execution_context_t *ec, VALUE tpval) rb_tracepoint_disable(tpval); return rb_ensure(rb_yield, Qundef, - previous_tracing ? rb_tracepoint_enable : rb_tracepoint_disable, - tpval); + previous_tracing ? rb_tracepoint_enable : rb_tracepoint_disable, + tpval); } else { rb_tracepoint_disable(tpval); - return RBOOL(previous_tracing); + return RBOOL(previous_tracing); } } @@ -1436,10 +1436,10 @@ rb_tracepoint_new(VALUE target_thval, rb_event_flag_t events, void (*func)(VALUE rb_thread_t *target_th = NULL; if (RTEST(target_thval)) { - target_th = rb_thread_ptr(target_thval); - /* TODO: Test it! - * Warning: This function is not tested. - */ + target_th = rb_thread_ptr(target_thval); + /* TODO: Test it! + * Warning: This function is not tested. + */ } return tracepoint_new(rb_cTracePoint, target_th, events, func, data, Qundef); } @@ -1453,15 +1453,15 @@ tracepoint_new_s(rb_execution_context_t *ec, VALUE self, VALUE args) if (argc > 0) { for (i=0; itrace_arg; if (trace_arg) { - switch (trace_arg->event) { - case RUBY_EVENT_LINE: - { - VALUE sym = rb_tracearg_method_id(trace_arg); - if (NIL_P(sym)) + switch (trace_arg->event) { + case RUBY_EVENT_LINE: + { + VALUE sym = rb_tracearg_method_id(trace_arg); + if (NIL_P(sym)) break; - return rb_sprintf("#", - rb_tracearg_event(trace_arg), - rb_tracearg_path(trace_arg), - FIX2INT(rb_tracearg_lineno(trace_arg)), - sym); - } - case RUBY_EVENT_CALL: - case RUBY_EVENT_C_CALL: - case RUBY_EVENT_RETURN: - case RUBY_EVENT_C_RETURN: - return rb_sprintf("#", - rb_tracearg_event(trace_arg), - rb_tracearg_method_id(trace_arg), - rb_tracearg_path(trace_arg), - FIX2INT(rb_tracearg_lineno(trace_arg))); - case RUBY_EVENT_THREAD_BEGIN: - case RUBY_EVENT_THREAD_END: - return rb_sprintf("#", - rb_tracearg_event(trace_arg), - rb_tracearg_self(trace_arg)); - default: + return rb_sprintf("#", + rb_tracearg_event(trace_arg), + rb_tracearg_path(trace_arg), + FIX2INT(rb_tracearg_lineno(trace_arg)), + sym); + } + case RUBY_EVENT_CALL: + case RUBY_EVENT_C_CALL: + case RUBY_EVENT_RETURN: + case RUBY_EVENT_C_RETURN: + return rb_sprintf("#", + rb_tracearg_event(trace_arg), + rb_tracearg_method_id(trace_arg), + rb_tracearg_path(trace_arg), + FIX2INT(rb_tracearg_lineno(trace_arg))); + case RUBY_EVENT_THREAD_BEGIN: + case RUBY_EVENT_THREAD_END: + return rb_sprintf("#", + rb_tracearg_event(trace_arg), + rb_tracearg_self(trace_arg)); + default: break; - } + } return rb_sprintf("#", rb_tracearg_event(trace_arg), rb_tracearg_path(trace_arg), FIX2INT(rb_tracearg_lineno(trace_arg))); } else { - return rb_sprintf("#", tp->tracing ? "enabled" : "disabled"); + return rb_sprintf("#", tp->tracing ? "enabled" : "disabled"); } } @@ -1527,13 +1527,13 @@ tracepoint_stat_event_hooks(VALUE hash, VALUE key, rb_event_hook_t *hook) int active = 0, deleted = 0; while (hook) { - if (hook->hook_flags & RUBY_EVENT_HOOK_FLAG_DELETED) { - deleted++; - } - else { - active++; - } - hook = hook->next; + if (hook->hook_flags & RUBY_EVENT_HOOK_FLAG_DELETED) { + deleted++; + } + else { + active++; + } + hook = hook->next; } rb_hash_aset(hash, key, rb_ary_new3(2, INT2FIX(active), INT2FIX(deleted))); @@ -1762,8 +1762,8 @@ rb_postponed_job_flush(rb_vm_t *vm) /* mask POSTPONED_JOB dispatch */ ec->interrupt_mask |= block_mask; { - EC_PUSH_TAG(ec); - if (EC_EXEC_TAG() == TAG_NONE) { + EC_PUSH_TAG(ec); + if (EC_EXEC_TAG() == TAG_NONE) { rb_atomic_t index; struct rb_workqueue_job *wq_job; @@ -1772,15 +1772,15 @@ rb_postponed_job_flush(rb_vm_t *vm) rb_postponed_job_t *pjob = &vm->postponed_job_buffer[index-1]; (*pjob->func)(pjob->data); } - } + } while ((wq_job = ccan_list_pop(&tmp, struct rb_workqueue_job, jnode))) { rb_postponed_job_t pjob = wq_job->job; free(wq_job); (pjob.func)(pjob.data); } - } - EC_POP_TAG(); + } + EC_POP_TAG(); } /* restore POSTPONED_JOB mask */ ec->interrupt_mask &= ~(saved_mask ^ block_mask); diff --git a/win32/file.c b/win32/file.c index 33303823b6..243cb1722a 100644 --- a/win32/file.c +++ b/win32/file.c @@ -46,9 +46,9 @@ static inline void replace_wchar(wchar_t *s, int find, int replace) { while (*s != 0) { - if (*s == find) - *s = replace; - s++; + if (*s == find) + *s = replace; + s++; } } @@ -60,26 +60,26 @@ remove_invalid_alternative_data(wchar_t *wfullpath, size_t size) enum { prime_len = (sizeof(prime) / sizeof(wchar_t)) -1 }; if (size <= prime_len || _wcsnicmp(wfullpath + size - prime_len, prime, prime_len) != 0) - return size; + return size; /* alias of stream */ /* get rid of a bug of x64 VC++ */ if (wfullpath[size - (prime_len + 1)] == ':') { - /* remove trailing '::$DATA' */ - size -= prime_len + 1; /* prime */ - wfullpath[size] = L'\0'; + /* remove trailing '::$DATA' */ + size -= prime_len + 1; /* prime */ + wfullpath[size] = L'\0'; } else { - /* remove trailing ':$DATA' of paths like '/aa:a:$DATA' */ - wchar_t *pos = wfullpath + size - (prime_len + 1); - while (!IS_DIR_SEPARATOR_P(*pos) && pos != wfullpath) { - if (*pos == L':') { - size -= prime_len; /* alternative */ - wfullpath[size] = L'\0'; - break; - } - pos--; - } + /* remove trailing ':$DATA' of paths like '/aa:a:$DATA' */ + wchar_t *pos = wfullpath + size - (prime_len + 1); + while (!IS_DIR_SEPARATOR_P(*pos) && pos != wfullpath) { + if (*pos == L':') { + size -= prime_len; /* alternative */ + wfullpath[size] = L'\0'; + break; + } + pos--; + } } return size; } @@ -91,22 +91,22 @@ code_page_i(st_data_t name, st_data_t idx, st_data_t arg) { const char *n = (const char *)name; if (strncmp("CP", n, 2) == 0) { - int code_page = atoi(n + 2); - if (code_page != 0) { - struct code_page_table *cp = (struct code_page_table *)arg; - unsigned int count = cp->count; - USHORT *table = cp->table; - if (count <= idx) { - unsigned int i = count; - count = (((idx + 4) & ~31) | 28); - table = realloc(table, count * sizeof(*table)); - if (!table) return ST_CONTINUE; - cp->count = count; - cp->table = table; - while (i < count) table[i++] = INVALID_CODE_PAGE; - } - table[idx] = (USHORT)code_page; - } + int code_page = atoi(n + 2); + if (code_page != 0) { + struct code_page_table *cp = (struct code_page_table *)arg; + unsigned int count = cp->count; + USHORT *table = cp->table; + if (count <= idx) { + unsigned int i = count; + count = (((idx + 4) & ~31) | 28); + table = realloc(table, count * sizeof(*table)); + if (!table) return ST_CONTINUE; + cp->count = count; + cp->table = table; + while (i < count) table[i++] = INVALID_CODE_PAGE; + } + table[idx] = (USHORT)code_page; + } } return ST_CONTINUE; } @@ -122,20 +122,20 @@ code_page(rb_encoding *enc) int enc_idx; if (!enc) - return system_code_page(); + return system_code_page(); enc_idx = rb_enc_to_index(enc); /* map US-ASCII and ASCII-8bit as code page 1252 (us-ascii) */ if (enc_idx == rb_usascii_encindex() || enc_idx == rb_ascii8bit_encindex()) { - return 1252; + return 1252; } if (enc_idx == rb_utf8_encindex()) { - return CP_UTF8; + return CP_UTF8; } if (0 <= enc_idx && (unsigned int)enc_idx < rb_code_page.count) - return rb_code_page.table[enc_idx]; + return rb_code_page.table[enc_idx]; return INVALID_CODE_PAGE; } @@ -167,25 +167,25 @@ replace_to_long_name(wchar_t **wfullpath, size_t size, size_t buffer_size) wchar_t *pos = *wfullpath; if (size == 3 && pos[1] == L':' && pos[2] == L'\\' && pos[3] == L'\0') { - /* root path doesn't need short name expansion */ - return size; + /* root path doesn't need short name expansion */ + return size; } /* skip long name conversion if path contains wildcard characters */ if (wcspbrk(pos, L"*?")) { - return size; + return size; } pos = *wfullpath + size - 1; while (!IS_DIR_SEPARATOR_P(*pos) && pos != *wfullpath) { - if (!extension_len && *pos == L'.') { - extension_len = path_len - 1; - } - if (path_len > max_short_name_size || extension_len > max_extension_size) { - return size; - } - path_len++; - pos--; + if (!extension_len && *pos == L'.') { + extension_len = path_len - 1; + } + if (path_len > max_short_name_size || extension_len > max_extension_size) { + return size; + } + path_len++; + pos--; } if ((pos >= *wfullpath + 2) && @@ -204,20 +204,20 @@ replace_to_long_name(wchar_t **wfullpath, size_t size, size_t buffer_size) find_handle = FindFirstFileW(*wfullpath, &find_data); if (find_handle != INVALID_HANDLE_VALUE) { - size_t trail_pos = pos - *wfullpath + IS_DIR_SEPARATOR_P(*pos); - size_t file_len = wcslen(find_data.cFileName); - size_t oldsize = size; + size_t trail_pos = pos - *wfullpath + IS_DIR_SEPARATOR_P(*pos); + size_t file_len = wcslen(find_data.cFileName); + size_t oldsize = size; - FindClose(find_handle); - size = trail_pos + file_len; - if (size > (buffer_size ? buffer_size-1 : oldsize)) { - wchar_t *buf = ALLOC_N(wchar_t, (size + 1)); - wcsncpy(buf, *wfullpath, trail_pos); - if (!buffer_size) - xfree(*wfullpath); - *wfullpath = buf; - } - wcsncpy(*wfullpath + trail_pos, find_data.cFileName, file_len + 1); + FindClose(find_handle); + size = trail_pos + file_len; + if (size > (buffer_size ? buffer_size-1 : oldsize)) { + wchar_t *buf = ALLOC_N(wchar_t, (size + 1)); + wcsncpy(buf, *wfullpath, trail_pos); + if (!buffer_size) + xfree(*wfullpath); + *wfullpath = buf; + } + wcsncpy(*wfullpath + trail_pos, find_data.cFileName, file_len + 1); } return size; } @@ -228,7 +228,7 @@ user_length_in_path(const wchar_t *wuser, size_t len) size_t i; for (i = 0; i < len && !IS_DIR_SEPARATOR_P(wuser[i]); i++) - ; + ; return i; } @@ -239,21 +239,21 @@ append_wstr(VALUE dst, const WCHAR *ws, ssize_t len, UINT cp, rb_encoding *enc) long olen, nlen = (long)len; if (cp != INVALID_CODE_PAGE) { - if (len == -1) len = lstrlenW(ws); - nlen = WideCharToMultiByte(cp, 0, ws, len, NULL, 0, NULL, NULL); - olen = RSTRING_LEN(dst); - rb_str_modify_expand(dst, nlen); - WideCharToMultiByte(cp, 0, ws, len, RSTRING_PTR(dst) + olen, nlen, NULL, NULL); - rb_enc_associate(dst, enc); - rb_str_set_len(dst, olen + nlen); + if (len == -1) len = lstrlenW(ws); + nlen = WideCharToMultiByte(cp, 0, ws, len, NULL, 0, NULL, NULL); + olen = RSTRING_LEN(dst); + rb_str_modify_expand(dst, nlen); + WideCharToMultiByte(cp, 0, ws, len, RSTRING_PTR(dst) + olen, nlen, NULL, NULL); + rb_enc_associate(dst, enc); + rb_str_set_len(dst, olen + nlen); } else { - const int replaceflags = ECONV_UNDEF_REPLACE|ECONV_INVALID_REPLACE; - char *utf8str = wstr_to_mbstr(CP_UTF8, ws, (int)len, &nlen); - rb_econv_t *ec = rb_econv_open("UTF-8", rb_enc_name(enc), replaceflags); - dst = rb_econv_append(ec, utf8str, nlen, dst, replaceflags); - rb_econv_close(ec); - free(utf8str); + const int replaceflags = ECONV_UNDEF_REPLACE|ECONV_INVALID_REPLACE; + char *utf8str = wstr_to_mbstr(CP_UTF8, ws, (int)len, &nlen); + rb_econv_t *ec = rb_econv_open("UTF-8", rb_enc_name(enc), replaceflags); + dst = rb_econv_append(ec, utf8str, nlen, dst, replaceflags); + rb_econv_close(ec); + free(utf8str); } return dst; } @@ -263,10 +263,10 @@ rb_default_home_dir(VALUE result) { WCHAR *dir = rb_w32_home_dir(); if (!dir) { - rb_raise(rb_eArgError, "couldn't find HOME environment -- expanding `~'"); + rb_raise(rb_eArgError, "couldn't find HOME environment -- expanding `~'"); } append_wstr(result, dir, -1, - rb_w32_filecp(), rb_filesystem_encoding()); + rb_w32_filecp(), rb_filesystem_encoding()); xfree(dir); return result; } @@ -289,198 +289,198 @@ rb_file_expand_path_internal(VALUE fname, VALUE dname, int abs_mode, int long_na /* get path encoding */ if (NIL_P(dir)) { - path_encoding = rb_enc_get(path); + path_encoding = rb_enc_get(path); } else { - path_encoding = rb_enc_check(path, dir); + path_encoding = rb_enc_check(path, dir); } cp = path_cp = code_page(path_encoding); /* workaround invalid codepage */ if (path_cp == INVALID_CODE_PAGE) { - cp = CP_UTF8; - if (!NIL_P(path)) { - path = fix_string_encoding(path, path_encoding); - } + cp = CP_UTF8; + if (!NIL_P(path)) { + path = fix_string_encoding(path, path_encoding); + } } /* convert char * to wchar_t */ if (!NIL_P(path)) { - const long path_len = RSTRING_LEN(path); + const long path_len = RSTRING_LEN(path); #if SIZEOF_INT < SIZEOF_LONG - if ((long)(int)path_len != path_len) { - rb_raise(rb_eRangeError, "path (%ld bytes) is too long", - path_len); - } + if ((long)(int)path_len != path_len) { + rb_raise(rb_eRangeError, "path (%ld bytes) is too long", + path_len); + } #endif - wpath = mbstr_to_wstr(cp, RSTRING_PTR(path), path_len, &wpath_len); - wpath_pos = wpath; + wpath = mbstr_to_wstr(cp, RSTRING_PTR(path), path_len, &wpath_len); + wpath_pos = wpath; } /* determine if we need the user's home directory */ /* expand '~' only if NOT rb_file_absolute_path() where `abs_mode` is 1 */ if (abs_mode == 0 && wpath_len > 0 && wpath_pos[0] == L'~' && - (wpath_len == 1 || IS_DIR_SEPARATOR_P(wpath_pos[1]))) { - whome = rb_w32_home_dir(); - if (whome == NULL) { - free(wpath); - rb_raise(rb_eArgError, "couldn't find HOME environment -- expanding `~'"); - } - whome_len = wcslen(whome); + (wpath_len == 1 || IS_DIR_SEPARATOR_P(wpath_pos[1]))) { + whome = rb_w32_home_dir(); + if (whome == NULL) { + free(wpath); + rb_raise(rb_eArgError, "couldn't find HOME environment -- expanding `~'"); + } + whome_len = wcslen(whome); - if (!IS_ABSOLUTE_PATH_P(whome, whome_len)) { - free(wpath); - xfree(whome); - rb_raise(rb_eArgError, "non-absolute home"); - } + if (!IS_ABSOLUTE_PATH_P(whome, whome_len)) { + free(wpath); + xfree(whome); + rb_raise(rb_eArgError, "non-absolute home"); + } - if (path_cp == INVALID_CODE_PAGE || rb_enc_str_asciionly_p(path)) { - /* use filesystem encoding if expanding home dir */ - path_encoding = rb_filesystem_encoding(); - cp = path_cp = code_page(path_encoding); - } + if (path_cp == INVALID_CODE_PAGE || rb_enc_str_asciionly_p(path)) { + /* use filesystem encoding if expanding home dir */ + path_encoding = rb_filesystem_encoding(); + cp = path_cp = code_page(path_encoding); + } - /* ignores dir since we are expanding home */ - ignore_dir = 1; + /* ignores dir since we are expanding home */ + ignore_dir = 1; - /* exclude ~ from the result */ - wpath_pos++; - wpath_len--; + /* exclude ~ from the result */ + wpath_pos++; + wpath_len--; - /* exclude separator if present */ - if (wpath_len && IS_DIR_SEPARATOR_P(wpath_pos[0])) { - wpath_pos++; - wpath_len--; - } + /* exclude separator if present */ + if (wpath_len && IS_DIR_SEPARATOR_P(wpath_pos[0])) { + wpath_pos++; + wpath_len--; + } } else if (wpath_len >= 2 && wpath_pos[1] == L':') { - if (wpath_len >= 3 && IS_DIR_SEPARATOR_P(wpath_pos[2])) { - /* ignore dir since path contains a drive letter and a root slash */ - ignore_dir = 1; - } - else { - /* determine if we ignore dir or not later */ - path_drive = wpath_pos[0]; - wpath_pos += 2; - wpath_len -= 2; - } + if (wpath_len >= 3 && IS_DIR_SEPARATOR_P(wpath_pos[2])) { + /* ignore dir since path contains a drive letter and a root slash */ + ignore_dir = 1; + } + else { + /* determine if we ignore dir or not later */ + path_drive = wpath_pos[0]; + wpath_pos += 2; + wpath_len -= 2; + } } else if (abs_mode == 0 && wpath_len >= 2 && wpath_pos[0] == L'~') { - result = rb_str_new_cstr("can't find user "); - result = append_wstr(result, wpath_pos + 1, user_length_in_path(wpath_pos + 1, wpath_len - 1), - path_cp, path_encoding); + result = rb_str_new_cstr("can't find user "); + result = append_wstr(result, wpath_pos + 1, user_length_in_path(wpath_pos + 1, wpath_len - 1), + path_cp, path_encoding); - if (wpath) - free(wpath); + if (wpath) + free(wpath); - rb_exc_raise(rb_exc_new_str(rb_eArgError, result)); + rb_exc_raise(rb_exc_new_str(rb_eArgError, result)); } /* convert dir */ if (!ignore_dir && !NIL_P(dir)) { - /* fix string encoding */ - if (path_cp == INVALID_CODE_PAGE) { - dir = fix_string_encoding(dir, path_encoding); - } + /* fix string encoding */ + if (path_cp == INVALID_CODE_PAGE) { + dir = fix_string_encoding(dir, path_encoding); + } - /* convert char * to wchar_t */ - if (!NIL_P(dir)) { - const long dir_len = RSTRING_LEN(dir); + /* convert char * to wchar_t */ + if (!NIL_P(dir)) { + const long dir_len = RSTRING_LEN(dir); #if SIZEOF_INT < SIZEOF_LONG - if ((long)(int)dir_len != dir_len) { - if (wpath) free(wpath); - rb_raise(rb_eRangeError, "base directory (%ld bytes) is too long", - dir_len); - } + if ((long)(int)dir_len != dir_len) { + if (wpath) free(wpath); + rb_raise(rb_eRangeError, "base directory (%ld bytes) is too long", + dir_len); + } #endif - wdir = mbstr_to_wstr(cp, RSTRING_PTR(dir), dir_len, &wdir_len); - wdir_pos = wdir; - } + wdir = mbstr_to_wstr(cp, RSTRING_PTR(dir), dir_len, &wdir_len); + wdir_pos = wdir; + } - if (abs_mode == 0 && wdir_len > 0 && wdir_pos[0] == L'~' && - (wdir_len == 1 || IS_DIR_SEPARATOR_P(wdir_pos[1]))) { - whome = rb_w32_home_dir(); - if (whome == NULL) { - free(wpath); - free(wdir); - rb_raise(rb_eArgError, "couldn't find HOME environment -- expanding `~'"); - } - whome_len = wcslen(whome); + if (abs_mode == 0 && wdir_len > 0 && wdir_pos[0] == L'~' && + (wdir_len == 1 || IS_DIR_SEPARATOR_P(wdir_pos[1]))) { + whome = rb_w32_home_dir(); + if (whome == NULL) { + free(wpath); + free(wdir); + rb_raise(rb_eArgError, "couldn't find HOME environment -- expanding `~'"); + } + whome_len = wcslen(whome); - if (!IS_ABSOLUTE_PATH_P(whome, whome_len)) { - free(wpath); - free(wdir); - xfree(whome); - rb_raise(rb_eArgError, "non-absolute home"); - } + if (!IS_ABSOLUTE_PATH_P(whome, whome_len)) { + free(wpath); + free(wdir); + xfree(whome); + rb_raise(rb_eArgError, "non-absolute home"); + } - /* exclude ~ from the result */ - wdir_pos++; - wdir_len--; + /* exclude ~ from the result */ + wdir_pos++; + wdir_len--; - /* exclude separator if present */ - if (wdir_len && IS_DIR_SEPARATOR_P(wdir_pos[0])) { - wdir_pos++; - wdir_len--; - } - } - else if (wdir_len >= 2 && wdir[1] == L':') { - dir_drive = wdir[0]; - if (wpath_len && IS_DIR_SEPARATOR_P(wpath_pos[0])) { - wdir_len = 2; - } - } - else if (wdir_len >= 2 && IS_DIR_UNC_P(wdir)) { - /* UNC path */ - if (wpath_len && IS_DIR_SEPARATOR_P(wpath_pos[0])) { - /* cut the UNC path tail to '//host/share' */ - long separators = 0; - long pos = 2; - while (pos < wdir_len && separators < 2) { - if (IS_DIR_SEPARATOR_P(wdir[pos])) { - separators++; - } - pos++; - } - if (separators == 2) - wdir_len = pos - 1; - } - } - else if (abs_mode == 0 && wdir_len >= 2 && wdir_pos[0] == L'~') { - result = rb_str_new_cstr("can't find user "); - result = append_wstr(result, wdir_pos + 1, user_length_in_path(wdir_pos + 1, wdir_len - 1), - path_cp, path_encoding); - if (wpath) - free(wpath); + /* exclude separator if present */ + if (wdir_len && IS_DIR_SEPARATOR_P(wdir_pos[0])) { + wdir_pos++; + wdir_len--; + } + } + else if (wdir_len >= 2 && wdir[1] == L':') { + dir_drive = wdir[0]; + if (wpath_len && IS_DIR_SEPARATOR_P(wpath_pos[0])) { + wdir_len = 2; + } + } + else if (wdir_len >= 2 && IS_DIR_UNC_P(wdir)) { + /* UNC path */ + if (wpath_len && IS_DIR_SEPARATOR_P(wpath_pos[0])) { + /* cut the UNC path tail to '//host/share' */ + long separators = 0; + long pos = 2; + while (pos < wdir_len && separators < 2) { + if (IS_DIR_SEPARATOR_P(wdir[pos])) { + separators++; + } + pos++; + } + if (separators == 2) + wdir_len = pos - 1; + } + } + else if (abs_mode == 0 && wdir_len >= 2 && wdir_pos[0] == L'~') { + result = rb_str_new_cstr("can't find user "); + result = append_wstr(result, wdir_pos + 1, user_length_in_path(wdir_pos + 1, wdir_len - 1), + path_cp, path_encoding); + if (wpath) + free(wpath); - if (wdir) - free(wdir); + if (wdir) + free(wdir); - rb_exc_raise(rb_exc_new_str(rb_eArgError, result)); - } + rb_exc_raise(rb_exc_new_str(rb_eArgError, result)); + } } /* determine if we ignore dir or not */ if (!ignore_dir && path_drive && dir_drive) { - if (towupper(path_drive) != towupper(dir_drive)) { - /* ignore dir since path drive is different from dir drive */ - ignore_dir = 1; - wdir_len = 0; - dir_drive = 0; - } + if (towupper(path_drive) != towupper(dir_drive)) { + /* ignore dir since path drive is different from dir drive */ + ignore_dir = 1; + wdir_len = 0; + dir_drive = 0; + } } if (!ignore_dir && wpath_len >= 2 && IS_DIR_UNC_P(wpath)) { - /* ignore dir since path has UNC root */ - ignore_dir = 1; - wdir_len = 0; + /* ignore dir since path has UNC root */ + ignore_dir = 1; + wdir_len = 0; } else if (!ignore_dir && wpath_len >= 1 && IS_DIR_SEPARATOR_P(wpath[0]) && - !dir_drive && !(wdir_len >= 2 && IS_DIR_UNC_P(wdir))) { - /* ignore dir since path has root slash and dir doesn't have drive or UNC root */ - ignore_dir = 1; - wdir_len = 0; + !dir_drive && !(wdir_len >= 2 && IS_DIR_UNC_P(wdir))) { + /* ignore dir since path has root slash and dir doesn't have drive or UNC root */ + ignore_dir = 1; + wdir_len = 0; } buffer_len = wpath_len + 1 + wdir_len + 1 + whome_len + 1; @@ -489,41 +489,41 @@ rb_file_expand_path_internal(VALUE fname, VALUE dname, int abs_mode, int long_na /* add home */ if (whome_len) { - wcsncpy(buffer_pos, whome, whome_len); - buffer_pos += whome_len; + wcsncpy(buffer_pos, whome, whome_len); + buffer_pos += whome_len; } /* Add separator if required */ if (whome_len && wcsrchr(L"\\/:", buffer_pos[-1]) == NULL) { - buffer_pos[0] = L'\\'; - buffer_pos++; + buffer_pos[0] = L'\\'; + buffer_pos++; } else if (!dir_drive && path_drive) { - *buffer_pos++ = path_drive; - *buffer_pos++ = L':'; + *buffer_pos++ = path_drive; + *buffer_pos++ = L':'; } if (wdir_len) { - wcsncpy(buffer_pos, wdir_pos, wdir_len); - buffer_pos += wdir_len; + wcsncpy(buffer_pos, wdir_pos, wdir_len); + buffer_pos += wdir_len; } /* add separator if required */ if (wdir_len && wcsrchr(L"\\/:", buffer_pos[-1]) == NULL) { - buffer_pos[0] = L'\\'; - buffer_pos++; + buffer_pos[0] = L'\\'; + buffer_pos++; } /* now deal with path */ if (wpath_len) { - wcsncpy(buffer_pos, wpath_pos, wpath_len); - buffer_pos += wpath_len; + wcsncpy(buffer_pos, wpath_pos, wpath_len); + buffer_pos += wpath_len; } /* GetFullPathNameW requires at least "." to determine current directory */ if (wpath_len == 0) { - buffer_pos[0] = L'.'; - buffer_pos++; + buffer_pos[0] = L'.'; + buffer_pos++; } /* Ensure buffer is NULL terminated */ @@ -533,26 +533,26 @@ rb_file_expand_path_internal(VALUE fname, VALUE dname, int abs_mode, int long_na /* Determine require buffer size */ size = GetFullPathNameW(buffer, PATH_BUFFER_SIZE, wfullpath_buffer, NULL); if (size > PATH_BUFFER_SIZE) { - /* allocate more memory than allotted originally by PATH_BUFFER_SIZE */ - wfullpath = ALLOC_N(wchar_t, size); - size = GetFullPathNameW(buffer, size, wfullpath, NULL); + /* allocate more memory than allotted originally by PATH_BUFFER_SIZE */ + wfullpath = ALLOC_N(wchar_t, size); + size = GetFullPathNameW(buffer, size, wfullpath, NULL); } else { - wfullpath = wfullpath_buffer; + wfullpath = wfullpath_buffer; } /* Remove any trailing slashes */ if (IS_DIR_SEPARATOR_P(wfullpath[size - 1]) && - wfullpath[size - 2] != L':' && - !(size == 2 && IS_DIR_UNC_P(wfullpath))) { - size -= 1; - wfullpath[size] = L'\0'; + wfullpath[size - 2] != L':' && + !(size == 2 && IS_DIR_UNC_P(wfullpath))) { + size -= 1; + wfullpath[size] = L'\0'; } /* Remove any trailing dot */ if (wfullpath[size - 1] == L'.') { - size -= 1; - wfullpath[size] = L'\0'; + size -= 1; + wfullpath[size] = L'\0'; } /* removes trailing invalid ':$DATA' */ @@ -560,8 +560,8 @@ rb_file_expand_path_internal(VALUE fname, VALUE dname, int abs_mode, int long_na /* Replace the trailing path to long name */ if (long_name) { - size_t bufsize = wfullpath == wfullpath_buffer ? PATH_BUFFER_SIZE : 0; - size = replace_to_long_name(&wfullpath, size, bufsize); + size_t bufsize = wfullpath == wfullpath_buffer ? PATH_BUFFER_SIZE : 0; + size = replace_to_long_name(&wfullpath, size, bufsize); } /* sanitize backslashes with forwardslashes */ @@ -573,19 +573,19 @@ rb_file_expand_path_internal(VALUE fname, VALUE dname, int abs_mode, int long_na /* TODO: better cleanup */ if (buffer) - xfree(buffer); + xfree(buffer); if (wpath) - free(wpath); + free(wpath); if (wdir) - free(wdir); + free(wdir); if (whome) - xfree(whome); + xfree(whome); if (wfullpath != wfullpath_buffer) - xfree(wfullpath); + xfree(wfullpath); rb_enc_associate(result, path_encoding); return result; @@ -606,8 +606,8 @@ rb_readlink(VALUE path, rb_encoding *resultenc) enc = rb_enc_get(path); cp = path_cp = code_page(enc); if (cp == INVALID_CODE_PAGE) { - path = fix_string_encoding(path, enc); - cp = CP_UTF8; + path = fix_string_encoding(path, enc); + cp = CP_UTF8; } len = MultiByteToWideChar(cp, 0, RSTRING_PTR(path), RSTRING_LEN(path), NULL, 0); wpath = ALLOCV_N(WCHAR, wpathbuf, len+1); @@ -615,17 +615,17 @@ rb_readlink(VALUE path, rb_encoding *resultenc) wpath[len] = L'\0'; e = rb_w32_read_reparse_point(wpath, rp, sizeof(rbuf), &wbuf, &len); if (e == ERROR_MORE_DATA) { - size_t size = rb_w32_reparse_buffer_size(len + 1); - rp = ALLOCV(wtmp, size); - e = rb_w32_read_reparse_point(wpath, rp, size, &wbuf, &len); + size_t size = rb_w32_reparse_buffer_size(len + 1); + rp = ALLOCV(wtmp, size); + e = rb_w32_read_reparse_point(wpath, rp, size, &wbuf, &len); } ALLOCV_END(wpathbuf); if (e) { - ALLOCV_END(wtmp); - if (e != -1) - rb_syserr_fail_path(rb_w32_map_errno(e), path); - else /* not symlink; maybe volume mount point */ - rb_syserr_fail_path(EINVAL, path); + ALLOCV_END(wtmp); + if (e != -1) + rb_syserr_fail_path(rb_w32_map_errno(e), path); + else /* not symlink; maybe volume mount point */ + rb_syserr_fail_path(EINVAL, path); } enc = resultenc; path_cp = code_page(enc); @@ -648,19 +648,19 @@ rb_file_load_ok(const char *path) attr = GetFileAttributesW(wpath); if (attr == INVALID_FILE_ATTRIBUTES || - (attr & FILE_ATTRIBUTE_DIRECTORY)) { - ret = 0; + (attr & FILE_ATTRIBUTE_DIRECTORY)) { + ret = 0; } else { - HANDLE h = CreateFileW(wpath, GENERIC_READ, - FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - if (h != INVALID_HANDLE_VALUE) { - CloseHandle(h); - } - else { - ret = 0; - } + HANDLE h = CreateFileW(wpath, GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (h != INVALID_HANDLE_VALUE) { + CloseHandle(h); + } + else { + ret = 0; + } } free(wpath); return ret; @@ -687,8 +687,8 @@ rb_freopen(VALUE fname, const char *mode, FILE *file) e = _wfreopen(wname, wmode, file) ? 0 : errno; #else { - FILE *newfp = 0; - e = _wfreopen_s(&newfp, wname, wmode, file); + FILE *newfp = 0; + e = _wfreopen_s(&newfp, wname, wmode, file); } #endif ALLOCV_END(wtmp); diff --git a/win32/file.h b/win32/file.h index f3ce244f5d..36ff27c9b1 100644 --- a/win32/file.h +++ b/win32/file.h @@ -12,21 +12,21 @@ typedef struct { USHORT ReparseDataLength; USHORT Reserved; union { - struct { - USHORT SubstituteNameOffset; - USHORT SubstituteNameLength; - USHORT PrintNameOffset; - USHORT PrintNameLength; - ULONG Flags; - WCHAR PathBuffer[4]; - } SymbolicLinkReparseBuffer; - struct { - USHORT SubstituteNameOffset; - USHORT SubstituteNameLength; - USHORT PrintNameOffset; - USHORT PrintNameLength; - WCHAR PathBuffer[4]; - } MountPointReparseBuffer; + struct { + USHORT SubstituteNameOffset; + USHORT SubstituteNameLength; + USHORT PrintNameOffset; + USHORT PrintNameLength; + ULONG Flags; + WCHAR PathBuffer[4]; + } SymbolicLinkReparseBuffer; + struct { + USHORT SubstituteNameOffset; + USHORT SubstituteNameLength; + USHORT PrintNameOffset; + USHORT PrintNameLength; + WCHAR PathBuffer[4]; + } MountPointReparseBuffer; }; } rb_w32_reparse_buffer_t; @@ -35,7 +35,7 @@ typedef struct { sizeof(WCHAR)*((n)-MINIMUM_REPARSE_BUFFER_PATH_LEN)) int rb_w32_read_reparse_point(const WCHAR *path, rb_w32_reparse_buffer_t *rp, - size_t bufsize, WCHAR **result, DWORD *len); + size_t bufsize, WCHAR **result, DWORD *len); int lchown(const char *path, int owner, int group); int rb_w32_ulchown(const char *path, int owner, int group); diff --git a/win32/win32.c b/win32/win32.c index bf3d058171..6d3e368565 100644 --- a/win32/win32.c +++ b/win32/win32.c @@ -283,17 +283,17 @@ rb_w32_map_errno(DWORD winerr) int i; if (winerr == 0) { - return 0; + return 0; } for (i = 0; i < (int)(sizeof(errmap) / sizeof(*errmap)); i++) { - if (errmap[i].winerr == winerr) { - return errmap[i].err; - } + if (errmap[i].winerr == winerr) { + return errmap[i].err; + } } if (winerr >= WSABASEERR) { - return winerr; + return winerr; } return EINVAL; } @@ -334,17 +334,17 @@ rb_w32_osver(void) /* License: Artistic or GPL */ #define LK_ERR(f,i) \ do { \ - if (f) \ - i = 0; \ - else { \ - DWORD err = GetLastError(); \ - if (err == ERROR_LOCK_VIOLATION || err == ERROR_IO_PENDING) \ - errno = EWOULDBLOCK; \ - else if (err == ERROR_NOT_LOCKED) \ - i = 0; \ - else \ - errno = map_errno(err); \ - } \ + if (f) \ + i = 0; \ + else { \ + DWORD err = GetLastError(); \ + if (err == ERROR_LOCK_VIOLATION || err == ERROR_IO_PENDING) \ + errno = EWOULDBLOCK; \ + else if (err == ERROR_NOT_LOCKED) \ + i = 0; \ + else \ + errno = map_errno(err); \ + } \ } while (0) #define LK_LEN ULONG_MAX @@ -361,26 +361,26 @@ flock_winnt(uintptr_t self, int argc, uintptr_t* argv) switch (oper) { case LOCK_SH: /* shared lock */ - LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, LK_LEN, &o), i); - break; + LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, LK_LEN, &o), i); + break; case LOCK_EX: /* exclusive lock */ - LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, LK_LEN, &o), i); - break; + LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, LK_LEN, &o), i); + break; case LOCK_SH|LOCK_NB: /* non-blocking shared lock */ - LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, LK_LEN, &o), i); - break; + LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, LK_LEN, &o), i); + break; case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */ - LK_ERR(LockFileEx(fh, - LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY, - 0, LK_LEN, LK_LEN, &o), i); - break; + LK_ERR(LockFileEx(fh, + LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY, + 0, LK_LEN, LK_LEN, &o), i); + break; case LOCK_UN: /* unlock lock */ case LOCK_UN|LOCK_NB: /* unlock is always non-blocking, I hope */ - LK_ERR(UnlockFileEx(fh, 0, LK_LEN, LK_LEN, &o), i); - break; + LK_ERR(UnlockFileEx(fh, 0, LK_LEN, LK_LEN, &o), i); + break; default: /* unknown */ - errno = EINVAL; - break; + errno = EINVAL; + break; } return i; } @@ -394,8 +394,8 @@ flock(int fd, int oper) const asynchronous_func_t locker = flock_winnt; return rb_w32_asynchronize(locker, - (VALUE)_get_osfhandle(fd), oper, NULL, - (DWORD)-1); + (VALUE)_get_osfhandle(fd), oper, NULL, + (DWORD)-1); } /* License: Ruby's */ @@ -403,8 +403,8 @@ static inline WCHAR * translate_wchar(WCHAR *p, int from, int to) { for (; *p; p++) { - if (*p == from) - *p = to; + if (*p == from) + *p = to; } return p; } @@ -414,9 +414,9 @@ static inline char * translate_char(char *p, int from, int to, UINT cp) { while (*p) { - if ((unsigned char)*p == from) - *p = to; - p = CharNextExA(cp, p, 0); + if ((unsigned char)*p == from) + *p = to; + p = CharNextExA(cp, p, 0); } return p; } @@ -448,21 +448,21 @@ get_special_folder(int n, WCHAR *buf, size_t len) static get_path_func func = (get_path_func)-1; if (func == (get_path_func)-1) { - func = (get_path_func) - get_proc_address("shell32", "SHGetPathFromIDListEx", NULL); + func = (get_path_func) + get_proc_address("shell32", "SHGetPathFromIDListEx", NULL); } if (!func && len < MAX_PATH) return FALSE; if (SHGetSpecialFolderLocation(NULL, n, &pidl) == 0) { - if (func) { - f = func(pidl, buf, len, 0); - } - else { - f = SHGetPathFromIDListW(pidl, buf); - } - SHGetMalloc(&alloc); - alloc->lpVtbl->Free(alloc, pidl); - alloc->lpVtbl->Release(alloc); + if (func) { + f = func(pidl, buf, len, 0); + } + else { + f = SHGetPathFromIDListW(pidl, buf); + } + SHGetMalloc(&alloc); + alloc->lpVtbl->Free(alloc, pidl); + alloc->lpVtbl->Release(alloc); } return f; } @@ -473,8 +473,8 @@ regulate_path(WCHAR *path) { WCHAR *p = translate_wchar(path, L'\\', L'/'); if (p - path == 2 && path[1] == L':') { - *p++ = L'/'; - *p = L'\0'; + *p++ = L'/'; + *p = L'\0'; } } @@ -486,18 +486,18 @@ get_proc_address(const char *module, const char *func, HANDLE *mh) FARPROC ptr; if (mh) - h = LoadLibrary(module); + h = LoadLibrary(module); else - h = GetModuleHandle(module); + h = GetModuleHandle(module); if (!h) - return NULL; + return NULL; ptr = GetProcAddress(h, func); if (mh) { - if (ptr) - *mh = h; - else - FreeLibrary(h); + if (ptr) + *mh = h; + else + FreeLibrary(h); } return ptr; } @@ -526,7 +526,7 @@ rb_w32_system_tmpdir(WCHAR *path, UINT len) WCHAR *p; if (!get_special_folder(CSIDL_LOCAL_APPDATA, path, len)) { - if (GetSystemWindowsDirectoryW(path, len)) return 0; + if (GetSystemWindowsDirectoryW(path, len)) return 0; } p = translate_wchar(path, L'\\', L'/'); if (*(p - 1) != L'/') *p++ = L'/'; @@ -550,23 +550,23 @@ rb_w32_home_dir(void) WCHAR *buffer = NULL; size_t buffer_len = MAX_PATH, len = 0; enum { - HOME_NONE, ENV_HOME, ENV_DRIVEPATH, ENV_USERPROFILE + HOME_NONE, ENV_HOME, ENV_DRIVEPATH, ENV_USERPROFILE } home_type = HOME_NONE; if ((len = GetEnvironmentVariableW(L"HOME", NULL, 0)) != 0) { - buffer_len = len; - home_type = ENV_HOME; + buffer_len = len; + home_type = ENV_HOME; } else if ((len = GetEnvironmentVariableW(L"HOMEDRIVE", NULL, 0)) != 0) { - buffer_len = len; - if ((len = GetEnvironmentVariableW(L"HOMEPATH", NULL, 0)) != 0) { - buffer_len += len; - home_type = ENV_DRIVEPATH; - } + buffer_len = len; + if ((len = GetEnvironmentVariableW(L"HOMEPATH", NULL, 0)) != 0) { + buffer_len += len; + home_type = ENV_DRIVEPATH; + } } else if ((len = GetEnvironmentVariableW(L"USERPROFILE", NULL, 0)) != 0) { - buffer_len = len; - home_type = ENV_USERPROFILE; + buffer_len = len; + home_type = ENV_USERPROFILE; } /* allocate buffer */ @@ -574,23 +574,23 @@ rb_w32_home_dir(void) switch (home_type) { case ENV_HOME: - GetEnvironmentVariableW(L"HOME", buffer, buffer_len); - break; + GetEnvironmentVariableW(L"HOME", buffer, buffer_len); + break; case ENV_DRIVEPATH: - len = GetEnvironmentVariableW(L"HOMEDRIVE", buffer, buffer_len); - GetEnvironmentVariableW(L"HOMEPATH", buffer + len, buffer_len - len); - break; + len = GetEnvironmentVariableW(L"HOMEDRIVE", buffer, buffer_len); + GetEnvironmentVariableW(L"HOMEPATH", buffer + len, buffer_len - len); + break; case ENV_USERPROFILE: - GetEnvironmentVariableW(L"USERPROFILE", buffer, buffer_len); - break; + GetEnvironmentVariableW(L"USERPROFILE", buffer, buffer_len); + break; default: - if (!get_special_folder(CSIDL_PROFILE, buffer, buffer_len) && - !get_special_folder(CSIDL_PERSONAL, buffer, buffer_len)) { - xfree(buffer); - return NULL; - } - REALLOC_N(buffer, WCHAR, lstrlenW(buffer) + 1); - break; + if (!get_special_folder(CSIDL_PROFILE, buffer, buffer_len) && + !get_special_folder(CSIDL_PERSONAL, buffer, buffer_len)) { + xfree(buffer); + return NULL; + } + REALLOC_N(buffer, WCHAR, lstrlenW(buffer) + 1); + break; } /* sanitize backslashes with forwardslashes */ @@ -609,57 +609,57 @@ init_env(void) BOOL f; #define env wk.val #define set_env_val(vname) do { \ - typedef char wk_name_offset[(numberof(wk.name) - (numberof(vname) - 1)) * 2 + 1]; \ - WCHAR *const buf = wk.name + sizeof(wk_name_offset) / 2; \ - MEMCPY(buf, vname, WCHAR, numberof(vname) - 1); \ - _wputenv(buf); \ + typedef char wk_name_offset[(numberof(wk.name) - (numberof(vname) - 1)) * 2 + 1]; \ + WCHAR *const buf = wk.name + sizeof(wk_name_offset) / 2; \ + MEMCPY(buf, vname, WCHAR, numberof(vname) - 1); \ + _wputenv(buf); \ } while (0) wk.eq = L'='; if (!GetEnvironmentVariableW(L"HOME", env, numberof(env))) { - f = FALSE; - if (GetEnvironmentVariableW(L"HOMEDRIVE", env, numberof(env))) - len = lstrlenW(env); - else - len = 0; - if (GetEnvironmentVariableW(L"HOMEPATH", env + len, numberof(env) - len) || len) { - f = TRUE; - } - else if (GetEnvironmentVariableW(L"USERPROFILE", env, numberof(env))) { - f = TRUE; - } - else if (get_special_folder(CSIDL_PROFILE, env, numberof(env))) { - f = TRUE; - } - else if (get_special_folder(CSIDL_PERSONAL, env, numberof(env))) { - f = TRUE; - } - if (f) { - regulate_path(env); - set_env_val(L"HOME"); - } + f = FALSE; + if (GetEnvironmentVariableW(L"HOMEDRIVE", env, numberof(env))) + len = lstrlenW(env); + else + len = 0; + if (GetEnvironmentVariableW(L"HOMEPATH", env + len, numberof(env) - len) || len) { + f = TRUE; + } + else if (GetEnvironmentVariableW(L"USERPROFILE", env, numberof(env))) { + f = TRUE; + } + else if (get_special_folder(CSIDL_PROFILE, env, numberof(env))) { + f = TRUE; + } + else if (get_special_folder(CSIDL_PERSONAL, env, numberof(env))) { + f = TRUE; + } + if (f) { + regulate_path(env); + set_env_val(L"HOME"); + } } if (!GetEnvironmentVariableW(L"USER", env, numberof(env))) { - if (!GetEnvironmentVariableW(L"USERNAME", env, numberof(env)) && - !GetUserNameW(env, (len = numberof(env), &len))) { - NTLoginName = ""; - } - else { - set_env_val(L"USER"); - NTLoginName = rb_w32_wstr_to_mbstr(CP_UTF8, env, -1, NULL); - } + if (!GetEnvironmentVariableW(L"USERNAME", env, numberof(env)) && + !GetUserNameW(env, (len = numberof(env), &len))) { + NTLoginName = ""; + } + else { + set_env_val(L"USER"); + NTLoginName = rb_w32_wstr_to_mbstr(CP_UTF8, env, -1, NULL); + } } else { - NTLoginName = rb_w32_wstr_to_mbstr(CP_UTF8, env, -1, NULL); + NTLoginName = rb_w32_wstr_to_mbstr(CP_UTF8, env, -1, NULL); } if (!GetEnvironmentVariableW(TMPDIR, env, numberof(env)) && - !GetEnvironmentVariableW(L"TMP", env, numberof(env)) && - !GetEnvironmentVariableW(L"TEMP", env, numberof(env)) && - rb_w32_system_tmpdir(env, numberof(env))) { - set_env_val(TMPDIR); + !GetEnvironmentVariableW(L"TMP", env, numberof(env)) && + !GetEnvironmentVariableW(L"TEMP", env, numberof(env)) && + rb_w32_system_tmpdir(env, numberof(env))) { + set_env_val(TMPDIR); } #undef env @@ -707,8 +707,8 @@ static st_table *conlist = NULL; #define thread_exclusive(obj) \ for (bool exclusive_for_##obj = (EnterCriticalSection(&obj##_mutex), true); \ - exclusive_for_##obj; \ - exclusive_for_##obj = (LeaveCriticalSection(&obj##_mutex), false)) + exclusive_for_##obj; \ + exclusive_for_##obj = (LeaveCriticalSection(&obj##_mutex), false)) static CRITICAL_SECTION uenvarea_mutex; static char *uenvarea; @@ -716,9 +716,9 @@ static char *uenvarea; /* License: Ruby's */ struct constat { struct { - int state, seq[16], reverse; - WORD attr; - COORD saved; + int state, seq[16], reverse; + WORD attr; + COORD saved; } vt100; }; enum {constat_init = -2, constat_esc = -1, constat_seq = 0}; @@ -736,11 +736,11 @@ static void constat_delete(HANDLE h) { thread_exclusive(conlist) { - if (conlist && conlist != conlist_disabled) { - st_data_t key = (st_data_t)h, val; - st_delete(conlist, &key, &val); - xfree((struct constat *)val); - } + if (conlist && conlist != conlist_disabled) { + st_data_t key = (st_data_t)h, val; + st_delete(conlist, &key, &val); + xfree((struct constat *)val); + } } } @@ -753,10 +753,10 @@ exit_handler(void) DeleteCriticalSection(&socklist_mutex); DeleteCriticalSection(&conlist_mutex); thread_exclusive(uenvarea) { - if (uenvarea) { - free(uenvarea); - uenvarea = NULL; - } + if (uenvarea) { + free(uenvarea); + uenvarea = NULL; + } } DeleteCriticalSection(&uenvarea_mutex); } @@ -767,16 +767,16 @@ vm_exit_handler(ruby_vm_t *vm) { EnterCriticalSection(&socklist_mutex); if (socklist) { - st_free_table(socklist); - socklist = NULL; + st_free_table(socklist); + socklist = NULL; } LeaveCriticalSection(&socklist_mutex); EnterCriticalSection(&conlist_mutex); if (conlist && conlist != conlist_disabled) { - st_foreach(conlist, free_conlist, 0); - st_free_table(conlist); - conlist = NULL; + st_foreach(conlist, free_conlist, 0); + st_free_table(conlist); + conlist = NULL; } LeaveCriticalSection(&conlist_mutex); } @@ -791,13 +791,13 @@ install_vm_exit_handler(void) LONG i; while ((i = ATOMIC_LONG_CAS(installed, 0, -1)) != 1) { - if (i != 0) { - Sleep(1); - continue; - } - ruby_vm_at_exit(vm_exit_handler); - ATOMIC_LONG_CAS(installed, -1, 1); - break; + if (i != 0) { + Sleep(1); + continue; + } + ruby_vm_at_exit(vm_exit_handler); + ATOMIC_LONG_CAS(installed, -1, 1); + break; } } @@ -814,9 +814,9 @@ StartSockets(void) // version = MAKEWORD(2, 0); if (WSAStartup(version, &retdata)) - rb_fatal("Unable to locate winsock library!"); + rb_fatal("Unable to locate winsock library!"); if (LOBYTE(retdata.wVersion) != 2) - rb_fatal("could not find version 2 of winsock dll"); + rb_fatal("could not find version 2 of winsock dll"); InitializeCriticalSection(&select_mutex); InitializeCriticalSection(&socklist_mutex); @@ -836,11 +836,11 @@ socklist_insert(SOCKET sock, int flag) int ret; thread_exclusive(socklist) { - if (!socklist) { - socklist = st_init_numtable(); - install_vm_exit_handler(); - } - ret = st_insert(socklist, (st_data_t)sock, (st_data_t)flag); + if (!socklist) { + socklist = st_init_numtable(); + install_vm_exit_handler(); + } + ret = st_insert(socklist, (st_data_t)sock, (st_data_t)flag); } return ret; @@ -854,10 +854,10 @@ socklist_lookup(SOCKET sock, int *flagp) int ret = 0; thread_exclusive(socklist) { - if (!socklist) continue; - ret = st_lookup(socklist, (st_data_t)sock, &data); - if (ret && flagp) - *flagp = (int)data; + if (!socklist) continue; + ret = st_lookup(socklist, (st_data_t)sock, &data); + if (ret && flagp) + *flagp = (int)data; } return ret; @@ -872,16 +872,16 @@ socklist_delete(SOCKET *sockp, int *flagp) int ret = 0; thread_exclusive(socklist) { - if (!socklist) continue; - key = (st_data_t)*sockp; - if (flagp) - data = (st_data_t)*flagp; - ret = st_delete(socklist, &key, &data); - if (ret) { - *sockp = (SOCKET)key; - if (flagp) - *flagp = (int)data; - } + if (!socklist) continue; + key = (st_data_t)*sockp; + if (flagp) + data = (st_data_t)*flagp; + ret = st_delete(socklist, &key, &data); + if (ret) { + *sockp = (SOCKET)key; + if (flagp) + *flagp = (int)data; + } } return ret; @@ -959,9 +959,9 @@ FindChildSlot(rb_pid_t pid) { FOREACH_CHILD(child) { - if (child->pid == pid) { - return child; - } + if (child->pid == pid) { + return child; + } } END_FOREACH_CHILD; return NULL; } @@ -972,9 +972,9 @@ FindChildSlotByHandle(HANDLE h) { FOREACH_CHILD(child) { - if (child->hProcess == h) { - return child; - } + if (child->hProcess == h) { + return child; + } } END_FOREACH_CHILD; return NULL; } @@ -994,11 +994,11 @@ static struct ChildRecord * FindFreeChildSlot(void) { FOREACH_CHILD(child) { - if (!child->pid) { - child->pid = -1; /* lock the slot */ - child->hProcess = NULL; - return child; - } + if (!child->pid) { + child->pid = -1; /* lock the slot */ + child->hProcess = NULL; + return child; + } } END_FOREACH_CHILD; return NULL; } @@ -1077,8 +1077,8 @@ is_command_com(const char *interp) int i = strlen(interp) - 11; if ((i == 0 || (i > 0 && isdirsep(interp[i-1]))) && - strcasecmp(interp+i, "command.com") == 0) { - return 1; + strcasecmp(interp+i, "command.com") == 0) { + return 1; } return 0; } @@ -1092,23 +1092,23 @@ is_internal_cmd(const char *cmd, int nt) char cmdname[9], *b = cmdname, c; do { - if (!(c = *cmd++)) return 0; + if (!(c = *cmd++)) return 0; } while (isspace(c)); if (c == '@') - return 1; + return 1; while (isalpha(c)) { - *b++ = tolower(c); - if (b == cmdname + sizeof(cmdname)) return 0; - c = *cmd++; + *b++ = tolower(c); + if (b == cmdname + sizeof(cmdname)) return 0; + c = *cmd++; } if (c == '.') c = *cmd; switch (c) { case '<': case '>': case '|': - return 1; + return 1; case '\0': case ' ': case '\t': case '\n': - break; + break; default: - return 0; + return 0; } *b = 0; return internal_cmd_match(cmdname, nt); @@ -1121,11 +1121,11 @@ internal_cmd_match(const char *cmdname, int nt) char *nm; nm = bsearch(cmdname, szInternalCmds, - sizeof(szInternalCmds) / sizeof(*szInternalCmds), - sizeof(*szInternalCmds), - internal_match); + sizeof(szInternalCmds) / sizeof(*szInternalCmds), + sizeof(*szInternalCmds), + internal_match); if (!nm || !(nm[0] & (nt ? 2 : 1))) - return 0; + return 0; return 1; } @@ -1145,67 +1145,67 @@ join_argv(char *cmd, char *const *argv, BOOL escape, UINT cp, int backslash) int len, n, bs, quote; for (t = argv, q = cmd, len = 0; (p = *t) != 0; t++) { - quote = 0; - s = p; - if (!*p || strpbrk(p, " \t\"'")) { - quote = 1; - len++; - if (q) *q++ = '"'; - } - for (bs = 0; *p; ++p) { - switch (*p) { - case '\\': - ++bs; - break; - case '"': - len += n = p - s; - if (q) { - memcpy(q, s, n); - q += n; - } - s = p; - len += ++bs; - if (q) { - memset(q, '\\', bs); - q += bs; - } - bs = 0; - break; - case '<': case '>': case '|': case '^': - if (escape && !quote) { - len += (n = p - s) + 1; - if (q) { - memcpy(q, s, n); - q += n; - *q++ = '^'; - } - s = p; - break; - } - default: - bs = 0; - p = CharNextExA(cp, p, 0) - 1; - break; - } - } - len += (n = p - s) + 1; - if (quote) len++; - if (q) { - memcpy(q, s, n); - if (backslash > 0) { - --backslash; - q[n] = 0; - translate_char(q, '/', '\\', cp); - } - q += n; - if (quote) *q++ = '"'; - *q++ = ' '; - } + quote = 0; + s = p; + if (!*p || strpbrk(p, " \t\"'")) { + quote = 1; + len++; + if (q) *q++ = '"'; + } + for (bs = 0; *p; ++p) { + switch (*p) { + case '\\': + ++bs; + break; + case '"': + len += n = p - s; + if (q) { + memcpy(q, s, n); + q += n; + } + s = p; + len += ++bs; + if (q) { + memset(q, '\\', bs); + q += bs; + } + bs = 0; + break; + case '<': case '>': case '|': case '^': + if (escape && !quote) { + len += (n = p - s) + 1; + if (q) { + memcpy(q, s, n); + q += n; + *q++ = '^'; + } + s = p; + break; + } + default: + bs = 0; + p = CharNextExA(cp, p, 0) - 1; + break; + } + } + len += (n = p - s) + 1; + if (quote) len++; + if (q) { + memcpy(q, s, n); + if (backslash > 0) { + --backslash; + q[n] = 0; + translate_char(q, '/', '\\', cp); + } + q += n; + if (quote) *q++ = '"'; + *q++ = ' '; + } } if (q > cmd) --len; if (q) { - if (q > cmd) --q; - *q = '\0'; + if (q > cmd) --q; + *q = '\0'; } return len; } @@ -1221,10 +1221,10 @@ check_spawn_mode(int mode) switch (mode) { case P_NOWAIT: case P_OVERLAY: - return 0; + return 0; default: - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } } @@ -1235,14 +1235,14 @@ child_result(struct ChildRecord *child, int mode) DWORD exitcode; if (!child) { - return -1; + return -1; } if (mode == P_OVERLAY) { - WaitForSingleObject(child->hProcess, INFINITE); - GetExitCodeProcess(child->hProcess, &exitcode); - CloseChildHandle(child); - _exit(exitcode); + WaitForSingleObject(child->hProcess, INFINITE); + GetExitCodeProcess(child->hProcess, &exitcode); + CloseChildHandle(child); + _exit(exitcode); } return child->pid; } @@ -1257,7 +1257,7 @@ CreateChild(struct ChildRecord *child, const WCHAR *cmd, const WCHAR *prog, HAND SECURITY_ATTRIBUTES sa; if (!cmd && !prog) { - errno = EFAULT; + errno = EFAULT; return FALSE; } @@ -1275,41 +1275,41 @@ CreateChild(struct ChildRecord *child, const WCHAR *cmd, const WCHAR *prog, HAND aStartupInfo.cb = sizeof(aStartupInfo); aStartupInfo.dwFlags = STARTF_USESTDHANDLES; if (hInput) { - aStartupInfo.hStdInput = hInput; + aStartupInfo.hStdInput = hInput; } else { - aStartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE); + aStartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE); } if (hOutput) { - aStartupInfo.hStdOutput = hOutput; + aStartupInfo.hStdOutput = hOutput; } else { - aStartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); + aStartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); } if (hError) { - aStartupInfo.hStdError = hError; + aStartupInfo.hStdError = hError; } else { - aStartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE); + aStartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE); } dwCreationFlags |= NORMAL_PRIORITY_CLASS; if (lstrlenW(cmd) > 32767) { - child->pid = 0; /* release the slot */ - errno = E2BIG; + child->pid = 0; /* release the slot */ + errno = E2BIG; return FALSE; } RUBY_CRITICAL { fRet = CreateProcessW(prog, (WCHAR *)cmd, &sa, &sa, sa.bInheritHandle, dwCreationFlags, NULL, NULL, - &aStartupInfo, &aProcessInformation); - errno = map_errno(GetLastError()); + &aStartupInfo, &aProcessInformation); + errno = map_errno(GetLastError()); } if (!fRet) { - child->pid = 0; /* release the slot */ + child->pid = 0; /* release the slot */ return FALSE; } @@ -1402,95 +1402,95 @@ w32_spawn(int mode, const char *cmd, const char *prog, UINT cp) if (check_spawn_mode(mode)) return -1; if (prog) { - if (!(p = dln_find_exe_r(prog, NULL, fbuf, sizeof(fbuf)))) { - shell = prog; - } - else { - shell = p; - translate_char(p, '/', '\\', cp); - } + if (!(p = dln_find_exe_r(prog, NULL, fbuf, sizeof(fbuf)))) { + shell = prog; + } + else { + shell = p; + translate_char(p, '/', '\\', cp); + } } else { - int redir = -1; - int nt; - while (ISSPACE(*cmd)) cmd++; - if ((shell = w32_getenv("RUBYSHELL", cp)) && (redir = has_redirection(cmd, cp))) { - size_t shell_len = strlen(shell); - char *tmp = ALLOCV(v, shell_len + strlen(cmd) + sizeof(" -c ") + 2); - memcpy(tmp, shell, shell_len + 1); - translate_char(tmp, '/', '\\', cp); - sprintf(tmp + shell_len, " -c \"%s\"", cmd); - cmd = tmp; - } - else if ((shell = w32_getenv("COMSPEC", cp)) && - (nt = !is_command_com(shell), - (redir < 0 ? has_redirection(cmd, cp) : redir) || - is_internal_cmd(cmd, nt))) { - char *tmp = ALLOCV(v, strlen(shell) + strlen(cmd) + sizeof(" /c ") + (nt ? 2 : 0)); - sprintf(tmp, nt ? "%s /c \"%s\"" : "%s /c %s", shell, cmd); - cmd = tmp; - } - else { - int len = 0, quote = (*cmd == '"') ? '"' : (*cmd == '\'') ? '\'' : 0; - int slash = 0; - for (prog = cmd + !!quote;; prog = CharNextExA(cp, prog, 0)) { - if (*prog == '/') slash = 1; - if (!*prog) { - len = prog - cmd; - if (slash) { - STRNDUPV(p, v2, cmd, len); - cmd = p; - } - shell = cmd; - break; - } - if ((unsigned char)*prog == quote) { - len = prog++ - cmd - 1; - STRNDUPV(p, v2, cmd + 1, len); - shell = p; - break; - } - if (quote) continue; - if (ISSPACE(*prog) || strchr("<>|*?\"", *prog)) { - len = prog - cmd; - STRNDUPV(p, v2, cmd, len + (slash ? strlen(prog) : 0)); - if (slash) { - cmd = p; - sep = *(cmd_sep = &p[len]); - *cmd_sep = '\0'; - } - shell = p; - break; - } - } - shell = dln_find_exe_r(shell, NULL, fbuf, sizeof(fbuf)); - if (p && slash) translate_char(p, '/', '\\', cp); - if (!shell) { - shell = p ? p : cmd; - } - else { - len = strlen(shell); - if (strchr(shell, ' ')) quote = -1; - if (shell == fbuf) { - p = fbuf; - } - else if (shell != p && strchr(shell, '/')) { - STRNDUPV(p, v2, shell, len); - shell = p; - } - if (p) translate_char(p, '/', '\\', cp); - if (is_batch(shell)) { - int alen = strlen(prog); - cmd = p = ALLOCV(v, len + alen + (quote ? 2 : 0) + 1); - if (quote) *p++ = '"'; - memcpy(p, shell, len); - p += len; - if (quote) *p++ = '"'; - memcpy(p, prog, alen + 1); - shell = 0; - } - } - } + int redir = -1; + int nt; + while (ISSPACE(*cmd)) cmd++; + if ((shell = w32_getenv("RUBYSHELL", cp)) && (redir = has_redirection(cmd, cp))) { + size_t shell_len = strlen(shell); + char *tmp = ALLOCV(v, shell_len + strlen(cmd) + sizeof(" -c ") + 2); + memcpy(tmp, shell, shell_len + 1); + translate_char(tmp, '/', '\\', cp); + sprintf(tmp + shell_len, " -c \"%s\"", cmd); + cmd = tmp; + } + else if ((shell = w32_getenv("COMSPEC", cp)) && + (nt = !is_command_com(shell), + (redir < 0 ? has_redirection(cmd, cp) : redir) || + is_internal_cmd(cmd, nt))) { + char *tmp = ALLOCV(v, strlen(shell) + strlen(cmd) + sizeof(" /c ") + (nt ? 2 : 0)); + sprintf(tmp, nt ? "%s /c \"%s\"" : "%s /c %s", shell, cmd); + cmd = tmp; + } + else { + int len = 0, quote = (*cmd == '"') ? '"' : (*cmd == '\'') ? '\'' : 0; + int slash = 0; + for (prog = cmd + !!quote;; prog = CharNextExA(cp, prog, 0)) { + if (*prog == '/') slash = 1; + if (!*prog) { + len = prog - cmd; + if (slash) { + STRNDUPV(p, v2, cmd, len); + cmd = p; + } + shell = cmd; + break; + } + if ((unsigned char)*prog == quote) { + len = prog++ - cmd - 1; + STRNDUPV(p, v2, cmd + 1, len); + shell = p; + break; + } + if (quote) continue; + if (ISSPACE(*prog) || strchr("<>|*?\"", *prog)) { + len = prog - cmd; + STRNDUPV(p, v2, cmd, len + (slash ? strlen(prog) : 0)); + if (slash) { + cmd = p; + sep = *(cmd_sep = &p[len]); + *cmd_sep = '\0'; + } + shell = p; + break; + } + } + shell = dln_find_exe_r(shell, NULL, fbuf, sizeof(fbuf)); + if (p && slash) translate_char(p, '/', '\\', cp); + if (!shell) { + shell = p ? p : cmd; + } + else { + len = strlen(shell); + if (strchr(shell, ' ')) quote = -1; + if (shell == fbuf) { + p = fbuf; + } + else if (shell != p && strchr(shell, '/')) { + STRNDUPV(p, v2, shell, len); + shell = p; + } + if (p) translate_char(p, '/', '\\', cp); + if (is_batch(shell)) { + int alen = strlen(prog); + cmd = p = ALLOCV(v, len + alen + (quote ? 2 : 0) + 1); + if (quote) *p++ = '"'; + memcpy(p, shell, len); + p += len; + if (quote) *p++ = '"'; + memcpy(p, prog, alen + 1); + shell = 0; + } + } + } } if (!e && shell && !(wshell = mbstr_to_wstr(cp, shell, -1, NULL))) e = E2BIG; @@ -1544,43 +1544,43 @@ w32_aspawn_flags(int mode, const char *prog, char *const *argv, DWORD flags, UIN if (!prog) prog = argv[0]; if ((shell = w32_getenv("COMSPEC", cp)) && - internal_cmd_match(prog, tmpnt = !is_command_com(shell))) { - ntcmd = tmpnt; - prog = shell; - c_switch = 1; + internal_cmd_match(prog, tmpnt = !is_command_com(shell))) { + ntcmd = tmpnt; + prog = shell; + c_switch = 1; } else if ((cmd = dln_find_exe_r(prog, NULL, fbuf, sizeof(fbuf)))) { - if (cmd == prog) strlcpy(cmd = fbuf, prog, sizeof(fbuf)); - translate_char(cmd, '/', '\\', cp); - prog = cmd; + if (cmd == prog) strlcpy(cmd = fbuf, prog, sizeof(fbuf)); + translate_char(cmd, '/', '\\', cp); + prog = cmd; } else if (strchr(prog, '/')) { - len = strlen(prog); - if (len < sizeof(fbuf)) - strlcpy(cmd = fbuf, prog, sizeof(fbuf)); - else - STRNDUPV(cmd, v, prog, len); - translate_char(cmd, '/', '\\', cp); - prog = cmd; + len = strlen(prog); + if (len < sizeof(fbuf)) + strlcpy(cmd = fbuf, prog, sizeof(fbuf)); + else + STRNDUPV(cmd, v, prog, len); + translate_char(cmd, '/', '\\', cp); + prog = cmd; } if (c_switch || is_batch(prog)) { - char *progs[2]; - progs[0] = (char *)prog; - progs[1] = NULL; - len = join_argv(NULL, progs, ntcmd, cp, 1); - if (c_switch) len += 3; - else ++argv; - if (argv[0]) len += join_argv(NULL, argv, ntcmd, cp, 0); - cmd = ALLOCV(v, len); - join_argv(cmd, progs, ntcmd, cp, 1); - if (c_switch) strlcat(cmd, " /c", len); - if (argv[0]) join_argv(cmd + strlcat(cmd, " ", len), argv, ntcmd, cp, 0); - prog = c_switch ? shell : 0; + char *progs[2]; + progs[0] = (char *)prog; + progs[1] = NULL; + len = join_argv(NULL, progs, ntcmd, cp, 1); + if (c_switch) len += 3; + else ++argv; + if (argv[0]) len += join_argv(NULL, argv, ntcmd, cp, 0); + cmd = ALLOCV(v, len); + join_argv(cmd, progs, ntcmd, cp, 1); + if (c_switch) strlcat(cmd, " /c", len); + if (argv[0]) join_argv(cmd + strlcat(cmd, " ", len), argv, ntcmd, cp, 0); + prog = c_switch ? shell : 0; } else { - len = join_argv(NULL, argv, FALSE, cp, 1); - cmd = ALLOCV(v, len); - join_argv(cmd, argv, FALSE, cp, 1); + len = join_argv(NULL, argv, FALSE, cp, 1); + cmd = ALLOCV(v, len); + join_argv(cmd, argv, FALSE, cp, 1); } if (!e && cmd && !(wcmd = mbstr_to_wstr(cp, cmd, -1, NULL))) e = E2BIG; @@ -1673,18 +1673,18 @@ cmdglob(NtCmdLineElement *patt, NtCmdLineElement **tail, UINT cp, rb_encoding *e int status; if (patt->len >= PATH_MAX) - if (!(buf = malloc(patt->len + 1))) return 0; + if (!(buf = malloc(patt->len + 1))) return 0; memcpy(buf, patt->str, patt->len); buf[patt->len] = '\0'; translate_char(buf, '\\', '/', cp); status = ruby_brace_glob_with_enc(buf, 0, insert, (VALUE)&tail, enc); if (buf != buffer) - free(buf); + free(buf); if (status || last == tail) return 0; if (patt->flags & NTMALLOC) - free(patt->str); + free(patt->str); free(patt); return tail; } @@ -1707,38 +1707,38 @@ has_redirection(const char *cmd, UINT cp) // for (ptr = cmd; *ptr;) { - switch (*ptr) { - case '\'': - case '\"': - if (!quote) - quote = *ptr; - else if (quote == *ptr) - quote = '\0'; - ptr++; - break; + switch (*ptr) { + case '\'': + case '\"': + if (!quote) + quote = *ptr; + else if (quote == *ptr) + quote = '\0'; + ptr++; + break; - case '>': - case '<': - case '|': - case '&': - case '\n': - if (!quote) - return TRUE; - ptr++; - break; + case '>': + case '<': + case '|': + case '&': + case '\n': + if (!quote) + return TRUE; + ptr++; + break; - case '%': - if (*++ptr != '_' && !ISALPHA(*ptr)) break; - while (*++ptr == '_' || ISALNUM(*ptr)); - if (*ptr++ == '%') return TRUE; - break; + case '%': + if (*++ptr != '_' && !ISALPHA(*ptr)) break; + while (*++ptr == '_' || ISALNUM(*ptr)); + if (*ptr++ == '%') return TRUE; + break; - case '\\': - ptr++; - default: - ptr = CharNextExA(cp, ptr, 0); - break; - } + case '\\': + ptr++; + default: + ptr = CharNextExA(cp, ptr, 0); + break; + } } return FALSE; } @@ -1748,7 +1748,7 @@ static inline WCHAR * skipspace(WCHAR *ptr) { while (ISSPACE(*ptr)) - ptr++; + ptr++; return ptr; } @@ -1770,10 +1770,10 @@ w32_cmdvector(const WCHAR *cmd, char ***vec, UINT cp, rb_encoding *enc) // just return if we don't have a command line // while (ISSPACE(*cmd)) - cmd++; + cmd++; if (!*cmd) { - *vec = NULL; - return 0; + *vec = NULL; + return 0; } ptr = cmdline = wcsdup(cmd); @@ -1788,147 +1788,147 @@ w32_cmdvector(const WCHAR *cmd, char ***vec, UINT cp, rb_encoding *enc) // while (*(ptr = skipspace(ptr))) { - base = ptr; - quote = slashes = globbing = escape = 0; - for (done = 0; !done && *ptr; ) { - // - // Switch on the current character. We only care about the - // white-space characters, the wild-card characters, and the - // quote characters. - // + base = ptr; + quote = slashes = globbing = escape = 0; + for (done = 0; !done && *ptr; ) { + // + // Switch on the current character. We only care about the + // white-space characters, the wild-card characters, and the + // quote characters. + // - switch (*ptr) { - case L'\\': - if (quote != L'\'') slashes++; - break; + switch (*ptr) { + case L'\\': + if (quote != L'\'') slashes++; + break; - case L' ': - case L'\t': - case L'\n': - // - // if we're not in a string, then we're finished with this - // element - // + case L' ': + case L'\t': + case L'\n': + // + // if we're not in a string, then we're finished with this + // element + // - if (!quote) { - *ptr = 0; - done = 1; - } - break; + if (!quote) { + *ptr = 0; + done = 1; + } + break; - case L'*': - case L'?': - case L'[': - case L'{': - // - // record the fact that this element has a wildcard character - // N.B. Don't glob if inside a single quoted string - // + case L'*': + case L'?': + case L'[': + case L'{': + // + // record the fact that this element has a wildcard character + // N.B. Don't glob if inside a single quoted string + // - if (quote != L'\'') - globbing++; - slashes = 0; - break; + if (quote != L'\'') + globbing++; + slashes = 0; + break; - case L'\'': - case L'\"': - // - // if we're already in a string, see if this is the - // terminating close-quote. If it is, we're finished with - // the string, but not necessarily with the element. - // If we're not already in a string, start one. - // + case L'\'': + case L'\"': + // + // if we're already in a string, see if this is the + // terminating close-quote. If it is, we're finished with + // the string, but not necessarily with the element. + // If we're not already in a string, start one. + // - if (!(slashes & 1)) { - if (!quote) - quote = *ptr; - else if (quote == *ptr) { - if (quote == L'"' && quote == ptr[1]) - ptr++; - quote = L'\0'; - } - } - escape++; - slashes = 0; - break; + if (!(slashes & 1)) { + if (!quote) + quote = *ptr; + else if (quote == *ptr) { + if (quote == L'"' && quote == ptr[1]) + ptr++; + quote = L'\0'; + } + } + escape++; + slashes = 0; + break; - default: - ptr = CharNextW(ptr); - slashes = 0; - continue; - } - ptr++; - } + default: + ptr = CharNextW(ptr); + slashes = 0; + continue; + } + ptr++; + } - // - // when we get here, we've got a pair of pointers to the element, - // base and ptr. Base points to the start of the element while ptr - // points to the character following the element. - // + // + // when we get here, we've got a pair of pointers to the element, + // base and ptr. Base points to the start of the element while ptr + // points to the character following the element. + // - len = ptr - base; - if (done) --len; + len = ptr - base; + if (done) --len; - // - // if it's an input vector element and it's enclosed by quotes, - // we can remove them. - // + // + // if it's an input vector element and it's enclosed by quotes, + // we can remove them. + // - if (escape) { - WCHAR *p = base, c; - slashes = quote = 0; - while (p < base + len) { - switch (c = *p) { - case L'\\': - p++; - if (quote != L'\'') slashes++; - break; + if (escape) { + WCHAR *p = base, c; + slashes = quote = 0; + while (p < base + len) { + switch (c = *p) { + case L'\\': + p++; + if (quote != L'\'') slashes++; + break; - case L'\'': - case L'"': - if (!(slashes & 1) && quote && quote != c) { - p++; - slashes = 0; - break; - } - memcpy(p - ((slashes + 1) >> 1), p + (~slashes & 1), - sizeof(WCHAR) * (base + len - p)); - len -= ((slashes + 1) >> 1) + (~slashes & 1); - p -= (slashes + 1) >> 1; - if (!(slashes & 1)) { - if (quote) { - if (quote == L'"' && quote == *p) - p++; - quote = L'\0'; - } - else - quote = c; - } - else - p++; - slashes = 0; - break; + case L'\'': + case L'"': + if (!(slashes & 1) && quote && quote != c) { + p++; + slashes = 0; + break; + } + memcpy(p - ((slashes + 1) >> 1), p + (~slashes & 1), + sizeof(WCHAR) * (base + len - p)); + len -= ((slashes + 1) >> 1) + (~slashes & 1); + p -= (slashes + 1) >> 1; + if (!(slashes & 1)) { + if (quote) { + if (quote == L'"' && quote == *p) + p++; + quote = L'\0'; + } + else + quote = c; + } + else + p++; + slashes = 0; + break; - default: - p = CharNextW(p); - slashes = 0; - break; - } - } - } + default: + p = CharNextW(p); + slashes = 0; + break; + } + } + } - curr = (NtCmdLineElement *)calloc(sizeof(NtCmdLineElement), 1); - if (!curr) goto do_nothing; - curr->str = rb_w32_wstr_to_mbstr(cp, base, len, &curr->len); - curr->flags |= NTMALLOC; + curr = (NtCmdLineElement *)calloc(sizeof(NtCmdLineElement), 1); + if (!curr) goto do_nothing; + curr->str = rb_w32_wstr_to_mbstr(cp, base, len, &curr->len); + curr->flags |= NTMALLOC; - if (globbing && (tail = cmdglob(curr, cmdtail, cp, enc))) { - cmdtail = tail; - } - else { - *cmdtail = curr; - cmdtail = &curr->next; - } + if (globbing && (tail = cmdglob(curr, cmdtail, cp, enc))) { + cmdtail = tail; + } + else { + *cmdtail = curr; + cmdtail = &curr->next; + } } // @@ -1938,22 +1938,22 @@ w32_cmdvector(const WCHAR *cmd, char ***vec, UINT cp, rb_encoding *enc) // for (elements = 0, strsz = 0, curr = cmdhead; curr; curr = curr->next) { - elements++; - strsz += (curr->len + 1); + elements++; + strsz += (curr->len + 1); } len = (elements+1)*sizeof(char *) + strsz; buffer = (char *)malloc(len); if (!buffer) { do_nothing: - while ((curr = cmdhead) != 0) { - cmdhead = curr->next; - if (curr->flags & NTMALLOC) free(curr->str); - free(curr); - } - free(cmdline); - for (vptr = *vec; *vptr; ++vptr); - return vptr - *vec; + while ((curr = cmdhead) != 0) { + cmdhead = curr->next; + if (curr->flags & NTMALLOC) free(curr->str); + free(curr); + } + free(cmdline); + for (vptr = *vec; *vptr; ++vptr); + return vptr - *vec; } // @@ -1973,13 +1973,13 @@ w32_cmdvector(const WCHAR *cmd, char ***vec, UINT cp, rb_encoding *enc) cptr = buffer + (elements+1) * sizeof(char *); while ((curr = cmdhead) != 0) { - memcpy(cptr, curr->str, curr->len); - cptr[curr->len] = '\0'; - *vptr++ = cptr; - cptr += curr->len + 1; - cmdhead = curr->next; - if (curr->flags & NTMALLOC) free(curr->str); - free(curr); + memcpy(cptr, curr->str, curr->len); + cptr[curr->len] = '\0'; + *vptr++ = cptr; + cptr += curr->len + 1; + cmdhead = curr->next; + if (curr->flags & NTMALLOC) free(curr->str); + free(curr); } *vptr = 0; @@ -2006,7 +2006,7 @@ get_final_path_unknown(HANDLE f, WCHAR *buf, DWORD len, DWORD flag) { /* Since Windows Vista and Windows Server 2008 */ get_final_path_func func = (get_final_path_func) - get_proc_address("kernel32", "GetFinalPathNameByHandleW", NULL); + get_proc_address("kernel32", "GetFinalPathNameByHandleW", NULL); if (!func) func = get_final_path_fail; get_final_path = func; return func(f, buf, len, flag); @@ -2020,9 +2020,9 @@ static HANDLE open_special(const WCHAR *path, DWORD access, DWORD flags) { const DWORD share_mode = - FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; return CreateFileW(path, access, share_mode, NULL, OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS|flags, NULL); + FILE_FLAG_BACKUP_SEMANTICS|flags, NULL); } // @@ -2058,20 +2058,20 @@ open_dir_handle(const WCHAR *filename, WIN32_FIND_DATAW *fd) fh = open_special(filename, 0, 0); if (fh != INVALID_HANDLE_VALUE) { - len = get_final_path(fh, fullname, FINAL_PATH_MAX, 0); - CloseHandle(fh); - if (len >= FINAL_PATH_MAX) { - errno = ENAMETOOLONG; - return INVALID_HANDLE_VALUE; - } + len = get_final_path(fh, fullname, FINAL_PATH_MAX, 0); + CloseHandle(fh); + if (len >= FINAL_PATH_MAX) { + errno = ENAMETOOLONG; + return INVALID_HANDLE_VALUE; + } } if (!len) { - len = lstrlenW(filename); - if (len >= PATH_MAX) { - errno = ENAMETOOLONG; - return INVALID_HANDLE_VALUE; - } - MEMCPY(fullname, filename, WCHAR, len); + len = lstrlenW(filename); + if (len >= PATH_MAX) { + errno = ENAMETOOLONG; + return INVALID_HANDLE_VALUE; + } + MEMCPY(fullname, filename, WCHAR, len); } p = &fullname[len-1]; if (!(isdirsep(*p) || *p == L':')) *++p = L'\\'; @@ -2083,7 +2083,7 @@ open_dir_handle(const WCHAR *filename, WIN32_FIND_DATAW *fd) // fh = FindFirstFileW(fullname, fd); if (fh == INVALID_HANDLE_VALUE) { - errno = map_errno(GetLastError()); + errno = map_errno(GetLastError()); } return fh; } @@ -2107,17 +2107,17 @@ w32_wopendir(const WCHAR *wpath) // check to see if we've got a directory // if (wstati128(wpath, &sbuf, FALSE) < 0) { - return NULL; + return NULL; } if (!(sbuf.st_mode & S_IFDIR) && - (!ISALPHA(wpath[0]) || wpath[1] != L':' || wpath[2] != L'\0' || - ((1 << ((wpath[0] & 0x5f) - 'A')) & GetLogicalDrives()) == 0)) { - errno = ENOTDIR; - return NULL; + (!ISALPHA(wpath[0]) || wpath[1] != L':' || wpath[2] != L'\0' || + ((1 << ((wpath[0] & 0x5f) - 'A')) & GetLogicalDrives()) == 0)) { + errno = ENOTDIR; + return NULL; } fh = open_dir_handle(wpath, &fd); if (fh == INVALID_HANDLE_VALUE) { - return NULL; + return NULL; } // @@ -2125,7 +2125,7 @@ w32_wopendir(const WCHAR *wpath) // p = calloc(sizeof(DIR), 1); if (p == NULL) - return NULL; + return NULL; pathlen = lstrlenW(wpath); idx = 0; @@ -2137,47 +2137,47 @@ w32_wopendir(const WCHAR *wpath) // of the previous string found. // do { - len = lstrlenW(fd.cFileName) + 1; - altlen = lstrlenW(fd.cAlternateFileName) + 1; + len = lstrlenW(fd.cFileName) + 1; + altlen = lstrlenW(fd.cAlternateFileName) + 1; - // - // bump the string table size by enough for the - // new name and it's null terminator - // - tmpW = realloc(p->start, (idx + len + altlen) * sizeof(WCHAR)); - if (!tmpW) { - error: - rb_w32_closedir(p); - FindClose(fh); - errno = ENOMEM; - return NULL; - } + // + // bump the string table size by enough for the + // new name and it's null terminator + // + tmpW = realloc(p->start, (idx + len + altlen) * sizeof(WCHAR)); + if (!tmpW) { + error: + rb_w32_closedir(p); + FindClose(fh); + errno = ENOMEM; + return NULL; + } - p->start = tmpW; - memcpy(&p->start[idx], fd.cFileName, len * sizeof(WCHAR)); - memcpy(&p->start[idx + len], fd.cAlternateFileName, altlen * sizeof(WCHAR)); + p->start = tmpW; + memcpy(&p->start[idx], fd.cFileName, len * sizeof(WCHAR)); + memcpy(&p->start[idx + len], fd.cAlternateFileName, altlen * sizeof(WCHAR)); - if (p->nfiles % DIRENT_PER_CHAR == 0) { - tmp = realloc(p->bits, p->nfiles / DIRENT_PER_CHAR + 1); - if (!tmp) - goto error; - p->bits = tmp; - p->bits[p->nfiles / DIRENT_PER_CHAR] = 0; - } - if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) - SetBit(p->bits, BitOfIsDir(p->nfiles)); - if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) { - WCHAR *tmppath = malloc((pathlen + len + 1) * sizeof(WCHAR)); - memcpy(tmppath, wpath, pathlen * sizeof(WCHAR)); - tmppath[pathlen] = L'\\'; - memcpy(tmppath + pathlen + 1, fd.cFileName, len * sizeof(WCHAR)); - if (rb_w32_reparse_symlink_p(tmppath)) - SetBit(p->bits, BitOfIsRep(p->nfiles)); - free(tmppath); - } + if (p->nfiles % DIRENT_PER_CHAR == 0) { + tmp = realloc(p->bits, p->nfiles / DIRENT_PER_CHAR + 1); + if (!tmp) + goto error; + p->bits = tmp; + p->bits[p->nfiles / DIRENT_PER_CHAR] = 0; + } + if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + SetBit(p->bits, BitOfIsDir(p->nfiles)); + if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) { + WCHAR *tmppath = malloc((pathlen + len + 1) * sizeof(WCHAR)); + memcpy(tmppath, wpath, pathlen * sizeof(WCHAR)); + tmppath[pathlen] = L'\\'; + memcpy(tmppath + pathlen + 1, fd.cFileName, len * sizeof(WCHAR)); + if (rb_w32_reparse_symlink_p(tmppath)) + SetBit(p->bits, BitOfIsRep(p->nfiles)); + free(tmppath); + } - p->nfiles++; - idx += len + altlen; + p->nfiles++; + idx += len + altlen; } while (FindNextFileW(fh, &fd)); FindClose(fh); p->size = idx; @@ -2202,9 +2202,9 @@ rb_w32_wstr_to_mbstr(UINT cp, const WCHAR *wstr, int clen, long *plen) if (!(ptr = malloc(len))) return 0; WideCharToMultiByte(cp, 0, wstr, clen, ptr, len, NULL, NULL); if (plen) { - /* exclude NUL only if NUL-terminated string */ - if (clen == -1) --len; - *plen = len; + /* exclude NUL only if NUL-terminated string */ + if (clen == -1) --len; + *plen = len; } return ptr; } @@ -2219,9 +2219,9 @@ rb_w32_mbstr_to_wstr(UINT cp, const char *str, int clen, long *plen) if (!(ptr = malloc(sizeof(WCHAR) * len))) return 0; MultiByteToWideChar(cp, 0, str, clen, ptr, len); if (plen) { - /* exclude NUL only if NUL-terminated string */ - if (clen == -1) --len; - *plen = len; + /* exclude NUL only if NUL-terminated string */ + if (clen == -1) --len; + *plen = len; } return ptr; } @@ -2233,7 +2233,7 @@ rb_w32_opendir(const char *filename) DIR *ret; WCHAR *wpath = filecp_to_wstr(filename, NULL); if (!wpath) - return NULL; + return NULL; ret = w32_wopendir(wpath); free(wpath); return ret; @@ -2246,7 +2246,7 @@ rb_w32_uopendir(const char *filename) DIR *ret; WCHAR *wpath = utf8_to_wstr(filename, NULL); if (!wpath) - return NULL; + return NULL; ret = w32_wopendir(wpath); free(wpath); return ret; @@ -2261,12 +2261,12 @@ static void move_to_next_entry(DIR *dirp) { if (dirp->curr) { - dirp->loc++; - dirp->curr += lstrlenW(dirp->curr) + 1; - dirp->curr += lstrlenW(dirp->curr) + 1; - if (dirp->curr >= (dirp->start + dirp->size)) { - dirp->curr = NULL; - } + dirp->loc++; + dirp->curr += lstrlenW(dirp->curr) + 1; + dirp->curr += lstrlenW(dirp->curr) + 1; + if (dirp->curr >= (dirp->start + dirp->size)) { + dirp->curr = NULL; + } } } @@ -2280,11 +2280,11 @@ win32_direct_conv(const WCHAR *file, const WCHAR *alt, struct direct *entry, con { UINT cp = *((UINT *)enc); if (!(entry->d_name = wstr_to_mbstr(cp, file, -1, &entry->d_namlen))) - return FALSE; + return FALSE; if (alt && *alt) { - long altlen = 0; - entry->d_altname = wstr_to_mbstr(cp, alt, -1, &altlen); - entry->d_altlen = altlen; + long altlen = 0; + entry->d_altname = wstr_to_mbstr(cp, alt, -1, &altlen); + entry->d_altlen = altlen; } return TRUE; } @@ -2298,24 +2298,24 @@ rb_w32_conv_from_wchar(const WCHAR *wstr, rb_encoding *enc) int encindex = rb_enc_to_index(enc); if (encindex == ENCINDEX_UTF_16LE) { - return rb_enc_str_new((char *)wstr, len * sizeof(WCHAR), enc); + return rb_enc_str_new((char *)wstr, len * sizeof(WCHAR), enc); } else { #if SIZEOF_INT < SIZEOF_LONG # error long should equal to int on Windows #endif - int clen = rb_long2int(len); - len = WideCharToMultiByte(CP_UTF8, 0, wstr, clen, NULL, 0, NULL, NULL); - src = rb_enc_str_new(0, len, rb_enc_from_index(ENCINDEX_UTF_8)); - WideCharToMultiByte(CP_UTF8, 0, wstr, clen, RSTRING_PTR(src), len, NULL, NULL); + int clen = rb_long2int(len); + len = WideCharToMultiByte(CP_UTF8, 0, wstr, clen, NULL, 0, NULL, NULL); + src = rb_enc_str_new(0, len, rb_enc_from_index(ENCINDEX_UTF_8)); + WideCharToMultiByte(CP_UTF8, 0, wstr, clen, RSTRING_PTR(src), len, NULL, NULL); } switch (encindex) { case ENCINDEX_ASCII_8BIT: case ENCINDEX_US_ASCII: - /* assume UTF-8 */ + /* assume UTF-8 */ case ENCINDEX_UTF_8: - /* do nothing */ - return src; + /* do nothing */ + return src; } return rb_str_conv_enc_opts(src, NULL, enc, ECONV_UNDEF_REPLACE, Qnil); } @@ -2340,11 +2340,11 @@ static BOOL ruby_direct_conv(const WCHAR *file, const WCHAR *alt, struct direct *entry, const void *enc) { if (!(entry->d_name = rb_w32_conv_from_wstr(file, &entry->d_namlen, enc))) - return FALSE; + return FALSE; if (alt && *alt) { - long altlen = 0; - entry->d_altname = rb_w32_conv_from_wstr(alt, &altlen, enc); - entry->d_altlen = altlen; + long altlen = 0; + entry->d_altname = rb_w32_conv_from_wstr(alt, &altlen, enc); + entry->d_altlen = altlen; } return TRUE; } @@ -2357,44 +2357,44 @@ readdir_internal(DIR *dirp, BOOL (*conv)(const WCHAR *, const WCHAR *, struct di if (dirp->curr) { - // - // first set up the structure to return - // - if (dirp->dirstr.d_name) - free(dirp->dirstr.d_name); - if (dirp->dirstr.d_altname) - free(dirp->dirstr.d_altname); - dirp->dirstr.d_altname = 0; - dirp->dirstr.d_altlen = 0; - conv(dirp->curr, dirp->curr + lstrlenW(dirp->curr) + 1, &dirp->dirstr, enc); + // + // first set up the structure to return + // + if (dirp->dirstr.d_name) + free(dirp->dirstr.d_name); + if (dirp->dirstr.d_altname) + free(dirp->dirstr.d_altname); + dirp->dirstr.d_altname = 0; + dirp->dirstr.d_altlen = 0; + conv(dirp->curr, dirp->curr + lstrlenW(dirp->curr) + 1, &dirp->dirstr, enc); - // - // Fake inode - // - dirp->dirstr.d_ino = (ino_t)(InterlockedIncrement(&dummy_ino) - 1); + // + // Fake inode + // + dirp->dirstr.d_ino = (ino_t)(InterlockedIncrement(&dummy_ino) - 1); - // - // Attributes - // - /* ignore FILE_ATTRIBUTE_DIRECTORY as unreliable for reparse points */ - if (GetBit(dirp->bits, BitOfIsRep(dirp->loc))) - dirp->dirstr.d_type = DT_LNK; - else if (GetBit(dirp->bits, BitOfIsDir(dirp->loc))) - dirp->dirstr.d_type = DT_DIR; - else - dirp->dirstr.d_type = DT_REG; + // + // Attributes + // + /* ignore FILE_ATTRIBUTE_DIRECTORY as unreliable for reparse points */ + if (GetBit(dirp->bits, BitOfIsRep(dirp->loc))) + dirp->dirstr.d_type = DT_LNK; + else if (GetBit(dirp->bits, BitOfIsDir(dirp->loc))) + dirp->dirstr.d_type = DT_DIR; + else + dirp->dirstr.d_type = DT_REG; - // - // Now set up for the next call to readdir - // + // + // Now set up for the next call to readdir + // - move_to_next_entry(dirp); + move_to_next_entry(dirp); - return &(dirp->dirstr); + return &(dirp->dirstr); } else - return NULL; + return NULL; } /* License: Ruby's */ @@ -2403,15 +2403,15 @@ rb_w32_readdir(DIR *dirp, rb_encoding *enc) { int idx = rb_enc_to_index(enc); if (idx == ENCINDEX_ASCII_8BIT) { - const UINT cp = filecp(); - return readdir_internal(dirp, win32_direct_conv, &cp); + const UINT cp = filecp(); + return readdir_internal(dirp, win32_direct_conv, &cp); } else if (idx == ENCINDEX_UTF_8) { - const UINT cp = CP_UTF8; - return readdir_internal(dirp, win32_direct_conv, &cp); + const UINT cp = CP_UTF8; + return readdir_internal(dirp, win32_direct_conv, &cp); } else - return readdir_internal(dirp, ruby_direct_conv, enc); + return readdir_internal(dirp, ruby_direct_conv, enc); } /* License: Ruby's */ @@ -2444,7 +2444,7 @@ rb_w32_seekdir(DIR *dirp, long loc) if (dirp->loc > loc) rb_w32_rewinddir(dirp); while (dirp->curr && dirp->loc < loc) { - move_to_next_entry(dirp); + move_to_next_entry(dirp); } } @@ -2469,15 +2469,15 @@ void rb_w32_closedir(DIR *dirp) { if (dirp) { - if (dirp->dirstr.d_name) - free(dirp->dirstr.d_name); - if (dirp->dirstr.d_altname) - free(dirp->dirstr.d_altname); - if (dirp->start) - free(dirp->start); - if (dirp->bits) - free(dirp->bits); - free(dirp); + if (dirp->dirstr.d_name) + free(dirp->dirstr.d_name); + if (dirp->dirstr.d_altname) + free(dirp->dirstr.d_altname); + if (dirp->start) + free(dirp->start); + if (dirp->bits) + free(dirp->bits); + free(dirp); } } @@ -2633,15 +2633,15 @@ set_pioinfo_extra(void) fd = _open("NUL", O_RDONLY); for (pioinfo_extra = 0; pioinfo_extra <= 64; pioinfo_extra += sizeof(void *)) { - if (_osfhnd(fd) == _get_osfhandle(fd)) { - break; - } + if (_osfhnd(fd) == _get_osfhandle(fd)) { + break; + } } _close(fd); if (pioinfo_extra > 64) { - /* not found, maybe something wrong... */ - pioinfo_extra = 0; + /* not found, maybe something wrong... */ + pioinfo_extra = 0; } } #else @@ -2653,7 +2653,7 @@ _pioinfo(int fd) { const size_t sizeof_ioinfo = sizeof(ioinfo) + pioinfo_extra; return (ioinfo*)((char*)__pioinfo[fd >> IOINFO_L2E] + - (fd & (IOINFO_ARRAY_ELTS - 1)) * sizeof_ioinfo); + (fd & (IOINFO_ARRAY_ELTS - 1)) * sizeof_ioinfo); } #define _set_osfhnd(fh, osfh) (void)(_osfhnd(fh) = osfh) @@ -2689,32 +2689,32 @@ rb_w32_open_osfhandle(intptr_t osfhandle, int flags) fileflags = FDEV; if (flags & O_APPEND) - fileflags |= FAPPEND; + fileflags |= FAPPEND; if (flags & O_TEXT) - fileflags |= FTEXT; + fileflags |= FTEXT; if (flags & O_NOINHERIT) - fileflags |= FNOINHERIT; + fileflags |= FNOINHERIT; /* attempt to allocate a C Runtime file handle */ hF = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL); fh = _open_osfhandle((intptr_t)hF, 0); CloseHandle(hF); if (fh == -1) { - errno = EMFILE; /* too many open files */ - _doserrno = 0L; /* not an OS error */ + errno = EMFILE; /* too many open files */ + _doserrno = 0L; /* not an OS error */ } else { - rb_acrt_lowio_lock_fh(fh); - /* the file is open. now, set the info in _osfhnd array */ - _set_osfhnd(fh, osfhandle); + rb_acrt_lowio_lock_fh(fh); + /* the file is open. now, set the info in _osfhnd array */ + _set_osfhnd(fh, osfhandle); - fileflags |= FOPEN; /* mark as open */ + fileflags |= FOPEN; /* mark as open */ - _set_osflags(fh, fileflags); /* set osfile entry */ - rb_acrt_lowio_unlock_fh(fh); + _set_osflags(fh, fileflags); /* set osfile entry */ + rb_acrt_lowio_unlock_fh(fh); } return fh; /* return handle */ } @@ -2732,16 +2732,16 @@ init_stdhandle(void) (fd)) if (fileno(stdin) < 0) { - FILE_FILENO(stdin) = open_null(0); + FILE_FILENO(stdin) = open_null(0); } else { - setmode(fileno(stdin), O_BINARY); + setmode(fileno(stdin), O_BINARY); } if (fileno(stdout) < 0) { - FILE_FILENO(stdout) = open_null(1); + FILE_FILENO(stdout) = open_null(1); } if (fileno(stderr) < 0) { - FILE_FILENO(stderr) = open_null(2); + FILE_FILENO(stderr) = open_null(2); } if (nullfd >= 0 && !keep) close(nullfd); setvbuf(stderr, NULL, _IONBF, 0); @@ -2765,9 +2765,9 @@ static int is_socket(SOCKET sock) { if (socklist_lookup(sock, NULL)) - return TRUE; + return TRUE; else - return FALSE; + return FALSE; } /* License: Ruby's */ @@ -2794,38 +2794,38 @@ rb_w32_strerror(int e) char *p; if (e < 0 || e > sys_nerr) { - if (e < 0) - e = GetLastError(); + if (e < 0) + e = GetLastError(); #if WSAEWOULDBLOCK != EWOULDBLOCK - else if (e >= EADDRINUSE && e <= EWOULDBLOCK) { - static int s = -1; - int i; - if (s < 0) - for (s = 0; s < (int)(sizeof(errmap)/sizeof(*errmap)); s++) - if (errmap[s].winerr == WSAEWOULDBLOCK) - break; - for (i = s; i < (int)(sizeof(errmap)/sizeof(*errmap)); i++) - if (errmap[i].err == e) { - e = errmap[i].winerr; - break; - } - } + else if (e >= EADDRINUSE && e <= EWOULDBLOCK) { + static int s = -1; + int i; + if (s < 0) + for (s = 0; s < (int)(sizeof(errmap)/sizeof(*errmap)); s++) + if (errmap[s].winerr == WSAEWOULDBLOCK) + break; + for (i = s; i < (int)(sizeof(errmap)/sizeof(*errmap)); i++) + if (errmap[i].err == e) { + e = errmap[i].winerr; + break; + } + } #endif - if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, &source, e, - MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), - buffer, sizeof(buffer), NULL) == 0 && - FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, &source, e, 0, - buffer, sizeof(buffer), NULL) == 0) - strlcpy(buffer, "Unknown Error", sizeof(buffer)); + if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, &source, e, + MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), + buffer, sizeof(buffer), NULL) == 0 && + FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, &source, e, 0, + buffer, sizeof(buffer), NULL) == 0) + strlcpy(buffer, "Unknown Error", sizeof(buffer)); } else - strlcpy(buffer, strerror(e), sizeof(buffer)); + strlcpy(buffer, strerror(e), sizeof(buffer)); p = buffer; while ((p = strpbrk(p, "\r\n")) != NULL) { - memmove(p, p + 1, strlen(p)); + memmove(p, p + 1, strlen(p)); } return buffer; } @@ -2848,21 +2848,21 @@ rb_w32_strerror(int e) rb_uid_t getuid(void) { - return ROOT_UID; + return ROOT_UID; } /* License: Artistic or GPL */ rb_uid_t geteuid(void) { - return ROOT_UID; + return ROOT_UID; } /* License: Artistic or GPL */ rb_gid_t getgid(void) { - return ROOT_GID; + return ROOT_GID; } /* License: Artistic or GPL */ @@ -2915,8 +2915,8 @@ rb_w32_fdclr(int fd, fd_set *set) for (i = 0; i < set->fd_count; i++) { if (set->fd_array[i] == s) { - memmove(&set->fd_array[i], &set->fd_array[i+1], - sizeof(set->fd_array[0]) * (--set->fd_count - i)); + memmove(&set->fd_array[i], &set->fd_array[i+1], + sizeof(set->fd_array[0]) * (--set->fd_count - i)); break; } } @@ -2942,12 +2942,12 @@ rb_w32_fd_copy(rb_fdset_t *dst, const fd_set *src, int max) { max = min(src->fd_count, (UINT)max); if ((UINT)dst->capa < (UINT)max) { - dst->capa = (src->fd_count / FD_SETSIZE + 1) * FD_SETSIZE; - dst->fdset = xrealloc(dst->fdset, sizeof(unsigned int) + sizeof(SOCKET) * dst->capa); + dst->capa = (src->fd_count / FD_SETSIZE + 1) * FD_SETSIZE; + dst->fdset = xrealloc(dst->fdset, sizeof(unsigned int) + sizeof(SOCKET) * dst->capa); } memcpy(dst->fdset->fd_array, src->fd_array, - max * sizeof(src->fd_array[0])); + max * sizeof(src->fd_array[0])); dst->fdset->fd_count = src->fd_count; } @@ -2956,12 +2956,12 @@ void rb_w32_fd_dup(rb_fdset_t *dst, const rb_fdset_t *src) { if ((UINT)dst->capa < src->fdset->fd_count) { - dst->capa = (src->fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE; - dst->fdset = xrealloc(dst->fdset, sizeof(unsigned int) + sizeof(SOCKET) * dst->capa); + dst->capa = (src->fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE; + dst->fdset = xrealloc(dst->fdset, sizeof(unsigned int) + sizeof(SOCKET) * dst->capa); } memcpy(dst->fdset->fd_array, src->fdset->fd_array, - src->fdset->fd_count * sizeof(src->fdset->fd_array[0])); + src->fdset->fd_count * sizeof(src->fdset->fd_array[0])); dst->fdset->fd_count = src->fdset->fd_count; } @@ -2984,32 +2984,32 @@ extract_fd(rb_fdset_t *dst, fd_set *src, int (*func)(SOCKET)) while (s < src->fd_count) { SOCKET fd = src->fd_array[s]; - if (!func || (*func)(fd)) { - if (dst) { /* move it to dst */ - unsigned int d; + if (!func || (*func)(fd)) { + if (dst) { /* move it to dst */ + unsigned int d; - for (d = 0; d < dst->fdset->fd_count; d++) { - if (dst->fdset->fd_array[d] == fd) - break; - } - if (d == dst->fdset->fd_count) { - if ((int)dst->fdset->fd_count >= dst->capa) { - dst->capa = (dst->fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE; - dst->fdset = xrealloc(dst->fdset, sizeof(unsigned int) + sizeof(SOCKET) * dst->capa); - } - dst->fdset->fd_array[dst->fdset->fd_count++] = fd; - } - memmove( - &src->fd_array[s], - &src->fd_array[s+1], - sizeof(src->fd_array[0]) * (--src->fd_count - s)); - } - else { - m++; - s++; - } - } - else s++; + for (d = 0; d < dst->fdset->fd_count; d++) { + if (dst->fdset->fd_array[d] == fd) + break; + } + if (d == dst->fdset->fd_count) { + if ((int)dst->fdset->fd_count >= dst->capa) { + dst->capa = (dst->fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE; + dst->fdset = xrealloc(dst->fdset, sizeof(unsigned int) + sizeof(SOCKET) * dst->capa); + } + dst->fdset->fd_array[dst->fdset->fd_count++] = fd; + } + memmove( + &src->fd_array[s], + &src->fd_array[s+1], + sizeof(src->fd_array[0]) * (--src->fd_count - s)); + } + else { + m++; + s++; + } + } + else s++; } return dst ? dst->fdset->fd_count : m; @@ -3023,15 +3023,15 @@ copy_fd(fd_set *dst, fd_set *src) if (!src || !dst) return 0; for (s = 0; s < src->fd_count; ++s) { - SOCKET fd = src->fd_array[s]; - unsigned int d; - for (d = 0; d < dst->fd_count; ++d) { - if (dst->fd_array[d] == fd) - break; - } - if (d == dst->fd_count && d < FD_SETSIZE) { - dst->fd_array[dst->fd_count++] = fd; - } + SOCKET fd = src->fd_array[s]; + unsigned int d; + for (d = 0; d < dst->fd_count; ++d) { + if (dst->fd_array[d] == fd) + break; + } + if (d == dst->fd_count && d < FD_SETSIZE) { + dst->fd_array[dst->fd_count++] = fd; + } } return dst->fd_count; @@ -3051,7 +3051,7 @@ is_pipe(SOCKET sock) /* DONT call this for SOCKET! it claims it is PIPE. */ int ret; RUBY_CRITICAL { - ret = (GetFileType((HANDLE)sock) == FILE_TYPE_PIPE); + ret = (GetFileType((HANDLE)sock) == FILE_TYPE_PIPE); } return ret; @@ -3065,12 +3065,12 @@ is_readable_pipe(SOCKET sock) /* call this for pipe only */ DWORD n = 0; RUBY_CRITICAL { - if (PeekNamedPipe((HANDLE)sock, NULL, 0, NULL, &n, NULL)) { - ret = (n > 0); - } - else { - ret = (GetLastError() == ERROR_BROKEN_PIPE); /* pipe was closed */ - } + if (PeekNamedPipe((HANDLE)sock, NULL, 0, NULL, &n, NULL)) { + ret = (n > 0); + } + else { + ret = (GetLastError() == ERROR_BROKEN_PIPE); /* pipe was closed */ + } } return ret; @@ -3085,7 +3085,7 @@ is_console(SOCKET sock) /* DONT call this for SOCKET! */ INPUT_RECORD ir; RUBY_CRITICAL { - ret = (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n)); + ret = (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n)); } return ret; @@ -3100,15 +3100,15 @@ is_readable_console(SOCKET sock) /* call this for console only */ INPUT_RECORD ir; RUBY_CRITICAL { - if (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n) && n > 0) { - if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown && - ir.Event.KeyEvent.uChar.AsciiChar) { - ret = 1; - } - else { - ReadConsoleInputW((HANDLE)sock, &ir, 1, &n); - } - } + if (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n) && n > 0) { + if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown && + ir.Event.KeyEvent.uChar.AsciiChar) { + ret = 1; + } + else { + ReadConsoleInputW((HANDLE)sock, &ir, 1, &n); + } + } } return ret; @@ -3124,26 +3124,26 @@ is_invalid_handle(SOCKET sock) /* License: Artistic or GPL */ static int do_select(int nfds, fd_set *rd, fd_set *wr, fd_set *ex, - struct timeval *timeout) + struct timeval *timeout) { int r = 0; if (nfds == 0) { - if (timeout) - rb_w32_sleep(timeout->tv_sec * 1000 + timeout->tv_usec / 1000); - else - rb_w32_sleep(INFINITE); + if (timeout) + rb_w32_sleep(timeout->tv_sec * 1000 + timeout->tv_usec / 1000); + else + rb_w32_sleep(INFINITE); } else { - RUBY_CRITICAL { - thread_exclusive(select) { - r = select(nfds, rd, wr, ex, timeout); - } - if (r == SOCKET_ERROR) { - errno = map_errno(WSAGetLastError()); - r = -1; - } - } + RUBY_CRITICAL { + thread_exclusive(select) { + r = select(nfds, rd, wr, ex, timeout); + } + if (r == SOCKET_ERROR) { + errno = map_errno(WSAGetLastError()); + r = -1; + } + } } return r; @@ -3158,14 +3158,14 @@ int rb_w32_time_subtract(struct timeval *rest, const struct timeval *wait) { if (rest->tv_sec < wait->tv_sec) { - return 0; + return 0; } while (rest->tv_usec < wait->tv_usec) { - if (rest->tv_sec <= wait->tv_sec) { - return 0; - } - rest->tv_sec -= 1; - rest->tv_usec += 1000 * 1000; + if (rest->tv_sec <= wait->tv_sec) { + return 0; + } + rest->tv_sec -= 1; + rest->tv_usec += 1000 * 1000; } rest->tv_sec -= wait->tv_sec; rest->tv_usec -= wait->tv_usec; @@ -3177,13 +3177,13 @@ static inline int compare(const struct timeval *t1, const struct timeval *t2) { if (t1->tv_sec < t2->tv_sec) - return -1; + return -1; if (t1->tv_sec > t2->tv_sec) - return 1; + return 1; if (t1->tv_usec < t2->tv_usec) - return -1; + return -1; if (t1->tv_usec > t2->tv_usec) - return 1; + return 1; return 0; } @@ -3195,7 +3195,7 @@ int rb_w32_check_interrupt(void *); /* @internal */ /* License: Ruby's */ int rb_w32_select_with_thread(int nfds, fd_set *rd, fd_set *wr, fd_set *ex, - struct timeval *timeout, void *th) + struct timeval *timeout, void *th) { int r; rb_fdset_t pipe_rd; @@ -3207,24 +3207,24 @@ rb_w32_select_with_thread(int nfds, fd_set *rd, fd_set *wr, fd_set *ex, struct timeval limit = {0, 0}; if (nfds < 0 || (timeout && (timeout->tv_sec < 0 || timeout->tv_usec < 0))) { - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } if (timeout) { - if (timeout->tv_sec < 0 || - timeout->tv_usec < 0 || - timeout->tv_usec >= 1000000) { - errno = EINVAL; - return -1; - } - gettimeofday(&limit, NULL); - limit.tv_sec += timeout->tv_sec; - limit.tv_usec += timeout->tv_usec; - if (limit.tv_usec >= 1000000) { - limit.tv_usec -= 1000000; - limit.tv_sec++; - } + if (timeout->tv_sec < 0 || + timeout->tv_usec < 0 || + timeout->tv_usec >= 1000000) { + errno = EINVAL; + return -1; + } + gettimeofday(&limit, NULL); + limit.tv_sec += timeout->tv_sec; + limit.tv_usec += timeout->tv_usec; + if (limit.tv_usec >= 1000000) { + limit.tv_usec -= 1000000; + limit.tv_sec++; + } } // assume else_{rd,wr} (other than socket, pipe reader, console reader) @@ -3241,11 +3241,11 @@ rb_w32_select_with_thread(int nfds, fd_set *rd, fd_set *wr, fd_set *ex, // check invalid handles if (extract_fd(NULL, else_rd.fdset, is_invalid_handle) > 0 || - extract_fd(NULL, else_wr.fdset, is_invalid_handle) > 0) { - rb_fd_term(&else_wr); - rb_fd_term(&else_rd); - errno = EBADF; - return -1; + extract_fd(NULL, else_wr.fdset, is_invalid_handle) > 0) { + rb_fd_term(&else_wr); + rb_fd_term(&else_rd); + errno = EBADF; + return -1; } rb_fd_init(&pipe_rd); @@ -3264,60 +3264,60 @@ rb_w32_select_with_thread(int nfds, fd_set *rd, fd_set *wr, fd_set *ex, if (nfds > r) nfds = r; { - struct timeval rest; - const struct timeval wait = {0, 10 * 1000}; // 10ms - struct timeval zero = {0, 0}; // 0ms - for (;;) { - if (th && rb_w32_check_interrupt(th) != WAIT_TIMEOUT) { - r = -1; - break; - } - if (nonsock) { - // modifying {else,pipe,cons}_rd is safe because - // if they are modified, function returns immediately. - extract_fd(&else_rd, pipe_rd.fdset, is_readable_pipe); - extract_fd(&else_rd, cons_rd.fdset, is_readable_console); - } + struct timeval rest; + const struct timeval wait = {0, 10 * 1000}; // 10ms + struct timeval zero = {0, 0}; // 0ms + for (;;) { + if (th && rb_w32_check_interrupt(th) != WAIT_TIMEOUT) { + r = -1; + break; + } + if (nonsock) { + // modifying {else,pipe,cons}_rd is safe because + // if they are modified, function returns immediately. + extract_fd(&else_rd, pipe_rd.fdset, is_readable_pipe); + extract_fd(&else_rd, cons_rd.fdset, is_readable_console); + } - if (else_rd.fdset->fd_count || else_wr.fdset->fd_count) { - r = do_select(nfds, rd, wr, ex, &zero); // polling - if (r < 0) break; // XXX: should I ignore error and return signaled handles? - r += copy_fd(rd, else_rd.fdset); - r += copy_fd(wr, else_wr.fdset); - if (ex) - r += ex->fd_count; - break; - } - else { - const struct timeval *dowait = &wait; + if (else_rd.fdset->fd_count || else_wr.fdset->fd_count) { + r = do_select(nfds, rd, wr, ex, &zero); // polling + if (r < 0) break; // XXX: should I ignore error and return signaled handles? + r += copy_fd(rd, else_rd.fdset); + r += copy_fd(wr, else_wr.fdset); + if (ex) + r += ex->fd_count; + break; + } + else { + const struct timeval *dowait = &wait; - fd_set orig_rd; - fd_set orig_wr; - fd_set orig_ex; + fd_set orig_rd; + fd_set orig_wr; + fd_set orig_ex; - FD_ZERO(&orig_rd); - FD_ZERO(&orig_wr); - FD_ZERO(&orig_ex); + FD_ZERO(&orig_rd); + FD_ZERO(&orig_wr); + FD_ZERO(&orig_ex); - if (rd) copy_fd(&orig_rd, rd); - if (wr) copy_fd(&orig_wr, wr); - if (ex) copy_fd(&orig_ex, ex); - r = do_select(nfds, rd, wr, ex, &zero); // polling - if (r != 0) break; // signaled or error - if (rd) copy_fd(rd, &orig_rd); - if (wr) copy_fd(wr, &orig_wr); - if (ex) copy_fd(ex, &orig_ex); + if (rd) copy_fd(&orig_rd, rd); + if (wr) copy_fd(&orig_wr, wr); + if (ex) copy_fd(&orig_ex, ex); + r = do_select(nfds, rd, wr, ex, &zero); // polling + if (r != 0) break; // signaled or error + if (rd) copy_fd(rd, &orig_rd); + if (wr) copy_fd(wr, &orig_wr); + if (ex) copy_fd(ex, &orig_ex); - if (timeout) { - struct timeval now; - gettimeofday(&now, NULL); - rest = limit; - if (!rb_w32_time_subtract(&rest, &now)) break; - if (compare(&rest, &wait) < 0) dowait = &rest; - } - Sleep(dowait->tv_sec * 1000 + (dowait->tv_usec + 999) / 1000); - } - } + if (timeout) { + struct timeval now; + gettimeofday(&now, NULL); + rest = limit; + if (!rb_w32_time_subtract(&rest, &now)) break; + if (compare(&rest, &wait) < 0) dowait = &rest; + } + Sleep(dowait->tv_sec * 1000 + (dowait->tv_usec + 999) / 1000); + } + } } rb_fd_term(&except); @@ -3332,7 +3332,7 @@ rb_w32_select_with_thread(int nfds, fd_set *rd, fd_set *wr, fd_set *ex, /* License: Ruby's */ int WSAAPI rb_w32_select(int nfds, fd_set *rd, fd_set *wr, fd_set *ex, - struct timeval *timeout) + struct timeval *timeout) { return rb_w32_select_with_thread(nfds, rd, wr, ex, timeout, 0); } @@ -3345,9 +3345,9 @@ get_wsa_extension_function(SOCKET s, GUID guid) FARPROC ptr = NULL; WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid), - &ptr, sizeof(ptr), &dmy, NULL, NULL); + &ptr, sizeof(ptr), &dmy, NULL, NULL); if (!ptr) - errno = ENOSYS; + errno = ENOSYS; return ptr; } @@ -3361,19 +3361,19 @@ rb_w32_accept(int s, struct sockaddr *addr, int *addrlen) int fd; RUBY_CRITICAL { - r = accept(TO_SOCKET(s), addr, addrlen); - if (r != INVALID_SOCKET) { - SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0); - fd = rb_w32_open_osfhandle((intptr_t)r, O_RDWR|O_BINARY|O_NOINHERIT); - if (fd != -1) - socklist_insert(r, 0); - else - closesocket(r); - } - else { - errno = map_errno(WSAGetLastError()); - fd = -1; - } + r = accept(TO_SOCKET(s), addr, addrlen); + if (r != INVALID_SOCKET) { + SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0); + fd = rb_w32_open_osfhandle((intptr_t)r, O_RDWR|O_BINARY|O_NOINHERIT); + if (fd != -1) + socklist_insert(r, 0); + else + closesocket(r); + } + else { + errno = map_errno(WSAGetLastError()); + fd = -1; + } } return fd; } @@ -3387,9 +3387,9 @@ rb_w32_bind(int s, const struct sockaddr *addr, int addrlen) int r; RUBY_CRITICAL { - r = bind(TO_SOCKET(s), addr, addrlen); - if (r == SOCKET_ERROR) - errno = map_errno(WSAGetLastError()); + r = bind(TO_SOCKET(s), addr, addrlen); + if (r == SOCKET_ERROR) + errno = map_errno(WSAGetLastError()); } return r; } @@ -3402,14 +3402,14 @@ rb_w32_connect(int s, const struct sockaddr *addr, int addrlen) { int r; RUBY_CRITICAL { - r = connect(TO_SOCKET(s), addr, addrlen); - if (r == SOCKET_ERROR) { - int err = WSAGetLastError(); - if (err != WSAEWOULDBLOCK) - errno = map_errno(err); - else - errno = EINPROGRESS; - } + r = connect(TO_SOCKET(s), addr, addrlen); + if (r == SOCKET_ERROR) { + int err = WSAGetLastError(); + if (err != WSAEWOULDBLOCK) + errno = map_errno(err); + else + errno = EINPROGRESS; + } } return r; } @@ -3423,9 +3423,9 @@ rb_w32_getpeername(int s, struct sockaddr *addr, int *addrlen) { int r; RUBY_CRITICAL { - r = getpeername(TO_SOCKET(s), addr, addrlen); - if (r == SOCKET_ERROR) - errno = map_errno(WSAGetLastError()); + r = getpeername(TO_SOCKET(s), addr, addrlen); + if (r == SOCKET_ERROR) + errno = map_errno(WSAGetLastError()); } return r; } @@ -3439,23 +3439,23 @@ rb_w32_getsockname(int fd, struct sockaddr *addr, int *addrlen) int sock; int r; RUBY_CRITICAL { - sock = TO_SOCKET(fd); - r = getsockname(sock, addr, addrlen); - if (r == SOCKET_ERROR) { - DWORD wsaerror = WSAGetLastError(); - if (wsaerror == WSAEINVAL) { - int flags; - if (socklist_lookup(sock, &flags)) { - int af = GET_FAMILY(flags); - if (af) { - memset(addr, 0, *addrlen); - addr->sa_family = af; - return 0; - } - } - } - errno = map_errno(wsaerror); - } + sock = TO_SOCKET(fd); + r = getsockname(sock, addr, addrlen); + if (r == SOCKET_ERROR) { + DWORD wsaerror = WSAGetLastError(); + if (wsaerror == WSAEINVAL) { + int flags; + if (socklist_lookup(sock, &flags)) { + int af = GET_FAMILY(flags); + if (af) { + memset(addr, 0, *addrlen); + addr->sa_family = af; + return 0; + } + } + } + errno = map_errno(wsaerror); + } } return r; } @@ -3468,9 +3468,9 @@ rb_w32_getsockopt(int s, int level, int optname, char *optval, int *optlen) { int r; RUBY_CRITICAL { - r = getsockopt(TO_SOCKET(s), level, optname, optval, optlen); - if (r == SOCKET_ERROR) - errno = map_errno(WSAGetLastError()); + r = getsockopt(TO_SOCKET(s), level, optname, optval, optlen); + if (r == SOCKET_ERROR) + errno = map_errno(WSAGetLastError()); } return r; } @@ -3483,9 +3483,9 @@ rb_w32_ioctlsocket(int s, long cmd, u_long *argp) { int r; RUBY_CRITICAL { - r = ioctlsocket(TO_SOCKET(s), cmd, argp); - if (r == SOCKET_ERROR) - errno = map_errno(WSAGetLastError()); + r = ioctlsocket(TO_SOCKET(s), cmd, argp); + if (r == SOCKET_ERROR) + errno = map_errno(WSAGetLastError()); } return r; } @@ -3498,9 +3498,9 @@ rb_w32_listen(int s, int backlog) { int r; RUBY_CRITICAL { - r = listen(TO_SOCKET(s), backlog); - if (r == SOCKET_ERROR) - errno = map_errno(WSAGetLastError()); + r = listen(TO_SOCKET(s), backlog); + if (r == SOCKET_ERROR) + errno = map_errno(WSAGetLastError()); } return r; } @@ -3518,44 +3518,44 @@ finish_overlapped_socket(BOOL input, SOCKET s, WSAOVERLAPPED *wol, int result, D int err; if (result != SOCKET_ERROR) - *len = size; + *len = size; else if ((err = WSAGetLastError()) == WSA_IO_PENDING) { - switch (rb_w32_wait_events_blocking(&wol->hEvent, 1, INFINITE)) { - case WAIT_OBJECT_0: - RUBY_CRITICAL { - result = WSAGetOverlappedResult(s, wol, &size, TRUE, &flg); - } - if (result) { - result = 0; - *len = size; - break; - } - result = SOCKET_ERROR; - /* thru */ - default: - if ((err = WSAGetLastError()) == WSAECONNABORTED && !input) - errno = EPIPE; - else if (err == WSAEMSGSIZE && input) { - result = 0; - *len = size; - break; - } - else - errno = map_errno(err); - /* thru */ - case WAIT_OBJECT_0 + 1: - /* interrupted */ - *len = -1; - CancelIo((HANDLE)s); - break; - } + switch (rb_w32_wait_events_blocking(&wol->hEvent, 1, INFINITE)) { + case WAIT_OBJECT_0: + RUBY_CRITICAL { + result = WSAGetOverlappedResult(s, wol, &size, TRUE, &flg); + } + if (result) { + result = 0; + *len = size; + break; + } + result = SOCKET_ERROR; + /* thru */ + default: + if ((err = WSAGetLastError()) == WSAECONNABORTED && !input) + errno = EPIPE; + else if (err == WSAEMSGSIZE && input) { + result = 0; + *len = size; + break; + } + else + errno = map_errno(err); + /* thru */ + case WAIT_OBJECT_0 + 1: + /* interrupted */ + *len = -1; + CancelIo((HANDLE)s); + break; + } } else { - if (err == WSAECONNABORTED && !input) - errno = EPIPE; - else - errno = map_errno(err); - *len = -1; + if (err == WSAECONNABORTED && !input) + errno = EPIPE; + else + errno = map_errno(err); + *len = -1; } CloseHandle(wol->hEvent); @@ -3565,7 +3565,7 @@ finish_overlapped_socket(BOOL input, SOCKET s, WSAOVERLAPPED *wol, int result, D /* License: Artistic or GPL */ static int overlapped_socket_io(BOOL input, int fd, char *buf, int len, int flags, - struct sockaddr *addr, int *addrlen) + struct sockaddr *addr, int *addrlen) { int r; int ret; @@ -3578,57 +3578,57 @@ overlapped_socket_io(BOOL input, int fd, char *buf, int len, int flags, s = TO_SOCKET(fd); socklist_lookup(s, &mode); if (GET_FLAGS(mode) & O_NONBLOCK) { - RUBY_CRITICAL { - if (input) { - if (addr && addrlen) - r = recvfrom(s, buf, len, flags, addr, addrlen); - else - r = recv(s, buf, len, flags); - if (r == SOCKET_ERROR) - errno = map_errno(WSAGetLastError()); - } - else { - if (addr && addrlen) - r = sendto(s, buf, len, flags, addr, *addrlen); - else - r = send(s, buf, len, flags); - if (r == SOCKET_ERROR) { - DWORD err = WSAGetLastError(); - if (err == WSAECONNABORTED) - errno = EPIPE; - else - errno = map_errno(err); - } - } - } + RUBY_CRITICAL { + if (input) { + if (addr && addrlen) + r = recvfrom(s, buf, len, flags, addr, addrlen); + else + r = recv(s, buf, len, flags); + if (r == SOCKET_ERROR) + errno = map_errno(WSAGetLastError()); + } + else { + if (addr && addrlen) + r = sendto(s, buf, len, flags, addr, *addrlen); + else + r = send(s, buf, len, flags); + if (r == SOCKET_ERROR) { + DWORD err = WSAGetLastError(); + if (err == WSAECONNABORTED) + errno = EPIPE; + else + errno = map_errno(err); + } + } + } } else { - DWORD size; - DWORD rlen; - wbuf.len = len; - wbuf.buf = buf; - memset(&wol, 0, sizeof(wol)); - RUBY_CRITICAL { - wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); - if (input) { - flg = flags; - if (addr && addrlen) - ret = WSARecvFrom(s, &wbuf, 1, &size, &flg, addr, addrlen, - &wol, NULL); - else - ret = WSARecv(s, &wbuf, 1, &size, &flg, &wol, NULL); - } - else { - if (addr && addrlen) - ret = WSASendTo(s, &wbuf, 1, &size, flags, addr, *addrlen, - &wol, NULL); - else - ret = WSASend(s, &wbuf, 1, &size, flags, &wol, NULL); - } - } + DWORD size; + DWORD rlen; + wbuf.len = len; + wbuf.buf = buf; + memset(&wol, 0, sizeof(wol)); + RUBY_CRITICAL { + wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + if (input) { + flg = flags; + if (addr && addrlen) + ret = WSARecvFrom(s, &wbuf, 1, &size, &flg, addr, addrlen, + &wol, NULL); + else + ret = WSARecv(s, &wbuf, 1, &size, &flg, &wol, NULL); + } + else { + if (addr && addrlen) + ret = WSASendTo(s, &wbuf, 1, &size, flags, addr, *addrlen, + &wol, NULL); + else + ret = WSASend(s, &wbuf, 1, &size, flags, &wol, NULL); + } + } - finish_overlapped_socket(input, s, &wol, ret, &rlen, size); - r = (int)rlen; + finish_overlapped_socket(input, s, &wol, ret, &rlen, size); + r = (int)rlen; } return r; @@ -3644,7 +3644,7 @@ rb_w32_recv(int fd, char *buf, int len, int flags) /* License: Ruby's */ int WSAAPI rb_w32_recvfrom(int fd, char *buf, int len, int flags, - struct sockaddr *from, int *fromlen) + struct sockaddr *from, int *fromlen) { return overlapped_socket_io(TRUE, fd, buf, len, flags, from, fromlen); } @@ -3659,10 +3659,10 @@ rb_w32_send(int fd, const char *buf, int len, int flags) /* License: Ruby's */ int WSAAPI rb_w32_sendto(int fd, const char *buf, int len, int flags, - const struct sockaddr *to, int tolen) + const struct sockaddr *to, int tolen) { return overlapped_socket_io(FALSE, fd, (char *)buf, len, flags, - (struct sockaddr *)to, &tolen); + (struct sockaddr *)to, &tolen); } #if !defined(MSG_TRUNC) && !defined(__MINGW32__) @@ -3686,18 +3686,18 @@ typedef struct { /* License: Ruby's */ #define msghdr_to_wsamsg(msg, wsamsg) \ do { \ - int i; \ - (wsamsg)->name = (msg)->msg_name; \ - (wsamsg)->namelen = (msg)->msg_namelen; \ - (wsamsg)->lpBuffers = ALLOCA_N(WSABUF, (msg)->msg_iovlen); \ - (wsamsg)->dwBufferCount = (msg)->msg_iovlen; \ - for (i = 0; i < (msg)->msg_iovlen; ++i) { \ - (wsamsg)->lpBuffers[i].buf = (msg)->msg_iov[i].iov_base; \ - (wsamsg)->lpBuffers[i].len = (msg)->msg_iov[i].iov_len; \ - } \ - (wsamsg)->Control.buf = (msg)->msg_control; \ - (wsamsg)->Control.len = (msg)->msg_controllen; \ - (wsamsg)->dwFlags = (msg)->msg_flags; \ + int i; \ + (wsamsg)->name = (msg)->msg_name; \ + (wsamsg)->namelen = (msg)->msg_namelen; \ + (wsamsg)->lpBuffers = ALLOCA_N(WSABUF, (msg)->msg_iovlen); \ + (wsamsg)->dwBufferCount = (msg)->msg_iovlen; \ + for (i = 0; i < (msg)->msg_iovlen; ++i) { \ + (wsamsg)->lpBuffers[i].buf = (msg)->msg_iov[i].iov_base; \ + (wsamsg)->lpBuffers[i].len = (msg)->msg_iov[i].iov_len; \ + } \ + (wsamsg)->Control.buf = (msg)->msg_control; \ + (wsamsg)->Control.len = (msg)->msg_controllen; \ + (wsamsg)->dwFlags = (msg)->msg_flags; \ } while (0) /* License: Ruby's */ @@ -3715,10 +3715,10 @@ recvmsg(int fd, struct msghdr *msg, int flags) s = TO_SOCKET(fd); if (!pWSARecvMsg) { - static const GUID guid = WSAID_WSARECVMSG; - pWSARecvMsg = (WSARecvMsg_t)get_wsa_extension_function(s, guid); - if (!pWSARecvMsg) - return -1; + static const GUID guid = WSAID_WSARECVMSG; + pWSARecvMsg = (WSARecvMsg_t)get_wsa_extension_function(s, guid); + if (!pWSARecvMsg) + return -1; } msghdr_to_wsamsg(msg, &wsamsg); @@ -3726,26 +3726,26 @@ recvmsg(int fd, struct msghdr *msg, int flags) socklist_lookup(s, &mode); if (GET_FLAGS(mode) & O_NONBLOCK) { - RUBY_CRITICAL { - if ((ret = pWSARecvMsg(s, &wsamsg, &len, NULL, NULL)) == SOCKET_ERROR) { - errno = map_errno(WSAGetLastError()); - len = -1; - } - } + RUBY_CRITICAL { + if ((ret = pWSARecvMsg(s, &wsamsg, &len, NULL, NULL)) == SOCKET_ERROR) { + errno = map_errno(WSAGetLastError()); + len = -1; + } + } } else { - DWORD size; - WSAOVERLAPPED wol; - memset(&wol, 0, sizeof(wol)); - RUBY_CRITICAL { - wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); - ret = pWSARecvMsg(s, &wsamsg, &size, &wol, NULL); - } + DWORD size; + WSAOVERLAPPED wol; + memset(&wol, 0, sizeof(wol)); + RUBY_CRITICAL { + wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + ret = pWSARecvMsg(s, &wsamsg, &size, &wol, NULL); + } - ret = finish_overlapped_socket(TRUE, s, &wol, ret, &len, size); + ret = finish_overlapped_socket(TRUE, s, &wol, ret, &len, size); } if (ret == SOCKET_ERROR) - return -1; + return -1; /* WSAMSG to msghdr */ msg->msg_name = wsamsg.name; @@ -3770,33 +3770,33 @@ sendmsg(int fd, const struct msghdr *msg, int flags) s = TO_SOCKET(fd); if (!pWSASendMsg) { - static const GUID guid = WSAID_WSASENDMSG; - pWSASendMsg = (WSASendMsg_t)get_wsa_extension_function(s, guid); - if (!pWSASendMsg) - return -1; + static const GUID guid = WSAID_WSASENDMSG; + pWSASendMsg = (WSASendMsg_t)get_wsa_extension_function(s, guid); + if (!pWSASendMsg) + return -1; } msghdr_to_wsamsg(msg, &wsamsg); socklist_lookup(s, &mode); if (GET_FLAGS(mode) & O_NONBLOCK) { - RUBY_CRITICAL { - if ((ret = pWSASendMsg(s, &wsamsg, flags, &len, NULL, NULL)) == SOCKET_ERROR) { - errno = map_errno(WSAGetLastError()); - len = -1; - } - } + RUBY_CRITICAL { + if ((ret = pWSASendMsg(s, &wsamsg, flags, &len, NULL, NULL)) == SOCKET_ERROR) { + errno = map_errno(WSAGetLastError()); + len = -1; + } + } } else { - DWORD size; - WSAOVERLAPPED wol; - memset(&wol, 0, sizeof(wol)); - RUBY_CRITICAL { - wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); - ret = pWSASendMsg(s, &wsamsg, flags, &size, &wol, NULL); - } + DWORD size; + WSAOVERLAPPED wol; + memset(&wol, 0, sizeof(wol)); + RUBY_CRITICAL { + wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + ret = pWSASendMsg(s, &wsamsg, flags, &size, &wol, NULL); + } - finish_overlapped_socket(FALSE, s, &wol, ret, &len, size); + finish_overlapped_socket(FALSE, s, &wol, ret, &len, size); } return len; @@ -3810,9 +3810,9 @@ rb_w32_setsockopt(int s, int level, int optname, const char *optval, int optlen) { int r; RUBY_CRITICAL { - r = setsockopt(TO_SOCKET(s), level, optname, optval, optlen); - if (r == SOCKET_ERROR) - errno = map_errno(WSAGetLastError()); + r = setsockopt(TO_SOCKET(s), level, optname, optval, optlen); + if (r == SOCKET_ERROR) + errno = map_errno(WSAGetLastError()); } return r; } @@ -3825,9 +3825,9 @@ rb_w32_shutdown(int s, int how) { int r; RUBY_CRITICAL { - r = shutdown(TO_SOCKET(s), how); - if (r == SOCKET_ERROR) - errno = map_errno(WSAGetLastError()); + r = shutdown(TO_SOCKET(s), how); + if (r == SOCKET_ERROR) + errno = map_errno(WSAGetLastError()); } return r; } @@ -3841,42 +3841,42 @@ open_ifs_socket(int af, int type, int protocol) SOCKET out = INVALID_SOCKET; if (WSAEnumProtocols(NULL, NULL, &proto_buffers_len) == SOCKET_ERROR) { - error_code = WSAGetLastError(); - if (error_code == WSAENOBUFS) { - WSAPROTOCOL_INFO *proto_buffers; - int protocols_available = 0; + error_code = WSAGetLastError(); + if (error_code == WSAENOBUFS) { + WSAPROTOCOL_INFO *proto_buffers; + int protocols_available = 0; - proto_buffers = (WSAPROTOCOL_INFO *)malloc(proto_buffers_len); - if (!proto_buffers) { - WSASetLastError(WSA_NOT_ENOUGH_MEMORY); - return INVALID_SOCKET; - } + proto_buffers = (WSAPROTOCOL_INFO *)malloc(proto_buffers_len); + if (!proto_buffers) { + WSASetLastError(WSA_NOT_ENOUGH_MEMORY); + return INVALID_SOCKET; + } - protocols_available = - WSAEnumProtocols(NULL, proto_buffers, &proto_buffers_len); - if (protocols_available != SOCKET_ERROR) { - int i; - for (i = 0; i < protocols_available; i++) { - if ((af != AF_UNSPEC && af != proto_buffers[i].iAddressFamily) || - (type != proto_buffers[i].iSocketType) || - (protocol != 0 && protocol != proto_buffers[i].iProtocol)) - continue; + protocols_available = + WSAEnumProtocols(NULL, proto_buffers, &proto_buffers_len); + if (protocols_available != SOCKET_ERROR) { + int i; + for (i = 0; i < protocols_available; i++) { + if ((af != AF_UNSPEC && af != proto_buffers[i].iAddressFamily) || + (type != proto_buffers[i].iSocketType) || + (protocol != 0 && protocol != proto_buffers[i].iProtocol)) + continue; - if ((proto_buffers[i].dwServiceFlags1 & XP1_IFS_HANDLES) == 0) - continue; + if ((proto_buffers[i].dwServiceFlags1 & XP1_IFS_HANDLES) == 0) + continue; - out = WSASocket(af, type, protocol, &(proto_buffers[i]), 0, - WSA_FLAG_OVERLAPPED); - break; - } - if (out == INVALID_SOCKET) - out = WSASocket(af, type, protocol, NULL, 0, 0); - if (out != INVALID_SOCKET) - SetHandleInformation((HANDLE)out, HANDLE_FLAG_INHERIT, 0); - } + out = WSASocket(af, type, protocol, &(proto_buffers[i]), 0, + WSA_FLAG_OVERLAPPED); + break; + } + if (out == INVALID_SOCKET) + out = WSASocket(af, type, protocol, NULL, 0, 0); + if (out != INVALID_SOCKET) + SetHandleInformation((HANDLE)out, HANDLE_FLAG_INHERIT, 0); + } - free(proto_buffers); - } + free(proto_buffers); + } } return out; @@ -3892,18 +3892,18 @@ rb_w32_socket(int af, int type, int protocol) int fd; RUBY_CRITICAL { - s = open_ifs_socket(af, type, protocol); - if (s == INVALID_SOCKET) { - errno = map_errno(WSAGetLastError()); - fd = -1; - } - else { - fd = rb_w32_open_osfhandle(s, O_RDWR|O_BINARY|O_NOINHERIT); - if (fd != -1) - socklist_insert(s, MAKE_SOCKDATA(af, 0)); - else - closesocket(s); - } + s = open_ifs_socket(af, type, protocol); + if (s == INVALID_SOCKET) { + errno = map_errno(WSAGetLastError()); + fd = -1; + } + else { + fd = rb_w32_open_osfhandle(s, O_RDWR|O_BINARY|O_NOINHERIT); + if (fd != -1) + socklist_insert(s, MAKE_SOCKDATA(af, 0)); + else + closesocket(s); + } } return fd; } @@ -3916,9 +3916,9 @@ rb_w32_gethostbyaddr(const char *addr, int len, int type) { struct hostent *r; RUBY_CRITICAL { - r = gethostbyaddr(addr, len, type); - if (r == NULL) - errno = map_errno(WSAGetLastError()); + r = gethostbyaddr(addr, len, type); + if (r == NULL) + errno = map_errno(WSAGetLastError()); } return r; } @@ -3931,9 +3931,9 @@ rb_w32_gethostbyname(const char *name) { struct hostent *r; RUBY_CRITICAL { - r = gethostbyname(name); - if (r == NULL) - errno = map_errno(WSAGetLastError()); + r = gethostbyname(name); + if (r == NULL) + errno = map_errno(WSAGetLastError()); } return r; } @@ -3946,9 +3946,9 @@ rb_w32_gethostname(char *name, int len) { int r; RUBY_CRITICAL { - r = gethostname(name, len); - if (r == SOCKET_ERROR) - errno = map_errno(WSAGetLastError()); + r = gethostname(name, len); + if (r == SOCKET_ERROR) + errno = map_errno(WSAGetLastError()); } return r; } @@ -3961,9 +3961,9 @@ rb_w32_getprotobyname(const char *name) { struct protoent *r; RUBY_CRITICAL { - r = getprotobyname(name); - if (r == NULL) - errno = map_errno(WSAGetLastError()); + r = getprotobyname(name); + if (r == NULL) + errno = map_errno(WSAGetLastError()); } return r; } @@ -3976,9 +3976,9 @@ rb_w32_getprotobynumber(int num) { struct protoent *r; RUBY_CRITICAL { - r = getprotobynumber(num); - if (r == NULL) - errno = map_errno(WSAGetLastError()); + r = getprotobynumber(num); + if (r == NULL) + errno = map_errno(WSAGetLastError()); } return r; } @@ -3991,9 +3991,9 @@ rb_w32_getservbyname(const char *name, const char *proto) { struct servent *r; RUBY_CRITICAL { - r = getservbyname(name, proto); - if (r == NULL) - errno = map_errno(WSAGetLastError()); + r = getservbyname(name, proto); + if (r == NULL) + errno = map_errno(WSAGetLastError()); } return r; } @@ -4006,9 +4006,9 @@ rb_w32_getservbyport(int port, const char *proto) { struct servent *r; RUBY_CRITICAL { - r = getservbyport(port, proto); - if (r == NULL) - errno = map_errno(WSAGetLastError()); + r = getservbyport(port, proto); + if (r == NULL) + errno = map_errno(WSAGetLastError()); } return r; } @@ -4031,71 +4031,71 @@ socketpair_internal(int af, int type, int protocol, SOCKET *sv) #if defined PF_INET && PF_INET != AF_INET case PF_INET: #endif - sock_in4.sin_family = AF_INET; - sock_in4.sin_port = 0; - sock_in4.sin_addr.s_addr = htonl(INADDR_LOOPBACK); - addr = (struct sockaddr *)&sock_in4; - len = sizeof(sock_in4); - break; + sock_in4.sin_family = AF_INET; + sock_in4.sin_port = 0; + sock_in4.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + addr = (struct sockaddr *)&sock_in4; + len = sizeof(sock_in4); + break; #ifdef INET6 case AF_INET6: - memset(&sock_in6, 0, sizeof(sock_in6)); - sock_in6.sin6_family = AF_INET6; - sock_in6.sin6_addr = IN6ADDR_LOOPBACK_INIT; - addr = (struct sockaddr *)&sock_in6; - len = sizeof(sock_in6); - break; + memset(&sock_in6, 0, sizeof(sock_in6)); + sock_in6.sin6_family = AF_INET6; + sock_in6.sin6_addr = IN6ADDR_LOOPBACK_INIT; + addr = (struct sockaddr *)&sock_in6; + len = sizeof(sock_in6); + break; #endif default: - errno = EAFNOSUPPORT; - return -1; + errno = EAFNOSUPPORT; + return -1; } if (type != SOCK_STREAM) { - errno = EPROTOTYPE; - return -1; + errno = EPROTOTYPE; + return -1; } sv[0] = (SOCKET)INVALID_HANDLE_VALUE; sv[1] = (SOCKET)INVALID_HANDLE_VALUE; RUBY_CRITICAL { - do { - svr = open_ifs_socket(af, type, protocol); - if (svr == INVALID_SOCKET) - break; - if (bind(svr, addr, len) < 0) - break; - if (getsockname(svr, addr, &len) < 0) - break; - if (type == SOCK_STREAM) - listen(svr, 5); + do { + svr = open_ifs_socket(af, type, protocol); + if (svr == INVALID_SOCKET) + break; + if (bind(svr, addr, len) < 0) + break; + if (getsockname(svr, addr, &len) < 0) + break; + if (type == SOCK_STREAM) + listen(svr, 5); - w = open_ifs_socket(af, type, protocol); - if (w == INVALID_SOCKET) - break; - if (connect(w, addr, len) < 0) - break; + w = open_ifs_socket(af, type, protocol); + if (w == INVALID_SOCKET) + break; + if (connect(w, addr, len) < 0) + break; - r = accept(svr, addr, &len); - if (r == INVALID_SOCKET) - break; - SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0); + r = accept(svr, addr, &len); + if (r == INVALID_SOCKET) + break; + SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0); - ret = 0; - } while (0); + ret = 0; + } while (0); - if (ret < 0) { - errno = map_errno(WSAGetLastError()); - if (r != INVALID_SOCKET) - closesocket(r); - if (w != INVALID_SOCKET) - closesocket(w); - } - else { - sv[0] = r; - sv[1] = w; - } - if (svr != INVALID_SOCKET) - closesocket(svr); + if (ret < 0) { + errno = map_errno(WSAGetLastError()); + if (r != INVALID_SOCKET) + closesocket(r); + if (w != INVALID_SOCKET) + closesocket(w); + } + else { + sv[0] = r; + sv[1] = w; + } + if (svr != INVALID_SOCKET) + closesocket(svr); } return ret; @@ -4108,18 +4108,18 @@ socketpair(int af, int type, int protocol, int *sv) SOCKET pair[2]; if (socketpair_internal(af, type, protocol, pair) < 0) - return -1; + return -1; sv[0] = rb_w32_open_osfhandle(pair[0], O_RDWR|O_BINARY|O_NOINHERIT); if (sv[0] == -1) { - closesocket(pair[0]); - closesocket(pair[1]); - return -1; + closesocket(pair[0]); + closesocket(pair[1]); + return -1; } sv[1] = rb_w32_open_osfhandle(pair[1], O_RDWR|O_BINARY|O_NOINHERIT); if (sv[1] == -1) { - rb_w32_close(sv[0]); - closesocket(pair[1]); - return -1; + rb_w32_close(sv[0]); + closesocket(pair[1]); + return -1; } socklist_insert(pair[0], MAKE_SOCKDATA(af, 0)); socklist_insert(pair[1], MAKE_SOCKDATA(af, 0)); @@ -4148,20 +4148,20 @@ str2guid(const char *str, GUID *guid) guid->Data4[1] = hex2byte(str); str += 3; for (i = 0; i < 6; i++) { - guid->Data4[i + 2] = hex2byte(str); - str += 2; + guid->Data4[i + 2] = hex2byte(str); + str += 2; } } /* License: Ruby's */ #ifndef HAVE_TYPE_NET_LUID typedef struct { - uint64_t Value; - struct { - uint64_t Reserved :24; - uint64_t NetLuidIndex :24; - uint64_t IfType :16; - } Info; + uint64_t Value; + struct { + uint64_t Reserved :24; + uint64_t NetLuidIndex :24; + uint64_t IfType :16; + } Info; } NET_LUID; #endif typedef DWORD (WINAPI *cigl_t)(const GUID *, NET_LUID *); @@ -4179,76 +4179,76 @@ getifaddrs(struct ifaddrs **ifap) ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, NULL, &size); if (ret != ERROR_BUFFER_OVERFLOW) { - errno = map_errno(ret); - return -1; + errno = map_errno(ret); + return -1; } root = ruby_xmalloc(size); ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, root, &size); if (ret != ERROR_SUCCESS) { - errno = map_errno(ret); - ruby_xfree(root); - return -1; + errno = map_errno(ret); + ruby_xfree(root); + return -1; } if (pConvertInterfaceGuidToLuid == (cigl_t)-1) - pConvertInterfaceGuidToLuid = - (cigl_t)get_proc_address("iphlpapi.dll", - "ConvertInterfaceGuidToLuid", NULL); + pConvertInterfaceGuidToLuid = + (cigl_t)get_proc_address("iphlpapi.dll", + "ConvertInterfaceGuidToLuid", NULL); if (pConvertInterfaceLuidToNameA == (cilnA_t)-1) - pConvertInterfaceLuidToNameA = - (cilnA_t)get_proc_address("iphlpapi.dll", - "ConvertInterfaceLuidToNameA", NULL); + pConvertInterfaceLuidToNameA = + (cilnA_t)get_proc_address("iphlpapi.dll", + "ConvertInterfaceLuidToNameA", NULL); for (prev = NULL, addr = root; addr; addr = addr->Next) { - struct ifaddrs *ifa = ruby_xcalloc(1, sizeof(*ifa)); - char name[IFNAMSIZ]; - GUID guid; - NET_LUID luid; + struct ifaddrs *ifa = ruby_xcalloc(1, sizeof(*ifa)); + char name[IFNAMSIZ]; + GUID guid; + NET_LUID luid; - if (prev) - prev->ifa_next = ifa; - else - *ifap = ifa; + if (prev) + prev->ifa_next = ifa; + else + *ifap = ifa; - str2guid(addr->AdapterName, &guid); - if (pConvertInterfaceGuidToLuid && pConvertInterfaceLuidToNameA && - pConvertInterfaceGuidToLuid(&guid, &luid) == NO_ERROR && - pConvertInterfaceLuidToNameA(&luid, name, sizeof(name)) == NO_ERROR) { - ifa->ifa_name = ruby_strdup(name); - } - else { - ifa->ifa_name = ruby_strdup(addr->AdapterName); - } + str2guid(addr->AdapterName, &guid); + if (pConvertInterfaceGuidToLuid && pConvertInterfaceLuidToNameA && + pConvertInterfaceGuidToLuid(&guid, &luid) == NO_ERROR && + pConvertInterfaceLuidToNameA(&luid, name, sizeof(name)) == NO_ERROR) { + ifa->ifa_name = ruby_strdup(name); + } + else { + ifa->ifa_name = ruby_strdup(addr->AdapterName); + } - if (addr->IfType & IF_TYPE_SOFTWARE_LOOPBACK) - ifa->ifa_flags |= IFF_LOOPBACK; - if (addr->OperStatus == IfOperStatusUp) { - ifa->ifa_flags |= IFF_UP; + if (addr->IfType & IF_TYPE_SOFTWARE_LOOPBACK) + ifa->ifa_flags |= IFF_LOOPBACK; + if (addr->OperStatus == IfOperStatusUp) { + ifa->ifa_flags |= IFF_UP; - if (addr->FirstUnicastAddress) { - IP_ADAPTER_UNICAST_ADDRESS *cur; - int added = 0; - for (cur = addr->FirstUnicastAddress; cur; cur = cur->Next) { - if (cur->Flags & IP_ADAPTER_ADDRESS_TRANSIENT || - cur->DadState == IpDadStateDeprecated) { - continue; - } - if (added) { - prev = ifa; - ifa = ruby_xcalloc(1, sizeof(*ifa)); - prev->ifa_next = ifa; - ifa->ifa_name = ruby_strdup(prev->ifa_name); - ifa->ifa_flags = prev->ifa_flags; - } - ifa->ifa_addr = ruby_xmalloc(cur->Address.iSockaddrLength); - memcpy(ifa->ifa_addr, cur->Address.lpSockaddr, - cur->Address.iSockaddrLength); - added = 1; - } - } - } + if (addr->FirstUnicastAddress) { + IP_ADAPTER_UNICAST_ADDRESS *cur; + int added = 0; + for (cur = addr->FirstUnicastAddress; cur; cur = cur->Next) { + if (cur->Flags & IP_ADAPTER_ADDRESS_TRANSIENT || + cur->DadState == IpDadStateDeprecated) { + continue; + } + if (added) { + prev = ifa; + ifa = ruby_xcalloc(1, sizeof(*ifa)); + prev->ifa_next = ifa; + ifa->ifa_name = ruby_strdup(prev->ifa_name); + ifa->ifa_flags = prev->ifa_flags; + } + ifa->ifa_addr = ruby_xmalloc(cur->Address.iSockaddrLength); + memcpy(ifa->ifa_addr, cur->Address.lpSockaddr, + cur->Address.iSockaddrLength); + added = 1; + } + } + } - prev = ifa; + prev = ifa; } ruby_xfree(root); @@ -4260,11 +4260,11 @@ void freeifaddrs(struct ifaddrs *ifp) { while (ifp) { - struct ifaddrs *next = ifp->ifa_next; - if (ifp->ifa_addr) ruby_xfree(ifp->ifa_addr); - if (ifp->ifa_name) ruby_xfree(ifp->ifa_name); - ruby_xfree(ifp); - ifp = next; + struct ifaddrs *next = ifp->ifa_next; + if (ifp->ifa_addr) ruby_xfree(ifp->ifa_addr); + if (ifp->ifa_name) ruby_xfree(ifp->ifa_name); + ruby_xfree(ifp); + ifp = next; } } #endif @@ -4313,19 +4313,19 @@ setfl(SOCKET sock, int arg) af = GET_FAMILY(flag); flag = GET_FLAGS(flag); if (arg & O_NONBLOCK) { - flag |= O_NONBLOCK; - ioctlArg = 1; + flag |= O_NONBLOCK; + ioctlArg = 1; } else { - flag &= ~O_NONBLOCK; - ioctlArg = 0; + flag &= ~O_NONBLOCK; + ioctlArg = 0; } RUBY_CRITICAL { - ret = ioctlsocket(sock, FIONBIO, &ioctlArg); - if (ret == 0) - socklist_insert(sock, MAKE_SOCKDATA(af, flag)); - else - errno = map_errno(WSAGetLastError()); + ret = ioctlsocket(sock, FIONBIO, &ioctlArg); + if (ret == 0) + socklist_insert(sock, MAKE_SOCKDATA(af, flag)); + else + errno = map_errno(WSAGetLastError()); } return ret; @@ -4341,14 +4341,14 @@ dupfd(HANDLE hDup, int flags, int minfd) int filled = 0; do { - ret = _open_osfhandle((intptr_t)hDup, flags | FOPEN); - if (ret == -1) { - goto close_fds_and_return; - } - if (ret >= minfd) { - goto close_fds_and_return; - } - fds[filled++] = ret; + ret = _open_osfhandle((intptr_t)hDup, flags | FOPEN); + if (ret == -1) { + goto close_fds_and_return; + } + if (ret >= minfd) { + goto close_fds_and_return; + } + fds[filled++] = ret; } while (filled < (int)numberof(fds)); ret = dupfd(hDup, flags, minfd); @@ -4356,9 +4356,9 @@ dupfd(HANDLE hDup, int flags, int minfd) close_fds_and_return: save_errno = errno; while (filled > 0) { - int fd = fds[--filled]; - _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE); - close(fd); + int fd = fds[--filled]; + _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE); + close(fd); } errno = save_errno; @@ -4375,64 +4375,64 @@ fcntl(int fd, int cmd, ...) switch (cmd) { case F_SETFL: { - va_start(va, cmd); - arg = va_arg(va, int); - va_end(va); - return rb_w32_set_nonblock2(fd, arg); + va_start(va, cmd); + arg = va_arg(va, int); + va_end(va); + return rb_w32_set_nonblock2(fd, arg); } case F_DUPFD: case F_DUPFD_CLOEXEC: { - int ret; - HANDLE hDup; - flag = _osfile(fd); - if (!(DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd), - GetCurrentProcess(), &hDup, 0L, - cmd == F_DUPFD && !(flag & FNOINHERIT), - DUPLICATE_SAME_ACCESS))) { - errno = map_errno(GetLastError()); - return -1; - } + int ret; + HANDLE hDup; + flag = _osfile(fd); + if (!(DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd), + GetCurrentProcess(), &hDup, 0L, + cmd == F_DUPFD && !(flag & FNOINHERIT), + DUPLICATE_SAME_ACCESS))) { + errno = map_errno(GetLastError()); + return -1; + } - va_start(va, cmd); - arg = va_arg(va, int); - va_end(va); + va_start(va, cmd); + arg = va_arg(va, int); + va_end(va); - if (cmd != F_DUPFD) - flag |= FNOINHERIT; - else - flag &= ~FNOINHERIT; - if ((ret = dupfd(hDup, flag, arg)) == -1) - CloseHandle(hDup); - return ret; + if (cmd != F_DUPFD) + flag |= FNOINHERIT; + else + flag &= ~FNOINHERIT; + if ((ret = dupfd(hDup, flag, arg)) == -1) + CloseHandle(hDup); + return ret; } case F_GETFD: { - SIGNED_VALUE h = _get_osfhandle(fd); - if (h == -1) return -1; - if (!GetHandleInformation((HANDLE)h, &flag)) { - errno = map_errno(GetLastError()); - return -1; - } - return (flag & HANDLE_FLAG_INHERIT) ? 0 : FD_CLOEXEC; + SIGNED_VALUE h = _get_osfhandle(fd); + if (h == -1) return -1; + if (!GetHandleInformation((HANDLE)h, &flag)) { + errno = map_errno(GetLastError()); + return -1; + } + return (flag & HANDLE_FLAG_INHERIT) ? 0 : FD_CLOEXEC; } case F_SETFD: { - SIGNED_VALUE h = _get_osfhandle(fd); - if (h == -1) return -1; - va_start(va, cmd); - arg = va_arg(va, int); - va_end(va); - if (!SetHandleInformation((HANDLE)h, HANDLE_FLAG_INHERIT, - (arg & FD_CLOEXEC) ? 0 : HANDLE_FLAG_INHERIT)) { - errno = map_errno(GetLastError()); - return -1; - } - if (arg & FD_CLOEXEC) - _osfile(fd) |= FNOINHERIT; - else - _osfile(fd) &= ~FNOINHERIT; - return 0; + SIGNED_VALUE h = _get_osfhandle(fd); + if (h == -1) return -1; + va_start(va, cmd); + arg = va_arg(va, int); + va_end(va); + if (!SetHandleInformation((HANDLE)h, HANDLE_FLAG_INHERIT, + (arg & FD_CLOEXEC) ? 0 : HANDLE_FLAG_INHERIT)) { + errno = map_errno(GetLastError()); + return -1; + } + if (arg & FD_CLOEXEC) + _osfile(fd) |= FNOINHERIT; + else + _osfile(fd) &= ~FNOINHERIT; + return 0; } default: - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } } @@ -4442,29 +4442,29 @@ rb_w32_set_nonblock2(int fd, int nonblock) { SOCKET sock = TO_SOCKET(fd); if (is_socket(sock)) { - return setfl(sock, nonblock ? O_NONBLOCK : 0); + return setfl(sock, nonblock ? O_NONBLOCK : 0); } else if (is_pipe(sock)) { - DWORD state; - if (!GetNamedPipeHandleState((HANDLE)sock, &state, NULL, NULL, NULL, NULL, 0)) { - errno = map_errno(GetLastError()); - return -1; - } + DWORD state; + if (!GetNamedPipeHandleState((HANDLE)sock, &state, NULL, NULL, NULL, NULL, 0)) { + errno = map_errno(GetLastError()); + return -1; + } if (nonblock) { state |= PIPE_NOWAIT; } else { state &= ~PIPE_NOWAIT; } - if (!SetNamedPipeHandleState((HANDLE)sock, &state, NULL, NULL)) { - errno = map_errno(GetLastError()); - return -1; - } - return 0; + if (!SetNamedPipeHandleState((HANDLE)sock, &state, NULL, NULL)) { + errno = map_errno(GetLastError()); + return -1; + } + return 0; } else { - errno = EBADF; - return -1; + errno = EBADF; + return -1; } } @@ -4486,69 +4486,69 @@ poll_child_status(struct ChildRecord *child, int *stat_loc) DWORD err; if (!GetExitCodeProcess(child->hProcess, &exitcode)) { - /* If an error occurred, return immediately. */ - err = GetLastError(); - switch (err) { - case ERROR_INVALID_PARAMETER: - errno = ECHILD; - break; - case ERROR_INVALID_HANDLE: - errno = EINVAL; - break; - default: - errno = map_errno(err); - break; - } + /* If an error occurred, return immediately. */ + err = GetLastError(); + switch (err) { + case ERROR_INVALID_PARAMETER: + errno = ECHILD; + break; + case ERROR_INVALID_HANDLE: + errno = EINVAL; + break; + default: + errno = map_errno(err); + break; + } error_exit: - CloseChildHandle(child); - return -1; + CloseChildHandle(child); + return -1; } if (exitcode != STILL_ACTIVE) { rb_pid_t pid; - /* If already died, wait process's real termination. */ + /* If already died, wait process's real termination. */ if (rb_w32_wait_events_blocking(&child->hProcess, 1, INFINITE) != WAIT_OBJECT_0) { - goto error_exit; + goto error_exit; } - pid = child->pid; - CloseChildHandle(child); - if (stat_loc) { - *stat_loc = exitcode << 8; - if (exitcode & 0xC0000000) { - static const struct { - DWORD status; - int sig; - } table[] = { - {STATUS_ACCESS_VIOLATION, SIGSEGV}, - {STATUS_ILLEGAL_INSTRUCTION, SIGILL}, - {STATUS_PRIVILEGED_INSTRUCTION, SIGILL}, - {STATUS_FLOAT_DENORMAL_OPERAND, SIGFPE}, - {STATUS_FLOAT_DIVIDE_BY_ZERO, SIGFPE}, - {STATUS_FLOAT_INEXACT_RESULT, SIGFPE}, - {STATUS_FLOAT_INVALID_OPERATION, SIGFPE}, - {STATUS_FLOAT_OVERFLOW, SIGFPE}, - {STATUS_FLOAT_STACK_CHECK, SIGFPE}, - {STATUS_FLOAT_UNDERFLOW, SIGFPE}, + pid = child->pid; + CloseChildHandle(child); + if (stat_loc) { + *stat_loc = exitcode << 8; + if (exitcode & 0xC0000000) { + static const struct { + DWORD status; + int sig; + } table[] = { + {STATUS_ACCESS_VIOLATION, SIGSEGV}, + {STATUS_ILLEGAL_INSTRUCTION, SIGILL}, + {STATUS_PRIVILEGED_INSTRUCTION, SIGILL}, + {STATUS_FLOAT_DENORMAL_OPERAND, SIGFPE}, + {STATUS_FLOAT_DIVIDE_BY_ZERO, SIGFPE}, + {STATUS_FLOAT_INEXACT_RESULT, SIGFPE}, + {STATUS_FLOAT_INVALID_OPERATION, SIGFPE}, + {STATUS_FLOAT_OVERFLOW, SIGFPE}, + {STATUS_FLOAT_STACK_CHECK, SIGFPE}, + {STATUS_FLOAT_UNDERFLOW, SIGFPE}, #ifdef STATUS_FLOAT_MULTIPLE_FAULTS - {STATUS_FLOAT_MULTIPLE_FAULTS, SIGFPE}, + {STATUS_FLOAT_MULTIPLE_FAULTS, SIGFPE}, #endif #ifdef STATUS_FLOAT_MULTIPLE_TRAPS - {STATUS_FLOAT_MULTIPLE_TRAPS, SIGFPE}, + {STATUS_FLOAT_MULTIPLE_TRAPS, SIGFPE}, #endif - {STATUS_CONTROL_C_EXIT, SIGINT}, - }; - int i; - for (i = 0; i < (int)numberof(table); i++) { - if (table[i].status == exitcode) { - *stat_loc |= table[i].sig; - break; - } - } - // if unknown status, assume SEGV - if (i >= (int)numberof(table)) - *stat_loc |= SIGSEGV; - } - } - return pid; + {STATUS_CONTROL_C_EXIT, SIGINT}, + }; + int i; + for (i = 0; i < (int)numberof(table); i++) { + if (table[i].status == exitcode) { + *stat_loc |= table[i].sig; + break; + } + } + // if unknown status, assume SEGV + if (i >= (int)numberof(table)) + *stat_loc |= SIGSEGV; + } + } + return pid; } return 0; } @@ -4561,68 +4561,68 @@ waitpid(rb_pid_t pid, int *stat_loc, int options) /* Artistic or GPL part start */ if (options == WNOHANG) { - timeout = 0; + timeout = 0; } else { - timeout = INFINITE; + timeout = INFINITE; } /* Artistic or GPL part end */ if (pid == -1) { - int count = 0; - int ret; - HANDLE events[MAXCHILDNUM]; - struct ChildRecord* cause; + int count = 0; + int ret; + HANDLE events[MAXCHILDNUM]; + struct ChildRecord* cause; - FOREACH_CHILD(child) { - if (!child->pid || child->pid < 0) continue; - if ((pid = poll_child_status(child, stat_loc))) return pid; - events[count++] = child->hProcess; - } END_FOREACH_CHILD; - if (!count) { - errno = ECHILD; - return -1; - } + FOREACH_CHILD(child) { + if (!child->pid || child->pid < 0) continue; + if ((pid = poll_child_status(child, stat_loc))) return pid; + events[count++] = child->hProcess; + } END_FOREACH_CHILD; + if (!count) { + errno = ECHILD; + return -1; + } - ret = rb_w32_wait_events_blocking(events, count, timeout); - if (ret == WAIT_TIMEOUT) return 0; - if ((ret -= WAIT_OBJECT_0) == count) { - return -1; - } - if (ret > count) { - errno = map_errno(GetLastError()); - return -1; - } + ret = rb_w32_wait_events_blocking(events, count, timeout); + if (ret == WAIT_TIMEOUT) return 0; + if ((ret -= WAIT_OBJECT_0) == count) { + return -1; + } + if (ret > count) { + errno = map_errno(GetLastError()); + return -1; + } - cause = FindChildSlotByHandle(events[ret]); - if (!cause) { - errno = ECHILD; - return -1; - } - return poll_child_status(cause, stat_loc); + cause = FindChildSlotByHandle(events[ret]); + if (!cause) { + errno = ECHILD; + return -1; + } + return poll_child_status(cause, stat_loc); } else { - struct ChildRecord* child = FindChildSlot(pid); - int retried = 0; - if (!child) { - errno = ECHILD; - return -1; - } + struct ChildRecord* child = FindChildSlot(pid); + int retried = 0; + if (!child) { + errno = ECHILD; + return -1; + } - while (!(pid = poll_child_status(child, stat_loc))) { - /* wait... */ - int ret = rb_w32_wait_events_blocking(&child->hProcess, 1, timeout); - if (ret == WAIT_OBJECT_0 + 1) return -1; /* maybe EINTR */ - if (ret != WAIT_OBJECT_0) { - /* still active */ - if (options & WNOHANG) { - pid = 0; - break; - } - ++retried; - } - } - if (pid == -1 && retried) pid = 0; + while (!(pid = poll_child_status(child, stat_loc))) { + /* wait... */ + int ret = rb_w32_wait_events_blocking(&child->hProcess, 1, timeout); + if (ret == WAIT_OBJECT_0 + 1) return -1; /* maybe EINTR */ + if (ret != WAIT_OBJECT_0) { + /* still active */ + if (options & WNOHANG) { + pid = 0; + break; + } + ++retried; + } + } + if (pid == -1 && retried) pid = 0; } return pid; @@ -4639,14 +4639,14 @@ get_systemtime(FILETIME *ft) static get_time_func func = (get_time_func)-1; if (func == (get_time_func)-1) { - /* GetSystemTimePreciseAsFileTime is available since Windows 8 and Windows Server 2012. */ - func = (get_time_func)get_proc_address("kernel32", "GetSystemTimePreciseAsFileTime", NULL); - if (func == NULL) { - func = GetSystemTimeAsFileTime; - have_precisetime = 0; - } - else - have_precisetime = 1; + /* GetSystemTimePreciseAsFileTime is available since Windows 8 and Windows Server 2012. */ + func = (get_time_func)get_proc_address("kernel32", "GetSystemTimePreciseAsFileTime", NULL); + if (func == NULL) { + func = GetSystemTimeAsFileTime; + have_precisetime = 0; + } + else + have_precisetime = 1; } if (!ft) return; func(ft); @@ -4695,37 +4695,37 @@ clock_gettime(clockid_t clock_id, struct timespec *sp) { switch (clock_id) { case CLOCK_REALTIME: - { - FILETIME ft; - long subsec; + { + FILETIME ft; + long subsec; - get_systemtime(&ft); - sp->tv_sec = filetime_split(&ft, &subsec); - sp->tv_nsec = subsec * 100; - return 0; - } + get_systemtime(&ft); + sp->tv_sec = filetime_split(&ft, &subsec); + sp->tv_nsec = subsec * 100; + return 0; + } case CLOCK_MONOTONIC: - { - LARGE_INTEGER freq; - LARGE_INTEGER count; - if (!QueryPerformanceFrequency(&freq)) { - errno = map_errno(GetLastError()); - return -1; - } - if (!QueryPerformanceCounter(&count)) { - errno = map_errno(GetLastError()); - return -1; - } - sp->tv_sec = count.QuadPart / freq.QuadPart; - if (freq.QuadPart < 1000000000) - sp->tv_nsec = (count.QuadPart % freq.QuadPart) * 1000000000 / freq.QuadPart; - else - sp->tv_nsec = (long)((count.QuadPart % freq.QuadPart) * (1000000000.0 / freq.QuadPart)); - return 0; - } + { + LARGE_INTEGER freq; + LARGE_INTEGER count; + if (!QueryPerformanceFrequency(&freq)) { + errno = map_errno(GetLastError()); + return -1; + } + if (!QueryPerformanceCounter(&count)) { + errno = map_errno(GetLastError()); + return -1; + } + sp->tv_sec = count.QuadPart / freq.QuadPart; + if (freq.QuadPart < 1000000000) + sp->tv_nsec = (count.QuadPart % freq.QuadPart) * 1000000000 / freq.QuadPart; + else + sp->tv_nsec = (long)((count.QuadPart % freq.QuadPart) * (1000000000.0 / freq.QuadPart)); + return 0; + } default: - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } } @@ -4735,25 +4735,25 @@ clock_getres(clockid_t clock_id, struct timespec *sp) { switch (clock_id) { case CLOCK_REALTIME: - { - sp->tv_sec = 0; - sp->tv_nsec = 1000; - return 0; - } + { + sp->tv_sec = 0; + sp->tv_nsec = 1000; + return 0; + } case CLOCK_MONOTONIC: - { - LARGE_INTEGER freq; - if (!QueryPerformanceFrequency(&freq)) { - errno = map_errno(GetLastError()); - return -1; - } - sp->tv_sec = 0; - sp->tv_nsec = (long)(1000000000.0 / freq.QuadPart); - return 0; - } + { + LARGE_INTEGER freq; + if (!QueryPerformanceFrequency(&freq)) { + errno = map_errno(GetLastError()); + return -1; + } + sp->tv_sec = 0; + sp->tv_nsec = (long)(1000000000.0 / freq.QuadPart); + return 0; + } default: - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } } @@ -4766,35 +4766,35 @@ w32_getcwd(char *buffer, int size, UINT cp, void *alloc(int, void *), void *arg) len = GetCurrentDirectoryW(0, NULL); if (!len) { - errno = map_errno(GetLastError()); - return NULL; + errno = map_errno(GetLastError()); + return NULL; } if (buffer && size < len) { - errno = ERANGE; - return NULL; + errno = ERANGE; + return NULL; } p = ALLOCA_N(WCHAR, len); if (!GetCurrentDirectoryW(len, p)) { - errno = map_errno(GetLastError()); + errno = map_errno(GetLastError()); return NULL; } wlen = translate_wchar(p, L'\\', L'/') - p + 1; len = WideCharToMultiByte(cp, 0, p, wlen, NULL, 0, NULL, NULL); if (buffer) { - if (size < len) { - errno = ERANGE; - return NULL; - } + if (size < len) { + errno = ERANGE; + return NULL; + } } else { - buffer = (*alloc)(len, arg); - if (!buffer) { - errno = ENOMEM; - return NULL; - } + buffer = (*alloc)(len, arg); + if (!buffer) { + errno = ENOMEM; + return NULL; + } } WideCharToMultiByte(cp, 0, p, wlen, buffer, len, NULL, NULL); @@ -4873,103 +4873,103 @@ kill(rb_pid_t pid, int sig) DWORD err; if (pid < 0 || (pid == 0 && sig != SIGINT)) { - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } if ((unsigned int)pid == GetCurrentProcessId() && - (sig != 0 && sig != SIGKILL)) { - if ((ret = raise(sig)) != 0) { - /* MSVCRT doesn't set errno... */ - errno = EINVAL; - } - return ret; + (sig != 0 && sig != SIGKILL)) { + if ((ret = raise(sig)) != 0) { + /* MSVCRT doesn't set errno... */ + errno = EINVAL; + } + return ret; } switch (sig) { case 0: - RUBY_CRITICAL { - HANDLE hProc = - OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid); - if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) { - if (GetLastError() == ERROR_INVALID_PARAMETER) { - errno = ESRCH; - } - else { - errno = EPERM; - } - ret = -1; - } - else { - CloseHandle(hProc); - } - } - break; + RUBY_CRITICAL { + HANDLE hProc = + OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid); + if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) { + if (GetLastError() == ERROR_INVALID_PARAMETER) { + errno = ESRCH; + } + else { + errno = EPERM; + } + ret = -1; + } + else { + CloseHandle(hProc); + } + } + break; case SIGINT: - RUBY_CRITICAL { - DWORD ctrlEvent = CTRL_C_EVENT; - if (pid != 0) { - /* CTRL+C signal cannot be generated for process groups. - * Instead, we use CTRL+BREAK signal. */ - ctrlEvent = CTRL_BREAK_EVENT; - } - if (!GenerateConsoleCtrlEvent(ctrlEvent, (DWORD)pid)) { - if ((err = GetLastError()) == 0) - errno = EPERM; - else - errno = map_errno(GetLastError()); - ret = -1; - } - } - break; + RUBY_CRITICAL { + DWORD ctrlEvent = CTRL_C_EVENT; + if (pid != 0) { + /* CTRL+C signal cannot be generated for process groups. + * Instead, we use CTRL+BREAK signal. */ + ctrlEvent = CTRL_BREAK_EVENT; + } + if (!GenerateConsoleCtrlEvent(ctrlEvent, (DWORD)pid)) { + if ((err = GetLastError()) == 0) + errno = EPERM; + else + errno = map_errno(GetLastError()); + ret = -1; + } + } + break; case SIGKILL: - RUBY_CRITICAL { - HANDLE hProc; - struct ChildRecord* child = FindChildSlot(pid); - if (child) { - hProc = child->hProcess; - } - else { - hProc = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid); - } - if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) { - if (GetLastError() == ERROR_INVALID_PARAMETER) { - errno = ESRCH; - } - else { - errno = EPERM; - } - ret = -1; - } - else { - DWORD status; - if (!GetExitCodeProcess(hProc, &status)) { - errno = map_errno(GetLastError()); - ret = -1; - } - else if (status == STILL_ACTIVE) { - if (!TerminateProcess(hProc, 0)) { - errno = EPERM; - ret = -1; - } - } - else { - errno = ESRCH; - ret = -1; - } - if (!child) { - CloseHandle(hProc); - } - } - } - break; + RUBY_CRITICAL { + HANDLE hProc; + struct ChildRecord* child = FindChildSlot(pid); + if (child) { + hProc = child->hProcess; + } + else { + hProc = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid); + } + if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) { + if (GetLastError() == ERROR_INVALID_PARAMETER) { + errno = ESRCH; + } + else { + errno = EPERM; + } + ret = -1; + } + else { + DWORD status; + if (!GetExitCodeProcess(hProc, &status)) { + errno = map_errno(GetLastError()); + ret = -1; + } + else if (status == STILL_ACTIVE) { + if (!TerminateProcess(hProc, 0)) { + errno = EPERM; + ret = -1; + } + } + else { + errno = ESRCH; + ret = -1; + } + if (!child) { + CloseHandle(hProc); + } + } + } + break; default: - errno = EINVAL; - ret = -1; - break; + errno = EINVAL; + ret = -1; + break; } return ret; @@ -4980,8 +4980,8 @@ static int wlink(const WCHAR *from, const WCHAR *to) { if (!CreateHardLinkW(to, from, NULL)) { - errno = map_errno(GetLastError()); - return -1; + errno = map_errno(GetLastError()); + return -1; } return 0; @@ -4996,10 +4996,10 @@ rb_w32_ulink(const char *from, const char *to) int ret; if (!(wfrom = utf8_to_wstr(from, NULL))) - return -1; + return -1; if (!(wto = utf8_to_wstr(to, NULL))) { - free(wfrom); - return -1; + free(wfrom); + return -1; } ret = wlink(wfrom, wto); free(wto); @@ -5016,10 +5016,10 @@ link(const char *from, const char *to) int ret; if (!(wfrom = filecp_to_wstr(from, NULL))) - return -1; + return -1; if (!(wto = filecp_to_wstr(to, NULL))) { - free(wfrom); - return -1; + free(wfrom); + return -1; } ret = wlink(wfrom, wto); free(wto); @@ -5048,16 +5048,16 @@ reparse_symlink(const WCHAR *path, rb_w32_reparse_buffer_t *rp, size_t size) f = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT); if (f == INVALID_HANDLE_VALUE) { - return GetLastError(); + return GetLastError(); } if (!DeviceIoControl(f, FSCTL_GET_REPARSE_POINT, NULL, 0, - rp, size, &ret, NULL)) { - e = GetLastError(); + rp, size, &ret, NULL)) { + e = GetLastError(); } else if (rp->ReparseTag != IO_REPARSE_TAG_SYMLINK && - rp->ReparseTag != IO_REPARSE_TAG_MOUNT_POINT) { - e = ERROR_INVALID_PARAMETER; + rp->ReparseTag != IO_REPARSE_TAG_MOUNT_POINT) { + e = ERROR_INVALID_PARAMETER; } CloseHandle(f); return e; @@ -5075,15 +5075,15 @@ rb_w32_reparse_symlink_p(const WCHAR *path) e = rb_w32_read_reparse_point(path, rp, sizeof(rbuf), &wbuf, &len); if (e == ERROR_MORE_DATA) { - size_t size = rb_w32_reparse_buffer_size(len + 1); - rp = ALLOCV(wtmp, size); - e = rb_w32_read_reparse_point(path, rp, size, &wbuf, &len); - ALLOCV_END(wtmp); + size_t size = rb_w32_reparse_buffer_size(len + 1); + rp = ALLOCV(wtmp, size); + e = rb_w32_read_reparse_point(path, rp, size, &wbuf, &len); + ALLOCV_END(wtmp); } switch (e) { case 0: case ERROR_MORE_DATA: - return TRUE; + return TRUE; } return FALSE; } @@ -5091,47 +5091,47 @@ rb_w32_reparse_symlink_p(const WCHAR *path) /* License: Ruby's */ int rb_w32_read_reparse_point(const WCHAR *path, rb_w32_reparse_buffer_t *rp, - size_t bufsize, WCHAR **result, DWORD *len) + size_t bufsize, WCHAR **result, DWORD *len) { int e = reparse_symlink(path, rp, bufsize); DWORD ret = 0; if (!e || e == ERROR_MORE_DATA) { - void *name; - if (rp->ReparseTag == IO_REPARSE_TAG_SYMLINK) { - name = ((char *)rp->SymbolicLinkReparseBuffer.PathBuffer + - rp->SymbolicLinkReparseBuffer.PrintNameOffset); - ret = rp->SymbolicLinkReparseBuffer.PrintNameLength; - *len = ret / sizeof(WCHAR); - } - else if (rp->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT) { - static const WCHAR volume[] = L"Volume{"; - enum {volume_prefix_len = rb_strlen_lit("\\??\\")}; - name = ((char *)rp->MountPointReparseBuffer.PathBuffer + - rp->MountPointReparseBuffer.SubstituteNameOffset + - volume_prefix_len * sizeof(WCHAR)); - ret = rp->MountPointReparseBuffer.SubstituteNameLength; - *len = ret / sizeof(WCHAR); - ret -= volume_prefix_len * sizeof(WCHAR); - if (ret > sizeof(volume) - 1 * sizeof(WCHAR) && - memcmp(name, volume, sizeof(volume) - 1 * sizeof(WCHAR)) == 0) - return -1; - } - else { - return -1; - } - *result = name; - if (e) { - if ((char *)name + ret + sizeof(WCHAR) > (char *)rp + bufsize) - return e; - /* SubstituteName is not used */ - } - ((WCHAR *)name)[ret/sizeof(WCHAR)] = L'\0'; - translate_wchar(name, L'\\', L'/'); - return 0; + void *name; + if (rp->ReparseTag == IO_REPARSE_TAG_SYMLINK) { + name = ((char *)rp->SymbolicLinkReparseBuffer.PathBuffer + + rp->SymbolicLinkReparseBuffer.PrintNameOffset); + ret = rp->SymbolicLinkReparseBuffer.PrintNameLength; + *len = ret / sizeof(WCHAR); + } + else if (rp->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT) { + static const WCHAR volume[] = L"Volume{"; + enum {volume_prefix_len = rb_strlen_lit("\\??\\")}; + name = ((char *)rp->MountPointReparseBuffer.PathBuffer + + rp->MountPointReparseBuffer.SubstituteNameOffset + + volume_prefix_len * sizeof(WCHAR)); + ret = rp->MountPointReparseBuffer.SubstituteNameLength; + *len = ret / sizeof(WCHAR); + ret -= volume_prefix_len * sizeof(WCHAR); + if (ret > sizeof(volume) - 1 * sizeof(WCHAR) && + memcmp(name, volume, sizeof(volume) - 1 * sizeof(WCHAR)) == 0) + return -1; + } + else { + return -1; + } + *result = name; + if (e) { + if ((char *)name + ret + sizeof(WCHAR) > (char *)rp + bufsize) + return e; + /* SubstituteName is not used */ + } + ((WCHAR *)name)[ret/sizeof(WCHAR)] = L'\0'; + translate_wchar(name, L'\\', L'/'); + return 0; } else { - return e; + return e; } } @@ -5150,20 +5150,20 @@ w32_readlink(UINT cp, const char *path, char *buf, size_t bufsize) MultiByteToWideChar(cp, 0, path, -1, wpath, len); e = rb_w32_read_reparse_point(wpath, rp, size, &wname, &len); if (e && e != ERROR_MORE_DATA) { - ALLOCV_END(wtmp); - errno = map_errno(e); - return -1; + ALLOCV_END(wtmp); + errno = map_errno(e); + return -1; } len = lstrlenW(wname) + 1; ret = WideCharToMultiByte(cp, 0, wname, len, buf, bufsize, NULL, NULL); ALLOCV_END(wtmp); if (e) { - ret = bufsize; + ret = bufsize; } else if (!ret) { - e = GetLastError(); - errno = map_errno(e); - ret = -1; + e = GetLastError(); + errno = map_errno(e); + ret = -1; } return ret; } @@ -5202,17 +5202,17 @@ w32_symlink(UINT cp, const char *src, const char *link) typedef BOOLEAN (WINAPI *create_symbolic_link_func)(WCHAR*, WCHAR*, DWORD); static create_symbolic_link_func create_symbolic_link = - (create_symbolic_link_func)-1; + (create_symbolic_link_func)-1; static DWORD create_flag = SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE; if (create_symbolic_link == (create_symbolic_link_func)-1) { - /* Since Windows Vista and Windows Server 2008 */ - create_symbolic_link = (create_symbolic_link_func) - get_proc_address("kernel32", "CreateSymbolicLinkW", NULL); + /* Since Windows Vista and Windows Server 2008 */ + create_symbolic_link = (create_symbolic_link_func) + get_proc_address("kernel32", "CreateSymbolicLinkW", NULL); } if (!create_symbolic_link) { - errno = ENOSYS; - return -1; + errno = ENOSYS; + return -1; } if (!*link) { @@ -5233,7 +5233,7 @@ w32_symlink(UINT cp, const char *src, const char *link) atts = GetFileAttributesW(wsrc); if (atts != -1 && atts & FILE_ATTRIBUTE_DIRECTORY) - flag = SYMBOLIC_LINK_FLAG_DIRECTORY; + flag = SYMBOLIC_LINK_FLAG_DIRECTORY; ret = create_symbolic_link(wlink, wsrc, flag |= create_flag); if (!ret && (e = GetLastError()) == ERROR_INVALID_PARAMETER && @@ -5246,8 +5246,8 @@ w32_symlink(UINT cp, const char *src, const char *link) ALLOCV_END(buf); if (!ret) { - errno = map_errno(e); - return -1; + errno = map_errno(e); + return -1; } return 0; } @@ -5285,34 +5285,34 @@ w32_getenv(const char *name, UINT cp) if (len == 0) return NULL; if (!NTLoginName) { - /* initialized in init_env, uenvarea_mutex should have been - * initialized before it */ - return getenv(name); + /* initialized in init_env, uenvarea_mutex should have been + * initialized before it */ + return getenv(name); } thread_exclusive(uenvarea) { - if (uenvarea) { - free(uenvarea); - uenvarea = NULL; - } - wenvarea = GetEnvironmentStringsW(); - if (!wenvarea) { - map_errno(GetLastError()); - continue; - } - for (wenv = wenvarea, wlen = 1; *wenv; wenv += lstrlenW(wenv) + 1) - wlen += lstrlenW(wenv) + 1; - uenvarea = wstr_to_mbstr(cp, wenvarea, wlen, NULL); - FreeEnvironmentStringsW(wenvarea); - if (!uenvarea) - continue; + if (uenvarea) { + free(uenvarea); + uenvarea = NULL; + } + wenvarea = GetEnvironmentStringsW(); + if (!wenvarea) { + map_errno(GetLastError()); + continue; + } + for (wenv = wenvarea, wlen = 1; *wenv; wenv += lstrlenW(wenv) + 1) + wlen += lstrlenW(wenv) + 1; + uenvarea = wstr_to_mbstr(cp, wenvarea, wlen, NULL); + FreeEnvironmentStringsW(wenvarea); + if (!uenvarea) + continue; - for (env = uenvarea; *env; env += strlen(env) + 1) { - if (strncasecmp(env, name, len) == 0 && *(env + len) == '=') { - found = env + len + 1; - break; - } - } + for (env = uenvarea; *env; env += strlen(env) + 1) { + if (strncasecmp(env, name, len) == 0 && *(env + len) == '=') { + found = env + len + 1; + break; + } + } } return found; @@ -5341,17 +5341,17 @@ get_attr_vsn(const WCHAR *path, DWORD *atts, DWORD *vsn) HANDLE h = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT); if (h == INVALID_HANDLE_VALUE) { - e = GetLastError(); - ASSUME(e); - return e; + e = GetLastError(); + ASSUME(e); + return e; } if (!GetFileInformationByHandle(h, &st)) { - e = GetLastError(); - ASSUME(e); + e = GetLastError(); + ASSUME(e); } else { - *atts = st.dwFileAttributes; - *vsn = st.dwVolumeSerialNumber; + *atts = st.dwFileAttributes; + *vsn = st.dwVolumeSerialNumber; } CloseHandle(h); return e; @@ -5367,39 +5367,39 @@ wrename(const WCHAR *oldpath, const WCHAR *newpath) e = get_attr_vsn(oldpath, &oldatts, &oldvsn); if (e) { - errno = map_errno(e); - return -1; + errno = map_errno(e); + return -1; } if (oldatts & FILE_ATTRIBUTE_REPARSE_POINT) { - HANDLE fh = open_special(oldpath, 0, 0); - if (fh == INVALID_HANDLE_VALUE) { - e = GetLastError(); - if (e == ERROR_CANT_RESOLVE_FILENAME) { - errno = ELOOP; - return -1; - } - } - CloseHandle(fh); + HANDLE fh = open_special(oldpath, 0, 0); + if (fh == INVALID_HANDLE_VALUE) { + e = GetLastError(); + if (e == ERROR_CANT_RESOLVE_FILENAME) { + errno = ELOOP; + return -1; + } + } + CloseHandle(fh); } get_attr_vsn(newpath, &newatts, &newvsn); RUBY_CRITICAL { - if (newatts != (DWORD)-1 && newatts & FILE_ATTRIBUTE_READONLY) - SetFileAttributesW(newpath, newatts & ~ FILE_ATTRIBUTE_READONLY); + if (newatts != (DWORD)-1 && newatts & FILE_ATTRIBUTE_READONLY) + SetFileAttributesW(newpath, newatts & ~ FILE_ATTRIBUTE_READONLY); - if (!MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED)) - res = -1; + if (!MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED)) + res = -1; - if (res) { - DWORD e = GetLastError(); - if ((e == ERROR_ACCESS_DENIED) && (oldatts & FILE_ATTRIBUTE_DIRECTORY) && - oldvsn != newvsn) - errno = EXDEV; - else - errno = map_errno(e); - } - else - SetFileAttributesW(newpath, oldatts); + if (res) { + DWORD e = GetLastError(); + if ((e == ERROR_ACCESS_DENIED) && (oldatts & FILE_ATTRIBUTE_DIRECTORY) && + oldvsn != newvsn) + errno = EXDEV; + else + errno = map_errno(e); + } + else + SetFileAttributesW(newpath, oldatts); } return res; @@ -5413,10 +5413,10 @@ int rb_w32_urename(const char *from, const char *to) int ret = -1; if (!(wfrom = utf8_to_wstr(from, NULL))) - return -1; + return -1; if (!(wto = utf8_to_wstr(to, NULL))) { - free(wfrom); - return -1; + free(wfrom); + return -1; } ret = wrename(wfrom, wto); free(wto); @@ -5432,10 +5432,10 @@ int rb_w32_rename(const char *from, const char *to) int ret = -1; if (!(wfrom = filecp_to_wstr(from, NULL))) - return -1; + return -1; if (!(wto = filecp_to_wstr(to, NULL))) { - free(wfrom); - return -1; + free(wfrom); + return -1; } ret = wrename(wfrom, wto); free(wto); @@ -5448,38 +5448,38 @@ static int isUNCRoot(const WCHAR *path) { if (path[0] == L'\\' && path[1] == L'\\') { - const WCHAR *p = path + 2; - if (p[0] == L'?' && p[1] == L'\\') { - p += 2; - } - for (; *p; p++) { - if (*p == L'\\') - break; - } - if (p[0] && p[1]) { - for (p++; *p; p++) { - if (*p == L'\\') - break; - } - if (!p[0] || !p[1] || (p[1] == L'.' && !p[2])) - return 1; - } + const WCHAR *p = path + 2; + if (p[0] == L'?' && p[1] == L'\\') { + p += 2; + } + for (; *p; p++) { + if (*p == L'\\') + break; + } + if (p[0] && p[1]) { + for (p++; *p; p++) { + if (*p == L'\\') + break; + } + if (!p[0] || !p[1] || (p[1] == L'.' && !p[2])) + return 1; + } } return 0; } #define COPY_STAT(src, dest, size_cast) do { \ - (dest).st_dev = (src).st_dev; \ - (dest).st_ino = (src).st_ino; \ - (dest).st_mode = (src).st_mode; \ - (dest).st_nlink = (src).st_nlink; \ - (dest).st_uid = (src).st_uid; \ - (dest).st_gid = (src).st_gid; \ - (dest).st_rdev = (src).st_rdev; \ - (dest).st_size = size_cast(src).st_size; \ - (dest).st_atime = (src).st_atime; \ - (dest).st_mtime = (src).st_mtime; \ - (dest).st_ctime = (src).st_ctime; \ + (dest).st_dev = (src).st_dev; \ + (dest).st_ino = (src).st_ino; \ + (dest).st_mode = (src).st_mode; \ + (dest).st_nlink = (src).st_nlink; \ + (dest).st_uid = (src).st_uid; \ + (dest).st_gid = (src).st_gid; \ + (dest).st_rdev = (src).st_rdev; \ + (dest).st_size = size_cast(src).st_size; \ + (dest).st_atime = (src).st_atime; \ + (dest).st_mtime = (src).st_mtime; \ + (dest).st_ctime = (src).st_ctime; \ } while (0) static time_t filetime_to_unixtime(const FILETIME *ft); @@ -5498,9 +5498,9 @@ rb_w32_fstat(int fd, struct stat *st) if (ret) return ret; if (GetEnvironmentVariableW(L"TZ", NULL, 0) == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND) return ret; if (GetFileInformationByHandle((HANDLE)_get_osfhandle(fd), &info)) { - st->st_atime = filetime_to_unixtime(&info.ftLastAccessTime); - st->st_mtime = filetime_to_unixtime(&info.ftLastWriteTime); - st->st_ctime = filetime_to_unixtime(&info.ftCreationTime); + st->st_atime = filetime_to_unixtime(&info.ftLastAccessTime); + st->st_mtime = filetime_to_unixtime(&info.ftLastWriteTime); + st->st_ctime = filetime_to_unixtime(&info.ftCreationTime); } return ret; } @@ -5540,14 +5540,14 @@ get_ino(HANDLE h, FILE_ID_INFO *id) static gfibhe_t pGetFileInformationByHandleEx = (gfibhe_t)-1; if (pGetFileInformationByHandleEx == (gfibhe_t)-1) - /* Since Windows Vista and Windows Server 2008 */ - pGetFileInformationByHandleEx = (gfibhe_t)get_proc_address("kernel32", "GetFileInformationByHandleEx", NULL); + /* Since Windows Vista and Windows Server 2008 */ + pGetFileInformationByHandleEx = (gfibhe_t)get_proc_address("kernel32", "GetFileInformationByHandleEx", NULL); if (pGetFileInformationByHandleEx) { - if (pGetFileInformationByHandleEx(h, FileIdInfo, id, sizeof(*id))) - return 0; - else - return GetLastError(); + if (pGetFileInformationByHandleEx(h, FileIdInfo, id, sizeof(*id))) + return 0; + else + return GetLastError(); } return ERROR_INVALID_PARAMETER; } @@ -5560,24 +5560,24 @@ stati128_handle(HANDLE h, struct stati128 *st) DWORD attr = (DWORD)-1; if (GetFileInformationByHandle(h, &info)) { - FILE_ID_INFO fii; - st->st_size = ((__int64)info.nFileSizeHigh << 32) | info.nFileSizeLow; - st->st_atime = filetime_to_unixtime(&info.ftLastAccessTime); - st->st_atimensec = filetime_to_nsec(&info.ftLastAccessTime); - st->st_mtime = filetime_to_unixtime(&info.ftLastWriteTime); - st->st_mtimensec = filetime_to_nsec(&info.ftLastWriteTime); - st->st_ctime = filetime_to_unixtime(&info.ftCreationTime); - st->st_ctimensec = filetime_to_nsec(&info.ftCreationTime); - st->st_nlink = info.nNumberOfLinks; - attr = info.dwFileAttributes; - if (!get_ino(h, &fii)) { - st->st_ino = *((unsigned __int64 *)&fii.FileId); - st->st_inohigh = *((__int64 *)&fii.FileId + 1); - } - else { - st->st_ino = ((__int64)info.nFileIndexHigh << 32) | info.nFileIndexLow; - st->st_inohigh = 0; - } + FILE_ID_INFO fii; + st->st_size = ((__int64)info.nFileSizeHigh << 32) | info.nFileSizeLow; + st->st_atime = filetime_to_unixtime(&info.ftLastAccessTime); + st->st_atimensec = filetime_to_nsec(&info.ftLastAccessTime); + st->st_mtime = filetime_to_unixtime(&info.ftLastWriteTime); + st->st_mtimensec = filetime_to_nsec(&info.ftLastWriteTime); + st->st_ctime = filetime_to_unixtime(&info.ftCreationTime); + st->st_ctimensec = filetime_to_nsec(&info.ftCreationTime); + st->st_nlink = info.nNumberOfLinks; + attr = info.dwFileAttributes; + if (!get_ino(h, &fii)) { + st->st_ino = *((unsigned __int64 *)&fii.FileId); + st->st_inohigh = *((__int64 *)&fii.FileId + 1); + } + else { + st->st_ino = ((__int64)info.nFileIndexHigh << 32) | info.nFileIndexLow; + st->st_inohigh = 0; + } } return attr; } @@ -5598,12 +5598,12 @@ static long filetime_to_nsec(const FILETIME *ft) { if (have_precisetime <= 0) - return 0; + return 0; else { - ULARGE_INTEGER tmp; - tmp.LowPart = ft->dwLowDateTime; - tmp.HighPart = ft->dwHighDateTime; - return (long)(tmp.QuadPart % 10000000) * 100; + ULARGE_INTEGER tmp; + tmp.LowPart = ft->dwLowDateTime; + tmp.HighPart = ft->dwHighDateTime; + return (long)(tmp.QuadPart % 10000000) * 100; } } @@ -5612,43 +5612,43 @@ static unsigned fileattr_to_unixmode(DWORD attr, const WCHAR *path, unsigned mode) { if (attr & FILE_ATTRIBUTE_READONLY) { - mode |= S_IREAD; + mode |= S_IREAD; } else { - mode |= S_IREAD | S_IWRITE | S_IWUSR; + mode |= S_IREAD | S_IWRITE | S_IWUSR; } if (mode & S_IFMT) { - /* format is already set */ + /* format is already set */ } else if (attr & FILE_ATTRIBUTE_REPARSE_POINT) { - if (rb_w32_reparse_symlink_p(path)) - mode |= S_IFLNK | S_IEXEC; - else - mode |= S_IFDIR | S_IEXEC; + if (rb_w32_reparse_symlink_p(path)) + mode |= S_IFLNK | S_IEXEC; + else + mode |= S_IFDIR | S_IEXEC; } else if (attr & FILE_ATTRIBUTE_DIRECTORY) { - mode |= S_IFDIR | S_IEXEC; + mode |= S_IFDIR | S_IEXEC; } else { - mode |= S_IFREG; + mode |= S_IFREG; } if (path && (mode & S_IFREG)) { - const WCHAR *end = path + lstrlenW(path); - while (path < end) { - end = CharPrevW(path, end); - if (*end == L'.') { - if ((_wcsicmp(end, L".bat") == 0) || - (_wcsicmp(end, L".cmd") == 0) || - (_wcsicmp(end, L".com") == 0) || - (_wcsicmp(end, L".exe") == 0)) { - mode |= S_IEXEC; - } - break; - } - if (!iswalnum(*end)) break; - } + const WCHAR *end = path + lstrlenW(path); + while (path < end) { + end = CharPrevW(path, end); + if (*end == L'.') { + if ((_wcsicmp(end, L".bat") == 0) || + (_wcsicmp(end, L".cmd") == 0) || + (_wcsicmp(end, L".com") == 0) || + (_wcsicmp(end, L".exe") == 0)) { + mode |= S_IEXEC; + } + break; + } + if (!iswalnum(*end)) break; + } } mode |= (mode & 0500) >> 3; @@ -5670,26 +5670,26 @@ check_valid_dir(const WCHAR *path) /* GetFileAttributes() determines "..." as directory. */ /* We recheck it by FindFirstFile(). */ if (!(p = wcsstr(path, L"..."))) - return 0; + return 0; q = p + wcsspn(p, L"."); if ((p == path || wcschr(L":/\\", *(p - 1))) && - (!*q || wcschr(L":/\\", *q))) { - errno = ENOENT; - return -1; + (!*q || wcschr(L":/\\", *q))) { + errno = ENOENT; + return -1; } /* if the specified path is the root of a drive and the drive is empty, */ /* FindFirstFile() returns INVALID_HANDLE_VALUE. */ if (!GetFullPathNameW(path, sizeof(full) / sizeof(WCHAR), full, &dmy)) { - errno = map_errno(GetLastError()); - return -1; + errno = map_errno(GetLastError()); + return -1; } if (full[1] == L':' && !full[3] && GetDriveTypeW(full) != DRIVE_NO_ROOT_DIR) - return 0; + return 0; fh = open_dir_handle(path, &fd); if (fh == INVALID_HANDLE_VALUE) - return -1; + return -1; FindClose(fh); return 0; } @@ -5704,16 +5704,16 @@ stat_by_find(const WCHAR *path, struct stati128 *st) int e = GetLastError(); if ((e == ERROR_FILE_NOT_FOUND) || (e == ERROR_INVALID_NAME) - || (e == ERROR_PATH_NOT_FOUND || (e == ERROR_BAD_NETPATH))) { - errno = map_errno(e); - return -1; + || (e == ERROR_PATH_NOT_FOUND || (e == ERROR_BAD_NETPATH))) { + errno = map_errno(e); + return -1; } /* Fall back to FindFirstFile for ERROR_SHARING_VIOLATION */ h = FindFirstFileW(path, &wfd); if (h == INVALID_HANDLE_VALUE) { - errno = map_errno(GetLastError()); - return -1; + errno = map_errno(GetLastError()); + return -1; } FindClose(h); st->st_mode = fileattr_to_unixmode(wfd.dwFileAttributes, path, 0); @@ -5733,7 +5733,7 @@ static int path_drive(const WCHAR *path) { return (iswalpha(path[0]) && path[1] == L':') ? - towupper(path[0]) - L'A' : _getdrive() - 1; + towupper(path[0]) - L'A' : _getdrive() - 1; } /* License: Ruby's */ @@ -5747,38 +5747,38 @@ winnt_stat(const WCHAR *path, struct stati128 *st, BOOL lstat) memset(st, 0, sizeof(*st)); f = open_special(path, 0, flags); if (f != INVALID_HANDLE_VALUE) { - DWORD attr = stati128_handle(f, st); - const DWORD len = get_final_path(f, finalname, numberof(finalname), 0); - unsigned mode = 0; - switch (GetFileType(f)) { - case FILE_TYPE_CHAR: - mode = S_IFCHR; - break; - case FILE_TYPE_PIPE: - mode = S_IFIFO; - break; - } - CloseHandle(f); - if (attr & FILE_ATTRIBUTE_REPARSE_POINT) { - /* TODO: size in which encoding? */ - if (rb_w32_reparse_symlink_p(path)) - st->st_size = 0; - else - attr &= ~FILE_ATTRIBUTE_REPARSE_POINT; - } - if (attr & FILE_ATTRIBUTE_DIRECTORY) { - if (check_valid_dir(path)) return -1; - } - st->st_mode = fileattr_to_unixmode(attr, path, mode); - if (len) { - finalname[min(len, numberof(finalname)-1)] = L'\0'; - path = finalname; - if (wcsncmp(path, namespace_prefix, numberof(namespace_prefix)) == 0) - path += numberof(namespace_prefix); - } + DWORD attr = stati128_handle(f, st); + const DWORD len = get_final_path(f, finalname, numberof(finalname), 0); + unsigned mode = 0; + switch (GetFileType(f)) { + case FILE_TYPE_CHAR: + mode = S_IFCHR; + break; + case FILE_TYPE_PIPE: + mode = S_IFIFO; + break; + } + CloseHandle(f); + if (attr & FILE_ATTRIBUTE_REPARSE_POINT) { + /* TODO: size in which encoding? */ + if (rb_w32_reparse_symlink_p(path)) + st->st_size = 0; + else + attr &= ~FILE_ATTRIBUTE_REPARSE_POINT; + } + if (attr & FILE_ATTRIBUTE_DIRECTORY) { + if (check_valid_dir(path)) return -1; + } + st->st_mode = fileattr_to_unixmode(attr, path, mode); + if (len) { + finalname[min(len, numberof(finalname)-1)] = L'\0'; + path = finalname; + if (wcsncmp(path, namespace_prefix, numberof(namespace_prefix)) == 0) + path += numberof(namespace_prefix); + } } else { - if (stat_by_find(path, st)) return -1; + if (stat_by_find(path, st)) return -1; } st->st_dev = st->st_rdev = path_drive(path); @@ -5806,16 +5806,16 @@ wstati128(const WCHAR *path, struct stati128 *st, BOOL lstat) VALUE v; if (!path || !st) { - errno = EFAULT; - return -1; + errno = EFAULT; + return -1; } size = lstrlenW(path) + 2; buf1 = ALLOCV_N(WCHAR, v, size); if (!(path = name_for_stat(buf1, path))) - return -1; + return -1; ret = winnt_stat(path, st, lstat); if (v) - ALLOCV_END(v); + ALLOCV_END(v); return ret; } @@ -5829,27 +5829,27 @@ name_for_stat(WCHAR *buf1, const WCHAR *path) int len; for (p = path, s = buf1; *p; p++, s++) { - if (*p == L'/') - *s = L'\\'; - else - *s = *p; + if (*p == L'/') + *s = L'\\'; + else + *s = *p; } *s = '\0'; len = s - buf1; if (!len || L'\"' == *(--s)) { - errno = ENOENT; - return NULL; + errno = ENOENT; + return NULL; } end = buf1 + len - 1; if (isUNCRoot(buf1)) { - if (*end == L'.') - *end = L'\0'; - else if (*end != L'\\') - lstrcatW(buf1, L"\\"); + if (*end == L'.') + *end = L'\0'; + else if (*end != L'\\') + lstrcatW(buf1, L"\\"); } else if (*end == L'\\' || (buf1 + 1 == end && *end == L':')) - lstrcatW(buf1, L"."); + lstrcatW(buf1, L"."); return buf1; } @@ -5876,7 +5876,7 @@ w32_stati128(const char *path, struct stati128 *st, UINT cp, BOOL lstat) int ret; if (!(wpath = mbstr_to_wstr(cp, path, -1, NULL))) - return -1; + return -1; ret = wstati128(wpath, st, lstat); free(wpath); return ret; @@ -5914,11 +5914,11 @@ w32_access(const char *path, int mode, UINT cp) { struct stati128 stat; if (w32_stati128(path, &stat, cp, FALSE) != 0) - return -1; + return -1; mode <<= 6; if ((stat.st_mode & mode) != mode) { - errno = EACCES; - return -1; + errno = EACCES; + return -1; } return 0; } @@ -5946,21 +5946,21 @@ rb_chsize(HANDLE h, off_t size) DWORD e; if ((lpos = SetFilePointer(h, 0, (upos = 0, &upos), SEEK_CUR)) == -1L && - (e = GetLastError())) { - errno = map_errno(e); - return -1; + (e = GetLastError())) { + errno = map_errno(e); + return -1; } usize = (long)(size >> 32); lsize = (long)size; if (SetFilePointer(h, lsize, &usize, SEEK_SET) == (DWORD)-1L && - (e = GetLastError())) { - errno = map_errno(e); + (e = GetLastError())) { + errno = map_errno(e); } else if (!SetEndOfFile(h)) { - errno = map_errno(GetLastError()); + errno = map_errno(GetLastError()); } else { - ret = 0; + ret = 0; } SetFilePointer(h, lpos, &upos, SEEK_SET); return ret; @@ -5975,12 +5975,12 @@ w32_truncate(const char *path, off_t length, UINT cp) WCHAR *wpath; if (!(wpath = mbstr_to_wstr(cp, path, -1, NULL))) - return -1; + return -1; h = CreateFileW(wpath, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); if (h == INVALID_HANDLE_VALUE) { - errno = map_errno(GetLastError()); - free(wpath); - return -1; + errno = map_errno(GetLastError()); + free(wpath); + return -1; } free(wpath); ret = rb_chsize(h, length); @@ -6031,16 +6031,16 @@ rb_w32_times(struct tms *tmbuf) FILETIME create, exit, kernel, user; if (GetProcessTimes(GetCurrentProcess(),&create, &exit, &kernel, &user)) { - tmbuf->tms_utime = filetime_to_clock(&user); - tmbuf->tms_stime = filetime_to_clock(&kernel); - tmbuf->tms_cutime = 0; - tmbuf->tms_cstime = 0; + tmbuf->tms_utime = filetime_to_clock(&user); + tmbuf->tms_stime = filetime_to_clock(&kernel); + tmbuf->tms_cutime = 0; + tmbuf->tms_cstime = 0; } else { - tmbuf->tms_utime = clock(); - tmbuf->tms_stime = 0; - tmbuf->tms_cutime = 0; - tmbuf->tms_cstime = 0; + tmbuf->tms_utime = clock(); + tmbuf->tms_stime = 0; + tmbuf->tms_cutime = 0; + tmbuf->tms_cstime = 0; } return 0; } @@ -6078,61 +6078,61 @@ call_asynchronous(PVOID argp) /* License: Ruby's */ uintptr_t rb_w32_asynchronize(asynchronous_func_t func, uintptr_t self, - int argc, uintptr_t* argv, uintptr_t intrval) + int argc, uintptr_t* argv, uintptr_t intrval) { DWORD val; BOOL interrupted = FALSE; HANDLE thr; RUBY_CRITICAL { - struct asynchronous_arg_t arg; + struct asynchronous_arg_t arg; - arg.stackaddr = NULL; - arg.errnum = 0; - arg.func = func; - arg.self = self; - arg.argc = argc; - arg.argv = argv; + arg.stackaddr = NULL; + arg.errnum = 0; + arg.func = func; + arg.self = self; + arg.argc = argc; + arg.argv = argv; - thr = CreateThread(NULL, 0, call_asynchronous, &arg, 0, &val); + thr = CreateThread(NULL, 0, call_asynchronous, &arg, 0, &val); - if (thr) { - yield_until(arg.stackaddr); + if (thr) { + yield_until(arg.stackaddr); - if (rb_w32_wait_events_blocking(&thr, 1, INFINITE) != WAIT_OBJECT_0) { - interrupted = TRUE; + if (rb_w32_wait_events_blocking(&thr, 1, INFINITE) != WAIT_OBJECT_0) { + interrupted = TRUE; - if (TerminateThread(thr, intrval)) { - yield_once(); - } - } + if (TerminateThread(thr, intrval)) { + yield_once(); + } + } - GetExitCodeThread(thr, &val); - CloseHandle(thr); + GetExitCodeThread(thr, &val); + CloseHandle(thr); - if (interrupted) { - /* must release stack of killed thread, why doesn't Windows? */ - MEMORY_BASIC_INFORMATION m; + if (interrupted) { + /* must release stack of killed thread, why doesn't Windows? */ + MEMORY_BASIC_INFORMATION m; - memset(&m, 0, sizeof(m)); - if (!VirtualQuery(arg.stackaddr, &m, sizeof(m))) { - Debug(fprintf(stderr, "couldn't get stack base:%p:%d\n", - arg.stackaddr, GetLastError())); - } - else if (!VirtualFree(m.AllocationBase, 0, MEM_RELEASE)) { - Debug(fprintf(stderr, "couldn't release stack:%p:%d\n", - m.AllocationBase, GetLastError())); - } - errno = EINTR; - } - else { - errno = arg.errnum; - } - } + memset(&m, 0, sizeof(m)); + if (!VirtualQuery(arg.stackaddr, &m, sizeof(m))) { + Debug(fprintf(stderr, "couldn't get stack base:%p:%d\n", + arg.stackaddr, GetLastError())); + } + else if (!VirtualFree(m.AllocationBase, 0, MEM_RELEASE)) { + Debug(fprintf(stderr, "couldn't release stack:%p:%d\n", + m.AllocationBase, GetLastError())); + } + errno = EINTR; + } + else { + errno = arg.errnum; + } + } } if (!thr) { - rb_fatal("failed to launch waiter thread:%ld", GetLastError()); + rb_fatal("failed to launch waiter thread:%ld", GetLastError()); } return val; @@ -6158,16 +6158,16 @@ rb_w32_get_environ(void) */ envtop = GetEnvironmentStringsW(); for (env = envtop, num = 0; *env; env += lstrlenW(env) + 1) - if (*env != '=') num++; + if (*env != '=') num++; myenvtop = (char **)malloc(sizeof(char *) * (num + 1)); for (env = envtop, myenv = myenvtop; *env; env += lstrlenW(env) + 1) { - if (*env != '=') { - if (!(*myenv = wstr_to_utf8(env, NULL))) { - break; - } - myenv++; - } + if (*env != '=') { + if (!(*myenv = wstr_to_utf8(env, NULL))) { + break; + } + myenv++; + } } *myenv = NULL; FreeEnvironmentStringsW(envtop); @@ -6202,21 +6202,21 @@ rb_w32_getppid(void) rb_pid_t ppid = 0; if (pNtQueryInformationProcess == (query_func *)-1) - pNtQueryInformationProcess = (query_func *)get_proc_address("ntdll.dll", "NtQueryInformationProcess", NULL); + pNtQueryInformationProcess = (query_func *)get_proc_address("ntdll.dll", "NtQueryInformationProcess", NULL); if (pNtQueryInformationProcess) { - struct { - long ExitStatus; - void* PebBaseAddress; - uintptr_t AffinityMask; - uintptr_t BasePriority; - uintptr_t UniqueProcessId; - uintptr_t ParentProcessId; - } pbi; - ULONG len; - long ret = pNtQueryInformationProcess(GetCurrentProcess(), 0, &pbi, sizeof(pbi), &len); - if (!ret) { - ppid = pbi.ParentProcessId; - } + struct { + long ExitStatus; + void* PebBaseAddress; + uintptr_t AffinityMask; + uintptr_t BasePriority; + uintptr_t UniqueProcessId; + uintptr_t ParentProcessId; + } pbi; + ULONG len; + long ret = pNtQueryInformationProcess(GetCurrentProcess(), 0, &pbi, sizeof(pbi), &len); + if (!ret) { + ppid = pbi.ParentProcessId; + } } return ppid; @@ -6226,9 +6226,9 @@ STATIC_ASSERT(std_handle, (STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)==(STD_ERROR_HANDL /* License: Ruby's */ #define set_new_std_handle(newfd, handle) do { \ - if ((unsigned)(newfd) > 2) break; \ - SetStdHandle(STD_INPUT_HANDLE+(STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)*(newfd), \ - (handle)); \ + if ((unsigned)(newfd) > 2) break; \ + SetStdHandle(STD_INPUT_HANDLE+(STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)*(newfd), \ + (handle)); \ } while (0) #define set_new_std_fd(newfd) set_new_std_handle(newfd, (HANDLE)rb_w32_get_osfhandle(newfd)) @@ -6259,7 +6259,7 @@ rb_w32_uopen(const char *file, int oflag, ...) va_end(arg); if (!(wfile = utf8_to_wstr(file, NULL))) - return -1; + return -1; ret = w32_wopen(wfile, oflag, pmode); free(wfile); return ret; @@ -6271,9 +6271,9 @@ check_if_wdir(const WCHAR *wfile) { DWORD attr = GetFileAttributesW(wfile); if (attr == (DWORD)-1L || - !(attr & FILE_ATTRIBUTE_DIRECTORY) || - check_valid_dir(wfile)) { - return FALSE; + !(attr & FILE_ATTRIBUTE_DIRECTORY) || + check_valid_dir(wfile)) { + return FALSE; } errno = EISDIR; return TRUE; @@ -6293,7 +6293,7 @@ rb_w32_open(const char *file, int oflag, ...) va_end(arg); if (!(wfile = filecp_to_wstr(file, NULL))) - return -1; + return -1; ret = w32_wopen(wfile, oflag, pmode); free(wfile); return ret; @@ -6306,10 +6306,10 @@ rb_w32_wopen(const WCHAR *file, int oflag, ...) int pmode = 0; if (oflag & O_CREAT) { - va_list arg; - va_start(arg, oflag); - pmode = va_arg(arg, int); - va_end(arg); + va_list arg; + va_start(arg, oflag); + pmode = va_arg(arg, int); + va_end(arg); } return w32_wopen(file, oflag, pmode); @@ -6330,28 +6330,28 @@ w32_wopen(const WCHAR *file, int oflag, int pmode) share_delete = oflag & O_SHARE_DELETE ? FILE_SHARE_DELETE : 0; oflag &= ~O_SHARE_DELETE; if ((oflag & O_TEXT) || !(oflag & O_BINARY)) { - fd = _wopen(file, oflag, pmode); - if (fd == -1) { - switch (errno) { - case EACCES: - check_if_wdir(file); - break; - case EINVAL: - errno = map_errno(GetLastError()); - break; - } - } - return fd; + fd = _wopen(file, oflag, pmode); + if (fd == -1) { + switch (errno) { + case EACCES: + check_if_wdir(file); + break; + case EINVAL: + errno = map_errno(GetLastError()); + break; + } + } + return fd; } sec.nLength = sizeof(sec); sec.lpSecurityDescriptor = NULL; if (oflag & O_NOINHERIT) { - sec.bInheritHandle = FALSE; - flags |= FNOINHERIT; + sec.bInheritHandle = FALSE; + flags |= FNOINHERIT; } else { - sec.bInheritHandle = TRUE; + sec.bInheritHandle = TRUE; } oflag &= ~O_NOINHERIT; @@ -6360,128 +6360,128 @@ w32_wopen(const WCHAR *file, int oflag, int pmode) switch (oflag & (O_RDWR | O_RDONLY | O_WRONLY)) { case O_RDWR: - access = GENERIC_READ | GENERIC_WRITE; - break; + access = GENERIC_READ | GENERIC_WRITE; + break; case O_RDONLY: - access = GENERIC_READ; - break; + access = GENERIC_READ; + break; case O_WRONLY: - access = GENERIC_WRITE; - break; + access = GENERIC_WRITE; + break; default: - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } oflag &= ~(O_RDWR | O_RDONLY | O_WRONLY); switch (oflag & (O_CREAT | O_EXCL | O_TRUNC)) { case O_CREAT: - create = OPEN_ALWAYS; - break; + create = OPEN_ALWAYS; + break; case 0: case O_EXCL: - create = OPEN_EXISTING; - break; + create = OPEN_EXISTING; + break; case O_CREAT | O_EXCL: case O_CREAT | O_EXCL | O_TRUNC: - create = CREATE_NEW; - break; + create = CREATE_NEW; + break; case O_TRUNC: case O_TRUNC | O_EXCL: - create = TRUNCATE_EXISTING; - break; + create = TRUNCATE_EXISTING; + break; case O_CREAT | O_TRUNC: - create = CREATE_ALWAYS; - break; + create = CREATE_ALWAYS; + break; default: - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } if (oflag & O_CREAT) { - /* TODO: we need to check umask here, but it's not exported... */ - if (!(pmode & S_IWRITE)) - attr = FILE_ATTRIBUTE_READONLY; + /* TODO: we need to check umask here, but it's not exported... */ + if (!(pmode & S_IWRITE)) + attr = FILE_ATTRIBUTE_READONLY; } oflag &= ~(O_CREAT | O_EXCL | O_TRUNC); if (oflag & O_TEMPORARY) { - attr |= FILE_FLAG_DELETE_ON_CLOSE; - access |= DELETE; + attr |= FILE_FLAG_DELETE_ON_CLOSE; + access |= DELETE; } oflag &= ~O_TEMPORARY; if (oflag & _O_SHORT_LIVED) - attr |= FILE_ATTRIBUTE_TEMPORARY; + attr |= FILE_ATTRIBUTE_TEMPORARY; oflag &= ~_O_SHORT_LIVED; switch (oflag & (O_SEQUENTIAL | O_RANDOM)) { case 0: - break; + break; case O_SEQUENTIAL: - attr |= FILE_FLAG_SEQUENTIAL_SCAN; - break; + attr |= FILE_FLAG_SEQUENTIAL_SCAN; + break; case O_RANDOM: - attr |= FILE_FLAG_RANDOM_ACCESS; - break; + attr |= FILE_FLAG_RANDOM_ACCESS; + break; default: - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } oflag &= ~(O_SEQUENTIAL | O_RANDOM); if (oflag & ~O_APPEND) { - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } /* allocate a C Runtime file handle */ RUBY_CRITICAL { - h = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL); - fd = _open_osfhandle((intptr_t)h, 0); - CloseHandle(h); + h = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL); + fd = _open_osfhandle((intptr_t)h, 0); + CloseHandle(h); } if (fd == -1) { - errno = EMFILE; - return -1; + errno = EMFILE; + return -1; } RUBY_CRITICAL { - rb_acrt_lowio_lock_fh(fd); - _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE); - _set_osflags(fd, 0); + rb_acrt_lowio_lock_fh(fd); + _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE); + _set_osflags(fd, 0); - h = CreateFileW(file, access, FILE_SHARE_READ | FILE_SHARE_WRITE | share_delete, &sec, create, attr, NULL); - if (h == INVALID_HANDLE_VALUE) { - DWORD e = GetLastError(); - if (e != ERROR_ACCESS_DENIED || !check_if_wdir(file)) - errno = map_errno(e); - rb_acrt_lowio_unlock_fh(fd); - fd = -1; - goto quit; - } + h = CreateFileW(file, access, FILE_SHARE_READ | FILE_SHARE_WRITE | share_delete, &sec, create, attr, NULL); + if (h == INVALID_HANDLE_VALUE) { + DWORD e = GetLastError(); + if (e != ERROR_ACCESS_DENIED || !check_if_wdir(file)) + errno = map_errno(e); + rb_acrt_lowio_unlock_fh(fd); + fd = -1; + goto quit; + } - switch (GetFileType(h)) { - case FILE_TYPE_CHAR: - flags |= FDEV; - break; - case FILE_TYPE_PIPE: - flags |= FPIPE; - break; - case FILE_TYPE_UNKNOWN: - errno = map_errno(GetLastError()); - CloseHandle(h); - rb_acrt_lowio_unlock_fh(fd); - fd = -1; - goto quit; - } - if (!(flags & (FDEV | FPIPE)) && (oflag & O_APPEND)) - flags |= FAPPEND; + switch (GetFileType(h)) { + case FILE_TYPE_CHAR: + flags |= FDEV; + break; + case FILE_TYPE_PIPE: + flags |= FPIPE; + break; + case FILE_TYPE_UNKNOWN: + errno = map_errno(GetLastError()); + CloseHandle(h); + rb_acrt_lowio_unlock_fh(fd); + fd = -1; + goto quit; + } + if (!(flags & (FDEV | FPIPE)) && (oflag & O_APPEND)) + flags |= FAPPEND; - _set_osfhnd(fd, (intptr_t)h); - _set_osflags(fd, flags | FOPEN); + _set_osfhnd(fd, (intptr_t)h); + _set_osflags(fd, flags | FOPEN); - rb_acrt_lowio_unlock_fh(fd); + rb_acrt_lowio_unlock_fh(fd); quit: - ; + ; } return fd; @@ -6497,15 +6497,15 @@ rb_w32_fclose(FILE *fp) if (fflush(fp)) return -1; if (!is_socket(sock)) { - UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN); - return fclose(fp); + UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN); + return fclose(fp); } _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE); fclose(fp); errno = save_errno; if (closesocket(sock) == SOCKET_ERROR) { - errno = map_errno(WSAGetLastError()); - return -1; + errno = map_errno(WSAGetLastError()); + return -1; } return 0; } @@ -6517,10 +6517,10 @@ rb_w32_pipe(int fds[2]) static long serial = 0; static const char prefix[] = "\\\\.\\pipe\\ruby"; enum { - width_of_prefix = (int)sizeof(prefix) - 1, - width_of_pid = (int)sizeof(rb_pid_t) * 2, - width_of_serial = (int)sizeof(serial) * 2, - width_of_ids = width_of_pid + 1 + width_of_serial + 1 + width_of_prefix = (int)sizeof(prefix) - 1, + width_of_pid = (int)sizeof(rb_pid_t) * 2, + width_of_serial = (int)sizeof(serial) * 2, + width_of_ids = width_of_pid + 1 + width_of_serial + 1 }; char name[sizeof(prefix) + width_of_ids]; SECURITY_ATTRIBUTES sec; @@ -6530,74 +6530,74 @@ rb_w32_pipe(int fds[2]) memcpy(name, prefix, width_of_prefix); snprintf(name + width_of_prefix, width_of_ids, "%.*"PRI_PIDT_PREFIX"x-%.*lx", - width_of_pid, rb_w32_getpid(), width_of_serial, InterlockedIncrement(&serial)-1); + width_of_pid, rb_w32_getpid(), width_of_serial, InterlockedIncrement(&serial)-1); sec.nLength = sizeof(sec); sec.lpSecurityDescriptor = NULL; sec.bInheritHandle = FALSE; RUBY_CRITICAL { - hRead = CreateNamedPipe(name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, - 0, 2, 65536, 65536, 0, &sec); + hRead = CreateNamedPipe(name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, + 0, 2, 65536, 65536, 0, &sec); } if (hRead == INVALID_HANDLE_VALUE) { - DWORD err = GetLastError(); - if (err == ERROR_PIPE_BUSY) - errno = EMFILE; - else - errno = map_errno(GetLastError()); - return -1; + DWORD err = GetLastError(); + if (err == ERROR_PIPE_BUSY) + errno = EMFILE; + else + errno = map_errno(GetLastError()); + return -1; } RUBY_CRITICAL { - hWrite = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, &sec, - OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); + hWrite = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, &sec, + OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); } if (hWrite == INVALID_HANDLE_VALUE) { - errno = map_errno(GetLastError()); - CloseHandle(hRead); - return -1; + errno = map_errno(GetLastError()); + CloseHandle(hRead); + return -1; } RUBY_CRITICAL do { - ret = 0; - h = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL); - fdRead = _open_osfhandle((intptr_t)h, 0); - CloseHandle(h); - if (fdRead == -1) { - errno = EMFILE; - CloseHandle(hWrite); - CloseHandle(hRead); - ret = -1; - break; - } + ret = 0; + h = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL); + fdRead = _open_osfhandle((intptr_t)h, 0); + CloseHandle(h); + if (fdRead == -1) { + errno = EMFILE; + CloseHandle(hWrite); + CloseHandle(hRead); + ret = -1; + break; + } - rb_acrt_lowio_lock_fh(fdRead); - _set_osfhnd(fdRead, (intptr_t)hRead); - _set_osflags(fdRead, FOPEN | FPIPE | FNOINHERIT); - rb_acrt_lowio_unlock_fh(fdRead); + rb_acrt_lowio_lock_fh(fdRead); + _set_osfhnd(fdRead, (intptr_t)hRead); + _set_osflags(fdRead, FOPEN | FPIPE | FNOINHERIT); + rb_acrt_lowio_unlock_fh(fdRead); } while (0); if (ret) - return ret; + return ret; RUBY_CRITICAL do { - h = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL); - fdWrite = _open_osfhandle((intptr_t)h, 0); - CloseHandle(h); - if (fdWrite == -1) { - errno = EMFILE; - CloseHandle(hWrite); - ret = -1; - break; - } - rb_acrt_lowio_lock_fh(fdWrite); - _set_osfhnd(fdWrite, (intptr_t)hWrite); - _set_osflags(fdWrite, FOPEN | FPIPE | FNOINHERIT); - rb_acrt_lowio_unlock_fh(fdWrite); + h = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL); + fdWrite = _open_osfhandle((intptr_t)h, 0); + CloseHandle(h); + if (fdWrite == -1) { + errno = EMFILE; + CloseHandle(hWrite); + ret = -1; + break; + } + rb_acrt_lowio_lock_fh(fdWrite); + _set_osfhnd(fdWrite, (intptr_t)hWrite); + _set_osflags(fdWrite, FOPEN | FPIPE | FNOINHERIT); + rb_acrt_lowio_unlock_fh(fdWrite); } while (0); if (ret) { - rb_w32_close(fdRead); - return ret; + rb_w32_close(fdRead); + return ret; } fds[0] = fdRead; @@ -6619,7 +6619,7 @@ console_emulator_p(void) memset(&m, 0, sizeof(m)); if (!VirtualQuery(func, &m, sizeof(m))) { - return FALSE; + return FALSE; } k = GetModuleHandle("kernel32.dll"); if (!k) return FALSE; @@ -6634,32 +6634,32 @@ constat_handle(HANDLE h) st_data_t data; struct constat *p = NULL; thread_exclusive(conlist) { - if (!conlist) { - if (console_emulator_p()) { - conlist = conlist_disabled; - continue; - } - conlist = st_init_numtable(); - install_vm_exit_handler(); - } - else if (conlist == conlist_disabled) { - continue; - } - if (st_lookup(conlist, (st_data_t)h, &data)) { - p = (struct constat *)data; - } - else { - CONSOLE_SCREEN_BUFFER_INFO csbi; - p = ALLOC(struct constat); - p->vt100.state = constat_init; - p->vt100.attr = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED; - p->vt100.reverse = 0; - p->vt100.saved.X = p->vt100.saved.Y = 0; - if (GetConsoleScreenBufferInfo(h, &csbi)) { - p->vt100.attr = csbi.wAttributes; - } - st_insert(conlist, (st_data_t)h, (st_data_t)p); - } + if (!conlist) { + if (console_emulator_p()) { + conlist = conlist_disabled; + continue; + } + conlist = st_init_numtable(); + install_vm_exit_handler(); + } + else if (conlist == conlist_disabled) { + continue; + } + if (st_lookup(conlist, (st_data_t)h, &data)) { + p = (struct constat *)data; + } + else { + CONSOLE_SCREEN_BUFFER_INFO csbi; + p = ALLOC(struct constat); + p->vt100.state = constat_init; + p->vt100.attr = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED; + p->vt100.reverse = 0; + p->vt100.saved.X = p->vt100.saved.Y = 0; + if (GetConsoleScreenBufferInfo(h, &csbi)) { + p->vt100.attr = csbi.wAttributes; + } + st_insert(conlist, (st_data_t)h, (st_data_t)p); + } } return p; } @@ -6671,10 +6671,10 @@ constat_reset(HANDLE h) st_data_t data; struct constat *p; thread_exclusive(conlist) { - if (!conlist || conlist == conlist_disabled) continue; - if (!st_lookup(conlist, (st_data_t)h, &data)) continue; - p = (struct constat *)data; - p->vt100.state = constat_init; + if (!conlist || conlist == conlist_disabled) continue; + if (!st_lookup(conlist, (st_data_t)h, &data)) continue; + p = (struct constat *)data; + p->vt100.state = constat_init; } } @@ -6683,8 +6683,8 @@ constat_reset(HANDLE h) #define constat_attr_color_reverse(attr) \ ((attr) & ~(FOREGROUND_MASK | BACKGROUND_MASK)) | \ - (((attr) & FOREGROUND_MASK) << 4) | \ - (((attr) & BACKGROUND_MASK) >> 4) + (((attr) & FOREGROUND_MASK) << 4) | \ + (((attr) & BACKGROUND_MASK) >> 4) /* License: Ruby's */ static WORD @@ -6699,82 +6699,82 @@ constat_attr(int count, const int *seq, WORD attr, WORD default_attr, int *rever attr &= ~(FOREGROUND_INTENSITY | BACKGROUND_INTENSITY); while (count-- > 0) { - switch (*seq++) { - case 0: - attr = default_attr; - rev = 0; - bold = 0; - break; - case 1: - bold = FOREGROUND_INTENSITY; - break; - case 4: + switch (*seq++) { + case 0: + attr = default_attr; + rev = 0; + bold = 0; + break; + case 1: + bold = FOREGROUND_INTENSITY; + break; + case 4: #ifndef COMMON_LVB_UNDERSCORE #define COMMON_LVB_UNDERSCORE 0x8000 #endif - attr |= COMMON_LVB_UNDERSCORE; - break; - case 7: - rev = 1; - break; + attr |= COMMON_LVB_UNDERSCORE; + break; + case 7: + rev = 1; + break; - case 30: - attr &= ~(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED); - break; - case 17: - case 31: - attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_GREEN)) | FOREGROUND_RED; - break; - case 18: - case 32: - attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_RED)) | FOREGROUND_GREEN; - break; - case 19: - case 33: - attr = (attr & ~FOREGROUND_BLUE) | FOREGROUND_GREEN | FOREGROUND_RED; - break; - case 20: - case 34: - attr = (attr & ~(FOREGROUND_GREEN | FOREGROUND_RED)) | FOREGROUND_BLUE; - break; - case 21: - case 35: - attr = (attr & ~FOREGROUND_GREEN) | FOREGROUND_BLUE | FOREGROUND_RED; - break; - case 22: - case 36: - attr = (attr & ~FOREGROUND_RED) | FOREGROUND_BLUE | FOREGROUND_GREEN; - break; - case 23: - case 37: - attr |= FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED; - break; + case 30: + attr &= ~(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED); + break; + case 17: + case 31: + attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_GREEN)) | FOREGROUND_RED; + break; + case 18: + case 32: + attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_RED)) | FOREGROUND_GREEN; + break; + case 19: + case 33: + attr = (attr & ~FOREGROUND_BLUE) | FOREGROUND_GREEN | FOREGROUND_RED; + break; + case 20: + case 34: + attr = (attr & ~(FOREGROUND_GREEN | FOREGROUND_RED)) | FOREGROUND_BLUE; + break; + case 21: + case 35: + attr = (attr & ~FOREGROUND_GREEN) | FOREGROUND_BLUE | FOREGROUND_RED; + break; + case 22: + case 36: + attr = (attr & ~FOREGROUND_RED) | FOREGROUND_BLUE | FOREGROUND_GREEN; + break; + case 23: + case 37: + attr |= FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED; + break; - case 40: - attr &= ~(BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED); - break; - case 41: - attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_GREEN)) | BACKGROUND_RED; - break; - case 42: - attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_RED)) | BACKGROUND_GREEN; - break; - case 43: - attr = (attr & ~BACKGROUND_BLUE) | BACKGROUND_GREEN | BACKGROUND_RED; - break; - case 44: - attr = (attr & ~(BACKGROUND_GREEN | BACKGROUND_RED)) | BACKGROUND_BLUE; - break; - case 45: - attr = (attr & ~BACKGROUND_GREEN) | BACKGROUND_BLUE | BACKGROUND_RED; - break; - case 46: - attr = (attr & ~BACKGROUND_RED) | BACKGROUND_BLUE | BACKGROUND_GREEN; - break; - case 47: - attr |= BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED; - break; - } + case 40: + attr &= ~(BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED); + break; + case 41: + attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_GREEN)) | BACKGROUND_RED; + break; + case 42: + attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_RED)) | BACKGROUND_GREEN; + break; + case 43: + attr = (attr & ~BACKGROUND_BLUE) | BACKGROUND_GREEN | BACKGROUND_RED; + break; + case 44: + attr = (attr & ~(BACKGROUND_GREEN | BACKGROUND_RED)) | BACKGROUND_BLUE; + break; + case 45: + attr = (attr & ~BACKGROUND_GREEN) | BACKGROUND_BLUE | BACKGROUND_RED; + break; + case 46: + attr = (attr & ~BACKGROUND_RED) | BACKGROUND_BLUE | BACKGROUND_GREEN; + break; + case 47: + attr |= BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED; + break; + } } attr |= bold; if (rev) attr = constat_attr_color_reverse(attr); @@ -6807,136 +6807,136 @@ constat_apply(HANDLE handle, struct constat *s, WCHAR w) if (arg0) arg1 = seq[0]; switch (w) { case L'm': - SetConsoleTextAttribute(handle, constat_attr(count, seq, csbi.wAttributes, s->vt100.attr, &s->vt100.reverse)); - break; + SetConsoleTextAttribute(handle, constat_attr(count, seq, csbi.wAttributes, s->vt100.attr, &s->vt100.reverse)); + break; case L'F': - csbi.dwCursorPosition.X = 0; + csbi.dwCursorPosition.X = 0; case L'A': - csbi.dwCursorPosition.Y -= arg1; - if (csbi.dwCursorPosition.Y < csbi.srWindow.Top) - csbi.dwCursorPosition.Y = csbi.srWindow.Top; - SetConsoleCursorPosition(handle, csbi.dwCursorPosition); - break; + csbi.dwCursorPosition.Y -= arg1; + if (csbi.dwCursorPosition.Y < csbi.srWindow.Top) + csbi.dwCursorPosition.Y = csbi.srWindow.Top; + SetConsoleCursorPosition(handle, csbi.dwCursorPosition); + break; case L'E': - csbi.dwCursorPosition.X = 0; + csbi.dwCursorPosition.X = 0; case L'B': case L'e': - csbi.dwCursorPosition.Y += arg1; - if (csbi.dwCursorPosition.Y > csbi.srWindow.Bottom) - csbi.dwCursorPosition.Y = csbi.srWindow.Bottom; - SetConsoleCursorPosition(handle, csbi.dwCursorPosition); - break; + csbi.dwCursorPosition.Y += arg1; + if (csbi.dwCursorPosition.Y > csbi.srWindow.Bottom) + csbi.dwCursorPosition.Y = csbi.srWindow.Bottom; + SetConsoleCursorPosition(handle, csbi.dwCursorPosition); + break; case L'C': - csbi.dwCursorPosition.X += arg1; - if (csbi.dwCursorPosition.X >= csbi.srWindow.Right) - csbi.dwCursorPosition.X = csbi.srWindow.Right; - SetConsoleCursorPosition(handle, csbi.dwCursorPosition); - break; + csbi.dwCursorPosition.X += arg1; + if (csbi.dwCursorPosition.X >= csbi.srWindow.Right) + csbi.dwCursorPosition.X = csbi.srWindow.Right; + SetConsoleCursorPosition(handle, csbi.dwCursorPosition); + break; case L'D': - csbi.dwCursorPosition.X -= arg1; - if (csbi.dwCursorPosition.X < csbi.srWindow.Left) - csbi.dwCursorPosition.X = csbi.srWindow.Left; - SetConsoleCursorPosition(handle, csbi.dwCursorPosition); - break; + csbi.dwCursorPosition.X -= arg1; + if (csbi.dwCursorPosition.X < csbi.srWindow.Left) + csbi.dwCursorPosition.X = csbi.srWindow.Left; + SetConsoleCursorPosition(handle, csbi.dwCursorPosition); + break; case L'G': case L'`': - arg1 += csbi.srWindow.Left; - if (arg1 > csbi.srWindow.Right) - arg1 = csbi.srWindow.Right; - csbi.dwCursorPosition.X = arg1; - SetConsoleCursorPosition(handle, csbi.dwCursorPosition); - break; + arg1 += csbi.srWindow.Left; + if (arg1 > csbi.srWindow.Right) + arg1 = csbi.srWindow.Right; + csbi.dwCursorPosition.X = arg1; + SetConsoleCursorPosition(handle, csbi.dwCursorPosition); + break; case L'd': - arg1 += csbi.srWindow.Top; - if (arg1 > csbi.srWindow.Bottom) - arg1 = csbi.srWindow.Bottom; - csbi.dwCursorPosition.Y = arg1; - SetConsoleCursorPosition(handle, csbi.dwCursorPosition); - break; + arg1 += csbi.srWindow.Top; + if (arg1 > csbi.srWindow.Bottom) + arg1 = csbi.srWindow.Bottom; + csbi.dwCursorPosition.Y = arg1; + SetConsoleCursorPosition(handle, csbi.dwCursorPosition); + break; case L'H': case L'f': - pos.Y = arg1 + csbi.srWindow.Top - 1; - if (pos.Y > csbi.srWindow.Bottom) pos.Y = csbi.srWindow.Bottom; - if (count < 2 || (arg1 = seq[1]) <= 0) arg1 = 1; - pos.X = arg1 + csbi.srWindow.Left - 1; - if (pos.X > csbi.srWindow.Right) pos.X = csbi.srWindow.Right; - SetConsoleCursorPosition(handle, pos); - break; + pos.Y = arg1 + csbi.srWindow.Top - 1; + if (pos.Y > csbi.srWindow.Bottom) pos.Y = csbi.srWindow.Bottom; + if (count < 2 || (arg1 = seq[1]) <= 0) arg1 = 1; + pos.X = arg1 + csbi.srWindow.Left - 1; + if (pos.X > csbi.srWindow.Right) pos.X = csbi.srWindow.Right; + SetConsoleCursorPosition(handle, pos); + break; case L'J': - switch (arg0 ? arg1 : 0) { - case 0: /* erase after cursor */ - constat_clear(handle, csbi.wAttributes, - (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.dwCursorPosition.Y + 1) - - csbi.dwCursorPosition.X), - csbi.dwCursorPosition); - break; - case 1: /* erase before *and* cursor */ - pos.X = 0; - pos.Y = csbi.srWindow.Top; - constat_clear(handle, csbi.wAttributes, - (csbi.dwSize.X * (csbi.dwCursorPosition.Y - csbi.srWindow.Top) - + csbi.dwCursorPosition.X + 1), - pos); - break; - case 2: /* erase entire screen */ - pos.X = 0; - pos.Y = csbi.srWindow.Top; - constat_clear(handle, csbi.wAttributes, - (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1)), - pos); - break; - case 3: /* erase entire screen */ - pos.X = 0; - pos.Y = 0; - constat_clear(handle, csbi.wAttributes, - (csbi.dwSize.X * csbi.dwSize.Y), - pos); - break; - } - break; + switch (arg0 ? arg1 : 0) { + case 0: /* erase after cursor */ + constat_clear(handle, csbi.wAttributes, + (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.dwCursorPosition.Y + 1) + - csbi.dwCursorPosition.X), + csbi.dwCursorPosition); + break; + case 1: /* erase before *and* cursor */ + pos.X = 0; + pos.Y = csbi.srWindow.Top; + constat_clear(handle, csbi.wAttributes, + (csbi.dwSize.X * (csbi.dwCursorPosition.Y - csbi.srWindow.Top) + + csbi.dwCursorPosition.X + 1), + pos); + break; + case 2: /* erase entire screen */ + pos.X = 0; + pos.Y = csbi.srWindow.Top; + constat_clear(handle, csbi.wAttributes, + (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1)), + pos); + break; + case 3: /* erase entire screen */ + pos.X = 0; + pos.Y = 0; + constat_clear(handle, csbi.wAttributes, + (csbi.dwSize.X * csbi.dwSize.Y), + pos); + break; + } + break; case L'K': - switch (arg0 ? arg1 : 0) { - case 0: /* erase after cursor */ - constat_clear(handle, csbi.wAttributes, - (csbi.dwSize.X - csbi.dwCursorPosition.X), - csbi.dwCursorPosition); - break; - case 1: /* erase before *and* cursor */ - pos.X = 0; - pos.Y = csbi.dwCursorPosition.Y; - constat_clear(handle, csbi.wAttributes, - csbi.dwCursorPosition.X + 1, pos); - break; - case 2: /* erase entire line */ - pos.X = 0; - pos.Y = csbi.dwCursorPosition.Y; - constat_clear(handle, csbi.wAttributes, - csbi.dwSize.X, pos); - break; - } - break; + switch (arg0 ? arg1 : 0) { + case 0: /* erase after cursor */ + constat_clear(handle, csbi.wAttributes, + (csbi.dwSize.X - csbi.dwCursorPosition.X), + csbi.dwCursorPosition); + break; + case 1: /* erase before *and* cursor */ + pos.X = 0; + pos.Y = csbi.dwCursorPosition.Y; + constat_clear(handle, csbi.wAttributes, + csbi.dwCursorPosition.X + 1, pos); + break; + case 2: /* erase entire line */ + pos.X = 0; + pos.Y = csbi.dwCursorPosition.Y; + constat_clear(handle, csbi.wAttributes, + csbi.dwSize.X, pos); + break; + } + break; case L's': - s->vt100.saved = csbi.dwCursorPosition; - break; + s->vt100.saved = csbi.dwCursorPosition; + break; case L'u': - SetConsoleCursorPosition(handle, s->vt100.saved); - break; + SetConsoleCursorPosition(handle, s->vt100.saved); + break; case L'h': - if (count >= 2 && seq[0] == -1 && seq[1] == 25) { - CONSOLE_CURSOR_INFO cci; - GetConsoleCursorInfo(handle, &cci); - cci.bVisible = TRUE; - SetConsoleCursorInfo(handle, &cci); - } - break; + if (count >= 2 && seq[0] == -1 && seq[1] == 25) { + CONSOLE_CURSOR_INFO cci; + GetConsoleCursorInfo(handle, &cci); + cci.bVisible = TRUE; + SetConsoleCursorInfo(handle, &cci); + } + break; case L'l': - if (count >= 2 && seq[0] == -1 && seq[1] == 25) { - CONSOLE_CURSOR_INFO cci; - GetConsoleCursorInfo(handle, &cci); - cci.bVisible = FALSE; - SetConsoleCursorInfo(handle, &cci); - } - break; + if (count >= 2 && seq[0] == -1 && seq[1] == 25) { + CONSOLE_CURSOR_INFO cci; + GetConsoleCursorInfo(handle, &cci); + cci.bVisible = FALSE; + SetConsoleCursorInfo(handle, &cci); + } + break; } } @@ -6951,59 +6951,59 @@ constat_parse(HANDLE h, struct constat *s, const WCHAR **ptrp, long *lenp) const WCHAR *ptr = *ptrp; long rest, len = *lenp; while (len-- > 0) { - WCHAR wc = *ptr++; - if (wc == 0x1b) { - rest = *lenp - len - 1; - if (s->vt100.state == constat_esc) { - rest++; /* reuse this ESC */ - } - s->vt100.state = constat_init; - if (len > 0 && *ptr != L'[') continue; - s->vt100.state = constat_esc; - } - else if (s->vt100.state == constat_esc) { - if (wc != L'[') { - /* TODO: supply dropped ESC at beginning */ - s->vt100.state = constat_init; - continue; - } - rest = *lenp - len - 1; - if (rest > 0) --rest; - s->vt100.state = constat_seq; - s->vt100.seq[0] = 0; - } - else if (s->vt100.state >= constat_seq) { - if (wc >= L'0' && wc <= L'9') { - if (s->vt100.state < (int)numberof(s->vt100.seq)) { - int *seq = &s->vt100.seq[s->vt100.state]; - *seq = (*seq * 10) + (wc - L'0'); - } - } - else if (s->vt100.state == constat_seq && s->vt100.seq[0] == 0 && wc == L'?') { - s->vt100.seq[s->vt100.state++] = -1; - } - else { - do { - if (++s->vt100.state < (int)numberof(s->vt100.seq)) { - s->vt100.seq[s->vt100.state] = 0; - } - else { - s->vt100.state = (int)numberof(s->vt100.seq); - } - } while (0); - if (wc != L';') { - constat_apply(h, s, wc); - s->vt100.state = constat_init; - } - } - rest = 0; - } - else if ((rest = *lenp - len) < MAXSIZE_CONSOLE_WRITING) { - continue; - } - *ptrp = ptr; - *lenp = len; - return rest; + WCHAR wc = *ptr++; + if (wc == 0x1b) { + rest = *lenp - len - 1; + if (s->vt100.state == constat_esc) { + rest++; /* reuse this ESC */ + } + s->vt100.state = constat_init; + if (len > 0 && *ptr != L'[') continue; + s->vt100.state = constat_esc; + } + else if (s->vt100.state == constat_esc) { + if (wc != L'[') { + /* TODO: supply dropped ESC at beginning */ + s->vt100.state = constat_init; + continue; + } + rest = *lenp - len - 1; + if (rest > 0) --rest; + s->vt100.state = constat_seq; + s->vt100.seq[0] = 0; + } + else if (s->vt100.state >= constat_seq) { + if (wc >= L'0' && wc <= L'9') { + if (s->vt100.state < (int)numberof(s->vt100.seq)) { + int *seq = &s->vt100.seq[s->vt100.state]; + *seq = (*seq * 10) + (wc - L'0'); + } + } + else if (s->vt100.state == constat_seq && s->vt100.seq[0] == 0 && wc == L'?') { + s->vt100.seq[s->vt100.state++] = -1; + } + else { + do { + if (++s->vt100.state < (int)numberof(s->vt100.seq)) { + s->vt100.seq[s->vt100.state] = 0; + } + else { + s->vt100.state = (int)numberof(s->vt100.seq); + } + } while (0); + if (wc != L';') { + constat_apply(h, s, wc); + s->vt100.state = constat_init; + } + } + rest = 0; + } + else if ((rest = *lenp - len) < MAXSIZE_CONSOLE_WRITING) { + continue; + } + *ptrp = ptr; + *lenp = len; + return rest; } len = *lenp; *ptrp = ptr; @@ -7020,17 +7020,17 @@ rb_w32_close(int fd) int save_errno = errno; if (!is_socket(sock)) { - UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN); - constat_delete((HANDLE)sock); - return _close(fd); + UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN); + constat_delete((HANDLE)sock); + return _close(fd); } _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE); socklist_delete(&sock, NULL); _close(fd); errno = save_errno; if (closesocket(sock) == SOCKET_ERROR) { - errno = map_errno(WSAGetLastError()); - return -1; + errno = map_errno(WSAGetLastError()); + return -1; } return 0; } @@ -7040,30 +7040,30 @@ setup_overlapped(OVERLAPPED *ol, int fd, int iswrite) { memset(ol, 0, sizeof(*ol)); if (!(_osfile(fd) & (FDEV | FPIPE))) { - LONG high = 0; - /* On mode:a, it can write only FILE_END. - * On mode:a+, though it can write only FILE_END, - * it can read from everywhere. - */ - DWORD method = ((_osfile(fd) & FAPPEND) && iswrite) ? FILE_END : FILE_CURRENT; - DWORD low = SetFilePointer((HANDLE)_osfhnd(fd), 0, &high, method); + LONG high = 0; + /* On mode:a, it can write only FILE_END. + * On mode:a+, though it can write only FILE_END, + * it can read from everywhere. + */ + DWORD method = ((_osfile(fd) & FAPPEND) && iswrite) ? FILE_END : FILE_CURRENT; + DWORD low = SetFilePointer((HANDLE)_osfhnd(fd), 0, &high, method); #ifndef INVALID_SET_FILE_POINTER #define INVALID_SET_FILE_POINTER ((DWORD)-1) #endif - if (low == INVALID_SET_FILE_POINTER) { - DWORD err = GetLastError(); - if (err != NO_ERROR) { - errno = map_errno(err); - return -1; - } - } - ol->Offset = low; - ol->OffsetHigh = high; + if (low == INVALID_SET_FILE_POINTER) { + DWORD err = GetLastError(); + if (err != NO_ERROR) { + errno = map_errno(err); + return -1; + } + } + ol->Offset = low; + ol->OffsetHigh = high; } ol->hEvent = CreateEvent(NULL, TRUE, TRUE, NULL); if (!ol->hEvent) { - errno = map_errno(GetLastError()); - return -1; + errno = map_errno(GetLastError()); + return -1; } return 0; } @@ -7074,11 +7074,11 @@ finish_overlapped(OVERLAPPED *ol, int fd, DWORD size) CloseHandle(ol->hEvent); if (!(_osfile(fd) & (FDEV | FPIPE))) { - LONG high = ol->OffsetHigh; - DWORD low = ol->Offset + size; - if (low < ol->Offset) - ++high; - SetFilePointer((HANDLE)_osfhnd(fd), low, &high, FILE_BEGIN); + LONG high = ol->OffsetHigh; + DWORD low = ol->Offset + size; + if (low < ol->Offset) + ++high; + SetFilePointer((HANDLE)_osfhnd(fd), low, &high, FILE_BEGIN); } } @@ -7099,121 +7099,121 @@ rb_w32_read(int fd, void *buf, size_t size) int start = 0; if (is_socket(sock)) - return rb_w32_recv(fd, buf, size, 0); + return rb_w32_recv(fd, buf, size, 0); // validate fd by using _get_osfhandle() because we cannot access _nhandle if (_get_osfhandle(fd) == -1) { - return -1; + return -1; } if (_osfile(fd) & FTEXT) { - return _read(fd, buf, size); + return _read(fd, buf, size); } rb_acrt_lowio_lock_fh(fd); if (!size || _osfile(fd) & FEOFLAG) { - _set_osflags(fd, _osfile(fd) & ~FEOFLAG); - rb_acrt_lowio_unlock_fh(fd); - return 0; + _set_osflags(fd, _osfile(fd) & ~FEOFLAG); + rb_acrt_lowio_unlock_fh(fd); + return 0; } ret = 0; isconsole = is_console(_osfhnd(fd)) && (osver.dwMajorVersion < 6 || (osver.dwMajorVersion == 6 && osver.dwMinorVersion < 2)); if (isconsole) { - DWORD mode; - GetConsoleMode((HANDLE)_osfhnd(fd),&mode); - islineinput = (mode & ENABLE_LINE_INPUT) != 0; + DWORD mode; + GetConsoleMode((HANDLE)_osfhnd(fd),&mode); + islineinput = (mode & ENABLE_LINE_INPUT) != 0; } retry: /* get rid of console reading bug */ if (isconsole) { - constat_reset((HANDLE)_osfhnd(fd)); - if (start) - len = 1; - else { - len = 0; - start = 1; - } + constat_reset((HANDLE)_osfhnd(fd)); + if (start) + len = 1; + else { + len = 0; + start = 1; + } } else - len = size; + len = size; size -= len; if (setup_overlapped(&ol, fd, FALSE)) { - rb_acrt_lowio_unlock_fh(fd); - return -1; + rb_acrt_lowio_unlock_fh(fd); + return -1; } if (!ReadFile((HANDLE)_osfhnd(fd), buf, len, &read, &ol)) { - err = GetLastError(); - if (err == ERROR_NO_DATA && (_osfile(fd) & FPIPE)) { - DWORD state; - if (GetNamedPipeHandleState((HANDLE)_osfhnd(fd), &state, NULL, NULL, NULL, NULL, 0) && (state & PIPE_NOWAIT)) { - errno = EWOULDBLOCK; - } - else { - errno = map_errno(err); - } - rb_acrt_lowio_unlock_fh(fd); - return -1; - } - else if (err != ERROR_IO_PENDING) { - CloseHandle(ol.hEvent); - if (err == ERROR_ACCESS_DENIED) - errno = EBADF; - else if (err == ERROR_BROKEN_PIPE || err == ERROR_HANDLE_EOF) { - rb_acrt_lowio_unlock_fh(fd); - return 0; - } - else - errno = map_errno(err); + err = GetLastError(); + if (err == ERROR_NO_DATA && (_osfile(fd) & FPIPE)) { + DWORD state; + if (GetNamedPipeHandleState((HANDLE)_osfhnd(fd), &state, NULL, NULL, NULL, NULL, 0) && (state & PIPE_NOWAIT)) { + errno = EWOULDBLOCK; + } + else { + errno = map_errno(err); + } + rb_acrt_lowio_unlock_fh(fd); + return -1; + } + else if (err != ERROR_IO_PENDING) { + CloseHandle(ol.hEvent); + if (err == ERROR_ACCESS_DENIED) + errno = EBADF; + else if (err == ERROR_BROKEN_PIPE || err == ERROR_HANDLE_EOF) { + rb_acrt_lowio_unlock_fh(fd); + return 0; + } + else + errno = map_errno(err); - rb_acrt_lowio_unlock_fh(fd); - return -1; - } + rb_acrt_lowio_unlock_fh(fd); + return -1; + } - wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE); - if (wait != WAIT_OBJECT_0) { - if (wait == WAIT_OBJECT_0 + 1) - errno = EINTR; - else - errno = map_errno(GetLastError()); - CloseHandle(ol.hEvent); - CancelIo((HANDLE)_osfhnd(fd)); - rb_acrt_lowio_unlock_fh(fd); - return -1; - } + wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE); + if (wait != WAIT_OBJECT_0) { + if (wait == WAIT_OBJECT_0 + 1) + errno = EINTR; + else + errno = map_errno(GetLastError()); + CloseHandle(ol.hEvent); + CancelIo((HANDLE)_osfhnd(fd)); + rb_acrt_lowio_unlock_fh(fd); + return -1; + } - if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &read, TRUE) && - (err = GetLastError()) != ERROR_HANDLE_EOF) { - int ret = 0; - if (err != ERROR_BROKEN_PIPE) { - errno = map_errno(err); - ret = -1; - } - CloseHandle(ol.hEvent); - CancelIo((HANDLE)_osfhnd(fd)); - rb_acrt_lowio_unlock_fh(fd); - return ret; - } + if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &read, TRUE) && + (err = GetLastError()) != ERROR_HANDLE_EOF) { + int ret = 0; + if (err != ERROR_BROKEN_PIPE) { + errno = map_errno(err); + ret = -1; + } + CloseHandle(ol.hEvent); + CancelIo((HANDLE)_osfhnd(fd)); + rb_acrt_lowio_unlock_fh(fd); + return ret; + } } else { - err = GetLastError(); - errno = map_errno(err); + err = GetLastError(); + errno = map_errno(err); } finish_overlapped(&ol, fd, read); ret += read; if (read >= len) { - buf = (char *)buf + read; - if (err != ERROR_OPERATION_ABORTED && - !(isconsole && len == 1 && (!islineinput || *((char *)buf - 1) == '\n')) && size > 0) - goto retry; + buf = (char *)buf + read; + if (err != ERROR_OPERATION_ABORTED && + !(isconsole && len == 1 && (!islineinput || *((char *)buf - 1) == '\n')) && size > 0) + goto retry; } if (read == 0) - _set_osflags(fd, _osfile(fd) | FEOFLAG); + _set_osflags(fd, _osfile(fd) | FEOFLAG); rb_acrt_lowio_unlock_fh(fd); @@ -7235,27 +7235,27 @@ rb_w32_write(int fd, const void *buf, size_t size) OVERLAPPED ol; if (is_socket(sock)) - return rb_w32_send(fd, buf, size, 0); + return rb_w32_send(fd, buf, size, 0); // validate fd by using _get_osfhandle() because we cannot access _nhandle if (_get_osfhandle(fd) == -1) { - return -1; + return -1; } if ((_osfile(fd) & FTEXT) && (!(_osfile(fd) & FPIPE) || fd == fileno(stdout) || fd == fileno(stderr))) { - ssize_t w = _write(fd, buf, size); - if (w == (ssize_t)-1 && errno == EINVAL) { - errno = map_errno(GetLastError()); - } - return w; + ssize_t w = _write(fd, buf, size); + if (w == (ssize_t)-1 && errno == EINVAL) { + errno = map_errno(GetLastError()); + } + return w; } rb_acrt_lowio_lock_fh(fd); if (!size || _osfile(fd) & FEOFLAG) { - rb_acrt_lowio_unlock_fh(fd); - return 0; + rb_acrt_lowio_unlock_fh(fd); + return 0; } ret = 0; @@ -7265,61 +7265,61 @@ rb_w32_write(int fd, const void *buf, size_t size) retry2: if (setup_overlapped(&ol, fd, TRUE)) { - rb_acrt_lowio_unlock_fh(fd); - return -1; + rb_acrt_lowio_unlock_fh(fd); + return -1; } if (!WriteFile((HANDLE)_osfhnd(fd), buf, len, &written, &ol)) { - err = GetLastError(); - if (err != ERROR_IO_PENDING) { - CloseHandle(ol.hEvent); - if (err == ERROR_ACCESS_DENIED) - errno = EBADF; - else - errno = map_errno(err); + err = GetLastError(); + if (err != ERROR_IO_PENDING) { + CloseHandle(ol.hEvent); + if (err == ERROR_ACCESS_DENIED) + errno = EBADF; + else + errno = map_errno(err); - rb_acrt_lowio_unlock_fh(fd); - return -1; - } + rb_acrt_lowio_unlock_fh(fd); + return -1; + } - wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE); - if (wait != WAIT_OBJECT_0) { - if (wait == WAIT_OBJECT_0 + 1) - errno = EINTR; - else - errno = map_errno(GetLastError()); - CloseHandle(ol.hEvent); - CancelIo((HANDLE)_osfhnd(fd)); - rb_acrt_lowio_unlock_fh(fd); - return -1; - } + wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE); + if (wait != WAIT_OBJECT_0) { + if (wait == WAIT_OBJECT_0 + 1) + errno = EINTR; + else + errno = map_errno(GetLastError()); + CloseHandle(ol.hEvent); + CancelIo((HANDLE)_osfhnd(fd)); + rb_acrt_lowio_unlock_fh(fd); + return -1; + } - if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &written, TRUE)) { - errno = map_errno(GetLastError()); - CloseHandle(ol.hEvent); - CancelIo((HANDLE)_osfhnd(fd)); - rb_acrt_lowio_unlock_fh(fd); - return -1; - } + if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &written, TRUE)) { + errno = map_errno(GetLastError()); + CloseHandle(ol.hEvent); + CancelIo((HANDLE)_osfhnd(fd)); + rb_acrt_lowio_unlock_fh(fd); + return -1; + } } finish_overlapped(&ol, fd, written); ret += written; if (written == len) { - buf = (const char *)buf + len; - if (size > 0) - goto retry; + buf = (const char *)buf + len; + if (size > 0) + goto retry; } if (ret == 0) { - size_t newlen = len / 2; - if (newlen > 0) { - size += len - newlen; - len = newlen; - goto retry2; - } - ret = -1; - errno = EWOULDBLOCK; + size_t newlen = len / 2; + if (newlen > 0) { + size += len - newlen; + len = newlen; + goto retry2; + } + ret = -1; + errno = EWOULDBLOCK; } rb_acrt_lowio_unlock_fh(fd); @@ -7342,48 +7342,48 @@ rb_w32_write_console(uintptr_t strarg, int fd) handle = (HANDLE)_osfhnd(fd); if (!GetConsoleMode(handle, &dwMode)) - return -1L; + return -1L; s = constat_handle(handle); if (!s) return -1L; encindex = ENCODING_GET(str); switch (encindex) { default: - if (!rb_econv_has_convpath_p(rb_enc_name(rb_enc_from_index(encindex)), "UTF-8")) - return -1L; - str = rb_str_conv_enc_opts(str, NULL, rb_enc_from_index(ENCINDEX_UTF_8), - ECONV_INVALID_REPLACE|ECONV_UNDEF_REPLACE, Qnil); - /* fall through */ + if (!rb_econv_has_convpath_p(rb_enc_name(rb_enc_from_index(encindex)), "UTF-8")) + return -1L; + str = rb_str_conv_enc_opts(str, NULL, rb_enc_from_index(ENCINDEX_UTF_8), + ECONV_INVALID_REPLACE|ECONV_UNDEF_REPLACE, Qnil); + /* fall through */ case ENCINDEX_US_ASCII: case ENCINDEX_ASCII_8BIT: - /* assume UTF-8 */ + /* assume UTF-8 */ case ENCINDEX_UTF_8: - ptr = wbuffer = mbstr_to_wstr(CP_UTF8, RSTRING_PTR(str), RSTRING_LEN(str), &len); - if (!ptr) return -1L; - break; + ptr = wbuffer = mbstr_to_wstr(CP_UTF8, RSTRING_PTR(str), RSTRING_LEN(str), &len); + if (!ptr) return -1L; + break; case ENCINDEX_UTF_16LE: - ptr = (const WCHAR *)RSTRING_PTR(str); - len = RSTRING_LEN(str) / sizeof(WCHAR); - break; + ptr = (const WCHAR *)RSTRING_PTR(str); + len = RSTRING_LEN(str) / sizeof(WCHAR); + break; } reslen = 0; if (dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) { - if (!WriteConsoleW(handle, ptr, len, &reslen, NULL)) - reslen = (DWORD)-1L; + if (!WriteConsoleW(handle, ptr, len, &reslen, NULL)) + reslen = (DWORD)-1L; } else { - while (len > 0) { - long curlen = constat_parse(handle, s, (next = ptr, &next), &len); - reslen += next - ptr; - if (curlen > 0) { - DWORD written; - if (!WriteConsoleW(handle, ptr, curlen, &written, NULL)) { - reslen = (DWORD)-1L; - break; - } - } - ptr = next; - } + while (len > 0) { + long curlen = constat_parse(handle, s, (next = ptr, &next), &len); + reslen += next - ptr; + if (curlen > 0) { + DWORD written; + if (!WriteConsoleW(handle, ptr, curlen, &written, NULL)) { + reslen = (DWORD)-1L; + break; + } + } + ptr = next; + } } RB_GC_GUARD(str); if (wbuffer) free(wbuffer); @@ -7428,50 +7428,50 @@ wutimensat(int dirfd, const WCHAR *path, const struct timespec *times, int flags /* TODO: When path is absolute, dirfd should be ignored. */ if (dirfd != AT_FDCWD) { - errno = ENOSYS; - return -1; + errno = ENOSYS; + return -1; } if (flags != 0) { - errno = EINVAL; /* AT_SYMLINK_NOFOLLOW isn't supported. */ - return -1; + errno = EINVAL; /* AT_SYMLINK_NOFOLLOW isn't supported. */ + return -1; } if (wstati128(path, &stat, FALSE)) { - return -1; + return -1; } if (times) { - if (timespec_to_filetime(×[0], &atime)) { - return -1; - } - if (timespec_to_filetime(×[1], &mtime)) { - return -1; - } + if (timespec_to_filetime(×[0], &atime)) { + return -1; + } + if (timespec_to_filetime(×[1], &mtime)) { + return -1; + } } else { - get_systemtime(&atime); - mtime = atime; + get_systemtime(&atime); + mtime = atime; } RUBY_CRITICAL { - const DWORD attr = GetFileAttributesW(path); - if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) - SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY); - hFile = open_special(path, GENERIC_WRITE, 0); - if (hFile == INVALID_HANDLE_VALUE) { - errno = map_errno(GetLastError()); - ret = -1; - } - else { - if (!SetFileTime(hFile, NULL, &atime, &mtime)) { - errno = map_errno(GetLastError()); - ret = -1; - } - CloseHandle(hFile); - } - if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) - SetFileAttributesW(path, attr); + const DWORD attr = GetFileAttributesW(path); + if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) + SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY); + hFile = open_special(path, GENERIC_WRITE, 0); + if (hFile == INVALID_HANDLE_VALUE) { + errno = map_errno(GetLastError()); + ret = -1; + } + else { + if (!SetFileTime(hFile, NULL, &atime, &mtime)) { + errno = map_errno(GetLastError()); + ret = -1; + } + CloseHandle(hFile); + } + if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) + SetFileAttributesW(path, attr); } return ret; @@ -7485,8 +7485,8 @@ w32_utimensat(int dirfd, const char *path, const struct timespec *times, int fla int ret = -1; if (wpath) { - ret = wutimensat(dirfd, wpath, times, flags); - free(wpath); + ret = wutimensat(dirfd, wpath, times, flags); + free(wpath); } return ret; } @@ -7565,7 +7565,7 @@ rb_w32_uchdir(const char *path) int ret; if (!(wpath = utf8_to_wstr(path, NULL))) - return -1; + return -1; ret = _wchdir(wpath); free(wpath); return ret; @@ -7578,15 +7578,15 @@ wmkdir(const WCHAR *wpath, int mode) int ret = -1; RUBY_CRITICAL do { - if (CreateDirectoryW(wpath, NULL) == FALSE) { - errno = map_errno(GetLastError()); - break; - } - if (_wchmod(wpath, mode) == -1) { - RemoveDirectoryW(wpath); - break; - } - ret = 0; + if (CreateDirectoryW(wpath, NULL) == FALSE) { + errno = map_errno(GetLastError()); + break; + } + if (_wchmod(wpath, mode) == -1) { + RemoveDirectoryW(wpath); + break; + } + ret = 0; } while (0); return ret; } @@ -7599,7 +7599,7 @@ rb_w32_umkdir(const char *path, int mode) int ret; if (!(wpath = utf8_to_wstr(path, NULL))) - return -1; + return -1; ret = wmkdir(wpath, mode); free(wpath); return ret; @@ -7613,7 +7613,7 @@ rb_w32_mkdir(const char *path, int mode) int ret; if (!(wpath = filecp_to_wstr(path, NULL))) - return -1; + return -1; ret = wmkdir(wpath, mode); free(wpath); return ret; @@ -7625,17 +7625,17 @@ wrmdir(const WCHAR *wpath) { int ret = 0; RUBY_CRITICAL { - const DWORD attr = GetFileAttributesW(wpath); - if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) { - SetFileAttributesW(wpath, attr & ~FILE_ATTRIBUTE_READONLY); - } - if (RemoveDirectoryW(wpath) == FALSE) { - errno = map_errno(GetLastError()); - ret = -1; - if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) { - SetFileAttributesW(wpath, attr); - } - } + const DWORD attr = GetFileAttributesW(wpath); + if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) { + SetFileAttributesW(wpath, attr & ~FILE_ATTRIBUTE_READONLY); + } + if (RemoveDirectoryW(wpath) == FALSE) { + errno = map_errno(GetLastError()); + ret = -1; + if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) { + SetFileAttributesW(wpath, attr); + } + } } return ret; } @@ -7648,7 +7648,7 @@ rb_w32_rmdir(const char *path) int ret; if (!(wpath = filecp_to_wstr(path, NULL))) - return -1; + return -1; ret = wrmdir(wpath); free(wpath); return ret; @@ -7662,7 +7662,7 @@ rb_w32_urmdir(const char *path) int ret; if (!(wpath = utf8_to_wstr(path, NULL))) - return -1; + return -1; ret = wrmdir(wpath); free(wpath); return ret; @@ -7675,25 +7675,25 @@ wunlink(const WCHAR *path) int ret = 0; const DWORD SYMLINKD = FILE_ATTRIBUTE_REPARSE_POINT|FILE_ATTRIBUTE_DIRECTORY; RUBY_CRITICAL { - const DWORD attr = GetFileAttributesW(path); - if (attr == (DWORD)-1) { - } - else if ((attr & SYMLINKD) == SYMLINKD) { - ret = RemoveDirectoryW(path); - } - else { - if (attr & FILE_ATTRIBUTE_READONLY) { - SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY); - } - ret = DeleteFileW(path); - } - if (!ret) { - errno = map_errno(GetLastError()); - ret = -1; - if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) { - SetFileAttributesW(path, attr); - } - } + const DWORD attr = GetFileAttributesW(path); + if (attr == (DWORD)-1) { + } + else if ((attr & SYMLINKD) == SYMLINKD) { + ret = RemoveDirectoryW(path); + } + else { + if (attr & FILE_ATTRIBUTE_READONLY) { + SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY); + } + ret = DeleteFileW(path); + } + if (!ret) { + errno = map_errno(GetLastError()); + ret = -1; + if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) { + SetFileAttributesW(path, attr); + } + } } return ret; } @@ -7706,7 +7706,7 @@ rb_w32_uunlink(const char *path) int ret; if (!(wpath = utf8_to_wstr(path, NULL))) - return -1; + return -1; ret = wunlink(wpath); free(wpath); return ret; @@ -7720,7 +7720,7 @@ rb_w32_unlink(const char *path) int ret; if (!(wpath = filecp_to_wstr(path, NULL))) - return -1; + return -1; ret = wunlink(wpath); free(wpath); return ret; @@ -7734,7 +7734,7 @@ rb_w32_uchmod(const char *path, int mode) int ret; if (!(wpath = utf8_to_wstr(path, NULL))) - return -1; + return -1; ret = _wchmod(wpath, mode); free(wpath); return ret; @@ -7745,39 +7745,39 @@ int fchmod(int fd, int mode) { typedef BOOL (WINAPI *set_file_information_by_handle_func) - (HANDLE, int, void*, DWORD); + (HANDLE, int, void*, DWORD); static set_file_information_by_handle_func set_file_info = - (set_file_information_by_handle_func)-1; + (set_file_information_by_handle_func)-1; /* from winbase.h of the mingw-w64 runtime package. */ struct { - LARGE_INTEGER CreationTime; - LARGE_INTEGER LastAccessTime; - LARGE_INTEGER LastWriteTime; - LARGE_INTEGER ChangeTime; - DWORD FileAttributes; + LARGE_INTEGER CreationTime; + LARGE_INTEGER LastAccessTime; + LARGE_INTEGER LastWriteTime; + LARGE_INTEGER ChangeTime; + DWORD FileAttributes; } info = {{{0}}, {{0}}, {{0}},}; /* fields with 0 are unchanged */ HANDLE h = (HANDLE)_get_osfhandle(fd); if (h == INVALID_HANDLE_VALUE) { - errno = EBADF; - return -1; + errno = EBADF; + return -1; } if (set_file_info == (set_file_information_by_handle_func)-1) { - /* Since Windows Vista and Windows Server 2008 */ - set_file_info = (set_file_information_by_handle_func) - get_proc_address("kernel32", "SetFileInformationByHandle", NULL); + /* Since Windows Vista and Windows Server 2008 */ + set_file_info = (set_file_information_by_handle_func) + get_proc_address("kernel32", "SetFileInformationByHandle", NULL); } if (!set_file_info) { - errno = ENOSYS; - return -1; + errno = ENOSYS; + return -1; } info.FileAttributes = FILE_ATTRIBUTE_NORMAL; if (!(mode & 0200)) info.FileAttributes |= FILE_ATTRIBUTE_READONLY; if (!set_file_info(h, 0, &info, sizeof(info))) { - errno = map_errno(GetLastError()); - return -1; + errno = map_errno(GetLastError()); + return -1; } return 0; } @@ -7790,11 +7790,11 @@ rb_w32_isatty(int fd) // validate fd by using _get_osfhandle() because we cannot access _nhandle if (_get_osfhandle(fd) == -1) { - return 0; + return 0; } if (!GetConsoleMode((HANDLE)_osfhnd(fd), &mode)) { - errno = ENOTTY; - return 0; + errno = ENOTTY; + return 0; } return 1; } @@ -7833,14 +7833,14 @@ rb_w32_inet_ntop(int af, const void *addr, char *numaddr, size_t numaddr_len) typedef char *(WSAAPI inet_ntop_t)(int, void *, char *, size_t); static inet_ntop_t *pInetNtop = (inet_ntop_t *)-1; if (pInetNtop == (inet_ntop_t *)-1) - pInetNtop = (inet_ntop_t *)get_proc_address("ws2_32", "inet_ntop", NULL); + pInetNtop = (inet_ntop_t *)get_proc_address("ws2_32", "inet_ntop", NULL); if (pInetNtop) { - return pInetNtop(af, (void *)addr, numaddr, numaddr_len); + return pInetNtop(af, (void *)addr, numaddr, numaddr_len); } else { - struct in_addr in; - memcpy(&in.s_addr, addr, sizeof(in.s_addr)); - snprintf(numaddr, numaddr_len, "%s", inet_ntoa(in)); + struct in_addr in; + memcpy(&in.s_addr, addr, sizeof(in.s_addr)); + snprintf(numaddr, numaddr_len, "%s", inet_ntoa(in)); } return numaddr; } @@ -7852,9 +7852,9 @@ rb_w32_inet_pton(int af, const char *src, void *dst) typedef int (WSAAPI inet_pton_t)(int, const char*, void *); static inet_pton_t *pInetPton = (inet_pton_t *)-1; if (pInetPton == (inet_pton_t *)-1) - pInetPton = (inet_pton_t *)get_proc_address("ws2_32", "inet_pton", NULL); + pInetPton = (inet_pton_t *)get_proc_address("ws2_32", "inet_pton", NULL); if (pInetPton) { - return pInetPton(af, src, dst); + return pInetPton(af, src, dst); } return 0; } @@ -7891,14 +7891,14 @@ systemtime_to_tm(const SYSTEMTIME *st, struct tm *t) t->tm_wday = st->wDayOfWeek; switch (m) { case 1: - break; + break; case 2: - d += 31; - break; + d += 31; + break; default: - d += 31 + 28 + (!(y % 4) && ((y % 100) || !(y % 400))); - d += ((m - 3) * 153 + 2) / 5; - break; + d += 31 + 28 + (!(y % 4) && ((y % 100) || !(y % 400))); + d += ((m - 3) * 153 + 2) / 5; + break; } t->tm_yday = d - 1; } @@ -7912,8 +7912,8 @@ systemtime_to_localtime(TIME_ZONE_INFORMATION *tz, SYSTEMTIME *gst, SYSTEMTIME * if (!SystemTimeToTzSpecificLocalTime(tz, gst, lst)) return -1; if (!tz) { - GetTimeZoneInformation(&stdtz); - tz = &stdtz; + GetTimeZoneInformation(&stdtz); + tz = &stdtz; } if (tz->StandardBias == tz->DaylightBias) return 0; if (!tz->StandardDate.wMonth) return 0; @@ -7923,7 +7923,7 @@ systemtime_to_localtime(TIME_ZONE_INFORMATION *tz, SYSTEMTIME *gst, SYSTEMTIME * stdtz.StandardDate.wMonth = stdtz.DaylightDate.wMonth = 0; if (!SystemTimeToTzSpecificLocalTime(&stdtz, gst, &sst)) return 0; if (lst->wMinute == sst.wMinute && lst->wHour == sst.wHour) - return 0; + return 0; return 1; } #endif @@ -7948,18 +7948,18 @@ gmtime_r(const time_t *tp, struct tm *rp) int e = EINVAL; if (!tp || !rp) { error: - errno = e; - return NULL; + errno = e; + return NULL; } #if RUBY_MSVCRT_VERSION >= 80 || defined(HAVE__GMTIME64_S) e = gmtime_s(rp, tp); if (e != 0) goto error; #else { - SYSTEMTIME st; - if (unixtime_to_systemtime(*tp, &st)) goto error; - rp->tm_isdst = 0; - systemtime_to_tm(&st, rp); + SYSTEMTIME st; + if (unixtime_to_systemtime(*tp, &st)) goto error; + rp->tm_isdst = 0; + systemtime_to_tm(&st, rp); } #endif return rp; @@ -7972,18 +7972,18 @@ localtime_r(const time_t *tp, struct tm *rp) int e = EINVAL; if (!tp || !rp) { error: - errno = e; - return NULL; + errno = e; + return NULL; } #if RUBY_MSVCRT_VERSION >= 80 || defined(HAVE__LOCALTIME64_S) e = localtime_s(rp, tp); if (e) goto error; #else { - SYSTEMTIME gst, lst; - if (unixtime_to_systemtime(*tp, &gst)) goto error; - rp->tm_isdst = systemtime_to_localtime(NULL, &gst, &lst); - systemtime_to_tm(&lst, rp); + SYSTEMTIME gst, lst; + if (unixtime_to_systemtime(*tp, &gst)) goto error; + rp->tm_isdst = systemtime_to_localtime(NULL, &gst, &lst); + systemtime_to_tm(&lst, rp); } #endif return rp; @@ -8018,11 +8018,11 @@ rb_w32_unwrap_io_handle(int fd) SOCKET sock = TO_SOCKET(fd); _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE); if (!is_socket(sock)) { - UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN); - constat_delete((HANDLE)sock); + UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN); + constat_delete((HANDLE)sock); } else { - socklist_delete(&sock, NULL); + socklist_delete(&sock, NULL); } return _close(fd); } @@ -8049,8 +8049,8 @@ rb_w32_pow(double x, double y) typedef struct { BOOL file_id_p; union { - BY_HANDLE_FILE_INFORMATION bhfi; - FILE_ID_INFO fii; + BY_HANDLE_FILE_INFORMATION bhfi; + FILE_ID_INFO fii; } info; } w32_io_info_t; @@ -8062,48 +8062,48 @@ w32_io_info(VALUE *file, w32_io_info_t *st) tmp = rb_check_convert_type_with_id(*file, T_FILE, "IO", idTo_io); if (!NIL_P(tmp)) { - rb_io_t *fptr; + rb_io_t *fptr; - GetOpenFile(tmp, fptr); - f = (HANDLE)rb_w32_get_osfhandle(fptr->fd); - if (f == (HANDLE)-1) return INVALID_HANDLE_VALUE; + GetOpenFile(tmp, fptr); + f = (HANDLE)rb_w32_get_osfhandle(fptr->fd); + if (f == (HANDLE)-1) return INVALID_HANDLE_VALUE; } else { - VALUE tmp; - WCHAR *ptr; - int len; - VALUE v; + VALUE tmp; + WCHAR *ptr; + int len; + VALUE v; - FilePathValue(*file); - tmp = rb_str_encode_ospath(*file); - len = MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, NULL, 0); - ptr = ALLOCV_N(WCHAR, v, len); - MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, ptr, len); - f = CreateFileW(ptr, 0, - FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS, NULL); - ALLOCV_END(v); - if (f == INVALID_HANDLE_VALUE) return f; - ret = f; + FilePathValue(*file); + tmp = rb_str_encode_ospath(*file); + len = MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, NULL, 0); + ptr = ALLOCV_N(WCHAR, v, len); + MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, ptr, len); + f = CreateFileW(ptr, 0, + FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, NULL); + ALLOCV_END(v); + if (f == INVALID_HANDLE_VALUE) return f; + ret = f; } if (GetFileType(f) == FILE_TYPE_DISK) { - DWORD err; - ZeroMemory(st, sizeof(*st)); - err = get_ino(f, &st->info.fii); - if (!err) { - st->file_id_p = TRUE; - return ret; - } - else if (err != ERROR_INVALID_PARAMETER) { - CloseHandle(f); - return INVALID_HANDLE_VALUE; - } - /* this API may not work at files on non Microsoft SMB - * server, fallback to old API then. */ - if (GetFileInformationByHandle(f, &st->info.bhfi)) { - st->file_id_p = FALSE; - return ret; - } + DWORD err; + ZeroMemory(st, sizeof(*st)); + err = get_ino(f, &st->info.fii); + if (!err) { + st->file_id_p = TRUE; + return ret; + } + else if (err != ERROR_INVALID_PARAMETER) { + CloseHandle(f); + return INVALID_HANDLE_VALUE; + } + /* this API may not work at files on non Microsoft SMB + * server, fallback to old API then. */ + if (GetFileInformationByHandle(f, &st->info.bhfi)) { + st->file_id_p = FALSE; + return ret; + } } if (ret) CloseHandle(ret); return INVALID_HANDLE_VALUE; @@ -8137,28 +8137,28 @@ rb_w32_file_identical_p(VALUE fname1, VALUE fname2) f1 = w32_io_info(&fname1, &st1); if (f1 == INVALID_HANDLE_VALUE) return Qfalse; if (f1) { - struct w32_io_info_args arg; - arg.fname = &fname2; - arg.st = &st2; - f2 = (HANDLE)rb_ensure(call_w32_io_info, (VALUE)&arg, close_handle, (VALUE)f1); + struct w32_io_info_args arg; + arg.fname = &fname2; + arg.st = &st2; + f2 = (HANDLE)rb_ensure(call_w32_io_info, (VALUE)&arg, close_handle, (VALUE)f1); } else { - f2 = w32_io_info(&fname2, &st2); + f2 = w32_io_info(&fname2, &st2); } if (f2 == INVALID_HANDLE_VALUE) return Qfalse; if (f2) CloseHandle(f2); if (st1.file_id_p != st2.file_id_p) return Qfalse; if (!st1.file_id_p) { - if (st1.info.bhfi.dwVolumeSerialNumber == st2.info.bhfi.dwVolumeSerialNumber && - st1.info.bhfi.nFileIndexHigh == st2.info.bhfi.nFileIndexHigh && - st1.info.bhfi.nFileIndexLow == st2.info.bhfi.nFileIndexLow) - return Qtrue; + if (st1.info.bhfi.dwVolumeSerialNumber == st2.info.bhfi.dwVolumeSerialNumber && + st1.info.bhfi.nFileIndexHigh == st2.info.bhfi.nFileIndexHigh && + st1.info.bhfi.nFileIndexLow == st2.info.bhfi.nFileIndexLow) + return Qtrue; } else { - if (st1.info.fii.VolumeSerialNumber == st2.info.fii.VolumeSerialNumber && - memcmp(&st1.info.fii.FileId, &st2.info.fii.FileId, sizeof(FILE_ID_128)) == 0) - return Qtrue; + if (st1.info.fii.VolumeSerialNumber == st2.info.fii.VolumeSerialNumber && + memcmp(&st1.info.fii.FileId, &st2.info.fii.FileId, sizeof(FILE_ID_128)) == 0) + return Qtrue; } return Qfalse; } @@ -8169,14 +8169,14 @@ rb_w32_set_thread_description(HANDLE th, const WCHAR *name) int result = FALSE; typedef HRESULT (WINAPI *set_thread_description_func)(HANDLE, PCWSTR); static set_thread_description_func set_thread_description = - (set_thread_description_func)-1; + (set_thread_description_func)-1; if (set_thread_description == (set_thread_description_func)-1) { - /* Since Windows 10, version 1607 and Windows Server 2016 */ - set_thread_description = (set_thread_description_func) - get_proc_address("kernel32", "SetThreadDescription", NULL); + /* Since Windows 10, version 1607 and Windows Server 2016 */ + set_thread_description = (set_thread_description_func) + get_proc_address("kernel32", "SetThreadDescription", NULL); } if (set_thread_description) { - result = set_thread_description(th, name); + result = set_thread_description(th, name); } return result; } @@ -8188,18 +8188,18 @@ rb_w32_set_thread_description_str(HANDLE th, VALUE name) WCHAR *s; if (NIL_P(name)) { - return rb_w32_set_thread_description(th, L""); + return rb_w32_set_thread_description(th, L""); } s = (WCHAR *)StringValueCStr(name); idx = rb_enc_get_index(name); if (idx == ENCINDEX_UTF_16LE) { - result = rb_w32_set_thread_description(th, s); + result = rb_w32_set_thread_description(th, s); } else { - name = rb_str_conv_enc(name, rb_enc_from_index(idx), rb_utf8_encoding()); - s = mbstr_to_wstr(CP_UTF8, RSTRING_PTR(name), RSTRING_LEN(name)+1, NULL); - result = rb_w32_set_thread_description(th, s); - free(s); + name = rb_str_conv_enc(name, rb_enc_from_index(idx), rb_utf8_encoding()); + s = mbstr_to_wstr(CP_UTF8, RSTRING_PTR(name), RSTRING_LEN(name)+1, NULL); + result = rb_w32_set_thread_description(th, s); + free(s); } RB_GC_GUARD(name); return result;