lexer_kit 0.6.1 → 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 (113) 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/version.rb +1 -1
  43. data/lib/lexer_kit.rb +15 -2
  44. data/vendor/nupur/Cargo.toml +24 -0
  45. data/vendor/nupur/LICENSE +176 -0
  46. data/vendor/nupur/NOTICE +64 -0
  47. data/vendor/nupur/README.ja.md +150 -0
  48. data/vendor/nupur/README.md +257 -0
  49. data/vendor/nupur/src/abi.rs +143 -0
  50. data/vendor/nupur/src/args.rs +318 -0
  51. data/vendor/nupur/src/build.rs +101 -0
  52. data/vendor/nupur/src/caught.rs +171 -0
  53. data/vendor/nupur/src/cname.rs +37 -0
  54. data/vendor/nupur/src/describe.rs +175 -0
  55. data/vendor/nupur/src/encoding.rs +240 -0
  56. data/vendor/nupur/src/gvl.rs +181 -0
  57. data/vendor/nupur/src/hash.rs +52 -0
  58. data/vendor/nupur/src/inject.rs +20 -0
  59. data/vendor/nupur/src/lib.rs +280 -0
  60. data/vendor/nupur/src/lint_probe.rs +142 -0
  61. data/vendor/nupur/src/msg.rs +193 -0
  62. data/vendor/nupur/src/no_unwind.rs +39 -0
  63. data/vendor/nupur/src/raw/check.rs +71 -0
  64. data/vendor/nupur/src/raw/data.rs +28 -0
  65. data/vendor/nupur/src/raw/define.rs +215 -0
  66. data/vendor/nupur/src/raw/exception.rs +69 -0
  67. data/vendor/nupur/src/raw/iterate.rs +115 -0
  68. data/vendor/nupur/src/raw/mod.rs +105 -0
  69. data/vendor/nupur/src/raw/protect.rs +144 -0
  70. data/vendor/nupur/src/raw/string.rs +148 -0
  71. data/vendor/nupur/src/raw/symbol.rs +38 -0
  72. data/vendor/nupur/src/raw/values.rs +293 -0
  73. data/vendor/nupur/src/rb/call.rs +118 -0
  74. data/vendor/nupur/src/rb/class.rs +170 -0
  75. data/vendor/nupur/src/rb/convert.rs +134 -0
  76. data/vendor/nupur/src/rb/error.rs +355 -0
  77. data/vendor/nupur/src/rb/global.rs +141 -0
  78. data/vendor/nupur/src/rb/kept.rs +55 -0
  79. data/vendor/nupur/src/rb/method/frame.rs +81 -0
  80. data/vendor/nupur/src/rb/method.rs +468 -0
  81. data/vendor/nupur/src/rb/mod.rs +40 -0
  82. data/vendor/nupur/src/rb/object.rs +66 -0
  83. data/vendor/nupur/src/rb/ruby.rs +107 -0
  84. data/vendor/nupur/src/rb/value/header.rs +65 -0
  85. data/vendor/nupur/src/rb/value/id.rs +61 -0
  86. data/vendor/nupur/src/rb/value/integer.rs +132 -0
  87. data/vendor/nupur/src/rb/value.rs +454 -0
  88. data/vendor/nupur/src/stack.rs +32 -0
  89. data/vendor/nupur/src/string/make.rs +234 -0
  90. data/vendor/nupur/src/string/mod.rs +24 -0
  91. data/vendor/nupur/src/string/read.rs +411 -0
  92. data/vendor/nupur/src/table.rs +58 -0
  93. data/vendor/nupur/src/typed/callbacks.rs +125 -0
  94. data/vendor/nupur/src/typed/data_type.rs +132 -0
  95. data/vendor/nupur/src/typed/embedded.rs +103 -0
  96. data/vendor/nupur/src/typed/external.rs +76 -0
  97. data/vendor/nupur/src/typed/hidden.rs +95 -0
  98. data/vendor/nupur/src/typed/mod.rs +373 -0
  99. data/vendor/nupur/src/utf8_copy.rs +262 -0
  100. data/vendor/nupur/sys/Cargo.toml +29 -0
  101. data/vendor/nupur/sys/src/data_type.rs +213 -0
  102. data/vendor/nupur/sys/src/int.rs +248 -0
  103. data/vendor/nupur/sys/src/lib.rs +61 -0
  104. data/vendor/nupur/sys/src/lint_probe.rs +93 -0
  105. data/vendor/nupur/sys/src/no_unwind.rs +99 -0
  106. data/vendor/nupur/sys/src/non_raising.rs +585 -0
  107. data/vendor/nupur/sys/src/protect.rs +349 -0
  108. data/vendor/nupur/sys/src/raising.rs +257 -0
  109. data/vendor/nupur/sys/src/value.rs +279 -0
  110. data/vendor/nupur.sha256 +68 -0
  111. metadata +92 -12
  112. data/ext/lexer_kit_rust/src/deserializer.rs +0 -213
  113. data/ext/lexer_kit_rust/src/dfa.rs +0 -217
@@ -0,0 +1,318 @@
1
+ //! Reading a method's arguments: an arity -1 method's `&[Value]` separated
2
+ //! into positional arguments and keywords ([`scan`]), keywords read by name
3
+ //! ([`Kwargs`]), and each value's type checked with no conversion - a
4
+ //! `to_s`, `to_str` or `to_int` is the caller's Ruby code, which the layer
5
+ //! runs none of - so a value of another type is a `TypeError`, worded as
6
+ //! Ruby's own type check words it, with the way out.
7
+
8
+ #![forbid(unsafe_code)]
9
+
10
+ use crate::describe::ClassName;
11
+ use crate::rb::{prelude::*, Error, RHash, RString, Ruby, Value};
12
+
13
+ /// `v`, which must be a String (a subclass's instance included).
14
+ ///
15
+ /// There is no conversion: a `to_str` or `to_s` is the caller's Ruby code, and
16
+ /// the layer runs none, so anything else is a `TypeError`, worded as Ruby's own
17
+ /// type check words it.
18
+ pub fn string_arg(v: Value) -> Result<RString, Error> {
19
+ RString::from_value(v).ok_or_else(|| wrong_type(v, "String", TO_S_HINT))
20
+ }
21
+
22
+ /// `v`, which must be an Integer (a Fixnum or a Bignum). No conversion, as
23
+ /// [`string_arg`]: a `to_int` is the caller's Ruby.
24
+ pub fn integer_arg(v: Value) -> Result<crate::rb::Integer, Error> {
25
+ crate::rb::Integer::from_value(v).ok_or_else(|| wrong_type(v, "Integer", TO_I_HINT))
26
+ }
27
+
28
+ /// [`integer_arg`] as an index or a count: an `i64` - the same on every
29
+ /// target, where a C `long` is 32 bits on Windows - and Ruby's `RangeError`
30
+ /// past one.
31
+ pub fn index_arg(v: Value) -> Result<i64, Error> {
32
+ integer_arg(v)?.to_i64()
33
+ }
34
+
35
+ const TO_S_HINT: &str = "; call #to_s to convert it";
36
+ const TO_I_HINT: &str = "; call #to_i to convert it";
37
+
38
+ /// `v` as a String for a NAME - anything a caller may write as a Symbol as
39
+ /// well: a String, or a Symbol's name. Nothing else
40
+ /// converts, as [`string_arg`].
41
+ pub fn name_arg(v: Value) -> Result<RString, Error> {
42
+ if let Some(s) = RString::from_value(v) {
43
+ return Ok(s);
44
+ }
45
+ match crate::rb::Symbol::from_value(v) {
46
+ Some(sym) => crate::raw::sym2str(sym),
47
+ None => Err(wrong_type(v, "String or Symbol", TO_S_HINT)),
48
+ }
49
+ }
50
+
51
+ /// Ruby's `TypeError` for a value of the wrong class, worded as Ruby's own
52
+ /// type check words it, with the way out (`hint`): "wrong argument type
53
+ /// Integer (expected String); call #to_s to convert it". The layer converts
54
+ /// nothing itself (a `to_s` is the caller's Ruby), so the caller does. The
55
+ /// class name is read without a call.
56
+ fn wrong_type(v: Value, expected: &str, hint: &str) -> Error {
57
+ crate::rb::error::type_error(format_args!(
58
+ "wrong argument type {} (expected {expected}){hint}",
59
+ ClassName(v)
60
+ ))
61
+ }
62
+
63
+ /* ---- separating a call's arguments ---- */
64
+
65
+ /* A method's arguments, read as `rb_scan_args` reads them - in Rust, with no
66
+ * C call that can raise.
67
+ *
68
+ * Ruby 3 passes keywords to a C method as a trailing Hash and says so in the
69
+ * frame (`rb_keyword_given_p`); a Hash passed positionally is positional.
70
+ * So, as `rb_scan_args`'s `:` does:
71
+ *
72
+ * - a method that takes keywords separates the trailing Hash only when the
73
+ * call gave keywords, and a braced Hash (`f(x, {a: 1})`) stays positional;
74
+ * - a method that takes none receives any keywords as a positional Hash,
75
+ * which Ruby's own rules make of them.
76
+ *
77
+ * An arity error is `rb_error_arity`'s message, word for word, and counts
78
+ * the positional arguments only. `spec/call_shapes_spec.rb` holds both to
79
+ * what magnus's `scan_args` (over `rb_scan_args`) answered before this
80
+ * replaced it. */
81
+
82
+ /// What a method takes: `required` positional arguments, then up to
83
+ /// `optional` more, then - with `rest` - any number, and keywords when
84
+ /// `keywords`.
85
+ #[derive(Clone, Copy)]
86
+ pub struct Shape {
87
+ pub required: usize,
88
+ pub optional: usize,
89
+ pub rest: bool,
90
+ pub keywords: bool,
91
+ }
92
+
93
+ impl Shape {
94
+ /// `required` positional arguments and `optional` more.
95
+ pub const fn positional(required: usize, optional: usize) -> Shape {
96
+ Shape {
97
+ required,
98
+ optional,
99
+ rest: false,
100
+ keywords: false,
101
+ }
102
+ }
103
+
104
+ /// The same, and keywords.
105
+ pub const fn with_keywords(required: usize, optional: usize) -> Shape {
106
+ Shape {
107
+ keywords: true,
108
+ ..Shape::positional(required, optional)
109
+ }
110
+ }
111
+ }
112
+
113
+ /// The arguments of one call, separated.
114
+ pub struct Scanned<'a> {
115
+ positional: &'a [Value],
116
+ keywords: Option<RHash>,
117
+ required: usize,
118
+ }
119
+
120
+ impl<'a> Scanned<'a> {
121
+ /// Required argument `i`.
122
+ pub fn required(&self, i: usize) -> Value {
123
+ debug_assert!(i < self.required);
124
+ self.positional[i]
125
+ }
126
+
127
+ /// Optional argument `i` (counting from the first optional one), or
128
+ /// `None` when it was not passed or was `nil`.
129
+ pub fn optional(&self, i: usize) -> Option<Value> {
130
+ self.positional
131
+ .get(self.required + i)
132
+ .copied()
133
+ .filter(|v| !v.is_nil())
134
+ }
135
+
136
+ /// The arguments past the required ones, for a `rest` shape.
137
+ pub fn rest(&self) -> &'a [Value] {
138
+ self.positional.get(self.required..).unwrap_or_default()
139
+ }
140
+
141
+ /// The keywords, or `None` when the call gave none.
142
+ pub fn keywords(&self) -> Option<RHash> {
143
+ self.keywords
144
+ }
145
+ }
146
+
147
+ /// Separate `args`, the method's own, by `shape`. Call it first thing in the
148
+ /// method's body: whether keywords were given is read from the current frame.
149
+ pub fn scan<'a>(ruby: &Ruby, args: &'a [Value], shape: Shape) -> Result<Scanned<'a>, Error> {
150
+ let (positional, keywords) = match args.split_last() {
151
+ Some((last, init)) if shape.keywords && crate::rb::method::keyword_given(ruby) => {
152
+ let h = RHash::from_value(*last).ok_or_else(|| {
153
+ crate::rb::error::internal_error("keywords were given, but not as a Hash")
154
+ })?;
155
+ (init, Some(h))
156
+ }
157
+ _ => (args, None),
158
+ };
159
+ let max = shape.required.saturating_add(shape.optional);
160
+ let given = positional.len();
161
+ if given < shape.required || (!shape.rest && given > max) {
162
+ return Err(arity_error(
163
+ given,
164
+ shape.required,
165
+ (!shape.rest).then_some(max),
166
+ ));
167
+ }
168
+ Ok(Scanned {
169
+ positional,
170
+ keywords,
171
+ required: shape.required,
172
+ })
173
+ }
174
+
175
+ /// Ruby's `ArgumentError` for `given` arguments where `min` to `max` (`None`:
176
+ /// any number) are taken: `rb_error_arity`'s message.
177
+ pub fn arity_error(given: usize, min: usize, max: Option<usize>) -> Error {
178
+ let class = crate::rb::Builtin::ArgumentError;
179
+ match max {
180
+ Some(max) if max == min => Error::new(
181
+ class,
182
+ format_args!("wrong number of arguments (given {given}, expected {min})"),
183
+ ),
184
+ Some(max) => Error::new(
185
+ class,
186
+ format_args!("wrong number of arguments (given {given}, expected {min}..{max})"),
187
+ ),
188
+ None => Error::new(
189
+ class,
190
+ format_args!("wrong number of arguments (given {given}, expected {min}+)"),
191
+ ),
192
+ }
193
+ }
194
+
195
+ /* ---- keywords ---- */
196
+
197
+ /// A method's keywords, before it has said which it takes. They are read
198
+ /// only through [`only`](Self::only), which refuses any other - as Ruby
199
+ /// refuses a keyword a method does not declare - and answers the [`Known`]
200
+ /// that reads them; or taken apart whole by [`split_off`](Self::split_off),
201
+ /// for a method whose other keywords are open by design (XPath's namespace
202
+ /// bindings). There is no lookup that ignores the rest: a misspelt keyword
203
+ /// must not quietly leave a default - a limit, an encoding - in place.
204
+ ///
205
+ /// The no-argument call is `Kwargs(None)`, answered before any scan. It is
206
+ /// the overwhelmingly common one - `to_html` with a keyword is the exception -
207
+ /// and on a small element the call does little else.
208
+ #[derive(Clone, Copy)]
209
+ pub struct Kwargs(Option<RHash>);
210
+
211
+ /// The keywords of a method that has declared the ones it takes
212
+ /// ([`Kwargs::only`]): every keyword given is one of them, and only they
213
+ /// can be read.
214
+ #[derive(Clone, Copy)]
215
+ pub struct Known {
216
+ h: Option<RHash>,
217
+ names: &'static [&'static str],
218
+ }
219
+
220
+ impl Kwargs {
221
+ pub fn scan(ruby: &Ruby, args: &[Value]) -> Result<Kwargs, Error> {
222
+ if args.is_empty() {
223
+ return Ok(Kwargs(None));
224
+ }
225
+ let a = scan(ruby, args, Shape::with_keywords(0, 0))?;
226
+ Ok(Kwargs(a.keywords()))
227
+ }
228
+
229
+ /// The keywords a scan already separated out (`None` for none).
230
+ pub fn from_scan(h: Option<RHash>) -> Kwargs {
231
+ Kwargs(h)
232
+ }
233
+
234
+ /// The keywords, held to `names`: any other is `ArgumentError`, worded as
235
+ /// Ruby words it - `unknown keyword: :prety`, or `unknown keyword:
236
+ /// "context"` for a key given as a String (`**{"context" => v}`), which
237
+ /// a method's keywords never are. The first one found is named.
238
+ ///
239
+ /// Each key is compared with the names' Symbols by identity, so the
240
+ /// check copies nothing and calls none of the key's methods (`eql?`).
241
+ pub fn only(self, ruby: &Ruby, names: &'static [&'static str]) -> Result<Known, Error> {
242
+ let Some(h) = self.0.filter(|h| !h.is_empty()) else {
243
+ return Ok(Known { h: None, names });
244
+ };
245
+ crate::hash::hash_foreach(h, |k, _| {
246
+ for name in names {
247
+ let sym = crate::build::symbol(ruby, name)?;
248
+ if crate::rb::value::same_value(k, sym.as_value()) {
249
+ return Ok(());
250
+ }
251
+ }
252
+ Err(crate::rb::error::arg_error(format_args!(
253
+ "unknown keyword: {}",
254
+ crate::describe::Describe(k)
255
+ )))
256
+ })?;
257
+ Ok(Known { h: Some(h), names })
258
+ }
259
+
260
+ /// Keyword `name`, and the OTHER keywords as a fresh Hash (`None` when none
261
+ /// remain).
262
+ ///
263
+ /// The key is dropped by raw identity, which is sound because keyword keys
264
+ /// are interned symbols. Copied rather than mutated, and read through the
265
+ /// Hash storage (`rb_hash_foreach`/`rb_hash_aset`) rather than
266
+ /// `dup`/`delete`, which a Hash subclass can redefine.
267
+ pub fn split_off(
268
+ self,
269
+ ruby: &Ruby,
270
+ name: &str,
271
+ ) -> Result<(Option<Value>, Option<RHash>), Error> {
272
+ /* No keywords is the common call: answer it without a symbol or a Hash. */
273
+ let Some(h) = self.0.filter(|h| !h.is_empty()) else {
274
+ return Ok((None, None));
275
+ };
276
+ let sym = crate::build::symbol(ruby, name)?;
277
+ let taken = h.get(sym)?.filter(|v: &Value| !v.is_nil());
278
+ let sym = sym.as_value();
279
+ /* Made on the first key that stays, so a call passing only `name`
280
+ * allocates no Hash either. */
281
+ let mut rest: Option<RHash> = None;
282
+ crate::hash::hash_foreach(h, |k, v| {
283
+ if !crate::rb::value::same_value(k, sym) {
284
+ let into = match rest {
285
+ Some(h) => h,
286
+ None => *rest.insert(crate::build::hash(ruby)?),
287
+ };
288
+ crate::build::aset(into, k, v)?;
289
+ }
290
+ Ok(())
291
+ })?;
292
+ Ok((taken, rest))
293
+ }
294
+ }
295
+
296
+ impl Known {
297
+ /// Keyword `name`, or `None` when it is absent or `nil`. `name` must be
298
+ /// one [`Kwargs::only`] was given: reading another is the method's own
299
+ /// mistake, and an internal error rather than a quiet `None`.
300
+ pub fn value(self, ruby: &Ruby, name: &str) -> Result<Option<Value>, Error> {
301
+ if !self.names.contains(&name) {
302
+ return Err(crate::rb::error::internal_error(format_args!(
303
+ "the keyword {name} was read but not declared"
304
+ )));
305
+ }
306
+ let Some(h) = self.h else {
307
+ return Ok(None);
308
+ };
309
+ Ok(h.get(crate::build::symbol(ruby, name)?)?
310
+ .filter(|v: &Value| !v.is_nil()))
311
+ }
312
+
313
+ /// Keyword `name`, read for truthiness: absent and `nil` are false, any
314
+ /// other value - `0` included, this being Ruby - true.
315
+ pub fn flag(self, ruby: &Ruby, name: &str) -> Result<bool, Error> {
316
+ Ok(self.value(ruby, name)?.is_some_and(|v| v.to_bool()))
317
+ }
318
+ }
@@ -0,0 +1,101 @@
1
+ //! Ruby objects made from Rust values - Arrays, Hashes, Integers, Floats,
2
+ //! Symbols - each a protected call of `raw`'s, so a failed
3
+ //! allocation is `Err`. The one way a caller makes one: `raw`'s constructors
4
+ //! are the crate's own. Each answers its own type, which every function
5
+ //! taking a value takes as it is (`impl ReprValue`). A String is `string`'s
6
+ //! (`string::utf8_str`).
7
+
8
+ #![forbid(unsafe_code)]
9
+
10
+ use crate::rb::ReprValue;
11
+ use crate::rb::{Error, Float, Integer, RArray, RHash, Ruby, Symbol, Value};
12
+
13
+ use super::raw;
14
+
15
+ /// An empty Array with room for `capa` elements.
16
+ pub fn ary(ruby: &Ruby, capa: usize) -> Result<RArray, Error> {
17
+ raw::ary_new_capa(ruby, capa)
18
+ }
19
+
20
+ /// Append `v` to `a`.
21
+ pub fn push(a: RArray, v: impl ReprValue) -> Result<(), Error> {
22
+ raw::ary_push(a, v.as_value())
23
+ }
24
+
25
+ /// A new Array of `vals`, made in one protected call rather than a push
26
+ /// each. `vals` is held on the caller's stack, where the GC sees it.
27
+ pub fn ary_from(ruby: &Ruby, vals: &[Value]) -> Result<RArray, Error> {
28
+ raw::ary_from_values(ruby, vals)
29
+ }
30
+
31
+ /// Append `vals` to `a`, in one protected call.
32
+ pub fn ary_cat(a: RArray, vals: &[Value]) -> Result<(), Error> {
33
+ raw::ary_cat(a, vals)
34
+ }
35
+
36
+ /// `pairs` - key, value, key, value - into `h`, in one protected call, a
37
+ /// later key's value replacing an earlier one's. A key must be a String or
38
+ /// a Symbol, as for [`aset`].
39
+ pub fn hash_insert_pairs(h: RHash, pairs: &[Value]) -> Result<(), Error> {
40
+ raw::hash_bulk_insert(h, pairs)
41
+ }
42
+
43
+ /// An empty Hash.
44
+ pub fn hash(ruby: &Ruby) -> Result<RHash, Error> {
45
+ raw::hash_new(ruby)
46
+ }
47
+
48
+ /// `h[k] = v`, for a String or Symbol `k` (any other is a `TypeError`: see
49
+ /// `raw::hash_aset`).
50
+ pub fn aset(h: RHash, k: impl ReprValue, v: impl ReprValue) -> Result<(), Error> {
51
+ raw::hash_aset(h, k.as_value(), v.as_value())
52
+ }
53
+
54
+ /// An Integer. Inlined, so a Fixnum is its bits at the call, with no call
55
+ /// (`raw::int_from_i64`).
56
+ #[inline]
57
+ pub fn int(ruby: &Ruby, n: i64) -> Result<Integer, Error> {
58
+ raw::int_from_i64(ruby, n)
59
+ }
60
+
61
+ /// The Integer `digits` spell in decimal - an optional `-`, then one or
62
+ /// more ASCII digits, nothing else - which may be past an `i64` (a Bignum).
63
+ /// Anything else is `ArgumentError`, decided here before Ruby reads them.
64
+ /// A value an `i64` holds is made without a String.
65
+ pub fn int_from_decimal(ruby: &Ruby, digits: &[u8]) -> Result<Integer, Error> {
66
+ let body = digits.strip_prefix(b"-").unwrap_or(digits);
67
+ if body.is_empty() || !body.iter().all(u8::is_ascii_digit) {
68
+ return Err(crate::rb::error::arg_error("not a decimal integer"));
69
+ }
70
+ /* All ASCII, checked above. */
71
+ if let Some(n) = core::str::from_utf8(digits)
72
+ .ok()
73
+ .and_then(|s| s.parse::<i64>().ok())
74
+ {
75
+ return int(ruby, n);
76
+ }
77
+ raw::str_to_inum(crate::string::binary_str(ruby, digits)?)
78
+ }
79
+
80
+ /// An Integer from an unsigned value, inlined as [`int`].
81
+ #[inline]
82
+ pub(crate) fn uint(ruby: &Ruby, n: u64) -> Result<Integer, Error> {
83
+ raw::int_from_u64(ruby, n)
84
+ }
85
+
86
+ /// A Float, inlined as [`int`]: a flonum is its bits at the call
87
+ /// (`raw::float_new`).
88
+ #[inline]
89
+ pub fn float(ruby: &Ruby, f: f64) -> Result<Float, Error> {
90
+ raw::float_new(ruby, f)
91
+ }
92
+
93
+ /// `obj.enum_for(meth)`: an Enumerator over `obj`'s method `meth`.
94
+ pub fn enumerator(ruby: &Ruby, obj: Value, meth: &str) -> Result<Value, Error> {
95
+ raw::enumeratorize(obj, raw::sym(ruby, meth)?)
96
+ }
97
+
98
+ /// The Symbol named by the UTF-8 `name`.
99
+ pub fn symbol(ruby: &Ruby, name: &str) -> Result<Symbol, Error> {
100
+ raw::sym(ruby, name)
101
+ }
@@ -0,0 +1,171 @@
1
+ //! Catching a panic at a C boundary, and re-raising it once past one.
2
+ //!
3
+ //! The crate unwinds, so a panic normally becomes a Ruby exception on the
4
+ //! thread that raised it. That stops being true the moment a C frame is in the
5
+ //! way: Rust turns an unwind at an `extern "C"` boundary into an ABORT, because
6
+ //! unwinding through frames compiled without unwind tables is undefined
7
+ //! behaviour. A C library an extension calls can call back into Rust - and so
8
+ //! does Ruby, through
9
+ //! `rb_protect` and `rb_thread_call_without_gvl`. A panic in any of those would
10
+ //! take the host down, which is exactly what `panic = "unwind"` exists to stop.
11
+ //!
12
+ //! So a callback does not panic INTO C. It catches the panic, latches it, and
13
+ //! returns the status that asks C to stop. The caller, once C has unwound
14
+ //! normally and every resource it owns is released, calls [`PanicLatch::resume`]
15
+ //! and the panic continues from a frame that has only Rust above it.
16
+ //!
17
+ //! Deferred, not swallowed: `resume_unwind` re-raises the ORIGINAL payload, so
18
+ //! the message and the exception Ruby finally sees are the ones the panic
19
+ //! carried. The only difference from panicking directly is that the C frames
20
+ //! were unwound by C, in the way C expects.
21
+ //!
22
+ //! This is the same shape a callback uses for any other reason to stop - a
23
+ //! limit reached, an allocation failure - latch a flag, return STOP, report after the walk - and
24
+ //! it is deliberately the same, because a panic has no better claim than an OOM
25
+ //! to be handled mid-traversal.
26
+
27
+ use core::any::Any;
28
+ use core::panic::AssertUnwindSafe;
29
+
30
+ /// A caught panic, waiting for a frame where re-raising it is safe.
31
+ #[derive(Default)]
32
+ pub struct PanicLatch(Option<Box<dyn Any + Send + 'static>>);
33
+
34
+ impl PanicLatch {
35
+ pub const fn new() -> PanicLatch {
36
+ PanicLatch(None)
37
+ }
38
+
39
+ /// Whether a panic has been caught. Callers test this the way they test
40
+ /// their `oom` flag: it means "stop, the result is not usable".
41
+ #[inline]
42
+ pub fn caught(&self) -> bool {
43
+ self.0.is_some()
44
+ }
45
+
46
+ /// Run `f`; if it panics, latch the panic and return `stop` instead.
47
+ ///
48
+ /// The FIRST panic is the one kept. A traversal can call back many times,
49
+ /// and the later ones are consequences of stopping, not new information.
50
+ /// Always inlined: inside an `extern "C"` callback, where nothing may
51
+ /// unwind (`crate::no_unwind`), the compiler shows the catch complete
52
+ /// only when it sees it in place.
53
+ #[inline(always)]
54
+ pub fn guard<R>(&mut self, stop: R, f: impl FnOnce() -> R) -> R {
55
+ match std::panic::catch_unwind(AssertUnwindSafe(f)) {
56
+ Ok(v) => v,
57
+ Err(payload) => {
58
+ /* The first panic is the one kept; a later one is dropped -
59
+ * through `quietly`, as a payload's drop is its own code. */
60
+ if self.0.is_none() {
61
+ /* `replace`, not `=`: an assignment drops the old value,
62
+ * which the compiler cannot see is `None`. */
63
+ core::mem::forget(self.0.replace(payload));
64
+ } else {
65
+ quietly((), || drop(payload));
66
+ }
67
+ stop
68
+ }
69
+ }
70
+ }
71
+
72
+ /// Re-raise the latched panic, if there is one.
73
+ ///
74
+ /// Call this only where no C frame is left on the stack - that is the whole
75
+ /// point - and after anything the interrupted work owned has been released.
76
+ #[inline]
77
+ pub fn resume(&mut self) {
78
+ if let Some(payload) = self.0.take() {
79
+ std::panic::resume_unwind(payload);
80
+ }
81
+ }
82
+ }
83
+
84
+ /// Run `f` where nothing may unwind: a panic in it is caught and answered
85
+ /// by `fallback`, and its payload is leaked rather than dropped - a payload's
86
+ /// drop is its own type's code, which could panic in turn. A few bytes, on a
87
+ /// path that is already a bug.
88
+ ///
89
+ /// For the code the compiler cannot show unwind-free (`crate::no_unwind`): a
90
+ /// payload's drop or its `downcast` (calls through its vtable), a tree's
91
+ /// recursive drop glue, the GC's advisory size.
92
+ #[inline(always)]
93
+ pub fn quietly<R>(fallback: R, f: impl FnOnce() -> R) -> R {
94
+ match std::panic::catch_unwind(AssertUnwindSafe(f)) {
95
+ Ok(v) => v,
96
+ Err(payload) => {
97
+ core::mem::forget(payload);
98
+ fallback
99
+ }
100
+ }
101
+ }
102
+
103
+ /// The message a panic payload carries, as `panic!` and the standard library's
104
+ /// own panics produce it. `"a panic"` when it is neither of the two shapes the
105
+ /// runtime uses, which no panic in this crate is.
106
+ #[inline]
107
+ pub fn message(payload: &(dyn Any + Send)) -> &str {
108
+ if let Some(s) = payload.downcast_ref::<&'static str>() {
109
+ s
110
+ } else if let Some(s) = payload.downcast_ref::<String>() {
111
+ s.as_str()
112
+ } else {
113
+ "a panic"
114
+ }
115
+ }
116
+
117
+ /// A caught panic's [`message`], copied into a `Msg` for the exception
118
+ /// raised in its place, and the payload dropped - both [`quietly`], since a
119
+ /// payload's `downcast` and its drop are calls through its vtable, which the
120
+ /// compiler cannot show unwind-free. What the trampolines (`rb::method`'s
121
+ /// `finish` and `run_init`) make of a panic; inlined into them, or
122
+ /// `rake no_unwind` cannot see that the call does not unwind.
123
+ #[inline(always)]
124
+ pub(crate) fn panic_message(payload: Box<dyn Any + Send>) -> crate::msg::Msg {
125
+ let msg = quietly(crate::msg::Msg::copy("a panic"), || {
126
+ crate::msg::Msg::copy(message(payload.as_ref()))
127
+ });
128
+ quietly((), || drop(payload));
129
+ msg
130
+ }
131
+
132
+ #[cfg(test)]
133
+ mod tests {
134
+ use super::*;
135
+
136
+ fn payload_of(f: impl FnOnce()) -> Box<dyn Any + Send> {
137
+ std::panic::catch_unwind(AssertUnwindSafe(f)).err().unwrap()
138
+ }
139
+
140
+ #[test]
141
+ fn a_message_is_read_from_either_shape_panic_makes() {
142
+ assert_eq!(message(payload_of(|| panic!("static")).as_ref()), "static");
143
+ let n = 7;
144
+ assert_eq!(
145
+ message(payload_of(|| panic!("formatted {n}")).as_ref()),
146
+ "formatted 7"
147
+ );
148
+ let other = payload_of(|| std::panic::panic_any(42_u8));
149
+ assert_eq!(message(other.as_ref()), "a panic");
150
+ }
151
+
152
+ #[test]
153
+ fn a_latch_keeps_the_first_panic_and_resumes_it() {
154
+ let mut latch = PanicLatch::new();
155
+ assert_eq!(latch.guard(0, || 1), 1);
156
+ assert!(!latch.caught());
157
+ assert_eq!(latch.guard(0, || panic!("first")), 0);
158
+ assert_eq!(latch.guard(0, || panic!("second")), 0);
159
+ assert!(latch.caught());
160
+ let resumed = payload_of(|| latch.resume());
161
+ assert_eq!(message(resumed.as_ref()), "first");
162
+ assert!(!latch.caught());
163
+ latch.resume(); /* nothing latched: a no-op */
164
+ }
165
+
166
+ #[test]
167
+ fn quietly_answers_its_fallback_for_a_panic() {
168
+ assert_eq!(quietly(5, || 6), 6);
169
+ assert_eq!(quietly(5, || panic!("swallowed")), 5);
170
+ }
171
+ }
@@ -0,0 +1,37 @@
1
+ //! [`CName`]: a short name - a class or method to define, an encoding to
2
+ //! look up - as the NUL-terminated C string Ruby's C API takes, held on the
3
+ //! stack. Ruby-free.
4
+
5
+ #![forbid(unsafe_code)]
6
+
7
+ use core::ffi::CStr;
8
+
9
+ /// The longest name a [`CName`] holds, its NUL included. Every name the
10
+ /// layer hands Ruby this way is a short identifier.
11
+ const NAME_MAX: usize = 64;
12
+
13
+ /// A name as a C string, on the stack.
14
+ pub(crate) struct CName([u8; NAME_MAX]);
15
+
16
+ impl core::ops::Deref for CName {
17
+ type Target = CStr;
18
+ fn deref(&self) -> &CStr {
19
+ /* `new` wrote a NUL and checked there is no other. */
20
+ CStr::from_bytes_until_nul(&self.0).unwrap_or(c"")
21
+ }
22
+ }
23
+
24
+ impl CName {
25
+ /// `name` NUL-terminated on the stack, or `None` for one with a NUL of
26
+ /// its own or too long to leave room for the terminator.
27
+ pub(crate) fn new(name: &[u8]) -> Option<CName> {
28
+ let mut buf = [0u8; NAME_MAX];
29
+ match buf.get_mut(..name.len()) {
30
+ Some(dst) if name.len() < NAME_MAX && !name.contains(&0) => {
31
+ dst.copy_from_slice(name);
32
+ Some(CName(buf))
33
+ }
34
+ _ => None,
35
+ }
36
+ }
37
+ }