Skip to content

Commit fbbc027

Browse files
committed
[GR-18163] Fix MatchData#[] with negative length argument
PullRequest: truffleruby/3737
2 parents 365a678 + 736a950 commit fbbc027

File tree

4 files changed

+11
-3
lines changed

4 files changed

+11
-3
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ Bug fixes:
4444
* Fix `StringIO#write` to transcode strings with encodings that don't match the `StringIO`'s `external_encoding`. (#2839, @flavorjones)
4545
* Fix processing of proc rest arguments located at the beginning if there are no actual arguments (#2921, @andrykonchin).
4646
* Fix `Monitor#exit` to raise `ThreadError` when monitor not owned by the current thread (#2922, @andrykonchin).
47+
* Fix `MatchData#[]` to support negative `length` argument (#2929, @andrykonchin).
4748

4849
Compatibility:
4950

spec/ruby/core/matchdata/element_reference_spec.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,11 @@
2222

2323
# length argument larger than number of match values is capped to match value length
2424
/(.)(.)(\d+)(\d)/.match("THX1138.")[3, 10].should == %w|113 8|
25+
26+
/(.)(.)(\d+)(\d)/.match("THX1138.")[3, 0].should == []
27+
28+
/(.)(.)(\d+)(\d)/.match("THX1138.")[3, -1].should == nil
29+
/(.)(.)(\d+)(\d)/.match("THX1138.")[3, -30].should == nil
2530
end
2631

2732
it "supports ranges [start..end]" do

src/main/java/org/truffleruby/core/array/ArrayNodes.java

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -305,9 +305,6 @@ protected Object indexFallback(RubyArray array, Object index, NotProvided length
305305
protected Object slice(RubyArray array, int start, int length,
306306
@Cached ReadSliceNormalizedNode readSliceNode,
307307
@Cached ConditionProfile negativeIndexProfile) {
308-
if (length < 0) {
309-
return nil;
310-
}
311308
if (negativeIndexProfile.profile(start < 0)) {
312309
start += array.size;
313310
}

src/main/java/org/truffleruby/core/regexp/MatchDataNodes.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,11 +273,16 @@ protected Object getIndex(RubyMatchData matchData, int index, NotProvided length
273273

274274
@Specialization
275275
protected Object getIndex(RubyMatchData matchData, int index, int length,
276+
@Cached ConditionProfile negativeLengthProfile,
276277
@Cached ConditionProfile normalizedIndexProfile,
277278
@Cached ConditionProfile indexOutOfBoundsProfile,
278279
@Cached ConditionProfile tooLargeTotalProfile) {
279280
final Object[] values = getValuesNode.execute(matchData);
280281

282+
if (negativeLengthProfile.profile(length < 0)) {
283+
return nil;
284+
}
285+
281286
if (normalizedIndexProfile.profile(index < 0)) {
282287
index += values.length;
283288

0 commit comments

Comments
 (0)