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,280 @@
1
+ //! `nupur`: a Ruby binding layer for an extension - values, exceptions,
2
+ //! method trampolines, TypedData, the GVL, and every C call that can raise.
3
+ //! It reaches Ruby's C only through `nupur_sys` (`sys/`), the one crate that
4
+ //! depends on rb-sys, whose wrappers each take a proof - of the protection
5
+ //! for a call that can raise, of the GVL for any other.
6
+ //!
7
+ //! It knows nothing of the extension it serves - a crate of its own, which
8
+ //! does not depend on the extension - and what it needs of the extension
9
+ //! (the exception a broken invariant raises, the OOM sweep's hooks) is
10
+ //! registered at `Init_` ([`rb::error::INTERNAL_ERROR`],
11
+ //! `inject::install`). Every `unsafe` the extension needs to talk to
12
+ //! Ruby is here or in `nupur_sys`, each with its contract stated. The crate
13
+ //! denies `unsafe_code`, and the files that need it carry an `allow` each.
14
+ //!
15
+ //! # What the layer guarantees
16
+ //!
17
+ //! - **No raise skips Rust's cleanup.** Every C call that can raise is a
18
+ //! wrapper in `nupur_sys::raising` that takes a `&Protected`. Only
19
+ //! `rb_protect`'s thunk makes one, and lends it to the closure that
20
+ //! `raw::call` runs, so the call runs under `rb_protect` by its type and
21
+ //! its raise comes back as `Err`. Nupur has no other way to call one: it
22
+ //! does not depend on rb-sys, and `nupur_sys` re-exports no C function.
23
+ //! The raises outside it cross frames that own nothing: a trampoline's
24
+ //! ([`rb::method::finish`], `run_init`), and `gc_mark_in_dmark`'s
25
+ //! `NoMemoryError`, as in any C extension's mark function.
26
+ //! - **No panic reaches C.** A trampoline catches a panic and raises the
27
+ //! internal error in its place; a callback C runs latches one
28
+ //! ([`caught::PanicLatch`]) for its caller to resume. What must not unwind
29
+ //! (an `extern "C"` function, a `Drop` the GC runs) is a [`no_unwind`]
30
+ //! site, which a release build with `--cfg nupur_no_unwind` proves.
31
+ //! - **The GVL is a type.** A call of Ruby's C that needs the GVL takes a
32
+ //! proof that it is held: the Ruby value it is about
33
+ //! (`nupur_sys::value::Value`, which an [`rb::Value`] holds), or, where it
34
+ //! has none, the token (`nupur_sys::value::Ruby`, which an [`rb::Ruby`]
35
+ //! holds). Both are `!Send` and `!Sync`, so neither enters a body run with
36
+ //! the GVL released. A value is made only inside `nupur_sys`, from what a
37
+ //! C call returned or Ruby passed in. A token is made only by
38
+ //! `rb::method`'s private `entry_token`, which only the two entries Ruby
39
+ //! calls use: a method's trampoline and [`rb::method::run_init`].
40
+ //!
41
+ //! An [`rb::Value`] lends no [`rb::Ruby`], so a function takes `&Ruby`
42
+ //! when it reads something no argument proves - a C global, the running
43
+ //! method's frame, an `Opaque` - even if it holds a value too. The
44
+ //! few calls of Ruby's C that take no proof need no GVL (whether this is a
45
+ //! Ruby thread, an encoding's index) or run in a GC callback, whose
46
+ //! contract is the proof (`gc_mark_in_dmark`).
47
+ //! - **No Ruby value is held as an integer.** `nupur_sys` re-exports no
48
+ //! `VALUE`, nor any type whose definition holds one, and keeps the
49
+ //! conversions between a value and its word to itself. So nothing here
50
+ //! holds a Ruby value as a `u64`, which a lint, or a reader, could not tell
51
+ //! from a number.
52
+ //! - **A wrapped object's values are its slots** ([`typed`]): each a
53
+ //! `nupur_sys::value::Root`, marked by the layer's mark callback and read
54
+ //! back as a value only under a contract; a payload holds none. Memory the
55
+ //! object reported to the GC is given back by its free callback. A wrapped
56
+ //! object is made only of a [`rb::DataClass`], a class defined without an
57
+ //! allocator, so Ruby cannot make one with no payload.
58
+ //! - **A String is read by copying** ([`string`]): no slice of one is handed
59
+ //! out. Read as text ([`string::read_utf8`]), it is a copy checked to be
60
+ //! UTF-8 by std's validator over the copy itself ([`utf8_copy`]), never by
61
+ //! the String's cached coderange, which another C extension could leave
62
+ //! wrong.
63
+ //! - **A C integer is converted in one place** (`int`, `nupur_sys::int`): a
64
+ //! `long` is 32 bits on Windows, and the conversions are written once over
65
+ //! either width, tested at both and proved at both (`verus/int.rs`);
66
+ //! everything else converts with `From` / `TryFrom` and names no `long`.
67
+ //! - **A non-local exit is resumed as it was.** While a `break` or `throw`
68
+ //! a protected call caught is on its way to the trampoline, no protected
69
+ //! call runs C, so the thread's error info Ruby resumes it from is left
70
+ //! alone.
71
+ //! - **An object is held while its data is borrowed through a handle.**
72
+ //! A payload is reached only through a [`typed::Typed`]: from
73
+ //! `TypedType::check` for a value Ruby gave, `TypedType::known` for one
74
+ //! whose type is established, `TypedType::wrap` for an object just made.
75
+ //! It lends the data and keeps the object where the GC sees it until the
76
+ //! last borrow is over, wherever the object came from. `wrap_hidden` lends
77
+ //! it to its `fill` the same way, and hands the object out only once it is
78
+ //! complete and shown.
79
+ //! - **Two Ractors may run the layer at once.** Each runs its methods under
80
+ //! its own GVL, so nothing of the layer's is shared but what any Ractor
81
+ //! may read: a static keeps only a [`rb::Shareable`] value (a class or a
82
+ //! module), a pending exit is the native thread's own, and a wrapped
83
+ //! object never leaves its Ractor - its class, having no allocator,
84
+ //! cannot be copied or moved to another, and its type is not one Ruby may
85
+ //! make shareable - unless the type is declared shareable
86
+ //! ([`typed::TypedType::shareable`]): then its payload is `Sync` by the
87
+ //! constructor's bound, and the object is frozen and made shareable, with
88
+ //! what its slots reach, as it is made. An extension opts in at `Init_`
89
+ //! ([`rb::method::declare_ractor_safe`]).
90
+ //!
91
+ //! Most of these are types and dependencies. What they cannot state rests on
92
+ //! checks of the code: in Makiri `rake dylint` (`lints/nupur_lints`, which
93
+ //! names only `nupur::` and `nupur_sys::` paths, so another extension runs
94
+ //! them over itself, telling them of itself in its `dylint.toml`), `rake no_unwind`
95
+ //! and `rake unsafe:boundaries`. A copy of this layer elsewhere needs its
96
+ //! own:
97
+ //!
98
+ //! - which C functions can raise, and so which wrapper module each belongs
99
+ //! in: a table held to a survey of Ruby's C API
100
+ //! (`script/check_non_raising.rb`). `raising_call_outside_protect` and
101
+ //! `unraising_call_in_raw` apply it inside `nupur_sys`, the one crate that
102
+ //! can name rb-sys, and to `raw`'s protected calls;
103
+ //! - a safe function that calls Ruby's C inside `nupur_sys`, or one of
104
+ //! `nupur_sys`'s `unsafe fn`s here, holds a proof of the GVL -
105
+ //! `ffi_without_gvl_proof`;
106
+ //! - every `extern "C"` function and GC-run `Drop` is a [`no_unwind`] site -
107
+ //! `unguarded_no_unwind_site`, and `rake no_unwind`'s proof of each;
108
+ //! - no Ruby error is dropped, nor a `nupur_sys::protect::Caught` -
109
+ //! `discarded_ruby_error`;
110
+ //! - no C `long` is cast outside `int` - `c_integer_outside_int`;
111
+ //! - each file's count of `unsafe` is pinned - `rake unsafe:boundaries`.
112
+ //!
113
+ //! `nupur_sys`'s compile-fail doctests show that its tokens and values
114
+ //! cannot be made outside it; only nightly's rustdoc checks the error each
115
+ //! names (`rake rust:compile_fail`).
116
+ //!
117
+ //! Its behaviour is checked without Makiri too: `test/ext` is an extension
118
+ //! of a few methods over the layer alone, and `test/spec` the specs that load
119
+ //! it (`rake nupur:spec`) - a panic in a method, below the GVL release and in
120
+ //! a Hash walk, a block's exits, a slot under collection and compaction, a
121
+ //! checked String read and its `$!`.
122
+ //!
123
+ //! # What the extension must uphold
124
+ //!
125
+ //! The types do not carry these; a crate using the layer keeps them, by
126
+ //! review or by lints. Each says what checks it in Makiri, which a crate
127
+ //! that copies this layer has to supply in its own way:
128
+ //!
129
+ //! - **A Ruby value stays where the GC's stack scan sees it.** A [`rb::Value`]
130
+ //! (and every handle over one, [`typed::Typed`] included) is `!Send`, and
131
+ //! a `Value` is `Copy` (a `Typed`, which holds its object, is not): on the
132
+ //! stack it is kept alive and in place, but in a `Vec`, a `Box`, a
133
+ //! `static`, a thread-local or a payload's field it is not, and is freed
134
+ //! or moved while still held. Keep such values on the stack, in a Ruby
135
+ //! Array, in a wrapped object's slots, or in an [`rb::Opaque`] /
136
+ //! [`rb::RbConst`]. No type can refuse a value in a `Vec`. Checked by
137
+ //! `ruby_value_on_heap`, which reads the types of bindings, parameters,
138
+ //! results, fields, statics and every expression - so a temporary handed
139
+ //! straight to a call (`f(vec![v])`) too - and counts `nupur_sys`'s
140
+ //! `Value` and `Root` as Ruby values. Beyond it: a value behind
141
+ //! `dyn Trait` once coerced, and a generic body for the type it is called
142
+ //! with.
143
+ //! - **A payload's handle is not `mem::forget`ed.** A payload is borrowed
144
+ //! only through a [`typed::Typed`] (`check`, `known`, `wrap`), whose drop
145
+ //! is what holds the object past the last borrow; there is no way from a
146
+ //! bare `Value` to a `&T`. Checked by `forgotten_handle`; a type check
147
+ //! that borrows nothing is `TypedType::ensure`.
148
+ //! - **A GVL-released body runs no Ruby.** [`gvl::without_gvl`]'s `Send`
149
+ //! bound keeps a token and a value out of it, but not a call of a layer
150
+ //! function that needs neither (making an [`rb::Error`], say) - harmless
151
+ //! today, yet not a guarantee. Checked by `ruby_in_gvl_released_body`.
152
+ //! - **Nothing runs the caller's Ruby unasked** - a `to_s`, a block, a
153
+ //! method call. Checked by `runs_callers_ruby`, with each sanctioned call
154
+ //! an `allow` stating why. An extension that asks calls through
155
+ //! [`rb::call`], and holds nothing across the call that the callee could
156
+ //! invalidate: no payload borrow beyond a `Cell`, no `RefCell` guard, no
157
+ //! guard of its own, no slice of a Ruby collection (that module says why
158
+ //! each).
159
+ //! - **Declared Ractor-safe, the extension's own state is too.** What the
160
+ //! layer keeps is safe across Ractors; what the extension keeps - its
161
+ //! statics, whatever its methods take the GVL to serialise (now only one
162
+ //! Ractor's threads) - is its own to show, and a class of its wrapped
163
+ //! objects defines no Marshal hook, through which Ruby would copy one to
164
+ //! another Ractor. Checked by review alone, and by specs that run its
165
+ //! methods in several Ractors at once.
166
+ //! - **The GVL's token is made only where Ruby calls in.** That Ruby called
167
+ //! the code in, holding the GVL, is a fact about the caller, which no type
168
+ //! states. [`rb::method::run_init`] is called from the extension's
169
+ //! `extern "C" fn Init_*` alone, [`rb::method::finish`] from the
170
+ //! `method!` / `function!` expansions alone, and `nupur_sys`'s maker
171
+ //! (`Ruby::assume_gvl`) from `rb::method::entry_token` alone. Checked by
172
+ //! `gvl_token_outside_entry`, not the compiler: `assume_gvl` is `pub`.
173
+
174
+ #![deny(unsafe_code)]
175
+ /* The casts that lose a value. Where the code is built a C `long` is `i64`
176
+ * itself, so these see nothing there that `c_integer_outside_int` does not;
177
+ * on Windows, whose `long` is 32 bits, clippy sees the real types - CI runs
178
+ * it on that cell too. `int` is the one module that casts. */
179
+ #![warn(
180
+ clippy::cast_possible_truncation,
181
+ clippy::cast_possible_wrap,
182
+ clippy::cast_sign_loss,
183
+ clippy::cast_lossless
184
+ )]
185
+ /* `i64::from(a_c_long)` is a no-op here and a widening on Windows: the
186
+ * conversions are written for every target, which this lint cannot see. */
187
+ #![allow(
188
+ clippy::useless_conversion,
189
+ reason = "C's integer types are aliases whose width is the target's"
190
+ )]
191
+ #![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))]
192
+ /* `rake dylint` sets `dylint_lib` for the whole build, the extension's run
193
+ * compiling this crate as a plain dependency: there the extension's lints,
194
+ * which the `allow`s here name, are unknown. */
195
+ #![cfg_attr(dylint_lib = "nupur_lints", allow(unknown_lints))]
196
+ /* An `Err` of a Ruby error is never dropped: `Error::rescue` handles the
197
+ * classes it names and hands every exit back. `deny` here, not `forbid` as
198
+ * in the extension: the layer's one drop is `describe::for_message`, a
199
+ * message's lookup, allowed there with its reason. */
200
+ #![cfg_attr(dylint_lib = "nupur_lints", deny(discarded_ruby_error))]
201
+
202
+ /* "No panic reaches C" rests on the host's profile, not this crate's: a
203
+ * dependency's `[profile]` is ignored, so `panic = "abort"` in the
204
+ * extension's would leave every trampoline's catch dead and a panic killing
205
+ * the host. Refused here, where the guarantee is made. */
206
+ #[cfg(not(panic = "unwind"))]
207
+ compile_error!(
208
+ "nupur needs `panic = \"unwind\"`: set it in the extension's [profile.*] - \
209
+ with `abort`, a panic in a method kills the host instead of raising"
210
+ );
211
+
212
+ // The lints' self-test for this crate (`rake dylint`).
213
+ #[cfg(nupur_lint_probe)]
214
+ mod lint_probe;
215
+
216
+ // The value and method layer: `Value` and the class-checked handles,
217
+ // `Error`, the `method!` / `function!` trampolines, class definitions.
218
+ pub mod rb;
219
+
220
+ // Every Ruby C call that can raise, each under `rb_protect`.
221
+ pub(crate) mod raw;
222
+
223
+ // A short name as a C string on the stack, as Ruby's C API takes one.
224
+ pub(crate) mod cname;
225
+
226
+ // Every conversion between Rust's integer widths and C's `long` - the
227
+ // layer's own: what it hands an extension is in Rust's widths.
228
+ pub(crate) use nupur_sys::int;
229
+
230
+ // TypedData: wrapping a Rust value as a Ruby object, and its GC hooks.
231
+ pub mod typed;
232
+
233
+ // Running a body with the GVL released.
234
+ pub mod gvl;
235
+
236
+ // Building Ruby values: Arrays, Hashes, numbers, Symbols, UTF-8 Strings.
237
+ pub mod build;
238
+
239
+ // A Ruby encoding, as Strings are read and converted by it.
240
+ pub mod encoding;
241
+
242
+ // A Ruby String's bytes, read and written by copying.
243
+ pub mod string;
244
+
245
+ // Owned bytes checked to be UTF-8 (`Utf8Copy`), std alone.
246
+ pub mod utf8_copy;
247
+
248
+ // The OOM sweep's hooks, installed together (`rake oom`).
249
+ #[cfg(feature = "alloc-inject")]
250
+ pub mod inject;
251
+
252
+ // A private table from small integers to values ([`table::IntTable`]).
253
+ pub mod table;
254
+
255
+ // Reading a method's arguments: a type check each, no conversion; the
256
+ // separation of positional arguments and keywords; keywords by name.
257
+ pub mod args;
258
+
259
+ // Walking a Hash's pairs.
260
+ pub mod hash;
261
+
262
+ // Ruby values written into a message without a call.
263
+ pub mod describe;
264
+
265
+ // What the binary assumes of the running Ruby, and the load checks of it.
266
+ pub mod abi;
267
+
268
+ // The native-stack check, for a token.
269
+ pub mod stack;
270
+
271
+ // `Msg`: an exception message written into a fixed buffer on the stack,
272
+ // so an error path allocates nothing.
273
+ pub mod msg;
274
+
275
+ // Catching a panic at a C boundary and re-raising it past one.
276
+ pub mod caught;
277
+
278
+ // The layer's bodies that must not unwind, and the build that checks they
279
+ // cannot (`rake no_unwind`).
280
+ pub mod no_unwind;
@@ -0,0 +1,142 @@
1
+ //! What the layer's lints (`lints/nupur_lints`) must report in the
2
+ //! binding layer, the cases only code that names `nupur_sys` can write - the
3
+ //! extension cannot, since it does not depend on it. A call of rb-sys's own
4
+ //! C cannot be written here at all (`nupur_sys` re-exports no function): its
5
+ //! cases are `nupur_sys`'s probe's. Compiled only under
6
+ //! `--cfg nupur_lint_probe`, by `rake dylint`, which fails unless the lints
7
+ //! report exactly the lines that end in `//~`, each by the lints named
8
+ //! after it.
9
+ #![allow(dead_code, clippy::all)]
10
+
11
+ /// An `unsafe fn` of `nupur_sys`, whose contract is the GVL, from a safe
12
+ /// function with no proof (`ffi_without_gvl_proof`).
13
+ #[allow(unsafe_code)]
14
+ fn sys_contract() {
15
+ unsafe { nupur_sys::protect::forget_errinfo() } //~ ffi_without_gvl_proof
16
+ }
17
+
18
+ /// `nupur_sys`'s value types on the heap (`ruby_value_on_heap`): they hold
19
+ /// a `VALUE` and implement no trait of the layer's, so the lint names them.
20
+ struct SysKept {
21
+ values: Vec<nupur_sys::value::Value>, //~ ruby_value_on_heap
22
+ roots: Vec<nupur_sys::value::Root>, //~ ruby_value_on_heap
23
+ }
24
+
25
+ /// The GVL's token made outside the entries Ruby calls
26
+ /// (`gvl_token_outside_entry`): the maker outside `rb::method`, a
27
+ /// trampoline's helper outside a `method!` expansion, `run_init` outside an
28
+ /// `Init_` function.
29
+ #[allow(unsafe_code)]
30
+ #[rustfmt::skip] // keeps each marker on the line reported
31
+ mod entry {
32
+
33
+ fn trampoline() -> crate::rb::Value {
34
+ unsafe { crate::rb::method::finish(|ruby| Ok(ruby.qnil())) } //~ gvl_token_outside_entry
35
+ }
36
+
37
+ fn init(check: fn(&crate::rb::Ruby) -> Result<(), crate::rb::Error>) {
38
+ unsafe { crate::rb::method::run_init(check, check) } //~ gvl_token_outside_entry
39
+ }
40
+
41
+ fn sys_token() -> nupur_sys::value::Ruby {
42
+ unsafe { nupur_sys::value::Ruby::assume_gvl() } //~ ffi_without_gvl_proof gvl_token_outside_entry
43
+ }
44
+ }
45
+
46
+ /// A handle that holds its object forgotten (`forgotten_handle`).
47
+ #[rustfmt::skip] // keeps each marker on the line reported
48
+ mod handles {
49
+ struct P;
50
+ impl crate::typed::Payload for P {}
51
+ static T: crate::typed::TypedType<P> = crate::typed::TypedType::base(c"lint_probe");
52
+
53
+ fn forgotten(v: crate::rb::Value) -> Result<(), crate::rb::Error> {
54
+ let handle = T.check(v)?;
55
+ core::mem::forget(handle); //~ forgotten_handle
56
+ Ok(())
57
+ }
58
+
59
+ fn manually(v: crate::rb::Value) -> Result<(), crate::rb::Error> {
60
+ let _kept = core::mem::ManuallyDrop::new(T.check(v)?); //~ forgotten_handle
61
+ Ok(())
62
+ }
63
+ }
64
+
65
+ /// A C integer at the Ruby boundary outside `nupur_sys::int`
66
+ /// (`c_integer_outside_int`): an integer `as` cast - which the lint sees
67
+ /// even where `c_long` is `i64` itself - and `c_long` named; a `TryFrom`
68
+ /// passes.
69
+ #[rustfmt::skip] // keeps each marker on the line reported
70
+ mod c_integer {
71
+ fn cast(n: usize) -> i64 {
72
+ n as i64 //~ c_integer_outside_int
73
+ }
74
+
75
+ fn named(n: i64) -> Option<core::ffi::c_long> { //~ c_integer_outside_int
76
+ n.try_into().ok()
77
+ }
78
+
79
+ fn converted(n: usize) -> Option<i64> {
80
+ i64::try_from(n).ok()
81
+ }
82
+ }
83
+
84
+ /// What `raw` holds (`unraising_call_in_raw`), in a stand-in for it: a read
85
+ /// that raises nothing, outside `call` or as all a `call` protects, is
86
+ /// reported.
87
+ #[allow(unsafe_code)]
88
+ #[rustfmt::skip] // keeps each marker on the line reported
89
+ mod raw {
90
+ fn call<T>(f: impl FnOnce() -> T) -> T {
91
+ f()
92
+ }
93
+
94
+ /* The protected form, whose closure is lent the token: never run here,
95
+ * only checked. */
96
+ fn call_protected<T>(_: impl FnOnce(&nupur_sys::protect::Protected) -> T) -> Option<T> {
97
+ None
98
+ }
99
+
100
+ fn a_read_in_raw(ruby: &crate::rb::Ruby) -> bool {
101
+ unsafe { nupur_sys::non_raising::rb_block_given_p(ruby.sys()) != 0 } //~ unraising_call_in_raw
102
+ }
103
+
104
+ fn protecting_nothing(ruby: &crate::rb::Ruby) -> bool {
105
+ call(|| unsafe { nupur_sys::non_raising::rb_block_given_p(ruby.sys()) != 0 }) //~ unraising_call_in_raw
106
+ }
107
+
108
+ /* A call of a raising wrapper is what a protected call is for: passes. */
109
+ fn protecting_a_raise(_: &crate::rb::Ruby) {
110
+ let _ = call_protected(|inside| unsafe { nupur_sys::raising::rb_hash_new(inside) });
111
+ }
112
+ }
113
+
114
+ /// Stands in for the layer's Ruby-free module, `utf8_copy`:
115
+ /// `ruby_in_ruby_free_module` treats `lint_probe::ruby_free` as one.
116
+ #[rustfmt::skip] // keeps each marker on the line reported
117
+ mod ruby_free {
118
+ pub fn names_the_ruby_layer() -> crate::rb::Error { //~ ruby_in_ruby_free_module
119
+ crate::rb::error::type_error("x") //~ ruby_in_ruby_free_module
120
+ }
121
+
122
+ pub fn names_only_std(b: &[u8]) -> bool {
123
+ core::str::from_utf8(b).is_ok()
124
+ }
125
+ }
126
+
127
+ /// The raw wrappers that run the caller's Ruby, at their own level
128
+ /// (`runs_callers_ruby`): written here because the extension cannot name
129
+ /// them, and the layer's functions over them `expect` the lint.
130
+ #[rustfmt::skip] // keeps each marker on the line reported
131
+ fn callers_ruby(
132
+ ruby: &crate::rb::Ruby,
133
+ v: crate::rb::Value,
134
+ id: crate::rb::Id,
135
+ ) -> Result<(), crate::rb::Error> {
136
+ crate::raw::call_method(ruby, v, c"to_s", &[])?; //~ runs_callers_ruby
137
+ crate::raw::call_public(v, id, &[])?; //~ runs_callers_ruby
138
+ crate::raw::respond_to(v, id)?; //~ runs_callers_ruby
139
+ crate::raw::yield_value(ruby, v)?; //~ runs_callers_ruby
140
+ crate::raw::yield_values(ruby, [v, v])?; //~ runs_callers_ruby
141
+ Ok(())
142
+ }
@@ -0,0 +1,193 @@
1
+ //! Exception messages written without the heap.
2
+ //!
3
+ //! A message is formatted into [`Msg`], a fixed buffer kept inline - in a
4
+ //! `rb::Error`, which `Error::new` given `format_args!` makes - so an
5
+ //! error path allocates nothing of Rust's: a `format!` there would abort the
6
+ //! process under the very OOM it may be reporting. What a message quotes is written straight into the buffer -
7
+ //! bytes through [`Lossy`] and [`Quoted`], a Ruby value through `describe`'s
8
+ //! own `Display` types. Ruby-free.
9
+
10
+ #![forbid(unsafe_code)]
11
+
12
+ use core::fmt::{self, Write};
13
+
14
+ /// The longest message, in bytes. A longer one is cut at a character
15
+ /// boundary and ends with `...`: a message quotes untrusted input, and is
16
+ /// read by a person.
17
+ pub const MSG_MAX: usize = 256;
18
+
19
+ const ELLIPSIS: &str = "...";
20
+
21
+ /// A message being written: up to [`MSG_MAX`] bytes of UTF-8.
22
+ pub struct Msg {
23
+ buf: [u8; MSG_MAX],
24
+ len: u16,
25
+ cut: bool,
26
+ }
27
+
28
+ impl Msg {
29
+ const EMPTY: Msg = Msg {
30
+ buf: [0; MSG_MAX],
31
+ len: 0,
32
+ cut: false,
33
+ };
34
+
35
+ /// `args`, written out.
36
+ #[inline]
37
+ pub(crate) fn format(args: fmt::Arguments<'_>) -> Msg {
38
+ let mut m = Msg::EMPTY;
39
+ /* A `Display` that fails leaves what it wrote; the message is still
40
+ * worth raising. */
41
+ let _ = m.write_fmt(args);
42
+ m.finish()
43
+ }
44
+
45
+ /// `s`, copied - with no formatting machinery, so where nothing may
46
+ /// unwind (a trampoline that has caught a panic, `crate::no_unwind`) it
47
+ /// is provably panic-free.
48
+ #[inline]
49
+ pub fn copy(s: &str) -> Msg {
50
+ let mut m = Msg::EMPTY;
51
+ m.push(s);
52
+ m.finish()
53
+ }
54
+
55
+ /// Mark a cut message as such.
56
+ #[inline]
57
+ fn finish(mut self) -> Msg {
58
+ if self.cut {
59
+ let len = floor_char_boundary(self.as_bytes(), MSG_MAX - ELLIPSIS.len());
60
+ self.len = u16::try_from(len).unwrap_or(0);
61
+ self.cut = false;
62
+ self.push(ELLIPSIS);
63
+ }
64
+ self
65
+ }
66
+
67
+ /// Append what fits of `s`, cut at a character boundary. No operation
68
+ /// here can panic: every index is a checked `get`, and the arithmetic is
69
+ /// on values below [`MSG_MAX`].
70
+ #[inline]
71
+ fn push(&mut self, s: &str) {
72
+ let len = usize::from(self.len).min(MSG_MAX);
73
+ let room = MSG_MAX.saturating_sub(len);
74
+ let n = if s.len() <= room {
75
+ s.len()
76
+ } else {
77
+ self.cut = true;
78
+ floor_char_boundary(s.as_bytes(), room)
79
+ };
80
+ if let (Some(dst), Some(src)) = (self.buf.get_mut(len..), s.as_bytes().get(..n)) {
81
+ for (d, b) in dst.iter_mut().zip(src) {
82
+ *d = *b;
83
+ }
84
+ /* `len + n <= MSG_MAX`, which a u16 holds. */
85
+ self.len = u16::try_from(len.saturating_add(n).min(MSG_MAX)).unwrap_or(0);
86
+ }
87
+ }
88
+
89
+ /// The bytes: UTF-8, as only whole `&str`s and their prefixes at a char
90
+ /// boundary are ever copied in.
91
+ #[inline]
92
+ pub fn as_bytes(&self) -> &[u8] {
93
+ self.buf.get(..usize::from(self.len)).unwrap_or(&[])
94
+ }
95
+
96
+ /// The text.
97
+ #[inline]
98
+ pub fn as_str(&self) -> &str {
99
+ /* UTF-8 by construction (`as_bytes`); the fallback is unreachable. */
100
+ core::str::from_utf8(self.as_bytes()).unwrap_or("error")
101
+ }
102
+ }
103
+
104
+ /// The largest index `<= max` of `s` that starts a character (or ends `s`).
105
+ #[inline]
106
+ pub(crate) fn floor_char_boundary(s: &[u8], max: usize) -> usize {
107
+ let mut i = max.min(s.len());
108
+ while i > 0 && s.get(i).is_some_and(|&b| (b & 0xC0) == 0x80) {
109
+ i -= 1;
110
+ }
111
+ i
112
+ }
113
+
114
+ impl Write for Msg {
115
+ #[inline]
116
+ fn write_str(&mut self, s: &str) -> fmt::Result {
117
+ if !self.cut {
118
+ self.push(s);
119
+ }
120
+ Ok(())
121
+ }
122
+ }
123
+
124
+ /// Bytes as text: invalid UTF-8 written as U+FFFD, as `from_utf8_lossy`
125
+ /// has it, with no copy.
126
+ pub struct Lossy<'a>(pub &'a [u8]);
127
+
128
+ impl fmt::Display for Lossy<'_> {
129
+ #[inline]
130
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131
+ for chunk in self.0.utf8_chunks() {
132
+ f.write_str(chunk.valid())?;
133
+ if !chunk.invalid().is_empty() {
134
+ f.write_char(char::REPLACEMENT_CHARACTER)?;
135
+ }
136
+ }
137
+ Ok(())
138
+ }
139
+ }
140
+
141
+ /// Bytes as a quoted, escaped string, as `{:?}` writes a `&str`; invalid
142
+ /// UTF-8 as U+FFFD.
143
+ pub struct Quoted<'a>(pub &'a [u8]);
144
+
145
+ impl fmt::Display for Quoted<'_> {
146
+ #[inline]
147
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148
+ f.write_char('"')?;
149
+ for chunk in self.0.utf8_chunks() {
150
+ for c in chunk.valid().chars() {
151
+ match c {
152
+ '\'' => f.write_char('\'')?,
153
+ c => write!(f, "{}", c.escape_debug())?,
154
+ }
155
+ }
156
+ if !chunk.invalid().is_empty() {
157
+ f.write_char(char::REPLACEMENT_CHARACTER)?;
158
+ }
159
+ }
160
+ f.write_char('"')
161
+ }
162
+ }
163
+
164
+ #[cfg(test)]
165
+ mod tests {
166
+ use super::*;
167
+
168
+ #[test]
169
+ fn a_message_that_fits_is_written_whole() {
170
+ let m = Msg::format(format_args!("a {} c", "b"));
171
+ assert_eq!(m.as_str(), "a b c");
172
+ }
173
+
174
+ #[test]
175
+ fn a_long_message_is_cut_at_a_character_boundary() {
176
+ let long = "é".repeat(MSG_MAX);
177
+ let m = Msg::format(format_args!("x{long}"));
178
+ let s = m.as_str();
179
+ assert!(s.len() <= MSG_MAX);
180
+ assert!(s.ends_with("..."));
181
+ assert!(s.starts_with("xé"));
182
+ }
183
+
184
+ #[test]
185
+ fn lossy_and_quoted_replace_invalid_bytes() {
186
+ let m = Msg::format(format_args!(
187
+ "{} {}",
188
+ Lossy(b"a\xFFb"),
189
+ Quoted(b"q\"\n\xFF")
190
+ ));
191
+ assert_eq!(m.as_str(), "a\u{FFFD}b \"q\\\"\\n\u{FFFD}\"");
192
+ }
193
+ }
@@ -0,0 +1,39 @@
1
+ //! The layer's bodies that must not unwind, and the build that checks they
2
+ //! cannot (`rake no_unwind`): the guard is `nupur_sys`'s, where the protect
3
+ //! thunk runs under it; the sites below are Nupur's own, which that crate
4
+ //! does not name.
5
+
6
+ #[cfg(nupur_no_unwind)]
7
+ pub use nupur_sys::no_unwind::self_test;
8
+ pub use nupur_sys::no_unwind::{must_not_unwind, Site};
9
+
10
+ nupur_sys::no_unwind_sites! {
11
+ /// `typed`'s mark callback.
12
+ GcMark => "nupur_unwinds_gc_mark",
13
+ /// `typed`'s free callback: the data's whole drop glue.
14
+ GcFree => "nupur_unwinds_gc_free",
15
+ /// `typed`'s free callback for an embedded type.
16
+ GcFreeEmbedded => "nupur_unwinds_gc_free_embedded",
17
+ /// `typed`'s memsize callback.
18
+ GcMemsize => "nupur_unwinds_gc_memsize",
19
+ /// `raw::hash_foreach`'s `rb_hash_foreach` callback.
20
+ HashEach => "nupur_unwinds_hash_each",
21
+ /// `gvl::without_gvl`'s body, run with the GVL released.
22
+ GvlBody => "nupur_unwinds_gvl_body",
23
+ /// `gvl::without_gvl_cancellable`'s unblock function, which Ruby calls
24
+ /// from another thread to ask the body to stop.
25
+ GvlUnblock => "nupur_unwinds_gvl_unblock",
26
+ /// A method's trampoline (`rb::method::finish`, which `finish_cary` runs
27
+ /// too).
28
+ Method => "nupur_unwinds_method",
29
+ /// The extension's `Init_` (`rb::method::run_init`).
30
+ Init => "nupur_unwinds_init",
31
+ /// `string::utf8_str_filled`'s guard, which empties a String a panic left
32
+ /// unfilled - while that panic unwinds.
33
+ DropUnfilled => "nupur_unwinds_drop_unfilled",
34
+ /// `rb::kept::Kept`'s `Drop`, which hands its value to `keep_alive`.
35
+ DropKept => "nupur_unwinds_drop_kept",
36
+ /// `RString::with_locked_bytes`'s guard, which unlocks the String - while
37
+ /// a panic unwinds, too.
38
+ DropUnlock => "nupur_unwinds_drop_unlock",
39
+ }