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,213 @@
1
+ //! A TypedData type's `rb_data_type_t`, built where its layout is known:
2
+ //! the callbacks, the flags (`VALUE`-typed bits, which only this crate
3
+ //! spells), and the check that the callback table is a layout Nupur has
4
+ //! read.
5
+
6
+ #![allow(unsafe_code)]
7
+
8
+ use rb_sys::{rb_data_type_t, VALUE};
9
+
10
+ /// A `rb_data_type_t` that can live in a `static`.
11
+ ///
12
+ /// `rb_data_type_t` holds raw pointers, so it is not `Sync`; these are set at
13
+ /// compile time and never written. `repr(transparent)` keeps the layout exactly
14
+ /// `rb_data_type_t`, which is what `rb_data_typed_object_wrap` reads.
15
+ #[repr(transparent)]
16
+ pub struct DataType(rb_data_type_t);
17
+
18
+ // SAFETY: the contents are set once at compile time and never mutated. Ruby
19
+ // reads them from whichever thread holds the GVL.
20
+ unsafe impl Sync for DataType {}
21
+
22
+ /* The table of callbacks, in pointer-sized words: 5 up to Ruby 4.0 (dmark,
23
+ * dfree, dsize, dcompact, reserved[1]) and 12 from 4.1 (+ handle_weak_references,
24
+ * reserved[7]). Zero-initialising it is right for a layout whose extra words
25
+ * are all optional callbacks or zero-filled reserve - which only someone who
26
+ * has read the new header knows - so any other size stops the build here
27
+ * instead of shipping a table nobody has checked. */
28
+ const FUNCTION_TABLE_WORDS: usize =
29
+ size_of::<rb_sys::rb_data_type_struct__bindgen_ty_1>() / size_of::<usize>();
30
+ const _: () = assert!(
31
+ FUNCTION_TABLE_WORDS == 5 || FUNCTION_TABLE_WORDS == 12,
32
+ "rb_data_type_t's callback table has a layout nupur has not read: check Ruby's \
33
+ include/ruby/internal/core/rtypeddata.h, then list its size here"
34
+ );
35
+
36
+ /// What a type's objects are, for Ruby: the flags of its `rb_data_type_t`,
37
+ /// as the choices a type has rather than bits.
38
+ ///
39
+ /// Every type is freed at once when its object is collected
40
+ /// (`RUBY_TYPED_FREE_IMMEDIATELY`: the free callback only drops and frees,
41
+ /// which needs no deferral). What a type chooses is whether its data may be
42
+ /// embedded in the object's own slot (`RUBY_TYPED_EMBEDDABLE`), and whether
43
+ /// a frozen object may be shared between Ractors
44
+ /// (`RUBY_TYPED_FROZEN_SHAREABLE`). A shareable object can be read from two
45
+ /// Ractors at once, so only a payload that is `Sync` may choose it - which
46
+ /// Nupur's `TypedType::shareable` holds by its bound; without the flag Ruby
47
+ /// refuses to make an object shareable.
48
+ #[derive(Clone, Copy, PartialEq, Eq, Debug)]
49
+ pub struct DataFlags {
50
+ embeddable: bool,
51
+ shareable: bool,
52
+ }
53
+
54
+ impl DataFlags {
55
+ /// Data apart from the object, in a block of its own.
56
+ pub const SEPARATE: DataFlags = DataFlags {
57
+ embeddable: false,
58
+ shareable: false,
59
+ };
60
+ /// Data that Ruby may embed in the object's own slot.
61
+ pub const EMBEDDABLE: DataFlags = DataFlags {
62
+ embeddable: true,
63
+ shareable: false,
64
+ };
65
+
66
+ /// These flags, and a frozen object of the type shareable between
67
+ /// Ractors.
68
+ pub const fn frozen_shareable(self) -> DataFlags {
69
+ DataFlags {
70
+ embeddable: self.embeddable,
71
+ shareable: true,
72
+ }
73
+ }
74
+
75
+ /// The `flags` word, as `rb_data_type_t` holds it.
76
+ const fn bits(self) -> VALUE {
77
+ const FREE_IMMEDIATELY: VALUE =
78
+ rb_sys::rbimpl_typeddata_flags::RUBY_TYPED_FREE_IMMEDIATELY as VALUE;
79
+ const EMBEDDABLE: VALUE = rb_sys::rbimpl_typeddata_flags::RUBY_TYPED_EMBEDDABLE as VALUE;
80
+ const SHAREABLE: VALUE =
81
+ rb_sys::rbimpl_typeddata_flags::RUBY_TYPED_FROZEN_SHAREABLE as VALUE;
82
+ let mut bits = FREE_IMMEDIATELY;
83
+ if self.embeddable {
84
+ bits |= EMBEDDABLE;
85
+ }
86
+ if self.shareable {
87
+ bits |= SHAREABLE;
88
+ }
89
+ bits
90
+ }
91
+ }
92
+
93
+ impl DataType {
94
+ /// A type named `name` (what Ruby calls it in its messages and
95
+ /// `ObjectSpace`), deriving from `parent` (`None` for a base type), with
96
+ /// its GC callbacks and its [`DataFlags`].
97
+ pub const fn new(
98
+ name: &'static core::ffi::CStr,
99
+ parent: Option<&'static DataType>,
100
+ dmark: rb_sys::RUBY_DATA_FUNC,
101
+ dfree: rb_sys::RUBY_DATA_FUNC,
102
+ dsize: Option<unsafe extern "C" fn(*const core::ffi::c_void) -> rb_sys::size_t>,
103
+ flags: DataFlags,
104
+ ) -> DataType {
105
+ /* Zero first, then set only the fields used: Ruby's partial-initialiser
106
+ * convention (`reserved` "must be filled with zeros"), and what keeps
107
+ * this compiling when Ruby adds a callback to the table, as 4.1 did
108
+ * (`handle_weak_references`, `reserved[1]` -> `reserved[7]`). The
109
+ * layout check above is what turns a layout nobody has read into a
110
+ * build failure, not a silent one. */
111
+ // SAFETY: `rb_data_type_t` is plain C data - pointers, options of
112
+ // function pointers and an integer - for which all-zero is valid, and
113
+ // is Ruby's own initial state for the fields not set below.
114
+ let mut t: rb_data_type_t = unsafe { core::mem::zeroed() };
115
+ t.wrap_struct_name = name.as_ptr();
116
+ t.function.dmark = dmark;
117
+ t.function.dfree = dfree;
118
+ t.function.dsize = dsize;
119
+ /* No compaction callback (`dcompact` stays None): an object's only
120
+ * values are its slots, marked pinned. */
121
+ t.parent = match parent {
122
+ Some(p) => p.as_ptr(),
123
+ None => core::ptr::null(),
124
+ };
125
+ t.data = core::ptr::null_mut();
126
+ t.flags = flags.bits();
127
+ DataType(t)
128
+ }
129
+
130
+ /// The raw pointer the Ruby API wants - this crate's alone: its
131
+ /// wrappers take `&DataType`.
132
+ #[inline]
133
+ pub(crate) const fn as_ptr(&self) -> *const rb_data_type_t {
134
+ self as *const DataType as *const rb_data_type_t
135
+ }
136
+ }
137
+
138
+ #[cfg(test)]
139
+ mod tests {
140
+ use super::*;
141
+ use core::ffi::c_void;
142
+
143
+ unsafe extern "C" fn mark(_: *mut c_void) {}
144
+ unsafe extern "C" fn free(_: *mut c_void) {}
145
+ unsafe extern "C" fn size(_: *const c_void) -> rb_sys::size_t {
146
+ 0
147
+ }
148
+
149
+ /// The table's words past the three callbacks `DataType::new` sets are
150
+ /// all zero - `dcompact`, the reserve (`reserved[1]` up to Ruby 4.0), and on
151
+ /// 4.1 `handle_weak_references` and `reserved[7]` too - since a non-zero
152
+ /// reserve is a callback Ruby would call.
153
+ #[test]
154
+ fn the_callback_table_leaves_what_it_does_not_set_zero() {
155
+ let ty = DataType::new(
156
+ c"nupur::test",
157
+ None,
158
+ Some(mark),
159
+ Some(free),
160
+ Some(size),
161
+ DataFlags::SEPARATE,
162
+ );
163
+ let table = &ty.0.function;
164
+ assert!(table.dmark.is_some() && table.dfree.is_some() && table.dsize.is_some());
165
+ assert!(table.dcompact.is_none());
166
+ // SAFETY: the table is `FUNCTION_TABLE_WORDS` pointer-sized words of
167
+ // plain data, read here as such.
168
+ let words = unsafe {
169
+ core::slice::from_raw_parts(table as *const _ as *const usize, FUNCTION_TABLE_WORDS)
170
+ };
171
+ assert!(words[3..].iter().all(|&w| w == 0), "{words:?}");
172
+ assert_eq!(ty.0.flags, VALUE::from(FREE_IMMEDIATELY_FLAG));
173
+ }
174
+
175
+ /// Either kind of type that asks is one Ruby may make shareable.
176
+ #[test]
177
+ fn a_type_that_asks_is_frozen_shareable() {
178
+ const SHAREABLE_BIT: VALUE =
179
+ rb_sys::rbimpl_typeddata_flags::RUBY_TYPED_FROZEN_SHAREABLE as VALUE;
180
+ for flags in [DataFlags::SEPARATE, DataFlags::EMBEDDABLE] {
181
+ let asked = DataType::new(
182
+ c"nupur::test",
183
+ None,
184
+ Some(mark),
185
+ Some(free),
186
+ Some(size),
187
+ flags.frozen_shareable(),
188
+ );
189
+ assert_eq!(asked.0.flags & SHAREABLE_BIT, SHAREABLE_BIT);
190
+ }
191
+ }
192
+
193
+ /// Neither kind of type is one Ruby may make shareable unless it asks.
194
+ #[test]
195
+ fn no_type_is_frozen_shareable_unless_asked() {
196
+ const SHAREABLE: VALUE =
197
+ rb_sys::rbimpl_typeddata_flags::RUBY_TYPED_FROZEN_SHAREABLE as VALUE;
198
+ for flags in [DataFlags::SEPARATE, DataFlags::EMBEDDABLE] {
199
+ let ty = DataType::new(
200
+ c"nupur::test",
201
+ None,
202
+ Some(mark),
203
+ Some(free),
204
+ Some(size),
205
+ flags,
206
+ );
207
+ assert_eq!(ty.0.flags & SHAREABLE, 0);
208
+ }
209
+ }
210
+
211
+ const FREE_IMMEDIATELY_FLAG: u32 =
212
+ rb_sys::rbimpl_typeddata_flags::RUBY_TYPED_FREE_IMMEDIATELY as u32;
213
+ }
@@ -0,0 +1,248 @@
1
+ //! Every conversion between Rust's integer widths and C's: the one module
2
+ //! that names a C `long` or casts with `as` at the Ruby boundary
3
+ //! (`rake dylint`'s `c_integer_outside_int` holds every other one to that).
4
+ //! It is `nupur_sys`'s, beside the C types it converts, and Nupur reaches it
5
+ //! as `crate::int`.
6
+ //!
7
+ //! A C `long` is 64 bits on Linux and macOS and 32 bits on Windows (LLP64),
8
+ //! and Ruby's integers follow it: a Fixnum is `LONG_MIN / 2 ..= LONG_MAX /
9
+ //! 2`, so 2^30 - 1 at most on Windows. `c_long` is an alias, `i64` itself
10
+ //! where the code is built and linted, so a truncation there is invisible to
11
+ //! rustc and clippy - which is why each Windows bug was found by review. So
12
+ //! the rules are written once, over a `Long` of either width, and
13
+ //! instantiated at this target's: the tests run them at both widths on any
14
+ //! machine, and hold the host's instance to rb-sys's own constants and
15
+ //! `long2fix`. `verus/int.rs` proves the rules at both widths for every
16
+ //! input (`rake verus`), over copies `rake verus:sync` holds to this file.
17
+ //!
18
+ //! Everything else converts with `From` / `TryFrom`, which compile to what
19
+ //! each target allows and fail where a value does not fit, and never names
20
+ //! `c_long`: a length is a `usize`, an index or a count an `i64`.
21
+
22
+ #![forbid(unsafe_code)]
23
+ /* The one module that casts: each cast below is a widening a `const` assert
24
+ * proves, or a test's. */
25
+ #![allow(
26
+ clippy::cast_possible_truncation,
27
+ clippy::cast_possible_wrap,
28
+ clippy::cast_sign_loss,
29
+ reason = "the module whose casts are proved or tested; see each"
30
+ )]
31
+
32
+ use core::ffi::c_long;
33
+
34
+ /// A C `long` of some width: this target's (`c_long`), or the other one, for
35
+ /// the tests.
36
+ pub(crate) trait Long: Copy + Into<i64> + TryFrom<i64> + TryFrom<u64> {
37
+ const MIN: Self;
38
+ const MAX: Self;
39
+ }
40
+
41
+ impl Long for i32 {
42
+ const MIN: i32 = i32::MIN;
43
+ const MAX: i32 = i32::MAX;
44
+ }
45
+
46
+ impl Long for i64 {
47
+ const MIN: i64 = i64::MIN;
48
+ const MAX: i64 = i64::MAX;
49
+ }
50
+
51
+ /// `n` as a `long` within a Fixnum's range (`RB_FIXABLE`), or `None`: a
52
+ /// Fixnum is a `long` less its flag bit, `MIN / 2 ..= MAX / 2`.
53
+ #[inline]
54
+ pub(crate) fn fixable_in<L: Long>(n: i64) -> Option<L> {
55
+ let (min, max) = (Into::<i64>::into(L::MIN) / 2, Into::<i64>::into(L::MAX) / 2);
56
+ if n < min || n > max {
57
+ return None;
58
+ }
59
+ L::try_from(n).ok()
60
+ }
61
+
62
+ /// [`fixable_in`] for an unsigned value (`RB_POSFIXABLE`).
63
+ #[inline]
64
+ pub(crate) fn posfixable_in<L: Long>(n: u64) -> Option<L> {
65
+ i64::try_from(n).ok().and_then(fixable_in::<L>)
66
+ }
67
+
68
+ /// `n` as this target's `long`, when it is a Fixnum's.
69
+ #[inline]
70
+ pub(crate) fn fixable(n: i64) -> Option<c_long> {
71
+ fixable_in::<c_long>(n)
72
+ }
73
+
74
+ /// `n` as this target's `long`, when it is a Fixnum's.
75
+ #[inline]
76
+ pub(crate) fn posfixable(n: u64) -> Option<c_long> {
77
+ posfixable_in::<c_long>(n)
78
+ }
79
+
80
+ /// The Fixnum `n` is, as Ruby's `LONG2FIX` makes it - `(n << 1) | 1`, the
81
+ /// `long` sign-extended to a `VALUE` - or `None` past a Fixnum's range
82
+ /// (past 2^30 - 1 on Windows). Built from its bits here, where the tests
83
+ /// hold it to rb-sys's `long2fix`, so a caller needs no proof of the GVL for
84
+ /// what is arithmetic.
85
+ #[inline]
86
+ pub(crate) fn fixnum(n: i64) -> Option<rb_sys::VALUE> {
87
+ fixable(n).map(fixnum_bits)
88
+ }
89
+
90
+ /// [`fixnum`] for an unsigned value.
91
+ #[inline]
92
+ pub(crate) fn posfixnum(n: u64) -> Option<rb_sys::VALUE> {
93
+ posfixable(n).map(fixnum_bits)
94
+ }
95
+
96
+ #[inline]
97
+ fn fixnum_bits(l: c_long) -> rb_sys::VALUE {
98
+ ((l as rb_sys::VALUE) << 1) | rb_sys::FIXNUM_FLAG as rb_sys::VALUE
99
+ }
100
+
101
+ /// The flonum `f` is - Ruby's immediate Float, the bits
102
+ /// `rb_float_new_inline` builds - or `None` where Ruby makes a heap Float
103
+ /// instead. Only where a `VALUE` is 64 bits, as Ruby uses flonums only
104
+ /// there. [`flonum_bits`] is the work, over the double's bits.
105
+ #[inline]
106
+ pub(crate) fn flonum(f: f64) -> Option<rb_sys::VALUE> {
107
+ #[cfg(target_pointer_width = "64")]
108
+ {
109
+ flonum_bits(f.to_bits())
110
+ }
111
+ #[cfg(not(target_pointer_width = "64"))]
112
+ {
113
+ let _ = f;
114
+ None
115
+ }
116
+ }
117
+
118
+ /// [`flonum`] over a double's bits `t`: `Some` for an exponent in the
119
+ /// immediate range (its top three bits 011 or 100) but the one value whose
120
+ /// bits collide with a tag, and for +0.0; `None` for the rest (-0.0, a NaN,
121
+ /// an infinity, an exponent out of range), which Ruby makes a heap Float.
122
+ ///
123
+ /// `verus/int.rs` proves, for every `t`: a `Some` carries the flonum tag
124
+ /// (its low two bits `10`), so Ruby never reads it as a pointer, a Fixnum
125
+ /// or a special constant; and Ruby's own decoding (`rb_float_flonum_value`)
126
+ /// gives `t` back, bit for bit. The spec of Nupur's test extension holds it
127
+ /// to `rb_float_new` value by value.
128
+ #[cfg(target_pointer_width = "64")]
129
+ #[inline]
130
+ pub(crate) fn flonum_bits(t: u64) -> Option<rb_sys::VALUE> {
131
+ let exp = (t >> 60) & 0x7;
132
+ if t != 0x3000_0000_0000_0000 && (exp == 3 || exp == 4) {
133
+ /* Rotated left by three, the low bit cleared and the next set. */
134
+ #[allow(
135
+ clippy::manual_rotate,
136
+ reason = "Verus has no specification of rotate_left; the shifts are what verus/int.rs proves"
137
+ )]
138
+ let v = (((t << 3) | (t >> 61)) & !0x1) | 0x2;
139
+ return Some(v as rb_sys::VALUE);
140
+ }
141
+ if t == 0 {
142
+ /* +0.0 */
143
+ return Some(0x8000_0000_0000_0002_u64 as rb_sys::VALUE);
144
+ }
145
+ None
146
+ }
147
+
148
+ /// A non-negative `long` the C API answered as a length (`RSTRING_LEN`,
149
+ /// `RARRAY_LEN`): a `usize`, and 0 for a negative one, which no length is.
150
+ #[inline]
151
+ pub(crate) fn len(n: c_long) -> usize {
152
+ usize::try_from(n).unwrap_or(0)
153
+ }
154
+
155
+ /// A capacity for the C API: `n`, or the largest `long` for one past it - a
156
+ /// hint, which the allocation then refuses.
157
+ #[inline]
158
+ pub fn capacity(n: usize) -> c_long {
159
+ c_long::try_from(n).unwrap_or(c_long::MAX)
160
+ }
161
+
162
+ /// `rb_sys::posfixable`'s argument, for the test that holds [`posfixable`]
163
+ /// to it.
164
+ #[cfg(test)]
165
+ fn as_ulong(n: u64) -> Option<core::ffi::c_ulong> {
166
+ core::ffi::c_ulong::try_from(n).ok()
167
+ }
168
+
169
+ /// A word Ruby hands out (a `VALUE`) as a `usize`: the two are the same
170
+ /// width on every target, a `VALUE` being C's `uintptr_t`.
171
+ #[inline]
172
+ pub(crate) fn word(v: rb_sys::VALUE) -> usize {
173
+ const _: () = assert!(size_of::<rb_sys::VALUE>() == size_of::<usize>());
174
+ v as usize
175
+ }
176
+
177
+ /// A `usize` as a `u64`, which holds every one on every target Rust has.
178
+ #[inline]
179
+ pub fn wide(n: usize) -> u64 {
180
+ const _: () = assert!(usize::BITS <= u64::BITS);
181
+ n as u64
182
+ }
183
+
184
+ #[cfg(test)]
185
+ mod tests {
186
+ use super::*;
187
+ use rb_sys::stable_api::{get_default, StableApiDefinition};
188
+
189
+ /// A Windows `long`: 2^30 - 1 is the largest Fixnum, and a 64-bit key
190
+ /// with anything in its high half is far past it.
191
+ #[test]
192
+ fn a_32_bit_long_has_31_bit_fixnums() {
193
+ assert_eq!(fixable_in::<i32>((1 << 30) - 1), Some((1 << 30) - 1));
194
+ assert_eq!(fixable_in::<i32>(1 << 30), None);
195
+ assert_eq!(fixable_in::<i32>(-(1 << 30)), Some(-(1 << 30)));
196
+ assert_eq!(fixable_in::<i32>(-(1 << 30) - 1), None);
197
+ assert_eq!(fixable_in::<i32>(1 | (1 << 32)), None);
198
+ assert_eq!(posfixable_in::<i32>(u64::MAX), None);
199
+ assert_eq!(posfixable_in::<i32>(7), Some(7));
200
+ }
201
+
202
+ #[test]
203
+ fn a_64_bit_long_has_63_bit_fixnums() {
204
+ assert_eq!(fixable_in::<i64>((1 << 62) - 1), Some((1 << 62) - 1));
205
+ assert_eq!(fixable_in::<i64>(1 << 62), None);
206
+ assert_eq!(fixable_in::<i64>(-(1 << 62)), Some(-(1 << 62)));
207
+ assert_eq!(fixable_in::<i64>(-(1 << 62) - 1), None);
208
+ assert_eq!(posfixable_in::<i64>(1 << 62), None);
209
+ }
210
+
211
+ /// This target's instance is rb-sys's: the same bounds as its
212
+ /// `FIXNUM_MIN` / `FIXNUM_MAX`, and the same answer as its `fixable`.
213
+ #[test]
214
+ fn this_targets_long_agrees_with_rb_sys() {
215
+ use rb_sys::special_consts::{FIXNUM_MAX, FIXNUM_MIN};
216
+ let api = get_default();
217
+ let (min, max) = (i64::from(FIXNUM_MIN), i64::from(FIXNUM_MAX));
218
+ for n in [0, 1, -1, max, max + 1, min, min - 1, i64::MAX, i64::MIN] {
219
+ let ours = fixable(n);
220
+ let theirs = c_long::try_from(n).ok().filter(|&l| api.fixable(l));
221
+ assert_eq!(ours, theirs, "{n}");
222
+ }
223
+ for n in [0, 1, max as u64, max as u64 + 1, u64::MAX] {
224
+ let ours = posfixable(n).is_some();
225
+ let theirs = as_ulong(n).is_some_and(|l| api.posfixable(l));
226
+ assert_eq!(ours, theirs, "{n}");
227
+ }
228
+ }
229
+
230
+ /// A Fixnum built from its bits is the one `long2fix` makes, and reads
231
+ /// back as the number it was made from.
232
+ #[test]
233
+ fn a_fixnum_is_long2fix() {
234
+ let api = get_default();
235
+ let max = i64::from(rb_sys::special_consts::FIXNUM_MAX);
236
+ let min = i64::from(rb_sys::special_consts::FIXNUM_MIN);
237
+ for n in [0, 1, -1, 42, -42, max, min] {
238
+ let l = fixable(n).unwrap();
239
+ let v = fixnum(n).unwrap();
240
+ assert_eq!(v, api.long2fix(l), "{n}");
241
+ assert_eq!(i64::from(api.fix2long(v)), n, "{n}");
242
+ }
243
+ assert_eq!(posfixnum(max as u64), fixnum(max));
244
+ assert_eq!(posfixnum(max as u64 + 1), None);
245
+ assert_eq!(fixnum(max + 1), None);
246
+ assert_eq!(fixnum(min - 1), None);
247
+ }
248
+ }
@@ -0,0 +1,61 @@
1
+ //! `nupur_sys`: Ruby's C API as Nupur sees it - the one crate of the layer
2
+ //! that depends on rb-sys, so Nupur itself cannot name rb-sys.
3
+ //!
4
+ //! It holds the protection every C call that can raise runs under
5
+ //! ([`protect`]: `rb_protect`, `$!`, a pending non-local exit, and the
6
+ //! [`protect::Protected`] token the protected closure is lent), and the
7
+ //! mechanism that proves what must not unwind cannot ([`no_unwind`]), whose
8
+ //! guard the protect thunk runs under.
9
+ //!
10
+ //! Ruby's C is reached only through wrappers here, each taking its proof: a
11
+ //! raising call the protection's token ([`raising`], [`protect::Protected`]),
12
+ //! any other a value or the GVL's token ([`non_raising`], [`value::Value`],
13
+ //! [`value::Ruby`]). Of rb-sys itself only a few types and constants Nupur
14
+ //! names are re-exported, and no C function and no `VALUE`, so those rules
15
+ //! are types rather than lints.
16
+ //!
17
+ //! The crate denies `unsafe_code`, and the files that need it carry an
18
+ //! `allow` each, as Nupur does.
19
+ #![deny(unsafe_code)]
20
+ /* The casts that lose a value, as in Nupur: where the code is built a C
21
+ * `long` is `i64` itself, so these see nothing there; on Windows, whose
22
+ * `long` is 32 bits, clippy sees the real types - CI runs it on that cell
23
+ * too. `int` is the one module that casts. */
24
+ #![warn(
25
+ clippy::cast_possible_truncation,
26
+ clippy::cast_possible_wrap,
27
+ clippy::cast_sign_loss,
28
+ clippy::cast_lossless
29
+ )]
30
+ #![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))]
31
+ /* `i64::from(a_c_long)` is a no-op here and a widening on Windows: the
32
+ * conversions are written for every target, which this lint cannot see. */
33
+ #![allow(
34
+ clippy::useless_conversion,
35
+ reason = "C's integer types are aliases whose width is the target's"
36
+ )]
37
+ /* Built as a dependency under `rake dylint`, the crate sees `dylint_lib` but
38
+ * not the lints, so their `allow`s name lints it does not know. */
39
+ #![cfg_attr(dylint_lib = "nupur_lints", allow(unknown_lints))]
40
+
41
+ /* The types and constants Nupur names, and nothing else of rb-sys's: no C
42
+ * function is re-exported, so Nupur calls Ruby's C only through the
43
+ * wrappers here, each taking its proof (`raising`, `non_raising`, `protect`); and
44
+ * no `VALUE`, so Nupur holds a Ruby value only as a `value::Value` (or a
45
+ * slot's `value::Root`), never as an integer. */
46
+ pub use rb_sys::{
47
+ rb_encoding, ruby_coderange_type, ruby_econv_flag_type, ruby_encoding_consts, ruby_value_type,
48
+ size_t, ssize_t, st_retval, ID, RUBY_API_VERSION_MAJOR, RUBY_API_VERSION_MINOR, RUBY_DATA_FUNC,
49
+ };
50
+
51
+ pub mod data_type;
52
+ pub mod int;
53
+ pub mod no_unwind;
54
+ pub mod non_raising;
55
+ pub mod protect;
56
+ pub mod raising;
57
+ pub mod value;
58
+
59
+ /* `rake dylint`'s self-test: what the lints must report here. */
60
+ #[cfg(nupur_sys_lint_probe)]
61
+ mod lint_probe;
@@ -0,0 +1,93 @@
1
+ //! What the layer's lints (`lints/nupur_lints`) must report in
2
+ //! `nupur_sys`, the crate under the binding layer that alone depends on
3
+ //! rb-sys: that the layer's rules reach it too. Compiled only under
4
+ //! `--cfg nupur_sys_lint_probe`, by `rake dylint`, which fails unless the
5
+ //! lints report exactly the lines that end in `//~`, each by the lints named
6
+ //! after it.
7
+ #![allow(dead_code, unsafe_code, clippy::all)]
8
+
9
+ /// A raising C call outside the protection, from a function with no proof
10
+ /// of the GVL (`raising_call_outside_protect`, `ffi_without_gvl_proof`).
11
+ fn raising() {
12
+ let _ = unsafe { rb_sys::rb_ary_new_capa(0) }; //~ ffi_without_gvl_proof raising_call_outside_protect
13
+ }
14
+
15
+ /// An `unsafe fn` of the crate's, whose contract is the GVL, from a safe
16
+ /// function with no proof (`ffi_without_gvl_proof`).
17
+ fn sys_contract() {
18
+ unsafe { crate::protect::forget_errinfo() } //~ ffi_without_gvl_proof
19
+ }
20
+
21
+ /// An `extern "C"` function whose body runs under no guard
22
+ /// (`unguarded_no_unwind_site`).
23
+ extern "C" fn unguarded() {} //~ unguarded_no_unwind_site
24
+
25
+ /// An integer `as` cast (`c_integer_outside_int`).
26
+ fn cast(n: i64) -> i32 {
27
+ n as i32 //~ c_integer_outside_int
28
+ }
29
+
30
+ /// A wrapper of a call that cannot raise, beside the ones that can
31
+ /// (`unraising_call_in_raw`): the `raising` module holds only calls that need
32
+ /// the protection.
33
+ #[rustfmt::skip] // keeps each marker on the line reported
34
+ mod raising {
35
+ unsafe fn rb_utf8_encoding(_: &crate::protect::Protected) -> *mut rb_sys::rb_encoding {
36
+ unsafe { rb_sys::rb_utf8_encoding() } //~ unraising_call_in_raw
37
+ }
38
+
39
+ unsafe fn rb_ary_new(_: &crate::protect::Protected) -> rb_sys::VALUE {
40
+ unsafe { rb_sys::rb_ary_new() }
41
+ }
42
+ }
43
+
44
+ /// Ruby's C API from a function holding no proof of the GVL
45
+ /// (`ffi_without_gvl_proof`) - and the same with one, which passes.
46
+ #[rustfmt::skip] // keeps each marker on the line reported
47
+ mod gvl_proof {
48
+ fn without_proof() -> bool {
49
+ unsafe { rb_sys::rb_block_given_p() != 0 } //~ ffi_without_gvl_proof
50
+ }
51
+
52
+ fn with_the_proof(_: &crate::value::Ruby) -> bool {
53
+ unsafe { rb_sys::rb_block_given_p() != 0 }
54
+ }
55
+
56
+ fn with_a_value(_: crate::value::Value) -> bool {
57
+ unsafe { rb_sys::rb_block_given_p() != 0 }
58
+ }
59
+
60
+ fn in_a_closure() -> bool {
61
+ (|| unsafe { rb_sys::rb_block_given_p() != 0 })() //~ ffi_without_gvl_proof
62
+ }
63
+ }
64
+
65
+ /// Which C functions raise (`raising_call_outside_protect`): one nobody has
66
+ /// classified is taken to raise - `rb_undef_alloc_func`, which a list of the
67
+ /// raising ones did not name - and one the table says raises nothing passes.
68
+ #[rustfmt::skip] // keeps each marker on the line reported
69
+ mod classified {
70
+ fn unclassified(_: &crate::value::Ruby) {
71
+ unsafe { rb_sys::rb_undef_alloc_func(rb_sys::rb_cObject) } //~ raising_call_outside_protect
72
+ }
73
+
74
+ fn classified(_: &crate::value::Ruby) -> bool {
75
+ unsafe { rb_sys::rb_block_given_p() != 0 }
76
+ }
77
+ }
78
+
79
+ /// This crate's value types on the heap (`ruby_value_on_heap`): it has no
80
+ /// `ReprValue`, so the lint knows them by name.
81
+ #[rustfmt::skip] // keeps each marker on the line reported
82
+ struct Kept {
83
+ values: Vec<crate::value::Value>, //~ ruby_value_on_heap
84
+ roots: Vec<crate::value::Root>, //~ ruby_value_on_heap
85
+ boxed: Box<crate::value::Value>, //~ ruby_value_on_heap
86
+ }
87
+
88
+ /// A protected call's `Caught` thrown away (`discarded_ruby_error`): a raise
89
+ /// or an exit in it would be lost before Nupur made it an `Error`.
90
+ #[rustfmt::skip] // keeps the marker on the line reported
91
+ fn discarded(_: &crate::value::Ruby) -> Option<()> {
92
+ unsafe { crate::protect::call(|_| ()) }.ok() //~ discarded_ruby_error
93
+ }