From 176313e2babd4834aa46297d1d538d2aac0a2686 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 20:53:25 +0000 Subject: [PATCH 1/2] Match BINARY subjects with Onigmo's ASCII-8BIT ctype table "\xff".b =~ /\p{Alpha}/n, [[:alpha:]], \p{Word}, \p{Lower}, (?u)\w, \b and /i all treated bytes 0x80-0xFF as Latin-1 letters. MRI compiles a regexp that is not fixed-encoding for the subject's encoding (rb_reg_prepare_enc), and Onigmo's ASCII-8BIT and US-ASCII ctype tables have no letters, digits, spaces, punctuation or case pairs above 0x7F. IronRuby runs one CLR regex over the subject decoded to chars, where a binary byte is U+0080-U+00FF and .NET calls most of those letters. A non-ASCII BINARY subject now gets a third cached CLR regex (next to the astral one), translated with RegexpTransformer's new asciiCtype flag: properties become the POSIX class of the same name over ASCII (so \p{Punct} takes in $+<=>^`|~ as in those tables), POSIX brackets, (?u)\w \d \s, \b/\B and \R are ASCII only, and under /i a Latin-1 letter, literal or class member, matches only itself while ASCII still folds. A BINARY or US-ASCII regexp with a property uses the same translation for every subject, since its \p{Punct} differs on ASCII text too ("$" =~ Regexp.new('\p{Punct}'.b)). When the translation turns out no different from the plain one, the plain regex is used, so binary scanning keeps its compiled regex. ISO-8859-1 and UTF-8 subjects are untouched and keep their own letters. Util/regexp-binary-ctype-matrix.rb compares CRuby 4.0.10 and ./ir.sh over BINARY, US-ASCII, ISO-8859-1 and UTF-8 subjects for the properties, POSIX classes, \w \h \b \R, /i literals and classes, /n literals and the matching entry points; its BINARY and US-ASCII columns now agree, and what still differs (ISO-8859-1's own ctype table, two UTF-8 rows) is listed in its header and was already so. Regex_BinaryCtype1 covers the cases; IronRuby.Tests pass, and ruby/spec core/regexp, core/string, core/matchdata, library/stringscanner and language fail only on entries in Util/spec-known-failures.txt. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013PQjtyXebXCReTZrAePmUQ --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/RegexTests.cs | 55 ++++++ Src/Ruby/Builtins/RegexpTransformer.cs | 143 +++++++++++++++- Src/Ruby/Builtins/RubyRegex.cs | 70 +++++++- Src/Ruby/Builtins/UnicodeProperties.cs | 13 ++ Util/regexp-binary-ctype-matrix.rb | 208 +++++++++++++++++++++++ 6 files changed, 482 insertions(+), 8 deletions(-) create mode 100644 Util/regexp-binary-ctype-matrix.rb diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 13b56f072..cc5ae6002 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -207,6 +207,7 @@ public Tests(Driver/*!*/ driver) { Regex_SharedTranslation1, Regex_SharedTranslation2, Regex_PropertyEncoding1, + Regex_BinaryCtype1, Scenario_RubyScopeParsing, Scenario_RubyScopes1, diff --git a/Src/IronRuby.Tests/Runtime/RegexTests.cs b/Src/IronRuby.Tests/Runtime/RegexTests.cs index 8e59971cd..a9328c37f 100644 --- a/Src/IronRuby.Tests/Runtime/RegexTests.cs +++ b/Src/IronRuby.Tests/Runtime/RegexTests.cs @@ -665,6 +665,61 @@ def d(r) = [r.options, r.encoding, r.fixed_encoding?] marshal: [16, #, true] fragment: [16, #, true] fragments: [RegexpError, ""encoding mismatch in dynamic regexp : US-ASCII and UTF-8""] +"); + } + + /// + /// A BINARY subject is matched with Onigmo's ASCII-8BIT ctype table (MRI's + /// rb_reg_prepare_enc compiles a regexp that is not fixed-encoding for the subject's + /// encoding): no letters, punctuation, word characters or case pairs above 0x7F, where .NET + /// sees U+0080-U+00FF. ISO-8859-1 and UTF-8 subjects keep their own letters, and a BINARY + /// regexp's \p{Punct} is [[:punct:]] even on ASCII text. + /// + public void Regex_BinaryCtype1() { + TestOutput(@" +require 'ruby4' +def t(l) + v = begin; yield; rescue => e; [e.class, e.message]; end + puts ""#{l}: #{v.inspect}"" +end +s = ""a\xE9b\xFF c\xC9"".b +t('property /n') { ""\xff"".b =~ /\p{Alpha}/n } +t('posix') { ""\xff"".b =~ Regexp.new('[[:alpha:]]'.b) } +t('word') { ""\xff"".b =~ Regexp.new('\p{Word}'.b) } +t('lower') { ""\xff"".b =~ Regexp.new('\p{Lower}'.b) } +t('negated') { [""\xff"".b =~ /[[:^alpha:]]/, ""\xff"".b =~ /\P{Alpha}/n] } +t('\w') { [""\xff"".b =~ /\w/n, ""\xff"".b =~ /(?u)\w/] } +t('punct') { [""$"".b =~ Regexp.new('\p{Punct}'.b), ""$\xff"".b =~ /[[:punct:]]+/, ""\xab"".b =~ /[[:punct:]]/] } +t('\b') { [s.scan(/\b./), s.split(/\b/)] } +t('\R') { [""\x85"".b =~ /\R/, ""\r\n\x85"".b[/\R+/]] } +t('scan') { s.scan(/[[:alpha:]]+/) } +t('gsub') { s.gsub(/\p{^Alpha}/n, '.') } +t('/i literal') { [""\xC9"".b =~ /\xE9/in, ""\xC9"".b =~ Regexp.new(""\xE9"".b, Regexp::IGNORECASE), ""\xE9"".b =~ /\xE9/in] } +t('/i class') { [""\xC9"".b =~ /[\xE0-\xEF]/in, ""\xC9"".b =~ /[^\xE9]/in, ""A\xE9"".b =~ /[^a]/in, ""A\xE9"".b =~ /a/in] } +t('/i posix') { s.scan(/[[:upper:]]+/i) } +t('(?i)') { ""\xC9a"".b =~ /(?i:\xE9)|(?i)A/n } +t('one regexp') { re = /[[:alpha:]]/; [re.match?(""\u00e9""), re.match?(""\xE9"".b), re.match?(""\u00e9""), re.match?(""\xE9"".dup.force_encoding(""ISO-8859-1""))] } +t('iso-8859-1') { [""\xE9"".dup.force_encoding(""ISO-8859-1"") =~ /[[:alpha:]]/, ""\xC9"".dup.force_encoding(""ISO-8859-1"") =~ Regexp.new(""\xE9"".dup.force_encoding(""ISO-8859-1""), Regexp::IGNORECASE)] } +t('utf-8') { [""\u00e9"" =~ /\p{Alpha}/, ""\u00e9"" =~ /\b/] } +", @" +property /n: nil +posix: nil +word: nil +lower: nil +negated: [0, 0] +\w: [nil, nil] +punct: [0, 0, nil] +\b: [[""a"", ""\xE9"", ""b"", ""\xFF"", ""c"", ""\xC9""], [""a"", ""\xE9"", ""b"", ""\xFF "", ""c"", ""\xC9""]] +\R: [nil, ""\r\n""] +scan: [""a"", ""b"", ""c""] +gsub: ""a.b..c."" +/i literal: [nil, nil, 0] +/i class: [nil, 0, 1, 0] +/i posix: [""a"", ""b"", ""c""] +(?i): 1 +one regexp: [true, false, true, true] +iso-8859-1: [0, 0] +utf-8: [0, 0] "); } } diff --git a/Src/Ruby/Builtins/RegexpTransformer.cs b/Src/Ruby/Builtins/RegexpTransformer.cs index 7e7d7b5b6..57625498d 100644 --- a/Src/Ruby/Builtins/RegexpTransformer.cs +++ b/Src/Ruby/Builtins/RegexpTransformer.cs @@ -113,6 +113,12 @@ private sealed class SharedState { public int Emitted; // see Transform(..., astralSafe) public bool AstralSafe; + // see Transform(..., asciiCtype) + public bool AsciiCtype; + // Whether /i or an inline (?i) may be in effect anywhere in the pattern (AsciiCtype only). + public bool MayIgnoreCase; + // Whether AsciiCtype made the translation differ from the plain one. + public bool AsciiCtypeApplied; } private sealed class ExpansionTooLargeException : Exception { @@ -223,17 +229,37 @@ internal static string Transform(string/*!*/ rubyPattern, RubyRegexOptions optio /// with no pairs needs and is what keeps the common case as fast as it was. /// internal static string Transform(string/*!*/ rubyPattern, RubyRegexOptions options, out bool hasGAnchor, bool astralSafe) { + bool asciiCtypeApplied; + return Transform(rubyPattern, options, out hasGAnchor, astralSafe, false, out asciiCtypeApplied); + } + + /// + /// With the translation is for a match MRI makes with + /// Onigmo's ASCII-8BIT or US-ASCII ctype table (see RubyRegex.UsesAsciiCtype) - a BINARY + /// subject that holds bytes above 0x7F, above all. Those tables have nothing above 0x7F: + /// no letters, digits, spaces or punctuation, and no case pairs. A BINARY subject's bytes + /// reach .NET as U+0080-U+00FF, most of which .NET calls letters, so here the properties + /// (as the POSIX classes they are in those tables), the POSIX brackets, (?u)\w \d \s, + /// \b and \R are restricted to ASCII, and under /i a Latin-1 letter matches only itself. + /// says whether any of that made a difference, i.e. + /// whether the pattern has a construct the restriction applies to. + /// + internal static string Transform(string/*!*/ rubyPattern, RubyRegexOptions options, out bool hasGAnchor, bool astralSafe, + bool asciiCtype, out bool asciiCtypeApplied) { // TODO: surrogates (REXML uses this pattern) if (rubyPattern == "^[\t\n\r -\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF]*$") { hasGAnchor = false; + asciiCtypeApplied = false; return "^(?:[\t\n\r -\uD7FF\uE000-\uFFFD]|[\uD800-\uDBFF][\uDC00-\uDFFF])*$"; } RegexpTransformer transformer = new RegexpTransformer(rubyPattern); transformer._clrOptions = RubyRegex.ToClrOptions(options); transformer._state.AstralSafe = astralSafe; + transformer._state.AsciiCtype = asciiCtype; var result = transformer.Transform(); hasGAnchor = transformer._hasGAnchor; + asciiCtypeApplied = transformer._state.AsciiCtypeApplied; return result; } @@ -539,9 +565,29 @@ private void Append(char c) { } private void AppendEscaped(int c) { + if (IsUnfoldedLatin1Letter(c)) { + _sb.Append("(?-i:"); + AppendEscaped(_sb, c); + _sb.Append(')'); + return; + } AppendEscaped(_sb, c); } + /// + /// A Latin-1 letter that has its other case in U+00C0-U+00FE, while the translation is for + /// a BINARY subject (SharedState.AsciiCtype) under a pattern that may ignore case: Onigmo's + /// ASCII-8BIT folds only A-Z, so it has to be matched case-sensitively, where .NET's + /// IgnoreCase would take "\xC9" for "\xE9". + /// + private bool IsUnfoldedLatin1Letter(int c) { + if (_state.MayIgnoreCase && c >= 0xc0 && c <= 0xfe && c != 0xd7 && c != 0xf7) { + _state.AsciiCtypeApplied = true; + return true; + } + return false; + } + private static StringBuilder/*!*/ AppendEscaped(StringBuilder/*!*/ builder, string/*!*/ str) { for (int i = 0; i < str.Length; i++) { AppendEscaped(builder, str[i]); @@ -604,6 +650,25 @@ private static bool IsMetaCharacter(int c) { ((options & RegexOptions.IgnorePatternWhitespace) != 0 ? "x" : "")); } + /// + /// Whether some (?i) or (?i:...) - the i possibly among other options, before any '-' - + /// may turn /i on. Errs on the side of yes (an escaped \(?i) counts), which costs no + /// more than a (?-i:...) around a Latin-1 letter that did not need one. + /// + private static bool HasInlineIgnoreCase(string/*!*/ pattern) { + int i = 0; + while ((i = pattern.IndexOf("(?", i, StringComparison.Ordinal)) >= 0) { + i += 2; + while (i < pattern.Length && "imxadu".IndexOf(pattern[i]) >= 0) { + if (pattern[i] == 'i') { + return true; + } + i++; + } + } + return false; + } + private string/*!*/ Transform() { if (_copyGroups) { return TransformBody(); @@ -616,8 +681,12 @@ private static bool IsMetaCharacter(int c) { for (int depth = DefaultMaxCallDepth; ; depth /= 2) { bool astralSafe = _state.AstralSafe; + bool asciiCtype = _state.AsciiCtype; _state = new SharedState(); _state.AstralSafe = astralSafe; + _state.AsciiCtype = asciiCtype; + _state.MayIgnoreCase = asciiCtype && + ((_clrOptions & RegexOptions.IgnoreCase) != 0 || HasInlineIgnoreCase(_rubyPattern)); _state.MaxCallDepth = depth; _state.ClrOptions = _clrOptions; _state.RootPattern = _rubyPattern; @@ -863,6 +932,10 @@ private void Parse(bool isSubexpression) { } break; } + if (IsUnfoldedLatin1Letter(c)) { + _sb.Append("(?-i:").Append((char)c).Append(')'); + break; + } Append((char)c); break; } @@ -1532,7 +1605,13 @@ private void ParseEscape(int escape) { switch (escape) { case 'b': // word boundary case 'B': // not a word boundary - if (_state.AstralSafe) { + if (_state.AsciiCtype) { + // a BINARY subject's word characters are ASCII ones + _state.AsciiCtypeApplied = true; + _sb.Append(escape == 'b' + ? "(?:(?<=[0-9A-Za-z_])(?![0-9A-Za-z_])|(?\\r\\n|[\\n\\v\\f\\r\\u0085\\u2028\\u2029])"); + // In a BINARY subject (SharedState.AsciiCtype) 0x85 is no line terminator. + _state.AsciiCtypeApplied |= _state.AsciiCtype; + _sb.Append(_state.AsciiCtype ? "(?>\\r\\n|[\\n\\v\\f\\r])" : "(?>\\r\\n|[\\n\\v\\f\\r\\u0085\\u2028\\u2029])"); break; case 'K': @@ -1624,7 +1705,7 @@ private void ParseEscape(int escape) { } var set = ParseCharacterEscape(escape); - if ((escape == 'w' || escape == 'W') && _characterClassMode == CharacterClassMode.Unicode) { + if ((escape == 'w' || escape == 'W') && _characterClassMode == CharacterClassMode.Unicode && !_state.AsciiCtype) { // Outside a class Onigmo tests a (?u)\w below U+0100 against its ISO-8859-1 // ctype table, which also counts the superscripts and vulgar fractions // (U+00B2 U+00B3 U+00B9 U+00BC-U+00BE) as word characters. @@ -2164,6 +2245,26 @@ private void AppendAnyCharacter() { /// a * or + follows is emitted as one class (CharacterSet.AppendLoopBodyTo), for speed. /// private void AppendCharacterSet(CharacterSet/*!*/ set, bool parenthesize) { + if (_state.MayIgnoreCase) { + int[] latin1 = set.GetLatin1Members(); + if (!CodePointRanges.IsLatin1CaseClosed(latin1)) { + _state.AsciiCtypeApplied = true; + // .NET's IgnoreCase would fold the Latin-1 letters, Onigmo's ASCII-8BIT does + // not: the ASCII members as the set itself (so that [^a] still turns "A" + // away under /i), the others case-sensitively, as listed. + _sb.Append("(?:(?![\\x80-\\xff])"); + set.AppendTo(_sb, true); + int[] high = CodePointRanges.Intersect(latin1, CodePointRanges.Single(0x80, 0xff)); + if (high.Length != 0) { + _sb.Append("|(?-i:"); + CharacterSet.MakeSet(high, null).AppendTo(_sb, true); + _sb.Append(')'); + } + _sb.Append(')'); + return; + } + } + int next = Peek(); if ((next == '*' || next == '+') && set.HasAllAstral) { set.AppendLoopBodyTo(_sb); @@ -2185,7 +2286,10 @@ private void AppendCharacterSet(CharacterSet/*!*/ set, bool parenthesize) { /// private CharacterSet/*!*/ MakeAsciiAware(string/*!*/ property, int[]/*!*/ ascii, string/*!*/ asciiText, bool positive) { if (_characterClassMode == CharacterClassMode.Unicode) { - return CharacterSet.MakeProperty(UnicodeProperties.Find(property), positive); + if (!_state.AsciiCtype) { + return CharacterSet.MakeProperty(UnicodeProperties.Find(property), positive); + } + _state.AsciiCtypeApplied = true; } var result = CharacterSet.MakeSet(ascii, asciiText); return positive ? result : result.Complement(); @@ -2306,6 +2410,7 @@ private sealed class CharacterSet { public static readonly CharacterSet Empty = new CharacterSet(CodePointRanges.Empty, false, "", -1, -1); private static readonly int[] BmpRange = CodePointRanges.Single(0, 0xffff); + private static readonly int[] Latin1Range = CodePointRanges.Single(0, 0xff); private static readonly int[] AstralRange = CodePointRanges.Single(0x10000, CodePointRanges.MaxCodePoint); private static readonly int[] SurrogateRange = CodePointRanges.Single(0xd800, 0xdfff); @@ -2363,6 +2468,12 @@ private CharacterSet(int[]/*!*/ ranges, bool negated) return new CharacterSet(UnicodeProperties.GetRanges(table), !positive, null, -1, table); } + /// The members in U+0000-U+00FF, the characters a BINARY subject is made of. + internal int[]/*!*/ GetLatin1Members() { + int[] members = CodePointRanges.Intersect(_ranges, Latin1Range); + return _negated ? CodePointRanges.Subtract(Latin1Range, members) : members; + } + internal bool IsSingleCharacter { get { return _singleCodepoint >= 0; } } @@ -2955,6 +3066,14 @@ private CharacterSet ParseCharacter(ref IEnumerator codepoints, out bool ma if (table < 0) { throw MakeError("invalid character property name {" + name + "}"); } + if (_state.AsciiCtype) { + _state.AsciiCtypeApplied = true; + // A BINARY subject: the ASCII-8BIT ctype table, whose properties are the POSIX + // classes (\p{Punct} takes in $+<=>^`|~ there) over ASCII. A non-POSIX name never + // gets here: it makes the regexp fixed-encoding and not BINARY. + int posix = UnicodeProperties.FindPosix(normalized); + return RestrictToAscii(CharacterSet.MakeProperty(posix >= 0 ? posix : table, true), positive); + } return CharacterSet.MakeProperty(table, positive); } @@ -2997,17 +3116,27 @@ private CharacterSet ParsePosixCharacterClass() { private static readonly int[] _asciiRange = new int[] { 0, 0x7f }; - /// [[:name:]]: Onigmo's property of that name, all of Unicode unless (?a) is in effect. + /// + /// [[:name:]]: Onigmo's property of that name, all of Unicode unless (?a) is in effect or + /// the subject is BINARY (SharedState.AsciiCtype). + /// private CharacterSet/*!*/ MakePosixCharacterClass(int table, bool positive) { var result = CharacterSet.MakeProperty(table, true); - if (_characterClassMode == CharacterClassMode.Ascii) { + if (_characterClassMode == CharacterClassMode.Ascii || _state.AsciiCtype) { // (?a) restricts the POSIX classes to ASCII. A negated class still matches // non-ASCII: (?a)[[:^alpha:]] accepts a Hiragana character. - result = result.Intersect(CharacterSet.MakeSet(_asciiRange, null)); + _state.AsciiCtypeApplied |= _state.AsciiCtype; + return RestrictToAscii(result, positive); } return positive ? result : result.Complement(); } + /// The ASCII members of , or every character but those. + private static CharacterSet/*!*/ RestrictToAscii(CharacterSet/*!*/ set, bool positive) { + var result = set.Intersect(CharacterSet.MakeSet(_asciiRange, null)); + return positive ? result : result.Complement(); + } + #endregion } } diff --git a/Src/Ruby/Builtins/RubyRegex.cs b/Src/Ruby/Builtins/RubyRegex.cs index 0c1a4e125..71071865c 100644 --- a/Src/Ruby/Builtins/RubyRegex.cs +++ b/Src/Ruby/Builtins/RubyRegex.cs @@ -46,6 +46,17 @@ public partial class RubyRegex : IEquatable, IDuplicable, IRubyObject private Regex _cachedAstralRegex; private TimeSpan _cachedAstralTimeout; + // The same pattern translated for a match Onigmo makes with its ASCII-8BIT or US-ASCII + // ctype table (UsesAsciiCtype) - above all a BINARY subject with bytes above 0x7F, which + // has no letters, punctuation or case pairs there, where .NET sees U+0080-U+00FF (see + // RegexpTransformer.Transform(..., asciiCtype)). + private Regex _cachedBinaryRegex; + private TimeSpan _cachedBinaryTimeout; + // Set once that translation has turned out to be the plain one - the pattern has no + // property, POSIX class, \b, \R or /i Latin-1 letter - so that such a subject keeps + // matching with _cachedRegex, which is compiled once it has been used enough. + private bool _binaryIsPlain; + // The same CLR regex forced to start where the search starts, for the scanning operations // that only ever look at the current position (StringScanner#scan, #skip, #check, #match?). // Cached against the regex it was derived from, so it follows _cachedRegex's own lifetime. @@ -154,6 +165,8 @@ public void Set(MutableString/*!*/ pattern, RubyRegexOptions options) { _options = options & ~RubyRegexOptions.Once; _cachedRegex = null; _cachedAstralRegex = null; + _cachedBinaryRegex = null; + _binaryIsPlain = false; _nonAsciiEscape = -1; _hasProperty = -1; @@ -241,7 +254,62 @@ private void RequireMatchableEncoding(MutableString/*!*/ input) { // O(1): matching has just validated the input, which works the flags out astral = input.HasSurrogatePairs(); - return astral ? TransformAstralPattern() : TransformPattern(countUse); + if (astral) { + return TransformAstralPattern(); + } + if (UsesAsciiCtype(input)) { + return TransformBinaryPattern(countUse); + } + return TransformPattern(countUse); + } + + /// + /// Whether MRI would match with Onigmo's ASCII-8BIT or US-ASCII + /// ctype table. rb_reg_prepare_enc compiles a regexp that is not fixed-encoding for the + /// subject's encoding, and a fixed one for its own (the subject is then in that encoding + /// or ASCII only). Two cases differ from the plain translation: a BINARY subject with + /// bytes above 0x7F (a US-ASCII subject that got here is ASCII), and a BINARY or US-ASCII + /// regexp with a property, whose \p{Punct} is [[:punct:]] even on ASCII text. Any other + /// fixed BINARY or US-ASCII regexp matches ASCII text as the plain translation does. + /// + private bool UsesAsciiCtype(MutableString/*!*/ input) { + if (input.Encoding == RubyEncoding.Binary && !input.IsAscii()) { + return true; + } + if (PatternHasProperty) { + RubyEncoding encoding = Encoding; + return encoding == RubyEncoding.Binary || encoding == RubyEncoding.Ascii; + } + return false; + } + + private Regex/*!*/ TransformBinaryPattern(bool countUse) { + TimeSpan timeout = EffectiveTimeout; + if (_binaryIsPlain) { + return TransformPattern(countUse); + } + if (_cachedBinaryRegex != null && timeout == _cachedBinaryTimeout) { + return _cachedBinaryRegex; + } + + // the plain translation first: it validates the pattern and sets _hasGAnchor + Regex plain = TransformPattern(false); + Regex result; + try { + bool hasGAnchor, applied; + string translated = RegexpTransformer.Transform(GetClrPatternSource(), _options, out hasGAnchor, false, true, out applied); + if (!applied) { + _binaryIsPlain = true; + return plain; + } + result = new Regex(translated, plain.Options, timeout); + } catch (Exception) { + result = plain; + } + + _cachedBinaryTimeout = timeout; + _cachedBinaryRegex = result; + return result; } private Regex/*!*/ TransformAstralPattern() { diff --git a/Src/Ruby/Builtins/UnicodeProperties.cs b/Src/Ruby/Builtins/UnicodeProperties.cs index b5e8fa452..c6fe617f2 100644 --- a/Src/Ruby/Builtins/UnicodeProperties.cs +++ b/Src/Ruby/Builtins/UnicodeProperties.cs @@ -228,6 +228,19 @@ internal static bool Contains(int[]/*!*/ ranges, int low, int high) { return false; } + /// + /// Whether, of each Latin-1 letter pair U+00C0-U+00DE / U+00E0-U+00FE (but the + /// multiplication and division signs), holds both or neither. + /// + internal static bool IsLatin1CaseClosed(int[]/*!*/ ranges) { + for (int c = 0xc0; c <= 0xde; c++) { + if (c != 0xd7 && Contains(ranges, c, c) != Contains(ranges, c + 0x20, c + 0x20)) { + return false; + } + } + return true; + } + internal static bool Equals(int[]/*!*/ a, int[]/*!*/ b) { if (a.Length != b.Length) { return false; diff --git a/Util/regexp-binary-ctype-matrix.rb b/Util/regexp-binary-ctype-matrix.rb new file mode 100644 index 000000000..e0bd33e61 --- /dev/null +++ b/Util/regexp-binary-ctype-matrix.rb @@ -0,0 +1,208 @@ +# Differential matrix for character types in a regexp matched against a BINARY or US-ASCII +# subject, against ISO-8859-1 and UTF-8 subjects as controls. +# +# ruby Util/regexp-binary-ctype-matrix.rb > /tmp/ctype.mri +# ./ir.sh Util/regexp-binary-ctype-matrix.rb > /tmp/ctype.ir +# diff -u /tmp/ctype.mri /tmp/ctype.ir +# +# MRI compiles a regexp that is not fixed-encoding against the subject's encoding +# (rb_reg_prepare_enc), and Onigmo's ASCII-8BIT and US-ASCII ctype tables have no letters, +# digits, spaces or punctuation above 0x7F, nor any case pairs there. So against a binary +# string \p{Alpha}, [[:alpha:]], (?u)\w, \b and /i see the bytes 0x80-0xFF as nothing at all, +# while ISO-8859-1 keeps its own letters ("\xE9" is e-acute) and UTF-8 all of Unicode's. +# IronRuby matches one CLR regex over the subject decoded to chars, where a binary byte +# 0x80-0xFF is U+0080-U+00FF and .NET would call most of them letters. +# +# A row lists, for each subject encoding, which of the characters 0x80-0xFF (and 0x00-0x7F, +# as a check that ASCII is unchanged) the pattern matches, as hex ranges. +# +# The BINARY and US-ASCII columns and the entry points agree with CRuby 4.0. Rows that still +# differ, all in the other columns and all older than this matrix: ISO-8859-1 subjects are +# matched with Unicode's tables rather than Onigmo's ISO-8859-1 ctype table ([[:punct:]], +# [[:space:]], \s, (?u)\s, \R and 0x85, [[:word:]] and \b with the superscripts and fractions, +# (?a)[[:alpha:]], [[:upper:]]/i), UTF-8's \b and \B do not count U+00B2 U+00B3 U+00B9 +# U+00BC-U+00BE as word characters, and UTF-8's [[:upper:]]/i misses U+00B5. + +require "strscan" + +ENCODINGS = [Encoding::BINARY, Encoding::ISO_8859_1, Encoding::UTF_8] + +def subject(code, enc) + if enc == Encoding::UTF_8 + code.chr(Encoding::UTF_8) + else + code.chr.force_encoding(enc) + end +end + +def ranges(codes) + return "-" if codes.empty? + out = [] + start = prev = codes.first + codes.drop(1).each do |c| + if c == prev + 1 + prev = c + next + end + out << (start == prev ? "%02x" % start : "%02x-%02x" % [start, prev]) + start = prev = c + end + out << (start == prev ? "%02x" % start : "%02x-%02x" % [start, prev]) + out.join(",") +end + +def attempt + yield +rescue Exception => e + "#{e.class}: #{e.message[0, 70]}" +end + +# Which single characters of each encoding the regexp matches, as a whole-string match. +def row(label, re) + print label.ljust(34), " ", "#{re.encoding.name}#{re.fixed_encoding? ? '!' : ''}".ljust(11) + cols = ENCODINGS.map do |enc| + attempt do + lo = (0..0x7f).select { |c| re.match?(subject(c, enc)) } + hi = (0x80..0xff).select { |c| re.match?(subject(c, enc)) } + "#{enc.name}[#{ranges(lo)} | #{ranges(hi)}]" + end + end + # US-ASCII: only ASCII strings are valid, so the ASCII half is all there is to compare + cols << attempt do + lo = (0..0x7f).select { |c| re.match?(c.chr.force_encoding(Encoding::US_ASCII)) } + "US-ASCII[#{ranges(lo)}]" + end + puts cols.join(" ") +end + +def build(src, opts = 0) + attempt { Regexp.new(src, opts) } +end + +# Each pattern is made from a BINARY source and from a UTF-8 one. A property escape makes the +# regexp fixed-encoding (BINARY from a BINARY source, US-ASCII from a UTF-8 one, which then +# refuses a non-ASCII subject of any other encoding); anything else gives a US-ASCII regexp that +# is not fixed and is compiled for the subject's encoding. The column after the pattern is the +# regexp's encoding, with ! when it is fixed. +PATTERNS = [ + '\A\p{Alpha}\z', '\A\p{^Alpha}\z', '\A\P{Alpha}\z', '\A\p{Word}\z', '\A\p{Lower}\z', + '\A\p{Upper}\z', '\A\p{Alnum}\z', '\A\p{Punct}\z', '\A\p{Space}\z', '\A\p{Print}\z', + '\A\p{Graph}\z', '\A\p{Cntrl}\z', '\A\p{Digit}\z', '\A\p{XDigit}\z', '\A\p{Blank}\z', + '\A\p{ASCII}\z', '\A\p{Any}\z', + '\A[[:alpha:]]\z', '\A[[:^alpha:]]\z', '\A[^[:alpha:]]\z', '\A[[:punct:]]\z', '\A[[:lower:]]\z', + '\A[[:upper:]]\z', '\A[[:alnum:]]\z', '\A[[:space:]]\z', '\A[[:print:]]\z', '\A[[:graph:]]\z', + '\A[[:word:]]\z', '\A[[:cntrl:]]\z', '\A[[:xdigit:]]\z', '\A[[:ascii:]]\z', + '\A[[:alpha:]&&[^a-z]]\z', '\A[\p{Alpha}0-9]\z', '\A[^\p{Alpha}]\z', '\A[\w\x80]\z', + '\A\w\z', '\A\W\z', '\A\d\z', '\A\s\z', '\A\h\z', '\A\H\z', + '\A(?u)\w\z', '\A(?u)\W\z', '\A(?u)\s\z', '\A(?u)\d\z', '\A(?u:[\w])\z', + '\A(?a)[[:alpha:]]\z', '\A(?a)\p{Alpha}\z', + '\b', '\B', '\A.\b', '(?u)\b', '\A\R\z', '\A\X\z', '\A.\z', + '\A\p{Greek}\z', '\A\p{L}\z', '\A\p{Latin}\z', +] + +PATTERNS.each do |src| + [[src.b, ""], [src, " (utf8 src)"]].each do |source, tag| + re = build(source) + if re.is_a?(String) + puts "#{(src + tag).ljust(34)} #{re}" + else + row(src + tag, re) + end + end +end + +puts +puts "# case-insensitive" +PATTERNS_I = [ + '\A\p{Lower}\z', '\A\p{Upper}\z', '\A[[:lower:]]\z', '\A[[:upper:]]\z', '\A[a-z]\z', '\A\w\z', + '\A[^a-z]\z', '\A(?u)\w\z', +] +PATTERNS_I.each do |src| + re = build(src.b, Regexp::IGNORECASE) + if re.is_a?(String) + puts "#{(src + '/i').ljust(34)} #{re}" + else + row(src + "/i", re) + end +end + +# A pattern that spells a non-ASCII character: /i must fold it in ISO-8859-1 and UTF-8 only. +puts +puts "# non-ASCII literals, /i" +[[0xe9, 0xc9], [0xc9, 0xe9], [0xff, nil], [0xe0, 0xc0], [0xb5, nil], [0xdf, nil], [0xe9, 0xe9]].each do |pat, other| + ENCODINGS.each do |enc| + pattern = subject(pat, enc) + [0, Regexp::IGNORECASE].each do |opt| + re = attempt { Regexp.new(pattern, opt) } + results = (0x80..0xff).select { |c| attempt { re.match?(subject(c, enc)) } == true } + puts "lit %02x %-10s %-2s => %s" % [pat, enc.name, opt == 0 ? "" : "i", ranges(results)] + end + # a class range with a non-ASCII bound + lo = [pat, other || pat].min + hi = [pat, other || pat].max + cls = "[".encode(enc) + subject(lo, enc) + "-".encode(enc) + subject(hi, enc) + "]".encode(enc) + re = attempt { Regexp.new(cls, Regexp::IGNORECASE) } + results = (0x80..0xff).select { |c| attempt { re.match?(subject(c, enc)) } == true } + puts "cls %02x-%02x %-10s i => %s" % [lo, hi, enc.name, ranges(results)] + re = attempt { Regexp.new("[^".encode(enc) + subject(pat, enc) + "]".encode(enc), Regexp::IGNORECASE) } + results = (0x80..0xff).select { |c| attempt { re.match?(subject(c, enc)) } == true } + puts "neg %02x %-10s i => %s" % [pat, enc.name, ranges(results)] + end +end + +# The /n literals: an ASCII-only /n regexp is US-ASCII and not fixed; one with a byte escape +# above 0x7F is fixed BINARY. +puts +puts "# /n literals" +NREGEXPS = { + '/\p{Alpha}/n' => /\p{Alpha}/n, '/[[:alpha:]]/n' => /[[:alpha:]]/n, '/\w/n' => /\w/n, + '/(?u)\w/n' => /(?u)\w/n, '/\xff|\p{Alpha}/n' => /\xff|\p{Alpha}/n, + '/\xff|[[:alpha:]]/n' => /\xff|[[:alpha:]]/n, '/\xff|\b/n' => /\xff|\b/n, + '/\xe9/in' => /\xe9/in, '/[\xe0-\xef]/in' => /[\xe0-\xef]/in, '/\p{Lower}/in' => /\p{Lower}/in, + '/\p{Alpha}/u' => /\p{Alpha}/u, '/[[:alpha:]]/' => /[[:alpha:]]/, +} +NREGEXPS.each do |label, re| + print label.ljust(34), " enc=#{re.encoding} fixed=#{re.fixed_encoding?} " + hi = (0x80..0xff).map { |c| [c, attempt { (c.chr.b =~ re) }] } + matched = hi.select { |_, r| r.is_a?(Integer) }.map(&:first) + errors = hi.map(&:last).grep(String).uniq + puts "BINARY[#{ranges(matched)}]#{errors.empty? ? '' : ' ' + errors.join(' ')}" +end + +# The same question through every matching entry point, on a mixed binary string. +puts +puts "# entry points" +s = "a\xE9b\xFF c\xC9".b +re = Regexp.new('\p{Alpha}+') +ri = Regexp.new('[a-z]+', Regexp::IGNORECASE) +rb = Regexp.new('\b') +[ + ["=~", -> { s =~ Regexp.new('[[:alpha:]]{2}') }], + ["match", -> { s.match(re)&.to_a }], + ["match?", -> { s.match?(Regexp.new('\p{Alpha}\p{Alpha}')) }], + ["scan", -> { s.scan(re) }], + ["scan /i", -> { s.scan(ri) }], + ["scan \\b", -> { s.scan(Regexp.new('\b.')) }], + ["gsub", -> { s.gsub(re, "<\\0>") }], + ["sub", -> { s.sub(Regexp.new('[[:alpha:]](?=[[:alpha:]])'), "#") }], + ["split", -> { s.split(Regexp.new('[[:^alpha:]]')) }], + ["split \\b", -> { s.split(rb) }], + ["index", -> { s.index(Regexp.new('\p{Alpha}'), 1) }], + ["rindex", -> { s.rindex(Regexp.new('\p{Alpha}')) }], + ["[]", -> { s[Regexp.new('\p{Alpha}{2,}')] }], + ["slice!", -> { t = s.dup; [t.slice!(Regexp.new('[[:alpha:]]+\z')), t] }], + ["start_with?", -> { s.start_with?(Regexp.new('\p{Alpha}{2}')) }], + ["partition", -> { s.partition(Regexp.new('[[:alpha:]]{2}')) }], + ["count words", -> { s.scan(Regexp.new('\p{Word}+')).size }], + ["tr-like gsub", -> { s.gsub(Regexp.new('[^[:alpha:]]'), ".") }], + ["StringScanner#scan", -> { ss = StringScanner.new(s); [ss.scan(re), ss.scan(re), ss.pos] }], + ["StringScanner#scan_until", -> { ss = StringScanner.new(s); [ss.scan_until(Regexp.new('\p{Alpha}{2}')), ss.pos] }], + ["StringScanner#check", -> { ss = StringScanner.new(s); ss.pos = 1; ss.check(Regexp.new('[[:alpha:]]')) }], + ["Regexp#match pos", -> { re.match(s, 2)&.begin(0) }], + ["Regexp.union", -> { s.scan(Regexp.union(re, /\d/)) }], + ["same re, UTF-8 then BINARY", -> { [re.match?("é"), re.match?("\xE9".b), re.match?("é")] }], + ["same re, ISO-8859-1, BINARY", -> { [re.match?("\xE9".dup.force_encoding("ISO-8859-1")), re.match?("\xE9".b)] }], + ["astral UTF-8 then BINARY", -> { [re.match?("\u{1D4B3}é"), re.match?("\xE9".b)] }], +].each do |label, probe| + puts "#{label.ljust(30)} => #{attempt { probe.call }.inspect}" +end From fae9e1b27835e7e6feb0777015716d0160e9259c Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 22:58:52 +0000 Subject: [PATCH 2/2] Address the review of the BINARY ctype translation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (?~\xE9a)/in lost the fixed-length prefix of its absent operand: the case-sensitive (?-i:é) the translation wraps a Latin-1 letter in made GetLiteralLength give up, so matching "\xE9a".b from position 1 returned "" where CRuby 4.0 returns "a". GetLiteralLength now counts the wrapper as the one character it is, and a lone \xE9 escape is emitted as that wrapper too instead of the general ASCII/Latin-1 class split. The cached BINARY regex and the timeout it was made with were two fields, so two threads rebuilding it across a timeout change could pair one's regex with the other's timeout. They are now one Tuple published with one write, as RecompiledFor's cache is. Regex_BinaryCtype1 gains the absent-operator cases, expectations from CRuby 4.0.10. Util/regexp-binary-ctype-matrix.rb and regexp-escaped-byte-matrix.rb are unchanged against CRuby. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013PQjtyXebXCReTZrAePmUQ --- Src/IronRuby.Tests/Runtime/RegexTests.cs | 2 ++ Src/Ruby/Builtins/RegexpTransformer.cs | 33 +++++++++++++++++++----- Src/Ruby/Builtins/RubyRegex.cs | 17 ++++++------ 3 files changed, 38 insertions(+), 14 deletions(-) diff --git a/Src/IronRuby.Tests/Runtime/RegexTests.cs b/Src/IronRuby.Tests/Runtime/RegexTests.cs index d92b0879b..663e6052c 100644 --- a/Src/IronRuby.Tests/Runtime/RegexTests.cs +++ b/Src/IronRuby.Tests/Runtime/RegexTests.cs @@ -885,6 +885,7 @@ def t(l) t('one regexp') { re = /[[:alpha:]]/; [re.match?(""\u00e9""), re.match?(""\xE9"".b), re.match?(""\u00e9""), re.match?(""\xE9"".dup.force_encoding(""ISO-8859-1""))] } t('iso-8859-1') { [""\xE9"".dup.force_encoding(""ISO-8859-1"") =~ /[[:alpha:]]/, ""\xC9"".dup.force_encoding(""ISO-8859-1"") =~ Regexp.new(""\xE9"".dup.force_encoding(""ISO-8859-1""), Regexp::IGNORECASE)] } t('utf-8') { [""\u00e9"" =~ /\p{Alpha}/, ""\u00e9"" =~ /\b/] } +t('absent /i') { a = ""\xE9a"".b; [a.match(/(?~\xE9a)/in, 0)[0], a.match(/(?~\xE9a)/in, 1)[0], ""\xC9a"".b.match(/(?~\xE9a)/in)[0], a.match(/(?~\xC9a)/in)[0]] } ", @" property /n: nil posix: nil @@ -904,6 +905,7 @@ def t(l) one regexp: [true, false, true, true] iso-8859-1: [0, 0] utf-8: [0, 0] +absent /i: [""\xE9"", ""a"", ""\xC9a"", ""\xE9a""] "); } } diff --git a/Src/Ruby/Builtins/RegexpTransformer.cs b/Src/Ruby/Builtins/RegexpTransformer.cs index a55c3701b..ee6e7951d 100644 --- a/Src/Ruby/Builtins/RegexpTransformer.cs +++ b/Src/Ruby/Builtins/RegexpTransformer.cs @@ -566,14 +566,26 @@ private void Append(char c) { private void AppendEscaped(int c) { if (IsUnfoldedLatin1Letter(c)) { - _sb.Append("(?-i:"); - AppendEscaped(_sb, c); - _sb.Append(')'); + AppendUnfoldedLatin1Letter(c); return; } AppendEscaped(_sb, c); } + private const string CaseSensitiveLatin1Prefix = "(?-i:"; + + /// + /// (?-i:c) for a letter IsUnfoldedLatin1Letter accepts; GetLiteralLength counts it as the + /// one character it is, so that (?~...) keeps its fixed-length prefix. + /// + private void AppendUnfoldedLatin1Letter(int c) { + _sb.Append(CaseSensitiveLatin1Prefix).Append((char)c).Append(')'); + } + + private static bool IsUnfoldableLatin1Letter(int c) { + return c >= 0xc0 && c <= 0xfe && c != 0xd7 && c != 0xf7; + } + /// /// A Latin-1 letter that has its other case in U+00C0-U+00FE, while the translation is for /// a BINARY subject (SharedState.AsciiCtype) under a pattern that may ignore case: Onigmo's @@ -581,7 +593,7 @@ private void AppendEscaped(int c) { /// IgnoreCase would take "\xC9" for "\xE9". /// private bool IsUnfoldedLatin1Letter(int c) { - if (_state.MayIgnoreCase && c >= 0xc0 && c <= 0xfe && c != 0xd7 && c != 0xf7) { + if (_state.MayIgnoreCase && IsUnfoldableLatin1Letter(c)) { _state.AsciiCtypeApplied = true; return true; } @@ -935,7 +947,7 @@ private void Parse(bool isSubexpression) { break; } if (IsUnfoldedLatin1Letter(c)) { - _sb.Append("(?-i:").Append((char)c).Append(')'); + AppendUnfoldedLatin1Letter(c); break; } Append((char)c); @@ -1547,7 +1559,11 @@ private static int GetLiteralLength(string/*!*/ pattern) { int length = 0; for (int i = 0; i < pattern.Length; i++) { char c = pattern[i]; - if (c == '\\') { + if (c == '(' && i + 6 < pattern.Length && String.CompareOrdinal(pattern, i, CaseSensitiveLatin1Prefix, 0, 5) == 0 && + pattern[i + 6] == ')' && IsUnfoldableLatin1Letter(pattern[i + 5])) { + // one Latin-1 letter matched case-sensitively for a BINARY subject (AppendUnfoldedLatin1Letter) + i += 6; + } else if (c == '\\') { // a meta character or a whitespace character, as Escape writes them if (i + 1 == pattern.Length || !(IsMetaCharacter(pattern[i + 1]) || Char.IsWhiteSpace(pattern[i + 1]))) { return -1; @@ -2252,6 +2268,11 @@ private void AppendAnyCharacter() { /// private void AppendCharacterSet(CharacterSet/*!*/ set, bool parenthesize) { if (_state.MayIgnoreCase) { + if (set.IsSingleCharacter && IsUnfoldedLatin1Letter(set.SingleCodepoint)) { + // \xE9: the letter itself, spelled as a literal one is + AppendUnfoldedLatin1Letter(set.SingleCodepoint); + return; + } int[] latin1 = set.GetLatin1Members(); if (!CodePointRanges.IsLatin1CaseClosed(latin1)) { _state.AsciiCtypeApplied = true; diff --git a/Src/Ruby/Builtins/RubyRegex.cs b/Src/Ruby/Builtins/RubyRegex.cs index 4687eaa90..e543439b1 100644 --- a/Src/Ruby/Builtins/RubyRegex.cs +++ b/Src/Ruby/Builtins/RubyRegex.cs @@ -52,9 +52,10 @@ public partial class RubyRegex : IEquatable, IDuplicable, IRubyObject // The same pattern translated for a match Onigmo makes with its ASCII-8BIT or US-ASCII // ctype table (UsesAsciiCtype) - above all a BINARY subject with bytes above 0x7F, which // has no letters, punctuation or case pairs there, where .NET sees U+0080-U+00FF (see - // RegexpTransformer.Transform(..., asciiCtype)). - private Regex _cachedBinaryRegex; - private TimeSpan _cachedBinaryTimeout; + // RegexpTransformer.Transform(..., asciiCtype)). The regex and the timeout it was made + // with are published together, so that a thread never pairs one rebuild's regex with + // another's timeout. + private Tuple _cachedBinary; // Set once that translation has turned out to be the plain one - the pattern has no // property, POSIX class, \b, \R or /i Latin-1 letter - so that such a subject keeps // matching with _cachedRegex, which is compiled once it has been used enough. @@ -170,7 +171,7 @@ public void Set(MutableString/*!*/ pattern, RubyRegexOptions options) { _options = options & ~RubyRegexOptions.Once; _cachedRegex = null; _cachedAstralRegex = null; - _cachedBinaryRegex = null; + _cachedBinary = null; _binaryIsPlain = false; _nonAsciiEscape = -1; _hasProperty = -1; @@ -344,8 +345,9 @@ private bool UsesAsciiCtype(MutableString/*!*/ input) { if (_binaryIsPlain) { return TransformPattern(countUse); } - if (_cachedBinaryRegex != null && timeout == _cachedBinaryTimeout) { - return _cachedBinaryRegex; + var cached = _cachedBinary; + if (cached != null && timeout == cached.Item1) { + return cached.Item2; } // the plain translation first: it validates the pattern and sets _hasGAnchor @@ -363,8 +365,7 @@ private bool UsesAsciiCtype(MutableString/*!*/ input) { result = plain; } - _cachedBinaryTimeout = timeout; - _cachedBinaryRegex = result; + _cachedBinary = Tuple.Create(timeout, result); return result; }