carray 3.0.5 → 3.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +343 -0
  3. data/README.md +25 -4
  4. data/carray.gemspec +3 -2
  5. data/ext/ca_axis_dispatch.c +6 -0
  6. data/ext/ca_axis_group.c +7 -7
  7. data/ext/ca_binop_dispatch.c +8 -0
  8. data/ext/ca_binop_dispatch.h +1 -0
  9. data/ext/ca_categorical_iterator.c +14 -14
  10. data/ext/ca_kernel_iterator.c +116 -231
  11. data/ext/ca_kernel_iterator.h +416 -258
  12. data/ext/ca_obj_array.c +4 -4
  13. data/ext/ca_obj_bincmp.c +28 -4
  14. data/ext/ca_obj_binop.c +46 -12
  15. data/ext/ca_obj_bitarray.c +2 -4
  16. data/ext/ca_obj_bitfield.c +88 -4
  17. data/ext/ca_obj_byte_swap.c +4 -4
  18. data/ext/ca_obj_const_string.c +422 -257
  19. data/ext/ca_obj_face.c +73 -33
  20. data/ext/ca_obj_fake.c +114 -13
  21. data/ext/ca_obj_farray.c +7 -1
  22. data/ext/ca_obj_fixlen_string.c +51 -17
  23. data/ext/ca_obj_grid.c +179 -19
  24. data/ext/ca_obj_meld.c +74 -118
  25. data/ext/ca_obj_moncmp.c +9 -1
  26. data/ext/ca_obj_monop.c +100 -36
  27. data/ext/ca_obj_object.c +63 -29
  28. data/ext/ca_obj_reduce.c +17 -5
  29. data/ext/ca_obj_refer.c +162 -23
  30. data/ext/ca_obj_remap.c +69 -10
  31. data/ext/ca_obj_repeat.c +1 -1
  32. data/ext/ca_obj_roll.c +3 -4
  33. data/ext/ca_obj_select.c +12 -7
  34. data/ext/ca_obj_select_axis.c +9 -6
  35. data/ext/ca_obj_shift.c +1 -0
  36. data/ext/ca_obj_stack.c +315 -116
  37. data/ext/ca_obj_stride.c +177 -53
  38. data/ext/ca_obj_string.c +20 -4
  39. data/ext/ca_obj_tile.c +3 -4
  40. data/ext/ca_obj_triop.c +24 -13
  41. data/ext/ca_obj_window.c +23 -15
  42. data/ext/ca_op_ipower.c +71 -23
  43. data/ext/ca_op_powi.h +6 -29
  44. data/ext/ca_sort_kernels.h +3 -0
  45. data/ext/ca_sweep_engine.c +90 -23
  46. data/ext/ca_sweep_engine.h +5 -6
  47. data/ext/caframe_csv_reader.c +2 -2
  48. data/ext/carray.h +5 -2
  49. data/ext/carray_access.c +125 -103
  50. data/ext/carray_address_basis.c +209 -1
  51. data/ext/carray_attribute.c +8 -0
  52. data/ext/carray_broadcast.c +5 -6
  53. data/ext/carray_build_flags.h +1 -1
  54. data/ext/carray_call_cfunc.c +5 -8
  55. data/ext/carray_cast.c +319 -48
  56. data/ext/carray_cast_func.rb +37 -5
  57. data/ext/carray_conversion.c +65 -7
  58. data/ext/carray_copy.c +24 -0
  59. data/ext/carray_core.c +874 -72
  60. data/ext/carray_count.c +28 -9
  61. data/ext/carray_element.c +22 -12
  62. data/ext/carray_factorize.c +11 -11
  63. data/ext/carray_histogram.c +27 -5
  64. data/ext/carray_index_classifier.c +7 -5
  65. data/ext/carray_internal.h +241 -12
  66. data/ext/carray_kernels_bincmp.c +2007 -3
  67. data/ext/carray_kernels_binop.c +25502 -5336
  68. data/ext/carray_kernels_init.c +22 -22
  69. data/ext/carray_kernels_monop.c +10739 -3771
  70. data/ext/carray_kernels_reduce_aggregate.c +4429 -702
  71. data/ext/carray_kernels_reduce_boolean.c +1533 -15
  72. data/ext/carray_kernels_reduce_cumulative.c +1808 -248
  73. data/ext/carray_kernels_reduce_extreme.c +4508 -511
  74. data/ext/carray_kernels_reduce_variance.c +2284 -152
  75. data/ext/carray_kernels_scan.c +240 -240
  76. data/ext/carray_kernels_search.c +4211 -264
  77. data/ext/carray_kernels_sort.c +367 -450
  78. data/ext/carray_lazy.c +63 -1
  79. data/ext/carray_loop.c +10 -3
  80. data/ext/carray_mask.c +247 -149
  81. data/ext/carray_median_percentile.c +17 -12
  82. data/ext/carray_memory_view.c +54 -29
  83. data/ext/carray_operator.c +219 -55
  84. data/ext/carray_order.c +55 -11
  85. data/ext/carray_partition.c +1 -1
  86. data/ext/carray_random.c +5 -2
  87. data/ext/carray_round.c +24 -1
  88. data/ext/carray_scatter.c +4 -0
  89. data/ext/carray_segment.c +1 -1
  90. data/ext/carray_slab.c +110 -25
  91. data/ext/carray_sort.c +7 -4
  92. data/ext/carray_sort_kernel.c +24 -0
  93. data/ext/carray_struct.c +21 -6
  94. data/ext/carray_test.c +154 -53
  95. data/ext/carray_time_text.c +8 -2
  96. data/ext/carray_utils.c +124 -54
  97. data/ext/extconf.rb +11 -0
  98. data/ext/mk_call_cfunc.rb +6 -11
  99. data/ext/mkkernel.rb +383 -121
  100. data/ext/ruby_carray.c +4 -1
  101. data/ext/version.h +4 -4
  102. data/lib/carray/attribute.rb +25 -1
  103. data/lib/carray/autoload_carray.rb +3 -3
  104. data/lib/carray/autoload_method_extension.rb +5 -3
  105. data/lib/carray/axis_group.rb +22 -13
  106. data/lib/carray/basics.rb +27 -9
  107. data/lib/carray/bincount_nd.rb +8 -2
  108. data/lib/carray/block_iterator.rb +65 -24
  109. data/lib/carray/categorical.rb +27 -16
  110. data/lib/carray/categorical_iterator.rb +4 -3
  111. data/lib/carray/complex.rb +2 -2
  112. data/lib/carray/conditional.rb +55 -6
  113. data/lib/carray/const_string.rb +74 -0
  114. data/lib/carray/construct.rb +2 -2
  115. data/lib/carray/core_extensions.rb +19 -68
  116. data/lib/carray/data_type_extension.rb +1 -0
  117. data/lib/carray/fixlen_string.rb +83 -1
  118. data/lib/carray/frame/column_verbs.rb +102 -16
  119. data/lib/carray/frame/concat.rb +50 -6
  120. data/lib/carray/frame/convert.rb +19 -0
  121. data/lib/carray/frame/csv_parser.rb +45 -36
  122. data/lib/carray/frame/describe.rb +4 -2
  123. data/lib/carray/frame/frame.rb +436 -83
  124. data/lib/carray/frame/group.rb +731 -78
  125. data/lib/carray/frame/io.rb +216 -73
  126. data/lib/carray/frame/join.rb +166 -43
  127. data/lib/carray/frame/records.rb +9 -7
  128. data/lib/carray/frame/reshape.rb +109 -11
  129. data/lib/carray/frame/sort.rb +57 -9
  130. data/lib/carray/frame/verbs.rb +448 -60
  131. data/lib/carray/frame/windows.rb +71 -9
  132. data/lib/carray/fuse_source.rb +4 -2
  133. data/lib/carray/inspect.rb +7 -2
  134. data/lib/carray/iterator.rb +40 -0
  135. data/lib/carray/key_windows.rb +10 -4
  136. data/lib/carray/lazy.rb +28 -24
  137. data/lib/carray/mask_gap_fill.rb +37 -17
  138. data/lib/carray/meld_reduce.rb +1 -1
  139. data/lib/carray/methods/bin.rb +3 -0
  140. data/lib/carray/methods/choose.rb +3 -2
  141. data/lib/carray/methods/composition.rb +1 -1
  142. data/lib/carray/methods/factorize.rb +2 -0
  143. data/lib/carray/methods/gather_nd.rb +4 -1
  144. data/lib/carray/methods/is_in.rb +23 -3
  145. data/lib/carray/methods/locate_addr.rb +63 -12
  146. data/lib/carray/methods/meshgrid.rb +3 -1
  147. data/lib/carray/methods/repeat.rb +11 -1
  148. data/lib/carray/record_order.rb +35 -6
  149. data/lib/carray/runtime.rb +57 -8
  150. data/lib/carray/segment_iterator.rb +42 -24
  151. data/lib/carray/serialize.rb +56 -17
  152. data/lib/carray/slab_iterator.rb +1 -1
  153. data/lib/carray/stack.rb +21 -9
  154. data/lib/carray/string.rb +6 -6
  155. data/lib/carray/string_operation_extension.rb +25 -4
  156. data/lib/carray/struct_builder.rb +4 -1
  157. data/lib/carray/time.rb +195 -46
  158. data/lib/carray/window_iterator.rb +64 -16
  159. data/yard-stubs/ca_obj_array.rb +26 -1
  160. data/yard-stubs/ca_obj_bitfield.rb +4 -1
  161. data/yard-stubs/ca_obj_refer.rb +3 -0
  162. data/yard-stubs/ca_obj_window.rb +2 -1
  163. data/yard-stubs/carray_access.rb +4 -2
  164. data/yard-stubs/carray_cast.rb +14 -5
  165. data/yard-stubs/carray_conversion.rb +8 -2
  166. data/yard-stubs/carray_count.rb +6 -3
  167. data/yard-stubs/carray_mask.rb +20 -1
  168. data/yard-stubs/carray_math.rb +36 -16
  169. data/yard-stubs/carray_memory_view.rb +7 -0
  170. data/yard-stubs/carray_order.rb +6 -0
  171. data/yard-stubs/carray_scatter.rb +2 -1
  172. data/yard-stubs/carray_test.rb +23 -7
  173. metadata +17 -3
data/ext/carray_core.c CHANGED
@@ -10,6 +10,7 @@
10
10
  #include "carray.h"
11
11
  #include "carray_internal.h" /* ca_lazy_arena_enter / _exit */
12
12
  #include "ca_iter_substrate.h"
13
+ #include "ca_obj_face.h"
13
14
  #include <stdarg.h>
14
15
 
15
16
  /* definition of ca_endian */
@@ -29,6 +30,10 @@ const rb_data_type_t *ca_mask_typeddata[CA_OBJ_TYPE_MAX];
29
30
  ca_operation_function_t ca_func[CA_OBJ_TYPE_MAX];
30
31
  int ca_obj_num = 0;
31
32
 
33
+ /* The number of obj_types carray installs for itself, set once
34
+ Init_carray_ext has installed them all; 0 until then. */
35
+ int ca_obj_num_builtin = 0;
36
+
32
37
  /*
33
38
  definition of validity of each data_type [1 for valid, 0 for invalid]
34
39
 
@@ -350,6 +355,14 @@ ca_install_obj_type (VALUE klass,
350
355
  sizeof(((ca_operation_function_t *) 0)->xfer_all)));
351
356
  }
352
357
 
358
+ /* ca_allocate / ca_attach / ca_sync / ca_detach call these four slots
359
+ without asking, from any path that takes a view's buffer. */
360
+ if ( ! func->allocate || ! func->attach || ! func->sync || ! func->detach ) {
361
+ rb_raise(rb_eArgError,
362
+ "ca_install_obj_type: operation table has no allocate / attach / "
363
+ "sync / detach slot");
364
+ }
365
+
353
366
  /* A refused table takes no number. */
354
367
  obj_type = ca_obj_num++;
355
368
 
@@ -811,75 +824,393 @@ ca_index2addr (void *ap, ca_size_t *idx)
811
824
 
812
825
  /* ------------------------------------------------------------------- */
813
826
 
814
- /* The cyclic reference detection should be done in
815
- + ca_fetch_addr, ca_fetch_index,
816
- + ca_store_addr, ca_store_index,
817
- to avoid the system stack error in reference of the object array.
818
- */
827
+ /* Recursion over object arrays.
819
828
 
820
- void
821
- ca_set_cyclic_check(void *ap)
829
+ A cell of an object array can hold the array itself or a view of it.
830
+ Reading such a cell, or computing over the array, would come back into
831
+ the same cells without end. Both are refused when they enter an array
832
+ that the same Ruby method is already reading or computing over, in this
833
+ thread and fiber: rb_exec_recursive keeps that record, as it does for an
834
+ Array that holds itself (Array#flatten, Array#inspect). The array is
835
+ not written to, so a frozen array, or one shared between Ractors, is
836
+ read and computed over as any other.
837
+
838
+ A read, a computation and the evaluation of a lazy expression are
839
+ recorded apart (CA_RECURSION_READ / CA_RECURSION_COMPUTE /
840
+ CA_RECURSION_EVAL): a computation reads the cells it computes over, and
841
+ a reduction over a lazy expression evaluates it. */
842
+
843
+ #define CA_RECURSION_COMPUTE 0
844
+ #define CA_RECURSION_READ 1
845
+ #define CA_RECURSION_EVAL 2
846
+
847
+ static VALUE
848
+ ca_recursion_key (CArray *ca, int kind)
822
849
  {
823
- CArray *ca = (CArray *) ap;
824
- /* ca.data_type == CA_OBJECT */
825
- if ( ca_is_object_type(ca) ) {
826
- if ( ca->flags & CA_FLAG_CYCLE_CHECK ) {
827
- rb_raise(rb_eArgError, "cyclic reference is not allowed in CArray");
850
+ /* the struct of an array is aligned, so the low two bits are free */
851
+ return ULL2NUM(((unsigned long long) (uintptr_t) ca) | (unsigned long long) kind);
852
+ }
853
+
854
+ NORETURN(static void ca_refuse_cyclic (int kind));
855
+
856
+ static void
857
+ ca_refuse_cyclic (int kind)
858
+ {
859
+ if ( kind == CA_RECURSION_COMPUTE ) {
860
+ rb_raise(rb_eArgError, "%s: cyclic reference is not allowed in CArray",
861
+ ca_calling_method_name());
862
+ }
863
+ rb_raise(rb_eArgError, "cyclic reference is not allowed in CArray");
864
+ }
865
+
866
+ typedef struct {
867
+ int n;
868
+ CArray **ops;
869
+ int kind; /* CA_RECURSION_COMPUTE or CA_RECURSION_EVAL */
870
+ int k;
871
+ VALUE (*body)(VALUE);
872
+ VALUE arg;
873
+ } ca_computing_t;
874
+
875
+ static VALUE ca_computing_next (ca_computing_t *c);
876
+
877
+ static VALUE
878
+ ca_computing_step (VALUE key, VALUE varg, int recursive)
879
+ {
880
+ (void) key;
881
+ if ( recursive ) {
882
+ ca_refuse_cyclic(CA_RECURSION_COMPUTE); /* names the method */
883
+ }
884
+ return ca_computing_next((ca_computing_t *) varg);
885
+ }
886
+
887
+ static VALUE
888
+ ca_computing_next (ca_computing_t *c)
889
+ {
890
+ while ( c->k < c->n ) {
891
+ CArray *ca = c->ops[c->k++];
892
+ int j, seen = 0;
893
+ if ( ! ca || ( c->kind == CA_RECURSION_COMPUTE && ! ca_is_object_type(ca) ) ) continue;
894
+ for ( j = 0; j < c->k - 1; j++ ) {
895
+ if ( c->ops[j] == ca ) seen = 1;
896
+ }
897
+ if ( seen ) continue;
898
+ return rb_exec_recursive(ca_computing_step,
899
+ ca_recursion_key(ca, c->kind),
900
+ (VALUE) c);
901
+ }
902
+ return c->body(c->arg);
903
+ }
904
+
905
+ static VALUE ca_recursion_probe (VALUE key, VALUE arg, int recursive);
906
+
907
+ /* Whether ca is, or reaches through its parents, a lazy node being
908
+ evaluated (recorded by ca_computing_run_nodes). A cell value that does
909
+ would come back into that evaluation when it is computed. The walk is
910
+ bounded; past the bound the value is not refused here, and is caught when
911
+ it is evaluated, as a deeper expression is. */
912
+ static int
913
+ ca_reaches_evaluating_walk (CArray *ca, int *budget)
914
+ {
915
+ if ( --(*budget) < 0 ) {
916
+ return 0;
917
+ }
918
+ if ( RTEST(rb_exec_recursive(ca_recursion_probe,
919
+ ca_recursion_key(ca, CA_RECURSION_EVAL),
920
+ Qnil)) ) {
921
+ return 1;
922
+ }
923
+ if ( ca_is_entity(ca) ) {
924
+ return 0;
925
+ }
926
+ if ( ca_test_flag(ca, CA_FLAG_MULTI_PARENTS) ) {
927
+ CAMultiParent *mp = (CAMultiParent *) ca;
928
+ int32_t k;
929
+ for ( k = 0; k < mp->n_parents; k++ ) {
930
+ if ( mp->parents[k] && ca_reaches_evaluating_walk(mp->parents[k], budget) ) {
931
+ return 1;
932
+ }
828
933
  }
829
- ca_set_flag(ca, CA_FLAG_CYCLE_CHECK);
934
+ return 0;
830
935
  }
936
+ return ((CAView *) ca)->parent
937
+ ? ca_reaches_evaluating_walk(((CAView *) ca)->parent, budget)
938
+ : 0;
831
939
  }
832
940
 
833
941
  void
834
- ca_clear_cyclic_check(void *ap)
942
+ ca_refuse_cells_reaching_evaluation (ca_size_t n, const VALUE *cells)
835
943
  {
836
- CArray *ca = (CArray *) ap;
837
- /* ca.data_type == CA_OBJECT */
838
- if ( ca_is_object_type(ca) ) {
839
- ca_unset_flag(ca, CA_FLAG_CYCLE_CHECK);
944
+ ca_size_t i;
945
+ for ( i = 0; i < n; i++ ) {
946
+ if ( rb_obj_is_carray(cells[i]) ) {
947
+ CArray *cv;
948
+ int budget = 1024;
949
+ TypedData_Get_Struct(cells[i], CArray, &carray_data_type, cv);
950
+ if ( ! ca_is_entity(cv) && ca_reaches_evaluating_walk(cv, &budget) ) {
951
+ ca_refuse_cyclic(CA_RECURSION_COMPUTE);
952
+ }
953
+ }
840
954
  }
841
955
  }
842
956
 
957
+ static VALUE
958
+ ca_computing_start (VALUE arg)
959
+ {
960
+ return ca_computing_next((ca_computing_t *) arg);
961
+ }
962
+
963
+ /* Runs body(arg), a computation over ops[0..n), with each object array
964
+ among them recorded as computed over. Raises when one of them is
965
+ already being computed over by the same method: a cell's value, or an
966
+ element's operation, led the computation back into it. A computation
967
+ over object cells calls methods of the cells, so it counts as a walk into
968
+ them (ca_cell_walk_run). */
969
+ VALUE
970
+ ca_computing_run (int n, CArray **ops, VALUE (*body)(VALUE), VALUE arg)
971
+ {
972
+ ca_computing_t c;
973
+ int k;
974
+ c.n = n; c.ops = ops; c.kind = CA_RECURSION_COMPUTE; c.k = 0; c.body = body; c.arg = arg;
975
+ for (k=0; k<n; k++) {
976
+ if ( ops[k] && ca_is_object_type(ops[k]) ) {
977
+ return ca_cell_walk_run(ca_computing_start, (VALUE) &c);
978
+ }
979
+ }
980
+ return ca_computing_next(&c);
981
+ }
982
+
983
+ /* As ca_computing_run, for the nodes of a lazy expression evaluated over
984
+ object cells: every array of ops[0..n) is recorded whatever its data type
985
+ (a comparison is boolean), apart from computations, so a reduction over
986
+ the expression evaluating it is no re-entry. */
987
+ VALUE
988
+ ca_computing_run_nodes (int n, CArray **ops, VALUE (*body)(VALUE), VALUE arg)
989
+ {
990
+ ca_computing_t c;
991
+ c.n = n; c.ops = ops; c.kind = CA_RECURSION_EVAL; c.k = 0; c.body = body; c.arg = arg;
992
+ return ca_computing_next(&c);
993
+ }
994
+
995
+ static VALUE
996
+ ca_recursion_probe (VALUE key, VALUE arg, int recursive)
997
+ {
998
+ (void) key; (void) arg;
999
+ return recursive ? Qtrue : Qfalse;
1000
+ }
1001
+
1002
+ /* A walk into the cells of an object array (#hash, #==, a nested dump) goes
1003
+ on into any array it finds there. An array holding itself is found by
1004
+ the records above, but a cell can also give a new array each time it is
1005
+ opened (a lazy expression over an array that holds it), and then the walk
1006
+ never meets an array it has seen. So the depth of these walks is
1007
+ limited. It is counted for each fiber, not in the arrays. */
1008
+
1009
+ #define CA_CELL_NESTING_MAX 256
1010
+
1011
+ typedef struct {
1012
+ VALUE thread;
1013
+ VALUE before;
1014
+ } ca_cell_nesting_t;
1015
+
1016
+ static VALUE
1017
+ ca_cell_nesting_leave (VALUE varg)
1018
+ {
1019
+ ca_cell_nesting_t *t = (ca_cell_nesting_t *) varg;
1020
+ rb_thread_local_aset(t->thread, rb_intern("carray_cell_nesting"), t->before);
1021
+ return Qnil;
1022
+ }
1023
+
1024
+ VALUE
1025
+ ca_cell_walk_run (VALUE (*body)(VALUE), VALUE arg)
1026
+ {
1027
+ ca_cell_nesting_t t;
1028
+ long depth;
1029
+
1030
+ t.thread = rb_thread_current();
1031
+ if ( OBJ_FROZEN(t.thread) ) { /* it can not hold the count */
1032
+ return body(arg);
1033
+ }
1034
+ t.before = rb_thread_local_aref(t.thread, rb_intern("carray_cell_nesting"));
1035
+ depth = NIL_P(t.before) ? 0 : FIX2LONG(t.before);
1036
+ if ( depth >= CA_CELL_NESTING_MAX ) {
1037
+ rb_raise(rb_eArgError, "%s: object cells nested too deep: more than %d levels",
1038
+ ca_calling_method_name(), CA_CELL_NESTING_MAX);
1039
+ }
1040
+ rb_thread_local_aset(t.thread, rb_intern("carray_cell_nesting"), LONG2FIX(depth + 1));
1041
+ return rb_ensure(body, arg, ca_cell_nesting_leave, (VALUE) &t);
1042
+ }
1043
+
1044
+ static VALUE
1045
+ ca_yield_nil (VALUE arg)
1046
+ {
1047
+ (void) arg;
1048
+ return rb_yield(Qnil);
1049
+ }
1050
+
1051
+ static VALUE
1052
+ ca_refuse_reentry_step (VALUE self, VALUE name, int recursive)
1053
+ {
1054
+ (void) self;
1055
+ if ( recursive ) {
1056
+ rb_raise(rb_eArgError, "%" PRIsVALUE ": cyclic reference is not allowed in CArray",
1057
+ name);
1058
+ }
1059
+ return ca_cell_walk_run(ca_yield_nil, Qnil);
1060
+ }
1061
+
1062
+ /* refuse_reentry(name) { ... } -- runs the block, refusing as cyclic a
1063
+ second call for the same array from inside it (rb_exec_recursive, by
1064
+ the receiver), and counting it as a walk into cells. Ruby code that
1065
+ walks the cells of an object array and comes back to the array through a
1066
+ cell, such as the nested dump of a view, goes through this. */
1067
+ static VALUE
1068
+ rb_ca_refuse_reentry (VALUE self, VALUE name)
1069
+ {
1070
+ return rb_exec_recursive(ca_refuse_reentry_step, self, name);
1071
+ }
1072
+
1073
+ /* A cell read that delivers an array being read refuses it: the array the
1074
+ cell was read from (an entity is not recorded, see ca_with_cyclic_check)
1075
+ or one recorded further out. */
843
1076
  void
844
- ca_test_cyclic_check(void *ap, void *ptr)
1077
+ ca_test_cyclic_check (void *ap, void *ptr)
845
1078
  {
846
1079
  CArray *ca = (CArray *) ap;
847
-
848
- /* ca.data_type == CA_OBJECT */
849
1080
  if ( ca_is_object_type(ca) ) {
850
- VALUE rval = *(VALUE*) ptr;
1081
+ volatile VALUE rval = *(VALUE *) ptr;
851
1082
  if ( rb_obj_is_carray(rval) ) {
852
1083
  CArray *cv;
853
1084
  TypedData_Get_Struct(rval, CArray, &carray_data_type, cv);
854
- if ( ca_test_flag(cv, CA_FLAG_CYCLE_CHECK) ) {
855
- rb_raise(rb_eArgError, "cyclic reference is not allowed in CArray");
1085
+ if ( cv == ca ||
1086
+ RTEST(rb_exec_recursive(ca_recursion_probe,
1087
+ ca_recursion_key(cv, CA_RECURSION_READ),
1088
+ Qnil)) ) {
1089
+ ca_refuse_cyclic(CA_RECURSION_READ);
856
1090
  }
857
1091
  }
858
1092
  }
859
1093
  }
860
1094
 
861
- /* Runs body(arg) -- one transfer of an object cell or cells -- with ca's
862
- cycle check set, and clears the check however body leaves. Either
863
- direction can call into Ruby: a GET through a CAObject slot or the
864
- check of what it delivered, a PUT that converts the caller's value. A
865
- raise that skipped the clear would leave every later access to ca
866
- reporting a cyclic reference. A PUT into an entity only copies VALUEs
867
- and cannot raise, so it runs unprotected. */
1095
+ /* Refuse to write into an object array a value that is a CArray sharing
1096
+ its cells -- the array itself or a view of it. Reading such a cell back
1097
+ is refused as cyclic (ca_test_cyclic_check); refusing the write where it
1098
+ passes through here reports the mistake where it is made. A write that
1099
+ reaches the cells another way is still caught when the cell is read.
1100
+ data holds n VALUEs. */
868
1101
  static void
869
- ca_with_cyclic_check (CArray *ca, int dir, VALUE (*body)(VALUE), VALUE arg)
1102
+ ca_refuse_storing_self (CArray *ca, const void *data, ca_size_t n)
870
1103
  {
871
- int state = 0;
872
- ca_set_cyclic_check(ca);
873
- if ( dir == CA_XFER_PUT && ca_is_entity(ca) ) {
874
- body(arg);
1104
+ const char *d = (const char *) data;
1105
+ ca_size_t i;
1106
+ for (i=0; i<n; i++) {
1107
+ VALUE rval;
1108
+ memcpy(&rval, d + i * sizeof(VALUE), sizeof(VALUE));
1109
+ if ( rb_obj_is_carray(rval) ) {
1110
+ CArray *cv;
1111
+ TypedData_Get_Struct(rval, CArray, &carray_data_type, cv);
1112
+ if ( ca_shares_root(ca, cv) ) {
1113
+ rb_raise(rb_eArgError, "%s: can not store an object array into itself",
1114
+ ca_calling_method_name());
1115
+ }
1116
+ }
875
1117
  }
876
- else {
877
- rb_protect(body, arg, &state);
1118
+ }
1119
+
1120
+ typedef struct {
1121
+ VALUE (*body)(VALUE);
1122
+ VALUE arg;
1123
+ } ca_reading_t;
1124
+
1125
+ static VALUE
1126
+ ca_reading_step (VALUE key, VALUE varg, int recursive)
1127
+ {
1128
+ ca_reading_t *r = (ca_reading_t *) varg;
1129
+ (void) key;
1130
+ if ( recursive ) {
1131
+ ca_refuse_cyclic(CA_RECURSION_READ);
878
1132
  }
879
- ca_clear_cyclic_check(ca);
880
- if ( state ) {
881
- rb_jump_tag(state);
1133
+ return r->body(r->arg);
1134
+ }
1135
+
1136
+ static char ca_obj_moves_cells[CA_OBJ_TYPE_MAX];
1137
+
1138
+ void
1139
+ ca_register_cell_moving_view (int8_t obj_type)
1140
+ {
1141
+ ca_obj_moves_cells[(uint8_t) obj_type] = 1;
1142
+ }
1143
+
1144
+ /* Whether the transfers of a Face are the forwarders of ca_obj_face.c, which
1145
+ hand the request to the parent unchanged. A Face with transfer slots of
1146
+ its own (one defined in Ruby on CAObject, or by an extension) may run Ruby
1147
+ and answers no. */
1148
+ static int
1149
+ ca_face_forwards_transfers (CArray *ca)
1150
+ {
1151
+ ca_operation_function_t *f = &ca_func[ca->obj_type];
1152
+ return f->xfer_index == ca_face_xfer_index &&
1153
+ f->xfer_addrs == ca_face_xfer_addrs &&
1154
+ f->xfer_stride == ca_face_xfer_stride &&
1155
+ f->xfer_all == ca_face_xfer_all;
1156
+ }
1157
+
1158
+ /* Whether a transfer of ca reaches entities through cell-moving views only:
1159
+ then it calls no Ruby on the way. An unknown view, one that computes its
1160
+ cells (CAObject, a lazy expression) or converts them, answers no. */
1161
+ static int
1162
+ ca_transfer_calls_no_ruby (CArray *ca, int depth)
1163
+ {
1164
+ while ( ! ca_is_entity(ca) ) {
1165
+ if ( depth++ > 64 ) {
1166
+ return 0;
1167
+ }
1168
+ if ( ca_test_flag(ca, CA_FLAG_MULTI_PARENTS) ) {
1169
+ CAMultiParent *mp = (CAMultiParent *) ca;
1170
+ int32_t k;
1171
+ if ( ! ca_obj_moves_cells[(uint8_t) ca->obj_type] ) {
1172
+ return 0;
1173
+ }
1174
+ for ( k = 0; k < mp->n_parents; k++ ) {
1175
+ if ( ! mp->parents[k] ||
1176
+ ! ca_transfer_calls_no_ruby(mp->parents[k], depth) ) {
1177
+ return 0;
1178
+ }
1179
+ }
1180
+ return 1;
1181
+ }
1182
+ if ( ca_is_face(ca) ? ! ca_face_forwards_transfers(ca)
1183
+ : ! ( ca_is_stride_family(ca) ||
1184
+ ca_obj_moves_cells[(uint8_t) ca->obj_type] ) ) {
1185
+ return 0;
1186
+ }
1187
+ ca = ((CAView *) ca)->parent;
1188
+ if ( ! ca ) {
1189
+ return 0;
1190
+ }
882
1191
  }
1192
+ return 1;
1193
+ }
1194
+
1195
+ /* Runs body(arg) -- one transfer of an object cell or cells -- with ca
1196
+ recorded as being read. Entering a transfer of ca again from inside it
1197
+ is refused as cyclic. A transfer of an entity, or of views that only move
1198
+ cells down to entities, copies VALUEs and calls no Ruby, so it cannot be
1199
+ entered again; it is not recorded, and a cell holding the array itself is
1200
+ caught by ca_test_cyclic_check. */
1201
+ static void
1202
+ ca_with_cyclic_check (CArray *ca, int dir, VALUE (*body)(VALUE), VALUE arg)
1203
+ {
1204
+ ca_reading_t r;
1205
+ (void) dir;
1206
+ if ( ca_transfer_calls_no_ruby(ca, 0) ) {
1207
+ body(arg);
1208
+ return;
1209
+ }
1210
+ r.body = body;
1211
+ r.arg = arg;
1212
+ rb_exec_recursive(ca_reading_step, ca_recursion_key(ca, CA_RECURSION_READ),
1213
+ (VALUE) &r);
883
1214
  }
884
1215
 
885
1216
  /* ------------------------------------------------------------------- */
@@ -912,6 +1243,58 @@ ca_store_addr (void *ap, ca_size_t addr, void *pval)
912
1243
  public C-API for external ext gems). Every view supplies an
913
1244
  xfer_index slot. */
914
1245
 
1246
+ /* ---- A write through a view, tried first against a stack's stand-ins ----
1247
+ (ca_multi_parent_value_trial_below) */
1248
+
1249
+ typedef struct {
1250
+ int kind;
1251
+ CArray *ca;
1252
+ ca_size_t n;
1253
+ ca_size_t *addrs;
1254
+ ca_size_t *starts;
1255
+ ca_size_t *counts;
1256
+ ca_size_t *strides;
1257
+ void *data;
1258
+ ca_size_t base;
1259
+ int8_t ndim;
1260
+ ca_size_t *steps;
1261
+ } ca_value_trial_put_t;
1262
+
1263
+ enum { CA_TRIAL_ADDRS, CA_TRIAL_STRIDE, CA_TRIAL_ALL, CA_TRIAL_FILL,
1264
+ CA_TRIAL_FILL_STRIDE, CA_TRIAL_FILL_ADDRS, CA_TRIAL_SYNC };
1265
+
1266
+ static VALUE
1267
+ ca_value_trial_put_body (VALUE arg)
1268
+ {
1269
+ ca_value_trial_put_t *a = (ca_value_trial_put_t *) arg;
1270
+ switch ( a->kind ) {
1271
+ case CA_TRIAL_ADDRS:
1272
+ ca_xfer_addrs(a->ca, a->n, a->addrs, a->data, CA_XFER_PUT); break;
1273
+ case CA_TRIAL_STRIDE:
1274
+ ca_xfer_stride(a->ca, a->starts, a->counts, a->strides, a->data, CA_XFER_PUT); break;
1275
+ case CA_TRIAL_ALL:
1276
+ ca_xfer_all(a->ca, a->data, CA_XFER_PUT); break;
1277
+ case CA_TRIAL_FILL:
1278
+ ca_fill_data(a->ca, a->data); break;
1279
+ case CA_TRIAL_FILL_STRIDE:
1280
+ ca_fill_stride(a->ca, a->base, a->ndim, a->counts, a->steps, a->data); break;
1281
+ case CA_TRIAL_FILL_ADDRS:
1282
+ ca_fill_addrs(a->ca, a->n, a->addrs, a->data); break;
1283
+ case CA_TRIAL_SYNC:
1284
+ ca_func[a->ca->obj_type].sync(a->ca); break;
1285
+ }
1286
+ return Qnil;
1287
+ }
1288
+
1289
+ #define CA_VALUE_TRIAL_PUT(...) \
1290
+ do { \
1291
+ ca_value_trial_put_t a_ = { __VA_ARGS__ }; \
1292
+ CArray *m_ = ca_multi_parent_value_trial_below(a_.ca); \
1293
+ if ( m_ != NULL ) { \
1294
+ ca_multi_parent_value_trial_through(m_, ca_value_trial_put_body, (VALUE) &a_); \
1295
+ } \
1296
+ } while (0)
1297
+
915
1298
  static inline void
916
1299
  ca_xfer_index_dispatch (CArray *ca, ca_size_t *idx, void *data, int dir)
917
1300
  {
@@ -950,6 +1333,7 @@ ca_xfer_index (void *ap, ca_size_t *idx, void *data, int dir)
950
1333
  ca_refuse_read_only();
951
1334
  }
952
1335
 
1336
+
953
1337
  /* Fast path: non-CA_OBJECT element type needs no GC protection. */
954
1338
  if ( ca->data_type != CA_OBJECT ) {
955
1339
  ca_xfer_index_dispatch(ca, idx, data, dir);
@@ -957,6 +1341,9 @@ ca_xfer_index (void *ap, ca_size_t *idx, void *data, int dir)
957
1341
  }
958
1342
 
959
1343
  /* CA_OBJECT slow path: cyclic check. */
1344
+ if ( dir == CA_XFER_PUT ) {
1345
+ ca_refuse_storing_self(ca, data, 1);
1346
+ }
960
1347
  {
961
1348
  struct ca_xfer_index_args args;
962
1349
  args.ca = ca;
@@ -1030,7 +1417,27 @@ ca_xfer_addrs_dispatch (CArray *ca, ca_size_t n, ca_size_t *addrs,
1030
1417
  return;
1031
1418
  }
1032
1419
  /* Per-cell loop for arbitrary (non-sequential) addrs:
1033
- fancy gather/scatter from CASelect 2-D mapper, CSA sparse mask, etc. */
1420
+ fancy gather/scatter from CASelect 2-D mapper, CSA sparse mask, etc.
1421
+ Cells of 1, 2, 4 or 8 bytes are copied with that length as a
1422
+ constant, which the compiler turns into one load and store (and
1423
+ which stays legal for an unaligned buffer); a length known only at
1424
+ run time is a call per cell. */
1425
+ #define CA_XFER_ADDRS_AS(W) \
1426
+ do { \
1427
+ if ( dir == CA_XFER_GET ) { \
1428
+ for (i=0; i<n; i++) memcpy(d + i * (W), ca->ptr + (W) * addrs[i], (W)); \
1429
+ } \
1430
+ else { \
1431
+ for (i=0; i<n; i++) memcpy(ca->ptr + (W) * addrs[i], d + i * (W), (W)); \
1432
+ } \
1433
+ } while (0)
1434
+ switch ( ca->bytes ) {
1435
+ case 1: CA_XFER_ADDRS_AS(1); return;
1436
+ case 2: CA_XFER_ADDRS_AS(2); return;
1437
+ case 4: CA_XFER_ADDRS_AS(4); return;
1438
+ case 8: CA_XFER_ADDRS_AS(8); return;
1439
+ }
1440
+ #undef CA_XFER_ADDRS_AS
1034
1441
  for ( i = 0; i < n; i++ ) {
1035
1442
  char *p = ca->ptr + ca->bytes * addrs[i];
1036
1443
  if ( dir == CA_XFER_GET ) memcpy(d + i * ca->bytes, p, ca->bytes);
@@ -1078,6 +1485,11 @@ ca_xfer_addrs (void *ap, ca_size_t n, ca_size_t *addrs, void *data, int dir)
1078
1485
  ca_refuse_read_only();
1079
1486
  }
1080
1487
 
1488
+ if ( dir == CA_XFER_PUT && ca->ptr == NULL ) {
1489
+ CA_VALUE_TRIAL_PUT(CA_TRIAL_ADDRS, ca, n, addrs, NULL, NULL, NULL, data);
1490
+ }
1491
+
1492
+
1081
1493
  /* Fast path: non-CA_OBJECT element type needs no GC protection. */
1082
1494
  if ( ca->data_type != CA_OBJECT ) {
1083
1495
  ca_xfer_addrs_dispatch(ca, n, addrs, data, dir);
@@ -1085,6 +1497,9 @@ ca_xfer_addrs (void *ap, ca_size_t n, ca_size_t *addrs, void *data, int dir)
1085
1497
  }
1086
1498
 
1087
1499
  /* CA_OBJECT slow path: cyclic check. */
1500
+ if ( dir == CA_XFER_PUT ) {
1501
+ ca_refuse_storing_self(ca, data, n);
1502
+ }
1088
1503
  {
1089
1504
  struct ca_xfer_addrs_args args;
1090
1505
  args.ca = ca;
@@ -1440,7 +1855,6 @@ ca_xfer_stride_dispatch (CArray *ca, ca_size_t *starts, ca_size_t *counts,
1440
1855
  int8_t ndim = ca->ndim;
1441
1856
  ca_size_t native[CA_RANK_MAX];
1442
1857
  ca_size_t base = 0;
1443
- ca_size_t doff = 0;
1444
1858
  ca_size_t s;
1445
1859
  int8_t k;
1446
1860
  ca_size_t idx[CA_RANK_MAX];
@@ -1467,18 +1881,27 @@ ca_xfer_stride_dispatch (CArray *ca, ca_size_t *starts, ca_size_t *counts,
1467
1881
  return;
1468
1882
  }
1469
1883
 
1470
- /* fallback: per-cell via byte offset -> flat addr -> index -> xfer_index. */
1471
- for ( k = 0; k < ndim; k++ ) idx[k] = 0;
1472
- /* empty: its one caller, ca_xfer_stride, returns on an empty region */
1473
- while ( 1 ) {
1474
- ca_size_t soff = base, vidx[CA_RANK_MAX];
1475
- for ( k = 0; k < ndim; k++ ) soff += idx[k] * strides[k];
1476
- ca_addr2index(ca, soff / ca->bytes, vidx);
1477
- ca_xfer_index_dispatch(ca, vidx, d + doff, dir);
1478
- doff += ca->bytes;
1479
- k = ndim - 1;
1480
- while ( k >= 0 ) { if ( ++idx[k] < counts[k] ) break; idx[k] = 0; k--; }
1481
- if ( k < 0 ) break;
1884
+ /* fallback for a type without xfer_stride: the region's cells by address,
1885
+ handed to xfer_addrs in one call (data is packed over counts, as
1886
+ xfer_addrs takes it). */
1887
+ {
1888
+ volatile VALUE holder = 0;
1889
+ ca_size_t n = 1, i = 0;
1890
+ ca_size_t *addrs;
1891
+ for ( k = 0; k < ndim; k++ ) n *= counts[k];
1892
+ addrs = ALLOCV_N(ca_size_t, holder, n);
1893
+ for ( k = 0; k < ndim; k++ ) idx[k] = 0;
1894
+ /* empty: its one caller, ca_xfer_stride, returns on an empty region */
1895
+ while ( 1 ) {
1896
+ ca_size_t soff = base;
1897
+ for ( k = 0; k < ndim; k++ ) soff += idx[k] * strides[k];
1898
+ addrs[i++] = soff / ca->bytes;
1899
+ k = ndim - 1;
1900
+ while ( k >= 0 ) { if ( ++idx[k] < counts[k] ) break; idx[k] = 0; k--; }
1901
+ if ( k < 0 ) break;
1902
+ }
1903
+ ca_xfer_addrs_dispatch(ca, n, addrs, d, dir);
1904
+ ALLOCV_END(holder);
1482
1905
  }
1483
1906
  }
1484
1907
 
@@ -1523,11 +1946,22 @@ ca_xfer_stride (void *ap, ca_size_t *starts, ca_size_t *counts,
1523
1946
 
1524
1947
  if ( ca_region_is_empty(ca->ndim, counts) ) return;
1525
1948
 
1949
+ if ( dir == CA_XFER_PUT && ca->ptr == NULL ) {
1950
+ CA_VALUE_TRIAL_PUT(CA_TRIAL_STRIDE, ca, 0, NULL, starts, counts, strides, data);
1951
+ }
1952
+
1953
+
1526
1954
  if ( ca->data_type != CA_OBJECT ) {
1527
1955
  ca_xfer_stride_dispatch(ca, starts, counts, strides, data, dir);
1528
1956
  return;
1529
1957
  }
1530
1958
 
1959
+ if ( dir == CA_XFER_PUT ) {
1960
+ ca_size_t n = 1;
1961
+ int8_t k;
1962
+ for (k=0; k<ca->ndim; k++) n *= counts[k];
1963
+ ca_refuse_storing_self(ca, data, n);
1964
+ }
1531
1965
  {
1532
1966
  struct ca_xfer_stride_args args;
1533
1967
  args.ca = ca; args.starts = starts; args.counts = counts;
@@ -1588,6 +2022,9 @@ ca_xfer_all (void *ap, void *data, int dir)
1588
2022
  if ( ca->elements == 0 ) {
1589
2023
  return;
1590
2024
  }
2025
+ if ( dir == CA_XFER_PUT && ca->ptr == NULL ) {
2026
+ CA_VALUE_TRIAL_PUT(CA_TRIAL_ALL, ca, 0, NULL, NULL, NULL, NULL, data);
2027
+ }
1591
2028
  /* Universal arena lifetime hook. ca_xfer_all is the single universal
1592
2029
  entry for materialise (to_ca -> ca_copy -> ca_copy_data ->
1593
2030
  ca_xfer_all), so wrapping here covers every outermost view type,
@@ -1679,14 +2116,111 @@ rb_ca_s_attached_views (VALUE klass)
1679
2116
  return LONG2NUM(__atomic_load_n(&ca_attached_views, __ATOMIC_RELAXED));
1680
2117
  }
1681
2118
 
1682
- /* Set once at load from CARRAY_GENERAL_PATH; see carray_internal.h. */
2119
+ /* Set once at load from CARRAY_GENERAL_PATH and CARRAY_SHORTCUTS_OFF; see
2120
+ carray_internal.h. */
1683
2121
  int ca_fast_paths_on = 1;
1684
2122
  int ca_iter_transfer_only_on = 0;
2123
+ unsigned char ca_shortcut_off[CA_SC_COUNT];
2124
+
2125
+ /* In the order of enum ca_shortcut. */
2126
+ static const char *ca_shortcut_names[CA_SC_COUNT] = {
2127
+ "shift_whole_view",
2128
+ "stack",
2129
+ "stack_outer_k",
2130
+ "fiber_fused_conversion",
2131
+ "per_slab_hoist",
2132
+ "protect_only_may_raise",
2133
+ "stack_addrs_k0",
2134
+ "stack_stride_box",
2135
+ "stack_stride_reloc",
2136
+ "stack_parents_k0",
2137
+ "stack_fold",
2138
+ "meld_stride_box",
2139
+ "meld_parents_axis0",
2140
+ "median_partition",
2141
+ "percentile_partition",
2142
+ "loop_interchange",
2143
+ "stack_loop_interchange",
2144
+ "lazy_streaming_reduce",
2145
+ "short_fiber_reduce",
2146
+ "meld_reduce",
2147
+ "segment_nunique",
2148
+ "segment_scan_kernel",
2149
+ "segment_edge_kernel",
2150
+ "segment_reduce_kernel",
2151
+ "segment_all_any_kernel",
2152
+ "categorical_group_by_index",
2153
+ "axis_group_count_kernel",
2154
+ "axis_group_whole_block",
2155
+ "axis_group_reduce_kernel",
2156
+ "axis_group_scan_kernel",
2157
+ "window_fold_by_offset",
2158
+ };
1685
2159
 
2160
+ static int
2161
+ ca_shortcut_lookup (const char *name, long len)
2162
+ {
2163
+ int i;
2164
+ for (i=0; i<CA_SC_COUNT; i++) {
2165
+ if ( (long) strlen(ca_shortcut_names[i]) == len
2166
+ && ! strncmp(ca_shortcut_names[i], name, len) ) {
2167
+ return i;
2168
+ }
2169
+ }
2170
+ return -1;
2171
+ }
2172
+
2173
+ /* CARRAY_SHORTCUTS_OFF is a comma-separated list of names. A name it does
2174
+ not know is warned about, so a misspelt one does not leave the shortcut
2175
+ on unnoticed. */
2176
+ static void
2177
+ ca_shortcuts_off_from_env (void)
2178
+ {
2179
+ const char *p = getenv("CARRAY_SHORTCUTS_OFF");
2180
+ if ( ! p ) {
2181
+ return;
2182
+ }
2183
+ while ( *p ) {
2184
+ const char *q = strchr(p, ',');
2185
+ long len = q ? (long) (q - p) : (long) strlen(p);
2186
+ if ( len > 0 ) {
2187
+ int id = ca_shortcut_lookup(p, len);
2188
+ if ( id < 0 ) {
2189
+ rb_warn("CARRAY_SHORTCUTS_OFF: unknown shortcut %.*s", (int) len, p);
2190
+ }
2191
+ else {
2192
+ ca_shortcut_off[id] = 1;
2193
+ }
2194
+ }
2195
+ if ( ! q ) {
2196
+ break;
2197
+ }
2198
+ p = q + 1;
2199
+ }
2200
+ }
2201
+
2202
+ /* CArray.__fast_paths_enabled__ answers whether the fast paths are on;
2203
+ with a name, whether that one is. */
1686
2204
  static VALUE
1687
- rb_ca_s_fast_paths_enabled (VALUE klass)
2205
+ rb_ca_s_fast_paths_enabled (int argc, VALUE *argv, VALUE klass)
1688
2206
  {
1689
- return ca_fast_paths_on ? Qtrue : Qfalse;
2207
+ VALUE rname;
2208
+ int id;
2209
+
2210
+ rb_scan_args(argc, argv, "01", &rname);
2211
+ if ( NIL_P(rname) ) {
2212
+ return ca_fast_paths_on ? Qtrue : Qfalse;
2213
+ }
2214
+ if ( SYMBOL_P(rname) ) {
2215
+ rname = rb_sym2str(rname);
2216
+ }
2217
+ StringValue(rname);
2218
+ id = ca_shortcut_lookup(RSTRING_PTR(rname), RSTRING_LEN(rname));
2219
+ if ( id < 0 ) {
2220
+ rb_raise(rb_eArgError, "__fast_paths_enabled__: unknown shortcut %"PRIsVALUE,
2221
+ rname);
2222
+ }
2223
+ return ca_fast_path(id) ? Qtrue : Qfalse;
1690
2224
  }
1691
2225
 
1692
2226
  static VALUE
@@ -1880,27 +2414,37 @@ ca_sync_all_step (VALUE arg)
1880
2414
  return Qnil;
1881
2415
  }
1882
2416
 
2417
+ /* Syncs `ca`, carrying on past a raise: the first exception is kept in
2418
+ *error (left as it is when one is already there), to be raised once
2419
+ the others have been synced. A throw or break cannot wait, and goes at
2420
+ once. */
2421
+ void
2422
+ ca_sync_carry_on (CArray *ca, volatile VALUE *error)
2423
+ {
2424
+ int tag = 0;
2425
+ rb_protect(ca_sync_all_step, (VALUE) ca, &tag);
2426
+ if ( tag ) {
2427
+ VALUE err = rb_errinfo();
2428
+ if ( ! RTEST(rb_obj_is_kind_of(err, rb_eException)) ) {
2429
+ rb_jump_tag(tag);
2430
+ }
2431
+ if ( NIL_P(*error) ) {
2432
+ *error = err;
2433
+ }
2434
+ rb_set_errinfo(Qnil);
2435
+ }
2436
+ }
2437
+
1883
2438
  /* Syncs every one of list[0..n-1] in turn, carrying on past one that
1884
2439
  raises so that the others still receive what was written, then raises
1885
- the first exception. A throw or break cannot wait, and goes at once. */
2440
+ the first exception. */
1886
2441
  void
1887
2442
  ca_sync_all (CArray **list, int32_t n)
1888
2443
  {
1889
2444
  volatile VALUE error = Qnil;
1890
2445
  int32_t k;
1891
2446
  for ( k = 0; k < n; k++ ) {
1892
- int tag = 0;
1893
- rb_protect(ca_sync_all_step, (VALUE) list[k], &tag);
1894
- if ( tag ) {
1895
- VALUE err = rb_errinfo();
1896
- if ( ! RTEST(rb_obj_is_kind_of(err, rb_eException)) ) {
1897
- rb_jump_tag(tag);
1898
- }
1899
- if ( NIL_P(error) ) {
1900
- error = err;
1901
- }
1902
- rb_set_errinfo(Qnil);
1903
- }
2447
+ ca_sync_carry_on(list[k], &error);
1904
2448
  }
1905
2449
  if ( ! NIL_P(error) ) {
1906
2450
  rb_exc_raise(error);
@@ -2092,6 +2636,234 @@ ca_attach_window (int32_t n, CArray **list, const char *modes,
2092
2636
  return result;
2093
2637
  }
2094
2638
 
2639
+ /* ---- A window whose Fiber is abandoned ------------------------------------
2640
+
2641
+ A window that yields to a block is closed by rb_ensure. Ruby does not
2642
+ run the ensure of a Fiber that is suspended and then collected -- an
2643
+ Enumerator stopped with #next and dropped is one -- so such a window
2644
+ would stay open for good: a view keeps its attach, and a source that
2645
+ publishes its ptr only while held (a CASource) keeps it published and
2646
+ stops checking its backend.
2647
+
2648
+ The guard closes it from a finalizer instead. The window's state lives
2649
+ on the heap, owned by the guard; a sentinel object that only the
2650
+ window's frame refers to carries a finalizer that holds the guard. When
2651
+ the Fiber is collected the sentinel goes with it, and the finalizer --
2652
+ which runs outside GC, where Ruby may be called -- runs `cleanup`. A
2653
+ window that closes normally disarms the guard first.
2654
+
2655
+ `mark` marks the VALUEs `arg` holds, which nothing else does once the
2656
+ frame that referred to them is gone. The guard frees `arg` with xfree. */
2657
+
2658
+ typedef struct {
2659
+ void (*cleanup) (void *arg);
2660
+ void (*mark) (void *arg);
2661
+ void *arg;
2662
+ int armed;
2663
+ } ca_window_guard_t;
2664
+
2665
+ static void
2666
+ ca_window_guard_mark (void *p)
2667
+ {
2668
+ ca_window_guard_t *g = (ca_window_guard_t *) p;
2669
+ if ( g->arg && g->mark ) {
2670
+ g->mark(g->arg);
2671
+ }
2672
+ }
2673
+
2674
+ static void
2675
+ ca_window_guard_free (void *p)
2676
+ {
2677
+ ca_window_guard_t *g = (ca_window_guard_t *) p;
2678
+ xfree(g->arg);
2679
+ xfree(g);
2680
+ }
2681
+
2682
+ static const rb_data_type_t ca_window_guard_data_type = {
2683
+ .wrap_struct_name = "CArrayWindowGuard",
2684
+ .function = {
2685
+ .dmark = ca_window_guard_mark,
2686
+ .dfree = ca_window_guard_free,
2687
+ .dsize = NULL,
2688
+ },
2689
+ .flags = RUBY_TYPED_FREE_IMMEDIATELY
2690
+ };
2691
+
2692
+ static VALUE
2693
+ ca_window_guard_cleanup_step (VALUE gv)
2694
+ {
2695
+ ca_window_guard_t *g;
2696
+ TypedData_Get_Struct(gv, ca_window_guard_t, &ca_window_guard_data_type, g);
2697
+ g->cleanup(g->arg);
2698
+ return Qnil;
2699
+ }
2700
+
2701
+ /* The finalizer is the guard itself, called with the sentinel's object id.
2702
+ A proc made here would capture the frame it is made in -- inside the
2703
+ Fiber -- and keep the Fiber alive through the finalizer table. */
2704
+ static VALUE rb_cCAWindowGuard;
2705
+
2706
+ static VALUE
2707
+ ca_window_guard_call (VALUE gv, VALUE object_id)
2708
+ {
2709
+ ca_window_guard_t *g;
2710
+ int tag = 0;
2711
+ (void) object_id;
2712
+ TypedData_Get_Struct(gv, ca_window_guard_t, &ca_window_guard_data_type, g);
2713
+ if ( g->armed && g->cleanup ) {
2714
+ g->armed = 0;
2715
+ rb_protect(ca_window_guard_cleanup_step, gv, &tag);
2716
+ if ( tag ) {
2717
+ rb_set_errinfo(Qnil);
2718
+ }
2719
+ }
2720
+ return Qnil;
2721
+ }
2722
+
2723
+ /* Takes ownership of arg (allocated with xmalloc). Returns the guard and
2724
+ stores the sentinel; the caller keeps both on its frame (RB_GC_GUARD)
2725
+ for as long as the window may be open. */
2726
+ VALUE
2727
+ ca_window_guard_arm (void (*cleanup)(void *), void (*mark)(void *), void *arg,
2728
+ VALUE *sentinel)
2729
+ {
2730
+ ca_window_guard_t *g;
2731
+ volatile VALUE gv, sv;
2732
+ gv = TypedData_Make_Struct(rb_cCAWindowGuard, ca_window_guard_t,
2733
+ &ca_window_guard_data_type, g);
2734
+ g->cleanup = cleanup;
2735
+ g->mark = mark;
2736
+ g->arg = arg;
2737
+ g->armed = 1;
2738
+ sv = rb_class_new_instance(0, NULL, rb_cObject);
2739
+ rb_define_finalizer(sv, gv);
2740
+ *sentinel = sv;
2741
+ return gv;
2742
+ }
2743
+
2744
+ /* Called first thing when the window closes normally, so that cleanup
2745
+ cannot also run from the finalizer. */
2746
+ void
2747
+ ca_window_guard_disarm (VALUE gv, VALUE sentinel)
2748
+ {
2749
+ ca_window_guard_t *g;
2750
+ TypedData_Get_Struct(gv, ca_window_guard_t, &ca_window_guard_data_type, g);
2751
+ g->armed = 0;
2752
+ /* rb_undefine_finalizer is declared in the headers but not exported by
2753
+ every libruby (3.4.1 lacks it), so go through ObjectSpace. */
2754
+ rb_funcall(rb_const_get(rb_cObject, rb_intern("ObjectSpace")),
2755
+ rb_intern("undefine_finalizer"), 1, sentinel);
2756
+ }
2757
+
2758
+ /* ca_attach_window for a window that yields to a block, closed by the
2759
+ guard above if its Fiber is abandoned. The context, the list and the
2760
+ modes are copied to the heap, since the caller's frame goes with the
2761
+ Fiber; `owners` keeps the arrays in list alive until then. */
2762
+
2763
+ typedef struct {
2764
+ ca_window_ctx_t w;
2765
+ VALUE owners;
2766
+ CArray *list[CA_RANK_MAX];
2767
+ char modes[CA_RANK_MAX + 1];
2768
+ } ca_guarded_window_t;
2769
+
2770
+ static void
2771
+ ca_guarded_window_mark (void *p)
2772
+ {
2773
+ ca_guarded_window_t *gw = (ca_guarded_window_t *) p;
2774
+ rb_gc_mark(gw->owners);
2775
+ rb_gc_mark(gw->w.masks);
2776
+ rb_gc_mark(gw->w.sync_err);
2777
+ }
2778
+
2779
+ static void
2780
+ ca_guarded_window_cleanup (void *p)
2781
+ {
2782
+ ca_guarded_window_t *gw = (ca_guarded_window_t *) p;
2783
+ ca_attach_window_close((VALUE) &gw->w);
2784
+ }
2785
+
2786
+ typedef struct {
2787
+ ca_guarded_window_t *gw;
2788
+ VALUE guard;
2789
+ VALUE sentinel;
2790
+ } ca_guarded_window_run_t;
2791
+
2792
+ static VALUE
2793
+ ca_guarded_window_close (VALUE varg)
2794
+ {
2795
+ ca_guarded_window_run_t *r = (ca_guarded_window_run_t *) varg;
2796
+ ca_window_guard_disarm(r->guard, r->sentinel);
2797
+ return ca_attach_window_close((VALUE) &r->gw->w);
2798
+ }
2799
+
2800
+ VALUE
2801
+ ca_attach_window_yielding (VALUE owners, int32_t n, CArray **list,
2802
+ const char *modes, VALUE (*body)(VALUE), VALUE arg)
2803
+ {
2804
+ ca_guarded_window_t *gw;
2805
+ ca_guarded_window_run_t r;
2806
+ volatile VALUE guard, sentinel;
2807
+ VALUE result;
2808
+ int tag = 0;
2809
+
2810
+ if ( n < 1 || n > CA_RANK_MAX ) { /* rank-check: a count of arrays, bounded by gw->list */
2811
+ rb_raise(rb_eRuntimeError, "[BUG] ca_attach_window_yielding: %d arrays", (int) n);
2812
+ }
2813
+ gw = ZALLOC(ca_guarded_window_t);
2814
+ gw->owners = owners;
2815
+ memcpy(gw->list, list, sizeof(CArray *) * (size_t) n);
2816
+ memcpy(gw->modes, modes, (size_t) n);
2817
+ gw->w.n = n;
2818
+ gw->w.list = gw->list;
2819
+ gw->w.modes = gw->modes;
2820
+ gw->w.opened = 0;
2821
+ gw->w.body_done = 0;
2822
+ gw->w.sync_tag = 0;
2823
+ gw->w.sync_err = Qnil;
2824
+ gw->w.body = body;
2825
+ gw->w.arg = arg;
2826
+ gw->w.masks = Qnil;
2827
+ guard = ca_window_guard_arm(NULL, ca_guarded_window_mark, gw, (VALUE *) &sentinel);
2828
+ ca_attach_window_save_masks(&gw->w);
2829
+
2830
+ rb_protect(ca_attach_window_open, (VALUE) &gw->w, &tag);
2831
+ if ( tag ) {
2832
+ ca_window_guard_disarm(guard, sentinel);
2833
+ while ( gw->w.opened > 0 ) {
2834
+ gw->w.opened--;
2835
+ if ( gw->w.list[gw->w.opened] ) {
2836
+ ca_detach(gw->w.list[gw->w.opened]);
2837
+ }
2838
+ }
2839
+ ca_attach_window_restore_masks(&gw->w);
2840
+ rb_jump_tag(tag);
2841
+ }
2842
+
2843
+ /* Only now is there something for the finalizer to close. */
2844
+ {
2845
+ ca_window_guard_t *g;
2846
+ TypedData_Get_Struct(guard, ca_window_guard_t, &ca_window_guard_data_type, g);
2847
+ g->cleanup = ca_guarded_window_cleanup;
2848
+ }
2849
+
2850
+ r.gw = gw;
2851
+ r.guard = guard;
2852
+ r.sentinel = sentinel;
2853
+ result = rb_ensure(ca_attach_window_body, (VALUE) &gw->w,
2854
+ ca_guarded_window_close, (VALUE) &r);
2855
+ if ( gw->w.sync_tag && RB_TYPE_P(gw->w.sync_err, T_OBJECT) &&
2856
+ RTEST(rb_obj_is_kind_of(gw->w.sync_err, rb_eException)) ) {
2857
+ VALUE err = gw->w.sync_err;
2858
+ RB_GC_GUARD(guard);
2859
+ RB_GC_GUARD(sentinel);
2860
+ rb_exc_raise(err);
2861
+ }
2862
+ RB_GC_GUARD(guard);
2863
+ RB_GC_GUARD(sentinel);
2864
+ return result;
2865
+ }
2866
+
2095
2867
  /* re-gather an attached view's buffer from its parent */
2096
2868
 
2097
2869
  void
@@ -2139,6 +2911,12 @@ ca_sync (void *ap)
2139
2911
  ca_refuse_read_only();
2140
2912
  }
2141
2913
 
2914
+ /* Before the mask is synced: a refused write leaves the mask as well. */
2915
+ if ( ca_is_view(ca) && ! CAVIEW(ca)->nosync ) {
2916
+ CA_VALUE_TRIAL_PUT(CA_TRIAL_SYNC, ca, 0, NULL, NULL, NULL, NULL, NULL);
2917
+ }
2918
+
2919
+
2142
2920
  /* Only a mask that exists can hold writes: one made inside the window
2143
2921
  is attached with the view (ca_create_mask). Making one here would
2144
2922
  read the parent's mask while the window closes, and a parent that
@@ -2370,6 +3148,11 @@ ca_fill_data (void *ap, void *aptr)
2370
3148
  ca_refuse_read_only();
2371
3149
  }
2372
3150
 
3151
+ if ( ca->ptr == NULL ) {
3152
+ CA_VALUE_TRIAL_PUT(CA_TRIAL_FILL, ca, 0, NULL, NULL, NULL, NULL, ptr);
3153
+ }
3154
+
3155
+
2373
3156
  if ( ca_is_view(ca) ) { /* view array */
2374
3157
  if ( ca_is_attached(ca) ) { /* ca is to be attached */
2375
3158
  ca_func[CA_OBJ_ARRAY].fill_data(ap, ptr);
@@ -2426,6 +3209,12 @@ ca_fill_stride (void *ap, ca_size_t base, int8_t ndim,
2426
3209
 
2427
3210
  if ( ca_region_is_empty(ndim, counts) ) return;
2428
3211
 
3212
+ if ( ca->ptr == NULL ) {
3213
+ CA_VALUE_TRIAL_PUT(CA_TRIAL_FILL_STRIDE, ca, 0, NULL, NULL, counts, NULL, ptr,
3214
+ base, ndim, steps);
3215
+ }
3216
+
3217
+
2429
3218
  if ( ca_func[ca->obj_type].fill_stride ) {
2430
3219
  ca_func[ca->obj_type].fill_stride(ap, base, ndim, counts, steps, ptr);
2431
3220
  return;
@@ -2544,6 +3333,11 @@ ca_fill_addrs (void *ap, ca_size_t n, ca_size_t *addrs, void *ptr)
2544
3333
  ca_refuse_read_only();
2545
3334
  }
2546
3335
 
3336
+ if ( ca->ptr == NULL ) {
3337
+ CA_VALUE_TRIAL_PUT(CA_TRIAL_FILL_ADDRS, ca, n, addrs, NULL, NULL, NULL, ptr);
3338
+ }
3339
+
3340
+
2547
3341
  if ( ca_func[ca->obj_type].fill_addrs ) {
2548
3342
  ca_func[ca->obj_type].fill_addrs(ap, n, addrs, ptr);
2549
3343
  return;
@@ -3067,6 +3861,13 @@ Init_carray_core (void)
3067
3861
 
3068
3862
  ca_init_obj_type();
3069
3863
 
3864
+ rb_define_private_method(rb_cCArray, "refuse_reentry", rb_ca_refuse_reentry, 1);
3865
+
3866
+ rb_cCAWindowGuard = rb_define_class_under(rb_cCArray, "WindowGuard", rb_cObject);
3867
+ rb_undef_alloc_func(rb_cCAWindowGuard);
3868
+ rb_undef_method(CLASS_OF(rb_cCAWindowGuard), "new");
3869
+ rb_define_method(rb_cCAWindowGuard, "call", ca_window_guard_call, 1);
3870
+
3070
3871
  #ifdef CARRAY_DEV_BUILD
3071
3872
  rb_define_singleton_method(rb_cCArray, "attach", rb_ca_s_attach, -1);
3072
3873
  rb_define_singleton_method(rb_cCArray, "attach!", rb_ca_s_attach_bang, -1);
@@ -3085,9 +3886,10 @@ Init_carray_core (void)
3085
3886
  const char *general = getenv("CARRAY_GENERAL_PATH");
3086
3887
  ca_fast_paths_on = !( general && general[0] && strcmp(general, "0") );
3087
3888
  ca_iter_transfer_only_on = ( general && ! strcmp(general, "2") );
3889
+ ca_shortcuts_off_from_env();
3088
3890
  }
3089
3891
  rb_define_singleton_method(rb_cCArray, "__fast_paths_enabled__",
3090
- rb_ca_s_fast_paths_enabled, 0);
3892
+ rb_ca_s_fast_paths_enabled, -1);
3091
3893
  rb_define_singleton_method(rb_cCArray, "__iter_by_transfer_only__",
3092
3894
  rb_ca_s_iter_by_transfer_only, 0);
3093
3895
  #endif