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,144 @@
1
+ //! How a raise becomes an `Err`, and how one is raised again, in Nupur's
2
+ //! types: the protection every wrapper of [`super`] runs its C call under
3
+ //! ([`call`]), the exit a protected call left pending, `$!`, and the calls
4
+ //! that leave on purpose ([`exc_raise`], [`resume`]).
5
+ //!
6
+ //! The protection itself is `nupur_sys::protect`'s - the `rb_protect` thunk,
7
+ //! the pending exit, `$!` - and each function here is its safe face: it holds
8
+ //! the proof of the GVL its caller has, and makes the raw exception a
9
+ //! `nupur_sys` call came back with an [`Error`].
10
+ //!
11
+ //! The rest of `raw` is the wrappers, every one a C call made inside
12
+ //! [`call`]; `rake dylint` holds it to that (`unraising_call_in_raw`).
13
+
14
+ #![allow(unsafe_code)]
15
+
16
+ use core::ffi::c_int;
17
+
18
+ use crate::rb::value::AsSys;
19
+ use crate::rb::{Error, Ruby, Value};
20
+ use nupur_sys::protect::{Caught, Protected};
21
+
22
+ /// Forget a pending exit (`nupur_sys::protect::reset_pending_exit`).
23
+ ///
24
+ /// # Safety
25
+ ///
26
+ /// As there: nothing pending may be lost.
27
+ #[inline]
28
+ pub(crate) unsafe fn reset_pending_exit() {
29
+ // SAFETY: the caller's.
30
+ unsafe { nupur_sys::protect::reset_pending_exit() }
31
+ }
32
+
33
+ use nupur_sys::protect::injected_raise;
34
+ #[cfg(feature = "alloc-inject")]
35
+ pub(crate) use nupur_sys::protect::set_raise_injector;
36
+
37
+ /// The exit pending, as the `Err` that resumes it, or `None`.
38
+ #[inline]
39
+ pub(crate) fn pending_exit() -> Option<Error> {
40
+ nupur_sys::protect::pending_exit().map(Error::jump)
41
+ }
42
+
43
+ /// Resume the non-local exit `state` stands for, which a protected call
44
+ /// caught: the one way a pending exit leaves the layer. Only `Error::raise`
45
+ /// calls it, as a trampoline's last act, with nothing owned.
46
+ #[inline]
47
+ #[cfg_attr(
48
+ dylint_lib = "nupur_lints",
49
+ allow(
50
+ ffi_without_gvl_proof,
51
+ reason = "crate-private: only a trampoline's raise resumes an exit, with the GVL"
52
+ )
53
+ )]
54
+ pub(crate) fn resume(state: c_int) -> ! {
55
+ // SAFETY: a trampoline's last act, under the GVL, with nothing owned.
56
+ unsafe { nupur_sys::protect::resume(state) }
57
+ }
58
+
59
+ /// Run `f` - one C call, and the `Copy` values it reads - under
60
+ /// `nupur_sys::protect::call`; a raise comes back as `Err`, and `$!` is
61
+ /// cleared (an error the caller handles rather than raises is run under
62
+ /// [`keeping_errinfo`]). `F: Copy` and `T: Copy` are that call's: the
63
+ /// thunk's frame owns nothing a skipped destructor would leak. `f` is lent
64
+ /// the `&Protected` that `nupur_sys::raising`'s wrappers take.
65
+ #[inline]
66
+ #[cfg_attr(
67
+ dylint_lib = "nupur_lints",
68
+ allow(
69
+ ffi_without_gvl_proof,
70
+ reason = "the raw module's alone: every wrapper that hands it its C call holds the proof"
71
+ )
72
+ )]
73
+ pub(super) fn call<T: Copy, F: FnOnce(&Protected) -> T + Copy>(f: F) -> Result<T, Error> {
74
+ // SAFETY: every caller is a wrapper of `raw` holding a proof of the GVL;
75
+ // `f` owns nothing (it is `Copy`).
76
+ match unsafe { nupur_sys::protect::call(f) } {
77
+ Ok(out) => Ok(out),
78
+ Err(caught) => Err(error_of(caught)),
79
+ }
80
+ }
81
+
82
+ /// [`call`] for a C call that allocates, and so can raise `NoMemoryError`:
83
+ /// `rake oom`'s raise sweep may make it raise before the C call
84
+ /// (`injected_raise`), so the path that handles that `Err` is run. A call
85
+ /// that cannot raise for want of memory is [`call`]'s.
86
+ #[inline]
87
+ #[cfg_attr(
88
+ dylint_lib = "nupur_lints",
89
+ expect(
90
+ unraising_call_in_raw,
91
+ reason = "the C call is `f`'s, which the lint checks where `call_allocating` is called"
92
+ )
93
+ )]
94
+ pub(super) fn call_allocating<T: Copy, F: FnOnce(&Protected) -> T + Copy>(
95
+ f: F,
96
+ ) -> Result<T, Error> {
97
+ call(move |inside| {
98
+ injected_raise(inside);
99
+ f(inside)
100
+ })
101
+ }
102
+
103
+ /// The `Err` a protected call's [`Caught`] stands for.
104
+ #[inline]
105
+ fn error_of(caught: Caught) -> Error {
106
+ match caught {
107
+ Caught::Exception(exc) => Error::exception(Value::from_sys(exc)),
108
+ Caught::Jump(state) => Error::jump(state),
109
+ Caught::NotRun => crate::rb::error::internal_error("a protected call did not run"),
110
+ }
111
+ }
112
+
113
+ /// Run `f`, protected calls whose error the caller handles rather than
114
+ /// raises, with `$!` put back as it was after
115
+ /// (`nupur_sys::protect::keeping_errinfo`).
116
+ #[inline]
117
+ #[cfg_attr(
118
+ dylint_lib = "nupur_lints",
119
+ allow(
120
+ ffi_without_gvl_proof,
121
+ reason = "crate-private: called only from functions holding a proof, around their protected calls"
122
+ )
123
+ )]
124
+ pub(crate) fn keeping_errinfo<T>(f: impl FnOnce() -> T) -> T {
125
+ // SAFETY: under the GVL, as every caller's proof says.
126
+ unsafe { nupur_sys::protect::keeping_errinfo(f) }
127
+ }
128
+
129
+ /// Clear the error info a protected call left behind
130
+ /// (`nupur_sys::protect::forget_errinfo`).
131
+ #[inline]
132
+ pub(crate) fn forget_errinfo(_: &Ruby) {
133
+ // SAFETY: the token is the GVL.
134
+ unsafe { nupur_sys::protect::forget_errinfo() }
135
+ }
136
+
137
+ /// `rb_exc_raise`: raise `exc`. Raises, by design - only `Error::raise` calls
138
+ /// it, with nothing owned.
139
+ #[inline]
140
+ pub(crate) fn exc_raise(exc: Value) -> ! {
141
+ // SAFETY: `exc` is a live exception object, a Ruby value and so the
142
+ // proof of the GVL; the one caller owns nothing.
143
+ unsafe { nupur_sys::protect::exc_raise(exc.as_sys()) }
144
+ }
@@ -0,0 +1,148 @@
1
+ //! Strings and their encodings.
2
+
3
+ use super::*;
4
+
5
+ /// `rb_utf8_str_new` of `bytes`: raises `NoMemoryError`. The String is tagged
6
+ /// UTF-8 without a check: `bytes` that were not would make a wrong String,
7
+ /// never a memory error.
8
+ #[inline]
9
+ pub(crate) fn utf8_str_new(_: &Ruby, bytes: &[u8]) -> Result<RString, Error> {
10
+ let (p, n) = (
11
+ bytes.as_ptr() as *const c_char,
12
+ c_len(bytes.len(), "string too large")?,
13
+ );
14
+ let v = call_allocating(|inside| unsafe { nupur_sys::raising::rb_utf8_str_new(inside, p, n) })?;
15
+ typed(v, RString::from_value, "a C call made no String")
16
+ }
17
+
18
+ /// `rb_str_new` of `bytes`: an ASCII-8BIT String, which carries any bytes.
19
+ /// Raises `NoMemoryError`.
20
+ #[inline]
21
+ pub(crate) fn binary_str_new(_: &Ruby, bytes: &[u8]) -> Result<RString, Error> {
22
+ let (p, n) = (
23
+ bytes.as_ptr() as *const c_char,
24
+ c_len(bytes.len(), "string too large")?,
25
+ );
26
+ let v = call_allocating(|inside| unsafe { nupur_sys::raising::rb_str_new(inside, p, n) })?;
27
+ typed(v, RString::from_value, "a C call made no String")
28
+ }
29
+
30
+ /// A UTF-8 String of `len` bytes whose content is NOT written:
31
+ /// `rb_utf8_str_new(NULL, len)`, which raises `NoMemoryError`. What
32
+ /// `string::utf8_str_filled` writes in place.
33
+ ///
34
+ /// # Safety
35
+ /// Before Ruby code can see the String, every one of its `len` bytes is
36
+ /// written or its length set to 0: its buffer holds whatever the allocation
37
+ /// held.
38
+ #[inline]
39
+ pub(crate) unsafe fn utf8_str_unwritten(_: &Ruby, len: usize) -> Result<RString, Error> {
40
+ let n = c_len(len, "string too large")?;
41
+ let v = call_allocating(|inside| unsafe {
42
+ nupur_sys::raising::rb_utf8_str_new(inside, core::ptr::null(), n)
43
+ })?;
44
+ typed(v, RString::from_value, "a C call made no String")
45
+ }
46
+
47
+ /// `rb_enc_interned_str` of `bytes` in `enc`: raises `NoMemoryError`.
48
+ #[inline]
49
+ pub(crate) fn enc_interned_str(bytes: &[u8], enc: Encoding) -> Result<RString, Error> {
50
+ let (p, n, e) = (
51
+ bytes.as_ptr() as *const c_char,
52
+ c_len(bytes.len(), "string too large")?,
53
+ enc.as_raw(),
54
+ );
55
+ let v = call_allocating(|inside| unsafe {
56
+ nupur_sys::raising::rb_enc_interned_str(inside, p, n, e)
57
+ })?;
58
+ typed(v, RString::from_value, "a C call made no String")
59
+ }
60
+
61
+ /// `rb_str_dup`: raises `NoMemoryError`.
62
+ #[inline]
63
+ pub(crate) fn str_dup(s: RString) -> Result<RString, Error> {
64
+ let v = s.as_sys();
65
+ let d = call_allocating(|inside| unsafe { nupur_sys::raising::rb_str_dup(inside, v) })?;
66
+ typed(d, RString::from_value, "a C call made no String")
67
+ }
68
+
69
+ /// `rb_enc_str_coderange`: Ruby's scan of `s` for its coderange, cached in
70
+ /// the String's flags, so the next read of them answers without a scan.
71
+ /// Protected, as the survey finds a path to a raise.
72
+ #[inline]
73
+ pub(crate) fn enc_str_coderange(s: RString) -> Result<(), Error> {
74
+ let v = s.as_sys();
75
+ call(|inside| unsafe { nupur_sys::raising::rb_enc_str_coderange(inside, v) }).map(|_| ())
76
+ }
77
+
78
+ /// `rb_str_locktmp`: Ruby refuses every change to `s` until it is
79
+ /// unlocked, raising a `RuntimeError` for one already locked.
80
+ #[inline]
81
+ pub(crate) fn str_locktmp(s: RString) -> Result<(), Error> {
82
+ let v = s.as_sys();
83
+ call(|inside| unsafe { nupur_sys::raising::rb_str_locktmp(inside, v) }).map(|_| ())
84
+ }
85
+
86
+ /// `rb_enc_associate`: `s` itself, tagged `enc`. Raises `FrozenError` for a
87
+ /// frozen String, and `ArgumentError` for an encoding its bytes cannot carry.
88
+ #[inline]
89
+ pub(crate) fn enc_associate(s: RString, enc: Encoding) -> Result<RString, Error> {
90
+ let (v, e) = (s.as_sys(), enc.as_raw());
91
+ let r = call(|inside| unsafe { nupur_sys::raising::rb_enc_associate(inside, v, e) })?;
92
+ typed(r, RString::from_value, "a C call made no String")
93
+ }
94
+
95
+ /// `rb_str_encode` to `enc` with `flags`: raises `Encoding::ConverterNotFoundError`
96
+ /// when Ruby has no converter, and - without replacement flags -
97
+ /// `Encoding::InvalidByteSequenceError` / `UndefinedConversionError`; the new
98
+ /// String's allocation raises `NoMemoryError`.
99
+ #[inline]
100
+ pub(crate) fn str_encode(s: RString, enc: Encoding, flags: c_int) -> Result<RString, Error> {
101
+ let (v, e) = (s.as_sys(), enc.as_raw());
102
+ let r = call_allocating(|inside| unsafe {
103
+ nupur_sys::raising::rb_str_encode(
104
+ inside,
105
+ v,
106
+ nupur_sys::raising::rb_enc_from_encoding(inside, e),
107
+ flags,
108
+ inside.ruby().qnil(),
109
+ )
110
+ })?;
111
+ typed(r, RString::from_value, "a C call made no String")
112
+ }
113
+
114
+ /// `rb_to_encoding` of an `Encoding` or a String: raises `ArgumentError` for
115
+ /// an unknown name. Any other value is a `TypeError` here, before the call,
116
+ /// which would convert it with its `to_str`.
117
+ #[inline]
118
+ pub(crate) fn to_encoding(ruby: &Ruby, v: Value) -> Result<Encoding, Error> {
119
+ use crate::rb::ReprValue;
120
+ if !v.is_kind_of(ruby.class_encoding()) && RString::from_value(v).is_none() {
121
+ return Err(crate::rb::error::type_error(
122
+ "an Encoding or a String was expected",
123
+ ));
124
+ }
125
+ let r = v.as_sys();
126
+ let e = call(|inside| unsafe { nupur_sys::raising::rb_to_encoding(inside, r) })?;
127
+ // SAFETY: Ruby's encodings live for the process.
128
+ Ok(unsafe { Encoding::from_raw(e) })
129
+ }
130
+
131
+ /// `rb_enc_find_index` + `rb_enc_from_index`: may autoload the encoding,
132
+ /// which can raise (`LoadError`) and is a GC point; `None` for a name Ruby
133
+ /// does not know. Not `rb_enc_find`, which answers ASCII-8BIT for one.
134
+ #[inline]
135
+ pub(crate) fn enc_find(_: &Ruby, name: &core::ffi::CStr) -> Result<Option<Encoding>, Error> {
136
+ let p = name.as_ptr();
137
+ let e = call(|inside| unsafe {
138
+ let index = nupur_sys::raising::rb_enc_find_index(inside, p);
139
+ if index < 0 {
140
+ core::ptr::null_mut()
141
+ } else {
142
+ nupur_sys::non_raising::rb_enc_from_index(inside.ruby(), index)
143
+ }
144
+ })?;
145
+ // SAFETY: a non-null answer is one of Ruby's encodings, which live for
146
+ // the process.
147
+ Ok((!e.is_null()).then(|| unsafe { Encoding::from_raw(e) }))
148
+ }
@@ -0,0 +1,38 @@
1
+ //! Symbols and ids.
2
+
3
+ use super::*;
4
+
5
+ /// `rb_intern3` of a UTF-8 name: raises `NoMemoryError` when the symbol table
6
+ /// cannot grow (interning valid UTF-8 raises nothing else).
7
+ #[inline]
8
+ pub(crate) fn intern(_: &Ruby, name: &str) -> Result<Id, Error> {
9
+ let (p, n) = (
10
+ name.as_ptr() as *const c_char,
11
+ c_len(name.len(), "a name too long for the C API")?,
12
+ );
13
+ call_allocating(|inside| unsafe {
14
+ nupur_sys::raising::rb_intern3(
15
+ inside,
16
+ p,
17
+ n,
18
+ nupur_sys::non_raising::rb_utf8_encoding(inside.ruby()),
19
+ )
20
+ })
21
+ .map(Id::from_raw)
22
+ }
23
+
24
+ /// `rb_intern` of a NUL-terminated name: as [`intern`].
25
+ #[inline]
26
+ pub(crate) fn intern_cstr(_: &Ruby, name: &core::ffi::CStr) -> Result<Id, Error> {
27
+ let p = name.as_ptr();
28
+ call_allocating(|inside| unsafe { nupur_sys::raising::rb_intern(inside, p) }).map(Id::from_raw)
29
+ }
30
+
31
+ /// The Symbol of the UTF-8 `name`: [`intern`] and `rb_id2sym`, which raises
32
+ /// `NoMemoryError` when a dynamic Symbol is made.
33
+ #[inline]
34
+ pub(crate) fn sym(ruby: &Ruby, name: &str) -> Result<Symbol, Error> {
35
+ let id = intern(ruby, name)?.as_raw();
36
+ let v = call_allocating(|inside| unsafe { nupur_sys::raising::rb_id2sym(inside, id) })?;
37
+ typed(v, Symbol::from_value, "a C call made no Symbol")
38
+ }
@@ -0,0 +1,293 @@
1
+ //! Arrays, Hashes, Ranges and numbers (`build` spells some of these for a caller).
2
+
3
+ use super::*;
4
+
5
+ /// `rb_ary_new_capa`: raises `NoMemoryError`.
6
+ #[inline]
7
+ pub(crate) fn ary_new_capa(_: &Ruby, capa: usize) -> Result<RArray, Error> {
8
+ let n = crate::int::capacity(capa);
9
+ let v = call_allocating(|inside| unsafe { nupur_sys::raising::rb_ary_new_capa(inside, n) })?;
10
+ typed(v, RArray::from_value, "a C call made no Array")
11
+ }
12
+
13
+ /// `rb_ary_push`: raises `NoMemoryError`, and `FrozenError` for a frozen
14
+ /// Array.
15
+ #[inline]
16
+ pub(crate) fn ary_push(a: RArray, v: Value) -> Result<(), Error> {
17
+ let (a, v) = (a.as_sys(), v.as_sys());
18
+ call_allocating(|inside| unsafe { nupur_sys::raising::rb_ary_push(inside, a, v) }).map(|_| ())
19
+ }
20
+
21
+ /// `rb_ivar_set` for a hidden ivar (a name without `@`, so Ruby code cannot
22
+ /// see it): raises `FrozenError` for a frozen object and
23
+ /// `NoMemoryError`.
24
+ #[inline]
25
+ pub(crate) fn ivar_set(obj: Value, id: crate::rb::HiddenId, v: Value) -> Result<(), Error> {
26
+ let (o, v, id) = (obj.as_sys(), v.as_sys(), id.as_raw());
27
+ call_allocating(|inside| unsafe { nupur_sys::raising::rb_ivar_set(inside, o, id, v) })
28
+ .map(|_| ())
29
+ }
30
+
31
+ /// `rb_hash_lookup2` at the Fixnum `n`: a Fixnum hashes and compares by
32
+ /// value in C, so no Ruby code runs; protected all the same, and a raise
33
+ /// passed on, as [`hash_lookup`]'s is.
34
+ #[inline]
35
+ pub(crate) fn table_get(h: RHash, n: u32) -> Result<Option<Value>, Error> {
36
+ let h = h.as_sys();
37
+ /* No entry has a key past a Fixnum - past 2^30 - 1 on Windows. */
38
+ let Some(key) = h.ruby().fixnum(i64::from(n)) else {
39
+ return Ok(None);
40
+ };
41
+ let v = call(|inside| unsafe {
42
+ nupur_sys::raising::rb_hash_lookup2(inside, h, key, inside.ruby().qundef())
43
+ })?;
44
+ /* A value of the Hash's, or `Qundef`, which is not handed out. */
45
+ Ok((!v.is_undef()).then(|| Value::from_sys(v)))
46
+ }
47
+
48
+ /// `rb_hash_aset` at the Fixnum `n`: raises `NoMemoryError`.
49
+ #[inline]
50
+ pub(crate) fn table_set(h: RHash, n: u32, v: Value) -> Result<(), Error> {
51
+ /* No entry for a key past a Fixnum: refused, never wrapped round. */
52
+ let key = h.as_sys().ruby().fixnum(i64::from(n)).ok_or_else(|| {
53
+ Error::new(
54
+ crate::rb::Builtin::RangeError,
55
+ "a table key past a Fixnum (2^30 - 1 on Windows)",
56
+ )
57
+ })?;
58
+ let (h, v) = (h.as_sys(), v.as_sys());
59
+ call_allocating(|inside| unsafe { nupur_sys::raising::rb_hash_aset(inside, h, key, v) })
60
+ .map(|_| ())
61
+ }
62
+
63
+ /// A key whose hash Ruby computes itself ([`crate::rb::value::plain_key`]),
64
+ /// or the `TypeError` for one whose `#hash` and `#eql?` would be called.
65
+ #[inline]
66
+ pub(super) fn plain_key_or_refuse(k: Value) -> Result<(), Error> {
67
+ if crate::rb::value::plain_key(k) {
68
+ return Ok(());
69
+ }
70
+ Err(crate::rb::error::type_error(
71
+ "a Hash key must be a Symbol or a String (not a subclass's)",
72
+ ))
73
+ }
74
+
75
+ /// `rb_hash_new`: raises `NoMemoryError`.
76
+ #[inline]
77
+ pub(crate) fn hash_new(_: &Ruby) -> Result<RHash, Error> {
78
+ let v = call_allocating(|inside| unsafe { nupur_sys::raising::rb_hash_new(inside) })?;
79
+ typed(v, RHash::from_value, "a C call made no Hash")
80
+ }
81
+
82
+ /// A Hash no Ruby code can find: `rb_hash_new`, then `rb_obj_hide` with
83
+ /// nothing between, so `ObjectSpace` never lists it - an object's private
84
+ /// table ([`crate::table::IntTable`]), which is never shown. Raises
85
+ /// `NoMemoryError`. Hand it to no Ruby code: a hidden object has no class.
86
+ pub(crate) fn hidden_hash_new(ruby: &Ruby) -> Result<RHash, Error> {
87
+ let h = hash_new(ruby)?;
88
+ // SAFETY: the Hash just made, referenced only from this frame.
89
+ unsafe { crate::rb::object::obj_hide(crate::rb::ReprValue::as_value(h)) };
90
+ Ok(h)
91
+ }
92
+
93
+ /// `rb_ary_new_from_values`: a new Array of `vals`, in one call. Raises
94
+ /// `NoMemoryError`.
95
+ #[inline]
96
+ pub(crate) fn ary_from_values(_: &Ruby, vals: &[Value]) -> Result<RArray, Error> {
97
+ let n = c_len(vals.len(), "too many values for one Array")?;
98
+ /* `Value` is transparent over `VALUE`, so the slice is the C array. */
99
+ let p = vals.as_ptr().cast::<nupur_sys::value::Value>();
100
+ let v = call_allocating(|inside| unsafe {
101
+ nupur_sys::raising::rb_ary_new_from_values(inside, n, p)
102
+ })?;
103
+ typed(v, RArray::from_value, "a C call made no Array")
104
+ }
105
+
106
+ /// `rb_ary_cat`: append `vals` to `a`, in one call. Raises `NoMemoryError`,
107
+ /// and `FrozenError` for a frozen Array.
108
+ #[inline]
109
+ pub(crate) fn ary_cat(a: RArray, vals: &[Value]) -> Result<(), Error> {
110
+ let n = c_len(vals.len(), "too many values for one Array")?;
111
+ let (a, p) = (a.as_sys(), vals.as_ptr().cast::<nupur_sys::value::Value>());
112
+ call_allocating(|inside| unsafe { nupur_sys::raising::rb_ary_cat(inside, a, p, n) }).map(|_| ())
113
+ }
114
+
115
+ /// `rb_hash_bulk_insert`: `pairs` (key, value, key, value, ...) into `h`,
116
+ /// in one call, a later key's value replacing an earlier one's. Every key
117
+ /// must be one Ruby hashes in C, as [`hash_aset`] requires - anything else,
118
+ /// or an odd count, is refused before the call. Raises `NoMemoryError`, and
119
+ /// `FrozenError` for a frozen Hash.
120
+ #[inline]
121
+ pub(crate) fn hash_bulk_insert(h: RHash, pairs: &[Value]) -> Result<(), Error> {
122
+ if !pairs.len().is_multiple_of(2) {
123
+ return Err(crate::rb::error::arg_error(
124
+ "an odd number of keys and values",
125
+ ));
126
+ }
127
+ for k in pairs.iter().step_by(2) {
128
+ plain_key_or_refuse(*k)?;
129
+ }
130
+ let n = c_len(pairs.len(), "too many keys and values for one Hash")?;
131
+ let (h, p) = (h.as_sys(), pairs.as_ptr().cast::<nupur_sys::value::Value>());
132
+ call_allocating(|inside| unsafe { nupur_sys::raising::rb_hash_bulk_insert(inside, n, p, h) })
133
+ }
134
+
135
+ /// `rb_hash_aset` for a Symbol or String key, whose hash Ruby computes
136
+ /// itself ([`crate::rb::value::plain_key`]): any other key - an instance of a
137
+ /// String subclass included - would have its `#hash` and `#eql?` called, so
138
+ /// it is a `TypeError` here. Raises `NoMemoryError`, and `FrozenError` for a
139
+ /// frozen Hash.
140
+ #[inline]
141
+ pub(crate) fn hash_aset(h: RHash, k: Value, v: Value) -> Result<(), Error> {
142
+ plain_key_or_refuse(k)?;
143
+ let (h, k, v) = (h.as_sys(), k.as_sys(), v.as_sys());
144
+ call_allocating(|inside| unsafe { nupur_sys::raising::rb_hash_aset(inside, h, k, v) })
145
+ .map(|_| ())
146
+ }
147
+
148
+ /// `rb_ll2inum`: raises `NoMemoryError` for a value past a Fixnum (a Bignum).
149
+ #[inline]
150
+ pub(crate) fn int_from_i64(ruby: &Ruby, n: i64) -> Result<Integer, Error> {
151
+ /* A Fixnum is the value's own bits: no allocation, nothing to raise, no
152
+ * protected call - the common case (a length, an index, a count). */
153
+ if let Some(v) = ruby.sys().fixnum(n) {
154
+ return Ok(Integer::from_known(Value::from_sys(v)));
155
+ }
156
+ bignum_from_i64(ruby, n)
157
+ }
158
+
159
+ /// [`int_from_i64`] past a Fixnum, out of line: the Fixnum path, inlined
160
+ /// where an Integer is made, then holds no protected call.
161
+ #[cold]
162
+ #[inline(never)]
163
+ fn bignum_from_i64(_: &Ruby, n: i64) -> Result<Integer, Error> {
164
+ let v = call_allocating(|inside| unsafe { nupur_sys::raising::rb_ll2inum(inside, n) })?;
165
+ typed(v, Integer::from_value, "a C call made no Integer")
166
+ }
167
+
168
+ /// `rb_ull2inum`: as [`int_from_i64`].
169
+ #[inline]
170
+ pub(crate) fn int_from_u64(ruby: &Ruby, n: u64) -> Result<Integer, Error> {
171
+ /* As `int_from_i64`. */
172
+ if let Some(v) = ruby.sys().posfixnum(n) {
173
+ return Ok(Integer::from_known(Value::from_sys(v)));
174
+ }
175
+ bignum_from_u64(ruby, n)
176
+ }
177
+
178
+ /// [`int_from_u64`] past a Fixnum, out of line as [`bignum_from_i64`].
179
+ #[cold]
180
+ #[inline(never)]
181
+ fn bignum_from_u64(_: &Ruby, n: u64) -> Result<Integer, Error> {
182
+ let v = call_allocating(|inside| unsafe { nupur_sys::raising::rb_ull2inum(inside, n) })?;
183
+ typed(v, Integer::from_value, "a C call made no Integer")
184
+ }
185
+
186
+ /// `rb_float_new`: raises `NoMemoryError` for a value that is not a flonum.
187
+ #[inline]
188
+ pub(crate) fn float_new(ruby: &Ruby, f: f64) -> Result<Float, Error> {
189
+ /* A flonum is the value's own bits, as a Fixnum is: no allocation,
190
+ * nothing to raise, no protected call. */
191
+ if let Some(v) = ruby.sys().flonum(f) {
192
+ return Ok(Float::from_known(Value::from_sys(v)));
193
+ }
194
+ heap_float(ruby, f)
195
+ }
196
+
197
+ /// [`float_new`] past a flonum, out of line as [`bignum_from_i64`].
198
+ #[cold]
199
+ #[inline(never)]
200
+ fn heap_float(_: &Ruby, f: f64) -> Result<Float, Error> {
201
+ let v = call_allocating(|inside| unsafe { nupur_sys::raising::rb_float_new(inside, f) })?;
202
+ typed(v, Float::from_value, "a C call made no Float")
203
+ }
204
+
205
+ /// `rb_enumeratorize_with_size` with no arguments and no size: raises
206
+ /// `NoMemoryError`.
207
+ #[inline]
208
+ pub(crate) fn enumeratorize(obj: Value, meth: Symbol) -> Result<Value, Error> {
209
+ let (o, m) = (obj.as_sys(), meth.as_sys());
210
+ let v = call_allocating(|inside| unsafe {
211
+ nupur_sys::raising::rb_enumeratorize_with_size(inside, o, m, 0, core::ptr::null(), None)
212
+ })?;
213
+ typed(v, Some, "a C call made no value")
214
+ }
215
+
216
+ /// `rb_hash_lookup2` at `key`, `Ok(None)` for no entry. The key must be a
217
+ /// Symbol or a plain String, hashed and compared in C - any other is a
218
+ /// `TypeError` here, as [`hash_aset`]'s, since its own `#hash` would run - but
219
+ /// a key already IN the Hash may be any object, and one whose hash collides
220
+ /// is compared by calling `key.eql?(stored)` (`rb_any_cmp`, then `rb_eql`):
221
+ /// Symbol's or String's own, the caller's Ruby where a program redefined it,
222
+ /// which can raise or `throw`. That comes back as `Err`,
223
+ /// to be passed on: read as "no entry", the exception would be lost and the
224
+ /// keyword taken as absent. In the raise sweep's set (`call_allocating`), so
225
+ /// that path is run.
226
+ pub(crate) fn hash_lookup(h: RHash, key: Value) -> Result<Option<Value>, Error> {
227
+ plain_key_or_refuse(key)?;
228
+ let (h, key) = (h.as_sys(), key.as_sys());
229
+ let v = call_allocating(|inside| unsafe {
230
+ nupur_sys::raising::rb_hash_lookup2(inside, h, key, inside.ruby().qundef())
231
+ })?;
232
+ /* A value of the Hash's, or `Qundef`, which is not handed out. */
233
+ Ok((!v.is_undef()).then(|| Value::from_sys(v)))
234
+ }
235
+
236
+ /// `rb_range_values`: a Range's ends and whether it excludes its end. For a
237
+ /// Range (or a subclass's instance) the fields are read, and no Ruby runs.
238
+ pub(crate) fn range_values(r: Range) -> Result<(Value, Value, bool), Error> {
239
+ let r = r.as_sys();
240
+ let nil = r.ruby().qnil();
241
+ let (mut beg, mut end, mut excl): (_, _, c_int) = (nil, nil, 0);
242
+ let (pb, pe, px) = (
243
+ core::ptr::addr_of_mut!(beg),
244
+ core::ptr::addr_of_mut!(end),
245
+ core::ptr::addr_of_mut!(excl),
246
+ );
247
+ call(|inside| unsafe { nupur_sys::raising::rb_range_values(inside, r, pb, pe, px) })?;
248
+ /* The Range's own ends, live while it is. */
249
+ Ok((Value::from_sys(beg), Value::from_sys(end), excl != 0))
250
+ }
251
+
252
+ /// `rb_big2ll`: raises `RangeError` past an `i64`. For a Bignum only - the C
253
+ /// reads a Bignum's header unchecked - so it has one caller,
254
+ /// `Integer::to_i64`, which answers a Fixnum itself.
255
+ pub(crate) fn big2ll(n: Integer) -> Result<i64, Error> {
256
+ let n = n.as_sys();
257
+ Ok(i64::from(call(|inside| unsafe {
258
+ nupur_sys::raising::rb_big2ll(inside, n)
259
+ })?))
260
+ }
261
+
262
+ /// `rb_big2ull`: raises `RangeError` past a `u64`. For a non-negative Bignum
263
+ /// only (a negative one would wrap), so it has one caller,
264
+ /// `Integer::to_u64`, which refuses a negative value and answers a Fixnum
265
+ /// itself.
266
+ pub(crate) fn big2ull(n: Integer) -> Result<u64, Error> {
267
+ let n = n.as_sys();
268
+ Ok(u64::from(call(|inside| unsafe {
269
+ nupur_sys::raising::rb_big2ull(inside, n)
270
+ })?))
271
+ }
272
+
273
+ /// `rb_big2str(n, 10)`: a Bignum's decimal digits, as a new US-ASCII String.
274
+ /// Raises `NoMemoryError`. For a Bignum only (the C reads a Bignum's digits
275
+ /// unchecked), so it has one caller, `Integer::to_decimal`,
276
+ /// which writes a Fixnum itself.
277
+ pub(crate) fn big2str(n: Integer) -> Result<RString, Error> {
278
+ let n = n.as_sys();
279
+ let v = call_allocating(|inside| unsafe { nupur_sys::raising::rb_big2str(inside, n, 10) })?;
280
+ typed(v, RString::from_value, "a C call made no String")
281
+ }
282
+
283
+ /// `rb_str_to_inum(s, 10, 1)`: the Integer `s`'s decimal digits spell, which
284
+ /// may be a Bignum. Raises `ArgumentError` for anything but digits and
285
+ /// `NoMemoryError`. Its one caller, `build::int_from_decimal`, checks the
286
+ /// digits first and hands a String of its own, so no caller's String (whose
287
+ /// encoding or subclass the C would read) reaches it.
288
+ pub(crate) fn str_to_inum(s: RString) -> Result<Integer, Error> {
289
+ let s = s.as_sys();
290
+ let v =
291
+ call_allocating(|inside| unsafe { nupur_sys::raising::rb_str_to_inum(inside, s, 10, 1) })?;
292
+ typed(v, Integer::from_value, "a C call made no Integer")
293
+ }