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,175 @@
1
+ //! Ruby values written into a message, without a call: `#inspect` and
2
+ //! `#to_s` would be the caller's Ruby code, and a message is made on an
3
+ //! error path, where nothing may raise.
4
+ //!
5
+ //! A String's bytes are written from a copy (`Head`), never from a slice
6
+ //! of the String: a `Display` writes into whatever `fmt::Write` its caller
7
+ //! chose, which this module cannot hold to running no Ruby.
8
+
9
+ #![forbid(unsafe_code)]
10
+
11
+ use crate::msg::{floor_char_boundary, Lossy, Quoted, MSG_MAX};
12
+ use crate::rb::{prelude::*, Error, RString, Ruby, Value};
13
+
14
+ /// A lookup made only to word a message - a Symbol's name, a class's name,
15
+ /// an ID - with `$!` kept: its value, or `None` for the message to write a
16
+ /// fallback in its place.
17
+ ///
18
+ /// The one place the layer drops a Ruby error, and why that is safe: these
19
+ /// calls run no Ruby code and deliver no interrupt, so what can fail is an
20
+ /// allocation (`NoMemoryError`), which a message answers with a fallback, or
21
+ /// the exit already pending (a `throw`, a `break`, a kill), which every
22
+ /// protected call answers while one is and the trampoline resumes however
23
+ /// the method ends. Anything that runs Ruby goes through `?` or
24
+ /// [`Error::rescue`] instead.
25
+ #[cfg_attr(
26
+ dylint_lib = "nupur_lints",
27
+ allow(
28
+ discarded_ruby_error,
29
+ reason = "a message's lookup: an allocation failure is written as a fallback, and a pending exit is the trampoline's"
30
+ )
31
+ )]
32
+ pub(crate) fn for_message<T>(f: impl FnOnce() -> Result<T, Error>) -> Option<T> {
33
+ crate::raw::keeping_errinfo(f).ok()
34
+ }
35
+
36
+ /// Room for a message's worth of a String and the start of the character
37
+ /// that runs past it, so the cut can be put at a character boundary.
38
+ const HEAD_ROOM: usize = MSG_MAX + 4;
39
+
40
+ /// The first [`MSG_MAX`] bytes of a String, copied onto the stack: all of a
41
+ /// message there is room for, since [`crate::msg::Msg`] keeps no more.
42
+ /// `cut` says the String went on, so a message says it was cut even where
43
+ /// the copy alone would fit.
44
+ struct Head {
45
+ buf: [u8; HEAD_ROOM],
46
+ len: usize,
47
+ cut: bool,
48
+ }
49
+
50
+ impl Head {
51
+ fn of(s: RString) -> Head {
52
+ let mut buf = [0u8; HEAD_ROOM];
53
+ /* Copied, and its length read, with nothing run between. */
54
+ let n = s.copy_to(0, &mut buf);
55
+ let cut = n > MSG_MAX || s.len() > n;
56
+ let len = if cut {
57
+ floor_char_boundary(buf.get(..n).unwrap_or_default(), MSG_MAX)
58
+ } else {
59
+ n
60
+ };
61
+ Head { buf, len, cut }
62
+ }
63
+
64
+ fn bytes(&self) -> &[u8] {
65
+ self.buf.get(..self.len).unwrap_or_default()
66
+ }
67
+
68
+ /// `...` after a cut String, as [`crate::msg::Msg`] ends a cut message.
69
+ fn mark_cut(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
70
+ if self.cut {
71
+ f.write_str("...")?;
72
+ }
73
+ Ok(())
74
+ }
75
+ }
76
+
77
+ /// `v` for an error message, written without calling it: a Symbol as
78
+ /// `:name`, a String quoted, anything else by its class (`#inspect` would be
79
+ /// the caller's Ruby).
80
+ pub struct Describe(pub Value);
81
+
82
+ impl core::fmt::Display for Describe {
83
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
84
+ let v = self.0;
85
+ if let Some(sym) = crate::rb::Symbol::from_value(v) {
86
+ /* A name that cannot be made is written by the class instead. */
87
+ if let Some(s) = for_message(|| crate::raw::sym2str(sym)) {
88
+ let head = Head::of(s);
89
+ write!(f, ":{}", Lossy(head.bytes()))?;
90
+ return head.mark_cut(f);
91
+ }
92
+ }
93
+ if let Some(s) = RString::from_value(v) {
94
+ let head = Head::of(s);
95
+ Quoted(head.bytes()).fmt(f)?;
96
+ return head.mark_cut(f);
97
+ }
98
+ if v.is_nil() {
99
+ return f.write_str("nil");
100
+ }
101
+ f.write_str("an instance of ")?;
102
+ v.write_classname(f)
103
+ }
104
+ }
105
+
106
+ /// `v` as text for a message, as Ruby's `to_s` would have it for the values a
107
+ /// message holds - a String's text, a Symbol's name - but without calling it
108
+ /// (`to_s` is the caller's Ruby); anything else as [`Describe`] has it.
109
+ pub struct AsText(pub Value);
110
+
111
+ impl core::fmt::Display for AsText {
112
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
113
+ let v = self.0;
114
+ /* The String or the Symbol's name, read directly: `name_arg` would
115
+ * build (and format) a whole TypeError for any other value, only for
116
+ * it to be thrown away here. */
117
+ let text = match crate::rb::Symbol::from_value(v) {
118
+ Some(sym) => for_message(|| crate::raw::sym2str(sym)),
119
+ None => match RString::from_value(v) {
120
+ Some(s) => Some(s),
121
+ None => return Describe(v).fmt(f),
122
+ },
123
+ };
124
+ if let Some(s) = text {
125
+ let head = Head::of(s);
126
+ Lossy(head.bytes()).fmt(f)?;
127
+ return head.mark_cut(f);
128
+ }
129
+ Describe(v).fmt(f)
130
+ }
131
+ }
132
+
133
+ /// The class name of a value, for a message - "Object", "Hash", an
134
+ /// anonymous class's `#<Class:0x...>` - read without a call, as
135
+ /// `Describe` reads one.
136
+ pub struct ClassName(pub Value);
137
+
138
+ impl core::fmt::Display for ClassName {
139
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
140
+ self.0.write_classname(f)
141
+ }
142
+ }
143
+
144
+ /// The longest message kept: this runs on error paths to word another error,
145
+ /// and an exception's message is untrusted input.
146
+ const EXCEPTION_MESSAGE_MAX: usize = 255;
147
+
148
+ /// `exc`'s message, for wording another error with it: up to the first NUL,
149
+ /// at most `EXCEPTION_MESSAGE_MAX` bytes, invalid UTF-8 replaced. "error"
150
+ /// for a message that is not a String - this runs on error paths, so it must
151
+ /// not raise itself.
152
+ pub(crate) struct ExceptionText<'a>(pub &'a Ruby, pub Value);
153
+
154
+ impl core::fmt::Display for ExceptionText<'_> {
155
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
156
+ /* The message is the exception's `mesg`, read as an attribute: calling
157
+ * `#message` would run its class's Ruby. A message that is not a
158
+ * String is answered as "error". */
159
+ let Some(id) = for_message(|| crate::rb::HiddenId::intern(self.0, c"mesg")) else {
160
+ return f.write_str("error");
161
+ };
162
+ /* An attribute read: it runs no Ruby and raises nothing. */
163
+ let Some(r) = RString::from_value(crate::rb::object::ivar_get(self.1, id)) else {
164
+ return f.write_str("error");
165
+ };
166
+ let head = Head::of(r);
167
+ let bytes = head.bytes();
168
+ let n = bytes
169
+ .iter()
170
+ .position(|&b| b == 0)
171
+ .unwrap_or(bytes.len())
172
+ .min(EXCEPTION_MESSAGE_MAX);
173
+ Lossy(bytes.get(..n).unwrap_or_default()).fmt(f)
174
+ }
175
+ }
@@ -0,0 +1,240 @@
1
+ //! A Ruby encoding, as the layer reads and converts Strings by it.
2
+
3
+ #![allow(unsafe_code)]
4
+ #![allow(clippy::missing_safety_doc)]
5
+
6
+ use core::ffi::c_int;
7
+ use core::sync::atomic::{AtomicI32, Ordering};
8
+
9
+ use crate::rb::value::AsSys;
10
+ use crate::rb::{Error, RString};
11
+
12
+ /// A Ruby encoding - of a String, or resolved from a name or an `Encoding`.
13
+ ///
14
+ /// Opaque so callers never hold the raw `rb_encoding*`, and the one place the
15
+ /// "which encodings are already UTF-8 bytes" rules live. Ruby's encodings are
16
+ /// process-lifetime objects, so a value of this type stays valid.
17
+ #[derive(Clone, Copy, PartialEq, Eq)]
18
+ pub struct Encoding(*mut nupur_sys::rb_encoding);
19
+
20
+ /* The indices of Ruby's three builtin encodings - the ones whose text is read
21
+ * as UTF-8 bytes - asked once, at `Init_` ([`init`]), and only read after.
22
+ * Ruby keeps them as constants, but hides them from extensions
23
+ * (`ruby_preserved_encindex`), so they are asked rather than written here.
24
+ * They are the one way the layer tells these three encodings: by index, as
25
+ * a String's flags carry it, so an `Encoding` and a String are asked alike.
26
+ * -1 is no encoding's index: read before `init`, no test matches, which
27
+ * sends a String to Ruby's transcode - slower, never wrong. (No method runs
28
+ * before `Init_`.) */
29
+ static UTF8: AtomicI32 = AtomicI32::new(-1);
30
+ static USASCII: AtomicI32 = AtomicI32::new(-1);
31
+ static ASCII8BIT: AtomicI32 = AtomicI32::new(-1);
32
+
33
+ /// Whether `index` is the builtin encoding `builtin` holds the index of.
34
+ #[inline]
35
+ fn is_builtin(builtin: &AtomicI32, index: c_int) -> bool {
36
+ builtin.load(Ordering::Relaxed) == index
37
+ }
38
+
39
+ /// Ask Ruby the builtin encodings' indices, once: the first thing
40
+ /// `rb::method::run_init` does, before the extension's own `Init_` code.
41
+ pub(crate) fn init(ruby: &crate::rb::Ruby) {
42
+ let gvl = ruby.sys();
43
+ // SAFETY: at `Init_`; each returns a constant.
44
+ let (utf8, usascii, ascii8bit) = unsafe {
45
+ (
46
+ nupur_sys::non_raising::rb_utf8_encindex(gvl),
47
+ nupur_sys::non_raising::rb_usascii_encindex(gvl),
48
+ nupur_sys::non_raising::rb_ascii8bit_encindex(gvl),
49
+ )
50
+ };
51
+ UTF8.store(utf8, Ordering::Relaxed);
52
+ USASCII.store(usascii, Ordering::Relaxed);
53
+ ASCII8BIT.store(ascii8bit, Ordering::Relaxed);
54
+ }
55
+
56
+ /// Whether the encoding of index `index` is read as UTF-8 bytes with no
57
+ /// transcode: UTF-8, US-ASCII or ASCII-8BIT. The one definition of that set,
58
+ /// which [`Encoding::is_utf8_ascii_or_binary`] and a String's own
59
+ /// ([`RString::reads_as_utf8_bytes`](crate::rb::RString::reads_as_utf8_bytes))
60
+ /// both ask.
61
+ #[inline]
62
+ pub(crate) fn reads_as_utf8_index(index: c_int) -> bool {
63
+ [&UTF8, &USASCII, &ASCII8BIT]
64
+ .iter()
65
+ .any(|b| is_builtin(b, index))
66
+ }
67
+
68
+ /// Whether the encoding of index `index` is UTF-8.
69
+ #[inline]
70
+ pub(crate) fn is_utf8_index(index: c_int) -> bool {
71
+ is_builtin(&UTF8, index)
72
+ }
73
+
74
+ /// Whether the encoding of index `index` is ASCII-8BIT.
75
+ #[inline]
76
+ pub(crate) fn is_ascii8bit_index(index: c_int) -> bool {
77
+ is_builtin(&ASCII8BIT, index)
78
+ }
79
+
80
+ /// What a transcode ([`Encoding::encode`]) does with a byte sequence that is
81
+ /// invalid in the source, or a character the target has no form for.
82
+ #[derive(Clone, Copy, PartialEq, Eq, Debug)]
83
+ pub enum Unconvertible {
84
+ /// Raise Ruby's `EncodingError` (`InvalidByteSequenceError`,
85
+ /// `UndefinedConversionError`).
86
+ Raise,
87
+ /// Replace either with U+FFFD (or `?` where the target has none).
88
+ Replace,
89
+ /// Write a character the target has no form for as a hex character
90
+ /// reference (`&#x...;`); an invalid sequence still raises.
91
+ HexCharRef,
92
+ }
93
+
94
+ impl Unconvertible {
95
+ /// `rb_str_encode`'s flags for it.
96
+ fn ecflags(self) -> c_int {
97
+ use nupur_sys::ruby_econv_flag_type as f;
98
+ match self {
99
+ Unconvertible::Raise => 0,
100
+ Unconvertible::Replace => {
101
+ f::RUBY_ECONV_INVALID_REPLACE as c_int | f::RUBY_ECONV_UNDEF_REPLACE as c_int
102
+ }
103
+ Unconvertible::HexCharRef => f::RUBY_ECONV_UNDEF_HEX_CHARREF as c_int,
104
+ }
105
+ }
106
+ }
107
+
108
+ impl Encoding {
109
+ /// The encoding's name, as Ruby spells it.
110
+ pub fn name(self) -> &'static [u8] {
111
+ // SAFETY: a live encoding's name is a NUL-terminated C string that
112
+ // lives as long as the encoding, which is the process.
113
+ unsafe { core::ffi::CStr::from_ptr((*self.0).name) }.to_bytes()
114
+ }
115
+
116
+ /// The encoding `str` is tagged with.
117
+ pub fn of(str: RString) -> Encoding {
118
+ // SAFETY: a live String, by type; reading its tag runs no Ruby.
119
+ Encoding(unsafe { nupur_sys::non_raising::enc_get_of_string(str.as_sys()) })
120
+ }
121
+
122
+ /// UTF-8. Takes the token, as every C call of the layer that has no Ruby
123
+ /// value to show for the GVL does.
124
+ pub fn utf8(ruby: &crate::rb::Ruby) -> Encoding {
125
+ // SAFETY: Ruby's immutable global encoding.
126
+ Encoding(unsafe { nupur_sys::non_raising::rb_utf8_encoding(ruby.sys()) })
127
+ }
128
+
129
+ /// The encoding Ruby knows by `name`, or None for a name it does not
130
+ /// know - not an error. MAY AUTOLOAD the encoding, a Ruby allocation and so
131
+ /// a GC point: call it with no borrow of a String's bytes held.
132
+ ///
133
+ /// `rb_enc_find` wants a C string and the name is bytes, so the NUL is
134
+ /// added here. A name too long to fit, or holding a NUL, is not one Ruby
135
+ /// knows, so it reads as None rather than being truncated at the NUL. So
136
+ /// does a lookup Ruby refuses (`LoadError`, `ArgumentError`): the caller
137
+ /// then refuses the name as unknown, never reads with another.
138
+ ///
139
+ /// Any other `Err` is passed on: what reaches the autoload - a thread
140
+ /// kill, a `throw`, `NoMemoryError` - is not an answer about the name,
141
+ /// and read as one it would be lost (a kill's thread would run on).
142
+ pub fn find(ruby: &crate::rb::Ruby, name: &[u8]) -> Result<Option<Encoding>, crate::rb::Error> {
143
+ if name.is_empty() {
144
+ return Ok(None);
145
+ }
146
+ let Some(c) = crate::cname::CName::new(name) else {
147
+ return Ok(None);
148
+ };
149
+ use crate::rb::Builtin::{ArgumentError, LoadError};
150
+ match crate::raw::keeping_errinfo(|| crate::raw::enc_find(ruby, &c)) {
151
+ Ok(found) => Ok(found),
152
+ Err(e) => {
153
+ e.rescue(ruby, &[LoadError, ArgumentError])?;
154
+ Ok(None)
155
+ }
156
+ }
157
+ }
158
+
159
+ /// An encoding from Ruby's pointer to it.
160
+ ///
161
+ /// # Safety
162
+ /// `p` is one of Ruby's encodings (which live for the process).
163
+ pub(crate) unsafe fn from_raw(p: *mut nupur_sys::rb_encoding) -> Encoding {
164
+ Encoding(p)
165
+ }
166
+
167
+ /// The raw encoding, for a C call of the layer's that takes one.
168
+ pub(crate) fn as_raw(self) -> *mut nupur_sys::rb_encoding {
169
+ self.0
170
+ }
171
+
172
+ /// US-ASCII.
173
+ pub fn is_usascii(self) -> bool {
174
+ is_builtin(&USASCII, self.index())
175
+ }
176
+
177
+ /// ASCII-8BIT: bytes with no character encoding.
178
+ pub fn is_ascii8bit(self) -> bool {
179
+ is_builtin(&ASCII8BIT, self.index())
180
+ }
181
+
182
+ /// The encoding's index (`rb_enc_to_index`), as a String's flags carry
183
+ /// it.
184
+ fn index(self) -> c_int {
185
+ // SAFETY: one of Ruby's encodings, which live for the process; the
186
+ // read of its index field raises nothing.
187
+ unsafe { nupur_sys::non_raising::rb_enc_to_index(self.0) }
188
+ }
189
+
190
+ /// UTF-8 or US-ASCII: text in it is already UTF-8, character for
191
+ /// character. What a serialized String needs no transcoding into.
192
+ pub fn is_utf8_or_ascii(self) -> bool {
193
+ let index = self.index();
194
+ is_builtin(&UTF8, index) || is_builtin(&USASCII, index)
195
+ }
196
+
197
+ /// UTF-8, US-ASCII or ASCII-8BIT: an encoding whose text is read as
198
+ /// UTF-8 bytes with no transcode (ASCII-8BIT deliberately raw bytes).
199
+ /// Anything else is transcoded to UTF-8 first. How the bytes are then
200
+ /// checked is each reader's own: one repairs invalid UTF-8 to U+FFFD,
201
+ /// another refuses it.
202
+ ///
203
+ /// For an encoding that is not a String's - a declared one, a given one.
204
+ /// A String's own is [`RString::reads_as_utf8_bytes`](crate::rb::RString::reads_as_utf8_bytes),
205
+ /// which reads its flags rather than look its encoding up.
206
+ pub(crate) fn is_utf8_ascii_or_binary(self) -> bool {
207
+ reads_as_utf8_index(self.index())
208
+ }
209
+
210
+ /// A copy of `str` tagged with this encoding instead of its own: its
211
+ /// bytes read as this encoding's. Allocating, so a raise
212
+ /// (`NoMemoryError`, or `ArgumentError` from the tag) is returned.
213
+ pub(crate) fn relabel(self, str: RString) -> Result<RString, Error> {
214
+ /* The copy is on this frame, where the conservative scan sees it. */
215
+ let copy = crate::raw::str_dup(str)?;
216
+ crate::raw::enc_associate(copy, self)
217
+ }
218
+
219
+ /// `str` transcoded to this encoding by Ruby (`rb_str_encode`), `on`
220
+ /// deciding what an unconvertible sequence becomes. Raises - no
221
+ /// converter at all, or a sequence `on` leaves to raise - and the raise
222
+ /// comes back as `Err`.
223
+ pub fn encode(self, str: RString, on: Unconvertible) -> Result<RString, Error> {
224
+ crate::raw::str_encode(str, self, on.ecflags())
225
+ }
226
+ }
227
+
228
+ /// The encoding `v` names (an `Encoding`, or a String or Symbol naming one),
229
+ /// or the error Ruby's own lookup raises: `ArgumentError` for an unknown
230
+ /// name. Anything else is a `TypeError` before the lookup, which would run
231
+ /// its `to_str`.
232
+ pub fn to_encoding(ruby: &crate::rb::Ruby, v: crate::rb::Value) -> Result<Encoding, Error> {
233
+ use crate::rb::ReprValue;
234
+ let v = if v.is_kind_of(ruby.class_encoding()) {
235
+ v
236
+ } else {
237
+ crate::args::name_arg(v)?.as_value()
238
+ };
239
+ crate::raw::to_encoding(ruby, v)
240
+ }
@@ -0,0 +1,181 @@
1
+ //! Releasing the GVL around Ruby-free work.
2
+ //!
3
+ //! `rb_thread_call_without_gvl` is a raw Ruby C call, and the body it runs is
4
+ //! forbidden from touching Ruby state - not a `Value`, not a `Ruby` handle, not
5
+ //! anything Ruby owns. There is no way to check that, so it is the caller's
6
+ //! contract, stated on [`without_gvl`].
7
+ //!
8
+ //! `without_gvl` requires a `Send` body, which keeps a `Ruby` handle - and
9
+ //! anything else bound to the thread holding the GVL - out of it.
10
+
11
+ #![allow(unsafe_code)]
12
+
13
+ use core::ffi::c_void;
14
+
15
+ /// Run `f` with the GVL released, and return its result - or the exception a
16
+ /// pending interrupt raised instead.
17
+ ///
18
+ /// # Contract
19
+ /// `f` must touch no Ruby state and allocate no Ruby object. It must also be
20
+ /// `Send`, which is what keeps a `Ruby` handle - which is not - out of it. Its
21
+ /// argument is
22
+ /// typically a slice copied out of Ruby before the call, as a parse of a
23
+ /// copied source does.
24
+ ///
25
+ /// A panic inside `f` is CAUGHT and re-raised here, after the GVL is back. It
26
+ /// has to be: `f` runs below the GVL-releasing call, a C frame, and unwinding
27
+ /// into one aborts the process. A body may be a whole parser, so it can be the single
28
+ /// largest piece of Rust that runs under a callback - see [`crate::caught`].
29
+ ///
30
+ /// # Interrupts
31
+ /// `rb_thread_call_without_gvl` checks for pending interrupts before and after
32
+ /// the body and RAISES there - a longjmp over this frame and its callers, which
33
+ /// skips their destructors: whatever the body made and its callers own leaked
34
+ /// on every `Timeout`/`Thread#raise` that landed meanwhile (in Makiri, 30
35
+ /// interrupted 5 MB parses grew the process by ~900 MB). The `2` variant never
36
+ /// raises: an interrupt pending at the start makes it return without running
37
+ /// the body, and it does not check afterwards. So:
38
+ ///
39
+ /// - The body ran: its result is returned. An interrupt that arrived meanwhile
40
+ /// is delivered by Ruby's next check, after the result is a Ruby object that
41
+ /// the GC owns - nothing leaks.
42
+ /// - It did not run: the interrupt is delivered HERE, under `protect`, so it
43
+ /// comes back as `Err` through ordinary Rust returns. If delivering it raised
44
+ /// nothing (a trap handler that returned), the call is simply made again.
45
+ ///
46
+ /// A non-local exit already pending (`raw`'s `PENDING_JUMP`) is answered
47
+ /// at once, the body not run: releasing the GVL would let this thread run
48
+ /// interrupts - a trap handler's Ruby among them - whose raises overwrite the
49
+ /// error info Ruby resumes the exit from, and could move the Ruby thread to
50
+ /// another native thread, which does not see it pending.
51
+ pub fn without_gvl<F: FnOnce() -> R + Send, R>(
52
+ ruby: &crate::rb::Ruby,
53
+ f: F,
54
+ ) -> Result<R, crate::rb::Error> {
55
+ // SAFETY: no unblock function: Ruby's default.
56
+ unsafe { release(ruby, f, None, core::ptr::null_mut()) }
57
+ }
58
+
59
+ /// What a body run by [`without_gvl_cancellable`] asks to learn whether
60
+ /// Ruby wants the thread back: `Thread#kill`, `Thread#raise`, a `Timeout`,
61
+ /// a signal, the process exiting.
62
+ pub struct Cancel(core::sync::atomic::AtomicBool);
63
+
64
+ impl Cancel {
65
+ /// Whether Ruby has asked the body to stop. A load of one atomic, cheap
66
+ /// enough for a loop to ask every few thousand steps.
67
+ #[inline]
68
+ pub fn requested(&self) -> bool {
69
+ self.0.load(core::sync::atomic::Ordering::Relaxed)
70
+ }
71
+ }
72
+
73
+ /// [`without_gvl`] for a body that can stop part-way: Ruby's request to
74
+ /// have the thread back sets the [`Cancel`] the body is lent, and the body
75
+ /// asks it as it goes and returns early when it is set - with whatever
76
+ /// answer it gives for "stopped" (an `Err` of its own, say). Without one,
77
+ /// [`without_gvl`]'s body runs to its end before an interrupt takes effect,
78
+ /// however long that is.
79
+ ///
80
+ /// Once the body has returned, a request that came is delivered here, as
81
+ /// [`without_gvl`] delivers one that came first: the exception is the
82
+ /// `Err`. Should delivering it raise nothing (a trap handler that
83
+ /// returned), the body's own answer is returned.
84
+ pub fn without_gvl_cancellable<F: FnOnce(&Cancel) -> R + Send, R>(
85
+ ruby: &crate::rb::Ruby,
86
+ f: F,
87
+ ) -> Result<R, crate::rb::Error> {
88
+ unsafe extern "C" fn unblock(p: *mut c_void) {
89
+ crate::no_unwind::must_not_unwind::<crate::no_unwind::GvlUnblock, _>(|| {
90
+ // SAFETY: `p` is the `Cancel` on `without_gvl_cancellable`'s frame,
91
+ // which outlives the blocking region Ruby calls this inside.
92
+ let cancel = unsafe { &*(p as *const Cancel) };
93
+ cancel.0.store(true, core::sync::atomic::Ordering::Relaxed);
94
+ });
95
+ }
96
+ let cancel = Cancel(core::sync::atomic::AtomicBool::new(false));
97
+ let data = &cancel as *const Cancel as *mut c_void;
98
+ // SAFETY: `unblock` only stores to the atomic behind `data`, the `Cancel`
99
+ // on this frame, which lives past the call; it runs nothing else.
100
+ let out = unsafe { release(ruby, || f(&cancel), Some(unblock), data) }?;
101
+ if cancel.requested() {
102
+ crate::raw::thread_check_ints(ruby)?;
103
+ }
104
+ Ok(out)
105
+ }
106
+
107
+ /// [`without_gvl`] with `ubf` as the unblock function, given `ubf_data`.
108
+ ///
109
+ /// # Safety
110
+ ///
111
+ /// `ubf` (when given) is safe to call from another thread, with `ubf_data`,
112
+ /// at any time while the body runs, and unwinds into no C frame.
113
+ unsafe fn release<F: FnOnce() -> R + Send, R>(
114
+ ruby: &crate::rb::Ruby,
115
+ f: F,
116
+ ubf: Option<unsafe extern "C" fn(*mut c_void)>,
117
+ ubf_data: *mut c_void,
118
+ ) -> Result<R, crate::rb::Error> {
119
+ if let Some(exit) = crate::raw::pending_exit() {
120
+ return Err(exit);
121
+ }
122
+ struct Slot<F, R> {
123
+ f: Option<F>,
124
+ out: Option<R>,
125
+ panic: crate::caught::PanicLatch,
126
+ }
127
+
128
+ unsafe extern "C" fn run<F: FnOnce() -> R, R>(p: *mut c_void) -> *mut c_void {
129
+ crate::no_unwind::must_not_unwind::<crate::no_unwind::GvlBody, _>(|| {
130
+ // SAFETY: `p` is the `&mut Slot` passed below, live for this call.
131
+ let slot = unsafe { &mut *(p as *mut Slot<F, R>) };
132
+ /* Never a panic here: this frame is Ruby's C, outside the guard
133
+ * below, so one would abort the process. The body is present on
134
+ * the first run; if it somehow were not, `out` stays None and the
135
+ * caller reports that under the GVL. */
136
+ let Some(f) = slot.f.take() else {
137
+ return core::ptr::null_mut();
138
+ };
139
+ /* Catch here rather than let the panic reach Ruby's C frame: `out`
140
+ * simply stays None, and the caller re-raises once the GVL is
141
+ * back. */
142
+ let out = &mut slot.out;
143
+ slot.panic.guard((), || *out = Some(f()));
144
+ core::ptr::null_mut()
145
+ })
146
+ }
147
+
148
+ let mut slot = Slot {
149
+ f: Some(f),
150
+ out: None,
151
+ panic: crate::caught::PanicLatch::new(),
152
+ };
153
+ loop {
154
+ // SAFETY: the trampoline runs `f` at most once and returns; the unblock
155
+ // function is the caller's, by this function's contract, or Ruby's
156
+ // default (`None`). This variant raises nothing (see above), so no
157
+ // Rust frame is jumped.
158
+ unsafe {
159
+ nupur_sys::non_raising::rb_thread_call_without_gvl2(
160
+ ruby.sys(),
161
+ Some(run::<F, R>),
162
+ &mut slot as *mut Slot<F, R> as *mut c_void,
163
+ ubf,
164
+ ubf_data,
165
+ );
166
+ }
167
+ /* Back under the GVL and out of the C frame: safe to unwind from here. */
168
+ slot.panic.resume();
169
+ if let Some(out) = slot.out.take() {
170
+ return Ok(out);
171
+ }
172
+ if slot.f.is_none() {
173
+ /* It ran and neither answered nor panicked - which `run` cannot do. */
174
+ return Err(crate::rb::error::internal_error(
175
+ "the GVL-released body ran without a result",
176
+ ));
177
+ }
178
+ /* An interrupt was pending, so the body never started: deliver it. */
179
+ crate::raw::thread_check_ints(ruby)?;
180
+ }
181
+ }
@@ -0,0 +1,52 @@
1
+ //! Reading a Hash's pairs: the one walk of a Hash, which latches a panic
2
+ //! rather than let it unwind into `rb_hash_foreach`'s C frames.
3
+
4
+ #![forbid(unsafe_code)]
5
+
6
+ use crate::rb::{Error, RArray, RHash, Ruby, Value};
7
+
8
+ /// `h`'s pairs, each handed to `f` in turn; the first `Err` stops the walk
9
+ /// and is returned.
10
+ ///
11
+ /// Over `crate::raw::hash_foreach`, which latches a panic in `f` rather
12
+ /// than let it unwind into `rb_hash_foreach`'s C frames, and resumes it once
13
+ /// they are gone, where the method's trampoline makes it the internal error.
14
+ /// `f`'s own error is kept here rather than raised from inside the walk.
15
+ /// `RHash` has no walk of its own, so this is the one way an extension walks
16
+ /// a Hash.
17
+ pub fn hash_foreach(
18
+ h: RHash,
19
+ mut f: impl FnMut(Value, Value) -> Result<(), Error>,
20
+ ) -> Result<(), Error> {
21
+ let mut failed: Option<Error> = None;
22
+ crate::raw::hash_foreach(h, &mut |k, v| match f(k, v) {
23
+ Ok(()) => true,
24
+ Err(e) => {
25
+ failed = Some(e);
26
+ false
27
+ }
28
+ })?;
29
+ failed.map_or(Ok(()), Err)
30
+ }
31
+
32
+ /// `h`'s key-value pairs, copied out before any of them is used.
33
+ ///
34
+ /// Read from the Hash itself, not through a `to_a` a subclass can redefine (a
35
+ /// non-pair tripped an `expect`), and handed out only after the walk, so a
36
+ /// caller's use of them - which allocates - is outside the iteration. The copy runs no Ruby code of the caller's; the
37
+ /// Array holding it is a Ruby object on this frame, so the GC sees it.
38
+ pub fn each_pair(
39
+ ruby: &Ruby,
40
+ h: RHash,
41
+ mut f: impl FnMut(Value, Value) -> Result<(), Error>,
42
+ ) -> Result<(), Error> {
43
+ let pairs: RArray = crate::build::ary(ruby, h.len() * 2)?;
44
+ hash_foreach(h, |k, v| {
45
+ crate::build::push(pairs, k)?;
46
+ crate::build::push(pairs, v)
47
+ })?;
48
+ for i in (0..pairs.len()).step_by(2) {
49
+ f(pairs.entry(i), pairs.entry(i + 1))?;
50
+ }
51
+ Ok(())
52
+ }
@@ -0,0 +1,20 @@
1
+ //! The hooks an extension's OOM sweep installs, both at once: the raise
2
+ //! half (an allocating call of `crate::raw` raises `NoMemoryError`) and the
3
+ //! allocation half (a checked copy's heap buffer, [`crate::utf8_copy`],
4
+ //! fails). One call taking both, so an extension cannot arm one and leave the
5
+ //! other half of the sweep failing nothing.
6
+
7
+ /// What the sweep answers, call by call.
8
+ pub struct Injectors {
9
+ /// Whether the next allocating C call raises.
10
+ pub raise: fn() -> bool,
11
+ /// Whether the next fallible heap allocation fails.
12
+ pub alloc: fn() -> bool,
13
+ }
14
+
15
+ /// Install both answers, once, before any method runs (the extension's
16
+ /// `Init_`); a second installation is ignored.
17
+ pub fn install(i: Injectors) {
18
+ crate::raw::set_raise_injector(i.raise);
19
+ crate::utf8_copy::set_alloc_injector(i.alloc);
20
+ }