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
@@ -1,468 +1,131 @@
1
- //! LexStream - High-performance streaming lexer
1
+ //! `LexerKit::LexStream`: the tokens of one input, read in order with lookahead.
2
2
  //!
3
- //! This module implements the performance-critical parts of LexStream in Rust.
4
- //! Higher-level operations like token_name, text, and line_col are implemented in Ruby.
5
-
6
- use crate::types::CompiledProgram;
7
- use crate::vm;
8
- use rb_sys::*;
9
- use std::ptr;
10
-
11
- /// Define a Ruby method with no arguments
12
- macro_rules! define_ruby_method_noarg {
13
- ($class:expr, $name:expr, $fn:expr) => {
14
- rb_define_method(
15
- $class,
16
- $name.as_ptr(),
17
- Some(std::mem::transmute::<
18
- unsafe extern "C" fn(VALUE) -> VALUE,
19
- unsafe extern "C" fn() -> VALUE,
20
- >($fn)),
21
- 0,
22
- )
3
+ //! The tokens are collected when the stream is made (`CompiledProgram#create_rust_stream`), so a
4
+ //! stream needs no program afterwards. The input String stays in the object's slot for `#input`.
5
+ //! Higher-level operations (token names, text, line and column) are `LexerKit::Runner`'s, in Ruby.
6
+
7
+ use lexer_kit_core::types::CompiledProgram;
8
+ use lexer_kit_core::TokenBuffer;
9
+ use nupur::args::index_arg;
10
+ use nupur::method;
11
+ use nupur::rb::{prelude::*, Builtin, DataClass, Error, RModule, RString, RbConst, Ruby, Value};
12
+ use nupur::typed::{Birth, Payload, Typed, TypedType};
13
+ use std::cell::RefCell;
14
+
15
+ pub(crate) struct StreamBox {
16
+ /// Borrowed only inside one method, which runs no Ruby code meanwhile.
17
+ buffer: RefCell<TokenBuffer>,
18
+ /// The buffer's heap bytes, fixed when it is made: what `memsize` reports, read in the GC.
19
+ heap_bytes: usize,
20
+ }
21
+
22
+ impl Payload for StreamBox {
23
+ fn memsize(&self) -> usize {
24
+ std::mem::size_of::<Self>() + self.heap_bytes
25
+ }
26
+ }
27
+
28
+ /// Slot 0 is the input String.
29
+ static STREAM: TypedType<StreamBox, 1> = TypedType::base(c"LexerKit::LexStream");
30
+ static STREAM_CLASS: RbConst<DataClass> = RbConst::new();
31
+
32
+ /// A stream over the tokens `prog` finds in `input`.
33
+ pub(crate) fn create(ruby: &Ruby, prog: &CompiledProgram, input: RString) -> Result<Value, Error> {
34
+ let tokens = crate::lex(ruby, prog, input)?;
35
+ let buffer =
36
+ TokenBuffer::from_tokens(tokens).map_err(|e| Error::new(Builtin::RuntimeError, e))?;
37
+ let birth = Birth {
38
+ klass: STREAM_CLASS.defined(ruby)?,
39
+ data: StreamBox {
40
+ heap_bytes: buffer.heap_bytes(),
41
+ buffer: RefCell::new(buffer),
42
+ },
43
+ roots: [input],
23
44
  };
45
+ Ok(STREAM.wrap(ruby, birth)?.value())
24
46
  }
25
47
 
26
- /// Define a Ruby method with variable arguments
27
- macro_rules! define_ruby_method_vararg {
28
- ($class:expr, $name:expr, $fn:expr) => {
29
- rb_define_method(
30
- $class,
31
- $name.as_ptr(),
32
- Some(std::mem::transmute::<
33
- unsafe extern "C" fn(libc::c_int, *const VALUE, VALUE) -> VALUE,
34
- unsafe extern "C" fn() -> VALUE,
35
- >($fn)),
36
- -1,
37
- )
38
- };
48
+ fn stream(this: Value) -> Result<Typed<StreamBox, 1>, Error> {
49
+ STREAM.check(this)
39
50
  }
40
51
 
41
- const STRIDE: usize = 3;
42
-
43
- /// Token buffer using Vec for safe memory management
44
- ///
45
- /// Memory allocation and deallocation is handled safely by Vec.
46
- pub(crate) struct FastTokenBuffer {
47
- /// Flat array: [token_id, start, len] * count
48
- data: Vec<i32>,
49
- /// Number of tokens (data.len() / 3)
50
- count: usize,
51
- /// Current position
52
- index: usize,
52
+ /// A position from the buffer, where a negative one means there is no token.
53
+ fn position(n: i32) -> Option<i32> {
54
+ (n >= 0).then_some(n)
53
55
  }
54
56
 
55
- impl FastTokenBuffer {
56
- /// Create from collected tokens
57
- pub(crate) fn from_tokens(tokens: Vec<(u16, usize, usize)>) -> Result<Self, &'static str> {
58
- let count = tokens.len();
59
- let mut data = Vec::with_capacity(count * STRIDE);
60
-
61
- for (token_id, start, length) in tokens {
62
- if start > i32::MAX as usize || length > i32::MAX as usize {
63
- return Err("token position exceeds maximum value (input too large)");
64
- }
65
- data.push(token_id as i32);
66
- data.push(start as i32);
67
- data.push(length as i32);
68
- }
69
-
70
- Ok(Self { data, count, index: 0 })
71
- }
72
-
73
- #[inline(always)]
74
- pub(crate) fn eof(&self) -> bool {
75
- self.index >= self.count
76
- }
77
-
78
- #[inline(always)]
79
- pub(crate) fn token_id(&self) -> i32 {
80
- if self.index >= self.count {
81
- -1
82
- } else {
83
- self.data[self.index * STRIDE]
84
- }
85
- }
86
-
87
- #[inline(always)]
88
- pub(crate) fn start(&self) -> i32 {
89
- if self.index >= self.count {
90
- -1
91
- } else {
92
- self.data[self.index * STRIDE + 1]
93
- }
94
- }
95
-
96
- #[inline(always)]
97
- pub(crate) fn len(&self) -> i32 {
98
- if self.index >= self.count {
99
- -1
100
- } else {
101
- self.data[self.index * STRIDE + 2]
102
- }
103
- }
104
-
105
- #[inline(always)]
106
- pub(crate) fn peek_token_id(&self, n: usize) -> i32 {
107
- let i = self.index + n;
108
- if i >= self.count {
109
- -1
110
- } else {
111
- self.data[i * STRIDE]
112
- }
113
- }
114
-
115
- #[inline(always)]
116
- pub(crate) fn peek_start(&self, n: usize) -> i32 {
117
- let i = self.index + n;
118
- if i >= self.count {
119
- -1
120
- } else {
121
- self.data[i * STRIDE + 1]
122
- }
123
- }
124
-
125
- #[inline(always)]
126
- pub(crate) fn peek_len(&self, n: usize) -> i32 {
127
- let i = self.index + n;
128
- if i >= self.count {
129
- -1
130
- } else {
131
- self.data[i * STRIDE + 2]
132
- }
133
- }
134
-
135
- #[inline(always)]
136
- pub(crate) fn advance(&mut self) {
137
- if self.index < self.count {
138
- self.index += 1;
139
- }
140
- }
141
-
142
- /// Get total number of tokens (for testing)
143
- #[cfg(test)]
144
- pub(crate) fn count(&self) -> usize {
145
- self.count
146
- }
147
-
148
- /// Get current index (for testing)
149
- #[cfg(test)]
150
- pub(crate) fn index(&self) -> usize {
151
- self.index
57
+ /// The optional lookahead `n` of `peek_*` (default 1).
58
+ fn lookahead(args: &[Value]) -> Result<usize, Error> {
59
+ match args {
60
+ [] => Ok(1),
61
+ [n] => usize::try_from(index_arg(*n)?)
62
+ .map_err(|_| Error::new(Builtin::ArgumentError, "offset must be non-negative")),
63
+ _ => Err(nupur::args::arity_error(args.len(), 0, Some(1))),
152
64
  }
153
65
  }
154
66
 
155
- // No manual Drop needed - Vec handles memory deallocation automatically
156
-
157
- // ============================================================================
158
- // LexStream - Minimal Rust structure for fast VM execution
159
- // ============================================================================
160
-
161
- /// LexStream holds token buffer. Higher-level state is managed in Ruby.
162
- #[repr(C)]
163
- pub struct LexStream {
164
- buffer: FastTokenBuffer,
67
+ /// `#eof?`
68
+ fn eof(_: &Ruby, this: Value) -> Result<bool, Error> {
69
+ Ok(stream(this)?.data().buffer.borrow().eof())
165
70
  }
166
71
 
167
- // ============================================================================
168
- // Ruby TypedData integration
169
- // ============================================================================
170
-
171
- static mut LEX_STREAM_CLASS: VALUE = 0;
172
- static mut LEX_STREAM_DATA_TYPE: *const rb_data_type_t = ptr::null();
173
-
174
- // No mark function needed - LexStream no longer holds Ruby VALUEs
175
-
176
- unsafe extern "C" fn lex_stream_free(ptr: *mut libc::c_void) {
177
- if !ptr.is_null() {
178
- let _ = Box::from_raw(ptr as *mut LexStream);
179
- }
72
+ /// `#advance`: moves to the next token. Returns self.
73
+ fn advance(_: &Ruby, this: Value) -> Result<Value, Error> {
74
+ stream(this)?.data().buffer.borrow_mut().advance();
75
+ Ok(this)
180
76
  }
181
77
 
182
- unsafe extern "C" fn lex_stream_size(ptr: *const libc::c_void) -> size_t {
183
- if ptr.is_null() {
184
- 0
185
- } else {
186
- let stream = &*(ptr as *const LexStream);
187
- (std::mem::size_of::<LexStream>()
188
- + stream.buffer.data.capacity() * std::mem::size_of::<i32>()) as size_t
189
- }
78
+ /// `#token_id`: the current token's ID, or nil at the end.
79
+ fn token_id(_: &Ruby, this: Value) -> Result<Option<i32>, Error> {
80
+ Ok(position(stream(this)?.data().buffer.borrow().token_id()))
190
81
  }
191
82
 
192
- #[inline(always)]
193
- unsafe fn get_stream(obj: VALUE) -> *mut LexStream {
194
- RTYPEDDATA_GET_DATA(obj) as *mut LexStream
83
+ /// `#start`: the current token's byte offset, or nil at the end.
84
+ fn start(_: &Ruby, this: Value) -> Result<Option<i32>, Error> {
85
+ Ok(position(stream(this)?.data().buffer.borrow().start()))
195
86
  }
196
87
 
197
- // ============================================================================
198
- // Thread-local storage for passing program between magnus and rb-sys
199
- // ============================================================================
200
-
201
- thread_local! {
202
- static CURRENT_PROGRAM: std::cell::RefCell<*const CompiledProgram> = const { std::cell::RefCell::new(ptr::null()) };
88
+ /// `#len`: the current token's length in bytes, or nil at the end.
89
+ fn len(_: &Ruby, this: Value) -> Result<Option<i32>, Error> {
90
+ Ok(position(stream(this)?.data().buffer.borrow().len()))
203
91
  }
204
92
 
205
- pub fn set_current_program(prog: *const CompiledProgram) {
206
- CURRENT_PROGRAM.with(|p| {
207
- *p.borrow_mut() = prog;
208
- });
93
+ /// `#input`: the String the stream was made from.
94
+ fn input(_: &Ruby, this: Value) -> Result<Value, Error> {
95
+ Ok(stream(this)?.root::<0>())
209
96
  }
210
97
 
211
- fn take_current_program() -> *const CompiledProgram {
212
- CURRENT_PROGRAM.with(|p| {
213
- let ptr = *p.borrow();
214
- *p.borrow_mut() = ptr::null(); // Clear after taking
215
- ptr
216
- })
98
+ /// `#peek_token_id(n = 1)`: the ID of the token `n` ahead, or nil past the end.
99
+ fn peek_token_id(_: &Ruby, this: Value, args: &[Value]) -> Result<Option<i32>, Error> {
100
+ let n = lookahead(args)?;
101
+ Ok(position(
102
+ stream(this)?.data().buffer.borrow().peek_token_id(n),
103
+ ))
217
104
  }
218
105
 
219
- // ============================================================================
220
- // Ruby method implementations
221
- // ============================================================================
222
-
223
- /// LexStream.create(program, input) -> LexStream
224
- ///
225
- /// SAFETY: This method requires CURRENT_PROGRAM to be set via set_current_program()
226
- /// before calling. It is intended to be called only from CompiledProgram#stream.
227
- /// Direct calls will fail with an error.
228
- unsafe extern "C" fn lex_stream_create(
229
- _klass: VALUE,
230
- program: VALUE,
231
- input: VALUE,
232
- ) -> VALUE {
233
- // Take the compiled program from thread-local (clears it to prevent reuse)
234
- let prog_ptr = take_current_program();
235
- if prog_ptr.is_null() {
236
- rb_raise(
237
- rb_eArgError,
238
- c"LexStream.create must be called via CompiledProgram#stream".as_ptr(),
239
- );
240
- }
241
-
242
- // Get input bytes
243
- let input_ptr = rb_string_value_ptr(&input as *const _ as *mut _);
244
- let input_len = RSTRING_LEN(input) as usize;
245
- let bytes = std::slice::from_raw_parts(input_ptr as *const u8, input_len);
246
-
247
- // Collect tokens using VM
248
- let prog = &*prog_ptr;
249
- let tokens = match vm::collect_tokens(prog, bytes) {
250
- Ok(t) => t,
251
- Err(msg) => {
252
- let err_msg = std::ffi::CString::new(msg)
253
- .unwrap_or_else(|_| std::ffi::CString::new("VM error").unwrap());
254
- rb_raise(rb_eRuntimeError, err_msg.as_ptr());
255
- unreachable!()
256
- }
257
- };
258
-
259
- // Create buffer
260
- let buffer = match FastTokenBuffer::from_tokens(tokens) {
261
- Ok(b) => b,
262
- Err(_msg) => {
263
- rb_raise(rb_eRuntimeError, c"Lexer execution failed".as_ptr());
264
- unreachable!()
265
- }
266
- };
267
-
268
- // Create LexStream (minimal Rust struct)
269
- let stream = Box::new(LexStream { buffer });
270
- let stream_ptr = Box::into_raw(stream);
271
-
272
- let obj = rb_data_typed_object_wrap(
273
- LEX_STREAM_CLASS,
274
- stream_ptr as *mut libc::c_void,
275
- LEX_STREAM_DATA_TYPE,
276
- );
277
-
278
- // Get token_names from program
279
- let token_names = rb_funcall(program, rb_intern(c"token_names".as_ptr()), 0);
280
-
281
- // Set instance variables directly (avoids rb_funcall overhead)
282
- rb_ivar_set(obj, rb_intern(c"@input".as_ptr()), input);
283
- rb_ivar_set(obj, rb_intern(c"@token_names".as_ptr()), token_names);
284
-
285
- obj
106
+ /// `#peek_start(n = 1)`
107
+ fn peek_start(_: &Ruby, this: Value, args: &[Value]) -> Result<Option<i32>, Error> {
108
+ let n = lookahead(args)?;
109
+ Ok(position(stream(this)?.data().buffer.borrow().peek_start(n)))
286
110
  }
287
111
 
288
- /// eof? -> bool
289
- unsafe extern "C" fn lex_stream_eof(slf: VALUE) -> VALUE {
290
- let stream = get_stream(slf);
291
- if (*stream).buffer.eof() {
292
- Qtrue as VALUE
293
- } else {
294
- Qfalse as VALUE
295
- }
112
+ /// `#peek_len(n = 1)`
113
+ fn peek_len(_: &Ruby, this: Value, args: &[Value]) -> Result<Option<i32>, Error> {
114
+ let n = lookahead(args)?;
115
+ Ok(position(stream(this)?.data().buffer.borrow().peek_len(n)))
296
116
  }
297
117
 
298
- /// advance -> self
299
- unsafe extern "C" fn lex_stream_advance(slf: VALUE) -> VALUE {
300
- let stream = get_stream(slf);
301
- (*stream).buffer.advance();
302
- slf
303
- }
304
-
305
- /// token_id -> Integer or nil
306
- unsafe extern "C" fn lex_stream_token_id(slf: VALUE) -> VALUE {
307
- let stream = get_stream(slf);
308
- let id = (*stream).buffer.token_id();
309
- if id < 0 {
310
- Qnil as VALUE
311
- } else {
312
- rb_int2inum(id as isize)
313
- }
314
- }
315
-
316
- /// input -> String
317
- unsafe extern "C" fn lex_stream_input(slf: VALUE) -> VALUE {
318
- rb_ivar_get(slf, rb_intern(c"@input".as_ptr()))
319
- }
320
-
321
- /// start -> Integer or nil
322
- unsafe extern "C" fn lex_stream_start(slf: VALUE) -> VALUE {
323
- let stream = get_stream(slf);
324
- let s = (*stream).buffer.start();
325
- if s < 0 {
326
- Qnil as VALUE
327
- } else {
328
- rb_int2inum(s as isize)
329
- }
330
- }
331
-
332
- /// len -> Integer or nil
333
- unsafe extern "C" fn lex_stream_len(slf: VALUE) -> VALUE {
334
- let stream = get_stream(slf);
335
- let l = (*stream).buffer.len();
336
- if l < 0 {
337
- Qnil as VALUE
338
- } else {
339
- rb_int2inum(l as isize)
340
- }
341
- }
342
-
343
- /// peek_token_id(n = 1) -> Integer or nil
344
- unsafe extern "C" fn lex_stream_peek_token_id(argc: libc::c_int, argv: *const VALUE, slf: VALUE) -> VALUE {
345
- let n = if argc == 0 {
346
- 1
347
- } else {
348
- let n_val = rb_num2long(*argv);
349
- if n_val < 0 {
350
- rb_raise(rb_eArgError, c"offset must be non-negative".as_ptr());
351
- unreachable!()
352
- }
353
- n_val as usize
354
- };
355
-
356
- let stream = get_stream(slf);
357
- let id = (*stream).buffer.peek_token_id(n);
358
- if id < 0 {
359
- Qnil as VALUE
360
- } else {
361
- rb_int2inum(id as isize)
362
- }
363
- }
364
-
365
- /// peek_start(n = 1) -> Integer or nil
366
- unsafe extern "C" fn lex_stream_peek_start(argc: libc::c_int, argv: *const VALUE, slf: VALUE) -> VALUE {
367
- let n = if argc == 0 {
368
- 1
369
- } else {
370
- let n_val = rb_num2long(*argv);
371
- if n_val < 0 {
372
- rb_raise(rb_eArgError, c"offset must be non-negative".as_ptr());
373
- unreachable!()
374
- }
375
- n_val as usize
376
- };
377
-
378
- let stream = get_stream(slf);
379
- let s = (*stream).buffer.peek_start(n);
380
- if s < 0 {
381
- Qnil as VALUE
382
- } else {
383
- rb_int2inum(s as isize)
384
- }
385
- }
386
-
387
- /// peek_len(n = 1) -> Integer or nil
388
- unsafe extern "C" fn lex_stream_peek_len(argc: libc::c_int, argv: *const VALUE, slf: VALUE) -> VALUE {
389
- let n = if argc == 0 {
390
- 1
391
- } else {
392
- let n_val = rb_num2long(*argv);
393
- if n_val < 0 {
394
- rb_raise(rb_eArgError, c"offset must be non-negative".as_ptr());
395
- unreachable!()
396
- }
397
- n_val as usize
398
- };
399
-
400
- let stream = get_stream(slf);
401
- let l = (*stream).buffer.peek_len(n);
402
- if l < 0 {
403
- Qnil as VALUE
404
- } else {
405
- rb_int2inum(l as isize)
406
- }
407
- }
408
-
409
- // ============================================================================
410
- // Initialization
411
- // ============================================================================
412
-
413
- pub fn init_lex_stream() {
414
- unsafe {
415
- let data_type = Box::new(rb_data_type_t {
416
- wrap_struct_name: c"LexerKit::LexStream".as_ptr(),
417
- function: rb_data_type_struct__bindgen_ty_1 {
418
- dmark: None, // No Ruby VALUEs to mark
419
- dfree: Some(lex_stream_free),
420
- dsize: Some(lex_stream_size),
421
- dcompact: None,
422
- reserved: [ptr::null_mut(); 1],
423
- },
424
- parent: ptr::null(),
425
- data: ptr::null_mut(),
426
- flags: 0,
427
- });
428
- LEX_STREAM_DATA_TYPE = Box::into_raw(data_type);
429
-
430
- let lexer_kit_id = rb_intern(c"LexerKit".as_ptr());
431
- let lexer_kit = if rb_const_defined(rb_cObject, lexer_kit_id) != 0 {
432
- rb_const_get(rb_cObject, lexer_kit_id)
433
- } else {
434
- rb_define_module(c"LexerKit".as_ptr())
435
- };
436
-
437
- LEX_STREAM_CLASS = rb_define_class_under(
438
- lexer_kit,
439
- c"LexStream".as_ptr(),
440
- rb_cObject,
441
- );
442
-
443
- rb_undef_alloc_func(LEX_STREAM_CLASS);
444
-
445
- // Class method
446
- rb_define_singleton_method(
447
- LEX_STREAM_CLASS,
448
- c"create".as_ptr(),
449
- Some(std::mem::transmute::<
450
- unsafe extern "C" fn(VALUE, VALUE, VALUE) -> VALUE,
451
- unsafe extern "C" fn() -> VALUE,
452
- >(lex_stream_create)),
453
- 2,
454
- );
455
-
456
- // Instance methods (performance-critical, kept in Rust)
457
- define_ruby_method_noarg!(LEX_STREAM_CLASS, c"eof?", lex_stream_eof);
458
- define_ruby_method_noarg!(LEX_STREAM_CLASS, c"advance", lex_stream_advance);
459
- define_ruby_method_noarg!(LEX_STREAM_CLASS, c"token_id", lex_stream_token_id);
460
- define_ruby_method_noarg!(LEX_STREAM_CLASS, c"start", lex_stream_start);
461
- define_ruby_method_noarg!(LEX_STREAM_CLASS, c"len", lex_stream_len);
462
- define_ruby_method_noarg!(LEX_STREAM_CLASS, c"input", lex_stream_input);
463
-
464
- define_ruby_method_vararg!(LEX_STREAM_CLASS, c"peek_token_id", lex_stream_peek_token_id);
465
- define_ruby_method_vararg!(LEX_STREAM_CLASS, c"peek_start", lex_stream_peek_start);
466
- define_ruby_method_vararg!(LEX_STREAM_CLASS, c"peek_len", lex_stream_peek_len);
467
- }
118
+ pub(crate) fn init(ruby: &Ruby, lexer_kit: RModule) -> Result<(), Error> {
119
+ let class = lexer_kit.define_data_class(ruby, "LexStream", None)?;
120
+ STREAM_CLASS.set(class)?;
121
+ class.define_method("eof?", method!(eof, 0))?;
122
+ class.define_method("advance", method!(advance, 0))?;
123
+ class.define_method("token_id", method!(token_id, 0))?;
124
+ class.define_method("start", method!(start, 0))?;
125
+ class.define_method("len", method!(len, 0))?;
126
+ class.define_method("input", method!(input, 0))?;
127
+ class.define_method("peek_token_id", method!(peek_token_id, -1))?;
128
+ class.define_method("peek_start", method!(peek_start, -1))?;
129
+ class.define_method("peek_len", method!(peek_len, -1))?;
130
+ Ok(())
468
131
  }