lexer_kit 0.6.0-x86_64-linux → 0.7.0-x86_64-linux

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 (39) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +7 -3
  3. data/lib/lexer_kit/builder/compiler.rb +50 -15
  4. data/lib/lexer_kit/builder/conflict_detector.rb +18 -20
  5. data/lib/lexer_kit/builder/validator.rb +45 -0
  6. data/lib/lexer_kit/builder.rb +34 -7
  7. data/lib/lexer_kit/cli/commands.rb +17 -7
  8. data/lib/lexer_kit/core/source.rb +3 -2
  9. data/lib/lexer_kit/debug/disassembler.rb +0 -2
  10. data/lib/lexer_kit/dfa/dfa_builder.rb +1 -1
  11. data/lib/lexer_kit/dfa/dfa_minimizer.rb +2 -2
  12. data/lib/lexer_kit/dfa/regex_ast.rb +4 -0
  13. data/lib/lexer_kit/dfa/regex_parser.rb +41 -8
  14. data/lib/lexer_kit/errors.rb +2 -2
  15. data/lib/lexer_kit/format/lkb1.rb +3 -3
  16. data/lib/lexer_kit/format/lkt1.rb +3 -1
  17. data/lib/lexer_kit/format.rb +4 -4
  18. data/lib/lexer_kit/ir/compiled_program.rb +39 -26
  19. data/lib/lexer_kit/ir/constant_pool.rb +33 -11
  20. data/lib/lexer_kit/ir/dfa_table.rb +9 -19
  21. data/lib/lexer_kit/ir/instruction.rb +3 -0
  22. data/lib/lexer_kit/ir/jump_table.rb +3 -13
  23. data/lib/lexer_kit/ir/keyword_table.rb +0 -9
  24. data/lib/lexer_kit/ir/limits.rb +48 -0
  25. data/lib/lexer_kit/ir/serializer.rb +69 -30
  26. data/lib/lexer_kit/ir.rb +1 -0
  27. data/lib/lexer_kit/trie.rb +1 -1
  28. data/lib/lexer_kit/version.rb +1 -1
  29. data/lib/lexer_kit.rb +20 -2
  30. data/lib/lexer_kit_rust/3.3/lexer_kit_rust.so +0 -0
  31. data/lib/lexer_kit_rust/3.4/lexer_kit_rust.so +0 -0
  32. data/lib/lexer_kit_rust/4.0/lexer_kit_rust.so +0 -0
  33. data/vendor/nupur/LICENSE +176 -0
  34. data/vendor/nupur/NOTICE +64 -0
  35. data/vendor/nupur/README.ja.md +150 -0
  36. data/vendor/nupur/README.md +257 -0
  37. data/vendor/nupur.sha256 +68 -0
  38. metadata +18 -6
  39. data/lib/lexer_kit_rust/lexer_kit_rust.so +0 -0
@@ -14,6 +14,13 @@ module LexerKit
14
14
  # Include AST types from RegexAST module
15
15
  include RegexAST
16
16
 
17
+ # Byte ranges of the class escapes \d, \w and \s (ASCII only)
18
+ CLASS_ESCAPES = {
19
+ "d" => [[0x30, 0x39]],
20
+ "w" => [[0x30, 0x39], [0x41, 0x5A], [0x61, 0x7A], [0x5F, 0x5F]],
21
+ "s" => [[0x09, 0x0D], [0x20, 0x20]]
22
+ }.freeze
23
+
17
24
  def initialize(source)
18
25
  @source = source.is_a?(Regexp) ? source.source : source
19
26
  @pos = 0
@@ -145,9 +152,8 @@ module LexerKit
145
152
  advance
146
153
  Any.new(meta: meta_for_span(start_pos, @pos, literal_text: "."))
147
154
  when "^", "$"
148
- # Anchors - not supported in DFA, just skip
149
- advance
150
- Literal.new(byte: nil, meta: meta_for_span(start_pos, @pos, literal_text: @source[start_pos...@pos]))
155
+ # A token is matched where the previous one ended: a line anchor has no meaning there
156
+ error("anchor #{peek} is not supported at position #{@pos}")
151
157
  when nil, "|", ")", "*", "+", "?", "{"
152
158
  error("unexpected '#{peek}' at position #{@pos}")
153
159
  else
@@ -177,7 +183,9 @@ module LexerKit
177
183
  while peek && peek != "]"
178
184
  start_item = parse_char_class_item
179
185
 
180
- if range_follows?
186
+ if start_item[:type] == :ranges
187
+ start_item[:value].each { |lo, hi| collector.add_range({ type: :byte, value: lo }, { type: :byte, value: hi }) }
188
+ elsif range_follows?
181
189
  advance # skip -
182
190
  end_item = parse_char_class_item
183
191
  collector.add_range(start_item, end_item)
@@ -198,8 +206,19 @@ module LexerKit
198
206
  end
199
207
 
200
208
  def parse_char_class_item
209
+ error("POSIX bracket expressions like [[:alpha:]] are not supported") if peek == "[" && @source[@pos + 1] == ":"
210
+ error("nested character classes are not supported; escape [ as \\[") if peek == "["
211
+ error("character class intersection (&&) is not supported") if peek == "&" && @source[@pos + 1] == "&"
212
+
201
213
  if peek == "\\"
202
214
  advance
215
+ if CLASS_ESCAPES.key?(peek)
216
+ ranges = CLASS_ESCAPES[peek]
217
+ advance
218
+ return { type: :ranges, value: ranges }
219
+ end
220
+ error("\\#{peek} is not supported inside a character class") if %w[D W S].include?(peek)
221
+
203
222
  bytes = parse_escape_char
204
223
  if bytes.length == 1
205
224
  return { type: :byte, value: bytes[0] }
@@ -285,12 +304,25 @@ module LexerKit
285
304
  when nil
286
305
  error("unexpected end of pattern after \\")
287
306
  else
288
- byte = peek.ord
307
+ unsupported_escape! if peek.match?(/[0-9A-Za-z]/)
308
+ char = peek
289
309
  advance
290
- Literal.new(byte: byte, meta: meta_for_span(start_pos, @pos, literal_text: @source[start_pos...@pos], codepoint: byte, bytes: [byte]))
310
+ bytes = char.bytes
311
+ meta = meta_for_span(start_pos, @pos, literal_text: @source[start_pos...@pos], codepoint: char.ord, bytes: bytes)
312
+ if bytes.size == 1
313
+ Literal.new(byte: bytes[0], meta: meta)
314
+ else
315
+ Concat.new(children: bytes.map { |b| Literal.new(byte: b, meta: nil) }, meta: meta)
316
+ end
291
317
  end
292
318
  end
293
319
 
320
+ # A letter or digit escape that is not listed above: an anchor (\A, \z), a backreference
321
+ # (\1), \h, \p{...} and so on. Reading it as the plain character would change the pattern.
322
+ def unsupported_escape!
323
+ error("unsupported escape \\#{peek} at position #{@pos}")
324
+ end
325
+
294
326
  def consume_hex_digits(count)
295
327
  digits = +""
296
328
  count.times do
@@ -335,9 +367,10 @@ module LexerKit
335
367
  [codepoint].pack("U").bytes
336
368
  when nil then error("unexpected end of pattern after \\")
337
369
  else
338
- byte = peek.ord
370
+ unsupported_escape! if peek.match?(/[0-9A-Za-z]/)
371
+ char = peek
339
372
  advance
340
- [byte]
373
+ char.bytes
341
374
  end
342
375
  end
343
376
 
@@ -8,7 +8,7 @@ module LexerKit
8
8
  # Binary/File Errors
9
9
  # ===========================================================================
10
10
 
11
- # Raised when binary deserialization fails
11
+ # Raised when a program binary cannot be decoded, by the Ruby decoder or the native extension
12
12
  class InvalidBinaryError < Error; end
13
13
 
14
14
  # Raised when file integrity check fails (SHA256 mismatch, etc.)
@@ -68,7 +68,7 @@ module LexerKit
68
68
  # Runtime Errors
69
69
  # ===========================================================================
70
70
 
71
- # Raised when C native extension is required but not loaded
71
+ # Raised when the native extension is required but not loaded
72
72
  class NativeExtensionError < Error; end
73
73
 
74
74
  # Raised during VM execution (stack overflow, infinite loop, etc.)
@@ -62,14 +62,14 @@ module LexerKit
62
62
  decoded = Decoder.new(bytes).decode_container
63
63
  header = decoded[:header]
64
64
 
65
- unless header[:format_version] == IR::Serializer::FORMAT_VERSION
65
+ unless IR::Serializer::READABLE_FORMAT_VERSIONS.include?(header[:format_version])
66
66
  raise LexerKit::IntegrityError, "Unsupported format version: #{header[:format_version]}"
67
67
  end
68
68
 
69
+ # from_binary loads the native program too
69
70
  program = IR::CompiledProgram.from_binary(decoded[:payload])
70
- program.load_native! if LexerKit.native?
71
71
  new(program, meta: decoded[:meta])
72
- rescue ArgumentError => e
72
+ rescue ArgumentError, LexerKit::InvalidBinaryError => e
73
73
  raise LexerKit::IntegrityError, e.message
74
74
  end
75
75
 
@@ -71,11 +71,13 @@ module LexerKit
71
71
  raise LexerKit::IntegrityError, "Length mismatch: expected #{container[:uncompressed_len]}, got #{binary.bytesize}"
72
72
  end
73
73
 
74
+ # from_binary loads the native program too
74
75
  program = IR::CompiledProgram.from_binary(binary)
75
- program.load_native! if LexerKit.native?
76
76
  new(program)
77
77
  rescue JSON::ParserError => e
78
78
  raise LexerKit::IntegrityError, "Invalid JSON: #{e.message}"
79
+ rescue LexerKit::InvalidBinaryError => e
80
+ raise LexerKit::IntegrityError, e.message
79
81
  rescue ArgumentError => e
80
82
  # Base64 decode errors
81
83
  raise LexerKit::IntegrityError, "Decoding error: #{e.message}"
@@ -8,12 +8,12 @@ module LexerKit
8
8
  # Supports LKT1 (JSON-based) and LKB1 (binary) formats.
9
9
  #
10
10
  # @example Loading a lexer
11
- # program = LexerKit::Format::LKT1.load("lexer.lkt1")
12
- # program = LexerKit::Format::LKB1.load("lexer.lkb1")
11
+ # program = LexerKit::Format::LKT1.load("lexer.lkt1").program
12
+ # program = LexerKit::Format::LKB1.load("lexer.lkb1").program
13
13
  #
14
14
  # @example Saving a lexer
15
- # LexerKit::Format::LKT1.save(program, "lexer.lkt1")
16
- # LexerKit::Format::LKB1.save(program, "lexer.lkb1")
15
+ # LexerKit::Format::LKT1.save(program, path: "lexer.lkt1")
16
+ # LexerKit::Format::LKB1.save(program, path: "lexer.lkb1")
17
17
  module Format
18
18
  end
19
19
  end
@@ -90,16 +90,19 @@ module LexerKit
90
90
  @mode_offsets[name]
91
91
  end
92
92
 
93
- # Low-level lexing with callback (for performance-critical code)
93
+ # Low-level lexing with callback (for performance-critical code).
94
+ # The tokens are collected before the block runs, so the block may lex again.
94
95
  # @param bytes [String] input bytes
95
96
  # @yield [Integer, Integer, Integer] token_id, start, length
97
+ # @return [nil, Enumerator] an Enumerator without a block
96
98
  # @raise [NativeExtensionError] if Rust extension is not loaded
97
99
  def lowlevel_each(bytes, &)
98
- bytes = bytes.b
99
- raise LexerKit::NativeExtensionError, "Rust extension not loaded" unless LexerKit.native?
100
+ return enum_for(:lowlevel_each, bytes) unless block_given?
101
+
102
+ LexerKit.require_native!
100
103
 
101
104
  ensure_rust_native!
102
- lex_rust_native(bytes, &)
105
+ each_rust_native(bytes.b, &)
103
106
  end
104
107
 
105
108
  # Check if a token ID is an error token
@@ -145,10 +148,11 @@ module LexerKit
145
148
  # @return [Runner]
146
149
  # @raise [NativeExtensionError] if Rust extension is not loaded
147
150
  def stream(input, filename: nil)
148
- raise LexerKit::NativeExtensionError, "Rust extension not loaded" unless LexerKit.native?
151
+ LexerKit.require_native!
149
152
 
150
153
  ensure_rust_native!
151
- lex_stream = create_rust_stream(input)
154
+ # The stream keeps its input: a copy, so a later change to the caller's String cannot change its tokens
155
+ lex_stream = create_rust_stream(input.frozen? ? input : input.dup.freeze)
152
156
  Runner.new(self, lex_stream, filename: filename)
153
157
  end
154
158
 
@@ -161,16 +165,22 @@ module LexerKit
161
165
  bytes = input.b
162
166
  source = Core::Source.new(bytes, filename: filename)
163
167
 
168
+ # Straight from the flat Array: a yield per token would cost as much as making the Token.
169
+ flat = native_tokens(bytes)
164
170
  tokens = []
165
- lowlevel_each(bytes) do |tok_id, start, len|
171
+ i = 0
172
+ n = flat.size
173
+ while i < n
174
+ tok_id = flat[i]
166
175
  tokens << Core::Token.new(
167
176
  id: tok_id,
168
177
  name: token_name(tok_id),
169
- start: start,
170
- len: len,
178
+ start: flat[i + 1],
179
+ len: flat[i + 2],
171
180
  source: source,
172
181
  meta: @token_meta[tok_id]
173
182
  )
183
+ i += 3
174
184
  end
175
185
  tokens
176
186
  end
@@ -180,34 +190,27 @@ module LexerKit
180
190
  def load_native!
181
191
  return self unless LexerKit.native?
182
192
 
183
- load_rust_native(to_native_data)
193
+ load_rust_native(to_binary)
184
194
  self
185
195
  end
186
196
 
187
- # Convert to data format for Rust native loading
188
- # @return [Hash] data for Rust extension
189
- def to_native_data
190
- {
191
- instructions: @instructions.map(&:to_binary).join,
192
- dfa_tables: @dfa_tables.map(&:to_native_format),
193
- jump_tables: @jump_tables.map(&:to_native_format),
194
- keyword_tables: @keyword_tables.map(&:to_native_format),
195
- constant_pool: @constant_pool.entries,
196
- modes: @mode_offsets.map { |name, offset| [name.to_s, offset] }
197
- }
198
- end
199
-
200
197
  # Encode to binary
201
198
  # @return [String]
202
199
  def to_binary
203
200
  Serializer.to_binary(self)
204
201
  end
205
202
 
206
- # Decode from binary
203
+ # Decode from binary. The program is ready to lex, so it may be frozen.
207
204
  # @param bytes [String]
208
205
  # @return [CompiledProgram]
209
206
  def self.from_binary(bytes)
210
- Serializer.from_binary(bytes)
207
+ Serializer.from_binary(bytes).load_native!
208
+ end
209
+
210
+ # Loads the native program first: a frozen program cannot store it later.
211
+ def freeze
212
+ ensure_rust_native! if LexerKit.native? && !frozen?
213
+ super
211
214
  end
212
215
 
213
216
  def inspect
@@ -216,12 +219,22 @@ module LexerKit
216
219
 
217
220
  private
218
221
 
222
+ # The tokens of bytes as one flat Array, [id, start, len, id, start, len, ...]: for
223
+ # tokenize, which makes a Token of each and so needs no yield.
224
+ # @raise [NativeExtensionError] if Rust extension is not loaded
225
+ def native_tokens(bytes)
226
+ LexerKit.require_native!
227
+
228
+ ensure_rust_native!
229
+ lex_rust_native(bytes)
230
+ end
231
+
219
232
  # Ensure Rust native is loaded
220
233
  # @api private
221
234
  def ensure_rust_native!
222
235
  return if respond_to?(:rust_native_loaded?) && rust_native_loaded?
223
236
 
224
- load_rust_native(to_native_data)
237
+ load_rust_native(to_binary)
225
238
  end
226
239
  end
227
240
  end
@@ -60,45 +60,67 @@ module LexerKit
60
60
  @entries.size
61
61
  end
62
62
 
63
- # Encode to binary
63
+ # Encode to binary (format version 4: entry lengths are u32)
64
64
  # @return [String]
65
+ # @raise [ArgumentError] if the count or an entry length does not fit its field
65
66
  def to_binary
66
67
  parts = []
67
68
 
68
69
  # Count (u16)
69
- parts << [@entries.size].pack("S>")
70
+ parts << [Limits.check!(@entries.size, Limits::U16_MAX, "number of constants")].pack("S>")
70
71
 
71
- # Entries: [length (u16), bytes...]
72
+ # Entries: [length (u32), bytes...]
72
73
  @entries.each do |entry|
73
- parts << [entry.bytesize].pack("S>")
74
+ parts << [Limits.check!(entry.bytesize, Limits::U32_MAX, "length of a constant")].pack("L>")
74
75
  parts << entry
75
76
  end
76
77
 
77
78
  parts.join
78
79
  end
79
80
 
80
- # Decode from binary
81
+ # Decode from binary.
82
+ #
83
+ # Entries keep their positions: constant IDs in the instructions refer to them, so
84
+ # duplicates are kept as separate entries (as `add_uninterned` and `replace` make them).
81
85
  # @param bytes [String]
86
+ # @param format_version [Integer] 3 (u16 entry lengths) or 4 (u32 entry lengths)
82
87
  # @return [Array(ConstantPool, Integer)] [pool, bytes_consumed]
83
- def self.from_binary(bytes)
88
+ # @raise [ArgumentError] if the data is truncated
89
+ def self.from_binary(bytes, format_version: Serializer::FORMAT_VERSION)
90
+ length_format, length_size = format_version >= 4 ? ["L>", 4] : ["S>", 2]
84
91
  pos = 0
85
92
 
86
- count = bytes.byteslice(pos, 2).unpack1("S>")
93
+ count = read(bytes, pos, 2).unpack1("S>")
87
94
  pos += 2
88
95
 
89
96
  pool = new
90
97
  count.times do
91
- len = bytes.byteslice(pos, 2).unpack1("S>")
92
- pos += 2
98
+ len = read(bytes, pos, length_size).unpack1(length_format)
99
+ pos += length_size
93
100
 
94
- value = bytes.byteslice(pos, len)
95
- pool.add(value)
101
+ pool.append_decoded(read(bytes, pos, len))
96
102
  pos += len
97
103
  end
98
104
 
99
105
  [pool, pos]
100
106
  end
101
107
 
108
+ def self.read(bytes, pos, len)
109
+ data = bytes.byteslice(pos, len)
110
+ raise ArgumentError, "constant pool is truncated" if data.nil? || data.bytesize != len
111
+
112
+ data
113
+ end
114
+ private_class_method :read
115
+
116
+ # Append a decoded entry at the next position (no interning).
117
+ # @api private
118
+ def append_decoded(value)
119
+ value = value.b.freeze
120
+ @index[value] = @entries.size unless @index.key?(value)
121
+ @entries << value
122
+ end
123
+
102
124
  def inspect
103
125
  "#<ConstantPool size=#{@entries.size}>"
104
126
  end
@@ -5,9 +5,9 @@ module LexerKit
5
5
  # DFATable represents a compiled DFA for pattern matching.
6
6
  # Uses byte class compression to reduce table size.
7
7
  class DFATable
8
- # State 0 indicates no valid transition (must match C DFA_DEAD_STATE)
8
+ # State 0 indicates no valid transition (must match DFA_DEAD_STATE in crates/lexer_kit_core/src/types.rs)
9
9
  DEAD_STATE = 0
10
- # Token ID indicating non-accepting state (must match C DFA_NO_ACCEPT)
10
+ # Token ID indicating non-accepting state (must match DFA_NO_ACCEPT in crates/lexer_kit_core/src/types.rs)
11
11
  NO_ACCEPT = 0xFFFF
12
12
 
13
13
  attr_reader :state_count, :class_count, :byte_class, :transitions, :accept_states
@@ -46,19 +46,25 @@ module LexerKit
46
46
  parts = []
47
47
 
48
48
  # Header: state_count (u16), class_count (u16)
49
+ Limits.check!(@state_count, Limits::U16_MAX, "number of DFA states")
50
+ Limits.check!(@class_count, Limits::U16_MAX, "number of DFA byte classes")
49
51
  parts << [@state_count, @class_count].pack("S>S>")
50
52
 
51
53
  # Byte class table (256 bytes)
52
54
  parts << @byte_class.pack("C256")
53
55
 
54
56
  # Transitions (state_count × class_count × u16)
57
+ max_target = @transitions.max
58
+ Limits.check!(max_target, Limits::U16_MAX, "DFA transition target") if max_target
55
59
  parts << @transitions.pack("S>*")
56
60
 
57
61
  # Accept states count (u16)
58
- parts << [@accept_states.size].pack("S>")
62
+ parts << [Limits.check!(@accept_states.size, Limits::U16_MAX, "number of DFA accept states")].pack("S>")
59
63
 
60
64
  # Accept states: [state (u16), token_id (u16)] pairs
61
65
  @accept_states.each do |state, token_id|
66
+ Limits.check!(state, Limits::U16_MAX, "DFA accept state")
67
+ Limits.check!(token_id, Limits::U16_MAX, "token ID of a DFA accept state")
62
68
  parts << [state, token_id].pack("S>S>")
63
69
  end
64
70
 
@@ -104,22 +110,6 @@ module LexerKit
104
110
  def inspect
105
111
  "#<DFATable states=#{@state_count} classes=#{@class_count} accepts=#{@accept_states.size}>"
106
112
  end
107
-
108
- # Convert to format suitable for C native loading
109
- # Returns dense accept_tokens array for O(1) lookup
110
- # @return [Hash] data for C extension
111
- def to_native_format
112
- # Build dense array: accept_tokens[state] = token_id
113
- accept_tokens = Array.new(@state_count, NO_ACCEPT)
114
- @accept_states.each { |state, token_id| accept_tokens[state] = token_id }
115
- {
116
- state_count: @state_count,
117
- class_count: @class_count,
118
- byte_class: @byte_class.pack("C*"),
119
- transitions: @transitions.pack("S>*"),
120
- accept_tokens: accept_tokens.pack("S>*")
121
- }
122
- end
123
113
  end
124
114
  end
125
115
  end
@@ -16,7 +16,10 @@ module LexerKit
16
16
 
17
17
  # Encode to binary (4 bytes: 1 opcode + 3 arg)
18
18
  # @return [String] binary representation
19
+ # @raise [ArgumentError] if the opcode or argument does not fit (u8, u24)
19
20
  def to_binary
21
+ Limits.check!(@opcode, Limits::U8_MAX, "opcode")
22
+ Limits.check!(@arg, Limits::U24_MAX, "operand of #{Opcode.name(@opcode)}")
20
23
  [
21
24
  @opcode,
22
25
  (@arg >> 16) & 0xFF,
@@ -24,6 +24,7 @@ module LexerKit
24
24
  # Encode to binary
25
25
  # @return [String]
26
26
  def to_binary
27
+ Limits.check!(@default_offset, Limits::U24_MAX, "jump table default offset")
27
28
  parts = []
28
29
 
29
30
  # Default offset (u24)
@@ -38,6 +39,8 @@ module LexerKit
38
39
 
39
40
  # Entries: [byte (u8), offset (u24)] pairs
40
41
  @entries.each do |byte, offset|
42
+ Limits.check!(byte, Limits::U8_MAX, "jump table byte")
43
+ Limits.check!(offset, Limits::U24_MAX, "jump table offset")
41
44
  parts << [
42
45
  byte,
43
46
  (offset >> 16) & 0xFF,
@@ -76,19 +79,6 @@ module LexerKit
76
79
  def inspect
77
80
  "#<JumpTable entries=#{@entries.size} default=#{@default_offset}>"
78
81
  end
79
-
80
- # Convert to format suitable for C native loading
81
- # Returns dense 256-entry lookup table for O(1) access
82
- # @return [Hash] data for C extension
83
- def to_native_format
84
- # Build dense lookup table: all 256 bytes → offset
85
- lookup = Array.new(256, @default_offset)
86
- @entries.each { |byte, offset| lookup[byte] = offset }
87
- {
88
- lookup: lookup.pack("L>*"), # 256 * 4 = 1024 bytes
89
- default_offset: @default_offset # For EOF case
90
- }
91
- end
92
82
  end
93
83
  end
94
84
  end
@@ -61,15 +61,6 @@ module LexerKit
61
61
  parts.join
62
62
  end
63
63
 
64
- # Convert to format suitable for C native loading
65
- # @return [Hash] data for C extension
66
- def to_native_format
67
- {
68
- base_token_id: @base_token_id,
69
- keywords: @keywords.map { |key, token_id| [key.b, token_id] }
70
- }
71
- end
72
-
73
64
  # Decode from binary
74
65
  # @param bytes [String]
75
66
  # @return [Array(KeywordTable, Integer)] table and consumed bytes
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LexerKit
4
+ module IR
5
+ # Widths of the fields of the program binary (docs/ir-spec.md §5).
6
+ #
7
+ # `pack` truncates a value that does not fit its field instead of raising, so every
8
+ # encoder checks its values here first. A value that does not fit is an error, never
9
+ # a silently different program.
10
+ module Limits
11
+ U8_MAX = 0xFF
12
+ U16_MAX = 0xFFFF
13
+ U24_MAX = 0xFF_FFFF
14
+ U32_MAX = 0xFFFF_FFFF
15
+
16
+ # Packed instruction arguments: (upper << 14) | lower (docs/ir-spec.md §3).
17
+ PACKED_UPPER_MAX = 0x3FF # 10 bits
18
+ PACKED_LOWER_MAX = 0x3FFF # 14 bits
19
+ PACKED_LOWER_BITS = 14
20
+
21
+ module_function
22
+
23
+ # @param value [Integer]
24
+ # @param max [Integer]
25
+ # @param what [String] what the value is, for the error message
26
+ # @return [Integer] value
27
+ # @raise [ArgumentError] if value is not an integer in 0..max
28
+ def check!(value, max, what)
29
+ return value if value.is_a?(Integer) && value >= 0 && value <= max
30
+
31
+ raise ArgumentError, "#{what} (#{value.inspect}) does not fit in the program binary: the maximum is #{max}"
32
+ end
33
+
34
+ # UTF-8 bytes of a string whose length is written as u16.
35
+ # @return [String] binary string
36
+ # @raise [ArgumentError] if the string is too long or cannot be converted to UTF-8
37
+ def u16_string!(string, what)
38
+ bytes = begin
39
+ string.to_s.encode(Encoding::UTF_8).b
40
+ rescue EncodingError => e
41
+ raise ArgumentError, "#{what} (#{string.inspect}) cannot be written as UTF-8: #{e.message}"
42
+ end
43
+ check!(bytes.bytesize, U16_MAX, "length of #{what}")
44
+ bytes
45
+ end
46
+ end
47
+ end
48
+ end