diff --git a/Src/Libraries/Builtins/KernelOps.cs b/Src/Libraries/Builtins/KernelOps.cs index f75a73ffc..8b5693061 100644 --- a/Src/Libraries/Builtins/KernelOps.cs +++ b/Src/Libraries/Builtins/KernelOps.cs @@ -1955,6 +1955,149 @@ public static object GetHiddenInstanceVariable(RubyContext/*!*/ context, object return value; } + /// + /// Data.new (ruby4.rb) for the usual call: when the class's initialize is Data#initialize itself and the + /// arguments are a value for every member, positionally or as keywords named by their Symbols, the new + /// frozen instance, made the way Data#initialize would have made it; null for anything else - an + /// initialize of the class's own, missing, unknown or String keys, the wrong count - which the caller + /// then does the long way, through initialize. MRI's rb_class_new_instance_pass_kw allocates without + /// calling #allocate and rb_data_initialize_m freezes without calling #freeze, as this does. + /// + [RubyMethod("__ir_data_new__", RubyMethodAttributes.PrivateInstance)] + public static object DataNew(RubyContext/*!*/ context, object self, [NotNull]RubyClass/*!*/ dataClass, + [NotNull]RubyArray/*!*/ args, [NotNull]Hash/*!*/ kwargs) { + var cls = self as RubyClass; + DataLayout layout; + if (cls == null || (layout = GetDataLayout(context, cls, dataClass)) == null) { + return null; + } + var members = layout.Members; + int n = members.Length; + var values = new object[n]; + if (args.Count != 0) { + if (kwargs.Count != 0 || args.Count != n) { + return null; + } + for (int i = 0; i < n; i++) { + values[i] = args[i]; + } + } else { + if (kwargs.Count != n) { + return null; + } + for (int i = 0; i < n; i++) { + if (!kwargs.TryGetValue(members[i], out values[i])) { + return null; + } + } + } + return NewData(context, cls, layout, values); + } + + /// + /// Data#with (ruby4.rb) for the usual call: keywords that are all members named by their Symbols, on an + /// instance whose class's initialize is Data#initialize. The copy MRI's rb_data_with makes by passing + /// to_h merged with the keywords to initialize, made directly; null for anything else. + /// + [RubyMethod("__ir_data_with__", RubyMethodAttributes.PrivateInstance)] + public static object DataWith(RubyContext/*!*/ context, object self, [NotNull]RubyClass/*!*/ dataClass, [NotNull]Hash/*!*/ kwargs) { + var cls = context.GetClassOf(self).GetNonSingletonClass(); + var layout = GetDataLayout(context, cls, dataClass); + if (layout == null) { + return null; + } + var members = layout.Members; + int n = members.Length; + var values = new object[n]; + int found = 0; + for (int i = 0; i < n; i++) { + if (kwargs.TryGetValue(members[i], out values[i])) { + found++; + } else { + context.TryGetInstanceVariable(self, layout.Variables[i], out values[i]); + } + } + return found == kwargs.Count ? NewData(context, cls, layout, values) : null; + } + + /// + /// The end of Data.define (ruby4.rb): stores the member list on the new class, with the names of the hidden + /// instance variables the members' values live in (DataNew and DataWith read them, so that nothing makes + /// the names anew on every call), and defines each member's reader - an attribute reader of that variable, + /// which a call site reads as it reads an attr_reader's, where a define_method block calling + /// __ir_hidden_ivar__ cost a block frame and a new name on every read. + /// + [RubyMethod("__ir_data_define__", RubyMethodAttributes.PrivateInstance)] + public static void DefineData(RubyContext/*!*/ context, [NotNull]RubyClass/*!*/ self, [NotNull]RubyArray/*!*/ names) { + var members = new RubySymbol[names.Count]; + var variables = new string[names.Count]; + for (int i = 0; i < variables.Length; i++) { + members[i] = (RubySymbol)names[i]; + variables[i] = RubyUtils.GetHiddenInstanceVariableName(members[i].ToString()); + } + context.SetInstanceVariable(self, RubyUtils.GetHiddenInstanceVariableName("data_members"), names); + context.SetInstanceVariable(self, DataLayoutName, new DataLayout(members, variables)); + for (int i = 0; i < variables.Length; i++) { + string methodName = members[i].ToString(); + self.AddMethod(context, methodName, new RubyAttributeReaderInfo( + (RubyMemberFlags)RubyUtils.GetSpecialMethodVisibility(RubyMethodVisibility.Public, methodName), self, variables[i])); + } + } + + // A Data class's members and the hidden variables their values are kept in (DefineData). + private sealed class DataLayout { + public readonly RubySymbol/*!*/[]/*!*/ Members; + public readonly string/*!*/[]/*!*/ Variables; + + public DataLayout(RubySymbol/*!*/[]/*!*/ members, string/*!*/[]/*!*/ variables) { + Members = members; + Variables = variables; + } + } + + // The layout Data.define stored on cls or a class above it, when cls's initialize is Data#initialize - the + // prelude's own, which MarkDataInitializer recorded: a program that reopens Data and defines initialize again + // gets its initialize called, through the prelude's Ruby path. + private static DataLayout GetDataLayout(RubyContext/*!*/ context, RubyClass/*!*/ cls, RubyClass/*!*/ dataClass) { + var initializer = cls.ResolveMethod(Symbols.Initialize, VisibilityContext.AllVisible).Info; + object builtIn; + if (initializer == null || initializer.DeclaringModule != dataClass + || !context.TryGetInstanceVariable(dataClass, DataInitializerName, out builtIn) || builtIn != (object)initializer) { + return null; + } + for (var c = cls; c != null && c != dataClass; c = c.SuperClass) { + object layout; + if (context.TryGetInstanceVariable(c, DataLayoutName, out layout)) { + return layout as DataLayout; + } + } + return null; + } + + private static readonly string DataLayoutName = RubyUtils.GetHiddenInstanceVariableName("data_layout"); + private static readonly string DataInitializerName = RubyUtils.GetHiddenInstanceVariableName("data_initializer"); + + /// + /// Records Data#initialize as the prelude defines it (ruby4.rb, right after the def), so that DataNew and + /// DataWith make an instance directly only while that is the initialize a Data class has. + /// + [RubyMethod("__ir_data_initializer__", RubyMethodAttributes.PrivateInstance)] + public static void MarkDataInitializer(RubyContext/*!*/ context, [NotNull]RubyClass/*!*/ self) { + context.SetInstanceVariable(self, DataInitializerName, self.ResolveMethod(Symbols.Initialize, VisibilityContext.AllVisible).Info); + } + + private static object NewData(RubyContext/*!*/ context, RubyClass/*!*/ cls, DataLayout/*!*/ layout, object[]/*!*/ values) { + object instance = cls.TryAllocatePlainInstance(); + if (instance == null) { + return null; + } + for (int i = 0; i < values.Length; i++) { + context.SetInstanceVariable(instance, layout.Variables[i], values[i]); + } + context.FreezeObject(instance); + return instance; + } + [RubyMethod("__ir_set_hidden_ivar__", RubyMethodAttributes.PrivateInstance)] public static object SetHiddenInstanceVariable(RubyContext/*!*/ context, object self, [NotNull]RubySymbol/*!*/ name, object value) { context.SetInstanceVariable(self, RubyUtils.GetHiddenInstanceVariableName(name.ToString()), value); diff --git a/Src/Libraries/Date/Date.cs b/Src/Libraries/Date/Date.cs index b724a9632..c1f76ff80 100644 --- a/Src/Libraries/Date/Date.cs +++ b/Src/Libraries/Date/Date.cs @@ -213,6 +213,13 @@ internal Frac DayFraction { return CreateCivil(self, year, month, day, ToStart(start)); } + // date/format.rb's _strptime for ASCII-only strings (DateStrptime.cs): a Hash, nil, or false + // when format.rb has to do it. + [RubyMethod("__strptime_ascii", RubyMethodAttributes.PrivateSingleton)] + public static object StrptimeAscii(RubyContext/*!*/ context, RubyClass/*!*/ self, [NotNull]MutableString/*!*/ str, [NotNull]MutableString/*!*/ fmt) { + return DateStrptime.Parse(context, str, fmt); + } + [RubyMethod("civil", RubyMethodAttributes.PublicSingleton)] public static RubyDate/*!*/ Civil(RubyClass/*!*/ self, [DefaultProtocol, DefaultParameterValue(-4712)]int year, diff --git a/Src/Libraries/Date/DateStrptime.cs b/Src/Libraries/Date/DateStrptime.cs new file mode 100644 index 000000000..6c59214bc --- /dev/null +++ b/Src/Libraries/Date/DateStrptime.cs @@ -0,0 +1,543 @@ +/* **************************************************************************** + * + * Date for IronRuby - Date._strptime over ASCII-only strings. + * + * date/format.rb's _strptime_i (a port of 1.9's) cut the subject with a regular expression per + * directive and kept the fields in a Bag; called from Time.strptime it was twenty times CRuby's + * date__strptime, and the gap was spread over every step (a String per token, a case over sixty + * String literals, a MatchData and $1 per field). This is the same walk over the format, the + * regular expressions written out by hand, for the case where the subject and the format are + * both ASCII-only Strings: there \d, \s, [[:alpha:]] and \b are the ASCII classes and a + * position is a byte. Anything else (another encoding, a number too long for a long) answers + * false and format.rb does the work as before. + * + * This source code is subject to terms and conditions of the Apache License, + * Version 2.0. A copy of the license can be found in the License.html file at + * the root of this distribution. + * + * ***************************************************************************/ + +using System; +using System.Collections.Generic; +using IronRuby.Builtins; +using IronRuby.Runtime; + +namespace IronRuby.StandardLibrary.Date { + + internal sealed class DateStrptime { + // The fields in the order format.rb's Bag first set them (its Hash keeps that order). + private readonly List _names = new List(); + private readonly List _values = new List(); + private readonly string _str; + private int _pos; + private bool _unsupported; + + private static readonly string[] Days = { "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" }; + private static readonly string[] Months = { "january", "february", "march", "april", "may", "june", "july", + "august", "september", "october", "november", "december" }; + + // (?:gmt|utc?)? in the order the alternation tries them + private static readonly string[] ZonePrefixes = { "gmt", "utc", "ut", "" }; + + private DateStrptime(string str) { + _str = str; + } + + /// + /// Date._strptime(str, fmt) for ASCII-only str and fmt: a Hash, null when str does not match, + /// or false when this cannot say and format.rb must. The Hash holds :sec_fraction and + /// :seconds of %L, %N and %Q as [numerator, denominator] Arrays, and :offset as true after + /// each :zone, for the Ruby side to make into a Rational and zone_to_diff's answer. + /// + internal static object Parse(RubyContext/*!*/ context, MutableString/*!*/ str, MutableString/*!*/ fmt) { + var p = new DateStrptime(str.ToString()); + if (!p.Run(fmt.ToString())) { + return p._unsupported ? (object)false : null; + } + if (p._unsupported) { + return false; + } + + object cent = p.Get("_cent"); + if (cent != null) { + long c = (long)cent; + if (!p.AddCent("cwyear", c) || !p.AddCent("year", c)) { + return false; + } + } + object merid = p.Get("_merid"); + if (merid != null) { + object hour = p.Get("hour"); + if (hour != null) { + p.Set("hour", (long)hour % 12 + (long)merid); + } + } + + var hash = new Hash(context); + for (int i = 0; i < p._names.Count; i++) { + string name = p._names[i]; + object value = p._values[i]; + if (name[0] == '_' || (value == null && name != "offset")) { + continue; + } + if (value is long l) { + value = Clr.ToRubyInteger(l); + } else if (value is long[] frac) { + value = new RubyArray { Clr.ToRubyInteger(frac[0]), Clr.ToRubyInteger(frac[1]) }; + } else if (value is string s) { + value = MutableString.Create(s, str.Encoding); + } + hash[context.CreateAsciiSymbol(name)] = value; + } + if (p._pos < p._str.Length) { + hash[context.CreateAsciiSymbol("leftover")] = MutableString.Create(p._str.Substring(p._pos), str.Encoding); + } + return hash; + } + + private bool AddCent(string name, long cent) { + object v = Get(name); + if (v != null) { + try { + Set(name, checked((long)v + cent * 100)); + } catch (OverflowException) { + return false; + } + } + return true; + } + + private object Get(string name) { + int i = _names.IndexOf(name); + return i >= 0 ? _values[i] : null; + } + + private void Set(string name, object value) { + int i = _names.IndexOf(name); + if (i >= 0) { + _values[i] = value; + } else { + _names.Add(name); + _values.Add(value); + } + } + + #region subject + + private static bool IsDigit(char c) => c >= '0' && c <= '9'; + private static bool IsAlpha(char c) => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); + // Onigmo's \s for ASCII: space, \t, \n, \v, \f, \r. + private static bool IsSpace(char c) => c == ' ' || (c >= '\t' && c <= '\r'); + private static bool IsWord(char c) => IsAlpha(c) || IsDigit(c) || c == '_'; + + private char At(int i) => i < _str.Length ? _str[i] : '\0'; + + // \b at i, where the character before i is a word character: the one at i is not. + private bool BoundaryAfterWord(int i) => i >= _str.Length || !IsWord(_str[i]); + + private bool StartsWithIgnoreCase(int i, string lower) { + if (i + lower.Length > _str.Length) { + return false; + } + for (int k = 0; k < lower.Length; k++) { + char c = _str[i + k]; + if (c >= 'A' && c <= 'Z') c = (char)(c + 32); + if (c != lower[k]) { + return false; + } + } + return true; + } + + // /\A([-+]?\d{1,max})/ (signed) or /\A(\d{1,max})/; max 0 for \d{1,}. The value and the + // match's length (the sign counted), or false when there is no match. A number too long for + // a long marks the parse unsupported. + private bool Number(bool signed, int max, out long value, out int length) { + value = 0; length = 0; + int i = _pos; + bool negative = false; + if (signed && i < _str.Length && (_str[i] == '+' || _str[i] == '-')) { + negative = _str[i] == '-'; + i++; + } + int start = i; + while (i < _str.Length && IsDigit(_str[i]) && (max == 0 || i - start < max)) { + i++; + } + if (i == start) { + return false; + } + if (i - _pos > 18) { + _unsupported = true; + return false; + } + long v = 0; + for (int k = start; k < i; k++) { + v = v * 10 + (_str[k] - '0'); + } + value = negative ? -v : v; + length = i - _pos; + _pos = i; + return true; + } + + // /\A( \d|\d{1,2})/ + private bool SpaceDigitOrTwo(out long value) { + if (At(_pos) == ' ' && IsDigit(At(_pos + 1))) { + value = _str[_pos + 1] - '0'; + _pos += 2; + return true; + } + return Number(false, 2, out value, out _); + } + + private bool Ranged(long value, long lo, long hi) => value >= lo && value <= hi; + + // /\A(name1|name2|...)/i over full names, then over their first three letters. + private bool Name(string[] names, out int index) { + for (int k = 0; k < names.Length; k++) { + if (StartsWithIgnoreCase(_pos, names[k])) { + _pos += names[k].Length; + index = k; + return true; + } + } + for (int k = 0; k < names.Length; k++) { + if (StartsWithIgnoreCase(_pos, names[k].Substring(0, 3))) { + _pos += 3; + index = k; + return true; + } + } + index = -1; + return false; + } + + // The zone of %Z and %z: + // /\A((?:gmt|utc?)?[-+]\d+(?:[,.:]\d+(?::\d+)?)? + // |[[:alpha:].\s]+(?:standard|daylight)\s+time\b + // |[[:alpha:]]+(?:\s+dst)?\b + // )/ix + private int ZoneEnd() { + int end; + foreach (string prefix in ZonePrefixes) { + if (StartsWithIgnoreCase(_pos, prefix) && (end = OffsetEnd(_pos + prefix.Length)) >= 0) { + return end; + } + } + + int run = _pos; + while (run < _str.Length && (IsAlpha(_str[run]) || _str[run] == '.' || IsSpace(_str[run]))) { + run++; + } + for (int i = run; i > _pos; i--) { + if (StartsWithIgnoreCase(i, "standard") || StartsWithIgnoreCase(i, "daylight")) { + int k = i + 8; + int spaces = k; + while (k < _str.Length && IsSpace(_str[k])) { + k++; + } + if (k > spaces && StartsWithIgnoreCase(k, "time") && BoundaryAfterWord(k + 4)) { + return k + 4; + } + } + } + + int letters = _pos; + while (letters < _str.Length && IsAlpha(_str[letters])) { + letters++; + } + if (letters > _pos) { + int k = letters; + while (k < _str.Length && IsSpace(_str[k])) { + k++; + } + if (k > letters && StartsWithIgnoreCase(k, "dst") && BoundaryAfterWord(k + 3)) { + return k + 3; + } + // a shorter run of letters ends between two letters, where there is no \b + if (BoundaryAfterWord(letters)) { + return letters; + } + } + return -1; + } + + // [-+]\d+(?:[,.:]\d+(?::\d+)?)? from i: where it ends, or -1. + private int OffsetEnd(int i) { + if (i >= _str.Length || (_str[i] != '+' && _str[i] != '-')) { + return -1; + } + int k = Digits(i + 1); + if (k < 0) { + return -1; + } + char c = At(k); + int j; + if ((c == ',' || c == '.' || c == ':') && (j = Digits(k + 1)) >= 0) { + k = j; + int m; + if (At(k) == ':' && (m = Digits(k + 1)) >= 0) { + k = m; + } + } + return k; + } + + private int Digits(int i) { + int k = i; + while (k < _str.Length && IsDigit(_str[k])) { + k++; + } + return k > i ? k : -1; + } + + #endregion + + // /\A%[EO]?[CDdeFGgHIjkLlMmNQRrSsTUuVvWwXxYy\d]/ =~ s || /\A\d/ =~ s + private static bool NumPattern(string fmt, int pos) { + if (pos >= fmt.Length) { + return false; + } + char c = fmt[pos]; + if (IsDigit(c)) { + return true; + } + if (c != '%' || pos + 1 >= fmt.Length) { + return false; + } + c = fmt[pos + 1]; + if ((c == 'E' || c == 'O') && pos + 2 < fmt.Length && IsNumDirective(fmt[pos + 2])) { + return true; + } + return IsNumDirective(c); + } + + private static bool IsNumDirective(char c) => + IsDigit(c) || "CDdeFGgHIjkLlMmNQRrSsTUuVvWwXxYy".IndexOf(c) >= 0; + + // the subject at the position starts with fmt[start, length]: a token matched as itself + private bool Literal(string fmt, int start, int length) { + if (_pos + length <= _str.Length && string.CompareOrdinal(_str, _pos, fmt, start, length) == 0) { + _pos += length; + return true; + } + return false; + } + + private bool Run(string fmt) { + int pos = 0; + int size = fmt.Length; + while (pos < size) { + string s = null; + int len; + char ch = fmt[pos]; + if (ch == '%' && pos + 1 < size) { + int k = pos + 1; + char prefix = fmt[k]; + if ((prefix == 'E' || prefix == 'O') && k + 1 < size) { + k++; + } + int m = k; + while (m < size && m - k < 3 && fmt[m] == ':') { + m++; + } + if (m > k && m < size && fmt[m] == 'z') { + k = m; + } + s = fmt.Substring(pos + 1, k - pos); + len = k + 1 - pos; + } else { + len = 1; + } + int start = pos; + pos += len; + + if (s == null) { + if (IsSpace(ch)) { + while (_pos < _str.Length && IsSpace(_str[_pos])) { + _pos++; + } + } else if (!Literal(fmt, start, len)) { + return false; + } + continue; + } + + long v; + int n; + switch (s) { + case "A": case "a": + if (!Name(Days, out n)) return false; + Set("wday", (long)n); + break; + case "B": case "b": case "h": + if (!Name(Months, out n)) return false; + Set("mon", (long)n + 1); + break; + case "C": case "EC": + if (!Number(true, NumPattern(fmt, pos) ? 2 : 0, out v, out _)) return false; + Set("_cent", v); + break; + case "c": case "Ec": + if (!Run("%a %b %e %H:%M:%S %Y")) return false; + break; + case "D": case "x": case "Ex": + if (!Run("%m/%d/%y")) return false; + break; + case "d": case "e": case "Od": case "Oe": + if (!SpaceDigitOrTwo(out v) || !Ranged(v, 1, 31)) return false; + Set("mday", v); + break; + case "F": + if (!Run("%Y-%m-%d")) return false; + break; + case "G": + if (!Number(true, NumPattern(fmt, pos) ? 4 : 0, out v, out _)) return false; + Set("cwyear", v); + break; + case "g": + if (!Number(false, 2, out v, out _) || !Ranged(v, 0, 99)) return false; + Set("cwyear", v); + if (Get("_cent") == null) Set("_cent", v >= 69 ? 19L : 20L); + break; + case "H": case "k": case "OH": + if (!SpaceDigitOrTwo(out v) || !Ranged(v, 0, 24)) return false; + Set("hour", v); + break; + case "I": case "l": case "OI": + if (!SpaceDigitOrTwo(out v) || !Ranged(v, 1, 12)) return false; + Set("hour", v); + break; + case "j": + if (!Number(false, 3, out v, out _) || !Ranged(v, 1, 366)) return false; + Set("yday", v); + break; + case "L": + case "N": + if (!Number(true, NumPattern(fmt, pos) ? (s == "L" ? 3 : 9) : 0, out v, out n)) return false; + // the denominator counts the digits, not the sign (date__strptime) + Set("sec_fraction", new long[] { v, Pow10(_str[_pos - n] == '+' || _str[_pos - n] == '-' ? n - 1 : n) }); + break; + case "M": case "OM": + if (!Number(false, 2, out v, out _) || !Ranged(v, 0, 59)) return false; + Set("min", v); + break; + case "m": case "Om": + if (!Number(false, 2, out v, out _) || !Ranged(v, 1, 12)) return false; + Set("mon", v); + break; + case "n": case "t": + if (!Run(" ")) return false; + break; + case "P": case "p": { + char c = At(_pos); + if (c != 'a' && c != 'A' && c != 'p' && c != 'P') return false; + // "pmx" is a pm and a leftover "x": date__strptime looks for no word boundary + if (At(_pos + 1) == 'm' || At(_pos + 1) == 'M') { + _pos += 2; + } else if (At(_pos + 1) == '.' && (At(_pos + 2) == 'm' || At(_pos + 2) == 'M') && At(_pos + 3) == '.') { + _pos += 4; + } else { + return false; + } + Set("_merid", c == 'a' || c == 'A' ? 0L : 12L); + break; + } + case "Q": + if (!NegativeNumber(out v)) return false; + Set("seconds", new long[] { v, 1000 }); + break; + case "R": + if (!Run("%H:%M")) return false; + break; + case "r": + if (!Run("%I:%M:%S %p")) return false; + break; + case "S": case "OS": + if (!Number(false, 2, out v, out _) || !Ranged(v, 0, 60)) return false; + Set("sec", v); + break; + case "s": + if (!NegativeNumber(out v)) return false; + Set("seconds", v); + break; + case "T": case "X": case "EX": + if (!Run("%H:%M:%S")) return false; + break; + case "U": case "W": case "OU": case "OW": + if (!Number(false, 2, out v, out _) || !Ranged(v, 0, 53)) return false; + Set(s[s.Length - 1] == 'U' ? "wnum0" : "wnum1", v); + break; + case "u": case "Ou": + if (!Number(false, 1, out v, out _) || !Ranged(v, 1, 7)) return false; + Set("cwday", v); + break; + case "V": case "OV": + if (!Number(false, 2, out v, out _) || !Ranged(v, 1, 53)) return false; + Set("cweek", v); + break; + case "v": + if (!Run("%e-%b-%Y")) return false; + break; + case "w": + if (!Number(false, 1, out v, out _) || !Ranged(v, 0, 6)) return false; + Set("wday", v); + break; + case "Y": case "EY": + if (!Number(true, NumPattern(fmt, pos) ? 4 : 0, out v, out _)) return false; + Set("year", v); + break; + case "y": case "Ey": case "Oy": + if (!Number(false, 2, out v, out _) || !Ranged(v, 0, 99)) return false; + Set("year", v); + if (Get("_cent") == null) Set("_cent", v >= 69 ? 19L : 20L); + break; + case "Z": case "z": case ":z": case "::z": case ":::z": { + int end = ZoneEnd(); + if (end < 0) return false; + Set("zone", _str.Substring(_pos, end - _pos)); + Set("offset", true); + _pos = end; + break; + } + case "%": + if (At(_pos) != '%') return false; + _pos++; + break; + case "+": + if (!Run("%a %b %e %H:%M:%S %Z %Y")) return false; + break; + default: + if (!Literal(fmt, start, len)) return false; + break; + } + if (_unsupported) { + return false; + } + } + return true; + } + + // /\A(-?\d{1,})/ + private bool NegativeNumber(out long value) { + if (At(_pos) == '-') { + int start = _pos; + _pos++; + if (!Number(false, 0, out value, out _)) { + _pos = start; + return false; + } + value = -value; + return true; + } + return Number(false, 0, out value, out _); + } + + private static long Pow10(int n) { + long r = 1; + while (n-- > 0) r *= 10; + return r; + } + } +} diff --git a/Src/Libraries/Erb/ErbEscape.cs b/Src/Libraries/Erb/ErbEscape.cs new file mode 100644 index 000000000..ca5651772 --- /dev/null +++ b/Src/Libraries/Erb/ErbEscape.cs @@ -0,0 +1,187 @@ +/* **************************************************************************** + * + * IronRuby's implementation of erb's C extension, erb/escape. + * + * The erb gem is pure Ruby apart from ERB::Escape.html_escape (ext/erb/escape/escape.c), + * which ERB::Util.html_escape and its alias h are. Without the extension erb/util.rb falls + * back to CGI.escapeHTML(s.to_s), a gsub with a Hash: a dozen times slower than the C + * function, and different from it in what it answers - the C function hands back the + * String it was given when nothing in it needs escaping, a subclass's instance included, + * and calls #to_s the way rb_convert_type does. Src/StdLib/ironruby/erb/escape.rb answers + * `require "erb/escape"` with this. + * + * This source code is subject to terms and conditions of the Apache License, + * Version 2.0. A copy of the license can be found in the License.html file at + * the root of this distribution. + * + * ***************************************************************************/ + +using System; +using System.Runtime.CompilerServices; +using IronRuby.Builtins; +using IronRuby.Runtime; +using IronRuby.Runtime.Calls; +using Microsoft.Scripting.Runtime; + +namespace IronRuby.StandardLibrary.Erb { + using AskStorage = CallSiteStorage>; + + + [RubyClass("ERB")] + public static class ErbOps { + + [RubyModule("Escape")] + public static class EscapeOps { + + /// + /// escape.c's erb_escape_html: a String in an ASCII-compatible encoding is escaped here + /// (optimized_escape_html), any other String goes to CGI.escapeHTML, and anything else is + /// converted with #to_s first (rb_convert_type). + /// + [RubyMethod("html_escape", RubyMethodAttributes.PrivateInstance)] + [RubyMethod("html_escape", RubyMethodAttributes.PublicSingleton)] + public static MutableString/*!*/ HtmlEscape(UnaryOpStorage/*!*/ storage, BinaryOpStorage/*!*/ cgiStorage, + BinaryOpStorage/*!*/ respondTo1Storage, AskStorage/*!*/ respondTo2Storage, AskStorage/*!*/ respondToMissingStorage, + object self, object value) { + MutableString str = value as MutableString ?? + ConvertToS(storage, respondTo1Storage, respondTo2Storage, respondToMissingStorage, value); + if (!str.Encoding.IsAsciiIdentity) { + return EscapeWithCgi(cgiStorage, str); + } + return Escape(str); + } + + /// + /// optimized_escape_html: the bytes & < > " ' become entities. None of them can be a + /// byte of a multibyte character in an ASCII-compatible encoding, so the bytes are scanned as + /// they are. The String itself is the answer when it has none of them; otherwise a new String in + /// its encoding. + /// + private static MutableString/*!*/ Escape(MutableString/*!*/ str) { + byte[] bytes = str.ToByteArray(); + int first = 0; + while (first < bytes.Length && EntityOf(bytes[first]) == null) { + first++; + } + if (first == bytes.Length) { + return str; + } + + var result = MutableString.CreateMutable(bytes.Length + 16, str.Encoding); + result.Append(bytes, 0, first); + int start = first; + for (int i = first; i < bytes.Length; i++) { + string entity = EntityOf(bytes[i]); + if (entity != null) { + result.Append(bytes, start, i - start); + result.Append(entity); + start = i + 1; + } + } + result.Append(bytes, start, bytes.Length - start); + return result; + } + + private static string EntityOf(byte b) { + switch (b) { + case (byte)'\'': return "'"; + case (byte)'&': return "&"; + case (byte)'"': return """; + case (byte)'<': return "<"; + case (byte)'>': return ">"; + default: return null; + } + } + + private static MutableString/*!*/ EscapeWithCgi(BinaryOpStorage/*!*/ storage, MutableString/*!*/ str) { + var context = storage.Context; + object cgi; + if (!context.ObjectClass.TryGetConstant(null, "CGI", out cgi)) { + throw RubyExceptions.CreateNameError("uninitialized constant CGI"); + } + var site = storage.GetCallSite("escapeHTML", 1); + return (MutableString)site.Target(site, cgi, str); + } + + /// + /// rb_convert_type(value, T_STRING, "String", "to_s"): a value without #to_s is a TypeError, + /// and so is a #to_s that answers anything but a String. Whether there is a #to_s is + /// rb_check_funcall's question (vm_eval.c), asked as it asks it: + /// - a respond_to? of the object's own is asked first (check_funcall_respond_to), with + /// include_private true unless it takes one argument, and a false is the TypeError; + /// - a #to_s of any visibility is called; + /// - otherwise (check_funcall_missing) a respond_to_missing? of the object's own is asked + /// (:to_s, true) and a false is the TypeError; then a method_missing of its own is called - + /// BasicObject's is the TypeError - and a NoMethodError out of it is the TypeError too, + /// unless respond_to? or respond_to_missing? had said yes (check_funcall_failed). + /// + private static MutableString/*!*/ ConvertToS(UnaryOpStorage/*!*/ storage, BinaryOpStorage/*!*/ respondTo1Storage, + AskStorage/*!*/ respondTo2Storage, AskStorage/*!*/ respondToMissingStorage, object value) { + var context = storage.Context; + RubyClass cls = context.GetImmediateClassOf(value); + RubySymbol name = context.CreateAsciiSymbol("to_s"); + + bool saidYes = false; + var respondTo = cls.ResolveMethod("respond_to?", VisibilityContext.AllVisible); + if (respondTo.Found && !(respondTo.Info.DeclaringModule == context.KernelModule && respondTo.Info is RubyLibraryMethodInfo)) { + object answer; + if (respondTo.Info.GetArity() == 1) { + var site = respondTo1Storage.GetCallSite("respond_to?", new RubyCallSignature(1, RubyCallFlags.HasImplicitSelf)); + answer = site.Target(site, value, name); + } else { + var site = respondTo2Storage.GetCallSite("respond_to?", new RubyCallSignature(2, RubyCallFlags.HasImplicitSelf)); + answer = site.Target(site, value, name, ScriptingRuntimeHelpers.True); + } + if (!RubyOps.IsTrue(answer)) { + throw CannotConvert(context, value); + } + saidYes = true; + // the respond_to? may have defined a singleton #to_s, which made the object a singleton class + // of its own: CRuby looks the method up on the object again after the probe + cls = context.GetImmediateClassOf(value); + } + + if (!cls.ResolveMethod("to_s", VisibilityContext.AllVisible).Found) { + var respondToMissing = cls.ResolveMethod("respond_to_missing?", VisibilityContext.AllVisible); + if (respondToMissing.Found && !(respondToMissing.Info.DeclaringModule == context.KernelModule && respondToMissing.Info is RubyLibraryMethodInfo)) { + var site = respondToMissingStorage.GetCallSite("respond_to_missing?", new RubyCallSignature(2, RubyCallFlags.HasImplicitSelf)); + if (!RubyOps.IsTrue(site.Target(site, value, name, ScriptingRuntimeHelpers.True))) { + throw CannotConvert(context, value); + } + saidYes = true; + } + var methodMissing = cls.ResolveMethod("method_missing", VisibilityContext.AllVisible); + if (!methodMissing.Found || + methodMissing.Info.DeclaringModule == context.BasicObjectClass && methodMissing.Info is RubyLibraryMethodInfo) { + throw CannotConvert(context, value); + } + try { + return CheckResult(context, value, CallToS(storage, value)); + } catch (MissingMethodException) when (!saidYes) { + throw CannotConvert(context, value); + } + } + return CheckResult(context, value, CallToS(storage, value)); + } + + private static object CallToS(UnaryOpStorage/*!*/ storage, object value) { + var site = storage.GetCallSite("to_s", new RubyCallSignature(0, RubyCallFlags.HasImplicitSelf)); + return site.Target(site, value); + } + + private static MutableString/*!*/ CheckResult(RubyContext/*!*/ context, object value, object result) { + if (result is MutableString str) { + return str; + } + string className = RubyExceptions.MessageTypeName(context.GetClassName(value)); + throw RubyExceptions.CreateTypeError("can't convert {0} to String ({0}#to_s gives {1})", + className, RubyExceptions.MessageTypeName(context.GetClassName(result))); + } + + private static Exception/*!*/ CannotConvert(RubyContext/*!*/ context, object value) { + return RubyExceptions.CreateTypeError("can't convert {0} into String", + RubyExceptions.MessageTypeName(context.GetClassName(value))); + } + } + } +} diff --git a/Src/Prism/PrismAstBridge.cs b/Src/Prism/PrismAstBridge.cs index 12644c563..1d532a08d 100644 --- a/Src/Prism/PrismAstBridge.cs +++ b/Src/Prism/PrismAstBridge.cs @@ -104,9 +104,26 @@ public static SourceUnitTree Parse(SourceUnit/*!*/ sourceUnit, RubyCompilerOptio if (mainScript && (commandLine & 0x20) == 0 && RubyUtils.ShebangNamesIronRuby(code)) { mainScript = false; } - return ParseText(code, sourceUnit.Path, options.LocalNames, sourceUnit, errorSink, - options.InitialLocation.Line, options.IsEval && options.TopLevelMethodName == null, options.IsEval, - options.EvalSourceEncoding, commandLine, mainScript, options.IsolatedLocalNames); + bool evalOutsideMethod = options.IsEval && options.TopLevelMethodName == null; + string key = null; + EvalAstCache cache = null; + if (options.IsEval && options.IsolatedLocalNames == null && commandLine == 0 && !mainScript && + code.Length <= EvalAstCache.MaxCodeLength && sourceUnit.LanguageContext is RubyContext evalContext) { + cache = evalContext.EvalAstCache ??= new EvalAstCache(); + key = EvalAstCache.MakeKey(code, sourceUnit.Path, options.InitialLocation.Line, evalOutsideMethod, + options.EvalSourceEncoding, options.LocalNames); + SourceUnitTree cached = cache.Get(key); + if (cached != null) { + return cached; + } + } + SourceUnitTree tree = ParseText(code, sourceUnit.Path, options.LocalNames, sourceUnit, errorSink, + options.InitialLocation.Line, evalOutsideMethod, options.IsEval, + options.EvalSourceEncoding, commandLine, mainScript, options.IsolatedLocalNames, out bool reported); + if (cache != null && tree != null && !reported) { + cache.Add(key, tree); + } + return tree; } finally { PhaseTimer.Exit(timed); } @@ -143,6 +160,17 @@ public static SourceUnitTree ParseText(string/*!*/ code, string path, List isolatedLocalNames = null) { + return ParseText(code, path, outerLocalNames, sourceUnit, errorSink, startLine, evalOutsideMethod, isEval, + evalSourceEncoding, commandLine, mainScript, isolatedLocalNames, out _); + } + + // reported: whether the parse told the error sink anything (a warning, which depends on + // $VERBOSE and must come again at the next parse), which keeps its tree out of EvalAstCache. + private static SourceUnitTree ParseText(string/*!*/ code, string path, List outerLocalNames, + SourceUnit sourceUnit, ErrorSink errorSink, int startLine, bool evalOutsideMethod, bool isEval, + RubyEncoding evalSourceEncoding, byte commandLine, bool mainScript, + ICollection isolatedLocalNames, out bool reported) { + reported = false; // --enable/--disable=frozen-string-literal only sets the default; the magic comment // in a file still wins, and prism applies that rule itself. @@ -218,6 +246,7 @@ public static SourceUnitTree ParseText(string/*!*/ code, string path, List 0) { + reported = true; if (errorSink != null && sourceUnit != null) { // A SyntaxError's message is MRI's: "syntax errors found" and prism's picture of where, // at the line of the first error prism found (not the first in the source). Any other @@ -237,6 +266,7 @@ public static SourceUnitTree ParseText(string/*!*/ code, string path, List 0; if (errorSink != null && sourceUnit != null) { foreach (var warning in result.Warnings) { // prism levels: 0 = always, 1 = only when $VERBOSE is true @@ -245,7 +275,17 @@ public static SourceUnitTree ParseText(string/*!*/ code, string path, List @@ -587,7 +627,7 @@ private int StatementLine(Pm.PmNode/*!*/ node) { // still map the operand: it may introduce locals the rest of the scope refers to Expr(defined.Value); if (_errorSink != null && _sourceUnit != null) { - _errorSink.Add(_sourceUnit, "possibly useless use of defined? in void context", span, + Report("possibly useless use of defined? in void context", span, Errors.RuntimeVerboseWarning, Severity.Warning); } return Literal.Nil(span); @@ -1007,7 +1047,7 @@ private int StatementLine(Pm.PmNode/*!*/ node) { case Pm.ReturnNode ret: if (ret.Arguments != null && !_isEval && CurrentScope is TopStaticLexicalScope && _errorSink != null && _sourceUnit != null) { - _errorSink.Add(_sourceUnit, "argument of top-level return is ignored", span, + Report("argument of top-level return is ignored", span, Errors.RuntimeWarning, Severity.Warning); } return new ReturnStatement(OptionalArguments(ret.Arguments), span); @@ -1020,7 +1060,7 @@ private int StatementLine(Pm.PmNode/*!*/ node) { case Pm.YieldNode yield: _usesBlock = true; if (!IsYieldAllowed() && _errorSink != null) { - _errorSink.Add(_sourceUnit, "Invalid yield", span, 0, Severity.FatalError); + Report("Invalid yield", span, 0, Severity.FatalError); } return new YieldCall(yield.Arguments != null ? BuildArguments(yield.Arguments) : null, span); @@ -1199,7 +1239,7 @@ private void WarnRegexp(byte[]/*!*/ pattern, SourceSpan span) { var warnings = RegexpTransformer.GetWarnings(text); if (warnings != null) { foreach (var warning in warnings) { - _errorSink.Add(_sourceUnit, warning + ": /" + text + "/", span, Errors.RuntimeWarning, Severity.Warning); + Report(warning + ": /" + text + "/", span, Errors.RuntimeWarning, Severity.Warning); } } } diff --git a/Src/Ruby/Builtins/RubyClass.cs b/Src/Ruby/Builtins/RubyClass.cs index 30e612a75..62e184923 100644 --- a/Src/Ruby/Builtins/RubyClass.cs +++ b/Src/Ruby/Builtins/RubyClass.cs @@ -1734,6 +1734,20 @@ internal bool TryGetPlainAllocation(out Func allocator) { return type == typeof(object) || type == typeof(RubyObject) || (allocator = RubyTypeDispenser.TryGetObjectAllocator(type)) != null; } + /// + /// A new, uninitialized instance of this class, made the way Class#new makes one of a plain Ruby class + /// (), without calling anything; null for a class whose instances are + /// made some other way. For core classes written in Ruby that construct their instances themselves, as + /// MRI's C does with rb_obj_alloc (Data.new and Data#with in ruby4.rb). + /// + public object TryAllocatePlainInstance() { + Func allocator; + if (!TryGetPlainAllocation(out allocator)) { + return null; + } + return allocator != null ? allocator(this) : new RubyObject(this); + } + /// /// The construction BuildObjectConstructionNoFlow builds for a call of Class#new with arguments and /// no block, in the cases it is the allocation of a RubyObject and maybe a call of a Ruby initializer of that arity and diff --git a/Src/Ruby/Runtime/Calls/DispatchIntrinsics.cs b/Src/Ruby/Runtime/Calls/DispatchIntrinsics.cs index 7ccdfe8de..696d55507 100644 --- a/Src/Ruby/Runtime/Calls/DispatchIntrinsics.cs +++ b/Src/Ruby/Runtime/Calls/DispatchIntrinsics.cs @@ -83,7 +83,7 @@ internal static bool TryBuildRespondTo(MetaObjectBuilder/*!*/ metaBuilder, CallA // Only a Ruby object's rule tests its exact class; a CLR object's may cover an instance with singleton methods. var symbol = args.GetSimpleArgument(0) as RubySymbol; var targetClass = args.TargetClass; - if (symbol == null || !(args.Target is IRubyObject)) { + if (symbol == null || !(args.Target is IRubyObject) || IsObjectSingleton(targetClass)) { return false; } @@ -319,14 +319,24 @@ internal static bool IsLightBlockGivenSite(string/*!*/ methodName, RubyCallSigna /// that for every call of the site, so any other respond_to? site gets the ordinary call and can share it. That is the /// site of `respond_to?(name, true)' in OpenStruct#is_method_protected!, which sees a new singleton class with each /// OpenStruct: it built and compiled a rule for every one of them (~0.1-0.2 ms each, most of OpenStruct.new). + /// + /// Nor is `respond_to?(:name)' folded for a receiver whose class is the singleton class of an object (not of a module): that + /// class has one instance, so its folded rule would serve one object - OpenStruct's `respond_to?(:total)' met a new one with + /// every OpenStruct, and built and compiled a rule for each. The ordinary call is shared between such classes instead. /// - internal static bool MaySpecialize(RubyMemberInfo/*!*/ method, RubyCallSignature signature) { + internal static bool MaySpecialize(RubyMemberInfo/*!*/ method, RubyCallSignature signature, RubyClass/*!*/ targetClass) { if (IsKernelMethod(method, ref _respondTo, "RespondTo")) { - return signature.ArgumentCount == 1 && !signature.HasBlock && !signature.HasSplattedArgument && !signature.HasRhsArgument; + return signature.ArgumentCount == 1 && !signature.HasBlock && !signature.HasSplattedArgument && !signature.HasRhsArgument && + !IsObjectSingleton(targetClass); } return IsSendMethod(method) || IsNotEqualsMethod(method); } + // the singleton class of an object that is not a module: its only instance is that object + private static bool IsObjectSingleton(RubyClass/*!*/ targetClass) { + return targetClass.IsSingletonClass && !(targetClass.SingletonClassOf is RubyModule); + } + /// /// Kernel#send and BasicObject#__send__: the call they make is bound in their place (TryBuildSend), and has no frame of its own. /// diff --git a/Src/Ruby/Runtime/Calls/MetaObjectBuilder.cs b/Src/Ruby/Runtime/Calls/MetaObjectBuilder.cs index c6f2d4705..90d232fd1 100644 --- a/Src/Ruby/Runtime/Calls/MetaObjectBuilder.cs +++ b/Src/Ruby/Runtime/Calls/MetaObjectBuilder.cs @@ -340,7 +340,7 @@ internal void AddTargetTypeTest(object target, RubyClass/*!*/ targetClass, Expre // (#{type})target.ImmediateClass.Version.Method in #{versionSet} AddCondition(versionSet.MakeTest( Ast.Field(Ast.Field(Ast.Call(Ast.Convert(targetParameter, type), classGetter), Fields.RubyModule_Version), Fields.VersionHandle_Method), - targetClass.Version.Method + targetClass.Version.Method, targetParameter )); return; } diff --git a/Src/Ruby/Runtime/Calls/MethodDispatcher.cs b/Src/Ruby/Runtime/Calls/MethodDispatcher.cs index 50adac35a..69df6209f 100644 --- a/Src/Ruby/Runtime/Calls/MethodDispatcher.cs +++ b/Src/Ruby/Runtime/Calls/MethodDispatcher.cs @@ -392,16 +392,23 @@ internal override void Initialize(string/*!*/ name, int version) { public object Invoke(CallSite/*!*/ callSite, TScope/*!*/ scope, object self, T0 arg0) { RubyClass cls; + // A site the method JIT typed passes `t.held = false' as a Boolean: one of the two shared boxes (Box), not a new + // object per store, sixteen megabytes per iteration of Richards once light sites had this dispatcher. Boxed only + // once the receiver is this dispatcher's: a miss hands the typed argument on to the next one in the chain. // an exact RubyObject that has the variable at the slot the site has seen: the cached store, inline if (self != null && self.GetType() == typeof(RubyObject)) { var robj = Unsafe.As(self); - if (robj.ImmediateClass.Version.Method == Version && RubyOps.TryWriteCached(robj._instanceData, (object)arg0, Site)) { - return (object)arg0; + if (robj.ImmediateClass.Version.Method == Version) { + object value = Box(arg0); + if (RubyOps.TryWriteCached(robj._instanceData, value, Site)) { + return value; + } + return RubyOps.WriteInstanceVariable(robj.ImmediateClass.Context, robj, value, Site); } } IRubyObject obj = GetRubyObject(self, out cls); if (obj != null && cls.Version.Method == Version) { - return RubyOps.WriteInstanceVariable(cls.Context, obj, (object)arg0, Site); + return RubyOps.WriteInstanceVariable(cls.Context, obj, Box(arg0), Site); } else { return Miss>(callSite)(callSite, scope, self, arg0); } diff --git a/Src/Ruby/Runtime/Calls/RubyAccessorInfo.cs b/Src/Ruby/Runtime/Calls/RubyAccessorInfo.cs index 1b0ed9f39..ff7be0ccc 100644 --- a/Src/Ruby/Runtime/Calls/RubyAccessorInfo.cs +++ b/Src/Ruby/Runtime/Calls/RubyAccessorInfo.cs @@ -32,7 +32,8 @@ public abstract class RubyAttributeAccessorInfo : RubyMemberInfo { protected RubyAttributeAccessorInfo(RubyMemberFlags flags, RubyModule/*!*/ declaringModule, string/*!*/ variableName) : base(flags, declaringModule) { Assert.NotEmpty(variableName); - Debug.Assert(variableName.StartsWith("@")); + // an attr_accessor's @name, or the hidden variable a Data member's reader reads (KernelOps.DefineData) + Debug.Assert(variableName.StartsWith("@") || variableName.StartsWith(RubyUtils.GetHiddenInstanceVariableName(""))); _instanceVariableName = variableName; } diff --git a/Src/Ruby/Runtime/Calls/RubyCallAction.cs b/Src/Ruby/Runtime/Calls/RubyCallAction.cs index 286a80d04..9702dd354 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallAction.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallAction.cs @@ -119,11 +119,24 @@ protected override object BindPrecompiled(Type/*!*/ delegateType, object[]/*!*/ // binder. Leaving it out of the mask sent every bare `foo` to a rule of its own. if (Context == null || Signature.ResolveOnly || - (Signature.Flags & ~(RubyCallFlags.HasImplicitSelf | RubyCallFlags.HasScope | RubyCallFlags.HasBlock | RubyCallFlags.HasRhsArgument | RubyCallFlags.HasSourceBlock | RubyCallFlags.IsVariableCall | RubyCallFlags.HasSplattedArgument)) != 0 || + (Signature.Flags & ~(RubyCallFlags.HasImplicitSelf | RubyCallFlags.HasScope | RubyCallFlags.HasBlock | RubyCallFlags.HasRhsArgument | RubyCallFlags.HasSourceBlock | RubyCallFlags.IsVariableCall | RubyCallFlags.HasSplattedArgument | RubyCallFlags.HasLightScope)) != 0 || Signature.HasSplattedArgument && Signature.HasRhsArgument) { return null; } + // A site with a light scope (a call in a method that runs without its scope, see MethodDefinition.LightScopeCall) is + // handed the declaring scope, not the caller's. The dispatcher of a Ruby method or an attribute accessor reads no scope: + // it calls the method with the receiver, the block and the arguments, which is all the rule does once the method is + // resolved as the rule resolves it - an explicit receiver's public method, which every caller sees, and no refinement. + // Everything else (library methods, which may take the scope, a splat, a refined name) is left to the rule, which + // answers RubyOps.LightScopeRequired where it would read the scope. Without this a light site whose receivers are of + // many classes - a visitor's `node.accept(self)' - built and compiled a rule for every class, and once there were more + // than the DLR's rule caches hold, kept building them again. + bool light = Signature.HasLightScope; + if (light && Signature.HasSplattedArgument) { + return null; + } + // Nor can it hold RubyMethodInfo.BuildCallNoFlow's unmarking of a keyword-arguments // hash handed to a method that declares no keywords. A call site's syntax decides // whether it passes keywords, so seeing one here means every call at this site @@ -161,6 +174,9 @@ protected override object BindPrecompiled(Type/*!*/ delegateType, object[]/*!*/ // MakeRefinementGuard); any other call of the kind is left to rule building. Refining the name // later re-versions the class, which retires a dispatcher made without the test. if (Signature.HasScope && targetClass.Context.IsRefinementSensitive(targetClass, _methodName)) { + if (light) { + return null; + } refinements = scope.GetActiveRefinements(); recordScope = GetRecordScope(scope, refinements); if (recordScope == RecordScope.None) { @@ -171,7 +187,8 @@ protected override object BindPrecompiled(Type/*!*/ delegateType, object[]/*!*/ refinements).InvalidateSitesOnOverride(); } else { version = targetClass.Version.Method; - method = targetClass.ResolveMethodForSiteNoLock(_methodName, GetVisibilityContext(Signature, scope)); + method = targetClass.ResolveMethodForSiteNoLock(_methodName, (light && !Signature.HasImplicitSelf) ? + new VisibilityContext(RubyMethodAttributes.Public) : GetVisibilityContext(Signature, scope)); } clrTest = (target != null && !(target is IRubyObject)) ? GetClrReceiverTest(targetClass, _methodName) : ClrReceiverTest.None; } @@ -180,6 +197,14 @@ protected override object BindPrecompiled(Type/*!*/ delegateType, object[]/*!*/ return null; } + // A singleton class is one object's: a dispatcher made for it serves that object only, and a light site that sees a new + // one every few calls is better off with the shared rule (RubyMetaBinder tries it first). Not so a method define_method + // made of a block (LambdaMethodCall, which reads no scope), the kind OpenStruct defines on each object's singleton class: + // no rule is shared for it, so the first calls of each go through a LibraryDispatcher (below) rather than a rule each. + if (light && targetClass.IsSingletonClass && method.Info.GetType() != typeof(RubyLambdaMethodInfo)) { + return null; + } + // The first calls go through a LibraryDispatcher, rather than a rule, until the call is hot: bool mayDispatch = LibraryDispatcher.MayDispatch(this, target); @@ -192,7 +217,7 @@ protected override object BindPrecompiled(Type/*!*/ delegateType, object[]/*!*/ // of Ruby methods don't, a RubyMethodCallPlan does var rubyMethod = method.Info as RubyMethodInfo; if (rubyMethod != null && rubyMethod.DefinitionName != _methodName) { - if (!mayDispatch || refinements != null || passesKeywords && !rubyMethod.TakesOrRefusesKeywords) { + if (light || !mayDispatch || refinements != null || passesKeywords && !rubyMethod.TakesOrRefusesKeywords) { return null; } return LibraryDispatcher.TryCreateRubyCall(this, delegateType, Signature, rubyMethod, targetClass, target, clrTest, version, args, null, _methodName); @@ -233,7 +258,8 @@ protected override object BindPrecompiled(Type/*!*/ delegateType, object[]/*!*/ null; } - dispatcher = method.Info.GetDispatcher(delegateType, Signature, target, version); + dispatcher = (!light || rubyMethod != null || method.Info is RubyAttributeAccessorInfo) ? + method.Info.GetDispatcher(delegateType, Signature, target, version) : null; // a Ruby method of a builtin class (much of the core library is written in Ruby), called on nil, true, false or a CLR object: if (dispatcher == null && rubyMethod != null && !(target is IRubyObject) && @@ -252,6 +278,14 @@ protected override object BindPrecompiled(Type/*!*/ delegateType, object[]/*!*/ return null; } + // At a light site only the first calls of a method define_method made of a block go on (see above); every other method + // the dispatchers above do not call is left to the rule. + if (light) { + return (method.Info is RubyLambdaMethodInfo) ? + LibraryDispatcher.TryCreateRubyCall(this, delegateType, Signature, method.Info, targetClass, target, clrTest, version, args) : + null; + } + // The first calls of a Ruby method that those dispatchers do not call (one with optional parameters or a rest parameter, // say) go without a rule too, as library methods' do (below). if (rubyMethod != null) { @@ -299,6 +333,8 @@ protected override object BindPrecompiled(Type/*!*/ delegateType, object[]/*!*/ // the set once the call has been resolved for it again - with no rule built or compiled. private sealed class SharedRule { internal readonly RubyMemberInfo/*!*/ Member; + // the call finds no method of its name, and Member is the method_missing it calls + internal readonly bool IsMissing; internal readonly Type/*!*/ TargetType; internal readonly Type/*!*/ DelegateType; internal readonly int FirstVersion; @@ -307,8 +343,9 @@ private sealed class SharedRule { internal RuleVersionSet Versions; internal volatile object Rule; - internal SharedRule(RubyMemberInfo/*!*/ member, Type/*!*/ targetType, Type/*!*/ delegateType, int firstVersion) { + internal SharedRule(RubyMemberInfo/*!*/ member, bool isMissing, Type/*!*/ targetType, Type/*!*/ delegateType, int firstVersion) { Member = member; + IsMissing = isMissing; TargetType = targetType; DelegateType = delegateType; FirstVersion = firstVersion; @@ -330,69 +367,138 @@ internal SharedRule(RubyMemberInfo/*!*/ member, Type/*!*/ targetType, Type/*!*/ [ThreadStatic] private static RubyCallAction _PendingVersionSetOwner; - internal override T BindShared(object[]/*!*/ args) { - RubyContext context = Context; - if (context == null || Signature.ResolveOnly || (Signature.Flags & ~SharableCallFlags) != 0 || - TracePoint.CCallTracing) { - return null; - } - - RubyScope scope; - object target; - if (Signature.HasScope) { - scope = (RubyScope)args[0]; - target = args[1]; - } else { - scope = context.EmptyScope; - target = args[0]; + private bool IsSharable { + get { + return !Signature.ResolveOnly && (Signature.Flags & ~SharableCallFlags) == 0 && !TracePoint.CCallTracing; } + } - // The type test of a Ruby object is only a version check (see MetaObjectBuilder.AddTargetTypeTest), and so is that of nil - // and of a CLR object whose class has neither singletons nor instances of a Ruby subclass. Not true/false: they are - // told apart by value. - Type targetType; - if (target == null) { - targetType = typeof(DynamicNull); - } else if (target is bool) { - return null; - } else { - targetType = target.GetType(); - } + // Resolves the call for the target as BindShared does: the method a rule shared with receivers of other classes would call + // (or the method_missing a call of an undefined name makes), and the version of the target's class it is resolved for. + // publicOnly: resolve for a caller that sees public methods only (see TryShareVersion). + private bool ResolveShared(RubyContext/*!*/ context, RubyScope/*!*/ scope, object target, bool publicOnly, out int version, + out RubyMemberInfo member, out bool isMissing) { + version = 0; + member = null; + isMissing = false; // an object of another runtime: RubyClass targetClass = context.GetImmediateClassOf(target); if (targetClass.Context != context) { - return null; + return false; } - int version; MethodResolutionResult method; + RubyMemberInfo methodMissing = null; using (context.ClassHierarchyLocker()) { targetClass.InitializeMethodsNoLock(); if (target != null && !(target is IRubyObject) && !HasPlainClrTypeTest(targetClass, _methodName)) { - return null; + return false; } // a rule shared by receivers of several classes cannot hold the lexical refinement guard either if (Signature.HasScope && context.IsRefinementSensitive(targetClass, _methodName)) { - return null; + return false; } version = targetClass.Version.Method; // As Resolve does: a site with a light scope has not got the caller's scope, so an explicit-receiver call there // looks for a public method; when there is none, nothing is shared and the ordinary bind reads the scope. - var visibility = (Signature.HasLightScope && !Signature.HasImplicitSelf) ? + var visibility = (publicOnly || Signature.HasLightScope && !Signature.HasImplicitSelf) ? new VisibilityContext(RubyMethodAttributes.Public) : GetVisibilityContext(Signature, scope); method = targetClass.ResolveMethodForSiteNoLock(_methodName, visibility, MethodLookup.Default); + + // A call of a name a Ruby object's class has no method of, at any visibility, is a call of the method_missing it + // resolves: OpenStruct's first `o.total = x' is, on a new singleton class each time. Resolve registers the lookup + // of the missing name the same way, so that defining it re-versions the class. + if (!method.Found && method.Info == null && method.IncompatibleVisibility == RubyMethodVisibility.None && + target is IRubyObject && _methodName != Symbols.MethodMissing) { + methodMissing = targetClass.ResolveMethodMissingForSite(_methodName, RubyMethodVisibility.None); + } } // Rules calling these methods depend on nothing but the method, the call signature and the arguments. // A protected method's rule also tests the caller's class. - if (!method.Found || method.Info.IsProtected || - method.Info.GetType() != typeof(RubyLibraryMethodInfo) && method.Info.GetType() != typeof(RubyMethodInfo)) { - return null; + if (method.Found) { + member = method.Info; + isMissing = false; + } else if (methodMissing != null && methodMissing.GetType() == typeof(RubyMethodInfo)) { + member = methodMissing; + isMissing = true; + } else { + return false; + } + if (member.IsProtected || member.GetType() != typeof(RubyLibraryMethodInfo) && member.GetType() != typeof(RubyMethodInfo)) { + return false; } // respond_to?(:sym) and send(:sym) rules are specialized on the receiver's class (DispatchIntrinsics): - if (DispatchIntrinsics.MaySpecialize(method.Info, Signature)) { + if (!isMissing && DispatchIntrinsics.MaySpecialize(member, Signature, targetClass)) { + return false; + } + + return true; + } + + /// + /// Called by the test of a shared rule (see RuleVersionSet.IsValid) for a Ruby object whose class version the rule does not + /// hold yet: if the call resolves to the rule's method for the object's class, adds the version and returns true. This is + /// what BindShared would do, but without going through the call site's update and the binder: a call in a method that + /// runs for objects that each get a singleton class of their own (OpenStruct's update_to_values!, new_ostruct_member!...) + /// sees a new class version on every call, and bound each of them (~2-10 us apiece, twice once the rule was compiled). + /// The caller's scope is not at hand: a call with an explicit receiver whose visibility the bind reads from the scope is + /// resolved for public methods, which every caller sees, so it takes in the version only if the rule's method is public there. + /// + internal bool TryShareVersion(object/*!*/ target, RuleVersionSet/*!*/ versionSet) { + RubyContext context = Context; + if (context == null || !IsSharable || versionSet.Member == null) { + return false; + } + bool publicOnly = Signature.HasScope && !Signature.HasImplicitSelf && !Signature.HasLightScope && !Signature.IsInteropCall; + + int version; + RubyMemberInfo member; + bool isMissing; + if (!ResolveShared(context, context.EmptyScope, target, publicOnly, out version, out member, out isMissing) || + member != versionSet.Member || isMissing != versionSet.IsMissing) { + return false; + } + + versionSet.TryAdd(version); + return true; + } + + internal override T BindShared(object[]/*!*/ args, bool beforeDispatcher, out bool deferred) { + deferred = false; + RubyContext context = Context; + if (context == null || !IsSharable) { + return null; + } + + RubyScope scope; + object target; + if (Signature.HasScope) { + scope = (RubyScope)args[0]; + target = args[1]; + } else { + scope = context.EmptyScope; + target = args[0]; + } + + // The type test of a Ruby object is only a version check (see MetaObjectBuilder.AddTargetTypeTest), and so is that of nil + // and of a CLR object whose class has neither singletons nor instances of a Ruby subclass. Not true/false: they are + // told apart by value. + Type targetType; + if (target == null) { + targetType = typeof(DynamicNull); + } else if (target is bool) { + return null; + } else { + targetType = target.GetType(); + } + + int version; + RubyMemberInfo member; + bool isMissing; + if (!ResolveShared(context, scope, target, false, out version, out member, out isMissing)) { return null; } @@ -400,7 +506,7 @@ internal override T BindShared(object[]/*!*/ args) { var sharedRules = _sharedRules; if (sharedRules != null) { foreach (var rule in sharedRules) { - if (rule.Member == method.Info && rule.TargetType == targetType && rule.DelegateType == typeof(T)) { + if (rule.Member == member && rule.IsMissing == isMissing && rule.TargetType == targetType && rule.DelegateType == typeof(T)) { shared = rule; break; } @@ -408,10 +514,16 @@ internal override T BindShared(object[]/*!*/ args) { } if (shared == null) { + // (see RubyMetaBinder.BindDelegateNoTiming) + if (beforeDispatcher && member.DeclaringModule is RubyClass declaring && declaring.IsSingletonClass && + declaring == context.GetImmediateClassOf(target)) { + deferred = true; + return null; + } lock (_SharedRulesLock) { sharedRules = _sharedRules; if (sharedRules == null || sharedRules.Length < MaxSharedRules) { - _sharedRules = ArrayUtils.Append(sharedRules ?? new SharedRule[0], new SharedRule(method.Info, targetType, typeof(T), version)); + _sharedRules = ArrayUtils.Append(sharedRules ?? new SharedRule[0], new SharedRule(member, isMissing, targetType, typeof(T), version)); } } return null; @@ -430,7 +542,21 @@ internal override T BindShared(object[]/*!*/ args) { // The shared rule is handed out for a version it does not hold yet, and only then: a call that comes here although // the rule holds its version didn't match the rule (its arguments are of other types, say) and gets a rule of its own. if (!shared.Versions.TryAdd(version)) { - return null; + // Or the rule is interpreted and has been compiled meanwhile: it then fails its test once, so that the site binds again + // and picks up the compiled one (DynamicUtils.LightBind), which the rule's binder hands out without building a rule. + // The shared rule is that one from now on; handing out the interpreted one again would fail and bind every call. + RuleBuilt = false; + T compiled = this.LightBind(args, Context.CompilationThreshold); + if (!RuleBuilt) { + lock (_SharedRulesLock) { + if (shared.Rule == sharedRule) { + shared.Rule = compiled; + } + } + } else { + CacheTarget(compiled); + } + return compiled; } return (T)sharedRule; @@ -486,7 +612,7 @@ internal static bool HasPlainClrTypeTest(RubyClass/*!*/ targetClass, string/*!*/ } private T/*!*/ BindSharedRule(SharedRule/*!*/ shared, object[]/*!*/ args) where T : class { - var versionSet = new RuleVersionSet(); + var versionSet = new RuleVersionSet(this); T result; _PendingVersionSet = versionSet; @@ -500,7 +626,7 @@ internal static bool HasPlainClrTypeTest(RubyClass/*!*/ targetClass, string/*!*/ CacheTarget(result); // The rule tests the version set iff Build has taken it and bound it to a version the method was resolved for: - if (versionSet.Member == shared.Member) { + if (versionSet.Member == shared.Member && versionSet.IsMissing == shared.IsMissing) { lock (_SharedRulesLock) { if (shared.Rule == null) { shared.Versions = versionSet; @@ -822,7 +948,15 @@ internal static MethodResolutionResult Resolve(MetaObjectBuilder/*!*/ metaBuilde // the version the test was bound against resolves to this method: if (versionSet != null && versionSet.Count > 0) { - versionSet.Member = method.Found ? method.Info : null; + if (method.Found) { + versionSet.Member = method.Info; + } else if (method.Info == null && method.IncompatibleVisibility == RubyMethodVisibility.None) { + // the method_missing a call of an undefined name makes (see BindShared) + versionSet.Member = methodMissing; + versionSet.IsMissing = true; + } else { + versionSet.Member = null; + } } } diff --git a/Src/Ruby/Runtime/Calls/RubyMetaBinder.cs b/Src/Ruby/Runtime/Calls/RubyMetaBinder.cs index 5da0f7358..e89f3034b 100644 --- a/Src/Ruby/Runtime/Calls/RubyMetaBinder.cs +++ b/Src/Ruby/Runtime/Calls/RubyMetaBinder.cs @@ -78,10 +78,27 @@ private T BindDelegateNoTiming(CallSite site, object[] args) where T : cla ArgumentArray argArray = firstArg as ArgumentArray; Type delegateType = typeof(T); T result; + bool sharedProbed = false; if (argArray != null) { firstArg = argArray.GetArgument(0); } else { + // A site with a light scope has a precompiled dispatcher for a Ruby method (RubyCallAction.BindPrecompiled), one class + // at a time; a method that receivers of many classes resolve the call to - singleton classes of objects of one class, + // say - is better served by the one rule that holds them all, as it was before light sites had dispatchers. + // So is a call on an object with a singleton class of its own at any site: a dispatcher serves that one object, while the + // shared rule's test takes in the next object's singleton class without a bind (RuleVersionSet.IsValidFor). + // This probe gives no new table entry to a method of the receiver's own singleton class, which no other receiver + // resolves to: one-off `def o.m`s would fill the table that calls needing a rule share. Such a call records its entry + // below if no dispatcher serves it; any other answer of this probe is the one below would give, so that is skipped. + if ((Signature.HasLightScope || IsObjectWithSingleton(args)) && _context != null && !_context.Options.NoAdaptiveCompilation) { + bool deferred; + if ((result = BindShared(args, true, out deferred)) != null) { + if (PhaseTimer.BindTrace) PhaseTimer.BindKind = PhaseTimer.BindKind == "rule" ? "shared-new" : "shared-hit"; + return result; + } + sharedProbed = !deferred; + } object precompiled = BindPrecompiled(delegateType, args); if (precompiled != null) { result = (T)precompiled; @@ -115,7 +132,7 @@ private T BindDelegateNoTiming(CallSite site, object[] args) where T : cla ), "BIND"); } #endif - if (argArray == null && (result = BindShared(args)) != null) { + if (argArray == null && !sharedProbed && (result = BindShared(args, false, out _)) != null) { if (PhaseTimer.BindTrace) PhaseTimer.BindKind = PhaseTimer.BindKind == "rule" ? "shared-new" : "shared-hit"; return result; } @@ -138,6 +155,12 @@ private static void ChainDispatcher(CallSite/*!*/ site, T/*!*/ result) whe } } + // The receiver is a Ruby object (not a module) whose class is its singleton class. + private bool IsObjectWithSingleton(object[]/*!*/ args) { + int i = Signature.HasScope ? 1 : 0; + return i < args.Length && args[i] is IronRuby.Builtins.RubyObject obj && obj.ImmediateClass.IsSingletonClass; + } + /// /// Returns a precompiled rule delegate or null, if not available for the given delegate type and arguments. /// @@ -155,8 +178,11 @@ internal virtual int GetRuleCompilationThreshold(object[]/*!*/ args, RubyContext /// /// Returns a rule that is shared with receivers of other classes the call resolves the same for, or null (see ). + /// Before a precompiled dispatcher is tried (beforeDispatcher), a call that resolves to a method of its receiver's own singleton + /// class and has no entry yet gets none: deferred is then true, and the call is to be asked again if no dispatcher serves it. /// - internal virtual T BindShared(object[]/*!*/ args) where T : class { + internal virtual T BindShared(object[]/*!*/ args, bool beforeDispatcher, out bool deferred) where T : class { + deferred = false; return null; } @@ -169,7 +195,12 @@ internal virtual T BindShared(object[]/*!*/ args) where T : class { } } + // Set by every Bind: tells a LightBind that built a rule from one that handed out a compiled target (see RubyCallAction.BindShared). + [ThreadStatic] + internal static bool RuleBuilt; + private DynamicMetaObject/*!*/ BindNoTiming(DynamicMetaObject/*!*/ scopeOrContextOrTargetOrArgArray, DynamicMetaObject/*!*/[]/*!*/ args) { + RuleBuilt = true; if (PhaseTimer.BindTrace) PhaseTimer.BindKind = "rule"; PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "Ruby: " + GetType().Name + Signature.ToString() + ": Bind"); diff --git a/Src/Ruby/Runtime/Calls/RuleVersionSet.cs b/Src/Ruby/Runtime/Calls/RuleVersionSet.cs index c7f475e8b..4a0b6a4af 100644 --- a/Src/Ruby/Runtime/Calls/RuleVersionSet.cs +++ b/Src/Ruby/Runtime/Calls/RuleVersionSet.cs @@ -54,7 +54,14 @@ public sealed class RuleVersionSet { /// internal RubyMemberInfo Member; - internal RuleVersionSet() { + // Member is the method_missing a call of a name no method has makes (see RubyCallAction.BindShared). + internal bool IsMissing; + + // The binder of the call the rule makes: asked to verify a version the set does not hold yet (see IsValidFor). + private readonly RubyCallAction _owner; + + internal RuleVersionSet(RubyCallAction owner) { + _owner = owner; _slots = new int[8]; } @@ -134,7 +141,29 @@ public static bool IsValid(RuleVersionSet/*!*/ set, int version) { return set.Contains(version); } - private static MethodInfo _IsValidMethod; + /// + /// The test of a Ruby object's class version: a version the set does not hold is added if the call resolves to the rule's + /// method for the object's class (RubyCallAction.TryShareVersion), without binding the call again. + /// + public static bool IsValidFor(RuleVersionSet/*!*/ set, int version, object target) { + if (set.Contains(version)) { + return true; + } + // A site whose receivers resolve the call to other methods tries its rules in turn: a version found not to resolve to this + // one fails at once the next time instead of being resolved again. + if (set._owner == null || !(target is IRubyObject) || version == Volatile.Read(ref set._lastRejected)) { + return false; + } + if (set._owner.TryShareVersion(target, set)) { + return true; + } + Volatile.Write(ref set._lastRejected, version); + return false; + } + + private int _lastRejected; + + private static MethodInfo _IsValidMethod, _IsValidForMethod; private static FieldInfo _LastVersionField; @@ -147,15 +176,25 @@ public static bool IsValid(RuleVersionSet/*!*/ set, int version) { /// rules ran 5-10% slower than one whose sites got rules of their own (the precompiled startup library makes the former /// common: its compiled sites register the typed delegate shapes before startup's last method definitions bump the classes). /// - internal Expression/*!*/ MakeTest(Expression/*!*/ versionExpression, int boundVersion) { - var method = _IsValidMethod ?? (_IsValidMethod = CallInstruction.CacheFunc(IsValid)); + /// + /// , if given, is the receiver (a Ruby object) whose class version is tested: a version not in the set + /// is then verified and added by the test itself (see ). + internal Expression/*!*/ MakeTest(Expression/*!*/ versionExpression, int boundVersion, Expression target = null) { var lastVersion = _LastVersionField ?? (_LastVersionField = typeof(RuleVersionSet).GetField("LastVersion")); var set = AstUtils.Constant(this); + Expression inSet; + if (target != null) { + var method = _IsValidForMethod ?? (_IsValidForMethod = CallInstruction.CacheFunc(IsValidFor)); + inSet = Expression.Call(method, set, versionExpression, AstUtils.Convert(target, typeof(object))); + } else { + var method = _IsValidMethod ?? (_IsValidMethod = CallInstruction.CacheFunc(IsValid)); + inSet = Expression.Call(method, set, versionExpression); + } return Expression.OrElse( Expression.Equal(versionExpression, AstUtils.Constant(boundVersion)), Expression.OrElse( Expression.Equal(versionExpression, Expression.Field(set, lastVersion)), - Expression.Call(method, set, versionExpression) + inSet ) ); } diff --git a/Src/Ruby/Runtime/EvalAstCache.cs b/Src/Ruby/Runtime/EvalAstCache.cs new file mode 100644 index 000000000..362d65d56 --- /dev/null +++ b/Src/Ruby/Runtime/EvalAstCache.cs @@ -0,0 +1,79 @@ +/* **************************************************************************** + * + * This source code is subject to terms and conditions of the Apache License, Version 2.0. A + * copy of the license can be found in the License.html file at the root of this distribution. + * + * ***************************************************************************/ + +using System.Collections.Generic; +using System.Text; +using IronRuby.Builtins; +using IronRuby.Compiler.Ast; + +namespace IronRuby.Runtime { + + /// + /// The trees (SourceUnitTree) of the strings a runtime evaluated lately, so that a template + /// evaluated again and again (ERB#result) is parsed and mapped by the prism bridge once. + /// What is kept is the AST only, which holds no runtime state: every eval still transforms + /// and compiles it afresh, so /o regexps, END {}, literal identity and the call sites of the + /// code a second eval runs are its own (the compiled-code cache tried before shared those; + /// Util/eval-matrix.rb). The AST is already compiled more than once elsewhere - a method body + /// per lexical module chain, a `def` run many times - and its transformation assigns the same + /// closure slots each time (LexicalScope.AllocateClosureSlotsForLocals). + /// + /// The key is everything the bridge's result depends on for an eval: the text, the file and + /// line, the outer locals in order, the source encoding and whether the eval is outside a method. + /// A parse that reported anything (a warning, which may depend on $VERBOSE and must be reported + /// again) or failed is not kept, nor are evals of an isolated proc. Per runtime, bounded (LRU), + /// and locked: threads run in parallel. + /// + internal sealed class EvalAstCache { + internal const int MaxCodeLength = 64 * 1024; + private const int Capacity = 64; + + private readonly Dictionary>> _map = + new Dictionary>>(); + private readonly LinkedList> _order = new LinkedList>(); + + internal static string/*!*/ MakeKey(string/*!*/ code, string path, int line, bool outsideMethod, + RubyEncoding encoding, List localNames) { + var key = new StringBuilder(code.Length + 64); + key.Append(path).Append('\0').Append(line).Append('\0').Append(outsideMethod ? '1' : '0').Append('\0'); + key.Append(encoding != null ? encoding.Name : "").Append('\0'); + if (localNames != null) { + key.Append(localNames.Count); + foreach (var name in localNames) { + key.Append('\0').Append(name); + } + } + key.Append('\u0001').Append(code); + return key.ToString(); + } + + internal SourceUnitTree Get(string/*!*/ key) { + lock (_map) { + if (_map.TryGetValue(key, out var node)) { + _order.Remove(node); + _order.AddFirst(node); + return node.Value.Value; + } + return null; + } + } + + internal void Add(string/*!*/ key, SourceUnitTree/*!*/ tree) { + lock (_map) { + if (_map.ContainsKey(key)) { + return; + } + if (_map.Count >= Capacity) { + var last = _order.Last; + _order.RemoveLast(); + _map.Remove(last.Value.Key); + } + _map.Add(key, _order.AddFirst(new KeyValuePair(key, tree))); + } + } + } +} diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index 5927481ab..875592599 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -579,6 +579,28 @@ internal int CompilationThreshold { // binders' rule caches - into the program's first few hundred milliseconds instead. internal const int StartupCompilationThreshold = 200; + /// The trees of recently evaluated strings (PrismAstBridge.Parse); made at the first eval. + internal EvalAstCache EvalAstCache; + + /// + /// The compilation threshold of the code an eval of a String compiles (Kernel#eval, Binding#eval, + /// instance_eval and module_eval of a String): its blocks and loops. Each eval builds a new lambda, + /// so a block in it that crosses the threshold is compiled - a JIT of a new DynamicMethod, about a + /// millisecond on a pool thread - for that one eval, and the next eval of the same text compiles + /// it again. ERB#result evals its template each time: the template's `items.each do ... end` + /// over 40 items was compiled on every result, three times the CPU the result itself took. + /// A block that runs 1000 times in one eval still gets compiled; an explicit + /// -X:CompilationThreshold applies as it is. + /// + internal int EvalCompilationThreshold { + get { + int threshold = _options.CompilationThreshold; + return threshold < 0 ? Math.Max(DefaultEvalCompilationThreshold, CompilationThreshold) : threshold; + } + } + + internal const int DefaultEvalCompilationThreshold = 1000; + internal RubyScope/*!*/ EmptyScope { get { return _emptyScope; } } diff --git a/Src/Ruby/Runtime/RubyUtils.cs b/Src/Ruby/Runtime/RubyUtils.cs index 5d9c8dbbe..bbec01de8 100644 --- a/Src/Ruby/Runtime/RubyUtils.cs +++ b/Src/Ruby/Runtime/RubyUtils.cs @@ -1513,7 +1513,8 @@ public static object Evaluate(MutableString/*!*/ code, RubyScope/*!*/ targetScop } Debug.Assert(lambda != null); - var compiled = (EvalEntryPointDelegate)RubyScriptCode.CompileLambda(lambda, context); + var compiled = (EvalEntryPointDelegate)RubyScriptCode.CompileLambda(lambda, context.DomainManager.Configuration.DebugMode, + context.Options.NoAdaptiveCompilation, context.EvalCompilationThreshold); var blockParameter = (methodScope != null) ? methodScope.BlockParameter : null; if ((TracePoint.ActiveEvents & (int)TraceEvents.ScriptCompiled) != 0) { diff --git a/Src/StdLib/ironruby/date/format.rb b/Src/StdLib/ironruby/date/format.rb index ff6bf7f3a..92945cf9c 100644 --- a/Src/StdLib/ironruby/date/format.rb +++ b/Src/StdLib/ironruby/date/format.rb @@ -148,7 +148,8 @@ def method_missing(t, *args, &block) end def to_hash - @elem.reject{|k, v| /\A_/ =~ k.to_s || v.nil?} + # date__strptime leaves offset: nil when it does not know the zone + @elem.reject{|k, v| /\A_/ =~ k.to_s || (v.nil? && k != :offset)} end end @@ -264,7 +265,7 @@ def self._strptime_i(str, fmt, e) # :nodoc: else /\A([-+]?\d{1,})/ end, '') # val = Rational($1.to_i, 10**3) - val = Rational($1.to_i, 10**$1.size) + val = Rational($1.to_i, 10**$1.delete('-+').size) e.sec_fraction = val when 'M', 'OM' return unless str.sub!(/\A(\d{1,2})/, '') @@ -282,12 +283,12 @@ def self._strptime_i(str, fmt, e) # :nodoc: else /\A([-+]?\d{1,})/ end, '') # val = Rational($1.to_i, 10**9) - val = Rational($1.to_i, 10**$1.size) + val = Rational($1.to_i, 10**$1.delete('-+').size) e.sec_fraction = val when 'n', 't' return unless _strptime_i(str, "\s", e) when 'P', 'p' - return unless str.sub!(/\A([ap])(?:m\b|\.m\.)/i, '') + return unless str.sub!(/\A([ap])(?:m|\.m\.)/i, '') e._merid = if $1.downcase == 'a' then 0 else 12 end when 'Q' return unless str.sub!(/\A(-?\d{1,})/, '') @@ -382,6 +383,23 @@ def self._strptime_i(str, fmt, e) # :nodoc: private_class_method :_strptime_i def self._strptime(str, fmt='%F') + # StringValue, as date_s__strptime takes both (String#+ converts with #to_str, or raises + # MRI's TypeError: "no implicit conversion of nil into String") + str = '' + str unless String === str + fmt = '' + fmt unless String === fmt + # ASCII-only Strings go to the C# walk (Src/Libraries/Date/DateStrptime.cs), which answers + # false for what it leaves to the Ruby below. It hands back the Rationals as [n, d] and the + # offset as a place after the zone, so that the Hash keeps the Bag's order. + if String.equal?(str.class) && String.equal?(fmt.class) && str.ascii_only? && fmt.ascii_only? + h = __strptime_ascii(str, fmt) + unless false.equal?(h) + return h unless h + if (v = h[:sec_fraction]) then h[:sec_fraction] = Rational(v[0], v[1]) end + if Array === (v = h[:seconds]) then h[:seconds] = Rational(v[0], v[1]) end + h[:offset] = zone_to_diff(h[:zone]) if h.key?(:offset) + return h + end + end str = str.dup e = Format::Bag.new return unless _strptime_i(str, fmt, e) diff --git a/Src/StdLib/ironruby/erb/escape.rb b/Src/StdLib/ironruby/erb/escape.rb new file mode 100644 index 000000000..5879cf84f --- /dev/null +++ b/Src/StdLib/ironruby/erb/escape.rb @@ -0,0 +1,21 @@ +# frozen_string_literal: true +# +# erb's C extension, provided by IronRuby itself. +# +# erb/util.rb starts with +# +# begin +# require 'erb/escape' +# rescue LoadError +# module ERB::Escape +# def html_escape(s) = CGI.escapeHTML(s.to_s) # (spelled out there) +# module_function :html_escape +# end +# end +# +# and this file is what that require finds: ERB::Escape.html_escape in C# +# (Src/Libraries/Erb/ErbEscape.cs), what escape.c defines on CRuby. It hands back the String +# it was given when nothing in it needs escaping, as escape.c does, and it is what every +# <%= h(...) %> of a template and ERB::Util.html_escape run. + +load_assembly 'IronRuby.Libraries', 'IronRuby.StandardLibrary.Erb' diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 4c3cdb504..2b91ede32 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -1460,7 +1460,9 @@ def sum(init = 0, &block) result = __numeric_sum__(init) return result unless result.nil? return __float_init_sum__(init, __ary_at__(0), 1) if ::Float === init - super + # not Enumerable#sum, which goes through #each and compensates again at a Float after + # a value that is not a number: MRI's rb_ary_sum does neither (see __sum_tail__) + __array_sum__(init) { |e| e } end # Array#sum with a block (see there). A method of its own so that #sum without one stays @@ -1475,6 +1477,13 @@ def __array_sum__(init, &block) acc = acc + x next end + # an Integer and a Rational, or two Rationals, are added exactly, as MRI's rb_ary_sum does + # until its first Float (rb_rational_plus, whatever Rational#+ is now): a Rational must not + # take the plain fold of __sum_rest__, which leaves out the compensation at a later Float + if (::Rational === x || ::Integer === x) && (::Rational === acc || ::Integer === acc) + acc = __exact_add__(acc, x) + next + end unless ::Float === x && (::Integer === acc || ::Rational === acc) # (a Float initial value ends up here at the first value: see __sum_rest__) return __sum_rest__(acc, x, i, &block) @@ -1584,16 +1593,19 @@ def __sum_rest__(acc, x, i, &block) end private :__sum_rest__ - # __sum_rest__'s fold itself, which __float_init_sum__ calls too. + # __sum_rest__'s fold itself, which __float_init_sum__ calls too: from the first value that is + # not a number on, everything is added with #+, a Float to a number too, as in MRI's rb_ary_sum + # (init_is_a_value: has_some_value). It was Enumerable#sum over an Enumerator of the rest, + # which switched to compensated Float summation again at the next Float: an Enumerator and + # a block call more for each value, and [2, 1e100, 1.0, -1e100].sum(x) was 4.0 where MRI's + # 0.0 is what the plain fold gives. def __sum_tail__(acc, x, i) - rest = ::Enumerator.new do |y| - y.yield(x) - while i < __ary_size__ - y.yield(yield(__ary_at__(i))) - i = i.succ - end + while true + acc = acc + x + return acc unless i < __ary_size__ + x = yield(__ary_at__(i)) + i = i.succ end - rest.sum(acc) end private :__sum_tail__ @@ -7630,16 +7642,15 @@ def define(*names, &block) names.freeze klass = ::Class.new(self) do - names.each do |name| - define_method(name) { __ir_hidden_ivar__(name) } - end - class << self def members __data_members__.dup end def new(*args, **kwargs, &block) + # every member given, to the class's own Data#initialize: made directly (KernelOps.DataNew) + instance = __ir_data_new__(::Data, args, kwargs) + return instance if instance unless args.empty? unless kwargs.empty? ::Kernel.raise(::ArgumentError, "wrong number of arguments (given #{args.size + 1}, expected 0)") @@ -7673,7 +7684,8 @@ def inspect end end # klass is a new receiver: see Struct.new - ::Kernel.instance_method(:__ir_set_hidden_ivar__).bind_call(klass, :data_members, names) + # (and its readers, read as an attr_reader is: KernelOps.DefineData) + ::Kernel.instance_method(:__ir_data_define__).bind_call(klass, names) ::Module.instance_method(:class_eval).bind_call(klass, &block) if block klass end @@ -7759,6 +7771,8 @@ def initialize(*args, **kwargs) freeze nil end + # the initialize KernelOps.DataNew and DataWith stand in for: not one a program defines on Data later + __ir_data_initializer__ def members __data_members__.dup @@ -7829,11 +7843,13 @@ def deconstruct_keys(keys) result end - def with(*args, **kwargs) - unless args.empty? - ::Kernel.raise(::ArgumentError, "wrong number of arguments (given #{args.size}, expected 0)") - end + # Positional arguments, a Hash among them, are the arity error a `**kwargs` method raises, + # in MRI's words (rb_scan_args "0:"). + def with(**kwargs) return self if kwargs.empty? + # members named by their Symbols, for Data#initialize: copied directly (KernelOps.DataWith) + copy = __ir_data_with__(::Data, kwargs) + return copy if copy # MRI's rb_data_with: initialize gets to_h merged with the keywords as given (a # String key is not converted, an unknown one is initialize's to report). values = {} diff --git a/Src/StdLib/ironruby/set.rb b/Src/StdLib/ironruby/set.rb index 1b45359ed..f4f3d6be2 100644 --- a/Src/StdLib/ironruby/set.rb +++ b/Src/StdLib/ironruby/set.rb @@ -244,11 +244,46 @@ def initialize(enum = nil, &block) # :yields: o enum.nil? and return if block - __do_with_enum__(enum) { |o| add(block[o]) } + if __core_set__? + __init_block__(enum, block) + else + __do_with_enum__(enum) { |o| add(block[o]) } + end else - merge(enum) + __init_enum__(enum) + end + end + + # set_i_initialize: an Array's elements are stored as they are, anything else's come + # from its each_entry (or #each), a Set's too. A Set whose #each is Set's own is copied + # by its table, which nothing can tell apart. A subclass with Set::SubclassCompatible + # merges. + def __init_enum__(enum) # :nodoc: + return merge(enum) unless __core_set__? && !frozen? && !@__iter_lev__ + if ::Array === enum + __merge_array__(enum) + elsif ::Set === enum && enum.method(:each).owner.equal?(::Set) && + enum.method(:each_entry).owner.equal?(::Enumerable) + @__hash__.update(enum.__send__(:__ir_hidden_ivar__, :@__hash__)) + else + __merge_each__(enum) + end + end + private :__init_enum__ + + # set_initialize_with_block: what the block answers is stored without #add. + def __init_block__(enum, block) # :nodoc: + if ::Array === enum + i = 0 + while i < enum.__send__(:__ary_size__) + __store__(block[enum.__send__(:__ary_at__, i)]) + i = i.succ + end + else + __do_with_enum__(enum) { |o| __store__(block[o]) } end end + private :__init_block__ # Makes the set compare its elements by their identity and returns # self. This method may not be supported by all subclasses of Set. @@ -436,6 +471,9 @@ def include?(o) # Returns true if the set is a superset of the given set. def superset?(set) case + when ::Set === set && __core_set__? + other = set.__send__(:__ir_hidden_ivar__, :@__hash__) + @__hash__.size >= other.size && __table_in__(other, @__hash__) when set.instance_of?(self.class) && @__hash__.respond_to?(:>=) @__hash__ >= set.__send__(:__ir_hidden_ivar__, :@__hash__) when set.is_a?(Set) @@ -449,6 +487,9 @@ def superset?(set) # Returns true if the set is a proper superset of the given set. def proper_superset?(set) case + when ::Set === set && __core_set__? + other = set.__send__(:__ir_hidden_ivar__, :@__hash__) + @__hash__.size > other.size && __table_in__(other, @__hash__) when set.instance_of?(self.class) && @__hash__.respond_to?(:>) @__hash__ > set.__send__(:__ir_hidden_ivar__, :@__hash__) when set.is_a?(Set) @@ -462,6 +503,9 @@ def proper_superset?(set) # Returns true if the set is a subset of the given set. def subset?(set) case + when ::Set === set && __core_set__? + other = set.__send__(:__ir_hidden_ivar__, :@__hash__) + @__hash__.size <= other.size && __table_in__(@__hash__, other) when set.instance_of?(self.class) && @__hash__.respond_to?(:<=) @__hash__ <= set.__send__(:__ir_hidden_ivar__, :@__hash__) when set.is_a?(Set) @@ -475,6 +519,9 @@ def subset?(set) # Returns true if the set is a proper subset of the given set. def proper_subset?(set) case + when ::Set === set && __core_set__? + other = set.__send__(:__ir_hidden_ivar__, :@__hash__) + @__hash__.size < other.size && __table_in__(@__hash__, other) when set.instance_of?(self.class) && @__hash__.respond_to?(:<) @__hash__ < set.__send__(:__ir_hidden_ivar__, :@__hash__) when set.is_a?(Set) @@ -485,6 +532,22 @@ def proper_subset?(set) end alias < proper_subset? + # Whether every key of +a+ is one of +b+ (set_le_i): the tables, not #each or #include?, + # as core Set compares with another Set. + def __table_in__(a, b) # :nodoc: + a.each_key { |o| return false unless b.key?(o) } + true + end + private :__table_in__ + + # Whether +a+ and +b+ share a key (set_i_intersect's walk of the smaller table). + def __tables_meet__(a, b) # :nodoc: + a, b = b, a if a.size > b.size + a.each_key { |o| return true if b.key?(o) } + false + end + private :__tables_meet__ + # Returns 0 if the set are equal, # -1 / +1 if the set is a proper subset / superset of the given set, # or nil if they both have unique elements. @@ -508,6 +571,7 @@ def <=>(set) def intersect?(set) case set when Set + return __tables_meet__(@__hash__, set.__send__(:__ir_hidden_ivar__, :@__hash__)) if __core_set__? if size < set.size any?(set) else @@ -658,16 +722,87 @@ def select!(&block) def merge(*enums, **nil) __check_frozen__ raise RuntimeError, "cannot add to set during iteration" if @__iter_lev__ - enums.each do |enum| - if enum.instance_of?(self.class) - @__hash__.update(enum.__send__(:__ir_hidden_ivar__, :@__hash__)) + enums.each { |enum| __merge_enum__(enum) } + self + end + + # set_merge_enum_into: core Set fills its table from another Set or an Array without + # calling #each or #add, and from anything else with each_entry (or #each), still without + # #add. A subclass with Set::SubclassCompatible adds each element with #add. + def __merge_enum__(enum) # :nodoc: + if enum.instance_of?(self.class) + @__hash__.update(enum.__send__(:__ir_hidden_ivar__, :@__hash__)) + elsif !__core_set__? + __do_with_enum__(enum) { |o| add(o) } + elsif ::Array === enum + __merge_array__(enum) + elsif ::Set === enum + @__hash__.update(enum.__send__(:__ir_hidden_ivar__, :@__hash__)) + else + __merge_each__(enum) + end + self + end + private :__merge_enum__ + + # The Array's storage, not its #each, #size or #[]: a subclass's own are not called. + def __merge_array__(ary) # :nodoc: + h = @__hash__ + if ary.instance_of?(::Array) + ary.each { |o| h[o] = true } + else + i = 0 + while i < ary.__send__(:__ary_size__) + h[ary.__send__(:__ary_at__, i)] = true + i = i.succ + end + end + end + private :__merge_array__ + + # set_merge_enum_into's rb_block_call of each_entry (or #each), whose block stores the + # element without #add. Enumerable#each_entry is inlined when it is the receiver's: it + # packs what #each yields (no value is nil, several an Array) as enum_yield does. The + # block raises as #add did when the enumerable froze or began iterating the set (MRI + # stores the element regardless; the table here, a Hash, would raise its own error). + def __merge_each__(enum) # :nodoc: + if enum.respond_to?(:each_entry) + if enum.method(:each_entry).owner.equal?(::Enumerable) + __merge_one_each__(enum) and return + enum.each { |*v| __store__(v.size == 1 ? v[0] : (v.empty? ? nil : v)) } else - __do_with_enum__(enum) { |o| add(o) } + enum.each_entry { |o| __store__(o) } end + elsif enum.respond_to?(:each) + enum.each { |o| __store__(o) } + else + raise ArgumentError, "value must be enumerable" end + end + private :__merge_each__ - self + # #add without the call of a subclass's own. + def __store__(o) # :nodoc: + h = @__hash__ + h.frozen? and __check_frozen__ + if @__iter_lev__ && !h.key?(o) + raise RuntimeError, "can't add a new item into set during iteration" + end + h[o] = true + end + private :__store__ + + # A Range's or an arithmetic sequence's own #each yields one value at a time, so the + # block takes it as it is. Answers nil for any other #each. + def __merge_one_each__(enum) # :nodoc: + c = enum.class + return unless (c.equal?(::Range) || c.equal?(::Enumerator::ArithmeticSequence)) && + enum.method(:each).owner.equal?(c) + h = @__hash__ + enum.each { |o| h[o] = true } + true end + private :__merge_one_each__ # Deletes every element that appears in the given enumerable object # and returns self. @@ -694,7 +829,15 @@ def |(enum) # Set[1, 3, 5] - Set[1, 5] #=> # # Set['a', 'b', 'z'] - ['a', 'c'] #=> # def -(enum) - dup.subtract(enum) + return dup.subtract(enum) unless __core_set__? + n = dup + h = n.__send__(:__ir_hidden_ivar__, :@__hash__) + if ::Set === enum + enum.__send__(:__ir_hidden_ivar__, :@__hash__).each_key { |o| h.delete(o) } + else + __do_with_enum__(enum) { |o| h.delete(o) } + end + n end alias difference - @@ -705,7 +848,17 @@ def -(enum) # Set['a', 'b', 'z'] & ['a', 'b', 'c'] #=> # def &(enum) n = __new_like__ - if enum.is_a?(Set) + if ::Set === enum && __core_set__? + # set_i_intersection: the smaller table walked, the larger one looked up + h = n.__send__(:__ir_hidden_ivar__, :@__hash__) + mine = @__hash__ + other = enum.__send__(:__ir_hidden_ivar__, :@__hash__) + if other.size > mine.size + mine.each_key { |o| h[o] = true if other.key?(o) } + else + other.each_key { |o| h[o] = true if mine.key?(o) } + end + elsif enum.is_a?(Set) if enum.size > size each { |o| n.add(o) if enum.include?(o) } else @@ -716,9 +869,11 @@ def &(enum) # enumerable's #each may look at what its block answers. Kept and called after # #& has returned, it still adds to the result but answers nil, as MRI's does # (test_set.rb's test_and). + h = n.__send__(:__ir_hidden_ivar__, :@__hash__) + mine = @__hash__ done = false begin - __do_with_enum__(enum) { |o| n.add(o) if include?(o); done ? nil : o } + __do_with_enum__(enum) { |o| h[o] = true if mine.key?(o); done ? nil : o } ensure done = true end @@ -749,8 +904,15 @@ def ^(enum) return n end n = dup - enum = __alloc_like__.merge(enum) unless enum.is_a?(Set) - enum.each { |o| n.add(o) unless n.delete?(o) } + h = n.__send__(:__ir_hidden_ivar__, :@__hash__) + enum = __alloc_like__.merge(enum) unless ::Set === enum + enum.__send__(:__ir_hidden_ivar__, :@__hash__).each_key do |o| + if h.key?(o) + h.delete(o) + else + h[o] = true + end + end n end diff --git a/Util/bench/erb-shapes.rb b/Util/bench/erb-shapes.rb new file mode 100644 index 000000000..5db38793a --- /dev/null +++ b/Util/bench/erb-shapes.rb @@ -0,0 +1,46 @@ +# Where ERB#result's time goes (perf/erb2): the parts of app-shapes.rb's erb_result, one template +# render per unit. erb_full is result_with_hash; erb_eval evals the template's src in a fresh +# binding (parse, bridge, transform, compile and run); erb_def runs the same src as a method +# defined once (the body alone); erb_toplevel is new_toplevel + local_variable_set (the binding); +# erb_new is ERB.new(t).src (the template compiler); eval_small is eval('1 + 1', fresh binding). +# +# IR_CONFIG=Release ./ir.sh Util/bench/erb-shapes.rb [shape ...] +# ruby Util/bench/erb-shapes.rb +$stdout.sync = true +require 'erb' +require 'zlib' +def crc(s) = Zlib.crc32(s) + +PAGE = <<~'EOS' +

<%= title %>

+
    + <% items.each do |item| -%> +
  • <%= ERB::Util.html_escape(item[:text]) %> (<%= item[:n] %>)
  • + <% end -%> +
+

Total: <%= items.sum { |i| i[:n] } %>

+EOS +ITEMS = (1..40).map { |i| { text: "Task <#{i}> & more", n: i * 3, done: i.even? } }.freeze +ERBT = ERB.new(PAGE, trim_mode: '-') +SRC = ERBT.src +class Body; end +Body.class_eval("def self.run(title, items)\n#{SRC}\nend") +def fresh(title) = (b = binding; b.local_variable_set(:title, title); b.local_variable_set(:items, ITEMS); b) + +def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; sum = nil + 7.times { t0 = cpu; sum = yield n; d = cpu - t0; best = d if d < best } + printf "%-16s %9.1f ns %d\n", name, best * 1e9 / n, sum +end +N = (ENV["N"] || 1000).to_i +def n(count) = [count * N / 1000, 1].max + +t("erb_full", n(300)) { |n| s = 0; n.times { |i| s += crc(ERBT.result_with_hash(title: "T#{i & 3}", items: ITEMS)) }; s } +t("erb_eval", n(300)) { |n| s = 0; n.times { |i| s += crc(eval(SRC, fresh("T#{i & 3}"), '(erb)', 0)) }; s } +t("erb_def", n(3000)) { |n| s = 0; n.times { |i| s += crc(Body.run("T#{i & 3}", ITEMS)) }; s } +t("erb_toplevel", n(3000)) { |n| s = 0; n.times { |i| b = ERBT.send(:new_toplevel, [:title, :items]); b.local_variable_set(:title, i); s += b.local_variable_get(:title) }; s } +t("erb_new", n(1000)) { |n| s = 0; n.times { s += crc(ERB.new(PAGE, trim_mode: '-').src) }; s } +t("eval_small", n(10000)) { |n| s = 0; n.times { s += eval('1 + 1', binding) }; s } diff --git a/Util/bench/invoice-parts.rb b/Util/bench/invoice-parts.rb new file mode 100644 index 000000000..b5ad9fc29 --- /dev/null +++ b/Util/bench/invoice-parts.rb @@ -0,0 +1,64 @@ +# The parts of app-shapes.rb's invoice_build and invoice_render (module Shop), one operation per +# shape, to see which of them carry the gap to CRuby: +# ruby Util/bench/invoice-parts.rb [shape...] +# ruby Util/perf/ab.rb Util/bench/invoice-parts.rb "base=..." "new=..." -- money_new money_with +$stdout.sync = true +def cpu = Process.clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; sum = nil + 7.times { t0 = cpu; sum = yield n; d = cpu - t0; best = d if d < best } + printf "%-16s %9.1f ns %d\n", name, best * 1e9 / n, sum +end +N = (ENV["N"] || 1000).to_i +def n(c) = [c * N / 1000, 1].max + +module P + Address = Struct.new(:street, :city, :country, keyword_init: true) + Money = Data.define(:cents) do + include Comparable + def +(other) = with(cents: cents + other.cents) + def *(n) = with(cents: (cents * n).round) + def <=>(other) = cents <=> other.cents + def to_s = format("%d.%02d", cents / 100, cents % 100) + end + class Product + attr_reader :sku, :price + def initialize(sku:, name:, price:, tax: :standard) + @sku, @name, @price, @tax = sku, name, Money.new(price), tax + end + end + class Line + attr_reader :qty + def initialize(product, qty: 1, discount: 0) + @product, @qty, @discount = product, qty, discount + end + end + class Doc + def audit_log = (@audit_log ||= []) + def record(event, **details) = audit_log << { event: event, at: audit_log.size, **details } + end + module Deep; class Order; end; end + M = Money.new(5) + PR = Product.new(sku: "A", name: "B", price: 1) + LINES = Array.new(6) { |i| Money.new(i) } +end + +t("money_new", n(100000)) { |n| s = 0; n.times { |i| s += P::Money.new(i).cents }; s } +t("money_new_kw", n(100000)) { |n| s = 0; n.times { |i| s += P::Money.new(cents: i).cents }; s } +t("money_plus", n(100000)) { |n| m = P::M; s = 0; n.times { s += (m + m).cents }; s } +t("money_mul", n(100000)) { |n| m = P::M; s = 0; n.times { s += (m * 2).cents }; s } +t("money_with", n(100000)) { |n| m = P::M; s = 0; n.times { |i| s += m.with(cents: i).cents }; s } +t("address_new", n(100000)) { |n| s = 0; n.times { s += P::Address.new(street: "a", city: "b", country: "c").country.size }; s } +t("product_new", n(100000)) { |n| s = 0; n.times { s += P::Product.new(sku: "A", name: "B", price: 3).price.cents }; s } +t("product_new_opt", n(100000)) { |n| s = 0; n.times { s += P::Product.new(sku: "A", name: "B", price: 3, tax: :zero).price.cents }; s } +t("line_new", n(100000)) { |n| s = 0; pr = P::PR; n.times { s += P::Line.new(pr, qty: 2).qty }; s } +t("line_new2", n(100000)) { |n| s = 0; pr = P::PR; n.times { s += P::Line.new(pr, qty: 2, discount: 1).qty }; s } +t("record", n(100000)) { |n| s = 0; d = P::Doc.new; n.times { |i| d.instance_variable_set(:@audit_log, nil) if i % 8 == 0; s += d.record(:x, a: 1).size }; s } +t("sum_init", n(30000)) { |n| s = 0; l = P::LINES; n.times { s += l.sum(P::Money.new(0)) { |x| x }.cents }; s } +t("format", n(100000)) { |n| s = 0; n.times { |i| s += format("%d.%02d", i / 100, i % 100).size }; s } +t("class_last", n(100000)) { |n| s = 0; o = P::Deep::Order.new; n.times { s += o.class.name.split('::').last.size }; s } +t("cmp", n(100000)) { |n| s = 0; a = P::M; b = P::Money.new(7); n.times { s += (a <=> b) }; s } +t("sort", n(30000)) { |n| s = 0; l = P::LINES; n.times { s += l.sort.first.cents }; s } +t("sort_by_arr", n(30000)) { |n| s = 0; l = P::LINES; n.times { s += l.sort_by { |x| [-x.cents, "a"] }.first.cents }; s } diff --git a/Util/bench/set-shapes.rb b/Util/bench/set-shapes.rb new file mode 100644 index 000000000..8be5d4850 --- /dev/null +++ b/Util/bench/set-shapes.rb @@ -0,0 +1,52 @@ +# Times each operation of app-shapes.rb's `set` alone (Set is core in CRuby 4.0, set.c, and +# Ruby in IronRuby, Src/StdLib/ironruby/set.rb). Prints ` ns `; the +# checksums must equal CRuby's. +# +# ruby Util/bench/set-shapes.rb [shape...] +# ruby Util/perf/ab.rb Util/bench/set-shapes.rb cruby=ruby "new=env IR_CONFIG=Release ./ir.sh" +$stdout.sync = true +def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end +# INSTR=1 (Util/perf/ab.rb -i) adds a column: the instructions of a call, from the least of the +# seven sections as the time is. See Util/perf/instructions.rb. +INSTR = ENV["INSTR"] && (require_relative "../perf/instructions"; Instructions.open || warn("no instruction counter (perf_event_open)")) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; fewest = nil; counted = !!INSTR; sum = nil + 7.times do + c0 = INSTR && INSTR.read; t0 = cpu; sum = yield n; d = cpu - t0; c1 = INSTR && INSTR.read + best = d if d < best + # a read is nil once the counter is lost: then there is no count, rather than one of the sections that had it + if c0 && c1 then c = c1 - c0; fewest = c if fewest.nil? || c < fewest else counted = false end + end + printf "%-16s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(" %.1f instr", fewest.to_f / n) : "" +end +N = (ENV["N"] || 1000).to_i +def n(c) = [c * N / 1000, 1].max +A = Set.new(1..200) +B = Set.new((100..300).step(2)) +D = A & B +R = (1..200) +AR = R.to_a +EN = (100..300).step(2) +S3 = Set[1, 2, 3] +W = %w[apple pear apple plum fig pear kiwi fig] +T = Set[1000] +t("new_range", n(300)) { |n| s = 0; n.times { s += Set.new(R).size }; s } +t("new_step", n(300)) { |n| s = 0; n.times { s += Set.new(EN).size }; s } +t("new_array", n(300)) { |n| s = 0; n.times { s += Set.new(AR).size }; s } +t("new_empty", n(30000)) { |n| s = 0; n.times { s += Set.new.size }; s } +t("brackets", n(30000)) { |n| s = 0; n.times { s += Set[1, 2, 3].size }; s } +t("union", n(300)) { |n| s = 0; n.times { s += (A | B).size }; s } +t("minus", n(300)) { |n| s = 0; n.times { s += (A - S3).size }; s } +t("and", n(300)) { |n| s = 0; n.times { s += (A & B).size }; s } +t("xor", n(300)) { |n| s = 0; n.times { s += (A ^ B).size }; s } +t("subset", n(3000)) { |n| s = 0; n.times { s += 1 if D.subset?(A) }; s } +t("superset", n(3000)) { |n| s = 0; n.times { s += 1 if A.superset?(D) }; s } +t("disjoint", n(30000)) { |n| s = 0; n.times { s += 1 if A.disjoint?(T) }; s } +t("add_words", n(10000)) { |n| s = 0; n.times { w = Set.new; W.each { |x| w << x }; s += w.size }; s } +t("include", n(100000)) { |n| s = 0; n.times { s += 1 if A.include?(150) }; s } +t("each", n(1000)) { |n| s = 0; n.times { A.each { |x| s += x } }; s } +t("select_sum", n(1000)) { |n| s = 0; n.times { s += A.select(&:even?).sum }; s } +t("map_sum", n(1000)) { |n| s = 0; n.times { s += D.map { |x| x * 2 }.sum }; s } +t("size", n(100000)) { |n| s = 0; n.times { s += A.size }; s } diff --git a/Util/bench/time-shapes.rb b/Util/bench/time-shapes.rb new file mode 100644 index 000000000..19ebff99c --- /dev/null +++ b/Util/bench/time-shapes.rb @@ -0,0 +1,32 @@ +# The parts of app-shapes.rb's `time` shape, one shape each. +$stdout.sync = true +require 'time' +require 'zlib' +def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end +INSTR = ENV["INSTR"] && (require_relative "../perf/instructions"; Instructions.open || warn("no instruction counter (perf_event_open)")) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; fewest = nil; counted = !!INSTR; sum = nil + 7.times do + c0 = INSTR && INSTR.read; t0 = cpu; sum = yield n; d = cpu - t0; c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 then c = c1 - c0; fewest = c if fewest.nil? || c < fewest else counted = false end + end + printf "%-16s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(" %.1f instr", fewest.to_f / n) : "" +end +N = (ENV["N"] || 1000).to_i +def n(c) = [c * N / 1000, 1].max +ST = ["2026-03-14 15:09:26", "2025-12-31 23:59:59", "2024-02-29 00:00:01", "2001-09-09 01:46:40"].freeze +TS = ST.map { |s| Time.utc(*s.scan(/\d+/).map(&:to_i)) }.freeze +ISO = TS.map(&:iso8601).freeze +def crc(s) = Zlib.crc32(s) +t("strptime", n(2000)) { |n| s = 0; n.times { |i| s += Time.strptime(ST[i & 3] + " UTC", "%Y-%m-%d %H:%M:%S %Z").utc.to_i % 1000 }; s } +t("d_strptime", n(4000)) { |n| s = 0; n.times { |i| s += Date._strptime(ST[i & 3] + " UTC", "%Y-%m-%d %H:%M:%S %Z").size }; s } +t("iso_out", n(20000)) { |n| s = 0; n.times { |i| s += TS[i & 3].iso8601.size }; s } +t("iso_in", n(4000)) { |n| s = 0; n.times { |i| s += Time.iso8601(ISO[i & 3]).to_i % 1000 }; s } +t("strftime", n(20000)) { |n| s = 0; n.times { |i| s += TS[i & 3].strftime("%a %d %b %Y %H:%M").size }; s } +t("parse", n(2000)) { |n| s = 0; n.times { |i| s += Time.parse(ST[i & 3] + " +0000").utc.to_i % 1000 }; s } +t("d_parse", n(2000)) { |n| s = 0; n.times { |i| s += Date._parse(ST[i & 3] + " +0000").size }; s } +t("httpdate", n(20000)) { |n| s = 0; n.times { |i| s += TS[i & 3].httpdate.size }; s } +t("crc", n(20000)) { |n| s = 0; n.times { |i| s += crc(ISO[i & 3]) % 1000 }; s } diff --git a/Util/erb-escape-matrix.rb b/Util/erb-escape-matrix.rb new file mode 100644 index 000000000..d57923fca --- /dev/null +++ b/Util/erb-escape-matrix.rb @@ -0,0 +1,107 @@ +# Differential matrix for ERB::Escape.html_escape (Src/Libraries/Erb/ErbEscape.cs, escape.c's erb_escape_html): +# what it escapes and hands back, and how it converts a non-String with #to_s - rb_convert_type, whose +# rb_check_funcall asks a respond_to? of the object's own, then any #to_s, then respond_to_missing? and a +# method_missing of the object's own, and turns a NoMethodError out of method_missing into the TypeError +# unless respond_to? or respond_to_missing? said yes. +# +# ruby Util/erb-escape-matrix.rb > cruby.txt +# IR_CONFIG=Release ./ir.sh Util/erb-escape-matrix.rb > ir.txt +# IR_CONFIG=Release ./ir.sh -X:NoJIT -X:NoOSR Util/erb-escape-matrix.rb > ir-nojit.txt +# +# All three outputs must be identical. +require 'erb/escape' +def t(label) + r = yield + puts "#{label}: #{r.inspect}" +rescue Exception => e + puts "#{label}: #{e.class}: #{e.message}" +end +class P1 < BasicObject # no respond_to?, no respond_to_missing? + def method_missing(m, *a) = m == :to_s ? "" : super +end +class P2 < BasicObject # respond_to_missing? only, BasicObject has no respond_to? + def respond_to_missing?(m, priv) = m == :to_s + def method_missing(m, *a) = m == :to_s ? "" : super +end +class P3 # to_s advertised only for private lookup + undef_method :to_s + def respond_to_missing?(m, priv) = m == :to_s && priv + def method_missing(m, *a) = m == :to_s ? "" : super +end +class P4 # advertised publicly + undef_method :to_s + def respond_to_missing?(m, priv) = m == :to_s + def method_missing(m, *a) = m == :to_s ? "" : super +end +class P5 # method_missing without respond_to_missing? + undef_method :to_s + def method_missing(m, *a) = m == :to_s ? "" : super +end +class P6 < BasicObject # nothing at all +end +class P7 # respond_to? redefined to say yes + undef_method :to_s + def respond_to?(m, priv = false) = m == :to_s || super + def method_missing(m, *a) = m == :to_s ? "" : super +end +class P8 # private to_s + private def to_s = "" +end +class P9 # to_s returns non-String + def to_s = 42 +end +[P1, P2, P3, P4, P5, P6, P7, P8, P9].each { |c| t(c.name) { ERB::Escape.html_escape(c.new) } } +class Q1 # method_missing that gives up (super) + undef_method :to_s + def method_missing(m, *a) = super +end +class Q2 # gives up although respond_to_missing? said yes + undef_method :to_s + def respond_to_missing?(m, priv) = m == :to_s + def method_missing(m, *a) = super +end +class Q3 # raises a NoMethodError about something else + undef_method :to_s + def method_missing(m, *a) = m == :to_s ? nil.zork : super +end +class Q4 # respond_to? says no although to_s exists + def respond_to?(m, priv = false) = m == :to_s ? false : super +end +class Q5 # respond_to? of one parameter + undef_method :to_s + def respond_to?(m) = m == :to_s + def method_missing(m, *a) = m == :to_s ? "" : super +end +class Q6 < BasicObject # respond_to_missing? says yes only privately, method_missing gives up + def respond_to_missing?(m, priv) = m == :to_s && priv + def method_missing(m, *a) = ::Kernel.raise(::NoMethodError.new("nope", m, receiver: self)) +end +$log = [] +class Q7 # what respond_to_missing? is asked + undef_method :to_s + def respond_to_missing?(m, priv) = ($log << [m, priv]; true) + def method_missing(m, *a) = m == :to_s ? "" : super +end +[Q1, Q2, Q3, Q4, Q5, Q6, Q7].each { |c| t(c.name) { ERB::Escape.html_escape(c.new) } } +class Q8 < BasicObject # respond_to? defines the to_s it says yes to: found on the first call + def respond_to?(m, priv = false) + return false unless m == :to_s + (class << self; self; end).send(:define_method, :to_s) { "" } + true + end +end +t("Q8") { ERB::Escape.html_escape(Q8.new) } +p $log +class SubS < String; end +plain = "no entities" +sub = SubS.new("plain sub") +[["plain", "a&\"c'd"], ["empty", ""], ["utf8", "é<ü>"], ["binary", "".b], ["sjis", "".encode("Shift_JIS")]].each do |label, s| + t(label) { r = ERB::Escape.html_escape(s); [r, r.encoding.name] } +end +t("same object") { [ERB::Escape.html_escape(plain).equal?(plain), ERB::Escape.html_escape(sub).equal?(sub), ERB::Escape.html_escape(sub).class] } +t("utf16") { require "cgi/escape"; ERB::Escape.html_escape("".encode("UTF-16LE")).encode("UTF-8") } +t("symbol") { ERB::Escape.html_escape(:"") } +t("integer") { ERB::Escape.html_escape(42) } +t("nil") { ERB::Escape.html_escape(nil) } +t("hot") { r = nil; 5000.times { |i| r = ERB::Escape.html_escape(i.even? ? "<#{i}>" : P4.new) }; r } +t("util") { require "erb"; [ERB::Util.html_escape("<&>"), ERB::Util.h(P5.new)] } diff --git a/Util/eval-matrix.rb b/Util/eval-matrix.rb index 7905e4c3a..1bced1185 100644 --- a/Util/eval-matrix.rb +++ b/Util/eval-matrix.rb @@ -224,4 +224,71 @@ def t23; m23; rescue => e; e.backtrace.first(3).map { |l| l[/:\d+:in '[^']*'/] } 2.times { eval("define_method(:evb24) { /blk/ }"); c << evb24 } puts "24. literals in defs: #{r.inspect} #{[a[0].equal?(a[1]), a[0].equal?(a[2]), b[0].equal?(b[1]), c[0].equal?(c[1])].inspect}" +# 25. blocks and loops of eval'd text that run past the interpreter's compilation threshold (an +# eval's is higher than other code's): a method redefined, a closure local, a /o regexp, break and +# next while they run; a while loop whose locals the binding keeps; a define_method block called on +def f25(i) = i +src25 = "acc = []; o = nil\n1500.times { |i| (def f25(i) = -i) if i == 700; (def f25(i) = i * 2) if i == 1200\n" \ + "o = /o\#{i}/o; next if i.odd?; break if i == 1400; acc << f25(i) }\n" \ + "j = 0; s = 0; while j < 3000; s += j; j += 1; end\n" \ + "define_method(:g25) { |x| x + j }\n[acc.size, acc.sum, acc[349..352], o, s]" +r = 3.times.map { eval(src25) } +g = (1..2500).sum { |x| g25(x) } +b25 = binding; eval("k25 = 0; 2000.times { k25 += 1 }", b25) +puts "25. hot blocks in eval: #{r.uniq.inspect} #{r.size} #{g} #{b25.local_variable_get(:k25)}" + +# 26-31: the trees of evaluated strings are kept (EvalAstCache, keyed by the text, file, line, +# outer locals and encoding) and transformed and compiled afresh at each eval. +# 26. the same text where a name is a method, a parameter, or a local an earlier eval of the +# binding defined +def x26 = :meth +def a26 = eval("x26") +def b26(x26) = eval("x26") +def c26 + b = binding + r = [eval("defined?(z26) ? z26 : :none", b)] + eval("z26 = 7", b) + r << eval("defined?(z26) ? z26 : :none", b) << eval("x26", b) +end +r = 600.times.map { |i| i.even? ? a26 : b26(i % 3) } +puts "26. names: #{r.tally.sort_by(&:to_s).inspect} #{300.times.map { c26 }.uniq.inspect}" + +# 27. the same text with a different file and line, hot (a line of 0 is left out: its backtrace +# line differs on the baseline too) +r = 600.times.map { |i| eval("[__FILE__, __LINE__, __method__.inspect, caller(0)[0].split('/').last]", nil, "f#{i % 2}.rb", [-1, 1, 7][i % 3]) } +puts "27. file and line: #{r.uniq.sort.inspect}" + +# 28. the same characters in strings of other encodings, and with a magic comment +u = "['é'.encoding.to_s, 'é'.bytesize, __ENCODING__.to_s]" +r = 300.times.map { |i| eval(i % 3 == 0 ? u : i % 3 == 1 ? u.encode("ISO-8859-1") : u.b) } +m = 200.times.map { |i| eval(i.even? ? "# encoding: us-ascii\n__ENCODING__.to_s" : "__ENCODING__.to_s") } +puts "28. encodings: #{r.uniq.inspect} #{m.uniq.inspect}" + +# 29. a syntax error and an error found while compiling, the same each time after the text was +# evaluated without one in another place +e = 3.times.map { begin; eval("1 +"); rescue SyntaxError => x; x.message.lines.first.chomp; end } +f = 3.times.map { |i| begin; eval("break", nil, "b29.rb", 5); rescue SyntaxError => x; x.message[/\A[^\n]*/]; end } +g = [1, 2].map { |v| eval("[v * 2].each { |w| break w + 1 }") } +puts "29. errors: #{e.uniq.inspect} #{f.uniq.inspect} #{g.inspect}" + +# 30. an ERB template rendered hot, with other values each time, and one that defines a method +# with a /o regexp and a literal each time it is rendered +require 'erb' +t30 = ERB.new("<% items.each do |it| -%><%= title %>:<%= it * k %>,<% end -%>|<%= defined?(extra) ? extra : '-' %>", trim_mode: '-') +r = 400.times.map { |i| t30.result_with_hash(title: "t#{i % 4}", items: [1, 2, i % 5], k: i % 7) } +x = 3.times.map { t30.result_with_hash(title: "x", items: [], k: 1, extra: "E") } +d30 = ERB.new("<% def d30(v) = [/a\#{v}/o, /lit/] %><%= d30(n).first.source %>") +o = 3.times.map { |n| d30.result_with_hash(n: n) + d30(9).first.source + d30(9)[1].equal?(d30(8)[1]).to_s } +puts "30. erb: #{r.sum(&:size)} #{r.uniq.size} #{r[0..1].inspect} #{x.uniq.inspect} #{o.inspect}" + +# 31. threads rendering the same template and evaluating the same text with other locals at once +r = 6.times.map do |n| + Thread.new do + s31 = 0 + 300.times { |i| s31 += t30.result_with_hash(title: "t", items: [n, i % 3], k: n).size + eval("n * i + 1") } + s31 + end +end.map(&:value) +puts "31. threads: #{r.inspect}" + puts 'end' diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 9373dee5f..e2ba3ba8c 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -858,6 +858,14 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has do not do it. Unexplained, and outside AWFY, but a factor of 2.6 on a polymorphic site is worth an afternoon. Bounce may be the same thing: one tree's steady state was 64 ms in one run and 81-83 ms in three others of the same session. + Round thirty-three (see Landed, perf/pwalk): a site in a method without a scope + (`node.accept(self)` in a visitor) built and compiled a rule per receiver class, and past + the DLR's rule caches kept building them again: 52 us a call over 60 classes. Such sites + now take a precompiled dispatcher per class (127 ns). Left: `prism_walk` spends about 12% + in the dispatcher chain and its cache lookup; a table from class to dispatcher per site is + the next idea. A light caller's call of a JIT-typed method with a Float argument (`selfcall` + of micro-table) is 3% slower by median through the dispatcher than through the rule, with + the same bytes. 13. **Calling an iterator at all costs twice what it does in CRuby**: `a.each { |x| s += x }` over one element from a method is 166 ns against 79, `n.times` 182 against 88, `a.map` 194 against 101, and `a.any? { |x| x > 1000 }` 414 against 67, 438 against @@ -940,6 +948,10 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has `super`, `{}`, a `while` with `break`, a block passed on - which is /perf-frame's. `uniq` is not this skill's: its C# method alone costs what the call does (500 ns against CRuby's 230). One method per run of `/perf-core`. `tap` and `then` are already minimal Ruby: what they pay is gap 13. + Round thirty-four (see Landed, perf/time2): ASCII `Date._strptime` is C#, `strptime` 0.2-0.3 + of its time. Left: `Date._parse` and `Time.parse` about 3x CRuby (Ruby regexps and Hash + building in `format.rb`), a "UT-3" style offset, UTF-16 subjects' errors, and a subclass of + String taking the Ruby path. 16. **A light frame whose usual callee wants the caller's scope costs more than a frame with a scope**, and **the splat itself is what a forwarding wrapper still pays**. Both are what is left of "wrappers that splat stay out of light frames", which is done (see @@ -1059,6 +1071,10 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has against 369 ns; positional creation is level at 142 against 131). And `h.each_pair { |k, v| }` / `each_with_index` are 1.6 to 1.9 times CRuby (gap 13 with two parameters). + Round thirty-four (see Landed, perf/inv2): `Data.new`, `#with` and Data readers are direct; + the invoice shapes are at CRuby's time. Left: initializers taking keywords (`Product.new(sku: + ...)`) at about 2x CRuby, `Hash#dup`, and Struct `keyword_init` as above. And + `Data.singleton_methods` lists `:allocate`, which CRuby's does not (as on the baseline). 25. **Havlak: 1.4 times CRuby, 25 times TruffleRuby, and no single place** (round sixteen's breakdown; its author's numbers, taken beside two other experiments at load 2-14, so ratios). CRuby runs a copy with som.rb's `Set` renamed to `SomSet`: 2.85-3.3 @@ -1190,6 +1206,13 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has 0.46 of its time, `instance_eval` and `binding.eval` about half. Left: the parse, bridge, transformation and compilation of every text (about 15 us at the least, CRuby's 2), and `caller(0)`/`caller_locations` paying the whole CLR walk. + Round thirty-three (see Landed, perf/erbr): the blocks of eval'd text are compiled after + 1000 runs instead of 32, and `ERB::Escape.html_escape` is C#: `erb_result` 0.68-0.81 of its + time. Left: an eval's own cost is about 1 ms on a template (light compile, transformation, + bridge), and the template's body run as a method is about 8 times CRuby's. + Round thirty-four (see Landed, perf/erb2): the parsed tree of an evaluated text is kept, so a + template's parse and bridge cost 5 us instead of 72; `erb_eval` 0.77 of its time. Left: the + transformation (~50 us) and light compile (~80 us) of every eval. 32. **A singleton class, and a method defined at run time, cost 25 to 60 times CRuby's** (`Object.new.singleton_class` 17 us, `def o.x` 18, `define_singleton_method` 46, `Class.new` 12, with a `def` 37), and `OpenStruct.new(h)` of three keys, which @@ -1208,6 +1231,15 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has Left: `singleton_class` (1.4 us here, mostly the class itself), `define_singleton_method` (4-9 us, which the factory does not cover: its body is a block), `extend` (gap 19), and the scope per call of a factory-made body. + Round thirty-three (see Landed, perf/ostr): readers at light sites, `respond_to?(:x)` and + the first setter through `method_missing` no longer build a rule per object's singleton + class: `ostruct` of `app-shapes.rb` 0.56 of its time, `ostruct3` of `sdef-shapes.rb` 0.14-0.16. + Left: `OpenStruct.new` is about 120 us against CRuby's 10, some fifteen binds per object. + Round thirty-four (see Landed, perf/ostr2): a shared rule's test takes in a re-versioned + singleton class that resolves the same: binds per OpenStruct 17 -> 4, `ostruct` 0.30-0.33 of + its time. Left: the four binds of per-object readers (a different method on each object); + the resolution in a polymorphic rule's test, which remembers one rejected version only; and + the lock that resolution takes inside a rule test. 33. **Three differences from CRuby in interpolation**, found by the probes of `Util/interpolation-matrix.rb` on the build before perf/interp and left as they were @@ -1227,6 +1259,141 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **Gate of 2026-11-24 for round thirty-four** (perf/time2, perf/inv2, perf/erb2, perf/ostr2): + the branch at 77f841b9 against 592c75ab, Release net10.0: **PASS** with 7289271b (below). + IronRuby.Tests PASSED on both trees, no failure name on either. 37 matrices in seven modes: + CRuby's output but for the differences the baseline has too; `strptime-matrix` differs from + CRuby in 20 lines against the baseline's 32 and `value-object-matrix` in 2 against 12. + `caller-matrix` and `block-loop-matrix` differed on the ReadyToRun host only (the known + `Kernel#eval` and nested `Range#each` frames). Recursion a million deep: SystemStackError in + both modes. ruby/spec, all five suites (32,285 examples): no failure the known list does not + name. The fourteen benchmarks verify; `app-shapes.rb` prints CRuby's checksums, JIT on and off. + Timing: AWFY, 12 iterations, both orders: geomean 0.967 and 1.015 (new/base), no benchmark + more than 5% slower in both. micro-table: `ivar_rw`, `abs`, `arr`, `yield`, `each4`, `poly2`, + `blockeach` and `selfcall` were slower in both orders; in six alternating rounds of their own + they are 0.96-1.08, all overlapping, and `poly2` (the shape perf/ostr2's rule test could + touch) 1.01 in twelve. Of the shape files, `iso_in`, `parse`, `format` and `eval_distinct` + looked slower in one order or both; in alternating rounds of their own, at a steady-state N, + they are 0.83-1.03, overlapping. `app-shapes.rb` four rounds each order: `ostruct` 0.30-0.33 + of its time, `invoice_build` 0.41-0.46, `invoice_render` 0.40-0.43, the rest overlapping. + Bytes per iteration: geomean 1.007, none more than 1% but Towers (149 -> 163 KB). Start-up on + the ReadyToRun host, twelve alternating runs, best ms (base -> new): `-e 1` 425 -> 449 (medians + 521 and 528), `gem --version` 585 -> 600 (medians 685 and 660), and of the gate's own runs + `gem list` 1436 -> 1430, `require "irb"` 1292 -> 1286, `irb` 1866 -> 1840. + +- **7289271b (round thirty-four, after the merge) - an attribute reader may read a hidden + variable.** `RubyAttributeReaderInfo` asserted a name starting with `@`; perf/inv2's Data + readers read the hidden `name`, so every Debug build (CI's) failed the assertion in + `Prelude_DataStructErrors1`. The assertion takes the hidden prefix too. + +- **perf/time2 (round thirty-four, 2026-11-23, ec0f1c98, merged in 1587bcd3) - ASCII-only + `Date._strptime` in C#** (`Src/Libraries/Date/DateStrptime.cs`). The Ruby port of 1.9's + `_strptime_i` cost about 18 us a call against CRuby's 1.1: a String per format token, a case + over sixty literals, a `sub!` with a MatchData per field. The C# walk takes a subject and a + format that are both ASCII-only plain Strings and answers false for anything else, which + `format.rb` then parses as before. Fixed on both paths: `%L`/`%N` with a sign, `%p` before a + letter, an unknown zone's `offset: nil` (in `Date._parse` too). `d_strptime` 0.09-0.31 of its + time, `strptime` 0.20-0.30, `time` of `app-shapes.rb` 0.52. `Util/strptime-matrix.rb` gains + 69 rows; `Util/bench/time-shapes.rb` splits `time` into its parts. + +- **perf/inv2 (round thirty-four, 2026-11-23, 7a2d25f4, merged in ef88aec2) - `Data.new`, + `Data#with`, Data readers and `Array#sum`'s plain fold.** `Data.new` built a keyword Hash out + of positional values and splatted it into `initialize` through three `__send__`s; when the + class's `initialize` is Data's own and the arguments name every member, `KernelOps.DataNew` + makes the frozen instance directly (as MRI, calling neither `allocate` nor `freeze`), and + `DataWith` likewise. Readers are attribute readers of hidden variables, not `define_method` + blocks. `Array#sum` past a non-number is a plain `+` loop, as rb_ary_sum. `Money.new` 1083 -> + 307 ns, `with` 1168 -> 478, `<=>` 143 -> 55; `invoice_build` 0.41-0.46 of its time, + `invoice_render` 0.40-0.43, near CRuby's at steady state (149 and 128 us against 128 and 126). `Util/bench/invoice-parts.rb`. + +- **perf/erb2 (round thirty-four, 2026-11-23, 66e5dec6, merged in acc9f9fc) - the prism trees + of evaluated strings are kept** (`EvalAstCache`, gap 31). Per runtime, the last 64 texts up + to 64 KB, keyed by text, file, line, outer locals, encoding and whether the eval is outside a + method; only the AST, so every eval still transforms and compiles afresh (literal identity, + `/o`, `END {}` and call sites stay per eval, which is what sank the compiled-code cache of + perf/evalc). A parse that reported anything is not kept. Parse and bridge of a template 72 -> + 5 us; `erb_eval` 0.77-0.78 of its time, `erb_full` 0.71-0.73, `erb_result` 0.68. + `Util/eval-matrix.rb` rows 26-31, `Util/bench/erb-shapes.rb`. + +- **perf/ostr2 (round thirty-four, 2026-11-23, 39fd30bf, merged in 77f841b9) - a shared rule's + test takes in a new class version that resolves to its method** (gap 32). Every + `define_singleton_method` re-versions the object's singleton class, so each self call inside + `ostruct.rb` bound again (about 22 binds per `OpenStruct.new`). `RuleVersionSet.IsValidFor` + now resolves the call for a version it does not hold (`RubyCallAction.TryShareVersion`, as + `BindShared` would) and adds it when it lands on the rule's method; a call whose visibility + comes from the caller's scope only for a public method; one rejected version is remembered. + `BindShared` no longer hands out the interpreted rule after the compiled one exists, and a + receiver with a singleton class of its own tries the shared rule before a dispatcher at any + site. Binds per OpenStruct 17 -> 4; `ostruct` of `app-shapes.rb` 0.30-0.33 of its time, + `ostruct3_new` and `ostruct_app` 0.21-0.32. `Util/sdef-matrix.rb` section 11. + +- **Gate of 2026-11-23 for round thirty-three** (perf/setx, perf/erbr, perf/ostr, perf/pwalk): + the branch at 4e349c7f against 02aa8db1, Release net10.0: **PASS** with 5f9f11ef (below). + IronRuby.Tests PASSED on both trees, no failure name on either. 36 matrices in seven modes + (JIT on, `-X:NoJIT -X:NoOSR`, `-X:NoJITCalls`, `IR_LIGHT_FRAMES=0`, `IR_PARKED_SCOPES=0`, + ReadyToRun, and the baseline): CRuby's output but for the differences the baseline has too, + and the new `set-matrix` matches CRuby where the baseline differs in 360 lines. + `block-loop-matrix` differed on the baseline and the ReadyToRun host only (the known nested + `Range#each` frame). Recursion a million deep: SystemStackError in both modes. ruby/spec, all + five suites (32,285 examples): no failure the known list does not name. The fourteen + benchmarks verify; `app-shapes.rb` prints CRuby's checksum for all 26 shapes, JIT on and off. + Timing: AWFY, 12 iterations, both orders: geomean 0.964 and 0.984 (new/base), Richards 0.86-0.89, + no benchmark more than 5% slower in both. micro-table: `symcase`, `selfcall` and `str==` were + slower in both orders; in eight alternating rounds of their own they overlap (`selfcall` again + in ten processes per tree: median 28.9 against 28.1 ns, minimum 27.7 against 26.2). + `app-shapes.rb` five rounds each order: `set` 0.48-0.50 of its time, `ostruct` 0.56, `prism_walk` + 0.87-0.90, `erb_result` 0.78-0.81 (overlapping), the rest overlapping. `set-shapes.rb` and + `eval_1p1`, slower in one order, overlap in eight alternating rounds of their own. + **Bytes per iteration: Richards 14.0 -> 30.3 MB**, the one finding: perf/pwalk gave light sites + the attribute writer's dispatcher, which boxed a typed Boolean per store. Fixed in 5f9f11ef + (geomean of bytes 0.993, Richards 12.8 MB; Richards, DeltaBlue, Towers and Havlak timed again + in both orders: 0.963 and 0.937). Start-up on the ReadyToRun host, ten alternating runs, best + ms (base -> new): `-e 1` 372 -> 380, `gem --version` 485 -> 491, `gem list` 1094 -> 1061, + `require "irb"` 926 -> 929, `irb` 1259 -> 1270. + +- **5f9f11ef (round thirty-three, after the gate) - an attribute writer's dispatcher boxes with + the shared boxes.** `RubyObjectAttributeWriterDispatcherWithScope` stored `(object)arg0`, a new + box per call when the method JIT had typed the site's argument as a Boolean or Integer; it now + converts with `MethodDispatcher.Box` (true and false the shared objects, small Integers from the + cache), as the method dispatchers do. A case of hot writers from light methods in + `Util/perf/hot-shapes-matrix.rb`. + +- **perf/setx (round thirty-three, 2026-11-23, a8c5b84c and e8de5370, merged in 8903a912) - + a core Set's table filled directly** (`Src/StdLib/ironruby/set.rb`). `Set.new`, `merge`, `&`, + `^`, `-`, `subset?` and their kin went through `add` and `include?` per element, which a + subclass may redefine and CRuby's set.c does not call; they now fill and read the Hash. + New `Util/set-matrix.rb` (408 lines; the baseline differs from CRuby in 360) and + `Util/bench/set-shapes.rb`. `set` of `app-shapes.rb` 0.48-0.50 of its time; `Set.new` of a + Range or Array 0.15-0.27, `subset?` 0.14-0.54, `&` 0.39, `[]` 0.42. Left: `^` and `|` cost dup + and Hash inserts; the method JIT refuses the `i.succ` and `frozen?` loops. Differences from + CRuby left as they were: a Set frozen or iterated during a merge, CRuby's interning of String + keys, one more `hash`/`eql?` call in `Hash#delete`, redefined Hash methods being seen. + +- **perf/erbr (round thirty-three, 2026-11-23, aaa9f836 and c9c171d0, merged in e08dc551) - + eval'd blocks compiled later, and `ERB::Escape.html_escape` in C#** (gap 31). The blocks of + an eval'd text were compiled after 32 runs, so a template evaluated per request compiled its + blocks on the background JIT again and again; `RubyContext.EvalCompilationThreshold` (1000) + is the threshold for eval'd code, and `Util/eval-matrix.rb` row 25 runs one past it. And + `erb/escape` was a `gsub` in Ruby; `Src/Libraries/Erb/ErbEscape.cs` ports escape.c. + `erb_result` 0.68-0.81 of its time; process CPU per call 9-11 -> 2.7-3.5 ms. + +- **perf/ostr (round thirty-three, 2026-11-23, 22468d63, merged in ce1ac3ab) - calls on + per-object singleton classes without a rule each** (gap 32). `BindShared` shares the rule of + a call that lands in a Ruby `method_missing` (`IsMissing`, `ResolveMethodMissingForSite`); + `DispatchIntrinsics.MaySpecialize` no longer folds `respond_to?` on a singleton class of a + plain object; a light site's first calls of a `define_method` block method go through a + LibraryDispatcher. `ostruct` of `app-shapes.rb` 0.56 of its time, `ostruct3` of + `sdef-shapes.rb` 0.14-0.16, `extend` 0.36-0.58. + +- **perf/pwalk (round thirty-three, 2026-11-23, 9e29c85b, merged in 4e349c7f) - precompiled + dispatchers at light sites** (gap 12). `BindPrecompiled` refused sites in methods without a + scope, so each receiver class got a rule; it now gives them the dispatchers of Ruby methods + and attribute accessors, resolving an explicit receiver's public method only, never for a + splat, a refined name or a singleton class (except a `define_method` block method), and + `RubyMetaBinder` tries the shared rule first. A site over 60 classes: 52 us -> 127 ns a call; + `prism_walk` 0.87-0.90 of its time, Richards 0.83-0.89. The writer's boxing it exposed is + fixed in 5f9f11ef. + - **Gate of 2026-11-23 for round thirty-two** (perf/caller, perf/stdre, perf/invoice, perf/sclass): the branch at dbe0a3b3 against b7b71c89, Release net10.0: **PASS**. IronRuby.Tests PASSED on both trees, no failure name on either. 35 matrices in seven modes diff --git a/Util/perf/hot-shapes-matrix.rb b/Util/perf/hot-shapes-matrix.rb index 1d1bd7897..9de7b8009 100644 --- a/Util/perf/hot-shapes-matrix.rb +++ b/Util/perf/hot-shapes-matrix.rb @@ -856,3 +856,37 @@ def one_char_slice_threads p [errs.size, dups, Array.new(128) { |i| (0..127).map(&:chr).join[i].ord } == Array.new(128) { |i| i }] end one_char_slice_threads + +# ---- attribute writers called hot from methods without a scope (their sites have a precompiled dispatcher), with a +# literal, a passed and a computed Boolean or Integer: the method JIT types those sites, and the dispatcher boxes the value +# as the runtime does (true and false are the shared objects). Then a subclass's own writer, a writer redefined, the +# receiver frozen and a singleton writer, each after the sites are hot. +class HSWriter + attr_accessor :b, :i, :f, :o + def set_lit; self.b = false; self.i = 7; self.f = 1.5; self.o = nil; self; end + def set_var(x, y); self.b = x; self.i = y; self; end + def set_cmp(y); self.b = y > 3; self.i = y * 2; self; end +end +class HSWriter2 < HSWriter + def b=(v); @b = [:w2, v]; end +end +def hs_writers + r = [] + w = HSWriter.new + 5000.times { |k| w.set_lit; w.set_var(k.odd?, k); w.set_cmp(k) } + r << [w.b, w.i, w.f, w.o, w.b.equal?(true), w.i.equal?(9998)] + w.set_lit + r << [w.b, w.b.equal?(false), w.i, w.f] + v = HSWriter2.new + 3000.times { |k| v.set_lit; v.set_cmp(k) } + r << [v.b, v.i] + HSWriter.class_eval { def i=(v); @i = -v; end } + w.set_lit; w.set_var(true, 100); r << [w.b, w.i] + w.freeze + begin; w.set_lit; rescue => e; r << e.class; end + o = HSWriter.new; def o.b=(v); @b = :single; end + 2000.times { o.set_lit } + r << o.b + p r +end +hs_writers diff --git a/Util/sdef-matrix.rb b/Util/sdef-matrix.rb index 34cae10a8..6aebf7402 100644 --- a/Util/sdef-matrix.rb +++ b/Util/sdef-matrix.rb @@ -206,5 +206,69 @@ class B10; def m(*) = :base; end row "hot #{key}", r end +# ---------------------------------------------------------------- 11. shared rules that take in a new singleton class in their test +# A shared rule's version test resolves the call again for a class version it does not hold (RuleVersionSet.IsValidFor): each +# object below has a singleton class of its own, and some resolve the call to another method, a private one, a protected one, +# method_missing, or nothing. + +class C11 + def m = :c11 + def go = m + def go_explicit(o) = o.m + def go_missing = zz + def method_missing(n, *a) = n == :zz ? :c11_missing : super + def respond_to_missing?(n, p = false) = n == :zz || super + protected def pm = :c11_pm + def call_pm(o) = o.pm +end +module M11; def m = :m11; end +def c11_object(i) + o = C11.new + o.singleton_class + case i % 7 + when 1 then def o.m = :single + when 2 then o.singleton_class.send(:private, :m) + when 3 then o.extend(M11) + when 4 then o.define_singleton_method(:m) { :dsm } + when 5 then def o.method_missing(n, *a) = n == :zz ? :own_missing : super + when 6 then o.singleton_class.send(:undef_method, :m) + end + o +end +row "implicit self over singletons", runs(700) { |i| (c11_object(i).go rescue $!.class) } +row "explicit receiver over singletons", runs(700) { |i| (C11.new.go_explicit(c11_object(i)) rescue $!.class) } +row "explicit top-level over singletons", runs(700) { |i| o = c11_object(i); (o.m rescue $!.class) } +row "method_missing over singletons", runs(700) { |i| (c11_object(i).go_missing rescue $!.class) } +row "protected over singletons", runs(700) { |i| o = c11_object(i); (o.call_pm(c11_object(i + 1)) rescue $!.class) } +row "public_send over singletons", runs(700) { |i| (c11_object(i).public_send(:m) rescue $!.class) } +row "respond_to? over singletons", runs(700) { |i| c11_object(i).respond_to?(:m) } +row "alternating owners", runs(700) { |i| o = C11.new; (i.even? ? (def o.m = :even) : o.singleton_class); o.go } +class C11b; def m = :b; def go = m; end +row "method removed mid-loop", runs(600) { |i| + C11b.send(:remove_method, :m) if i == 300 + C11b.send(:define_method, :m) { :back } if i == 450 + o = C11b.new; o.singleton_class; (o.go rescue $!.class) +} +row "method redefined mid-loop", runs(600) { |i| + C11b.send(:define_method, :m) { :redefined } if i == 200 + o = C11b.new; def o.x = 1; o.go +} +module R11; refine(C11b) { def m = :refined }; end +# the refinement is active only where `using R11` is (Use11); C11b#go, defined outside it, is the unrefined control +module Use11 + using R11 + def self.go(o) = o.m +end +row "refined class over singletons", runs(300) { |i| o = C11b.new; o.singleton_class; [Use11.go(o), o.go] } +# each worker counts its calls that did not give what one thread alone gives for the same kind of object +c11_expected = 7.times.map { |k| (c11_object(k).go rescue $!.class) } +threads = 4.times.map { |t| Thread.new { c11_wrong = 0; 2000.times { |c11_i| c11_v = (c11_object(c11_i + t).go rescue $!.class); c11_wrong += 1 unless c11_v.equal?(c11_expected[(c11_i + t) % 7]) }; c11_wrong } } +row "threads over singletons", [c11_expected, threads.map(&:value)] +os = 300.times.map { |i| OpenStruct.new(a: i, b: i * 2) } +row "ostruct readers", os.sum { |o| o.a + o.b + o[:a] + (o.respond_to?(:b) ? 1 : 0) } +os.each_with_index { |o, i| o.c = i; def o.a = -1 if i % 5 == 0 } +row "ostruct after writers", os.sum { |o| o.a + o.c + o.to_h.size } +row "ostruct dig/==", [os[3].dig(:a), os[3] == os[3].dup, os[5].delete_field(:a), (os[5].a rescue $!.class), os[1].frozen?, os[1].freeze.frozen?, (begin; os[1].a = 2; rescue => e; e.class; end)] + $stderr.puts "jit=#{defined?(IronRuby) ? 'ironruby' : 'cruby'}" puts "end" diff --git a/Util/set-matrix.rb b/Util/set-matrix.rb new file mode 100644 index 000000000..5b5507f1d --- /dev/null +++ b/Util/set-matrix.rb @@ -0,0 +1,202 @@ +# Differential matrix for Set's constructors and operators (Src/StdLib/ironruby/set.rb): +# Set.new and merge from a Set, an Array, a Range, an arithmetic sequence and other +# enumerables, |, -, &, ^, subset?, superset?, proper_subset?, proper_superset?, intersect? +# and disjoint?, for Set, a subclass (Set::SubclassCompatible) and a Set::CoreSet subclass. +# ruby Util/set-matrix.rb # CRuby reference +# ./ir.sh Util/set-matrix.rb # IronRuby; the same with -X:NoJIT -X:NoOSR +# # and with IR_LIGHT_FRAMES=0 +# Each row is evaluated once cold and again after thousands of runs, some with a method +# of Set or Range redefined or a singleton method added half way. + +$log = [] +class Sub < Set + def add(o) = ($log << [:sub_add, o]; super) + def each(&b) = ($log << :sub_each; super) + def include?(o) = ($log << [:sub_inc, o]; super) +end +class Core < Set::CoreSet + def add(o) = ($log << [:core_add, o]; super) + def each(&b) = ($log << :core_each; super) + def include?(o) = ($log << [:core_inc, o]; super) + def delete?(o) = ($log << [:core_del, o]; super) + def size = ($log << :core_size; super) +end +class Arr < Array + def each = ($log << :arr_each; super) + def size = ($log << :arr_size; super) + def [](i) = ($log << :arr_at; super) +end +class Rng < Range + def each = ($log << :rng_each; super) +end +class Key + attr_reader :k + def initialize(k) = @k = k + def hash = ($log << [:hash, @k]; @k.hash) + def eql?(o) = ($log << [:eql, @k]; o.is_a?(Key) && o.k == @k) + def inspect = "K#{@k}" +end +class Each2 + include Enumerable + def each = (yield 1; yield 2, 3; yield; yield [4, 5]; self) +end +class OwnEntry + include Enumerable + def each = (yield 9) + def each_entry = (yield 1; yield 2) +end +class OnlyEach + def each = (yield :x; yield :y) +end +class OnlyEntry + def each_entry = (yield :e) +end + +def row(name) + $log = [] + v = begin + r = yield + "#{r.class} #{r.inspect}#{r.frozen? ? ' frozen' : ''}" + rescue Exception => e + "!#{e.class}: #{e.message}" + end + puts "#{name.ljust(44)} #{v}#{$log.empty? ? '' : " #{$log.inspect}"}" +end + +ROWS = { + "new range" => -> { Set.new(1..6) }, + "new endless step" => -> { Set.new((1..12).step(5)) }, + "new int step" => -> { Set.new(1.step(10, 4)) }, + "new float step" => -> { Set.new(1.step(2, 0.5)) }, + "new string range" => -> { Set.new("a".."d") }, + "new beginless range" => -> { Set.new(..3) }, + "new Rng" => -> { Set.new(Rng.new(1, 3)) }, + "new array" => -> { Set.new([3, 1, 3, "s", nil]) }, + "new Arr" => -> { Set.new(Arr[1, 2, 2]) }, + "new hash" => -> { Set.new({a: 1, b: 2}) }, + "new struct" => -> { Set.new(Struct.new(:a, :b).new(1, 2)) }, + "new Each2" => -> { Set.new(Each2.new) }, + "new OwnEntry" => -> { Set.new(OwnEntry.new) }, + "new OnlyEach" => -> { Set.new(OnlyEach.new) }, + "new OnlyEntry" => -> { Set.new(OnlyEntry.new) }, + "new enumerator" => -> { Set.new([1, 2].each_slice(1)) }, + "new 5" => -> { Set.new(5) }, + "new keys" => -> { Set.new([Key.new(1), Key.new(1), Key.new(2)]) }, + "new block" => -> { Set.new(1..3) { |x| x * 10 } }, + "new Arr block" => -> { Set.new(Arr[1, 2]) { |x| x * 10 } }, + "Sub.new block" => -> { Sub.new([1, 2]) { |x| -x } }, + "Core.new block" => -> { Core.new(Each2.new) { |x| [x] } }, + "new string key" => -> { s = +"str"; r = Set.new([s]); [r.first.frozen?, r.first.equal?(s)] }, + "new Set" => -> { Set.new(Set[1, 2]) }, + "new Sub" => -> { Set.new(Sub[1, 2]) }, + "new Core" => -> { Set.new(Core[1, 2]) }, + "Sub.new array" => -> { Sub.new([1, 2]) }, + "Sub.new range" => -> { Sub.new(1..2) }, + "Core.new array" => -> { Core.new([1, 2]) }, + "Core.new range" => -> { Core.new(1..2) }, + "Core.new Each2" => -> { Core.new(Each2.new) }, + "Core.new Set" => -> { Core.new(Set[7]) }, + "brackets" => -> { Set[1, 2, 1] }, + "Core brackets" => -> { Core[1, 2, 1] }, + "identity new" => -> { a = "x"; s = Set.new.compare_by_identity; s.merge([a, a, "x".dup]); [s.size, s.compare_by_identity?] }, + "merge many" => -> { Set[1].merge([2], 3..4, Set[5]) }, + "merge frozen" => -> { Set[1].freeze.merge([2]) }, + "merge in each" => -> { s = Set[1]; s.each { s.merge([2]) } }, + "merge self in each" => -> { s = Set[1]; s.each { s.merge(s) } }, + "merge non-enum" => -> { Set[1].merge(Object.new) }, + "union" => -> { Set[1, 2] | Set[2, 3] }, + "union array" => -> { Set[1, 2] | [3, 1] }, + "union range" => -> { Set[1, 2] | (2..4) }, + "union non-enum" => -> { Set[1] | 3 }, + "union Sub" => -> { Set[1] | Sub[5] }, + "union Core" => -> { Set[1] | Core[5] }, + "Sub union" => -> { Sub[1] | [2] }, + "Core union" => -> { Core[1] | [2] }, + "Core union Core" => -> { Core[1] | Core[2] }, + "union frozen" => -> { Set[1].freeze | [2] }, + "union identity" => -> { s = Set["a"].compare_by_identity | ["a"]; [s.size, s.compare_by_identity?] }, + "minus" => -> { Set[1, 2, 3] - Set[2] }, + "minus array" => -> { Set[1, 2, 3] - [3, 4] }, + "minus range" => -> { Set[1, 2, 3] - (2..9) }, + "minus Sub" => -> { Set[1, 2] - Sub[1] }, + "minus Core" => -> { Set[1, 2] - Core[1] }, + "Sub minus" => -> { Sub[1, 2] - [1] }, + "Core minus" => -> { Core[1, 2] - [1] }, + "Core minus Core" => -> { Core[1, 2] - Core[2] }, + "minus non-enum" => -> { Set[1] - 3 }, + "minus frozen" => -> { Set[1, 2].freeze - [1] }, + "and" => -> { Set[1, 2, 3] & Set[3, 2, 9] }, + "and larger" => -> { Set[1, 2] & Set[3, 2, 9, 1] }, + "and array" => -> { Set[1, 2, 3] & [3, 1, 7] }, + "and Sub" => -> { Set[1, 2] & Sub[1, 2, 3] }, + "and Core" => -> { Set[1, 2, 3, 4] & Core[1] }, + "Sub and" => -> { Sub[1, 2] & [1] }, + "Sub and Set" => -> { Sub[1, 2] & Set[1] }, + "Core and" => -> { Core[1, 2] & [1] }, + "Core and Core" => -> { Core[1, 2] & Core[2, 3] }, + "and non-enum" => -> { Set[1] & 3 }, + "and identity" => -> { s = Set["a"].compare_by_identity & ["a"]; [s.size, s.compare_by_identity?] }, + "and keys" => -> { Set[Key.new(1), Key.new(2)] & Set[Key.new(2)] }, + "and frozen" => -> { Set[1, 2].freeze & Set[2] }, + "xor" => -> { Set[1, 2] ^ Set[2, 3] }, + "xor array" => -> { Set[1, 2] ^ [2, 3, 3] }, + "xor Sub" => -> { Set[1, 2] ^ Sub[2, 3] }, + "Sub xor" => -> { Sub[1, 2] ^ [3] }, + "Core xor" => -> { Core[1, 2] ^ [2, 3] }, + "Core xor Core" => -> { Core[1, 2] ^ Core[2, 3] }, + "xor non-enum" => -> { Set[1] ^ 3 }, + "xor identity" => -> { s = Set["a"].compare_by_identity ^ ["a"]; [s.size, s.compare_by_identity?] }, + "xor frozen" => -> { Set[1, 2].freeze ^ [2] }, + "subset" => -> { [Set[1].subset?(Set[1, 2]), Set[1, 3].subset?(Set[1, 2]), Set[1, 2] <= Set[1, 2], Set[1, 2] < Set[1, 2], Set[1] < Set[1, 2]] }, + "superset" => -> { [Set[1, 2].superset?(Set[1]), Set[1].superset?(Set[1, 2]), Set[1, 2] >= Set[1, 2], Set[1, 2] > Set[1, 2], Set[1, 2] > Set[1]] }, + "subset Sub" => -> { [Set[1].subset?(Sub[1, 2]), Set[1] < Sub[1, 2], Set[1, 2].superset?(Sub[1]), Set[1, 2] > Sub[1]] }, + "subset Core" => -> { [Set[1].subset?(Core[1, 2]), Set[1] < Core[1, 2], Set[1, 2].superset?(Core[1]), Set[1, 2] > Core[1]] }, + "Sub subset" => -> { [Sub[1].subset?(Set[1, 2]), Sub[1] < Sub[1, 2], Sub[1, 2].superset?(Core[1]), Sub[1, 2] > Set[1]] }, + "Core subset" => -> { [Core[1].subset?(Set[1, 2]), Core[1] < Core[1, 2], Core[1, 2].superset?(Sub[1]), Core[1, 2] > Set[1]] }, + "subset array" => -> { Set[1].subset?([1]) }, + "superset array" => -> { Set[1] >= [1] }, + "subset identity" => -> { a = "a".freeze; b = "a".dup.freeze; [Set[a].compare_by_identity <= Set[b], Set[b] <= Set[a].compare_by_identity, Set[a] <= Set[a].compare_by_identity, Set[a] <= Set[b].compare_by_identity] }, + "subset keys" => -> { Set[Key.new(1)] <= Set[Key.new(1), Key.new(2)] }, + "intersect" => -> { [Set[1].intersect?(Set[1, 2]), Set[1, 2, 3].intersect?(Set[4]), Set[1].intersect?([1]), Set[1].intersect?(2..3)] }, + "disjoint" => -> { [Set[1].disjoint?(Set[1, 2]), Set[1, 2, 3].disjoint?(Set[4]), Set[1].disjoint?([1]), Set[1].disjoint?(2..3)] }, + "intersect Sub Core" => -> { [Set[1].intersect?(Sub[1]), Set[1].disjoint?(Core[1]), Sub[1].intersect?(Core[1]), Core[1].disjoint?(Sub[1])] }, + "intersect non-enum" => -> { Set[1].intersect?(3) }, + "intersect keys" => -> { Set[Key.new(1), Key.new(2)].intersect?(Set[Key.new(2)]) }, +} + +ROWS.each { |name, f| row(name, &f) } +2000.times { ROWS.each_value { |f| $log = []; f.call rescue nil } } +puts "-- hot" +ROWS.each { |name, f| row(name, &f) } + +# something changes in the middle of hot loops +class Set + alias __m_keep_add add + def add(o) = ($log << [:set_add, o]; __m_keep_add(o)) +end +puts "-- Set#add redefined" +ROWS.each { |name, f| row(name, &f) } +class Set + alias add __m_keep_add +end +class Range + alias __m_keep_each each + def each(&b) = ($log << :range_each; __m_keep_each(&b)) +end +puts "-- Range#each redefined" +2.times { ["new range", "union range", "new beginless range"].each { |n| row(n, &ROWS[n]) } } +class Range + alias each __m_keep_each +end +s = Set[1, 2] +def s.each(&b) = ($log << :singleton_each; super) +def s.add(o) = ($log << :singleton_add; super) +puts "-- singleton methods" +row("single union") { s | [3] } +row("single and") { s & Set[2] } +row("single subset") { s <= Set[1, 2, 3] } +row("new from single") { Set.new(s) } +row("merge single") { Set[9].merge(s) } +puts "-- hot again" +2000.times { ROWS.each_value { |f| $log = []; f.call rescue nil } } +ROWS.each { |name, f| row(name, &f) } diff --git a/Util/strptime-matrix.rb b/Util/strptime-matrix.rb index 3ec99a0d6..373a1f7d7 100644 --- a/Util/strptime-matrix.rb +++ b/Util/strptime-matrix.rb @@ -25,7 +25,7 @@ def row(label) first = v if i == 0 last = v end - puts "#{label}: #{first.inspect}#{first == last ? '' : " HOT #{last.inspect}"}" + puts "#{label}: #{first.inspect}#{first.inspect == last.inspect ? '' : " HOT #{last.inspect}"}" end def sp(str, fmt) = row("_strptime #{str.inspect} #{fmt.inspect}") { Date._strptime(str, fmt) } @@ -47,6 +47,36 @@ def sp(str, fmt) = row("_strptime #{str.inspect} #{fmt.inspect}") { Date._strpti ["a.b*c", "a.b*c"], ["2026", "%EY"], ["04", "%Od"], ["5", "%Q"], ["2026 ", "%Y"], ["", "%Y"], ["", ""], ["abc", ""], ["2026", "%"], ["2026", "%Y%"], ["2026", "%q"], ["%q", "%q"]].each { |s, f| sp(s, f) } +# odd rows for the C# walk over ASCII-only strings (Src/Libraries/Date/DateStrptime.cs) and the +# cases it leaves to format.rb (another encoding, a number past a long) +[["EST5", "%Z"], ["EST DST", "%Z"], ["est dst5", "%Z"], ["est dstx", "%Z"], ["Central Daylight Time", "%Z"], + ["a.b standard time!", "%Z"], ["x standard timex", "%Z"], ["utc+09:30:15", "%Z"], ["UT-3", "%Z"], ["gmt", "%Z"], + ["gmtx", "%Z"], ["Z", "%z"], ["xyz", "%Z"], ["+5.5", "%z"], ["+09,30", "%z"], ["+", "%z"], ["UTC_", "%Z"], + ["9", "%Ez"], ["x", "%E"], ["x", "%O"], [":", "%:"], ["+09:00:00", "%:::z"], ["+0900", "%::::z"], + ["20260304", "%Y%m%d"], ["2026030405", "%Y%m%d%H"], ["1" * 30, "%Y"], ["-" + "9" * 20, "%s"], ["9" * 25, "%Q"], + ["12345678901234567", "%Y"], ["-5", "%L"], ["+5", "%N"], ["123456789012", "%N"], ["123456789012", "%N "], + ["-", "%s"], ["+", "%Y"], ["5 pmx", "%I %p"], ["5 p.m", "%I %p"], ["5 PM", "%H %p"], ["12 am", "%I %p"], + ["12 pm 3 am", "%I %p %I %p"], ["1926", "%C%y"], ["2619", "%y%C"], ["99 5", "%g %y"], ["a\vb", "a b"], + ["a \t\n b", "a b"], ["2026-03", "%Y-%m-%d"], ["Wednesday", "%a"], ["wedn", "%A"], ["Septem", "%B"], + ["2026 xx", "%Y"], ["2026", "%Y %"], ["2026 %", "%Y %%"], ["10 5", "%U %W"], ["2026", "%EC%Ey"], + ["3 7", "%Ou %OV"], ["2026é", "%Y"], ["é2026", "é%Y"], ["2026", "%Y é"]].each { |s, f| sp(s, f) } +row("_strptime binary leftover") { h = Date._strptime("2026 xx".b, "%Y"); [h, h[:leftover].encoding] } +row("_strptime binary zone") { h = Date._strptime("UTC".b, "%Z"); [h, h[:zone].encoding] } +row("_strptime us-ascii zone") { h = Date._strptime("UTC".encode("US-ASCII"), "%Z"); [h, h[:zone].encoding] } +row("_strptime utf-16") { Date._strptime("2026".encode("UTF-16LE"), "%Y") } +StrptimeSub = Class.new(String) # one class for all the runs: the row compares their inspect +row("_strptime subclass") { h = Date._strptime(StrptimeSub.new("2026 x"), "%Y"); [h, h[:leftover].class] } +row("_strptime frozen") { Date._strptime("2026".freeze, "%Y".freeze) } +row("_strptime int") { Date._strptime(2026, "%Y") } +row("_strptime nil fmt") { Date._strptime("2026", nil) } +row("_strptime fraction") { Date._strptime("1.5", "%s.%N")[:sec_fraction].class } +row("Time.strptime L") { Time.strptime("2026-03-04 05:06:07.5 +0900", "%Y-%m-%d %H:%M:%S.%L %z").inspect } +row("Time.strptime Q") { Time.strptime("1700000000123", "%Q").utc.inspect } +row("Time.strptime zone name") { Time.strptime("2026-03-04 05:06:07 PST", "%Y-%m-%d %H:%M:%S %Z").utc.inspect } +row("Time.strptime bad zone") { Time.strptime("2026-03-04 05:06:07 xyz", "%Y-%m-%d %H:%M:%S %Z").utc.inspect } +row("Time.strptime bad mday") { Time.strptime("2026-02-31", "%Y-%m-%d").inspect } +row("Time.strptime huge year") { Time.strptime("123456789012345678901234", "%Y").year } + row("_strptime default") { Date._strptime("2026-03-04") } row("DateTime._strptime default") { DateTime._strptime("2026-03-04T05:06:07+09:00") } row("Date.strptime") { Date.strptime("2026-03-04", "%Y-%m-%d").to_s } diff --git a/Util/value-object-matrix.rb b/Util/value-object-matrix.rb index dcdaa6925..9bb232b37 100644 --- a/Util/value-object-matrix.rb +++ b/Util/value-object-matrix.rb @@ -359,6 +359,77 @@ def initialize(w:, h:); super(w: w, h: h, area: w * h); end (ObjectSpace.undefine_finalizer(Object.new).class rescue "#{$!.class}") (ObjectSpace.each_object(Class).class rescue "#{$!.class}") (ObjectSpace.garbage_collect.class rescue "#{$!.class}") + # --- Data.new / #with made directly (KernelOps.DataNew, DataWith) and when they are not + M.new(1, "kg") + M.new(amount: 1, unit: "kg").frozen? + M.new("amount" => 1, "unit" => "kg") + (M.new(1) rescue "#{$!.class}: #{$!.message}") + (M.new(amount: 1) rescue "#{$!.class}: #{$!.message}") + (M.new(amount: 1, unit: 2, x: 3) rescue "#{$!.class}: #{$!.message}") + (M.new(1, 2, 3) rescue "#{$!.class}: #{$!.message}") + (M.new(1, unit: 2) rescue "#{$!.class}: #{$!.message}") + M.new(*[1, 2], **{}) + E0.new.frozen? + E0.new.instance_variables + M.new(1, 2).instance_variables + SUB.new(1, 2) + ($trace = nil; OVER.new(1, 2); $trace) + ($trace = nil; OVER.new(1, 2).with(unit: 3); $trace) + AREA.new(w: 2, h: 3) + AREA.new(w: 2, h: 3).with(w: 4) + (AREA.new(w: 2, h: 3).with(area: 1) rescue "#{$!.class}: #{$!.message}") + M.new(1, 2).with(unit: 3) + M.new(1, 2).with + M.new(1, 2).with("unit" => 4) + (M.new(1, 2).with(foo: 4) rescue "#{$!.class}: #{$!.message}") + (M.new(1, 2).with(1) rescue "#{$!.class}: #{$!.message}") + (M.new(1, 2).with({unit: 4}) rescue "#{$!.class}: #{$!.message}") + (m = M.new(1, 2); m.with(unit: 3).equal?(m)) + (m = M.new(1, 2); m.with(amount: 1, unit: 2).equal?(m)) + Class.new(M).new(1, 2).class.superclass + (c = Class.new(M); c.new(1, 2).with(unit: 5).class == c) + (m = M.new(1, 2); m.singleton_class; m.with(unit: 3).singleton_methods) + (o = Data.define(:a) { def self.allocate = raise("no") }; o.new(1).a) + (o = Data.define(:a) { def freeze = raise("no") }; o.new(1).frozen?) + (o = Data.define(:a); o.new(1).method(:a).arity) + (o = Data.define(:a); o.instance_method(:a).parameters) + (o = Data.define(:a); [o.public_method_defined?(:a), o.instance_method(:a).owner == o]) + (o = Data.define(:a) { def a = super * 2 }; o.new(4).a rescue $!.class) + (o = Data.define(:a); m = o.new(5); m.instance_variable_get(:@a)) + # hot loops with the class changed half way: initialize, the reader, a prepended initialize + (o = Data.define(:a); (1..300).map { |i| o.class_eval { def initialize(a:) = super(a: a * 10) } if i == 150; o.new(i).a }.sum) + (o = Data.define(:a); (1..300).map { |i| o.class_eval { def initialize(**kw) = super(a: 0) } if i == 150; o.new(a: i).with(a: 1).a }.sum) + (o = Data.define(:a); (1..300).map { |i| o.class_eval { def a = 7 } if i == 150; o.new(i).a }.sum) + (o = Data.define(:a); (1..300).map { |i| o.prepend(Module.new { def initialize(a:) = super(a: -a) }) if i == 150; o.new(i).a }.sum) + (o = Data.define(:a); (1..300).map { |i| o.class_eval { remove_method :a } if i == 150; (o.new(i).a rescue 1) }.sum) + # --- Array#sum folding something that is not a number (Array#__sum_tail__) + [M.new(1, 2), M.new(3, 4)].sum([]) + %w[a b c].sum("") + [[1], [2]].sum([0]) + [1, 2].sum(Rational(1, 2)) { |x| x * 0.5 } + ([1, "a"].sum(0) rescue "#{$!.class}: #{$!.message}") + ([0.1] * 10).sum + ([0.1] * 10).sum(0) { |x| x } + (t = Struct.new(:v) { def +(o) = v + (o.respond_to?(:v) ? o.v : o) }; [t.new(1), 1e100, 1.0, -1e100].sum(0) rescue $!.class) + (t = Struct.new(:v) { def +(o) = v + (o.respond_to?(:v) ? o.v : o) }; [t.new(1), 1e100, 1.0, -1e100].sum(0) { |x| x } rescue $!.class) + (t = Struct.new(:v) { def +(o) = v + (o.respond_to?(:v) ? o.v : o) }; [3, t.new(1), 0.1, t.new(2), 0.2, 0.3].sum(0) rescue $!.class) + (t = Struct.new(:v) { def +(o) = self.class.new(v + (o.respond_to?(:v) ? o.v : o)) }; [1, 2, 0.5].sum(t.new(0)).v) + (t = Struct.new(:v) { def +(o) = self.class.new(v + (o.respond_to?(:v) ? o.v : o)) }; (1..300).map { |i| t.class_eval { def +(o) = 1 } if i == 150; [1, 2].sum(t.new(0)) { |x| x }.then { |r| r.is_a?(t) ? r.v : r } }.sum) + (["a", 1.5].sum(0.0) rescue "#{$!.class}: #{$!.message}") + ([1, 1.5, "a"].sum(M.new(0, 0)) { |x| x } rescue "#{$!.class}: #{$!.message}") + (t = Struct.new(:v) { def +(o) = v + o }; [2, 0.1, 0.2, 0.3].sum(t.new(1)) { |x| x }) + (t = Struct.new(:v) { def +(o) = v + o }; [2, 1e100, 1.0, -1e100].sum(t.new(1))) + (t = Struct.new(:v) { def +(o) = v + o }; [1e100, 1.0, -1e100, 3].sum(t.new(1.5)) { |x| x }) + (t = Struct.new(:v) { def +(o) = v + o }; [1r / 3, 0.1, 2].sum(t.new(1))) + # a Rational before the first Float is added exactly, and the Floats after it are compensated + [Rational(1, 1), 1e100, 1.0, -1e100].sum(0) { |x| x } + [Rational(1, 1), 1e100, 1.0, -1e100].sum + [1, Rational(1, 3), 1e100, 1.0, -1e100].sum + [Rational(1, 3), Rational(2, 3), 1].sum + (1..300).map { |i| [Rational(i, 7), 1e100, 1.0, -1e100].sum }.uniq.size + # --- a Data#initialize redefined on Data itself: Data.new and #with call it (last: it stays redefined) + (class Data; alias_method :__vom_init, :initialize; def initialize(**kw) = __vom_init(**kw.transform_values { _1 * 10 }); end; o = Data.define(:a); [o.new(a: 2).a, o.new(3).a, o.new(a: 1).with(a: 4).a]) + (o = Data.define(:a, :b); (1..300).map { |i| o.new(i, 1).with(b: 2).b }.sum) RUBY eval(PRELUDE, TOPLEVEL_BINDING)