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.
- checksums.yaml +4 -4
- data/Cargo.lock +265 -0
- data/Cargo.toml +37 -0
- data/README.md +7 -3
- data/crates/lexer_kit_core/Cargo.toml +17 -0
- data/crates/lexer_kit_core/src/dfa.rs +437 -0
- data/crates/lexer_kit_core/src/format.rs +599 -0
- data/crates/lexer_kit_core/src/lib.rs +18 -0
- data/{ext/lexer_kit_rust → crates/lexer_kit_core}/src/opcodes.rs +375 -1
- data/{ext/lexer_kit_rust → crates/lexer_kit_core}/src/safety_test.rs +21 -16
- data/crates/lexer_kit_core/src/token_buffer.rs +130 -0
- data/{ext/lexer_kit_rust → crates/lexer_kit_core}/src/trie.rs +37 -1
- data/{ext/lexer_kit_rust → crates/lexer_kit_core}/src/types.rs +1 -1
- data/{ext/lexer_kit_rust → crates/lexer_kit_core}/src/vm.rs +165 -2
- data/ext/lexer_kit_rust/Cargo.toml +7 -3
- data/ext/lexer_kit_rust/src/fast_stream.rs +101 -438
- data/ext/lexer_kit_rust/src/lib.rs +200 -215
- data/lib/lexer_kit/builder/compiler.rb +50 -15
- data/lib/lexer_kit/builder/conflict_detector.rb +18 -20
- data/lib/lexer_kit/builder/validator.rb +45 -0
- data/lib/lexer_kit/builder.rb +34 -7
- data/lib/lexer_kit/cli/commands.rb +17 -7
- data/lib/lexer_kit/core/source.rb +3 -2
- data/lib/lexer_kit/debug/disassembler.rb +0 -2
- data/lib/lexer_kit/dfa/dfa_builder.rb +1 -1
- data/lib/lexer_kit/dfa/dfa_minimizer.rb +2 -2
- data/lib/lexer_kit/dfa/regex_ast.rb +4 -0
- data/lib/lexer_kit/dfa/regex_parser.rb +41 -8
- data/lib/lexer_kit/errors.rb +2 -2
- data/lib/lexer_kit/format/lkb1.rb +3 -3
- data/lib/lexer_kit/format/lkt1.rb +3 -1
- data/lib/lexer_kit/format.rb +4 -4
- data/lib/lexer_kit/ir/compiled_program.rb +39 -26
- data/lib/lexer_kit/ir/constant_pool.rb +33 -11
- data/lib/lexer_kit/ir/dfa_table.rb +9 -19
- data/lib/lexer_kit/ir/instruction.rb +3 -0
- data/lib/lexer_kit/ir/jump_table.rb +3 -13
- data/lib/lexer_kit/ir/keyword_table.rb +0 -9
- data/lib/lexer_kit/ir/limits.rb +48 -0
- data/lib/lexer_kit/ir/serializer.rb +69 -30
- data/lib/lexer_kit/ir.rb +1 -0
- data/lib/lexer_kit/trie.rb +1 -1
- data/lib/lexer_kit/version.rb +1 -1
- data/lib/lexer_kit.rb +20 -2
- data/vendor/nupur/Cargo.toml +24 -0
- data/vendor/nupur/LICENSE +176 -0
- data/vendor/nupur/NOTICE +64 -0
- data/vendor/nupur/README.ja.md +150 -0
- data/vendor/nupur/README.md +257 -0
- data/vendor/nupur/src/abi.rs +143 -0
- data/vendor/nupur/src/args.rs +318 -0
- data/vendor/nupur/src/build.rs +101 -0
- data/vendor/nupur/src/caught.rs +171 -0
- data/vendor/nupur/src/cname.rs +37 -0
- data/vendor/nupur/src/describe.rs +175 -0
- data/vendor/nupur/src/encoding.rs +240 -0
- data/vendor/nupur/src/gvl.rs +181 -0
- data/vendor/nupur/src/hash.rs +52 -0
- data/vendor/nupur/src/inject.rs +20 -0
- data/vendor/nupur/src/lib.rs +280 -0
- data/vendor/nupur/src/lint_probe.rs +142 -0
- data/vendor/nupur/src/msg.rs +193 -0
- data/vendor/nupur/src/no_unwind.rs +39 -0
- data/vendor/nupur/src/raw/check.rs +71 -0
- data/vendor/nupur/src/raw/data.rs +28 -0
- data/vendor/nupur/src/raw/define.rs +215 -0
- data/vendor/nupur/src/raw/exception.rs +69 -0
- data/vendor/nupur/src/raw/iterate.rs +115 -0
- data/vendor/nupur/src/raw/mod.rs +105 -0
- data/vendor/nupur/src/raw/protect.rs +144 -0
- data/vendor/nupur/src/raw/string.rs +148 -0
- data/vendor/nupur/src/raw/symbol.rs +38 -0
- data/vendor/nupur/src/raw/values.rs +293 -0
- data/vendor/nupur/src/rb/call.rs +118 -0
- data/vendor/nupur/src/rb/class.rs +170 -0
- data/vendor/nupur/src/rb/convert.rs +134 -0
- data/vendor/nupur/src/rb/error.rs +355 -0
- data/vendor/nupur/src/rb/global.rs +141 -0
- data/vendor/nupur/src/rb/kept.rs +55 -0
- data/vendor/nupur/src/rb/method/frame.rs +81 -0
- data/vendor/nupur/src/rb/method.rs +468 -0
- data/vendor/nupur/src/rb/mod.rs +40 -0
- data/vendor/nupur/src/rb/object.rs +66 -0
- data/vendor/nupur/src/rb/ruby.rs +107 -0
- data/vendor/nupur/src/rb/value/header.rs +65 -0
- data/vendor/nupur/src/rb/value/id.rs +61 -0
- data/vendor/nupur/src/rb/value/integer.rs +132 -0
- data/vendor/nupur/src/rb/value.rs +454 -0
- data/vendor/nupur/src/stack.rs +32 -0
- data/vendor/nupur/src/string/make.rs +234 -0
- data/vendor/nupur/src/string/mod.rs +24 -0
- data/vendor/nupur/src/string/read.rs +411 -0
- data/vendor/nupur/src/table.rs +58 -0
- data/vendor/nupur/src/typed/callbacks.rs +125 -0
- data/vendor/nupur/src/typed/data_type.rs +132 -0
- data/vendor/nupur/src/typed/embedded.rs +103 -0
- data/vendor/nupur/src/typed/external.rs +76 -0
- data/vendor/nupur/src/typed/hidden.rs +95 -0
- data/vendor/nupur/src/typed/mod.rs +373 -0
- data/vendor/nupur/src/utf8_copy.rs +262 -0
- data/vendor/nupur/sys/Cargo.toml +29 -0
- data/vendor/nupur/sys/src/data_type.rs +213 -0
- data/vendor/nupur/sys/src/int.rs +248 -0
- data/vendor/nupur/sys/src/lib.rs +61 -0
- data/vendor/nupur/sys/src/lint_probe.rs +93 -0
- data/vendor/nupur/sys/src/no_unwind.rs +99 -0
- data/vendor/nupur/sys/src/non_raising.rs +585 -0
- data/vendor/nupur/sys/src/protect.rs +349 -0
- data/vendor/nupur/sys/src/raising.rs +257 -0
- data/vendor/nupur/sys/src/value.rs +279 -0
- data/vendor/nupur.sha256 +68 -0
- metadata +102 -8
- data/ext/lexer_kit_rust/src/deserializer.rs +0 -213
- data/ext/lexer_kit_rust/src/dfa.rs +0 -217
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
//! The TypedData objects, and the GC callbacks Ruby drives.
|
|
2
|
+
//!
|
|
3
|
+
//! A wrapped value is a Rust struct behind a `rb_data_type_t`. Ruby calls the
|
|
4
|
+
//! function pointers in that struct directly, so they have the C calling
|
|
5
|
+
//! convention and receive a raw data pointer - the raw Ruby ABI, and therefore
|
|
6
|
+
//! this layer's job. A struct says what it is through [`Payload`], and the
|
|
7
|
+
//! callbacks (`callbacks`) are the one monomorphised bridge from Ruby's GC to it, so
|
|
8
|
+
//! no other module writes an `extern "C"` GC function.
|
|
9
|
+
//!
|
|
10
|
+
//! What an object holds is an `Envelope`: the payload `T`, and `N` slots
|
|
11
|
+
//! for the Ruby values the object keeps alive. The slots are this module's,
|
|
12
|
+
//! written once - in the same step as the payload, right after the object's
|
|
13
|
+
//! allocation - and never again, and the mark callback marks every one of
|
|
14
|
+
//! them pinned. So a payload holds no Ruby value at all (`rake dylint`'s
|
|
15
|
+
//! `ruby_value_on_heap` refuses one in a `Payload` type), and there is no
|
|
16
|
+
//! trace for a payload to forget: the `DocData.errors` crash - a value stored
|
|
17
|
+
//! before the object that marks it existed - and its mirror, a value stored
|
|
18
|
+
//! where no mark reaches it, have no code to happen in.
|
|
19
|
+
//!
|
|
20
|
+
//! The envelope is the object's data, made with the object by
|
|
21
|
+
//! `rb_data_typed_object_zalloc` (`wrap_built`) - in the object's own slot
|
|
22
|
+
//! for an embedded type, from `xcalloc` otherwise - and the free callback runs
|
|
23
|
+
//! the payload's `Drop` in place before the memory goes back: freeing alone
|
|
24
|
+
//! would skip the destructor, and with it everything the payload owns.
|
|
25
|
+
|
|
26
|
+
#![allow(unsafe_code)]
|
|
27
|
+
|
|
28
|
+
mod callbacks;
|
|
29
|
+
mod data_type;
|
|
30
|
+
mod embedded;
|
|
31
|
+
mod external;
|
|
32
|
+
// An object kept hidden while its data is completed (`TypedType::wrap_hidden`).
|
|
33
|
+
mod hidden;
|
|
34
|
+
|
|
35
|
+
pub use embedded::{EmbeddedType, EMBED_ALIGN, EMBED_MAX};
|
|
36
|
+
pub use external::External;
|
|
37
|
+
|
|
38
|
+
use callbacks::{free_cb, free_embedded_cb, mark_cb, memsize_cb};
|
|
39
|
+
use data_type::{data_pointer, typed_data, typed_data_known, wrap_built, DataType};
|
|
40
|
+
use nupur_sys::data_type::DataFlags;
|
|
41
|
+
|
|
42
|
+
use core::ffi::CStr;
|
|
43
|
+
use core::marker::PhantomData;
|
|
44
|
+
|
|
45
|
+
use crate::rb::value::AsSys;
|
|
46
|
+
use crate::rb::{Error, Value};
|
|
47
|
+
use nupur_sys::value::Root as Slot;
|
|
48
|
+
|
|
49
|
+
/// What an object's slot can be given ([`TypedType::wrap`]'s `roots`): any
|
|
50
|
+
/// Ruby value, or a value only a slot may keep - a hidden
|
|
51
|
+
/// [`IntTable`](crate::table::IntTable), which hands out no `Value` of its
|
|
52
|
+
/// own, since a hidden object has no class and Ruby code given one would
|
|
53
|
+
/// crash on it. Sealed: the value is read by this module alone.
|
|
54
|
+
pub trait Root: Copy + sealed::Root {}
|
|
55
|
+
|
|
56
|
+
impl<T: Copy + sealed::Root> Root for T {}
|
|
57
|
+
|
|
58
|
+
pub(crate) mod sealed {
|
|
59
|
+
use crate::rb::{ReprValue, Value};
|
|
60
|
+
|
|
61
|
+
/// [`super::Root`]'s value, out of reach of the crate's users.
|
|
62
|
+
pub trait Root {
|
|
63
|
+
fn root_value(self) -> Value;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
impl<T: ReprValue> Root for T {
|
|
67
|
+
#[inline]
|
|
68
|
+
fn root_value(self) -> Value {
|
|
69
|
+
self.as_value()
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
impl Root for crate::table::IntTable {
|
|
74
|
+
#[inline]
|
|
75
|
+
fn root_value(self) -> Value {
|
|
76
|
+
self.as_value()
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/// A Rust value owned by a Ruby object: what [`TypedType`] wraps.
|
|
82
|
+
///
|
|
83
|
+
/// It holds no Ruby value - those are the object's slots (`roots` in
|
|
84
|
+
/// [`TypedType::wrap`]). What it owns is released by its ordinary `Drop`,
|
|
85
|
+
/// which the free callback runs - so a `Drop` here runs inside Ruby's
|
|
86
|
+
/// collector, and must neither panic nor call Ruby: memory reported to the
|
|
87
|
+
/// GC is given back by this module ([`Payload::reported_external`]), not by
|
|
88
|
+
/// the `Drop`.
|
|
89
|
+
pub trait Payload: Sized {
|
|
90
|
+
/// The bytes this object owns, reported to Ruby's GC as its size.
|
|
91
|
+
fn memsize(&self) -> usize {
|
|
92
|
+
core::mem::size_of::<Self>()
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/// What this object has reported to the GC and not yet given back - its
|
|
96
|
+
/// [`External`]'s [`reported`](External::reported): the free callback
|
|
97
|
+
/// gives exactly these back after the `Drop`. Read in the collector, so
|
|
98
|
+
/// it must be a plain read.
|
|
99
|
+
fn reported_external(&self) -> usize {
|
|
100
|
+
0
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/// The bytes an object of payload `T` with `N` slots keeps as its data - its
|
|
105
|
+
/// envelope, padding included: what a size ratchet over a wrapper should
|
|
106
|
+
/// measure, since a sum of the parts misses the padding.
|
|
107
|
+
pub const fn envelope_size<T, const N: usize>() -> usize {
|
|
108
|
+
core::mem::size_of::<Envelope<T, N>>()
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/// What an object's data is: its `N` slots, then its payload.
|
|
112
|
+
///
|
|
113
|
+
/// `repr(C)`, so the slots come first at a fixed offset whatever `T` is.
|
|
114
|
+
#[repr(C)]
|
|
115
|
+
struct Envelope<T, const N: usize> {
|
|
116
|
+
/// The values the object keeps alive, marked pinned by [`mark_cb`].
|
|
117
|
+
/// Written once, by [`wrap_built`], and never again.
|
|
118
|
+
roots: [Slot; N],
|
|
119
|
+
data: T,
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/// What a new object is made of: its class, its payload, and the values its
|
|
123
|
+
/// slots keep alive - one value, as they are one object's, which
|
|
124
|
+
/// [`TypedType::wrap`] and its kin make and write together (`wrap_built`).
|
|
125
|
+
pub struct Birth<T, R, const N: usize> {
|
|
126
|
+
/// The class Ruby sees it as.
|
|
127
|
+
pub klass: crate::rb::DataClass,
|
|
128
|
+
/// The payload.
|
|
129
|
+
pub data: T,
|
|
130
|
+
/// What its slots keep alive.
|
|
131
|
+
pub roots: [R; N],
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/// A `rb_data_type_t` for a payload `T` with `N` slots: its GC callbacks
|
|
135
|
+
/// drive [`Payload`] for `T`, and every way to make or read an object of this
|
|
136
|
+
/// type goes through it.
|
|
137
|
+
///
|
|
138
|
+
/// The type parameters are the point. The raw API took a `*const
|
|
139
|
+
/// rb_data_type_t` beside a separate `T`, so wrapping a node's data under a
|
|
140
|
+
/// type for another struct - and reading it back as the wrong one - compiled. Here
|
|
141
|
+
/// the data type, the struct and the slot count are one value, so the pairing
|
|
142
|
+
/// cannot be wrong.
|
|
143
|
+
///
|
|
144
|
+
/// `const`, so a module keeps it in a `static`, as the C did.
|
|
145
|
+
pub struct TypedType<T: Payload, const N: usize = 0> {
|
|
146
|
+
raw: DataType,
|
|
147
|
+
/// Whether its objects are made shareable between Ractors at birth
|
|
148
|
+
/// ([`TypedType::shareable`]).
|
|
149
|
+
shareable: bool,
|
|
150
|
+
_t: PhantomData<fn() -> T>,
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
impl<T: Payload, const N: usize> TypedType<T, N> {
|
|
154
|
+
const fn with_flags(
|
|
155
|
+
name: &'static CStr,
|
|
156
|
+
parent: Option<&'static DataType>,
|
|
157
|
+
embedded: bool,
|
|
158
|
+
shareable: bool,
|
|
159
|
+
) -> TypedType<T, N> {
|
|
160
|
+
let flags = if embedded {
|
|
161
|
+
DataFlags::EMBEDDABLE
|
|
162
|
+
} else {
|
|
163
|
+
DataFlags::SEPARATE
|
|
164
|
+
};
|
|
165
|
+
let flags = if shareable {
|
|
166
|
+
flags.frozen_shareable()
|
|
167
|
+
} else {
|
|
168
|
+
flags
|
|
169
|
+
};
|
|
170
|
+
TypedType {
|
|
171
|
+
shareable,
|
|
172
|
+
raw: DataType::new(
|
|
173
|
+
name,
|
|
174
|
+
parent,
|
|
175
|
+
Some(mark_cb::<T, N>),
|
|
176
|
+
Some(if embedded {
|
|
177
|
+
free_embedded_cb::<T, N>
|
|
178
|
+
} else {
|
|
179
|
+
free_cb::<T, N>
|
|
180
|
+
}),
|
|
181
|
+
Some(if embedded {
|
|
182
|
+
memsize_cb::<T, N, true>
|
|
183
|
+
} else {
|
|
184
|
+
memsize_cb::<T, N, false>
|
|
185
|
+
}),
|
|
186
|
+
flags,
|
|
187
|
+
),
|
|
188
|
+
_t: PhantomData,
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/// A base type. `name` is what Ruby calls the type in its messages and
|
|
193
|
+
/// `ObjectSpace`, read as a C string for the life of the process - so a
|
|
194
|
+
/// `'static` one, NUL-terminated by type.
|
|
195
|
+
pub const fn base(name: &'static CStr) -> TypedType<T, N> {
|
|
196
|
+
Self::with_flags(name, None, false, false)
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/// A base type whose objects are shared between Ractors: each is frozen
|
|
200
|
+
/// and made shareable as it is made ([`wrap`](Self::wrap)), together
|
|
201
|
+
/// with everything its slots reach, which `rb_ractor_make_shareable`
|
|
202
|
+
/// freezes too - so put in a slot only what may be frozen, or is
|
|
203
|
+
/// already. Two Ractors may then read the payload at once, which its
|
|
204
|
+
/// `Sync` bound makes sound; nothing else of the layer mutates it.
|
|
205
|
+
pub const fn shareable(name: &'static CStr) -> TypedType<T, N>
|
|
206
|
+
where
|
|
207
|
+
T: Sync,
|
|
208
|
+
{
|
|
209
|
+
Self::with_flags(name, None, false, true)
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/// A type deriving from `parent`, which holds the same payload and
|
|
213
|
+
/// slots: an object of this type is also one of `parent`'s, and is
|
|
214
|
+
/// shareable between Ractors when `parent`'s are (whose `T: Sync` was
|
|
215
|
+
/// asked when `parent` was made).
|
|
216
|
+
///
|
|
217
|
+
/// `parent` is `'static`: its `rb_data_type_t`'s address is kept, and
|
|
218
|
+
/// Ruby follows it for the life of the process.
|
|
219
|
+
pub const fn derived(name: &'static CStr, parent: &'static TypedType<T, N>) -> TypedType<T, N> {
|
|
220
|
+
Self::with_flags(name, Some(&parent.raw), false, parent.shareable)
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/// Whether `v` is an object of this type or one deriving from it. Never
|
|
224
|
+
/// raises.
|
|
225
|
+
#[inline]
|
|
226
|
+
pub fn is(&'static self, v: Value) -> bool {
|
|
227
|
+
nupur_sys::non_raising::rb_typeddata_is_kind_of(v.as_sys(), &self.raw)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/// `Ok` for an object of this type (or one deriving from it), else Ruby's
|
|
231
|
+
/// own `TypeError` - a type check that borrows nothing, for a caller that
|
|
232
|
+
/// only needs to refuse another kind of value.
|
|
233
|
+
#[inline]
|
|
234
|
+
pub fn ensure(&'static self, v: Value) -> Result<(), Error> {
|
|
235
|
+
typed_data(v, &self.raw).map(|_| ())
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/// A handle on `v`, an object of this type whose type the caller already
|
|
239
|
+
/// established - a node's Document from its slot, a receiver its method's
|
|
240
|
+
/// conversion checked; a mismatch is a bug in that reasoning, and panics.
|
|
241
|
+
///
|
|
242
|
+
/// The fast way in for those: one `rb_typeddata_is_kind_of`, asserted,
|
|
243
|
+
/// where [`check`](Self::check) answers a `TypeError`. Its data is
|
|
244
|
+
/// borrowed from the handle, as any [`Typed`]'s, so the object is held
|
|
245
|
+
/// for as long as the borrow - there is no way from a bare `Value` to a
|
|
246
|
+
/// `&T`, whose lifetime the GC would not see.
|
|
247
|
+
#[inline]
|
|
248
|
+
pub fn known(&'static self, v: Value) -> Typed<T, N> {
|
|
249
|
+
self.known_ptr(v);
|
|
250
|
+
Typed::new(v)
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/// `v` checked once to be an object of this type (or one deriving from
|
|
254
|
+
/// it), or Ruby's own `TypeError`: a [`Typed`], which holds the object and
|
|
255
|
+
/// reads the data and the slots with no check of its own.
|
|
256
|
+
#[inline]
|
|
257
|
+
pub fn check(&'static self, v: Value) -> Result<Typed<T, N>, Error> {
|
|
258
|
+
typed_data(v, &self.raw)?;
|
|
259
|
+
Ok(Typed::new(v))
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/// The envelope behind an object whose type the caller established. The
|
|
263
|
+
/// pointer is valid while `v` is rooted.
|
|
264
|
+
fn known_ptr(&'static self, v: Value) -> *const Envelope<T, N> {
|
|
265
|
+
typed_data_known(v, &self.raw) as *const Envelope<T, N>
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/// Make the object `birth` describes, of this type: its payload wrapped
|
|
269
|
+
/// as an instance of its class, its roots kept alive in its slots. A
|
|
270
|
+
/// failed allocation is `Err`, the payload dropped.
|
|
271
|
+
///
|
|
272
|
+
/// The payload is built, and the roots held, before the object exists:
|
|
273
|
+
/// they are on this frame through the allocation - where the GC's stack
|
|
274
|
+
/// scan keeps the roots alive and in place - and both are written into
|
|
275
|
+
/// the object right after it, with nothing run between (`wrap_built`).
|
|
276
|
+
///
|
|
277
|
+
/// The object comes back as a [`Typed`]: nothing but this frame refers
|
|
278
|
+
/// to it yet, and the handle holds it while its data is borrowed.
|
|
279
|
+
pub fn wrap<R: Root>(
|
|
280
|
+
&'static self,
|
|
281
|
+
ruby: &crate::rb::Ruby,
|
|
282
|
+
birth: Birth<T, R, N>,
|
|
283
|
+
) -> Result<Typed<T, N>, Error> {
|
|
284
|
+
self.wrap_value(ruby, birth).map(Typed::new)
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/// [`wrap`](Self::wrap)'s object as a bare `Value`, for an embedded
|
|
288
|
+
/// type, whose data is never borrowed.
|
|
289
|
+
fn wrap_value<R: Root>(
|
|
290
|
+
&'static self,
|
|
291
|
+
_: &crate::rb::Ruby,
|
|
292
|
+
birth: Birth<T, R, N>,
|
|
293
|
+
) -> Result<Value, Error> {
|
|
294
|
+
let Birth { klass, data, roots } = birth;
|
|
295
|
+
// SAFETY: under the GVL (`&Ruby`), and `ty` is this payload's own type.
|
|
296
|
+
let obj = unsafe {
|
|
297
|
+
wrap_built::<T, N>(
|
|
298
|
+
klass.as_sys(),
|
|
299
|
+
&self.raw,
|
|
300
|
+
data,
|
|
301
|
+
roots.map(|v| Slot::of(sealed::Root::root_value(v).as_sys())),
|
|
302
|
+
)
|
|
303
|
+
}?;
|
|
304
|
+
let obj = Value::from_sys(obj);
|
|
305
|
+
if self.shareable {
|
|
306
|
+
crate::raw::ractor_make_shareable(obj)?;
|
|
307
|
+
}
|
|
308
|
+
Ok(obj)
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/// An object of a [`TypedType<T, N>`], its type established - checked by
|
|
313
|
+
/// [`TypedType::check`], or made by [`TypedType::wrap`] - and the handle its
|
|
314
|
+
/// data is borrowed through. Whatever the object is - a receiver, a value
|
|
315
|
+
/// read from somewhere, one just made that nothing else refers to - the
|
|
316
|
+
/// handle holds it where the GC sees it until the handle is dropped, which
|
|
317
|
+
/// is after the last borrow of [`data`](Self::data): borrow from the handle,
|
|
318
|
+
/// not from a copy of its [`value`](Self::value), and do not `mem::forget`
|
|
319
|
+
/// it. It is the only way to a `&T`: [`TypedType::check`] makes one for a
|
|
320
|
+
/// value Ruby gave, [`TypedType::known`] for one whose type is established,
|
|
321
|
+
/// and [`TypedType::wrap`] returns one for an object just made.
|
|
322
|
+
///
|
|
323
|
+
/// A hot path that reads an object's data and slots several times - a
|
|
324
|
+
/// collection's elements and its owner, per element - pays for the check
|
|
325
|
+
/// once. Sound with no further check because an object's type never changes
|
|
326
|
+
/// after it is made, its data was found allocated (and is never freed
|
|
327
|
+
/// before the object), and a non-embedded type's data, which is all this
|
|
328
|
+
/// reads, is its own allocation, which compaction does not move.
|
|
329
|
+
pub struct Typed<T: Payload + 'static, const N: usize> {
|
|
330
|
+
obj: crate::rb::kept::Kept,
|
|
331
|
+
_t: PhantomData<fn() -> T>,
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
impl<T: Payload + 'static, const N: usize> Typed<T, N> {
|
|
335
|
+
/// A handle on `v`, whose type the caller established.
|
|
336
|
+
#[inline]
|
|
337
|
+
fn new(v: Value) -> Typed<T, N> {
|
|
338
|
+
Typed {
|
|
339
|
+
obj: crate::rb::kept::Kept::new(v),
|
|
340
|
+
_t: PhantomData,
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/// The object, for handing to Ruby or storing where Ruby keeps it.
|
|
345
|
+
#[inline]
|
|
346
|
+
pub fn value(&self) -> Value {
|
|
347
|
+
*self.obj.value()
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/// The object's envelope, borrowed for as long as the handle is.
|
|
351
|
+
#[inline]
|
|
352
|
+
fn envelope(&self) -> &Envelope<T, N> {
|
|
353
|
+
// SAFETY: the type was established when the handle was made, which
|
|
354
|
+
// is `T`'s with `N` slots (a derived type holds the same); the data
|
|
355
|
+
// is the envelope `wrap_built` wrote, and the handle holds the object
|
|
356
|
+
// until after the borrow.
|
|
357
|
+
unsafe { &*(data_pointer(self.value().as_sys()) as *const Envelope<T, N>) }
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/// The payload, borrowed for as long as the handle is.
|
|
361
|
+
#[inline]
|
|
362
|
+
pub fn data(&self) -> &T {
|
|
363
|
+
&self.envelope().data
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/// Slot `I` (`I < N`, checked when it compiles).
|
|
367
|
+
#[inline]
|
|
368
|
+
pub fn root<const I: usize>(&self) -> Value {
|
|
369
|
+
const { assert!(I < N, "no such slot") };
|
|
370
|
+
// SAFETY: the slots hold live values the object marks.
|
|
371
|
+
Value::from_sys(unsafe { self.envelope().roots[I].value() })
|
|
372
|
+
}
|
|
373
|
+
}
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
//! `Utf8Copy`: an owned copy of some bytes, made only once the copy is
|
|
2
|
+
//! checked to be UTF-8 - so it can be read as a `&str` with no further check.
|
|
3
|
+
//!
|
|
4
|
+
//! A String read as text (`string::read_utf8`) is this copy, which is why it
|
|
5
|
+
//! is Ruby-free: the one claim a `&str` rests on -
|
|
6
|
+
//! these bytes are UTF-8 - is made here, by std's validator over the copy
|
|
7
|
+
//! itself, and depends on nothing a Ruby String says about itself (its cached
|
|
8
|
+
//! coderange, which another C extension or a Ruby bug could leave wrong).
|
|
9
|
+
//! The fields are private, so nothing outside this module can change the
|
|
10
|
+
//! bytes once they are checked.
|
|
11
|
+
//!
|
|
12
|
+
//! It depends on std alone, so the test build of Makiri's `falloc` crate (the
|
|
13
|
+
//! one of its crates that may hold `unsafe`) includes this same file
|
|
14
|
+
//! (`#[path]`), where Miri runs its tests without a Ruby (`rake miri`). A copy's heap allocation is fallible, and the extension's
|
|
15
|
+
//! OOM sweep can fail it (`set_alloc_injector`).
|
|
16
|
+
|
|
17
|
+
#![allow(unsafe_code)]
|
|
18
|
+
|
|
19
|
+
/// The function that answers whether the next heap copy fails, registered
|
|
20
|
+
/// by an extension's OOM sweep ([`set_alloc_injector`]).
|
|
21
|
+
#[cfg(feature = "alloc-inject")]
|
|
22
|
+
static ALLOC_INJECTOR: std::sync::OnceLock<fn() -> bool> = std::sync::OnceLock::new();
|
|
23
|
+
|
|
24
|
+
/// Register the OOM sweep's answer, once (nupur's `inject::install`, which
|
|
25
|
+
/// registers the raise half with it); a second registration is ignored.
|
|
26
|
+
#[cfg(feature = "alloc-inject")]
|
|
27
|
+
pub(crate) fn set_alloc_injector(fails: fn() -> bool) {
|
|
28
|
+
let _ = ALLOC_INJECTOR.set(fails);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/// Room for exactly `len` more bytes in the empty `v`, or `false`: a heap
|
|
32
|
+
/// copy's one allocation, which the OOM sweep can fail. The layer's other
|
|
33
|
+
/// byte copy (`string::read_bytes`) reserves through it too, so the sweep
|
|
34
|
+
/// sees that one as well.
|
|
35
|
+
pub(crate) fn reserve_exact(v: &mut Vec<u8>, len: usize) -> bool {
|
|
36
|
+
#[cfg(feature = "alloc-inject")]
|
|
37
|
+
if ALLOC_INJECTOR.get().is_some_and(|fails| fails()) {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
#[allow(
|
|
41
|
+
clippy::disallowed_methods,
|
|
42
|
+
reason = "std's fallible reserve: this module depends on std alone, and the sweep's hook is above"
|
|
43
|
+
)]
|
|
44
|
+
v.try_reserve_exact(len).is_ok()
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/// Up to this many bytes a copy lives inline, on the stack: a short argument
|
|
48
|
+
/// - a name, a query - allocates nothing.
|
|
49
|
+
pub const INLINE: usize = 64;
|
|
50
|
+
|
|
51
|
+
enum Bytes {
|
|
52
|
+
/* A `usize` length, so no conversion stands between `INLINE` and it. */
|
|
53
|
+
Inline { len: usize, buf: [u8; INLINE] },
|
|
54
|
+
Heap(Vec<u8>),
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/// Why no [`Utf8Copy`] was made.
|
|
58
|
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
59
|
+
pub enum CopyError {
|
|
60
|
+
/// The bytes are not UTF-8.
|
|
61
|
+
NotUtf8,
|
|
62
|
+
/// A copy past [`INLINE`] bytes could not be allocated.
|
|
63
|
+
Oom,
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/// Bytes that are UTF-8, owned.
|
|
67
|
+
pub struct Utf8Copy(Bytes);
|
|
68
|
+
|
|
69
|
+
/// Why [`Utf8Copy::from_source`] made no copy: [`CopyError`]'s reasons, or the
|
|
70
|
+
/// caller's own refusal of the bytes.
|
|
71
|
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
72
|
+
pub enum FillError<P> {
|
|
73
|
+
/// The copy could not be made ([`CopyError`]).
|
|
74
|
+
Copy(CopyError),
|
|
75
|
+
/// `refuse` turned the bytes down.
|
|
76
|
+
Refused(P),
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/// What a [`Utf8Copy`] is copied from: a thing of known length that copies
|
|
80
|
+
/// itself out - into a buffer as given, or appended to a `Vec` whose room is
|
|
81
|
+
/// already reserved for it, which it must not grow. A byte slice is one; a
|
|
82
|
+
/// Ruby String is another (`string::read_utf8`'s, over `RString::copy_to` /
|
|
83
|
+
/// `append_to`), which hands no slice of itself out.
|
|
84
|
+
pub trait Source {
|
|
85
|
+
/// How many bytes there are.
|
|
86
|
+
fn byte_len(&self) -> usize;
|
|
87
|
+
/// Copy them into `dst`, as many as fit; how many.
|
|
88
|
+
fn copy_into(&self, dst: &mut [u8]) -> usize;
|
|
89
|
+
/// Append them to `v`, whose spare room holds them; `false`, with `v`
|
|
90
|
+
/// unchanged, when it does not.
|
|
91
|
+
fn append_into(&self, v: &mut Vec<u8>) -> bool;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
impl Source for &[u8] {
|
|
95
|
+
fn byte_len(&self) -> usize {
|
|
96
|
+
<[u8]>::len(self)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
fn copy_into(&self, dst: &mut [u8]) -> usize {
|
|
100
|
+
let n = <[u8]>::len(self).min(dst.len());
|
|
101
|
+
if let (Some(d), Some(s)) = (dst.get_mut(..n), self.get(..n)) {
|
|
102
|
+
d.copy_from_slice(s);
|
|
103
|
+
}
|
|
104
|
+
n
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
fn append_into(&self, v: &mut Vec<u8>) -> bool {
|
|
108
|
+
if v.capacity() - v.len() < <[u8]>::len(self) {
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
#[allow(
|
|
112
|
+
clippy::disallowed_methods,
|
|
113
|
+
reason = "the room was checked above, so it cannot grow"
|
|
114
|
+
)]
|
|
115
|
+
v.extend_from_slice(self);
|
|
116
|
+
true
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
impl Utf8Copy {
|
|
121
|
+
/// A copy of `src`, checked to be UTF-8.
|
|
122
|
+
pub fn new(src: &[u8]) -> Result<Utf8Copy, CopyError> {
|
|
123
|
+
Utf8Copy::from_source(&src, |_| None::<core::convert::Infallible>).map_err(|e| match e {
|
|
124
|
+
FillError::Copy(e) => e,
|
|
125
|
+
FillError::Refused(never) => match never {},
|
|
126
|
+
})
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/// A copy of `src`, put to `refuse` and then checked to be UTF-8.
|
|
130
|
+
///
|
|
131
|
+
/// Up to [`INLINE`] bytes the copy is on the stack (`copy_into`); past
|
|
132
|
+
/// that it is a heap buffer reserved for exactly them and appended to
|
|
133
|
+
/// (`append_into`), so it is written once, not zeroed first.
|
|
134
|
+
///
|
|
135
|
+
/// `refuse` sees the copy before the UTF-8 check, so a caller's own rule
|
|
136
|
+
/// (a NUL, a length) is reported ahead of invalid UTF-8, and both look at
|
|
137
|
+
/// the same bytes that are read back later.
|
|
138
|
+
pub fn from_source<P>(
|
|
139
|
+
src: &impl Source,
|
|
140
|
+
refuse: impl FnOnce(&[u8]) -> Option<P>,
|
|
141
|
+
) -> Result<Utf8Copy, FillError<P>> {
|
|
142
|
+
let len = src.byte_len();
|
|
143
|
+
let bytes = if len <= INLINE {
|
|
144
|
+
let mut buf = [0u8; INLINE];
|
|
145
|
+
let n = src.copy_into(buf.get_mut(..len).unwrap_or_default());
|
|
146
|
+
/* A short copy is a failed one, as on the heap path below: a
|
|
147
|
+
* truncated text must never pass for the whole. */
|
|
148
|
+
if n != len {
|
|
149
|
+
return Err(FillError::Copy(CopyError::Oom));
|
|
150
|
+
}
|
|
151
|
+
Bytes::Inline { len: n, buf }
|
|
152
|
+
} else {
|
|
153
|
+
let mut v = Vec::new();
|
|
154
|
+
if !reserve_exact(&mut v, len) || !src.append_into(&mut v) || v.len() != len {
|
|
155
|
+
return Err(FillError::Copy(CopyError::Oom));
|
|
156
|
+
}
|
|
157
|
+
Bytes::Heap(v)
|
|
158
|
+
};
|
|
159
|
+
let copy = Utf8Copy(bytes);
|
|
160
|
+
if let Some(p) = refuse(copy.as_bytes()) {
|
|
161
|
+
return Err(FillError::Refused(p));
|
|
162
|
+
}
|
|
163
|
+
/* The check is of the copy, not of its source: what is read back
|
|
164
|
+
* later is exactly what was checked. */
|
|
165
|
+
match core::str::from_utf8(copy.as_bytes()) {
|
|
166
|
+
Ok(_) => Ok(copy),
|
|
167
|
+
Err(_) => Err(FillError::Copy(CopyError::NotUtf8)),
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/// The bytes.
|
|
172
|
+
pub fn as_bytes(&self) -> &[u8] {
|
|
173
|
+
match &self.0 {
|
|
174
|
+
Bytes::Inline { len, buf } => buf.get(..*len).unwrap_or(&[]),
|
|
175
|
+
Bytes::Heap(b) => b,
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/// The text.
|
|
180
|
+
pub fn as_str(&self) -> &str {
|
|
181
|
+
// SAFETY: a `Utf8Copy` is made only by `from_source`, which returns it only
|
|
182
|
+
// once `from_utf8` accepted exactly these bytes, and nothing changes
|
|
183
|
+
// them after: the fields are private to this module, and no method
|
|
184
|
+
// here writes them.
|
|
185
|
+
unsafe { core::str::from_utf8_unchecked(self.as_bytes()) }
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
#[cfg(test)]
|
|
190
|
+
mod tests {
|
|
191
|
+
#![allow(clippy::disallowed_methods)] /* test inputs */
|
|
192
|
+
use super::*;
|
|
193
|
+
|
|
194
|
+
#[test]
|
|
195
|
+
fn valid_text_reads_back_inline_and_on_the_heap() {
|
|
196
|
+
for s in ["", "a", "é", &"x".repeat(INLINE), &"é".repeat(INLINE)] {
|
|
197
|
+
assert_eq!(Utf8Copy::new(s.as_bytes()).unwrap().as_str(), s);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
#[test]
|
|
202
|
+
fn invalid_bytes_are_refused_inline_and_on_the_heap() {
|
|
203
|
+
assert_eq!(Utf8Copy::new(b"\xff").err(), Some(CopyError::NotUtf8));
|
|
204
|
+
let mut long = [b'a'; INLINE * 2 + 1];
|
|
205
|
+
long[INLINE * 2] = 0xc3;
|
|
206
|
+
assert_eq!(Utf8Copy::new(&long).err(), Some(CopyError::NotUtf8));
|
|
207
|
+
/* A cut multi-byte character at the inline limit. */
|
|
208
|
+
let mut edge = [b'a'; INLINE];
|
|
209
|
+
edge[INLINE - 1] = 0xc3;
|
|
210
|
+
assert_eq!(Utf8Copy::new(&edge).err(), Some(CopyError::NotUtf8));
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
#[test]
|
|
214
|
+
fn a_refusal_comes_before_the_utf8_check_and_sees_the_copy() {
|
|
215
|
+
for n in [3, INLINE * 2] {
|
|
216
|
+
let mut src = vec![b'a'; n];
|
|
217
|
+
src[0] = 0;
|
|
218
|
+
src[n - 1] = 0xff;
|
|
219
|
+
let got = Utf8Copy::from_source(&src.as_slice(), |b| b.contains(&0).then_some("nul"));
|
|
220
|
+
assert_eq!(got.err(), Some(FillError::Refused("nul")));
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/// A source whose room check fails is out of memory, not a short copy.
|
|
225
|
+
#[test]
|
|
226
|
+
fn a_source_that_will_not_append_is_refused() {
|
|
227
|
+
struct Short;
|
|
228
|
+
impl Source for Short {
|
|
229
|
+
fn byte_len(&self) -> usize {
|
|
230
|
+
INLINE * 2
|
|
231
|
+
}
|
|
232
|
+
fn copy_into(&self, _: &mut [u8]) -> usize {
|
|
233
|
+
0
|
|
234
|
+
}
|
|
235
|
+
fn append_into(&self, _: &mut Vec<u8>) -> bool {
|
|
236
|
+
false
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
let got = Utf8Copy::from_source(&Short, |_| None::<()>);
|
|
240
|
+
assert_eq!(got.err(), Some(FillError::Copy(CopyError::Oom)));
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/// The same, inline: a source that copies fewer bytes than it reported is
|
|
244
|
+
/// refused, not truncated.
|
|
245
|
+
#[test]
|
|
246
|
+
fn a_source_that_copies_short_inline_is_refused() {
|
|
247
|
+
struct Short;
|
|
248
|
+
impl Source for Short {
|
|
249
|
+
fn byte_len(&self) -> usize {
|
|
250
|
+
INLINE
|
|
251
|
+
}
|
|
252
|
+
fn copy_into(&self, _: &mut [u8]) -> usize {
|
|
253
|
+
INLINE - 1
|
|
254
|
+
}
|
|
255
|
+
fn append_into(&self, _: &mut Vec<u8>) -> bool {
|
|
256
|
+
false
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
let got = Utf8Copy::from_source(&Short, |_| None::<()>);
|
|
260
|
+
assert_eq!(got.err(), Some(FillError::Copy(CopyError::Oom)));
|
|
261
|
+
}
|
|
262
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[package]
|
|
2
|
+
name = "nupur_sys"
|
|
3
|
+
version = "0.0.1"
|
|
4
|
+
edition = "2021"
|
|
5
|
+
rust-version = "1.95"
|
|
6
|
+
publish = false
|
|
7
|
+
description = "Ruby's C API for Nupur: the one crate under it that depends on rb-sys"
|
|
8
|
+
|
|
9
|
+
[lib]
|
|
10
|
+
path = "src/lib.rs"
|
|
11
|
+
|
|
12
|
+
[lints]
|
|
13
|
+
workspace = true
|
|
14
|
+
|
|
15
|
+
[features]
|
|
16
|
+
# The raise half of `rake oom`'s hooks (`protect::injected_raise`), which
|
|
17
|
+
# Nupur's own `alloc-inject` turns on.
|
|
18
|
+
alloc-inject = []
|
|
19
|
+
|
|
20
|
+
[dependencies]
|
|
21
|
+
# Deliberately WITHOUT `link-ruby`: the extension is dlopen'd into a Ruby that
|
|
22
|
+
# already provides the rb_* symbols. The features are the ones Nupur was
|
|
23
|
+
# written against: the `rbimpl_*` flag enums, the struct layouts (`RBasic`,
|
|
24
|
+
# for a String's coderange flags) and the stable API.
|
|
25
|
+
rb-sys = { version = "0.9", features = [
|
|
26
|
+
"bindgen-rbimpls",
|
|
27
|
+
"bindgen-deprecated-types",
|
|
28
|
+
"stable-api",
|
|
29
|
+
] }
|