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
@@ -1,248 +1,233 @@
1
- //! LexerKit Rust Extension
1
+ //! LexerKit's Ruby native extension: runs compiled lexer programs on `lexer_kit_core`'s VM.
2
2
  //!
3
- //! High-performance VM for executing compiled lexer programs.
4
-
5
- mod deserializer;
6
- #[cfg(not(test))]
7
- mod dfa;
8
- #[cfg(test)]
9
- pub mod dfa; // テスト時は公開
10
- #[cfg(not(test))]
3
+ //! Everything that touches Ruby goes through Nupur (vendor/nupur, a copy of Makiri's binding
4
+ //! layer). Two kinds of objects are wrapped, and neither payload holds a Ruby value:
5
+ //!
6
+ //! - `LexerKit::IR::RustHandle`: a program decoded from its binary (`IR::Serializer`). A
7
+ //! `CompiledProgram` keeps its handle in a hidden instance variable.
8
+ //! - `LexerKit::LexStream`: the tokens of one input, read in order with lookahead. It keeps the
9
+ //! input String alive in its slot.
10
+ //!
11
+ //! The rules at the boundary:
12
+ //!
13
+ //! - The extension calls no Ruby method. It runs one block, `lowlevel_each`'s
14
+ //! (`each_rust_native`), after the tokens are collected, so nothing is borrowed meanwhile.
15
+ //! `tokenize` takes the tokens as one flat Array (`lex_rust_native`) and yields nothing.
16
+ //! - The VM runs no Ruby code. A long input is copied and lexed with the GVL released.
17
+ //! - A panic becomes `LexerKit::InternalError`, a child of `Exception` that `rescue => e` does
18
+ //! not catch.
19
+
11
20
  mod fast_stream;
12
- #[cfg(test)]
13
- pub mod fast_stream; // テスト時は公開
14
- #[cfg(not(test))]
15
- mod opcodes;
16
- #[cfg(test)]
17
- pub mod opcodes; // テスト時は公開
18
- #[cfg(not(test))]
19
- mod trie;
20
- #[cfg(test)]
21
- pub mod trie; // テスト時は公開
22
- #[cfg(not(test))]
23
- mod types;
24
- #[cfg(test)]
25
- pub mod types; // テスト時は公開
26
- #[cfg(not(test))]
27
- mod vm;
28
- #[cfg(test)]
29
- pub mod vm; // テスト時は公開
30
-
31
- #[cfg(test)]
32
- mod safety_test;
33
-
34
- use magnus::{
35
- function, method, prelude::*, Error, IntoValue, RArray, RHash, RString, Ruby, TryConvert, Value,
21
+
22
+ use lexer_kit_core::types::CompiledProgram;
23
+ use lexer_kit_core::vm;
24
+ use nupur::args::string_arg;
25
+ use nupur::method;
26
+ use nupur::rb::object::{ivar_get, ivar_set};
27
+ use nupur::rb::{
28
+ prelude::*, Builtin, DataClass, Error, ExceptionClass, HiddenId, IntoValue, RArray, RModule,
29
+ RString, RbConst, Ruby, Value,
36
30
  };
37
- use std::cell::RefCell;
38
- use types::CompiledProgram;
31
+ use nupur::typed::{Birth, Payload, Typed, TypedType};
32
+ use std::sync::OnceLock;
39
33
 
40
- /// Wrapper for CompiledProgram to make it shareable with Ruby
41
- #[magnus::wrap(class = "LexerKit::IR::RustHandle", free_immediately, size)]
42
- struct RustHandle {
43
- prog: RefCell<CompiledProgram>,
34
+ /// A program decoded from its binary.
35
+ pub(crate) struct ProgramBox {
36
+ prog: CompiledProgram,
44
37
  }
45
38
 
46
- impl RustHandle {
47
- /// Load program from Ruby data hash
48
- fn load_from_ruby(rb_data: RHash) -> Result<Self, Error> {
49
- let prog = deserializer::parse_ruby_data(rb_data)?;
50
- Ok(Self {
51
- prog: RefCell::new(prog),
52
- })
53
- }
39
+ impl Payload for ProgramBox {}
54
40
 
55
- /// Tokenize input using the VM and yield tokens
56
- fn lex_native(&self, rb_bytes: RString) -> Result<RArray, Error> {
57
- let ruby = Ruby::get().unwrap();
58
- let bytes = unsafe { rb_bytes.as_slice() };
59
- let prog = self.prog.borrow();
60
-
61
- let tokens = vm::collect_tokens(&prog, bytes)
62
- .map_err(|e| Error::new(ruby.exception_runtime_error(), e))?;
63
-
64
- let result = ruby.ary_new_capa(tokens.len());
65
- for (token_id, start, length) in tokens {
66
- let token = ruby.ary_new_from_values(&[
67
- ruby.into_value(token_id),
68
- ruby.into_value(start),
69
- ruby.into_value(length),
70
- ]);
71
- result.push(token)?;
72
- }
41
+ static PROGRAM: TypedType<ProgramBox> = TypedType::base(c"LexerKit::IR::RustHandle");
42
+ static PROGRAM_CLASS: RbConst<DataClass> = RbConst::new();
73
43
 
74
- Ok(result)
75
- }
44
+ /// `LexerKit::VMError`, defined in Ruby: the VM stopped on an error.
45
+ static VM_ERROR: RbConst<ExceptionClass> = RbConst::new();
46
+ /// `LexerKit::InvalidBinaryError`, defined in Ruby: the program binary did not decode.
47
+ static INVALID_BINARY: RbConst<ExceptionClass> = RbConst::new();
76
48
 
77
- /// Tokenize input and yield each token to a block
78
- fn lex_native_block(&self, rb_bytes: RString) -> Result<Value, Error> {
79
- let ruby = Ruby::get().unwrap();
80
- let bytes = unsafe { rb_bytes.as_slice() };
81
- let prog = self.prog.borrow();
82
-
83
- let tokens = vm::collect_tokens(&prog, bytes)
84
- .map_err(|e| Error::new(ruby.exception_runtime_error(), e))?;
85
-
86
- for (token_id, start, length) in tokens {
87
- let args = (
88
- ruby.into_value(token_id),
89
- ruby.into_value(start),
90
- ruby.into_value(length),
91
- );
92
- let _: Value = ruby.yield_values(args)?;
93
- }
49
+ /// The hidden instance variable of a `CompiledProgram` that holds its `RustHandle`.
50
+ static HANDLE_IVAR: OnceLock<HiddenId> = OnceLock::new();
94
51
 
95
- Ok(ruby.qnil().as_value())
52
+ fn handle_ivar(ruby: &Ruby) -> Result<HiddenId, Error> {
53
+ if let Some(id) = HANDLE_IVAR.get() {
54
+ return Ok(*id);
96
55
  }
56
+ let id = HiddenId::intern(ruby, c"__lkt_rust__")?;
57
+ Ok(*HANDLE_IVAR.get_or_init(|| id))
58
+ }
97
59
 
60
+ /// The handle `load_rust_native` stored in `program`.
61
+ fn program_handle(ruby: &Ruby, program: Value) -> Result<Typed<ProgramBox, 0>, Error> {
62
+ let handle = ivar_get(program, handle_ivar(ruby)?);
63
+ if handle.is_nil() {
64
+ return Err(Error::new(
65
+ Builtin::RuntimeError,
66
+ "Rust native not loaded. Call load_rust_native first.",
67
+ ));
68
+ }
69
+ PROGRAM.check(handle)
98
70
  }
99
71
 
100
- /// Internal variable name for Rust handle (non-@ name, inaccessible from Ruby)
101
- static RUST_HANDLE_IVAR: &std::ffi::CStr = c"__lkt_rust__";
72
+ /// Inputs at least this long are copied and lexed with the GVL released, so other Ruby threads
73
+ /// run meanwhile. A shorter input is read in place: releasing and taking back the GVL would
74
+ /// cost more than lexing it.
75
+ const GVL_RELEASE_MIN_BYTES: usize = 64 * 1024;
76
+
77
+ /// The tokens of `input` as (token ID, start, length).
78
+ pub(crate) fn lex(
79
+ ruby: &Ruby,
80
+ prog: &CompiledProgram,
81
+ input: RString,
82
+ ) -> Result<Vec<(u16, usize, usize)>, Error> {
83
+ let tokens = if input.len() < GVL_RELEASE_MIN_BYTES {
84
+ input.with_bytes(|bytes| vm::collect_tokens(prog, bytes))
85
+ } else {
86
+ // A copy, not a loan: with the GVL released, another thread could change the String.
87
+ let bytes = nupur::string::read_bytes(input)?;
88
+ nupur::gvl::without_gvl(ruby, move || vm::collect_tokens(prog, &bytes))?
89
+ };
90
+ tokens.map_err(|e| Error::new(&VM_ERROR, e))
91
+ }
102
92
 
103
- /// RustNative module methods - added to CompiledProgram
104
- struct RustNative;
93
+ /// `CompiledProgram#load_rust_native(binary)`: decodes the program binary and keeps the result
94
+ /// in the program. Returns the program.
95
+ fn load_rust_native(ruby: &Ruby, this: Value, binary: Value) -> Result<Value, Error> {
96
+ let binary = string_arg(binary)?;
97
+ // A closure, not the function: nupur_lints checks what a body lent the bytes calls.
98
+ #[allow(clippy::redundant_closure)]
99
+ let prog = binary
100
+ .with_bytes(|bytes| lexer_kit_core::decode_program(bytes))
101
+ .map_err(|e| Error::new(&INVALID_BINARY, format_args!("{e}")))?;
102
+ let birth = Birth {
103
+ klass: PROGRAM_CLASS.defined(ruby)?,
104
+ data: ProgramBox { prog },
105
+ roots: [],
106
+ };
107
+ let handle = PROGRAM.wrap::<Value>(ruby, birth)?;
108
+ ivar_set(this, handle_ivar(ruby)?, handle.value())?;
109
+ Ok(this)
110
+ }
105
111
 
106
- impl RustNative {
107
- /// Load Rust native handle from Ruby data
108
- /// compiled_program.load_rust_native(data) -> self
109
- fn load_rust_native(rb_self: Value, rb_data: RHash) -> Result<Value, Error> {
110
- let ruby = Ruby::get().unwrap();
111
- let handle = RustHandle::load_from_ruby(rb_data)?;
112
+ /// `CompiledProgram#rust_native_loaded?`
113
+ fn rust_native_loaded(ruby: &Ruby, this: Value) -> Result<bool, Error> {
114
+ Ok(PROGRAM.is(ivar_get(this, handle_ivar(ruby)?)))
115
+ }
112
116
 
113
- // Store handle as internal variable (non-@ name)
114
- unsafe {
115
- let ivar_id = rb_sys::rb_intern(RUST_HANDLE_IVAR.as_ptr());
116
- let handle_value: rb_sys::VALUE = std::mem::transmute::<Value, rb_sys::VALUE>(handle.into_value_with(&ruby));
117
- rb_sys::rb_ivar_set(std::mem::transmute::<Value, rb_sys::VALUE>(rb_self), ivar_id, handle_value);
117
+ /// How many values `lex_rust_native` appends to its Array in one call.
118
+ const FLAT_CHUNK: usize = 3 * 64;
119
+
120
+ /// `CompiledProgram#lex_rust_native(bytes)`: the tokens of `bytes` as one flat Array,
121
+ /// `[token_id, start, length, token_id, start, length, ...]`.
122
+ fn lex_rust_native(ruby: &Ruby, this: Value, bytes: Value) -> Result<RArray, Error> {
123
+ let bytes = string_arg(bytes)?;
124
+ let handle = program_handle(ruby, this)?;
125
+ let tokens = lex(ruby, &handle.data().prog, bytes)?;
126
+
127
+ let flat = nupur::build::ary(ruby, tokens.len().saturating_mul(3))?;
128
+ // On the stack, where the GC sees the values until they are in the Array.
129
+ let mut chunk = [ruby.qnil(); FLAT_CHUNK];
130
+ let mut filled = 0;
131
+ for (token_id, start, length) in tokens {
132
+ chunk[filled] = u32::from(token_id).into_value(ruby)?;
133
+ chunk[filled + 1] = start.into_value(ruby)?;
134
+ chunk[filled + 2] = length.into_value(ruby)?;
135
+ filled += 3;
136
+ if filled == FLAT_CHUNK {
137
+ nupur::build::ary_cat(flat, &chunk)?;
138
+ filled = 0;
118
139
  }
119
-
120
- Ok(rb_self)
121
- }
122
-
123
- /// Check if Rust native handle is loaded
124
- fn rust_native_loaded(rb_self: Value) -> bool {
125
- let handle = unsafe {
126
- let ivar_id = rb_sys::rb_intern(RUST_HANDLE_IVAR.as_ptr());
127
- rb_sys::rb_ivar_get(std::mem::transmute::<Value, rb_sys::VALUE>(rb_self), ivar_id)
128
- };
129
- handle != rb_sys::Qnil as rb_sys::VALUE
130
- }
131
-
132
- /// Tokenize using Rust VM and yield to block
133
- fn lex_rust_native(rb_self: Value, rb_bytes: RString) -> Result<Value, Error> {
134
- let handle = Self::get_handle(rb_self)?;
135
- handle.lex_native_block(rb_bytes)
136
140
  }
141
+ nupur::build::ary_cat(flat, &chunk[..filled])?;
142
+ Ok(flat)
143
+ }
137
144
 
138
- /// Create a LexStream
139
- fn create_rust_stream(rb_self: Value, rb_bytes: RString) -> Result<Value, Error> {
140
- use magnus::IntoValue;
141
- let handle = Self::get_handle(rb_self)?;
142
- let prog = handle.prog.borrow();
143
- let ruby = Ruby::get().unwrap();
144
-
145
- // Set current program for LexStream to use
146
- fast_stream::set_current_program(&*prog as *const CompiledProgram);
147
-
148
- // Create LexStream directly using rb-sys
149
- let result = unsafe {
150
- let klass = rb_sys::rb_const_get(
151
- rb_sys::rb_const_get(
152
- rb_sys::rb_cObject,
153
- rb_sys::rb_intern(c"LexerKit".as_ptr()),
154
- ),
155
- rb_sys::rb_intern(c"LexStream".as_ptr()),
156
- );
157
- let program_value: rb_sys::VALUE = std::mem::transmute(rb_self);
158
- let input_value: rb_sys::VALUE = std::mem::transmute(rb_bytes.into_value_with(&ruby));
159
- rb_sys::rb_funcall(
160
- klass,
161
- rb_sys::rb_intern(c"create".as_ptr()),
162
- 2,
163
- program_value,
164
- input_value,
145
+ /// `CompiledProgram#each_rust_native(bytes)`: yields each token of `bytes` to the block as
146
+ /// `token_id, start, length`. Returns nil.
147
+ ///
148
+ /// The tokens are collected first, so nothing is borrowed while the block runs: the block may
149
+ /// lex again, or reload the program, and its exceptions and `break` come back as `Err`.
150
+ fn each_rust_native(ruby: &Ruby, this: Value, bytes: Value) -> Result<(), Error> {
151
+ let bytes = string_arg(bytes)?;
152
+ let handle = program_handle(ruby, this)?;
153
+ let tokens = lex(ruby, &handle.data().prog, bytes)?;
154
+ drop(handle);
155
+ for (token_id, start, length) in tokens {
156
+ let vals = [
157
+ u32::from(token_id).into_value(ruby)?,
158
+ start.into_value(ruby)?,
159
+ length.into_value(ruby)?,
160
+ ];
161
+ #[cfg_attr(
162
+ dylint_lib = "nupur_lints",
163
+ allow(
164
+ runs_callers_ruby,
165
+ reason = "lowlevel_each's block, called for each token"
165
166
  )
166
- };
167
-
168
- Ok(unsafe { std::mem::transmute::<rb_sys::VALUE, Value>(result) })
167
+ )]
168
+ nupur::rb::method::yield_values(ruby, vals)?;
169
169
  }
170
+ Ok(())
171
+ }
170
172
 
171
- /// Get handle from internal variable
172
- ///
173
- /// # Safety
174
- /// The returned reference is valid as long as `rb_self` is kept alive by Ruby's GC.
175
- /// Since this is called within Ruby method invocations where `rb_self` is rooted,
176
- /// the reference is guaranteed to be valid for the duration of the method call.
177
- ///
178
- /// Note: The lifetime is tied to magnus's TypedData wrapper, not truly 'static.
179
- /// Callers must not store this reference beyond the current method call.
180
- fn get_handle<'a>(rb_self: Value) -> Result<&'a RustHandle, Error> {
181
- let ruby = Ruby::get().unwrap();
182
- let handle_value = unsafe {
183
- let ivar_id = rb_sys::rb_intern(RUST_HANDLE_IVAR.as_ptr());
184
- rb_sys::rb_ivar_get(std::mem::transmute::<Value, rb_sys::VALUE>(rb_self), ivar_id)
185
- };
186
-
187
- if handle_value == rb_sys::Qnil as rb_sys::VALUE {
188
- return Err(Error::new(
189
- ruby.exception_runtime_error(),
190
- "Rust native not loaded. Call load_rust_native first.",
191
- ));
192
- }
173
+ /// `CompiledProgram#create_rust_stream(input)`: a `LexStream` over the tokens of `input`.
174
+ fn create_rust_stream(ruby: &Ruby, this: Value, input: Value) -> Result<Value, Error> {
175
+ let input = string_arg(input)?;
176
+ let handle = program_handle(ruby, this)?;
177
+ fast_stream::create(ruby, &handle.data().prog, input)
178
+ }
193
179
 
194
- // Convert VALUE back to RustHandle reference.
195
- // Safety: The handle is stored as an instance variable of rb_self.
196
- // Ruby's GC keeps rb_self alive during method calls, so the handle
197
- // is valid for the duration of the caller's use.
198
- let handle: &RustHandle = unsafe {
199
- let value: Value = std::mem::transmute(handle_value);
200
- TryConvert::try_convert(value)?
201
- };
180
+ fn check(ruby: &Ruby) -> Result<(), Error> {
181
+ nupur::abi::check_running_api("lexer_kit_rust", "rake compile")?;
182
+ nupur::abi::check_raise_state(ruby)?;
183
+ // A second copy (the versioned binary and a local build) is a LoadError, not a half-run init.
184
+ nupur::abi::check_undefined(ruby, &["LexerKit", "IR", "RustHandle"])
185
+ }
202
186
 
203
- Ok(handle)
204
- }
187
+ /// The exception class `LexerKit::<name>`, which lib/lexer_kit/errors.rb defines.
188
+ fn ruby_error(ruby: &Ruby, lexer_kit: RModule, name: &str) -> Result<ExceptionClass, Error> {
189
+ ExceptionClass::from_value(lexer_kit.const_get(ruby, name)?).ok_or_else(|| {
190
+ Error::new(
191
+ Builtin::TypeError,
192
+ format_args!("LexerKit::{name} is not an exception class"),
193
+ )
194
+ })
205
195
  }
206
196
 
207
- #[magnus::init]
208
197
  fn init(ruby: &Ruby) -> Result<(), Error> {
209
- // Define LexerKit module and IR submodule
210
198
  let lexer_kit = ruby.define_module("LexerKit")?;
211
- let ir = lexer_kit.define_module("IR")?;
199
+ let internal = lexer_kit.define_error("InternalError", ruby.exception_exception())?;
200
+ nupur::rb::error::INTERNAL_ERROR.set(internal)?;
201
+ VM_ERROR.set(ruby_error(ruby, lexer_kit, "VMError")?)?;
202
+ INVALID_BINARY.set(ruby_error(ruby, lexer_kit, "InvalidBinaryError")?)?;
212
203
 
213
- // Define RustHandle class (internal, not meant to be used directly)
214
- let rust_handle = ir.define_class("RustHandle", ruby.class_object())?;
215
- rust_handle
216
- .define_singleton_method("load_from_ruby", function!(RustHandle::load_from_ruby, 1))?;
217
- rust_handle.define_method("lex_native", method!(RustHandle::lex_native, 1))?;
218
- rust_handle.define_method("lex_native_block", method!(RustHandle::lex_native_block, 1))?;
219
-
220
- // Define RustNative module (to be included in CompiledProgram)
204
+ let ir = lexer_kit.define_module("IR")?;
205
+ let handle = ir.define_data_class(ruby, "RustHandle", None)?;
206
+ PROGRAM_CLASS.set(handle)?;
207
+
208
+ // Included into CompiledProgram, defined in Ruby (lib/lexer_kit/ir) before the extension is loaded.
209
+ let program = nupur::rb::RClass::from_value(ir.const_get(ruby, "CompiledProgram")?)
210
+ .ok_or_else(|| {
211
+ Error::new(
212
+ Builtin::TypeError,
213
+ "LexerKit::IR::CompiledProgram is not a class",
214
+ )
215
+ })?;
221
216
  let rust_native = ir.define_module("RustNative")?;
222
- rust_native.define_method("load_rust_native", method!(RustNative::load_rust_native, 1))?;
223
- rust_native.define_method(
224
- "rust_native_loaded?",
225
- method!(RustNative::rust_native_loaded, 0),
226
- )?;
227
- rust_native.define_method("lex_rust_native", method!(RustNative::lex_rust_native, 1))?;
228
- rust_native.define_method(
229
- "create_rust_stream",
230
- method!(RustNative::create_rust_stream, 1),
231
- )?;
232
-
233
- // Include RustNative into CompiledProgram if it exists
234
- let compiled_program = ir.const_get::<_, Value>("CompiledProgram");
235
- if let Ok(cp) = compiled_program {
236
- unsafe {
237
- rb_sys::rb_include_module(
238
- std::mem::transmute::<Value, rb_sys::VALUE>(cp),
239
- std::mem::transmute::<Value, rb_sys::VALUE>(rust_native.as_value()),
240
- );
241
- }
242
- }
243
-
244
- // Initialize LexStream class (rb-sys based, no RefCell overhead)
245
- fast_stream::init_lex_stream();
246
-
217
+ rust_native.define_method("load_rust_native", method!(load_rust_native, 1))?;
218
+ rust_native.define_method("rust_native_loaded?", method!(rust_native_loaded, 0))?;
219
+ rust_native.define_method("lex_rust_native", method!(lex_rust_native, 1))?;
220
+ rust_native.define_method("each_rust_native", method!(each_rust_native, 1))?;
221
+ rust_native.define_method("create_rust_stream", method!(create_rust_stream, 1))?;
222
+ program.include_module(rust_native)?;
223
+
224
+ fast_stream::init(ruby, lexer_kit)?;
247
225
  Ok(())
248
226
  }
227
+
228
+ #[no_mangle]
229
+ #[allow(non_snake_case)]
230
+ pub extern "C" fn Init_lexer_kit_rust() {
231
+ // SAFETY: Ruby calls `Init_lexer_kit_rust` on its thread, with the GVL held.
232
+ unsafe { nupur::rb::method::run_init(check, init) };
233
+ }
@@ -33,10 +33,16 @@ module LexerKit
33
33
  # Assign token IDs
34
34
  assign_token_ids
35
35
 
36
+ # Assign mode IDs in definition order, before any PUSH_MODE refers to one.
37
+ # The program lists mode offsets in compilation (definition) order, and the VM
38
+ # finds a mode by its position in that list, so the IDs must follow the same order.
39
+ @builder.mode_defs.each_key { |name| ensure_mode_id(name) }
40
+
36
41
  # Compile each mode
37
42
  @builder.mode_defs.each do |_name, mode_def|
38
43
  compile_mode(mode_def)
39
44
  end
45
+ check_modes_defined!
40
46
 
41
47
  # Add HALT at end
42
48
  emit(IR::Opcode::HALT)
@@ -113,7 +119,6 @@ module LexerKit
113
119
  end
114
120
 
115
121
  def compile_mode(mode_def)
116
- ensure_mode_id(mode_def.name)
117
122
  @modes[mode_def.name] = current_offset
118
123
 
119
124
  if mode_def.delimited
@@ -201,8 +206,8 @@ module LexerKit
201
206
  escape = token_def.escape
202
207
  escape_bytes = escape.b
203
208
  bytes = [
204
- close.bytesize,
205
- escape_bytes.bytesize
209
+ check_operand!(close.bytesize, IR::Limits::U16_MAX, "length of the delimiter of :#{token_def.name}"),
210
+ check_operand!(escape_bytes.bytesize, IR::Limits::U16_MAX, "length of the escape of :#{token_def.name}")
206
211
  ].pack("S>S>") + close.b + escape_bytes
207
212
 
208
213
  @constant_pool.add(bytes)
@@ -401,8 +406,8 @@ module LexerKit
401
406
  end
402
407
 
403
408
  def compile_regex_to_dfa(pattern)
404
- # Cache DFA by pattern source to avoid duplicate compilation
405
- cache_key = pattern.is_a?(Regexp) ? pattern.source : pattern
409
+ # Cache DFA by pattern to avoid duplicate compilation; a Regexp's options (e.g. /i) change its DFA
410
+ cache_key = pattern.is_a?(Regexp) ? [pattern.source, pattern.options] : pattern
406
411
  return @dfa_cache[cache_key] if @dfa_cache.key?(cache_key)
407
412
 
408
413
  dfa_id = @dfa_tables.size
@@ -430,9 +435,38 @@ module LexerKit
430
435
  end
431
436
 
432
437
  def emit(opcode, arg = 0)
438
+ check_operand!(arg, IR::Limits::U24_MAX, "operand of #{IR::Opcode.name(opcode)}")
433
439
  @instructions << IR::Instruction.new(opcode, arg)
434
440
  end
435
441
 
442
+ # A PUSH_MODE to a mode that is never compiled would have no offset, and the mode
443
+ # list of the program would no longer be in mode ID order.
444
+ def check_modes_defined!
445
+ undefined = @mode_names - @modes.keys
446
+ return if undefined.empty?
447
+
448
+ raise LexerKit::CompileError, "undefined mode #{undefined.map { |m| ":#{m}" }.join(', ')}"
449
+ end
450
+
451
+ # Raise a CompileError if an operand does not fit its field of the instruction.
452
+ # Without this the encoding would silently drop the high bits and the program
453
+ # would emit wrong tokens or jump to the wrong place.
454
+ def check_operand!(value, max, what)
455
+ return value if value <= max
456
+
457
+ raise LexerKit::CompileError,
458
+ "#{what} is #{value}, but the program binary allows at most #{max} (docs/ir-spec.md §3)"
459
+ end
460
+
461
+ # (upper << 14) | lower, the packed argument of DFA_RUN_IF_MATCH, MATCH_LITERAL_OR_JUMP,
462
+ # EMIT_AND_JUMP, SET_MATCH and LITERAL_TRIE_COMMIT.
463
+ def packed_arg(upper, upper_what, lower)
464
+ check_operand!(upper, IR::Limits::PACKED_UPPER_MAX, upper_what)
465
+ check_operand!(lower, IR::Limits::PACKED_LOWER_MAX,
466
+ "jump target (an instruction offset; the program has #{@instructions.size} instructions)")
467
+ (upper << IR::Limits::PACKED_LOWER_BITS) | lower
468
+ end
469
+
436
470
  def emit_jump(opcode, label)
437
471
  @pending_jumps << [@instructions.size, label]
438
472
  emit(opcode, 0) # Placeholder
@@ -447,35 +481,35 @@ module LexerKit
447
481
  # Encoding: (dfa_id << 14) | fail_target (10+14 bits)
448
482
  def emit_dfa_run_if_match(dfa_id, fail_label)
449
483
  @pending_dfa_run_if_match << [@instructions.size, dfa_id, fail_label]
450
- emit(IR::Opcode::DFA_RUN_IF_MATCH, dfa_id << 14) # Placeholder with dfa_id in upper bits
484
+ emit(IR::Opcode::DFA_RUN_IF_MATCH, 0) # Placeholder: packed in resolve_jumps
451
485
  end
452
486
 
453
487
  # Emit MATCH_LITERAL_OR_JUMP with embedded fail_target
454
488
  # Encoding: (const_id << 14) | fail_target (10+14 bits)
455
489
  def emit_match_literal_or_jump(const_id, fail_label)
456
490
  @pending_match_literal_or_jump << [@instructions.size, const_id, fail_label]
457
- emit(IR::Opcode::MATCH_LITERAL_OR_JUMP, const_id << 14) # Placeholder with const_id in upper bits
491
+ emit(IR::Opcode::MATCH_LITERAL_OR_JUMP, 0) # Placeholder: packed in resolve_jumps
458
492
  end
459
493
 
460
494
  # Emit EMIT_AND_JUMP with embedded jump_target
461
495
  # Encoding: (token_id << 14) | jump_target (10+14 bits)
462
496
  def emit_emit_and_jump(token_id, jump_target)
463
497
  @pending_emit_and_jump << [@instructions.size, token_id, jump_target]
464
- emit(IR::Opcode::EMIT_AND_JUMP, token_id << 14) # Placeholder with token_id in upper bits
498
+ emit(IR::Opcode::EMIT_AND_JUMP, 0) # Placeholder: packed in resolve_jumps
465
499
  end
466
500
 
467
501
  # Emit SET_MATCH with embedded order and action_label
468
502
  # Encoding: (order << 14) | action_ip (10+14 bits)
469
503
  def emit_set_match(order, action_label)
470
504
  @pending_set_match << [@instructions.size, order, action_label]
471
- emit(IR::Opcode::SET_MATCH, order << 14) # Placeholder with order in upper bits
505
+ emit(IR::Opcode::SET_MATCH, 0) # Placeholder: packed in resolve_jumps
472
506
  end
473
507
 
474
508
  # Emit LITERAL_TRIE_COMMIT with embedded const_id and fail_target
475
509
  # Encoding: (const_id << 14) | fail_target (10+14 bits)
476
510
  def emit_literal_trie_commit(const_id, fail_label)
477
511
  @pending_literal_trie_commit << [@instructions.size, const_id, fail_label]
478
- emit(IR::Opcode::LITERAL_TRIE_COMMIT, const_id << 14) # Placeholder with const_id in upper bits
512
+ emit(IR::Opcode::LITERAL_TRIE_COMMIT, 0) # Placeholder: packed in resolve_jumps
479
513
  end
480
514
 
481
515
  def add_literal_trie(literals, order_map, action_label_map)
@@ -540,6 +574,7 @@ module LexerKit
540
574
  raise LexerKit::CompileError, "unresolved label #{label}" unless offset
541
575
 
542
576
  instr = @instructions[instr_idx]
577
+ check_operand!(offset, IR::Limits::U24_MAX, "jump target of #{IR::Opcode.name(instr.opcode)}")
543
578
  @instructions[instr_idx] = IR::Instruction.new(instr.opcode, offset)
544
579
  end
545
580
 
@@ -549,7 +584,7 @@ module LexerKit
549
584
  fail_offset = @labels[fail_label]
550
585
  raise LexerKit::CompileError, "unresolved label #{fail_label}" unless fail_offset
551
586
 
552
- arg = (dfa_id << 14) | fail_offset
587
+ arg = packed_arg(dfa_id, "DFA table ID", fail_offset)
553
588
  @instructions[instr_idx] = IR::Instruction.new(IR::Opcode::DFA_RUN_IF_MATCH, arg)
554
589
  end
555
590
 
@@ -559,7 +594,7 @@ module LexerKit
559
594
  fail_offset = @labels[fail_label]
560
595
  raise LexerKit::CompileError, "unresolved label #{fail_label}" unless fail_offset
561
596
 
562
- arg = (const_id << 14) | fail_offset
597
+ arg = packed_arg(const_id, "constant ID", fail_offset)
563
598
  @instructions[instr_idx] = IR::Instruction.new(IR::Opcode::MATCH_LITERAL_OR_JUMP, arg)
564
599
  end
565
600
 
@@ -567,7 +602,7 @@ module LexerKit
567
602
  # Encoding: (token_id << 14) | jump_target (10+14 bits)
568
603
  # Note: jump_target is a direct offset (loop_start), not a label
569
604
  @pending_emit_and_jump.each do |instr_idx, token_id, jump_target|
570
- arg = (token_id << 14) | jump_target
605
+ arg = packed_arg(token_id, "token ID of :#{@token_names[token_id]}", jump_target)
571
606
  @instructions[instr_idx] = IR::Instruction.new(IR::Opcode::EMIT_AND_JUMP, arg)
572
607
  end
573
608
 
@@ -577,7 +612,7 @@ module LexerKit
577
612
  action_offset = @labels[action_label]
578
613
  raise LexerKit::CompileError, "unresolved label #{action_label}" unless action_offset
579
614
 
580
- arg = (order << 14) | action_offset
615
+ arg = packed_arg(order, "position of a token in its mode", action_offset)
581
616
  @instructions[instr_idx] = IR::Instruction.new(IR::Opcode::SET_MATCH, arg)
582
617
  end
583
618
 
@@ -587,7 +622,7 @@ module LexerKit
587
622
  fail_offset = @labels[fail_label]
588
623
  raise LexerKit::CompileError, "unresolved label #{fail_label}" unless fail_offset
589
624
 
590
- arg = (const_id << 14) | fail_offset
625
+ arg = packed_arg(const_id, "constant ID", fail_offset)
591
626
  @instructions[instr_idx] = IR::Instruction.new(IR::Opcode::LITERAL_TRIE_COMMIT, arg)
592
627
  end
593
628
  end