lexer_kit 0.6.1-aarch64-linux → 0.7.0-aarch64-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 (37) 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/version.rb +1 -1
  28. data/lib/lexer_kit.rb +15 -2
  29. data/lib/lexer_kit_rust/3.3/lexer_kit_rust.so +0 -0
  30. data/lib/lexer_kit_rust/3.4/lexer_kit_rust.so +0 -0
  31. data/lib/lexer_kit_rust/4.0/lexer_kit_rust.so +0 -0
  32. data/vendor/nupur/LICENSE +176 -0
  33. data/vendor/nupur/NOTICE +64 -0
  34. data/vendor/nupur/README.ja.md +150 -0
  35. data/vendor/nupur/README.md +257 -0
  36. data/vendor/nupur.sha256 +68 -0
  37. metadata +9 -2
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1ebd01c49608cefd1ae270b24300b0d79db369552b7b63db668ec4423539b66c
4
- data.tar.gz: f9ee7d3e8bea3c6d29717e2d85942688e744a9765f58e200a465273e16ba8a35
3
+ metadata.gz: 3b28f7427bb2b3cd16ea87aabed2b4aea81ce7046d1bb56797e08853549351aa
4
+ data.tar.gz: 9f20acf88f62859bcbcd1c4f8b06ca2402157ac3291cd6edac3ddf0101130d66
5
5
  SHA512:
6
- metadata.gz: 8044a8d5be3549c4a62a78bc4addf88ca6d9d5c3c71e65b8fc88ff266a17441e5f40fdf99cb98847bfbe313fb3ccd12d306cea3223fc9ab1067dd0b2969d406c
7
- data.tar.gz: 87732c941ef6762bec21f216ce5e899a3d401fd6c213188f0d5d98d6757cc0b5daa05689109964d91b9a020c7388d65dab717e17f88068125fd22d4166315bf3
6
+ metadata.gz: 95ba90f2b6bbff12c013b94c3cfa14227379782c8f1d56ca8ae51b12c3952786ba2ee3c595de7390e6b94e249f20956488f74b6bc226ed8c521aeb51f1ec2cd1
7
+ data.tar.gz: 7bedbe0792c87d977d4db8195464113d53ff7c862cc54bf551aa23d250374985720ea945ba7f686b0feca559cb800719dd6023c346c29b286c00fc0ce14c37e7
data/README.md CHANGED
@@ -22,6 +22,9 @@ gem "lexer_kit"
22
22
  bundle install
23
23
  ```
24
24
 
25
+ Precompiled gems are published for x86_64 and arm64 Linux and macOS, for Ruby 3.3, 3.4 and 4.0.
26
+ On other platforms the gem builds its native extension from source, which needs Rust 1.95 or later.
27
+
25
28
  ## Quick Start
26
29
 
27
30
  ```ruby
@@ -104,8 +107,8 @@ token :CJK, LexerKit.utf8_range(0x4E00..0x9FFF)
104
107
  ## Regex Notes
105
108
 
106
109
  - Most common regex syntax is supported (`[]`, quantifiers, groups, alternation, escapes, `/.../i`)
107
- - Backtracking-dependent features are not supported (lookaround, backreference, etc.)
108
- - Anchors and word-boundary assertions are not used in lexer matching
110
+ - Unsupported syntax raises `LexerKit::ParseError`: lookaround, backreferences, anchors (`^`, `$`, `\A`, `\z`), `\B`, POSIX classes, and flags other than `/i`
111
+ - `.` and negated classes match one byte; use `utf8_range` for multibyte characters
109
112
  - `*?`, `+?`, `??` are parsed but behave as longest-match (DFA behavior)
110
113
 
111
114
  ## Stream API and Error Handling
@@ -154,4 +157,5 @@ JSON benchmark (600KB input, project benchmark script):
154
157
 
155
158
  ## License
156
159
 
157
- MIT License
160
+ MIT License.
161
+ The native extension includes Nupur from [Makiri](https://github.com/takahashim/makiri) in `vendor/nupur`, under the Apache License 2.0 (`vendor/nupur/LICENSE`, `vendor/nupur/NOTICE`).
@@ -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
@@ -40,6 +40,8 @@ module LexerKit
40
40
  def check_pair(token1, token2)
41
41
  # Skip if both have the same name (same token defined multiple times is ok)
42
42
  return if token1.name == token2.name
43
+ # A delimited token has no pattern: it scans its whole mode
44
+ return if token1.delimited? || token2.delimited?
43
45
 
44
46
  pattern1 = token1.pattern
45
47
  pattern2 = token2.pattern
@@ -51,10 +53,15 @@ module LexerKit
51
53
  elsif pattern1.is_a?(Regexp) && pattern2.is_a?(String)
52
54
  check_literal_regex_pair(token2, token1)
53
55
  else
54
- check_regex_pair(token1, token2)
56
+ # A literal against another kind of pattern (e.g. utf8_range): compare as regexes
57
+ check_regex_pair(token1, token2, as_regex(pattern1), as_regex(pattern2))
55
58
  end
56
59
  end
57
60
 
61
+ def as_regex(pattern)
62
+ pattern.is_a?(String) ? Regexp.new(Regexp.escape(pattern)) : pattern
63
+ end
64
+
58
65
  def check_literal_pair(token1, token2)
59
66
  lit1 = token1.pattern
60
67
  lit2 = token2.pattern
@@ -89,8 +96,8 @@ module LexerKit
89
96
  literal = literal_token.pattern
90
97
  regex = regex_token.pattern
91
98
 
92
- # Check if the literal matches the regex
93
- return unless regex.match?(literal)
99
+ # Check if the regex matches the whole literal
100
+ return unless Regexp.new("\\A(?:#{regex.source})\\z", regex.options).match?(literal)
94
101
 
95
102
  @conflicts << Conflict.new(
96
103
  type: :literal_matches_regex,
@@ -101,14 +108,11 @@ module LexerKit
101
108
  )
102
109
  end
103
110
 
104
- def check_regex_pair(token1, token2)
111
+ def check_regex_pair(token1, token2, pattern1 = token1.pattern, pattern2 = token2.pattern)
105
112
  # For regex pairs, we need to check if they can match the same string
106
113
  # We do this by building a combined DFA and checking for states
107
114
  # that accept both patterns
108
115
 
109
- pattern1 = token1.pattern
110
- pattern2 = token2.pattern
111
-
112
116
  # Check first byte overlap
113
117
  regex1 = DFA::RegexAST::Regex.parse(pattern1)
114
118
  regex2 = DFA::RegexAST::Regex.parse(pattern2)
@@ -163,9 +167,9 @@ module LexerKit
163
167
  dfa1 = DFA.compile_regex(regex1, 1)
164
168
  dfa2 = DFA.compile_regex(regex2, 2)
165
169
 
166
- # BFS to find accepting strings
167
- # State: [dfa1_state, dfa2_state, accumulated_string]
168
- queue = [[1, 1, ""]]
170
+ # BFS over bytes to find accepting strings
171
+ # State: [dfa1_state, dfa2_state, accumulated bytes]
172
+ queue = [[1, 1, "".b]]
169
173
  visited = Set.new
170
174
  max_depth = 10
171
175
 
@@ -179,26 +183,20 @@ module LexerKit
179
183
 
180
184
  # Check if both DFAs accept at this point
181
185
  if dfa1.accept(dfa1_state) && dfa2.accept(dfa2_state) && !str.empty?
182
- examples << str
186
+ text = str.dup.force_encoding(Encoding::UTF_8)
187
+ examples << (text.valid_encoding? ? text : str)
183
188
  next
184
189
  end
185
190
 
186
191
  # Explore transitions
187
- (0..127).each do |byte|
192
+ (0..255).each do |byte|
188
193
  next_state1 = dfa1.transition(dfa1_state, byte)
189
194
  next_state2 = dfa2.transition(dfa2_state, byte)
190
195
 
191
196
  # Both must have valid transitions
192
197
  next if next_state1.zero? || next_state2.zero?
193
198
 
194
- char = begin
195
- byte.chr
196
- rescue StandardError
197
- next
198
- end
199
- next unless char.valid_encoding?
200
-
201
- queue << [next_state1, next_state2, str + char]
199
+ queue << [next_state1, next_state2, str + byte.chr]
202
200
  end
203
201
  end
204
202
 
@@ -13,10 +13,55 @@ module LexerKit
13
13
  def validate!
14
14
  validate_mode_references!
15
15
  validate_reserved_token_names!
16
+ validate_patterns!
17
+ validate_modes!
18
+ validate_version!
16
19
  end
17
20
 
18
21
  private
19
22
 
23
+ def validate_patterns!
24
+ @builder.token_defs.each do |token_def|
25
+ next if token_def.delimited?
26
+
27
+ pattern = token_def.pattern
28
+ if pattern.is_a?(String)
29
+ next unless pattern.empty?
30
+
31
+ error!(token_def.location, "token :#{token_def.name} has an empty pattern")
32
+ end
33
+ next if token_def.regex?
34
+
35
+ error!(token_def.location, "token :#{token_def.name} needs a String or Regexp pattern, got #{pattern.inspect}")
36
+ end
37
+ end
38
+
39
+ # A delimited token scans a whole mode, so it is the mode's only token.
40
+ def validate_modes!
41
+ @builder.mode_defs.each_value do |mode_def|
42
+ if mode_def.tokens.empty?
43
+ error!(mode_def.location, "mode :#{mode_def.name} defines no tokens")
44
+ end
45
+
46
+ delimited = mode_def.tokens.select(&:delimited?)
47
+ next if delimited.empty? || mode_def.tokens.size == 1
48
+
49
+ other = mode_def.tokens.find { |t| !t.equal?(delimited.first) }
50
+ error!(other.location, "mode :#{mode_def.name} has a delimited token, so it can have no other token")
51
+ end
52
+ end
53
+
54
+ def validate_version!
55
+ version = @builder.version
56
+ return if version.is_a?(Integer) && version >= 0 && version <= IR::Limits::U32_MAX
57
+
58
+ error!(nil, "version must be an Integer from 0 to #{IR::Limits::U32_MAX}, got #{version.inspect}")
59
+ end
60
+
61
+ def error!(location, message)
62
+ raise LexerKit::BuildError.from_location(location, message)
63
+ end
64
+
20
65
  def validate_reserved_token_names!
21
66
  @builder.token_defs.each do |token_def|
22
67
  next unless token_def.name == :INVALID
@@ -22,10 +22,10 @@ module LexerKit
22
22
  def token(name, pattern, skip: false, push: nil, pop: false, meta: nil)
23
23
  location = caller_locations(1, 1).first
24
24
  token_def = TokenDef.new(
25
- name: name,
25
+ name: dsl_name(name, location),
26
26
  pattern: pattern,
27
27
  skip: skip,
28
- push: push,
28
+ push: push && dsl_name(push, location),
29
29
  pop: pop,
30
30
  meta: meta,
31
31
  location: location
@@ -38,7 +38,7 @@ module LexerKit
38
38
  # @param name [Symbol] keyword token name
39
39
  # @param value [String] keyword string
40
40
  def keyword(name, value)
41
- @keywords[value.freeze] = name
41
+ add_keyword(name, value, caller_locations(1, 1).first)
42
42
  end
43
43
 
44
44
  # Define multiple keywords at once
@@ -50,20 +50,22 @@ module LexerKit
50
50
  # # keyword :ELSE, "else"
51
51
  # # keyword :WHILE, "while"
52
52
  def define_keywords(*names)
53
+ location = caller_locations(1, 1).first
53
54
  names.each do |name|
54
55
  token_name = name.to_s.upcase.to_sym
55
56
  value = name.to_s.downcase
56
- keyword(token_name, value)
57
+ add_keyword(token_name, value, location)
57
58
  end
58
59
  end
59
60
 
60
61
  # Define a mode
61
62
  # @param name [Symbol] mode name
62
63
  # @yield mode definition block
64
+ # Defining a mode again adds to it.
63
65
  def mode(name, &block)
64
66
  location = caller_locations(1, 1).first
65
- mode_def = ModeDef.new(name, location: location)
66
- @mode_defs[name] = mode_def
67
+ name = dsl_name(name, location)
68
+ @mode_defs[name] ||= ModeDef.new(name, location: location)
67
69
 
68
70
  old_mode = @current_mode
69
71
  @current_mode = name
@@ -96,6 +98,7 @@ module LexerKit
96
98
  raise LexerKit::BuildError.from_location(location, message)
97
99
  end
98
100
  location = caller_locations(1, 1).first
101
+ name = dsl_name(name, location)
99
102
 
100
103
  token_def = add_delimited_token(
101
104
  name: name,
@@ -173,10 +176,16 @@ module LexerKit
173
176
 
174
177
  # Compile to IR
175
178
  # @return [IR::CompiledProgram]
179
+ # @raise [BuildError, CompileError] if the definitions are invalid or do not fit the program binary
176
180
  def compile
177
181
  Validator.new(self).validate!
178
182
  program = Compiler.new(self).compile
179
- program.load_native! if LexerKit.native?
183
+ begin
184
+ binary = program.to_binary
185
+ rescue ArgumentError => e
186
+ raise LexerKit::CompileError, e.message
187
+ end
188
+ program.load_rust_native(binary) if LexerKit.native?
180
189
  program
181
190
  end
182
191
 
@@ -203,6 +212,24 @@ module LexerKit
203
212
  @mode_defs[@current_mode]
204
213
  end
205
214
 
215
+ # A token or mode name as a Symbol: a String is converted, anything else is an error.
216
+ def dsl_name(name, location)
217
+ return name if name.is_a?(Symbol)
218
+ return name.to_sym if name.is_a?(String) && !name.empty?
219
+
220
+ raise LexerKit::BuildError.from_location(location, "a name must be a Symbol or String, got #{name.inspect}")
221
+ end
222
+
223
+ # Define a keyword, reporting errors at location (the user's call, not this file).
224
+ def add_keyword(name, value, location)
225
+ name = dsl_name(name, location)
226
+ if name == :INVALID
227
+ raise LexerKit::BuildError.from_location(location, ":INVALID is reserved for error tokens")
228
+ end
229
+
230
+ @keywords[value.freeze] = name
231
+ end
232
+
206
233
  # Generate unique internal mode name for scan_until etc.
207
234
  def next_internal_mode_name(base_name)
208
235
  @internal_mode_counter += 1
@@ -69,7 +69,11 @@ module LexerKit
69
69
  compiled = builder.compile
70
70
 
71
71
  # Write output
72
- output_path = options[:output] || path.sub(/\.rb$/, ".lkt1")
72
+ output_path = options[:output] || default_output_path(path)
73
+ if File.expand_path(output_path) == File.expand_path(path)
74
+ warn "error: Output file is the input file: #{output_path}"
75
+ return 1
76
+ end
73
77
  if output_path.end_with?(".lkb1")
74
78
  Format::LKB1.save(compiled, path: output_path)
75
79
  else
@@ -79,6 +83,11 @@ module LexerKit
79
83
 
80
84
  0
81
85
  end
86
+
87
+ # file.rb => file.lkt1; any other name gets .lkt1 appended
88
+ def self.default_output_path(path)
89
+ path.end_with?(".rb") ? "#{path.delete_suffix('.rb')}.lkt1" : "#{path}.lkt1"
90
+ end
82
91
  end
83
92
 
84
93
  # Show lexer information
@@ -110,8 +119,8 @@ module LexerKit
110
119
  puts
111
120
 
112
121
  puts "Tokens (#{lexer.tokens.size}):"
113
- lexer.tokens.each_with_index do |name, id|
114
- puts " #{id.to_s.rjust(3)}: #{name}"
122
+ lexer.tokens.each do |name|
123
+ puts " #{lexer.token_id(name).to_s.rjust(3)}: #{name}"
115
124
  end
116
125
  puts
117
126
 
@@ -180,11 +189,11 @@ module LexerKit
180
189
  lexer_path = argv.shift
181
190
  lexer = CLI.load_lexer(lexer_path)
182
191
 
183
- # Read input
192
+ # Read input as bytes: token offsets are byte offsets
184
193
  input = if argv.empty?
185
- $stdin.read
194
+ $stdin.binmode.read
186
195
  else
187
- File.read(argv.shift)
196
+ File.binread(argv.shift)
188
197
  end
189
198
 
190
199
  # Collect tokens
@@ -197,7 +206,8 @@ module LexerKit
197
206
  tokens << {
198
207
  id: tok_id,
199
208
  name: lexer.token_name(tok_id),
200
- text: input.byteslice(start, len),
209
+ # A token may end inside a multibyte character, so its text is scrubbed for output
210
+ text: input.byteslice(start, len).force_encoding(Encoding::UTF_8).scrub,
201
211
  line: line,
202
212
  col: col,
203
213
  start: start,
@@ -7,10 +7,11 @@ module LexerKit
7
7
  class Source
8
8
  attr_reader :bytes, :filename
9
9
 
10
- # @param input [String] input string (will be stored as-is for char conversion, and as BINARY for byte operations)
10
+ # @param input [String] input string (kept for char conversion, and as BINARY for byte operations).
11
+ # The caller's String is not frozen: an unfrozen input is copied.
11
12
  # @param filename [String, nil] optional filename for diagnostics
12
13
  def initialize(input, filename: nil)
13
- @original_string = input.freeze
14
+ @original_string = input.frozen? ? input : input.dup.freeze
14
15
  @bytes = input.dup.force_encoding(Encoding::BINARY).freeze
15
16
  @filename = filename&.freeze
16
17
  @line_starts = nil
@@ -56,7 +56,6 @@ module LexerKit
56
56
  end
57
57
 
58
58
  def format_arg(instr)
59
- # rubocop:disable Lint/DuplicateBranch
60
59
  case instr.opcode
61
60
  when IR::Opcode::DFA_RUN
62
61
  "dfa=#{instr.arg}"
@@ -128,7 +127,6 @@ module LexerKit
128
127
  else
129
128
  instr.arg.to_s
130
129
  end
131
- # rubocop:enable Lint/DuplicateBranch
132
130
  end
133
131
 
134
132
  def format_byte(byte)
@@ -74,7 +74,7 @@ module LexerKit
74
74
  class_count = byte_class_result[:class_count]
75
75
  transitions = byte_class_result[:transitions]
76
76
 
77
- # Minimize DFA using Hopcroft's algorithm
77
+ # Minimize DFA by partition refinement
78
78
  minimizer = DFAMinimizer.new(
79
79
  state_count: @state_count,
80
80
  transitions: transitions,
@@ -2,7 +2,7 @@
2
2
 
3
3
  module LexerKit
4
4
  module DFA
5
- # DFAMinimizer reduces DFA state count using Hopcroft's algorithm.
5
+ # DFAMinimizer reduces DFA state count by partition refinement (Moore's algorithm).
6
6
  # Merges equivalent states while preserving language recognition.
7
7
  class DFAMinimizer
8
8
  # @param state_count [Integer] number of states (including dead state 0)
@@ -24,7 +24,7 @@ module LexerKit
24
24
  # 1. Initial partition: group by acceptance status and token_id
25
25
  partitions = build_initial_partitions
26
26
 
27
- # 2. Refine partitions using Hopcroft's algorithm
27
+ # 2. Split partitions until no state's transitions tell its partition apart
28
28
  partitions = refine_partitions(partitions)
29
29
 
30
30
  # 3. Build minimized DFA
@@ -52,6 +52,10 @@ module LexerKit
52
52
  when LexerKit::RegexAstProvider
53
53
  pattern.to_regex
54
54
  else
55
+ if pattern.is_a?(Regexp) && pattern.options.anybits?(Regexp::EXTENDED | Regexp::MULTILINE)
56
+ raise LexerKit::ParseError, "regex flags other than /i are not supported: #{pattern.inspect}"
57
+ end
58
+
55
59
  source = pattern.is_a?(Regexp) ? pattern.source : pattern
56
60
  case_insensitive = pattern.is_a?(Regexp) && pattern.casefold?
57
61
  ast = RegexParser.new(source).parse