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,468 @@
1
+ //! A Rust function as a Ruby method: the `extern "C"` trampoline Ruby calls,
2
+ //! and the one place a method's error is raised.
3
+ //!
4
+ //! `method!(f, n)` / `function!(f, n)` expand to a trampoline of arity `n`
5
+ //! (-1: Ruby passes `argc`/`argv`) that calls `f` through [`finish`]. `finish`
6
+ //! catches a panic - which becomes the internal error (`rb::error::INTERNAL_ERROR`) - and, once `f`
7
+ //! and everything it owned have returned and dropped, raises the `Err` it
8
+ //! answered: the raise is a `longjmp` with nothing left to skip. The
9
+ //! expansion's one `unsafe` block is its call of [`finish`] (or
10
+ //! [`finish_cary`]), the token's entry, which an external macro's expansion
11
+ //! may hold where the extension forbids `unsafe_code`; the caller's `f` is
12
+ //! bound outside that block, so an unsafe operation written in it needs an
13
+ //! `unsafe` of the caller's own. The C argument array is a [`CArgv`], which
14
+ //! only Ruby makes.
15
+ //!
16
+ //! `f` takes `&Ruby` first or not, then for a method its receiver, then its
17
+ //! arguments - each read by [`TryConvert`], which is a `Value`
18
+ //! as it is or a receiver type checking its class, never a conversion that
19
+ //! runs Ruby - and returns anything [`ReturnValue`].
20
+
21
+ #![allow(unsafe_code)]
22
+
23
+ use core::ffi::c_int;
24
+ use core::panic::AssertUnwindSafe;
25
+ use core::sync::atomic::{AtomicBool, Ordering};
26
+
27
+ use super::convert::{ReturnValue, TryConvert};
28
+ use super::error::Error;
29
+ use super::ruby::Ruby;
30
+ use super::value::Value;
31
+
32
+ // What a method asks of the call it is running: its block, its keywords.
33
+ mod frame;
34
+ pub use frame::{
35
+ block_given, keyword_given, yield_dropping_error_for_test, yield_value, yield_values,
36
+ };
37
+
38
+ /// The token, made where Ruby has called in with the GVL held: private to
39
+ /// this module, so only its two entries, [`finish`] and [`run_init`], can make
40
+ /// one - the compiler's rule, not a lint's.
41
+ ///
42
+ /// # Safety
43
+ /// On a Ruby thread holding the GVL.
44
+ #[inline(always)]
45
+ unsafe fn entry_token() -> Ruby {
46
+ // SAFETY: the caller's.
47
+ Ruby(unsafe { nupur_sys::value::Ruby::assume_gvl() })
48
+ }
49
+
50
+ /// A trampoline and its arity, for `define_method` and its kin.
51
+ #[derive(Clone, Copy)]
52
+ pub struct Func {
53
+ pub(crate) ptr: unsafe extern "C" fn() -> nupur_sys::value::Value,
54
+ pub(crate) arity: c_int,
55
+ }
56
+
57
+ /// Ruby's argument array for an arity -1 method: made only by Ruby, as the
58
+ /// second parameter of a trampoline, and good for that call.
59
+ #[repr(transparent)]
60
+ pub struct CArgv(*const Value);
61
+
62
+ /// Run a method's body: its `Ok` value is the method's result, its `Err` is
63
+ /// raised, a panic is the internal error (`rb::error::INTERNAL_ERROR`). The raise happens here, after
64
+ /// `f` has returned - every destructor of the method's frames has run - and
65
+ /// the error's own message has been released ([`Error::raise`]).
66
+ ///
67
+ /// # Safety
68
+ /// Called only from a trampoline Ruby itself calls - the expansion of
69
+ /// `method!` / `function!` - so on a Ruby thread holding the GVL: this makes
70
+ /// the method's `Ruby` token, and a call from anywhere else (a thread
71
+ /// without the GVL) would make one that proves nothing. `unsafe` so that
72
+ /// nothing but the macros, whose expansion carries the `unsafe` block, can
73
+ /// call it: the extension's own code is `forbid(unsafe_code)`.
74
+ #[doc(hidden)]
75
+ #[inline]
76
+ pub unsafe fn finish(f: impl FnOnce(&Ruby) -> Result<Value, Error>) -> Value {
77
+ crate::no_unwind::must_not_unwind::<crate::no_unwind::Method, _>(|| {
78
+ // SAFETY: only a trampoline Ruby calls runs this: its thread, the GVL
79
+ // held. The one token a method's body sees is this one.
80
+ let ruby = unsafe { entry_token() };
81
+ /* A method starts with no exit pending: every trampoline resumes its
82
+ * own before it returns (below, and `Error::raise`), so this only
83
+ * makes sure. */
84
+ // SAFETY: a method starts here, so no exit of its is pending.
85
+ unsafe { crate::raw::reset_pending_exit() };
86
+ if unfinished() {
87
+ crate::rb::error::internal_error(UNFINISHED_MSG).raise(&ruby)
88
+ }
89
+ let e = match std::panic::catch_unwind(AssertUnwindSafe(|| f(&ruby))) {
90
+ /* An exit the method caught and dropped is resumed, not lost:
91
+ * a `throw`'s catcher is waiting, a killed thread must end. */
92
+ Ok(Ok(v)) => match crate::raw::pending_exit() {
93
+ None => return v,
94
+ Some(exit) => exit,
95
+ },
96
+ Ok(Err(e)) => e,
97
+ Err(payload) => crate::rb::error::internal_error(crate::caught::panic_message(payload)),
98
+ };
99
+ e.raise(&ruby)
100
+ })
101
+ }
102
+
103
+ /// [`finish`] for an arity -1 method: `f` is handed the arguments as a slice
104
+ /// of Ruby's array.
105
+ ///
106
+ /// # Safety
107
+ /// As [`finish`]; and `argc` / `argv` are the arguments Ruby passed.
108
+ #[doc(hidden)]
109
+ #[inline]
110
+ pub unsafe fn finish_cary(
111
+ argc: c_int,
112
+ argv: CArgv,
113
+ f: impl FnOnce(&Ruby, &[Value]) -> Result<Value, Error>,
114
+ ) -> Value {
115
+ let args: &[Value] = if argc <= 0 || argv.0.is_null() {
116
+ &[]
117
+ } else {
118
+ // SAFETY: Ruby passes `argc` live values at `argv` for the duration of
119
+ // the call, and the slice does not outlive it (`f` borrows it). A
120
+ // `CArgv` exists only as the parameter Ruby filled.
121
+ unsafe { core::slice::from_raw_parts(argv.0, usize::try_from(argc).unwrap_or(0)) }
122
+ };
123
+ // SAFETY: the caller's contract, which is `finish`'s.
124
+ unsafe { finish(|ruby| f(ruby, args)) }
125
+ }
126
+
127
+ impl Func {
128
+ /// # Safety
129
+ /// `f` is a trampoline Ruby may call with `arity` arguments as that
130
+ /// arity's C signature.
131
+ unsafe fn of<F: Copy>(f: F, arity: c_int) -> Func {
132
+ const { assert!(core::mem::size_of::<F>() == core::mem::size_of::<fn()>()) };
133
+ // SAFETY: a function pointer, cast to the generic type Ruby's
134
+ // `rb_define_method` takes, which calls it with `arity`'s signature.
135
+ Func {
136
+ ptr: unsafe { core::mem::transmute_copy(&f) },
137
+ arity,
138
+ }
139
+ }
140
+
141
+ #[doc(hidden)]
142
+ pub fn cary(f: extern "C" fn(c_int, CArgv, Value) -> Value) -> Func {
143
+ // SAFETY: arity -1's signature: `(int argc, VALUE *argv, VALUE self)`.
144
+ unsafe { Func::of(f, -1) }
145
+ }
146
+ }
147
+
148
+ macro_rules! arity {
149
+ ($n:literal, $new:ident, $method:ident, $ruby_method:ident, $function:ident, $ruby_function:ident;
150
+ $($a:ident : $t:ident),*) => {
151
+ impl Func {
152
+ #[doc(hidden)]
153
+ pub fn $new(f: extern "C" fn(Value $(, arity!(@v $a))*) -> Value) -> Func {
154
+ // SAFETY: the signature of arity `$n`: the receiver, then `$n`
155
+ // arguments, each a `VALUE` (`Value` is transparent over one).
156
+ unsafe { Func::of(f, $n) }
157
+ }
158
+ }
159
+
160
+ #[doc(hidden)]
161
+ pub trait $method<S, $($t,)* R> {
162
+ fn invoke(self, ruby: &Ruby, s: Value $(, $a: Value)*) -> Result<Value, Error>;
163
+ }
164
+
165
+ impl<F, S, $($t,)* R> $method<S, $($t,)* R> for F
166
+ where
167
+ F: Fn(S $(, $t)*) -> R,
168
+ S: TryConvert,
169
+ $($t: TryConvert,)*
170
+ R: ReturnValue,
171
+ {
172
+ #[inline]
173
+ fn invoke(self, ruby: &Ruby, s: Value $(, $a: Value)*) -> Result<Value, Error> {
174
+ (self)(S::try_convert(ruby, s)? $(, $t::try_convert(ruby, $a)?)*).into_return(ruby)
175
+ }
176
+ }
177
+
178
+ #[doc(hidden)]
179
+ pub trait $ruby_method<S, $($t,)* R> {
180
+ fn invoke(self, ruby: &Ruby, s: Value $(, $a: Value)*) -> Result<Value, Error>;
181
+ }
182
+
183
+ impl<F, S, $($t,)* R> $ruby_method<S, $($t,)* R> for F
184
+ where
185
+ F: for<'r> Fn(&'r Ruby, S $(, $t)*) -> R,
186
+ S: TryConvert,
187
+ $($t: TryConvert,)*
188
+ R: ReturnValue,
189
+ {
190
+ #[inline]
191
+ fn invoke(self, ruby: &Ruby, s: Value $(, $a: Value)*) -> Result<Value, Error> {
192
+ (self)(ruby, S::try_convert(ruby, s)? $(, $t::try_convert(ruby, $a)?)*).into_return(ruby)
193
+ }
194
+ }
195
+
196
+ #[doc(hidden)]
197
+ pub trait $function<$($t,)* R> {
198
+ fn invoke(self, ruby: &Ruby, s: Value $(, $a: Value)*) -> Result<Value, Error>;
199
+ }
200
+
201
+ impl<F, $($t,)* R> $function<$($t,)* R> for F
202
+ where
203
+ F: Fn($($t),*) -> R,
204
+ $($t: TryConvert,)*
205
+ R: ReturnValue,
206
+ {
207
+ #[inline]
208
+ fn invoke(self, ruby: &Ruby, _: Value $(, $a: Value)*) -> Result<Value, Error> {
209
+ (self)($($t::try_convert(ruby, $a)?),*).into_return(ruby)
210
+ }
211
+ }
212
+
213
+ #[doc(hidden)]
214
+ pub trait $ruby_function<$($t,)* R> {
215
+ fn invoke(self, ruby: &Ruby, s: Value $(, $a: Value)*) -> Result<Value, Error>;
216
+ }
217
+
218
+ impl<F, $($t,)* R> $ruby_function<$($t,)* R> for F
219
+ where
220
+ F: for<'r> Fn(&'r Ruby $(, $t)*) -> R,
221
+ $($t: TryConvert,)*
222
+ R: ReturnValue,
223
+ {
224
+ #[inline]
225
+ fn invoke(self, ruby: &Ruby, _: Value $(, $a: Value)*) -> Result<Value, Error> {
226
+ (self)(ruby $(, $t::try_convert(ruby, $a)?)*).into_return(ruby)
227
+ }
228
+ }
229
+ };
230
+ (@v $a:ident) => { Value };
231
+ }
232
+
233
+ arity!(0, new0, Method0, RubyMethod0, Function0, RubyFunction0;);
234
+ arity!(1, new1, Method1, RubyMethod1, Function1, RubyFunction1; a0: A0);
235
+ arity!(2, new2, Method2, RubyMethod2, Function2, RubyFunction2; a0: A0, a1: A1);
236
+ arity!(3, new3, Method3, RubyMethod3, Function3, RubyFunction3; a0: A0, a1: A1, a2: A2);
237
+ arity!(4, new4, Method4, RubyMethod4, Function4, RubyFunction4; a0: A0, a1: A1, a2: A2, a3: A3);
238
+
239
+ /// Arity -1, with a receiver: `f(S, &[Value])`.
240
+ #[doc(hidden)]
241
+ pub trait MethodCAry<S, R> {
242
+ fn invoke(self, ruby: &Ruby, s: Value, args: &[Value]) -> Result<Value, Error>;
243
+ }
244
+
245
+ impl<F, S, R> MethodCAry<S, R> for F
246
+ where
247
+ F: for<'a> Fn(S, &'a [Value]) -> R,
248
+ S: TryConvert,
249
+ R: ReturnValue,
250
+ {
251
+ #[inline]
252
+ fn invoke(self, ruby: &Ruby, s: Value, args: &[Value]) -> Result<Value, Error> {
253
+ (self)(S::try_convert(ruby, s)?, args).into_return(ruby)
254
+ }
255
+ }
256
+
257
+ /// Arity -1, with `&Ruby` and a receiver: `f(&Ruby, S, &[Value])`.
258
+ #[doc(hidden)]
259
+ pub trait RubyMethodCAry<S, R> {
260
+ fn invoke(self, ruby: &Ruby, s: Value, args: &[Value]) -> Result<Value, Error>;
261
+ }
262
+
263
+ impl<F, S, R> RubyMethodCAry<S, R> for F
264
+ where
265
+ F: for<'r, 'a> Fn(&'r Ruby, S, &'a [Value]) -> R,
266
+ S: TryConvert,
267
+ R: ReturnValue,
268
+ {
269
+ #[inline]
270
+ fn invoke(self, ruby: &Ruby, s: Value, args: &[Value]) -> Result<Value, Error> {
271
+ (self)(ruby, S::try_convert(ruby, s)?, args).into_return(ruby)
272
+ }
273
+ }
274
+
275
+ /// Arity -1, no receiver: `f(&[Value])`.
276
+ #[doc(hidden)]
277
+ pub trait FunctionCAry<R> {
278
+ fn invoke(self, ruby: &Ruby, s: Value, args: &[Value]) -> Result<Value, Error>;
279
+ }
280
+
281
+ impl<F, R> FunctionCAry<R> for F
282
+ where
283
+ F: for<'a> Fn(&'a [Value]) -> R,
284
+ R: ReturnValue,
285
+ {
286
+ #[inline]
287
+ fn invoke(self, ruby: &Ruby, _: Value, args: &[Value]) -> Result<Value, Error> {
288
+ (self)(args).into_return(ruby)
289
+ }
290
+ }
291
+
292
+ /// Arity -1, with `&Ruby` and no receiver: `f(&Ruby, &[Value])`.
293
+ #[doc(hidden)]
294
+ pub trait RubyFunctionCAry<R> {
295
+ fn invoke(self, ruby: &Ruby, s: Value, args: &[Value]) -> Result<Value, Error>;
296
+ }
297
+
298
+ impl<F, R> RubyFunctionCAry<R> for F
299
+ where
300
+ F: for<'r, 'a> Fn(&'r Ruby, &'a [Value]) -> R,
301
+ R: ReturnValue,
302
+ {
303
+ #[inline]
304
+ fn invoke(self, ruby: &Ruby, _: Value, args: &[Value]) -> Result<Value, Error> {
305
+ (self)(ruby, args).into_return(ruby)
306
+ }
307
+ }
308
+
309
+ /// `method!(f, n)`: `f` as a Ruby method of arity `n` (-1 for `argc`/`argv`),
310
+ /// for `define_method`.
311
+ #[macro_export]
312
+ macro_rules! method {
313
+ ($f:expr, -1) => { $crate::__trampoline!(cary $f, MethodCAry, RubyMethodCAry) };
314
+ ($f:expr, 0) => { $crate::__trampoline!(method $f, new0, Method0, RubyMethod0;) };
315
+ ($f:expr, 1) => { $crate::__trampoline!(method $f, new1, Method1, RubyMethod1; a0) };
316
+ ($f:expr, 2) => { $crate::__trampoline!(method $f, new2, Method2, RubyMethod2; a0, a1) };
317
+ ($f:expr, 3) => { $crate::__trampoline!(method $f, new3, Method3, RubyMethod3; a0, a1, a2) };
318
+ ($f:expr, 4) => { $crate::__trampoline!(method $f, new4, Method4, RubyMethod4; a0, a1, a2, a3) };
319
+ }
320
+
321
+ /// `function!(f, n)`: `f`, which takes no receiver, as a Ruby method of
322
+ /// arity `n` - a singleton method, say.
323
+ #[macro_export]
324
+ macro_rules! function {
325
+ ($f:expr, -1) => { $crate::__trampoline!(cary $f, FunctionCAry, RubyFunctionCAry) };
326
+ ($f:expr, 0) => { $crate::__trampoline!(function $f, new0, Function0, RubyFunction0;) };
327
+ ($f:expr, 1) => { $crate::__trampoline!(function $f, new1, Function1, RubyFunction1; a0) };
328
+ ($f:expr, 2) => { $crate::__trampoline!(function $f, new2, Function2, RubyFunction2; a0, a1) };
329
+ ($f:expr, 3) => { $crate::__trampoline!(function $f, new3, Function3, RubyFunction3; a0, a1, a2) };
330
+ ($f:expr, 4) => { $crate::__trampoline!(function $f, new4, Function4, RubyFunction4; a0, a1, a2, a3) };
331
+ }
332
+
333
+ #[doc(hidden)]
334
+ #[macro_export]
335
+ macro_rules! __trampoline {
336
+ (cary $f:expr, $plain:ident, $ruby:ident) => {{
337
+ extern "C" fn anon(
338
+ argc: ::core::ffi::c_int,
339
+ argv: $crate::rb::method::CArgv,
340
+ rb_self: $crate::rb::Value,
341
+ ) -> $crate::rb::Value {
342
+ #[allow(unused_imports)]
343
+ use $crate::rb::method::{$plain as _, $ruby as _};
344
+ /* Bound OUTSIDE the `unsafe` block: inside it, an unsafe
345
+ * operation written in `$f` would need no `unsafe` of its own,
346
+ * and the caller's `forbid(unsafe_code)` sees none in an
347
+ * external macro's expansion. */
348
+ let f = $f;
349
+ // SAFETY: Ruby is calling this trampoline, with the arguments it
350
+ // passed.
351
+ unsafe {
352
+ $crate::rb::method::finish_cary(argc, argv, |ruby, args| f.invoke(ruby, rb_self, args))
353
+ }
354
+ }
355
+ $crate::rb::method::Func::cary(anon)
356
+ }};
357
+ ($kind:ident $f:expr, $new:ident, $plain:ident, $ruby:ident; $($a:ident),*) => {{
358
+ extern "C" fn anon(
359
+ rb_self: $crate::rb::Value
360
+ $(, $a: $crate::rb::Value)*
361
+ ) -> $crate::rb::Value {
362
+ #[allow(unused_imports)]
363
+ use $crate::rb::method::{$plain as _, $ruby as _};
364
+ /* Bound outside the `unsafe` block, as the `cary` arm's. */
365
+ let f = $f;
366
+ // SAFETY: Ruby is calling this trampoline.
367
+ unsafe { $crate::rb::method::finish(|ruby| f.invoke(ruby, rb_self $(, $a)*)) }
368
+ }
369
+ $crate::rb::method::Func::$new(anon)
370
+ }};
371
+ }
372
+
373
+ /// `rb_ext_ractor_safe(true)`: every method the running `Init_` defines from
374
+ /// here on may be called from any Ractor, where Ruby would refuse it outside
375
+ /// the main one (`Ractor::UnsafeError`). Ruby keeps the declaration for the
376
+ /// `require` that runs this `Init_` alone. Raises nothing and runs no Ruby.
377
+ ///
378
+ /// The layer's part holds already: what it keeps for the process is
379
+ /// [`Shareable`](super::Shareable), a non-local exit is pending per thread,
380
+ /// and no wrapped object can leave its Ractor (it is never shareable, and,
381
+ /// its class having no allocator, cannot be copied or moved to another). The
382
+ /// extension's part is its own: its statics, what its methods assume the GVL
383
+ /// serialises (only one Ractor's threads now), and no Marshal hook on a
384
+ /// class of wrapped objects, through which a Ractor would copy one.
385
+ pub fn declare_ractor_safe(ruby: &Ruby) {
386
+ // SAFETY: under the GVL (`&Ruby`); sets the running thread's extension
387
+ // config.
388
+ unsafe { nupur_sys::non_raising::rb_ext_ractor_safe(ruby.sys(), true) }
389
+ }
390
+
391
+ /// Set when `init` stopped half-way ([`run_init`]): the extension's own,
392
+ /// as the layer is built into each extension. Read by every method, which
393
+ /// then refuses; written once, by the thread that ran `Init_`. A flag of
394
+ /// failure rather than of completion, so a method `init` calls on the way
395
+ /// (through the extension's own Ruby) runs.
396
+ static UNFINISHED: AtomicBool = AtomicBool::new(false);
397
+
398
+ const UNFINISHED_MSG: &str = "the extension stopped while defining itself and cannot be used; \
399
+ restart the process to load it";
400
+
401
+ /// Whether `Init_` stopped half-way, leaving the extension unusable.
402
+ #[inline]
403
+ pub fn unfinished() -> bool {
404
+ UNFINISHED.load(Ordering::Relaxed)
405
+ }
406
+
407
+ /// What the extension's `Init_` runs its two phases through.
408
+ ///
409
+ /// `check` runs first and defines nothing - a check that the binary suits
410
+ /// the running Ruby, say - so its `Err` is raised as it is: a `LoadError`
411
+ /// a caller may rescue, with nothing of the extension left behind.
412
+ ///
413
+ /// Once `init` has begun to define the extension, whatever stops it - an
414
+ /// exception (a `Timeout`, a hook of the program's that raised), a
415
+ /// non-local exit (a `throw`, a thread kill), a panic - leaves an extension
416
+ /// half-defined: classes without their methods, a registered constant not
417
+ /// yet set. That is the thread's to see, not the process's end: the
418
+ /// exception is raised and the exit resumed, as a method's are, and the
419
+ /// extension is marked unfinished ([`unfinished`]), so every method of its
420
+ /// refuses to run from then on. A second `require` runs `Init_` again, which
421
+ /// the extension's `check` refuses ([`crate::abi::check_undefined`]).
422
+ ///
423
+ /// # Safety
424
+ /// Called only from the extension's `Init_` function, which Ruby calls on its
425
+ /// thread with the GVL held: as [`finish`], this makes the token.
426
+ #[doc(hidden)]
427
+ pub unsafe fn run_init(
428
+ check: fn(&Ruby) -> Result<(), Error>,
429
+ init: fn(&Ruby) -> Result<(), Error>,
430
+ ) {
431
+ crate::no_unwind::must_not_unwind::<crate::no_unwind::Init, _>(|| {
432
+ // SAFETY: Ruby calls an extension's `Init_` on its thread, with the GVL.
433
+ let ruby = unsafe { entry_token() };
434
+ match std::panic::catch_unwind(AssertUnwindSafe(|| check(&ruby))) {
435
+ Ok(Ok(())) => match std::panic::catch_unwind(AssertUnwindSafe(|| {
436
+ /* What the layer asks Ruby once, before any of the extension
437
+ * runs - and after `check`, which is the first thing to
438
+ * touch the interpreter. */
439
+ crate::encoding::init(&ruby);
440
+ init(&ruby)
441
+ })) {
442
+ /* Complete. An exit `init` dropped is still resumed, as
443
+ * `finish` resumes a method's: a `throw`'s catcher waits, a
444
+ * killed thread must end. */
445
+ Ok(Ok(())) => match crate::raw::pending_exit() {
446
+ None => (),
447
+ Some(exit) => exit.raise(&ruby),
448
+ },
449
+ /* Stopped half-way: marked, then raised (an exit pending
450
+ * goes first, `Error::raise`). */
451
+ Ok(Err(e)) => {
452
+ UNFINISHED.store(true, Ordering::Relaxed);
453
+ e.raise(&ruby)
454
+ }
455
+ Err(payload) => {
456
+ UNFINISHED.store(true, Ordering::Relaxed);
457
+ crate::rb::error::internal_error(crate::caught::panic_message(payload))
458
+ .raise(&ruby)
459
+ }
460
+ },
461
+ Ok(Err(e)) => e.raise(&ruby),
462
+ /* Nothing is defined yet: the panic is raised, as a method's. */
463
+ Err(payload) => {
464
+ crate::rb::error::internal_error(crate::caught::panic_message(payload)).raise(&ruby)
465
+ }
466
+ }
467
+ })
468
+ }
@@ -0,0 +1,40 @@
1
+ //! The value and method layer over `rb-sys`: the values, errors, method registration
2
+ //! and class definitions an extension is written against.
3
+ //!
4
+ //! It stands where magnus stood, under the names magnus gave them, and holds
5
+ //! only what is used: a `Value` and the class-checked handles over it
6
+ //! ([`value`]), what an object is asked outside a method call - its hidden
7
+ //! ivars, its hiding, its class ([`object`]) - and what a handle holds
8
+ //! (`kept`), [`Error`] ([`error`]), what a method takes and returns
9
+ //! ([`convert`]), the trampolines `method!` / `function!` expand to
10
+ //! ([`method`]) and class and module definitions ([`class`]). Every C call it
11
+ //! makes that can raise is a `raw` wrapper under `rb_protect`, and
12
+ //! nothing raises until a method's trampoline has returned from the method
13
+ //! (`method::finish`). So the C functions an extension trusts are the ones
14
+ //! `raw/` names, and no other code stands between them and its methods.
15
+
16
+ pub mod call;
17
+ pub mod class;
18
+ pub mod convert;
19
+ pub mod error;
20
+ pub mod global;
21
+ pub(crate) mod kept;
22
+ pub mod method;
23
+ pub mod object;
24
+ pub mod ruby;
25
+ pub mod value;
26
+
27
+ pub use class::{freeze, DataClass, Module, Object};
28
+ pub use convert::{IntoValue, ReturnValue, TryConvert};
29
+ pub use error::{Builtin, Error, ErrorClass, Message, Rescued};
30
+ pub use global::{Opaque, RbConst, Shareable};
31
+ pub use ruby::Ruby;
32
+ pub use value::{
33
+ ExceptionClass, Float, HashKey, HiddenId, Id, Integer, Kind, RArray, RClass, RHash, RModule,
34
+ RString, Range, ReprValue, Symbol, Value,
35
+ };
36
+
37
+ /// The traits a method's module brings into scope with `use ...::prelude::*`.
38
+ pub mod prelude {
39
+ pub use super::{Module, Object, ReprValue, TryConvert};
40
+ }
@@ -0,0 +1,66 @@
1
+ //! What an object is asked or told outside a method call: its hidden
2
+ //! instance variables, its hiding from `ObjectSpace`, and whether it is an
3
+ //! instance of a class - each a C read or a protected call that runs no Ruby
4
+ //! code.
5
+
6
+ #![allow(unsafe_code)]
7
+
8
+ use super::error::Error;
9
+ use super::value::{AsSys, HiddenId, RClass, RModule, ReprValue, Value};
10
+
11
+ /// `rb_attr_get`: a hidden ivar's value, or nil. Runs no Ruby code (an
12
+ /// attribute read, not a method call), and raises nothing in any Ractor (a
13
+ /// [`HiddenId`] is a name the Ractor checks do not apply to).
14
+ #[inline]
15
+ pub fn ivar_get(obj: Value, id: HiddenId) -> Value {
16
+ // SAFETY: a live object, and a `HiddenId` is never an `@` name.
17
+ Value::from_sys(unsafe { nupur_sys::non_raising::attr_get_hidden(obj.as_sys(), id.as_raw()) })
18
+ }
19
+
20
+ /// Set the hidden ivar `id` (a name without `@`, so Ruby code cannot see it)
21
+ /// of `obj` to `v`: `FrozenError` for a frozen object, and `NoMemoryError`.
22
+ #[inline]
23
+ pub fn ivar_set(obj: Value, id: HiddenId, v: impl ReprValue) -> Result<(), Error> {
24
+ crate::raw::ivar_set(obj, id, v.as_value())
25
+ }
26
+
27
+ /// `rb_obj_hide`: take `v`'s class away, so `ObjectSpace` does not list it.
28
+ ///
29
+ /// # Safety
30
+ /// `v` is an object no Ruby code holds and none will be handed while it is
31
+ /// hidden: a hidden object has no class, and Ruby code given one crashes.
32
+ #[inline]
33
+ pub(crate) unsafe fn obj_hide(v: Value) {
34
+ // SAFETY: a live object; hiding writes only its class field.
35
+ unsafe { nupur_sys::non_raising::rb_obj_hide(v.as_sys()) };
36
+ }
37
+
38
+ /// Whether `v` is a class or a module - what `rb_obj_is_kind_of` and
39
+ /// `rb_class_inherited_p` require, and raise `TypeError` without.
40
+ #[inline]
41
+ fn is_module(v: Value) -> bool {
42
+ RClass::from_value(v).is_some() || RModule::from_value(v).is_some()
43
+ }
44
+
45
+ /// `rb_obj_is_kind_of`: an instance of `class` or of one deriving from it?
46
+ /// `false` when `class` is not a class or module, rather than the
47
+ /// `TypeError` the C function raises. Runs no Ruby code.
48
+ #[inline]
49
+ pub(crate) fn obj_is_kind_of(v: Value, class: Value) -> bool {
50
+ if !is_module(class) {
51
+ return false;
52
+ }
53
+ // SAFETY: both live; `class` is a class or module, checked above.
54
+ unsafe { nupur_sys::non_raising::obj_is_kind_of_module(v.as_sys(), class.as_sys()) }
55
+ }
56
+
57
+ /// `rb_class_inherited_p`: is `sub` `sup` or a descendant of it? `false`
58
+ /// when either is not a class or module. Runs no Ruby code.
59
+ #[inline]
60
+ pub(crate) fn class_inherits(sub: Value, sup: Value) -> bool {
61
+ if !is_module(sub) || !is_module(sup) {
62
+ return false;
63
+ }
64
+ // SAFETY: both live classes or modules, checked above.
65
+ unsafe { nupur_sys::non_raising::class_inherited_p_of_modules(sub.as_sys(), sup.as_sys()) }
66
+ }
@@ -0,0 +1,107 @@
1
+ //! [`Ruby`]: the proof that this thread holds the GVL.
2
+
3
+ #![allow(unsafe_code)]
4
+
5
+ use super::error::Error;
6
+ use super::value::{ExceptionClass, RClass, RModule, Value};
7
+
8
+ /// The GVL, held: a Ruby method's thread, between its entry and its return.
9
+ ///
10
+ /// A zero-sized token, neither `Send` nor `Sync`, so it cannot be carried into
11
+ /// a GVL-released body (`gvl::without_gvl`'s `Send` bound). Only the
12
+ /// entries Ruby calls make one - a method's trampoline (`method::finish`) and
13
+ /// `Init_` (`method::run_init`) - and everything below them is handed it as
14
+ /// `&Ruby`: there is no other way to get one. Making an [`Error`] needs none,
15
+ /// since its class is read only when it is raised.
16
+ ///
17
+ /// [`Error`]: super::error::Error
18
+ ///
19
+ /// `nupur_sys`'s token underneath, which its calls that take no value take.
20
+ ///
21
+ /// The field is `rb`'s, and it is built only from an owned `nupur_sys`
22
+ /// token, which `Ruby::assume_gvl` alone makes. That `rb::method`'s private
23
+ /// `entry_token` is the one caller of `assume_gvl`, and so the one maker of
24
+ /// this token, is `gvl_token_outside_entry`'s to hold.
25
+ pub struct Ruby(pub(super) nupur_sys::value::Ruby);
26
+
27
+ macro_rules! globals {
28
+ ($kind:ident: $($method:ident => $global:ident),* $(,)?) => {
29
+ $(
30
+ #[doc = concat!("`", stringify!($global), "`.")]
31
+ #[inline]
32
+ pub fn $method(&self) -> $kind {
33
+ let v = Value::from_sys(nupur_sys::non_raising::$global(self.sys()));
34
+ $kind::from_known(v)
35
+ }
36
+ )*
37
+ };
38
+ }
39
+
40
+ impl Ruby {
41
+ /// `nupur_sys`'s token, for its calls.
42
+ #[inline(always)]
43
+ pub(crate) fn sys(&self) -> &nupur_sys::value::Ruby {
44
+ &self.0
45
+ }
46
+
47
+ /// `nil`.
48
+ #[inline]
49
+ pub fn qnil(&self) -> Value {
50
+ Value::from_sys(self.0.qnil())
51
+ }
52
+
53
+ /// `true`.
54
+ #[inline]
55
+ pub fn qtrue(&self) -> Value {
56
+ Value::from_sys(self.0.qtrue())
57
+ }
58
+
59
+ /// `false`.
60
+ #[inline]
61
+ pub fn qfalse(&self) -> Value {
62
+ Value::from_sys(self.0.qfalse())
63
+ }
64
+
65
+ /// `true` or `false`, as `b` is.
66
+ #[inline]
67
+ pub fn boolean(&self, b: bool) -> Value {
68
+ if b {
69
+ self.qtrue()
70
+ } else {
71
+ self.qfalse()
72
+ }
73
+ }
74
+
75
+ /* The classes an `Error` can name are `error`'s (`builtins!`), which
76
+ * makes their accessors; these two are ancestors no error is made of. */
77
+ globals! { ExceptionClass:
78
+ exception_exception => rb_eException,
79
+ exception_standard_error => rb_eStandardError,
80
+ }
81
+
82
+ globals! { RClass:
83
+ class_array => rb_cArray,
84
+ class_encoding => rb_cEncoding,
85
+ class_float => rb_cFloat,
86
+ class_hash => rb_cHash,
87
+ class_integer => rb_cInteger,
88
+ class_object => rb_cObject,
89
+ class_range => rb_cRange,
90
+ class_string => rb_cString,
91
+ class_symbol => rb_cSymbol,
92
+ }
93
+ }
94
+
95
+ /* What a token defines: modules, at `Init_` (the classes and methods under
96
+ * them are `class`'s, on the module). */
97
+ impl Ruby {
98
+ /// A top-level module.
99
+ pub fn define_module(&self, name: &str) -> Result<RModule, Error> {
100
+ crate::raw::define_module(self, &super::class::c_name(name)?)
101
+ }
102
+
103
+ /// An anonymous module.
104
+ pub fn module_new(&self) -> Result<RModule, Error> {
105
+ crate::raw::module_new(self)
106
+ }
107
+ }