lexer_kit 0.6.0 → 0.7.0

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 (114) hide show
  1. checksums.yaml +4 -4
  2. data/Cargo.lock +265 -0
  3. data/Cargo.toml +37 -0
  4. data/README.md +7 -3
  5. data/crates/lexer_kit_core/Cargo.toml +17 -0
  6. data/crates/lexer_kit_core/src/dfa.rs +437 -0
  7. data/crates/lexer_kit_core/src/format.rs +599 -0
  8. data/crates/lexer_kit_core/src/lib.rs +18 -0
  9. data/{ext/lexer_kit_rust → crates/lexer_kit_core}/src/opcodes.rs +375 -1
  10. data/{ext/lexer_kit_rust → crates/lexer_kit_core}/src/safety_test.rs +21 -16
  11. data/crates/lexer_kit_core/src/token_buffer.rs +130 -0
  12. data/{ext/lexer_kit_rust → crates/lexer_kit_core}/src/trie.rs +37 -1
  13. data/{ext/lexer_kit_rust → crates/lexer_kit_core}/src/types.rs +1 -1
  14. data/{ext/lexer_kit_rust → crates/lexer_kit_core}/src/vm.rs +165 -2
  15. data/ext/lexer_kit_rust/Cargo.toml +7 -3
  16. data/ext/lexer_kit_rust/src/fast_stream.rs +101 -438
  17. data/ext/lexer_kit_rust/src/lib.rs +200 -215
  18. data/lib/lexer_kit/builder/compiler.rb +50 -15
  19. data/lib/lexer_kit/builder/conflict_detector.rb +18 -20
  20. data/lib/lexer_kit/builder/validator.rb +45 -0
  21. data/lib/lexer_kit/builder.rb +34 -7
  22. data/lib/lexer_kit/cli/commands.rb +17 -7
  23. data/lib/lexer_kit/core/source.rb +3 -2
  24. data/lib/lexer_kit/debug/disassembler.rb +0 -2
  25. data/lib/lexer_kit/dfa/dfa_builder.rb +1 -1
  26. data/lib/lexer_kit/dfa/dfa_minimizer.rb +2 -2
  27. data/lib/lexer_kit/dfa/regex_ast.rb +4 -0
  28. data/lib/lexer_kit/dfa/regex_parser.rb +41 -8
  29. data/lib/lexer_kit/errors.rb +2 -2
  30. data/lib/lexer_kit/format/lkb1.rb +3 -3
  31. data/lib/lexer_kit/format/lkt1.rb +3 -1
  32. data/lib/lexer_kit/format.rb +4 -4
  33. data/lib/lexer_kit/ir/compiled_program.rb +39 -26
  34. data/lib/lexer_kit/ir/constant_pool.rb +33 -11
  35. data/lib/lexer_kit/ir/dfa_table.rb +9 -19
  36. data/lib/lexer_kit/ir/instruction.rb +3 -0
  37. data/lib/lexer_kit/ir/jump_table.rb +3 -13
  38. data/lib/lexer_kit/ir/keyword_table.rb +0 -9
  39. data/lib/lexer_kit/ir/limits.rb +48 -0
  40. data/lib/lexer_kit/ir/serializer.rb +69 -30
  41. data/lib/lexer_kit/ir.rb +1 -0
  42. data/lib/lexer_kit/trie.rb +1 -1
  43. data/lib/lexer_kit/version.rb +1 -1
  44. data/lib/lexer_kit.rb +20 -2
  45. data/vendor/nupur/Cargo.toml +24 -0
  46. data/vendor/nupur/LICENSE +176 -0
  47. data/vendor/nupur/NOTICE +64 -0
  48. data/vendor/nupur/README.ja.md +150 -0
  49. data/vendor/nupur/README.md +257 -0
  50. data/vendor/nupur/src/abi.rs +143 -0
  51. data/vendor/nupur/src/args.rs +318 -0
  52. data/vendor/nupur/src/build.rs +101 -0
  53. data/vendor/nupur/src/caught.rs +171 -0
  54. data/vendor/nupur/src/cname.rs +37 -0
  55. data/vendor/nupur/src/describe.rs +175 -0
  56. data/vendor/nupur/src/encoding.rs +240 -0
  57. data/vendor/nupur/src/gvl.rs +181 -0
  58. data/vendor/nupur/src/hash.rs +52 -0
  59. data/vendor/nupur/src/inject.rs +20 -0
  60. data/vendor/nupur/src/lib.rs +280 -0
  61. data/vendor/nupur/src/lint_probe.rs +142 -0
  62. data/vendor/nupur/src/msg.rs +193 -0
  63. data/vendor/nupur/src/no_unwind.rs +39 -0
  64. data/vendor/nupur/src/raw/check.rs +71 -0
  65. data/vendor/nupur/src/raw/data.rs +28 -0
  66. data/vendor/nupur/src/raw/define.rs +215 -0
  67. data/vendor/nupur/src/raw/exception.rs +69 -0
  68. data/vendor/nupur/src/raw/iterate.rs +115 -0
  69. data/vendor/nupur/src/raw/mod.rs +105 -0
  70. data/vendor/nupur/src/raw/protect.rs +144 -0
  71. data/vendor/nupur/src/raw/string.rs +148 -0
  72. data/vendor/nupur/src/raw/symbol.rs +38 -0
  73. data/vendor/nupur/src/raw/values.rs +293 -0
  74. data/vendor/nupur/src/rb/call.rs +118 -0
  75. data/vendor/nupur/src/rb/class.rs +170 -0
  76. data/vendor/nupur/src/rb/convert.rs +134 -0
  77. data/vendor/nupur/src/rb/error.rs +355 -0
  78. data/vendor/nupur/src/rb/global.rs +141 -0
  79. data/vendor/nupur/src/rb/kept.rs +55 -0
  80. data/vendor/nupur/src/rb/method/frame.rs +81 -0
  81. data/vendor/nupur/src/rb/method.rs +468 -0
  82. data/vendor/nupur/src/rb/mod.rs +40 -0
  83. data/vendor/nupur/src/rb/object.rs +66 -0
  84. data/vendor/nupur/src/rb/ruby.rs +107 -0
  85. data/vendor/nupur/src/rb/value/header.rs +65 -0
  86. data/vendor/nupur/src/rb/value/id.rs +61 -0
  87. data/vendor/nupur/src/rb/value/integer.rs +132 -0
  88. data/vendor/nupur/src/rb/value.rs +454 -0
  89. data/vendor/nupur/src/stack.rs +32 -0
  90. data/vendor/nupur/src/string/make.rs +234 -0
  91. data/vendor/nupur/src/string/mod.rs +24 -0
  92. data/vendor/nupur/src/string/read.rs +411 -0
  93. data/vendor/nupur/src/table.rs +58 -0
  94. data/vendor/nupur/src/typed/callbacks.rs +125 -0
  95. data/vendor/nupur/src/typed/data_type.rs +132 -0
  96. data/vendor/nupur/src/typed/embedded.rs +103 -0
  97. data/vendor/nupur/src/typed/external.rs +76 -0
  98. data/vendor/nupur/src/typed/hidden.rs +95 -0
  99. data/vendor/nupur/src/typed/mod.rs +373 -0
  100. data/vendor/nupur/src/utf8_copy.rs +262 -0
  101. data/vendor/nupur/sys/Cargo.toml +29 -0
  102. data/vendor/nupur/sys/src/data_type.rs +213 -0
  103. data/vendor/nupur/sys/src/int.rs +248 -0
  104. data/vendor/nupur/sys/src/lib.rs +61 -0
  105. data/vendor/nupur/sys/src/lint_probe.rs +93 -0
  106. data/vendor/nupur/sys/src/no_unwind.rs +99 -0
  107. data/vendor/nupur/sys/src/non_raising.rs +585 -0
  108. data/vendor/nupur/sys/src/protect.rs +349 -0
  109. data/vendor/nupur/sys/src/raising.rs +257 -0
  110. data/vendor/nupur/sys/src/value.rs +279 -0
  111. data/vendor/nupur.sha256 +68 -0
  112. metadata +102 -8
  113. data/ext/lexer_kit_rust/src/deserializer.rs +0 -213
  114. data/ext/lexer_kit_rust/src/dfa.rs +0 -217
@@ -0,0 +1,58 @@
1
+ //! [`IntTable`]: a Ruby Hash from small non-negative integers to values, kept
2
+ //! by one object as its private table - a cache, say, from an index to the
3
+ //! one wrapper made for it. A key is a `u32` that must be a
4
+ //! Fixnum: up to 2^30 - 1 on Windows, whose `long` is 32 bits.
5
+ //!
6
+ //! A Ruby Hash rather than a Rust map, so the GC marks its values and moves
7
+ //! them itself, and the owner keeps one value (the table) where its mark
8
+ //! finds it. Its keys are Fixnums, which hash and compare in C, so no Ruby
9
+ //! code runs on a lookup; how an integer becomes one is the layer's
10
+ //! (`raw::table_get` / `table_set`), as is the hiding of the Hash. An
11
+ //! owner keeps it by handing it to its wrap as a slot's root
12
+ //! ([`crate::typed::Root`]): it is never a `Value` of its own.
13
+
14
+ #![forbid(unsafe_code)]
15
+
16
+ use crate::rb::{Error, RHash, ReprValue, Ruby, Value};
17
+
18
+ /// A Hash keyed by small non-negative integers ([module docs](self)).
19
+ #[derive(Clone, Copy)]
20
+ pub struct IntTable(RHash);
21
+
22
+ impl IntTable {
23
+ /// An empty table, hidden from `ObjectSpace` from the moment it is made:
24
+ /// no Ruby code can find it to clear, freeze or fill it. Hand it to no
25
+ /// Ruby code - a hidden object has no class - only to an owner's slot.
26
+ pub fn new_hidden(ruby: &Ruby) -> Result<IntTable, Error> {
27
+ crate::raw::hidden_hash_new(ruby).map(IntTable)
28
+ }
29
+
30
+ /// The table `v` is, read back from where its owner keeps it: `None`
31
+ /// for a value that is not a Hash.
32
+ #[inline]
33
+ pub fn from_value(v: Value) -> Option<IntTable> {
34
+ RHash::from_value(v).map(IntTable)
35
+ }
36
+
37
+ /// The table as a value. The layer's alone: a hidden object has no
38
+ /// class, so the table is handed out only as a slot's root
39
+ /// ([`crate::typed::Root`]), never as a `Value` Ruby code could be given.
40
+ #[inline]
41
+ pub(crate) fn as_value(self) -> Value {
42
+ self.0.as_value()
43
+ }
44
+
45
+ /// The value at `n`, or `None` - also for an `n` past a Fixnum, which
46
+ /// no entry can have.
47
+ #[inline]
48
+ pub fn get(self, n: u32) -> Result<Option<Value>, Error> {
49
+ crate::raw::table_get(self.0, n)
50
+ }
51
+
52
+ /// Set the value at `n`: raises `NoMemoryError`, and an `n` past a
53
+ /// Fixnum is a `RangeError` - refused, never wrapped round.
54
+ #[inline]
55
+ pub fn set(self, n: u32, v: Value) -> Result<(), Error> {
56
+ crate::raw::table_set(self.0, n, v)
57
+ }
58
+ }
@@ -0,0 +1,125 @@
1
+ //! The GC callbacks Ruby drives for every [`TypedType`](super::TypedType):
2
+ //! the one monomorphised bridge from Ruby's collector to [`Payload`].
3
+
4
+ #![allow(unsafe_code)]
5
+
6
+ use core::ffi::c_void;
7
+
8
+ use super::{Envelope, Payload};
9
+
10
+ /* The GC callbacks below are the crate's only `extern "C"` functions with no
11
+ * panic latch, and deliberately so. They run from Ruby's collector, where
12
+ * there is no frame to raise into: `mark_cb` cannot report a failure without
13
+ * risking premature collection of what it did not mark, and `free_cb` cannot
14
+ * report one without leaking or freeing twice. So a panic here keeps the old
15
+ * behaviour - Rust turns the unwind at the boundary into an abort - which is
16
+ * the honest answer when the alternative is a corrupted heap. Keep their
17
+ * bodies trivial; that is what makes the choice cheap.
18
+ *
19
+ * Each passes over a null data pointer. `rb_data_typed_object_zalloc` makes
20
+ * the object before it allocates a non-embedded type's data, so a failed
21
+ * allocation leaves an object with none; CRuby's collector does not call a
22
+ * callback for it today, but that is its implementation, not its documented
23
+ * contract, and one branch here means nothing rests on it. */
24
+
25
+ pub(super) unsafe extern "C" fn mark_cb<T: Payload, const N: usize>(ptr: *mut c_void) {
26
+ crate::no_unwind::must_not_unwind::<crate::no_unwind::GcMark, _>(|| {
27
+ if ptr.is_null() {
28
+ return;
29
+ }
30
+ // SAFETY: Ruby hands back the data pointer of an object `wrap_built`
31
+ // made, which holds a live envelope (see `wrap_built`). Only the slots
32
+ // are read: no reference to the payload is made, which a method may be
33
+ // reading when the collector runs.
34
+ let roots = unsafe { core::ptr::addr_of!((*(ptr as *const Envelope<T, N>)).roots).read() };
35
+ for r in roots {
36
+ // SAFETY: this is a dmark callback, in Ruby's mark phase, with the
37
+ // GVL held; a slot holds a live value (or `Qfalse`); and this
38
+ // frame loses nothing to a longjmp (the no_unwind guard's Drop
39
+ // does nothing unless unwinding).
40
+ unsafe { nupur_sys::non_raising::gc_mark_in_dmark(r) };
41
+ }
42
+ })
43
+ }
44
+
45
+ /// Give back what the payload reported, once it is dropped.
46
+ ///
47
+ /// # Safety
48
+ /// From a free callback (`gc_give_back_in_dfree`'s contract).
49
+ #[inline]
50
+ unsafe fn give_back(reported: usize) {
51
+ if reported != 0 {
52
+ let n = nupur_sys::ssize_t::try_from(reported).unwrap_or(nupur_sys::ssize_t::MAX);
53
+ // SAFETY: from a free callback, the caller's contract.
54
+ unsafe { nupur_sys::non_raising::gc_give_back_in_dfree(n) };
55
+ }
56
+ }
57
+
58
+ pub(super) unsafe extern "C" fn free_cb<T: Payload, const N: usize>(ptr: *mut c_void) {
59
+ crate::no_unwind::must_not_unwind::<crate::no_unwind::GcFree, _>(|| {
60
+ if ptr.is_null() {
61
+ return;
62
+ }
63
+ // SAFETY: as `mark_cb`; the object is being collected, so this is its
64
+ // last access - the payload is dropped exactly once, here, and never
65
+ // read again - and the data came from `rb_data_typed_object_zalloc`'s
66
+ // `xcalloc`, so it goes back to `ruby_xfree`, as
67
+ // `TypedData_Make_Struct`'s data does.
68
+ /* The drop is a read and `quietly`: a type whose drop the compiler
69
+ * cannot show unwind-free (a tree's recursive glue) is caught rather
70
+ * than unwound into the collector. */
71
+ unsafe {
72
+ let data = core::ptr::addr_of!((*(ptr as *const Envelope<T, N>)).data).read();
73
+ let reported = crate::caught::quietly(0, || data.reported_external());
74
+ crate::caught::quietly((), || drop(data));
75
+ give_back(reported);
76
+ nupur_sys::non_raising::xfree_in_dfree(ptr);
77
+ }
78
+ })
79
+ }
80
+
81
+ pub(super) unsafe extern "C" fn free_embedded_cb<T: Payload, const N: usize>(ptr: *mut c_void) {
82
+ crate::no_unwind::must_not_unwind::<crate::no_unwind::GcFreeEmbedded, _>(|| {
83
+ if ptr.is_null() {
84
+ return;
85
+ }
86
+ // SAFETY: as `free_cb`, for an embeddable type: the payload is dropped
87
+ // and the memory is left to Ruby - the object's own slot when it was
88
+ // embedded, and data Ruby frees after this callback when it was not.
89
+ let data = unsafe { core::ptr::addr_of!((*(ptr as *const Envelope<T, N>)).data).read() };
90
+ let reported = crate::caught::quietly(0, || data.reported_external());
91
+ crate::caught::quietly((), || drop(data));
92
+ // SAFETY: a free callback.
93
+ unsafe { give_back(reported) };
94
+ })
95
+ }
96
+
97
+ /// The bytes the object owns beyond what Ruby counts itself. For a plain
98
+ /// type that is the whole envelope (Ruby counts its slot, not the data it
99
+ /// points at); for an embeddable one Ruby counts the envelope - as part of
100
+ /// the slot it is embedded in, or by the allocation's own size when it is
101
+ /// not - so only what the payload owns beyond its struct is left.
102
+ pub(super) unsafe extern "C" fn memsize_cb<T: Payload, const N: usize, const EMBEDDABLE: bool>(
103
+ ptr: *const c_void,
104
+ ) -> nupur_sys::size_t {
105
+ crate::no_unwind::must_not_unwind::<crate::no_unwind::GcMemsize, _>(|| {
106
+ if ptr.is_null() {
107
+ return 0;
108
+ }
109
+ /* `quietly`: the size is advisory, so a panic in it - an overflow
110
+ * check in a sum, say - answers 0 rather than unwinding into the
111
+ * collector. (Not so for mark: a value left unmarked is freed while
112
+ * still referenced, so it must be unwind-free itself.) */
113
+ // SAFETY: as `mark_cb`.
114
+ let data = unsafe { &(*(ptr as *const Envelope<T, N>)).data };
115
+ let slots = core::mem::size_of::<[nupur_sys::value::Root; N]>();
116
+ let bytes = crate::caught::quietly(0, || {
117
+ if EMBEDDABLE {
118
+ data.memsize().saturating_sub(core::mem::size_of::<T>())
119
+ } else {
120
+ data.memsize().saturating_add(slots)
121
+ }
122
+ });
123
+ nupur_sys::size_t::try_from(bytes).unwrap_or(nupur_sys::size_t::MAX)
124
+ })
125
+ }
@@ -0,0 +1,132 @@
1
+ //! The raw machinery behind [`TypedType`](super::TypedType): reading an
2
+ //! object's data pointer, and making an object with its data. The
3
+ //! `rb_data_type_t` it carries is `nupur_sys`'s ([`DataType`]).
4
+
5
+ #![allow(unsafe_code)]
6
+
7
+ use core::ffi::c_void;
8
+
9
+ pub(super) use nupur_sys::data_type::DataType;
10
+
11
+ use super::Envelope;
12
+ use crate::rb::value::AsSys;
13
+ use crate::rb::{Error, Value};
14
+
15
+ /// The data pointer of a TypedData object of type `ty` (or a type deriving
16
+ /// from it), or the `TypeError` Ruby's own check raises.
17
+ ///
18
+ /// The type is tested first, so a well-typed object - every call on the normal
19
+ /// path - makes no protected call: its data pointer is read directly. Only a
20
+ /// mismatch runs `rb_check_typeddata` (protected), which is what keeps the
21
+ /// error message Ruby's own, word for word, on every supported Ruby.
22
+ ///
23
+ /// The pointer is never null: an object whose data was never allocated is a
24
+ /// `TypeError` too. `rb_data_typed_object_zalloc` makes a non-embedded type's
25
+ /// object before its data, so an allocation that failed leaves an object of
26
+ /// the class with none, which `ObjectSpace` can still hand to Ruby code until
27
+ /// it is collected; every reader of a payload comes through here or
28
+ /// [`typed_data_known`].
29
+ pub(super) fn typed_data(v: Value, ty: &'static DataType) -> Result<*mut c_void, Error> {
30
+ let sv = v.as_sys();
31
+ // SAFETY: `v` is a live value and `ty` a registered data type; the data
32
+ // pointer is read only once the type is known to match.
33
+ unsafe {
34
+ if nupur_sys::non_raising::rb_typeddata_is_kind_of(sv, ty) {
35
+ let p = data_pointer(sv);
36
+ if p.is_null() {
37
+ return Err(crate::rb::error::type_error(
38
+ "an object whose data was never allocated",
39
+ ));
40
+ }
41
+ return Ok(p);
42
+ }
43
+ match crate::raw::check_typeddata(sv, ty) {
44
+ Err(e) => Err(e),
45
+ /* rb_typeddata_is_kind_of said no, so the check should have raised. */
46
+ Ok(_) => Err(crate::rb::error::type_error("wrong argument type")),
47
+ }
48
+ }
49
+ }
50
+
51
+ /// The data pointer of a TypedData object, read without a check.
52
+ ///
53
+ /// # Safety
54
+ /// `v` is a TypedData object.
55
+ #[inline]
56
+ pub(super) unsafe fn data_pointer(v: nupur_sys::value::Value) -> *mut c_void {
57
+ // SAFETY: the caller's contract.
58
+ unsafe { nupur_sys::non_raising::rtypeddata_get_data(v) }
59
+ }
60
+
61
+ /// The data pointer of a TypedData object whose type the caller has already
62
+ /// established - a receiver its `TryConvert` checked, or the owner a
63
+ /// checked node holds.
64
+ ///
65
+ /// A mismatch here is a bug in that reasoning, not a user error, so it panics:
66
+ /// the panic unwinds through the Rust frames (running their destructors) and
67
+ /// the method's trampoline makes it the internal error (`rb::error::INTERNAL_ERROR`), where a raise
68
+ /// would longjmp past them.
69
+ pub(super) fn typed_data_known(v: Value, ty: &'static DataType) -> *mut c_void {
70
+ let sv = v.as_sys();
71
+ // SAFETY: as in `typed_data`; the assert is the type check.
72
+ unsafe {
73
+ assert!(
74
+ nupur_sys::non_raising::rb_typeddata_is_kind_of(sv, ty),
75
+ "a VALUE of an established type had a different one"
76
+ );
77
+ let p = data_pointer(sv);
78
+ /* An established object was checked (`typed_data`) or made whole
79
+ * (`wrap_built`), so its data is there. */
80
+ assert!(!p.is_null(), "an established object without its data");
81
+ p
82
+ }
83
+ }
84
+
85
+ /// Make a `klass` object of data type `ty` with room for an envelope, and
86
+ /// write `data` and `roots` into it: `TypedData_Make_Struct`, the C API's own
87
+ /// way to make an object with its data, for every type - embedded or not,
88
+ /// which only decides where Ruby puts the data (`rtypeddata_get_data` finds it
89
+ /// either way).
90
+ ///
91
+ /// One C call, `rb_data_typed_object_zalloc`, makes the object and its data,
92
+ /// so one protected call per object. A non-embedded type's data is its
93
+ /// `xcalloc`, which also makes it a point where Ruby decides whether malloc
94
+ /// pressure calls for a collection: `rb_gc_adjust_memory_usage`, which a
95
+ /// payload reports external memory with, only adds to that pressure, so a loop of
96
+ /// wraps with no Ruby allocation of their data ran no GC at all
97
+ /// (`spec/gc_accounting_spec.rb`).
98
+ ///
99
+ /// The order is the point. The data is zeroed until the envelope is written,
100
+ /// which is not a valid payload, so the payload is built BEFORE the object
101
+ /// exists, and nothing runs between the allocation and the write: no mark,
102
+ /// free or size callback can see the zeroed data, and a panic building the
103
+ /// payload leaves no object at all. The roots are on this frame through the
104
+ /// allocation (the caller's array), where the GC's stack scan keeps them
105
+ /// alive and unmoved, and are in the slots - where the mark finds them -
106
+ /// before anything else runs. A failed allocation - `Err`, from `raw`'s
107
+ /// protected call - drops the payload.
108
+ ///
109
+ /// # Safety
110
+ /// Under the GVL; `ty` must be the type of `T` with `N` slots; each root is
111
+ /// a live value.
112
+ pub(super) unsafe fn wrap_built<T, const N: usize>(
113
+ klass: nupur_sys::value::Value,
114
+ ty: &'static DataType,
115
+ data: T,
116
+ roots: [nupur_sys::value::Root; N],
117
+ ) -> Result<nupur_sys::value::Value, Error> {
118
+ const { assert!(core::mem::size_of::<Envelope<T, N>>() != 0) };
119
+ const { assert!(core::mem::align_of::<Envelope<T, N>>() <= 16) }; /* malloc's alignment */
120
+ let obj = crate::raw::typed_object_zalloc(klass, core::mem::size_of::<Envelope<T, N>>(), ty)?;
121
+ let p = data_pointer(obj) as *mut Envelope<T, N>;
122
+ if p.is_null() {
123
+ return Err(crate::rb::error::internal_error(
124
+ "a TypedData object was made without its data",
125
+ ));
126
+ }
127
+ /* The roots are read here, after the allocation - the one point a
128
+ * collection can run - so they stayed on this frame across it; from
129
+ * here the mark sees them in the slots. */
130
+ p.write(Envelope { roots, data });
131
+ Ok(obj)
132
+ }
@@ -0,0 +1,103 @@
1
+ //! [`EmbeddedType`]: a [`TypedType`] whose envelope is kept in the object's
2
+ //! own slot, and read only by copy.
3
+
4
+ #![allow(unsafe_code)]
5
+
6
+ use core::ffi::CStr;
7
+
8
+ use super::data_type::{typed_data, DataType};
9
+ use super::{Birth, Envelope, Payload, Root, TypedType};
10
+ use crate::rb::{Error, Value};
11
+
12
+ /// A [`TypedType`] whose envelope is kept IN the object's slot
13
+ /// (`RUBY_TYPED_EMBEDDABLE`): no allocation beside the object's own, and
14
+ /// none to free. Only for a small payload (see [`EMBED_MAX`]).
15
+ ///
16
+ /// Compaction moves embedded data with its object, so a `&T` held across
17
+ /// anything that can run the collector - an allocation - would point at
18
+ /// where the data was. This type is what keeps that from being written: it
19
+ /// has no `get`. A reader takes [`read`](Self::read)'s copy - the payload is
20
+ /// `Copy` - and only the GC callbacks see the data in place.
21
+ pub struct EmbeddedType<T: Payload + Copy, const N: usize = 0>(TypedType<T, N>);
22
+
23
+ impl<T: Payload + Copy, const N: usize> EmbeddedType<T, N> {
24
+ /// An embedded type deriving from `parent` (`None` for a base type),
25
+ /// shareable or not, its envelope held to what an object's slot takes.
26
+ const fn with_flags(
27
+ name: &'static CStr,
28
+ parent: Option<&'static DataType>,
29
+ shareable: bool,
30
+ ) -> EmbeddedType<T, N> {
31
+ const { assert!(core::mem::size_of::<Envelope<T, N>>() <= EMBED_MAX) };
32
+ const { assert!(core::mem::align_of::<Envelope<T, N>>() <= EMBED_ALIGN) };
33
+ EmbeddedType(TypedType::with_flags(name, parent, true, shareable))
34
+ }
35
+
36
+ /// A base type.
37
+ pub const fn base(name: &'static CStr) -> EmbeddedType<T, N> {
38
+ Self::with_flags(name, None, false)
39
+ }
40
+
41
+ /// A base type whose objects are shared between Ractors, as
42
+ /// [`TypedType::shareable`]'s are.
43
+ pub const fn shareable(name: &'static CStr) -> EmbeddedType<T, N>
44
+ where
45
+ T: Sync,
46
+ {
47
+ Self::with_flags(name, None, true)
48
+ }
49
+
50
+ /// A type deriving from `parent`, which holds the same payload and
51
+ /// slots, shareable when `parent`'s objects are.
52
+ ///
53
+ /// `parent` is `'static`, as [`TypedType::derived`]'s.
54
+ pub const fn derived(
55
+ name: &'static CStr,
56
+ parent: &'static EmbeddedType<T, N>,
57
+ ) -> EmbeddedType<T, N> {
58
+ Self::with_flags(name, Some(&parent.0.raw), parent.0.shareable)
59
+ }
60
+
61
+ /// Whether `v` is an object of this type or one deriving from it. Never
62
+ /// raises.
63
+ #[inline]
64
+ pub fn is(&'static self, v: Value) -> bool {
65
+ self.0.is(v)
66
+ }
67
+
68
+ /// A copy of `v`'s payload and slots, or Ruby's own `TypeError`. The
69
+ /// data is read in place and copied out at once: no reference into the
70
+ /// object is held past this call.
71
+ #[inline]
72
+ pub fn read(&'static self, v: Value) -> Result<(T, [Value; N]), Error> {
73
+ let p = typed_data(v, &self.0.raw)? as *const Envelope<T, N>;
74
+ // SAFETY: `typed_data` verified the type; the envelope is copied out
75
+ // (`T: Copy`) with nothing run between, and the slots hold live values
76
+ // the caller's `v` keeps marked.
77
+ let (data, roots) = unsafe { ((*p).data, (*p).roots) };
78
+ // SAFETY: as above.
79
+ Ok((data, roots.map(|r| Value::from_sys(unsafe { r.value() }))))
80
+ }
81
+
82
+ /// [`TypedType::wrap`], as a bare `Value`: an embedded payload is never
83
+ /// borrowed (only [`read`](Self::read)'s copy), so there is nothing for
84
+ /// a [`Typed`](super::Typed) to hold.
85
+ pub fn wrap<R: Root>(
86
+ &'static self,
87
+ ruby: &crate::rb::Ruby,
88
+ birth: Birth<T, R, N>,
89
+ ) -> Result<Value, Error> {
90
+ self.0.wrap_value(ruby, birth)
91
+ }
92
+ }
93
+
94
+ /// The largest envelope an embedded type takes: with `RTypedData`'s header it fits
95
+ /// the 80-byte slot, well inside Ruby's largest (640), so
96
+ /// `rb_data_typed_object_zalloc` embeds it. Were it not embedded, the object
97
+ /// would still be right - its data allocated apart, which Ruby frees.
98
+ pub const EMBED_MAX: usize = 40;
99
+
100
+ /// The strictest alignment an embedded `T` may have: its data starts right
101
+ /// after `RTypedData`'s header, which a slot places at an 8-byte boundary
102
+ /// only - not the 16 `wrap_built` allows for `xcalloc`'s data.
103
+ pub const EMBED_ALIGN: usize = 8;
@@ -0,0 +1,76 @@
1
+ //! [`External`]: the memory an object holds outside Ruby's heap, as it is
2
+ //! reported to the GC.
3
+
4
+ #![allow(unsafe_code)]
5
+
6
+ /// The bytes an object holds outside Ruby's heap, as reported to the GC -
7
+ /// the one way a report is made, so what was reported is always what the
8
+ /// free callback gives back ([`Payload::reported_external`](super::Payload::reported_external) answers
9
+ /// [`reported`](Self::reported)).
10
+ ///
11
+ /// Memory Ruby does not allocate is otherwise invisible to it and never
12
+ /// triggers a collection. A cell, so a payload read through `&T` reports.
13
+ #[derive(Default)]
14
+ pub struct External(core::sync::atomic::AtomicUsize);
15
+
16
+ impl External {
17
+ pub const fn new() -> External {
18
+ External(core::sync::atomic::AtomicUsize::new(0))
19
+ }
20
+
21
+ /// What has been reported and not given back.
22
+ #[inline]
23
+ pub fn reported(&self) -> usize {
24
+ self.0.load(core::sync::atomic::Ordering::Relaxed)
25
+ }
26
+
27
+ /// The object holds `bytes` outside the heap now: the change since the
28
+ /// last report goes to the GC. A change Ruby could not take whole - past
29
+ /// an `ssize_t` - is not reported, and not recorded, so the two never
30
+ /// disagree. The default collector only raises its malloc count here and
31
+ /// collects at the next allocation (`rb_gc_adjust_memory_usage` is
32
+ /// MEMOP_TYPE_REALLOC), but another may collect in the call, so what is
33
+ /// borrowed across it must be what a collection neither frees nor moves:
34
+ /// this payload, whose object its caller keeps (a receiver, a slot's
35
+ /// value, a [`Typed`](super::Typed) handle) and which compaction does not move - never
36
+ /// a String's bytes. The new figure is recorded first, for a collection
37
+ /// that reads it.
38
+ pub fn report(&self, ruby: &crate::rb::Ruby, bytes: usize) {
39
+ self.move_to(ruby, |_| bytes);
40
+ }
41
+
42
+ /// [`report`](Self::report) `more` bytes than were.
43
+ #[inline]
44
+ pub fn grow(&self, ruby: &crate::rb::Ruby, more: usize) {
45
+ self.move_to(ruby, |then| then.saturating_add(more));
46
+ }
47
+
48
+ /// Record `to(then)` in place of `then` and report the difference.
49
+ ///
50
+ /// A shareable payload is reached from several Ractors at once, each
51
+ /// holding its own lock and not a process-wide one, so the figure is
52
+ /// swapped by compare-and-exchange: the delta reported is always from
53
+ /// the figure it replaced, and two reports never count one change twice.
54
+ fn move_to(&self, ruby: &crate::rb::Ruby, to: impl Fn(usize) -> usize) {
55
+ use core::sync::atomic::Ordering::Relaxed;
56
+ let mut then = self.0.load(Relaxed);
57
+ let delta = loop {
58
+ let bytes = to(then);
59
+ let delta = if bytes >= then {
60
+ nupur_sys::ssize_t::try_from(bytes - then)
61
+ } else {
62
+ nupur_sys::ssize_t::try_from(then - bytes).map(|d| -d)
63
+ };
64
+ let Ok(delta) = delta else { return };
65
+ if delta == 0 {
66
+ return;
67
+ }
68
+ match self.0.compare_exchange_weak(then, bytes, Relaxed, Relaxed) {
69
+ Ok(_) => break delta,
70
+ Err(now) => then = now,
71
+ }
72
+ };
73
+ // SAFETY: a plain counter adjustment, with the GVL held (`&Ruby`).
74
+ unsafe { nupur_sys::non_raising::rb_gc_adjust_memory_usage(ruby.sys(), delta) };
75
+ }
76
+ }
@@ -0,0 +1,95 @@
1
+ //! [`TypedType::wrap_hidden`]: an object kept hidden from Ruby code while
2
+ //! its data is completed, and shown only once it is whole.
3
+
4
+ #![allow(unsafe_code)]
5
+
6
+ use super::{Birth, Payload, Root, Typed, TypedType};
7
+ use crate::rb::{Error, Value};
8
+
9
+ impl<T: Payload + 'static, const N: usize> TypedType<T, N> {
10
+ /// [`wrap`](Self::wrap) an object whose data is not complete when it is
11
+ /// made - one whose content arrives after it - and keep it HIDDEN
12
+ /// (`rb_obj_hide`: no class, so `ObjectSpace` does not list it and no
13
+ /// Ruby code can find it) while `fill` completes the data; then show it
14
+ /// with its class and return it.
15
+ ///
16
+ /// The object is never handed out before that: a hidden object has no
17
+ /// class, and Ruby code given one - a return value, an Array element -
18
+ /// would crash on it. `fill` sees only the data, and may run anything
19
+ /// (a GVL-released parse included), since nothing can reach the object.
20
+ /// An `Err` from `fill`, or a failure to show the object, leaves it
21
+ /// hidden for the GC to free, and is returned. The object comes back as
22
+ /// the [`Typed`] handle that held it through `fill`, so a caller that
23
+ /// goes on using it before handing it to Ruby still holds it.
24
+ ///
25
+ /// It is not hidden from birth. `ivars`, its hidden ivars (names without
26
+ /// `@`), are written first, while it still has its class - generic ivar
27
+ /// storage may read an object's class, so nothing is set on one that has
28
+ /// none - and then it is hidden. What keeps Ruby code from finding it in
29
+ /// between is that none runs there: the ivar writes may allocate, and so
30
+ /// collect, but a collection runs no Ruby code. A step added between the
31
+ /// wrap and the hide that can run Ruby code breaks that. A failed
32
+ /// allocation of a non-embedded type's data leaves an object of the class
33
+ /// with no data, visible, which every reader refuses (`typed_data`).
34
+ ///
35
+ /// Nothing but this call refers to the object until it is shown, so its
36
+ /// data is lent to `fill` through the handle the wrap made, held as a
37
+ /// `Hidden` - which lends the data and shows the object, and hands out
38
+ /// nothing else.
39
+ pub fn wrap_hidden<R: Root>(
40
+ &'static self,
41
+ ruby: &crate::rb::Ruby,
42
+ birth: Birth<T, R, N>,
43
+ ivars: &[(crate::rb::HiddenId, Value)],
44
+ fill: impl FnOnce(&T) -> Result<(), Error>,
45
+ ) -> Result<Typed<T, N>, Error> {
46
+ let klass = birth.klass;
47
+ let made = self.wrap(ruby, birth)?;
48
+ let written = ivars
49
+ .iter()
50
+ .try_for_each(|&(id, v)| crate::raw::ivar_set(made.value(), id, v));
51
+ // SAFETY: the object just made, which nothing but `made` refers to.
52
+ let hidden = unsafe { Hidden::hide(made, klass) };
53
+ written?;
54
+ fill(hidden.data())?;
55
+ hidden.show()
56
+ }
57
+ }
58
+
59
+ /// An object [`TypedType::wrap_hidden`] has hidden: its data can be lent
60
+ /// and it can be shown, but its value cannot be had - a hidden object has no
61
+ /// class, and Ruby code given one would crash on it. Dropped unshown, it
62
+ /// stays hidden for the GC to free.
63
+ struct Hidden<T: Payload + 'static, const N: usize> {
64
+ made: Typed<T, N>,
65
+ klass: crate::rb::DataClass,
66
+ }
67
+
68
+ impl<T: Payload + 'static, const N: usize> Hidden<T, N> {
69
+ /// Hide `made`, to be shown as an instance of `klass`.
70
+ ///
71
+ /// # Safety
72
+ /// `made` is an object just made that nothing else refers to - no Ruby
73
+ /// code holds it, and none will be handed it while it is hidden.
74
+ unsafe fn hide(made: Typed<T, N>, klass: crate::rb::DataClass) -> Hidden<T, N> {
75
+ // SAFETY: the caller's contract; hiding writes only the object's
76
+ // class field, which `show` restores.
77
+ unsafe { crate::rb::object::obj_hide(made.value()) };
78
+ Hidden { made, klass }
79
+ }
80
+
81
+ /// The payload, lent while the object is hidden.
82
+ fn data(&self) -> &T {
83
+ self.made.data()
84
+ }
85
+
86
+ /// Show the object with its class again, and hand it out. A failure (out
87
+ /// of memory) leaves it hidden, for the GC.
88
+ fn show(self) -> Result<Typed<T, N>, Error> {
89
+ crate::raw::obj_reveal(
90
+ self.made.value(),
91
+ crate::rb::ReprValue::as_value(self.klass),
92
+ )?;
93
+ Ok(self.made)
94
+ }
95
+ }