corvus_regex_ecma262 0.1.1

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.
@@ -0,0 +1,297 @@
1
+ # frozen_string_literal: true
2
+
3
+ # ECMA-262 (JavaScript) regular expressions for Ruby, with the grammar and the answers of RegExp, every flag, backed by
4
+ # the corvus-regex-ecma262 Rust crate.
5
+ #
6
+ # date = CorvusRegexEcma262::Regex.new('(?<year>\d{4})-(?<month>\d{2})', "gu")
7
+ # date.match?("due 2026-10") # => true
8
+ # date.match("due 2026-10")[:year] # => "2026"
9
+ # date.each_match("2026-10, 2027-01").map(&:to_s) # => ["2026-10", "2027-01"]
10
+ # date.replace("2026-10, 2027-01", "$<month>/$1") # => "10/2026, 01/2027"
11
+ #
12
+ # A String is matched as it is held: UTF-8 (or US-ASCII, or binary holding UTF-8) as UTF-8, with positions in
13
+ # characters as Ruby counts them and byte positions beside them; UTF-16LE as UTF-16, with positions in code units.
14
+ # Without the u or v flag a pattern is matched by UTF-16 code unit, so a match can take half of a character beyond the
15
+ # Basic Multilingual Plane: over UTF-8 its text holds that half as U+FFFD, and its start and end in characters are the
16
+ # whole character's.
17
+ require_relative "corvus_regex_ecma262/version"
18
+
19
+ begin
20
+ RUBY_VERSION =~ /(\d+\.\d+)/
21
+ require_relative "corvus_regex_ecma262/#{Regexp.last_match(1)}/corvus_regex_ecma262"
22
+ rescue LoadError
23
+ require_relative "corvus_regex_ecma262/corvus_regex_ecma262"
24
+ end
25
+
26
+ module CorvusRegexEcma262
27
+ UTF16LE = Encoding::UTF_16LE
28
+
29
+ # A compiled ECMA-262 regular expression, as new RegExp(pattern, flags) compiles it. It is immutable, and may be
30
+ # used from any number of threads.
31
+ class Regex
32
+ attr_reader :names
33
+
34
+ # Compiles a pattern with the flags new RegExp(pattern, flags) takes, any of dgimsuvy. Raises InvalidPatternError,
35
+ # InvalidFlagsError or PatternTooLargeError (each an Error).
36
+ def initialize(pattern, flags = "")
37
+ @native = Native::Regex.new(CorvusRegexEcma262.utf8(pattern), flags.to_s)
38
+ @names = @native.names.freeze
39
+ freeze
40
+ end
41
+
42
+ # Whether a pattern is valid with the flags, without compiling it.
43
+ def self.valid?(pattern, flags = "")
44
+ Native::Regex.valid?(CorvusRegexEcma262.utf8(pattern), flags.to_s)
45
+ end
46
+
47
+ # The pattern as it was given, as UTF-8.
48
+ def source = @native.source
49
+
50
+ # The flags as RegExp.prototype.flags writes them, in the order dgimsuvy.
51
+ def flags = @native.flags
52
+
53
+ # The number of capturing groups.
54
+ def group_count = @native.group_count
55
+
56
+ # Whether the pattern matches at or after pos (at pos alone with the y flag), as RegExp.prototype.test with
57
+ # lastIndex set to pos. With timeout: (seconds), a match that reaches it raises MatchLimitError.
58
+ def match?(string, pos = 0, timeout: nil)
59
+ @native.test(string, CorvusRegexEcma262.unit_of(string, pos), timeout&.to_f)
60
+ end
61
+
62
+ # The first match at or after pos, as exec finds it with lastIndex set to pos: a Match, or nil. With a block, the
63
+ # block's result for the match, or nil. With timeout: (seconds), a match that reaches it raises MatchLimitError.
64
+ def match(string, pos = 0, timeout: nil)
65
+ groups = @native.exec(string, CorvusRegexEcma262.unit_of(string, pos), timeout&.to_f)
66
+ return nil unless groups
67
+
68
+ m = Match.new(self, string, groups, Positions.new(string))
69
+ block_given? ? yield(m) : m
70
+ end
71
+
72
+ # Every match of a global search of the string, as matchAll makes one: yields each Match, or returns an
73
+ # Enumerator. After an empty match the search goes on one character later, and with the y flag each match must
74
+ # start where the one before ended.
75
+ def each_match(string)
76
+ return enum_for(:each_match, string) unless block_given?
77
+
78
+ string = CorvusRegexEcma262.snapshot(string)
79
+ positions = Positions.new(string)
80
+ @native.each(string) { |groups| yield Match.new(self, string, groups, positions) }
81
+ self
82
+ end
83
+
84
+ # The number of matches of a global search, without making them.
85
+ def match_count(string) = @native.count(string)
86
+
87
+ # The string with the first match replaced, or every match with the g flag, as String.prototype.replace replaces
88
+ # them. The replacement is a template ($& the match, $` the text before it, $' the text after it, $1 to $99 a
89
+ # group, $<name> a named group, $$ a dollar sign), or the block's result for each Match.
90
+ def replace(string, replacement = nil, &block)
91
+ substitute(string, replacement, @native.global?, &block)
92
+ end
93
+
94
+ # The string with every match replaced, whether or not the g flag is set (String.prototype.replaceAll).
95
+ def replace_all(string, replacement = nil, &block)
96
+ substitute(string, replacement, true, &block)
97
+ end
98
+
99
+ # The string split around the matches, as String.prototype.split(separator, limit) splits it: what each group
100
+ # captured is spliced in after the piece before it (nil for a group that did not take part), an empty match at
101
+ # the start or the end splits nothing, and there are at most limit pieces.
102
+ def split(string, limit = nil)
103
+ @native.split(string, limit).map { |piece| piece&.force_encoding(CorvusRegexEcma262.result_encoding(string)) }
104
+ end
105
+
106
+ def inspect = "#<CorvusRegexEcma262::Regex /#{source}/#{flags}>"
107
+ alias to_s inspect
108
+
109
+ def ==(other) = other.is_a?(Regex) && other.source == source && other.flags == flags
110
+ alias eql? ==
111
+ def hash = [source, flags].hash
112
+
113
+ private
114
+
115
+ def substitute(string, replacement, all)
116
+ unless block_given?
117
+ raise ArgumentError, "a replacement or a block" if replacement.nil?
118
+
119
+ template = string.encoding == UTF16LE ? replacement.encode(UTF16LE) : CorvusRegexEcma262.utf8(replacement)
120
+ return @native.replace(string, template, all).force_encoding(CorvusRegexEcma262.result_encoding(string))
121
+ end
122
+ raise ArgumentError, "a replacement or a block, not both" unless replacement.nil?
123
+
124
+ string = CorvusRegexEcma262.snapshot(string)
125
+ out = +""
126
+ out.force_encoding(CorvusRegexEcma262.result_encoding(string))
127
+ last = 0
128
+ unit = string.encoding == UTF16LE ? 2 : 1
129
+ positions = Positions.new(string)
130
+ @native.each(string) do |groups|
131
+ m = Match.new(self, string, groups, positions)
132
+ out << string.byteslice(last * unit, (groups[0] - last) * unit) << yield(m).to_s
133
+ last = groups[1]
134
+ break unless all
135
+ end
136
+ out << string.byteslice(last * unit, string.bytesize - last * unit)
137
+ end
138
+ end
139
+
140
+ # Where a match and its groups are, read as a MatchData is: by number, by name (String or Symbol), with begin, end
141
+ # and offset in characters (in code units for a UTF-16LE string), and byte_begin, byte_end and byteoffset in bytes.
142
+ class Match
143
+ attr_reader :string, :regexp
144
+
145
+ def initialize(regexp, string, groups, positions)
146
+ @regexp = regexp
147
+ @string = string
148
+ @groups = groups
149
+ @positions = positions
150
+ end
151
+
152
+ # The number of groups, the whole match among them.
153
+ def size = @regexp.group_count + 1
154
+ alias length size
155
+
156
+ def names = @regexp.names
157
+
158
+ # The text of a group, by number, name or Symbol: nil when it did not take part.
159
+ def [](group)
160
+ s, e = span(group)
161
+ return nil if s.negative?
162
+
163
+ text(s, e)
164
+ end
165
+
166
+ # The start of the group in characters (code units for UTF-16LE), or nil when it did not take part.
167
+ def begin(group = 0)
168
+ s, = span(group)
169
+ s.negative? ? nil : @positions.char(s, false)
170
+ end
171
+
172
+ # The end of the group in characters (code units for UTF-16LE), or nil when it did not take part.
173
+ def end(group = 0)
174
+ _, e = span(group)
175
+ e.negative? ? nil : @positions.char(e, true)
176
+ end
177
+
178
+ # [begin, end] of the group, or [nil, nil] when it did not take part.
179
+ def offset(group = 0) = [self.begin(group), self.end(group)]
180
+
181
+ def byte_begin(group = 0)
182
+ s, = span(group)
183
+ s.negative? ? nil : s * unit
184
+ end
185
+
186
+ def byte_end(group = 0)
187
+ _, e = span(group)
188
+ e.negative? ? nil : e * unit
189
+ end
190
+
191
+ def byteoffset(group = 0) = [byte_begin(group), byte_end(group)]
192
+
193
+ # The text of every capturing group, nil for one that did not take part.
194
+ def captures = (1...size).map { |g| self[g] }
195
+
196
+ # The text of each name's group.
197
+ def named_captures = names.to_h { |n| [n, self[n]] }
198
+
199
+ def to_a = (0...size).map { |g| self[g] }
200
+ def values_at(*groups) = groups.map { |g| self[g] }
201
+ def to_s = self[0]
202
+ def pre_match = text(0, @groups[0])
203
+ def post_match = @string.byteslice(@groups[1] * unit, @string.bytesize - (@groups[1] * unit))
204
+
205
+ def inspect = "#<CorvusRegexEcma262::Match #{to_s.inspect} #{offset.inspect}>"
206
+
207
+ private
208
+
209
+ def unit = @string.encoding == UTF16LE ? 2 : 1
210
+
211
+ # [start, end] of a group in engine positions (-1 for one that did not take part).
212
+ def span(group)
213
+ i = case group
214
+ when Integer
215
+ raise IndexError, "index #{group} out of matches" if group.negative? || group >= size
216
+
217
+ group
218
+ when String, Symbol
219
+ k = names.index(group.to_s)
220
+ raise IndexError, "undefined group name reference: #{group}" unless k
221
+
222
+ size + k
223
+ else
224
+ raise TypeError, "a group is an Integer, a String or a Symbol"
225
+ end
226
+ [@groups[2 * i], @groups[(2 * i) + 1]]
227
+ end
228
+
229
+ def text(s, e)
230
+ piece = @string.byteslice(s * unit, (e - s) * unit)
231
+ # A half of a character (without u or v, over UTF-8) is no UTF-8: written as U+FFFD, as the crate writes it.
232
+ piece.valid_encoding? ? piece : piece.scrub("�")
233
+ end
234
+ end
235
+
236
+ # Byte positions to character positions, going on from where it was last asked, since a search asks in order.
237
+ class Positions
238
+ def initialize(string)
239
+ @string = string
240
+ @identity = string.encoding == UTF16LE || string.ascii_only?
241
+ @byte = 0
242
+ @char = 0
243
+ end
244
+
245
+ # The character index of a byte position; a position inside a character (between the halves of one beyond the
246
+ # Basic Multilingual Plane) is its start, or (for an end) past it.
247
+ def char(byte, at_end)
248
+ return byte if @identity
249
+
250
+ @byte = @char = 0 if byte < @byte
251
+ inside = byte < @string.bytesize && (@string.getbyte(byte) & 0xC0) == 0x80
252
+ target = byte
253
+ target -= 1 while inside && target.positive? && (@string.getbyte(target) & 0xC0) == 0x80
254
+ @char += @string.byteslice(@byte, target - @byte).length
255
+ @byte = target
256
+ inside && at_end ? @char + 1 : @char
257
+ end
258
+ end
259
+
260
+ class << self
261
+ # Compiles a pattern: Regex.new(pattern, flags).
262
+ def compile(pattern, flags = "") = Regex.new(pattern, flags)
263
+
264
+ # Whether a pattern is valid with the flags, without compiling it.
265
+ def valid?(pattern, flags = "") = Regex.valid?(pattern, flags)
266
+
267
+ # The version of the crate the extension was built with.
268
+ def crate_version = Native.crate_version
269
+
270
+ # @api private
271
+ def utf8(s)
272
+ s = s.to_s
273
+ return s if s.encoding == Encoding::UTF_8 || (s.encoding == Encoding::US_ASCII && s.ascii_only?)
274
+
275
+ # A lone surrogate (in a UTF-16 pattern) is read as U+FFFD, as the crate's UTF-8 patterns have none.
276
+ s.encode(Encoding::UTF_8, invalid: :replace, undef: :replace, replace: "�")
277
+ end
278
+
279
+ # @api private: the string as a search that runs a block walks it, frozen, so that it cannot change under the
280
+ # search and any number of searches may walk it at once. A string that is not frozen is copied as Ruby copies a
281
+ # String, sharing its bytes until either is changed.
282
+ def snapshot(string) = string.frozen? ? string : string.dup.freeze
283
+
284
+ # @api private
285
+ def result_encoding(string) = string.encoding == UTF16LE ? UTF16LE : Encoding::UTF_8
286
+
287
+ # @api private: the engine position of a character position.
288
+ def unit_of(string, pos)
289
+ raise ArgumentError, "pos must not be negative" if pos.negative?
290
+ return pos if string.encoding == UTF16LE || string.ascii_only? || pos.zero?
291
+ # Past the end, as lastIndex past a string's length: no match.
292
+ return string.bytesize + 1 if pos > string.length
293
+
294
+ string[0, pos].bytesize
295
+ end
296
+ end
297
+ end
metadata ADDED
@@ -0,0 +1,74 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: corvus_regex_ecma262
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - endjin
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-10-21 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rb_sys
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.9.130
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 0.9.130
27
+ description: Regular expressions that answer as JavaScript's RegExp does, every flag
28
+ (dgimsuvy), over UTF-8 and UTF-16LE strings, with the corvus-regex-ecma262 Rust
29
+ crate.
30
+ email:
31
+ executables: []
32
+ extensions:
33
+ - ext/corvus_regex_ecma262/extconf.rb
34
+ extra_rdoc_files: []
35
+ files:
36
+ - Cargo.lock
37
+ - Cargo.toml
38
+ - LICENSE
39
+ - README.md
40
+ - ext/corvus_regex_ecma262/Cargo.toml
41
+ - ext/corvus_regex_ecma262/clippy.toml
42
+ - ext/corvus_regex_ecma262/extconf.rb
43
+ - ext/corvus_regex_ecma262/rustfmt.toml
44
+ - ext/corvus_regex_ecma262/src/lib.rs
45
+ - lib/corvus_regex_ecma262.rb
46
+ - lib/corvus_regex_ecma262/version.rb
47
+ homepage: https://github.com/corvus-dotnet/corvus-regex-ecma262-ruby
48
+ licenses:
49
+ - Apache-2.0
50
+ metadata:
51
+ source_code_uri: https://github.com/corvus-dotnet/corvus-regex-ecma262-ruby
52
+ bug_tracker_uri: https://github.com/corvus-dotnet/corvus-regex-ecma262-ruby/issues
53
+ rubygems_mfa_required: 'true'
54
+ post_install_message:
55
+ rdoc_options: []
56
+ require_paths:
57
+ - lib
58
+ required_ruby_version: !ruby/object:Gem::Requirement
59
+ requirements:
60
+ - - ">="
61
+ - !ruby/object:Gem::Version
62
+ version: '3.3'
63
+ required_rubygems_version: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: '0'
68
+ requirements: []
69
+ rubygems_version: 3.5.22
70
+ signing_key:
71
+ specification_version: 4
72
+ summary: 'ECMA-262 (JavaScript) regular expressions for Ruby: the grammar and the
73
+ answers of RegExp, backed by Rust.'
74
+ test_files: []