From: Jan Kotas Date: Mon, 12 Dec 2016 23:43:49 +0000 (-0800) Subject: Rename Contract.Assert to Debug.Assert (#8600) X-Git-Tag: accepted/tizen/base/20180629.140029~2791 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=b638af3a4dd52fa7b1ea1958164136c72096c25c;p=platform%2Fupstream%2Fcoreclr.git Rename Contract.Assert to Debug.Assert (#8600) --- diff --git a/src/mscorlib/corefx/System/Globalization/Calendar.cs b/src/mscorlib/corefx/System/Globalization/Calendar.cs index f71556c..7c71f28 100644 --- a/src/mscorlib/corefx/System/Globalization/Calendar.cs +++ b/src/mscorlib/corefx/System/Globalization/Calendar.cs @@ -5,6 +5,7 @@ using System; using System.Runtime.CompilerServices; using System.Globalization; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.Serialization; @@ -212,7 +213,7 @@ namespace System.Globalization // The following code assumes that the current era value can not be -1. if (_currentEraValue == -1) { - Contract.Assert(BaseCalendarID != CalendarId.UNINITIALIZED_VALUE, "[Calendar.CurrentEraValue] Expected a real calendar ID"); + Debug.Assert(BaseCalendarID != CalendarId.UNINITIALIZED_VALUE, "[Calendar.CurrentEraValue] Expected a real calendar ID"); _currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra; } return (_currentEraValue); @@ -527,7 +528,7 @@ namespace System.Globalization // this value can be less than 0. It's fine since we are making it positive again in calculating offset. int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7); int offset = (dayForJan1 - firstDayOfWeek + 14) % 7; - Contract.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0"); + Debug.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0"); return ((dayOfYear + offset) / 7 + 1); } diff --git a/src/mscorlib/corefx/System/Globalization/CalendarData.Unix.cs b/src/mscorlib/corefx/System/Globalization/CalendarData.Unix.cs index 6c6a18e..270d62f 100644 --- a/src/mscorlib/corefx/System/Globalization/CalendarData.Unix.cs +++ b/src/mscorlib/corefx/System/Globalization/CalendarData.Unix.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Security; @@ -200,7 +201,7 @@ namespace System.Globalization break; default: const string unsupportedDateFieldSymbols = "YuUrQqwWDFg"; - Contract.Assert(unsupportedDateFieldSymbols.IndexOf(input[index]) == -1, + Debug.Assert(unsupportedDateFieldSymbols.IndexOf(input[index]) == -1, string.Format(CultureInfo.InvariantCulture, "Encountered an unexpected date field symbol '{0}' from ICU which has no known corresponding .NET equivalent.", input[index])); diff --git a/src/mscorlib/corefx/System/Globalization/CalendarData.cs b/src/mscorlib/corefx/System/Globalization/CalendarData.cs index 2dbd1b8..60bd7cb 100644 --- a/src/mscorlib/corefx/System/Globalization/CalendarData.cs +++ b/src/mscorlib/corefx/System/Globalization/CalendarData.cs @@ -5,6 +5,7 @@ using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Collections.Generic; @@ -108,7 +109,7 @@ namespace System.Globalization if (!LoadCalendarDataFromSystem(localeName, calendarId)) { - Contract.Assert(false, "[CalendarData] LoadCalendarDataFromSystem call isn't expected to fail for calendar " + calendarId + " locale " + localeName); + Debug.Assert(false, "[CalendarData] LoadCalendarDataFromSystem call isn't expected to fail for calendar " + calendarId + " locale " + localeName); // Something failed, try invariant for missing parts // This is really not good, but we don't want the callers to crash. diff --git a/src/mscorlib/corefx/System/Globalization/CalendricalCalculationsHelper.cs b/src/mscorlib/corefx/System/Globalization/CalendricalCalculationsHelper.cs index ba7601b..d3820e1 100644 --- a/src/mscorlib/corefx/System/Globalization/CalendricalCalculationsHelper.cs +++ b/src/mscorlib/corefx/System/Globalization/CalendricalCalculationsHelper.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Globalization @@ -153,7 +154,7 @@ namespace System.Globalization // the following formulas defines a polynomial function which gives us the amount that the earth is slowing down for specific year ranges private static double DefaultEphemerisCorrection(int gregorianYear) { - Contract.Assert(gregorianYear < 1620 || 2020 <= gregorianYear); + Debug.Assert(gregorianYear < 1620 || 2020 <= gregorianYear); long january1stOfYear = GetNumberOfDays(new DateTime(gregorianYear, 1, 1)); double daysSinceStartOf1810 = january1stOfYear - StartOf1810; double x = TwelveHours + daysSinceStartOf1810; @@ -162,34 +163,34 @@ namespace System.Globalization private static double EphemerisCorrection1988to2019(int gregorianYear) { - Contract.Assert(1988 <= gregorianYear && gregorianYear <= 2019); + Debug.Assert(1988 <= gregorianYear && gregorianYear <= 2019); return (double)(gregorianYear - 1933) / SecondsPerDay; } private static double EphemerisCorrection1900to1987(int gregorianYear) { - Contract.Assert(1900 <= gregorianYear && gregorianYear <= 1987); + Debug.Assert(1900 <= gregorianYear && gregorianYear <= 1987); double centuriesFrom1900 = CenturiesFrom1900(gregorianYear); return PolynomialSum(s_coefficients1900to1987, centuriesFrom1900); } private static double EphemerisCorrection1800to1899(int gregorianYear) { - Contract.Assert(1800 <= gregorianYear && gregorianYear <= 1899); + Debug.Assert(1800 <= gregorianYear && gregorianYear <= 1899); double centuriesFrom1900 = CenturiesFrom1900(gregorianYear); return PolynomialSum(s_coefficients1800to1899, centuriesFrom1900); } private static double EphemerisCorrection1700to1799(int gregorianYear) { - Contract.Assert(1700 <= gregorianYear && gregorianYear <= 1799); + Debug.Assert(1700 <= gregorianYear && gregorianYear <= 1799); double yearsSince1700 = gregorianYear - 1700; return PolynomialSum(s_coefficients1700to1799, yearsSince1700) / SecondsPerDay; } private static double EphemerisCorrection1620to1699(int gregorianYear) { - Contract.Assert(1620 <= gregorianYear && gregorianYear <= 1699); + Debug.Assert(1620 <= gregorianYear && gregorianYear <= 1699); double yearsSince1600 = gregorianYear - 1600; return PolynomialSum(s_coefficients1620to1699, yearsSince1600) / SecondsPerDay; } @@ -216,7 +217,7 @@ namespace System.Globalization } } - Contract.Assert(false, "Not expected to come here"); + Debug.Assert(false, "Not expected to come here"); return DefaultEphemerisCorrection(year); } @@ -405,7 +406,7 @@ namespace System.Globalization break; } } - Contract.Assert(day != upperBoundNewYearDay); + Debug.Assert(day != upperBoundNewYearDay); return day - 1; } diff --git a/src/mscorlib/corefx/System/Globalization/CharUnicodeInfo.cs b/src/mscorlib/corefx/System/Globalization/CharUnicodeInfo.cs index d3a591e..2824c42 100644 --- a/src/mscorlib/corefx/System/Globalization/CharUnicodeInfo.cs +++ b/src/mscorlib/corefx/System/Globalization/CharUnicodeInfo.cs @@ -18,6 +18,7 @@ using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Reflection; using System.Security; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Globalization @@ -59,8 +60,8 @@ namespace System.Globalization internal static int InternalConvertToUtf32(String s, int index) { - Contract.Assert(s != null, "s != null"); - Contract.Assert(index >= 0 && index < s.Length, "index < s.Length"); + Debug.Assert(s != null, "s != null"); + Debug.Assert(index >= 0 && index < s.Length, "index < s.Length"); if (index < s.Length - 1) { int temp1 = (int)s[index] - HIGH_SURROGATE_START; @@ -100,9 +101,9 @@ namespace System.Globalization internal static int InternalConvertToUtf32(String s, int index, out int charLength) { - Contract.Assert(s != null, "s != null"); - Contract.Assert(s.Length > 0, "s.Length > 0"); - Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length"); + Debug.Assert(s != null, "s != null"); + Debug.Assert(s.Length > 0, "s.Length > 0"); + Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length"); charLength = 1; if (index < s.Length - 1) { @@ -131,8 +132,8 @@ namespace System.Globalization internal static bool IsWhiteSpace(String s, int index) { - Contract.Assert(s != null, "s!=null"); - Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length"); + Debug.Assert(s != null, "s!=null"); + Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length"); UnicodeCategory uc = GetUnicodeCategory(s, index); // In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator". @@ -172,7 +173,7 @@ namespace System.Globalization // internal unsafe static double InternalGetNumericValue(int ch) { - Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); + Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); // Get the level 2 item from the highest 12 bit (8 - 19) of ch. ushort index = s_pNumericLevel1Index[ch >> 8]; // Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table. @@ -193,7 +194,7 @@ namespace System.Globalization internal unsafe static ushort InternalGetDigitValues(int ch) { - Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); + Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); // Get the level 2 item from the highest 12 bit (8 - 19) of ch. ushort index = s_pNumericLevel1Index[ch >> 8]; // Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table. @@ -324,7 +325,7 @@ namespace System.Globalization internal unsafe static byte InternalGetCategoryValue(int ch, int offset) { - Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); + Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); // Get the level 2 item from the highest 12 bit (8 - 19) of ch. ushort index = s_pCategoryLevel1Index[ch >> 8]; // Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table. @@ -341,7 +342,7 @@ namespace System.Globalization // Make sure that OtherNotAssigned is the last category in UnicodeCategory. // If that changes, change the following assertion as well. // - //Contract.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category"); + //Debug.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category"); return (uc); } } @@ -361,8 +362,8 @@ namespace System.Globalization internal static UnicodeCategory InternalGetUnicodeCategory(String value, int index) { - Contract.Assert(value != null, "value can not be null"); - Contract.Assert(index < value.Length, "index < value.Length"); + Debug.Assert(value != null, "value can not be null"); + Debug.Assert(index < value.Length, "index < value.Length"); return (InternalGetUnicodeCategory(InternalConvertToUtf32(value, index))); } @@ -376,16 +377,16 @@ namespace System.Globalization internal static UnicodeCategory InternalGetUnicodeCategory(String str, int index, out int charLength) { - Contract.Assert(str != null, "str can not be null"); - Contract.Assert(str.Length > 0, "str.Length > 0"); ; - Contract.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length"); + Debug.Assert(str != null, "str can not be null"); + Debug.Assert(str.Length > 0, "str.Length > 0"); ; + Debug.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length"); return (InternalGetUnicodeCategory(InternalConvertToUtf32(str, index, out charLength))); } internal static bool IsCombiningCategory(UnicodeCategory uc) { - Contract.Assert(uc >= 0, "uc >= 0"); + Debug.Assert(uc >= 0, "uc >= 0"); return ( uc == UnicodeCategory.NonSpacingMark || uc == UnicodeCategory.SpacingCombiningMark || diff --git a/src/mscorlib/corefx/System/Globalization/CompareInfo.Unix.cs b/src/mscorlib/corefx/System/Globalization/CompareInfo.Unix.cs index 01483b2..21c3c9f 100644 --- a/src/mscorlib/corefx/System/Globalization/CompareInfo.Unix.cs +++ b/src/mscorlib/corefx/System/Globalization/CompareInfo.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -41,8 +42,8 @@ namespace System.Globalization internal static unsafe int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { - Contract.Assert(source != null); - Contract.Assert(value != null); + Debug.Assert(source != null); + Debug.Assert(value != null); if (value.Length == 0) { @@ -85,8 +86,8 @@ namespace System.Globalization internal static unsafe int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { - Contract.Assert(source != null); - Contract.Assert(value != null); + Debug.Assert(source != null); + Debug.Assert(value != null); if (value.Length == 0) { @@ -132,8 +133,8 @@ namespace System.Globalization private int GetHashCodeOfStringCore(string source, CompareOptions options) { - Contract.Assert(source != null); - Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); + Debug.Assert(source != null); + Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return GetHashCodeOfStringCore(source, options, forceRandomizedHashing: false, additionalEntropy: 0); } @@ -145,9 +146,9 @@ namespace System.Globalization private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options) { - Contract.Assert(string1 != null); - Contract.Assert(string2 != null); - Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); + Debug.Assert(string1 != null); + Debug.Assert(string2 != null); + Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); fixed (char* pString1 = string1) { @@ -160,9 +161,9 @@ namespace System.Globalization private unsafe int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options) { - Contract.Assert(!string.IsNullOrEmpty(source)); - Contract.Assert(target != null); - Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); + Debug.Assert(!string.IsNullOrEmpty(source)); + Debug.Assert(target != null); + Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); if (target.Length == 0) { @@ -189,9 +190,9 @@ namespace System.Globalization private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options) { - Contract.Assert(!string.IsNullOrEmpty(source)); - Contract.Assert(target != null); - Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); + Debug.Assert(!string.IsNullOrEmpty(source)); + Debug.Assert(target != null); + Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); if (target.Length == 0) { @@ -222,9 +223,9 @@ namespace System.Globalization private bool StartsWith(string source, string prefix, CompareOptions options) { - Contract.Assert(!string.IsNullOrEmpty(source)); - Contract.Assert(!string.IsNullOrEmpty(prefix)); - Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); + Debug.Assert(!string.IsNullOrEmpty(source)); + Debug.Assert(!string.IsNullOrEmpty(prefix)); + Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && prefix.IsFastSort()) { @@ -236,9 +237,9 @@ namespace System.Globalization private bool EndsWith(string source, string suffix, CompareOptions options) { - Contract.Assert(!string.IsNullOrEmpty(source)); - Contract.Assert(!string.IsNullOrEmpty(suffix)); - Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); + Debug.Assert(!string.IsNullOrEmpty(source)); + Debug.Assert(!string.IsNullOrEmpty(suffix)); + Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && suffix.IsFastSort()) { @@ -320,8 +321,8 @@ namespace System.Globalization internal unsafe int GetHashCodeOfStringCore(string source, CompareOptions options, bool forceRandomizedHashing, long additionalEntropy) { - Contract.Assert(source != null); - Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); + Debug.Assert(source != null); + Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); if (source.Length == 0) { @@ -378,7 +379,7 @@ namespace System.Globalization int bytesWritten = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, buffer, 0); - Contract.Assert(bytesWritten == byteLen); + Debug.Assert(bytesWritten == byteLen); return buffer; } diff --git a/src/mscorlib/corefx/System/Globalization/CompareInfo.Windows.cs b/src/mscorlib/corefx/System/Globalization/CompareInfo.Windows.cs index 9676dcc..d61edc8 100644 --- a/src/mscorlib/corefx/System/Globalization/CompareInfo.Windows.cs +++ b/src/mscorlib/corefx/System/Globalization/CompareInfo.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Globalization @@ -53,24 +54,24 @@ namespace System.Globalization internal static int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { - Contract.Assert(source != null); - Contract.Assert(value != null); + Debug.Assert(source != null); + Debug.Assert(value != null); return FindStringOrdinal(FIND_FROMSTART, source, startIndex, count, value, value.Length, ignoreCase); } internal static int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { - Contract.Assert(source != null); - Contract.Assert(value != null); + Debug.Assert(source != null); + Debug.Assert(value != null); return FindStringOrdinal(FIND_FROMEND, source, startIndex - count + 1, count, value, value.Length, ignoreCase); } private unsafe int GetHashCodeOfStringCore(string source, CompareOptions options) { - Contract.Assert(source != null); - Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); + Debug.Assert(source != null); + Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); if (source.Length == 0) { @@ -102,9 +103,9 @@ namespace System.Globalization private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options) { - Contract.Assert(string1 != null); - Contract.Assert(string2 != null); - Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); + Debug.Assert(string1 != null); + Debug.Assert(string2 != null); + Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); string localeName = _sortHandle != IntPtr.Zero ? null : _sortName; @@ -167,9 +168,9 @@ namespace System.Globalization private int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options) { - Contract.Assert(!string.IsNullOrEmpty(source)); - Contract.Assert(target != null); - Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); + Debug.Assert(!string.IsNullOrEmpty(source)); + Debug.Assert(target != null); + Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); // TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for // and add a precondition that target is not empty. @@ -200,9 +201,9 @@ namespace System.Globalization private int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options) { - Contract.Assert(!string.IsNullOrEmpty(source)); - Contract.Assert(target != null); - Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); + Debug.Assert(!string.IsNullOrEmpty(source)); + Debug.Assert(target != null); + Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); // TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for // and add a precondition that target is not empty. @@ -234,9 +235,9 @@ namespace System.Globalization private bool StartsWith(string source, string prefix, CompareOptions options) { - Contract.Assert(!string.IsNullOrEmpty(source)); - Contract.Assert(!string.IsNullOrEmpty(prefix)); - Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); + Debug.Assert(!string.IsNullOrEmpty(source)); + Debug.Assert(!string.IsNullOrEmpty(prefix)); + Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return FindString(FIND_STARTSWITH | (uint)GetNativeCompareFlags(options), source, @@ -249,9 +250,9 @@ namespace System.Globalization private bool EndsWith(string source, string suffix, CompareOptions options) { - Contract.Assert(!string.IsNullOrEmpty(source)); - Contract.Assert(!string.IsNullOrEmpty(suffix)); - Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); + Debug.Assert(!string.IsNullOrEmpty(source)); + Debug.Assert(!string.IsNullOrEmpty(suffix)); + Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return FindString(FIND_ENDSWITH | (uint)GetNativeCompareFlags(options), source, @@ -401,7 +402,7 @@ namespace System.Globalization // Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; } - Contract.Assert(((options & ~(CompareOptions.IgnoreCase | + Debug.Assert(((options & ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreSymbols | diff --git a/src/mscorlib/corefx/System/Globalization/CompareInfo.cs b/src/mscorlib/corefx/System/Globalization/CompareInfo.cs index a82f705..99e7eec 100644 --- a/src/mscorlib/corefx/System/Globalization/CompareInfo.cs +++ b/src/mscorlib/corefx/System/Globalization/CompareInfo.cs @@ -16,6 +16,7 @@ using System; using System.Reflection; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -245,7 +246,7 @@ namespace System.Globalization { get { - Contract.Assert(_name != null, "CompareInfo.Name Expected _name to be set"); + Debug.Assert(_name != null, "CompareInfo.Name Expected _name to be set"); if (_name == "zh-CHT" || _name == "zh-CHS") { return _name; @@ -428,8 +429,8 @@ namespace System.Globalization // internal static unsafe int CompareOrdinalIgnoreCase(string strA, int indexA, int lengthA, string strB, int indexB, int lengthB) { - Contract.Assert(indexA + lengthA <= strA.Length); - Contract.Assert(indexB + lengthB <= strB.Length); + Debug.Assert(indexA + lengthA <= strA.Length); + Debug.Assert(indexB + lengthB <= strB.Length); int length = Math.Min(lengthA, lengthB); int range = length; diff --git a/src/mscorlib/corefx/System/Globalization/CultureData.Unix.cs b/src/mscorlib/corefx/System/Globalization/CultureData.Unix.cs index 5742ff8..7f2f17d 100644 --- a/src/mscorlib/corefx/System/Globalization/CultureData.Unix.cs +++ b/src/mscorlib/corefx/System/Globalization/CultureData.Unix.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Security; @@ -26,7 +27,7 @@ namespace System.Globalization [SecuritySafeCritical] private unsafe bool InitCultureData() { - Contract.Assert(_sRealName != null); + Debug.Assert(_sRealName != null); string alternateSortName = string.Empty; string realNameBuffer = _sRealName; @@ -122,7 +123,7 @@ namespace System.Globalization private string GetLocaleInfo(LocaleStringData type) { - Contract.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo] Expected _sWindowsName to be populated already"); + Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo] Expected _sWindowsName to be populated already"); return GetLocaleInfo(_sWindowsName, type); } @@ -131,7 +132,7 @@ namespace System.Globalization [SecuritySafeCritical] private string GetLocaleInfo(string localeName, LocaleStringData type) { - Contract.Assert(localeName != null, "[CultureData.GetLocaleInfo] Expected localeName to be not be null"); + Debug.Assert(localeName != null, "[CultureData.GetLocaleInfo] Expected localeName to be not be null"); switch (type) { @@ -148,7 +149,7 @@ namespace System.Globalization { // Failed, just use empty string StringBuilderCache.Release(sb); - Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleStringData)] Failed"); + Debug.Assert(false, "[CultureData.GetLocaleInfo(LocaleStringData)] Failed"); return String.Empty; } return StringBuilderCache.GetStringAndRelease(sb); @@ -157,7 +158,7 @@ namespace System.Globalization [SecuritySafeCritical] private int GetLocaleInfo(LocaleNumberData type) { - Contract.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleNumberData)] Expected _sWindowsName to be populated already"); + Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleNumberData)] Expected _sWindowsName to be populated already"); switch (type) { @@ -172,7 +173,7 @@ namespace System.Globalization if (!result) { // Failed, just use 0 - Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleNumberData)] failed"); + Debug.Assert(false, "[CultureData.GetLocaleInfo(LocaleNumberData)] failed"); } return value; @@ -181,14 +182,14 @@ namespace System.Globalization [SecuritySafeCritical] private int[] GetLocaleInfo(LocaleGroupingData type) { - Contract.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleGroupingData)] Expected _sWindowsName to be populated already"); + Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleGroupingData)] Expected _sWindowsName to be populated already"); int primaryGroupingSize = 0; int secondaryGroupingSize = 0; bool result = Interop.GlobalizationInterop.GetLocaleInfoGroupingSizes(_sWindowsName, (uint)type, ref primaryGroupingSize, ref secondaryGroupingSize); if (!result) { - Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleGroupingData type)] failed"); + Debug.Assert(false, "[CultureData.GetLocaleInfo(LocaleGroupingData type)] failed"); } if (secondaryGroupingSize == 0) @@ -207,7 +208,7 @@ namespace System.Globalization [SecuritySafeCritical] private string GetTimeFormatString(bool shortFormat) { - Contract.Assert(_sWindowsName != null, "[CultureData.GetTimeFormatString(bool shortFormat)] Expected _sWindowsName to be populated already"); + Debug.Assert(_sWindowsName != null, "[CultureData.GetTimeFormatString(bool shortFormat)] Expected _sWindowsName to be populated already"); StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY); @@ -216,7 +217,7 @@ namespace System.Globalization { // Failed, just use empty string StringBuilderCache.Release(sb); - Contract.Assert(false, "[CultureData.GetTimeFormatString(bool shortFormat)] Failed"); + Debug.Assert(false, "[CultureData.GetTimeFormatString(bool shortFormat)] Failed"); return String.Empty; } diff --git a/src/mscorlib/corefx/System/Globalization/CultureData.Windows.cs b/src/mscorlib/corefx/System/Globalization/CultureData.Windows.cs index 481e1a1..de277e3 100644 --- a/src/mscorlib/corefx/System/Globalization/CultureData.Windows.cs +++ b/src/mscorlib/corefx/System/Globalization/CultureData.Windows.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Text; @@ -158,7 +159,7 @@ namespace System.Globalization private string GetLocaleInfo(LocaleStringData type) { - Contract.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected _sWindowsName to be populated by already"); + Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected _sWindowsName to be populated by already"); return GetLocaleInfo(_sWindowsName, type); } @@ -183,7 +184,7 @@ namespace System.Globalization // Ask OS for data, note that we presume it returns success, so we have to know that // sWindowsName is valid before calling. - Contract.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already"); + Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already"); int result = Interop.mincore.GetLocaleInfoExInt(_sWindowsName, lctype); return result; @@ -203,7 +204,7 @@ namespace System.Globalization private int GetFirstDayOfWeek() { - Contract.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already"); + Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already"); const uint LOCALE_IFIRSTDAYOFWEEK = 0x0000100C; @@ -216,7 +217,7 @@ namespace System.Globalization private String[] GetTimeFormats() { // Note that this gets overrides for us all the time - Contract.Assert(_sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected _sWindowsName to be populated by already"); + Debug.Assert(_sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected _sWindowsName to be populated by already"); String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(_sWindowsName, 0, UseUserOverride)); return result; @@ -225,7 +226,7 @@ namespace System.Globalization private String[] GetShortTimeFormats() { // Note that this gets overrides for us all the time - Contract.Assert(_sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected _sWindowsName to be populated by already"); + Debug.Assert(_sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected _sWindowsName to be populated by already"); String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(_sWindowsName, TIME_NOSECONDS, UseUserOverride)); return result; @@ -235,7 +236,7 @@ namespace System.Globalization // region name match the requested region name private static CultureData GetCultureDataFromRegionName(String regionName) { - Contract.Assert(regionName != null); + Debug.Assert(regionName != null); const uint LOCALE_SUPPLEMENTAL = 0x00000002; const uint LOCALE_SPECIFICDATA = 0x00000020; @@ -283,7 +284,7 @@ namespace System.Globalization private static string GetLocaleInfoFromLCType(string localeName, uint lctype, bool useUserOveride) { - Contract.Assert(localeName != null, "[CultureData.GetLocaleInfoFromLCType] Expected localeName to be not be null"); + Debug.Assert(localeName != null, "[CultureData.GetLocaleInfoFromLCType] Expected localeName to be not be null"); // Fix lctype if we don't want overrides if (!useUserOveride) diff --git a/src/mscorlib/corefx/System/Globalization/CultureData.cs b/src/mscorlib/corefx/System/Globalization/CultureData.cs index 3bc63c8..11fe088 100644 --- a/src/mscorlib/corefx/System/Globalization/CultureData.cs +++ b/src/mscorlib/corefx/System/Globalization/CultureData.cs @@ -9,6 +9,7 @@ using System.Text; using System.Threading; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Globalization @@ -708,7 +709,7 @@ namespace System.Globalization { get { - Contract.Assert(_sRealName != null, "[CultureData.CultureName] Expected _sRealName to be populated by already"); + Debug.Assert(_sRealName != null, "[CultureData.CultureName] Expected _sRealName to be populated by already"); // since windows doesn't know about zh-CHS and zh-CHT, // we leave sRealName == zh-Hanx but we still need to // pretend that it was zh-CHX. @@ -926,7 +927,7 @@ namespace System.Globalization get { // This got populated during the culture initialization - Contract.Assert(_sSpecificCulture != null, "[CultureData.SSPECIFICCULTURE] Expected this.sSpecificCulture to be populated by culture data initialization already"); + Debug.Assert(_sSpecificCulture != null, "[CultureData.SSPECIFICCULTURE] Expected this.sSpecificCulture to be populated by culture data initialization already"); return _sSpecificCulture; } } @@ -1717,7 +1718,7 @@ namespace System.Globalization // We then have to copy that list to a new array of the right size. // Default calendar should be first CalendarId[] calendars = new CalendarId[23]; - Contract.Assert(_sWindowsName != null, "[CultureData.CalendarIds] Expected _sWindowsName to be populated by already"); + Debug.Assert(_sWindowsName != null, "[CultureData.CalendarIds] Expected _sWindowsName to be populated by already"); int count = CalendarData.GetCalendars(_sWindowsName, _bUseOverrides, calendars); // See if we had a calendar to add. @@ -1789,7 +1790,7 @@ namespace System.Globalization internal CalendarData GetCalendar(CalendarId calendarId) { - Contract.Assert(calendarId > 0 && calendarId <= CalendarId.LAST_CALENDAR, + Debug.Assert(calendarId > 0 && calendarId <= CalendarId.LAST_CALENDAR, "[CultureData.GetCalendar] Expect calendarId to be in a valid range"); // arrays are 0 based, calendarIds are 1 based @@ -1808,7 +1809,7 @@ namespace System.Globalization // Make sure that calendar has data if (calendarData == null) { - Contract.Assert(_sWindowsName != null, "[CultureData.GetCalendar] Expected _sWindowsName to be populated by already"); + Debug.Assert(_sWindowsName != null, "[CultureData.GetCalendar] Expected _sWindowsName to be populated by already"); calendarData = new CalendarData(_sWindowsName, calendarId, this.UseUserOverride); _calendars[calendarIndex] = calendarData; } @@ -1848,7 +1849,7 @@ namespace System.Globalization { if (_iReadingLayout == undef) { - Contract.Assert(_sRealName != null, "[CultureData.IsRightToLeft] Expected _sRealName to be populated by already"); + Debug.Assert(_sRealName != null, "[CultureData.IsRightToLeft] Expected _sRealName to be populated by already"); _iReadingLayout = GetLocaleInfo(LocaleNumberData.ReadingLayout); } @@ -1869,7 +1870,7 @@ namespace System.Globalization { // Note: Custom cultures might point at another culture's textinfo, however windows knows how // to redirect it to the desired textinfo culture, so this is OK. - Contract.Assert(_sRealName != null, "[CultureData.STEXTINFO] Expected _sRealName to be populated by already"); + Debug.Assert(_sRealName != null, "[CultureData.STEXTINFO] Expected _sRealName to be populated by already"); return (_sRealName); } } @@ -1879,7 +1880,7 @@ namespace System.Globalization { get { - Contract.Assert(_sRealName != null, "[CultureData.SCOMPAREINFO] Expected _sRealName to be populated by already"); + Debug.Assert(_sRealName != null, "[CultureData.SCOMPAREINFO] Expected _sRealName to be populated by already"); return (_sRealName); } } @@ -1946,7 +1947,7 @@ namespace System.Globalization { if (_iLanguage == 0) { - Contract.Assert(_sRealName != null, "[CultureData.ILANGUAGE] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(_sRealName != null, "[CultureData.ILANGUAGE] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already"); _iLanguage = LocaleNameToLCID(_sRealName); } return _iLanguage; @@ -1989,21 +1990,21 @@ namespace System.Globalization // All of our era names internal String[] EraNames(CalendarId calendarId) { - Contract.Assert(calendarId > 0, "[CultureData.saEraNames] Expected Calendar.ID > 0"); + Debug.Assert(calendarId > 0, "[CultureData.saEraNames] Expected Calendar.ID > 0"); return this.GetCalendar(calendarId).saEraNames; } internal String[] AbbrevEraNames(CalendarId calendarId) { - Contract.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0"); + Debug.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0"); return this.GetCalendar(calendarId).saAbbrevEraNames; } internal String[] AbbreviatedEnglishEraNames(CalendarId calendarId) { - Contract.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0"); + Debug.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0"); return this.GetCalendar(calendarId).saAbbrevEnglishEraNames; } @@ -2163,8 +2164,8 @@ namespace System.Globalization private static int IndexOfTimePart(string format, int startIndex, string timeParts) { - Contract.Assert(startIndex >= 0, "startIndex cannot be negative"); - Contract.Assert(timeParts.IndexOfAny(new char[] { '\'', '\\' }) == -1, "timeParts cannot include quote characters"); + Debug.Assert(startIndex >= 0, "startIndex cannot be negative"); + Debug.Assert(timeParts.IndexOfAny(new char[] { '\'', '\\' }) == -1, "timeParts cannot include quote characters"); bool inQuote = false; for (int i = startIndex; i < format.Length; ++i) { @@ -2226,7 +2227,7 @@ namespace System.Globalization } else { - Contract.Assert(_sWindowsName != null, "[CultureData.GetNFIValues] Expected _sWindowsName to be populated by already"); + Debug.Assert(_sWindowsName != null, "[CultureData.GetNFIValues] Expected _sWindowsName to be populated by already"); // String values nfi.positiveSign = GetLocaleInfo(LocaleStringData.PositiveSign); nfi.negativeSign = GetLocaleInfo(LocaleStringData.NegativeSign); diff --git a/src/mscorlib/corefx/System/Globalization/CultureInfo.cs b/src/mscorlib/corefx/System/Globalization/CultureInfo.cs index ceee47c..dece40f 100644 --- a/src/mscorlib/corefx/System/Globalization/CultureInfo.cs +++ b/src/mscorlib/corefx/System/Globalization/CultureInfo.cs @@ -29,6 +29,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime; using System.Runtime.CompilerServices; @@ -434,7 +435,7 @@ namespace System.Globalization [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { - Contract.Assert(m_name != null, "[CultureInfo.OnDeserialized] m_name != null"); + Debug.Assert(m_name != null, "[CultureInfo.OnDeserialized] m_name != null"); InitializeFromName(m_name, m_useUserOverride); } @@ -486,7 +487,7 @@ namespace System.Globalization Init(); } - Contract.Assert(s_userDefaultCulture != null); + Debug.Assert(s_userDefaultCulture != null); return s_userDefaultCulture; } @@ -534,7 +535,7 @@ namespace System.Globalization Init(); } - Contract.Assert(s_userDefaultCulture != null); + Debug.Assert(s_userDefaultCulture != null); return s_userDefaultCulture; } @@ -566,7 +567,7 @@ namespace System.Globalization { Init(); } - Contract.Assert(s_userDefaultCulture != null, "[CultureInfo.InstalledUICulture] s_userDefaultCulture != null"); + Debug.Assert(s_userDefaultCulture != null, "[CultureInfo.InstalledUICulture] s_userDefaultCulture != null"); return s_userDefaultCulture; } } @@ -765,7 +766,7 @@ namespace System.Globalization get { Contract.Ensures(Contract.Result() != null); - Contract.Assert(m_name != null, "[CultureInfo.DisplayName] Always expect m_name to be set"); + Debug.Assert(m_name != null, "[CultureInfo.DisplayName] Always expect m_name to be set"); return m_cultureData.SLOCALIZEDDISPLAYNAME; } @@ -1108,7 +1109,7 @@ namespace System.Globalization //calendars unless they're required. internal static Calendar GetCalendarInstanceRare(CalendarId calType) { - Contract.Assert(calType != CalendarId.GREGORIAN, "calType!=CalendarId.GREGORIAN"); + Debug.Assert(calType != CalendarId.GREGORIAN, "calType!=CalendarId.GREGORIAN"); switch (calType) { @@ -1152,7 +1153,7 @@ namespace System.Globalization { if (calendar == null) { - Contract.Assert(this.m_cultureData.CalendarIds.Length > 0, "this.m_cultureData.CalendarIds.Length > 0"); + Debug.Assert(this.m_cultureData.CalendarIds.Length > 0, "this.m_cultureData.CalendarIds.Length > 0"); // Get the default calendar for this culture. Note that the value can be // from registry if this is a user default culture. Calendar newObj = this.m_cultureData.DefaultCalendar; diff --git a/src/mscorlib/corefx/System/Globalization/DateTimeFormatInfo.cs b/src/mscorlib/corefx/System/Globalization/DateTimeFormatInfo.cs index 577a95e..31deb4c 100644 --- a/src/mscorlib/corefx/System/Globalization/DateTimeFormatInfo.cs +++ b/src/mscorlib/corefx/System/Globalization/DateTimeFormatInfo.cs @@ -5,6 +5,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.Serialization; @@ -227,7 +228,7 @@ namespace System.Globalization { // Get the abbreviated day names for our current calendar this.abbreviatedDayNames = _cultureData.AbbreviatedDayNames(Calendar.ID); - Contract.Assert(this.abbreviatedDayNames.Length == 7, "[DateTimeFormatInfo.GetAbbreviatedDayOfWeekNames] Expected 7 day names in a week"); + Debug.Assert(this.abbreviatedDayNames.Length == 7, "[DateTimeFormatInfo.GetAbbreviatedDayOfWeekNames] Expected 7 day names in a week"); } return (this.abbreviatedDayNames); } @@ -251,7 +252,7 @@ namespace System.Globalization { // Get the super short day names for our current calendar this.m_superShortDayNames = _cultureData.SuperShortDayNames(Calendar.ID); - Contract.Assert(this.m_superShortDayNames.Length == 7, "[DateTimeFormatInfo.internalGetSuperShortDayNames] Expected 7 day names in a week"); + Debug.Assert(this.m_superShortDayNames.Length == 7, "[DateTimeFormatInfo.internalGetSuperShortDayNames] Expected 7 day names in a week"); } return (this.m_superShortDayNames); } @@ -268,7 +269,7 @@ namespace System.Globalization { // Get the day names for our current calendar this.dayNames = _cultureData.DayNames(Calendar.ID); - Contract.Assert(this.dayNames.Length == 7, "[DateTimeFormatInfo.GetDayOfWeekNames] Expected 7 day names in a week"); + Debug.Assert(this.dayNames.Length == 7, "[DateTimeFormatInfo.GetDayOfWeekNames] Expected 7 day names in a week"); } return (this.dayNames); } @@ -285,7 +286,7 @@ namespace System.Globalization { // Get the month names for our current calendar this.abbreviatedMonthNames = _cultureData.AbbreviatedMonthNames(Calendar.ID); - Contract.Assert(this.abbreviatedMonthNames.Length == 12 || this.abbreviatedMonthNames.Length == 13, + Debug.Assert(this.abbreviatedMonthNames.Length == 12 || this.abbreviatedMonthNames.Length == 13, "[DateTimeFormatInfo.GetAbbreviatedMonthNames] Expected 12 or 13 month names in a year"); } return (this.abbreviatedMonthNames); @@ -304,7 +305,7 @@ namespace System.Globalization { // Get the month names for our current calendar this.monthNames = _cultureData.MonthNames(Calendar.ID); - Contract.Assert(this.monthNames.Length == 12 || this.monthNames.Length == 13, + Debug.Assert(this.monthNames.Length == 12 || this.monthNames.Length == 13, "[DateTimeFormatInfo.GetMonthNames] Expected 12 or 13 month names in a year"); } @@ -335,7 +336,7 @@ namespace System.Globalization private void InitializeOverridableProperties(CultureData cultureData, CalendarId calendarId) { Contract.Requires(cultureData != null); - Contract.Assert(calendarId != CalendarId.UNINITIALIZED_VALUE, "[DateTimeFormatInfo.Populate] Expected initalized calendarId"); + Debug.Assert(calendarId != CalendarId.UNINITIALIZED_VALUE, "[DateTimeFormatInfo.Populate] Expected initalized calendarId"); if (this.firstDayOfWeek == -1) { this.firstDayOfWeek = cultureData.IFIRSTDAYOFWEEK; } if (this.calendarWeekRule == -1) { this.calendarWeekRule = cultureData.IFIRSTWEEKOFYEAR; } @@ -346,19 +347,19 @@ namespace System.Globalization if (this.dateSeparator == null) { this.dateSeparator = cultureData.DateSeparator(calendarId); } this.allLongTimePatterns = _cultureData.LongTimes; - Contract.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long time patterns"); + Debug.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long time patterns"); this.allShortTimePatterns = _cultureData.ShortTimes; - Contract.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short time patterns"); + Debug.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short time patterns"); this.allLongDatePatterns = cultureData.LongDates(calendarId); - Contract.Assert(this.allLongDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long date patterns"); + Debug.Assert(this.allLongDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long date patterns"); this.allShortDatePatterns = cultureData.ShortDates(calendarId); - Contract.Assert(this.allShortDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short date patterns"); + Debug.Assert(this.allShortDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short date patterns"); this.allYearMonthPatterns = cultureData.YearMonths(calendarId); - Contract.Assert(this.allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some year month patterns"); + Debug.Assert(this.allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some year month patterns"); } [OptionalField(VersionAdded = 1)] @@ -526,7 +527,7 @@ namespace System.Globalization { this.amDesignator = _cultureData.SAM1159; } - Contract.Assert(this.amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null"); + Debug.Assert(this.amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null"); return (this.amDesignator); } @@ -552,7 +553,7 @@ namespace System.Globalization { Contract.Ensures(Contract.Result() != null); - Contract.Assert(this.calendar != null, "DateTimeFormatInfo.Calendar: calendar != null"); + Debug.Assert(this.calendar != null, "DateTimeFormatInfo.Calendar: calendar != null"); return (this.calendar); } @@ -799,7 +800,7 @@ namespace System.Globalization { if (this.m_abbrevEnglishEraNames == null) { - Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.AbbreviatedEnglishEraNames] Expected Calendar.ID > 0"); + Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.AbbreviatedEnglishEraNames] Expected Calendar.ID > 0"); this.m_abbrevEnglishEraNames = _cultureData.AbbreviatedEnglishEraNames(Calendar.ID); } return (this.m_abbrevEnglishEraNames); @@ -816,7 +817,7 @@ namespace System.Globalization { dateSeparator = _cultureData.DateSeparator(Calendar.ID); } - Contract.Assert(this.dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null"); + Debug.Assert(this.dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null"); return dateSeparator; } @@ -843,7 +844,7 @@ namespace System.Globalization { this.firstDayOfWeek = _cultureData.IFIRSTDAYOFWEEK; } - Contract.Assert(this.firstDayOfWeek != -1, "DateTimeFormatInfo.FirstDayOfWeek, firstDayOfWeek != -1"); + Debug.Assert(this.firstDayOfWeek != -1, "DateTimeFormatInfo.FirstDayOfWeek, firstDayOfWeek != -1"); return ((DayOfWeek)this.firstDayOfWeek); } @@ -873,7 +874,7 @@ namespace System.Globalization { this.calendarWeekRule = _cultureData.IFIRSTWEEKOFYEAR; } - Contract.Assert(this.calendarWeekRule != -1, "DateTimeFormatInfo.CalendarWeekRule, calendarWeekRule != -1"); + Debug.Assert(this.calendarWeekRule != -1, "DateTimeFormatInfo.CalendarWeekRule, calendarWeekRule != -1"); return ((CalendarWeekRule)this.calendarWeekRule); } @@ -1012,10 +1013,10 @@ namespace System.Globalization { if (this.monthDayPattern == null) { - Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.MonthDayPattern] Expected calID > 0"); + Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.MonthDayPattern] Expected calID > 0"); this.monthDayPattern = _cultureData.MonthDay(Calendar.ID); } - Contract.Assert(this.monthDayPattern != null, "DateTimeFormatInfo.MonthDayPattern, monthDayPattern != null"); + Debug.Assert(this.monthDayPattern != null, "DateTimeFormatInfo.MonthDayPattern, monthDayPattern != null"); return (this.monthDayPattern); } @@ -1044,7 +1045,7 @@ namespace System.Globalization { this.pmDesignator = _cultureData.SPM2359; } - Contract.Assert(this.pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null"); + Debug.Assert(this.pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null"); return (this.pmDesignator); } @@ -1285,7 +1286,7 @@ namespace System.Globalization { timeSeparator = _cultureData.TimeSeparator; } - Contract.Assert(this.timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null"); + Debug.Assert(this.timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null"); return (timeSeparator); } @@ -1587,7 +1588,7 @@ namespace System.Globalization if (this.m_genitiveAbbreviatedMonthNames == null) { this.m_genitiveAbbreviatedMonthNames = _cultureData.AbbreviatedGenitiveMonthNames(this.Calendar.ID); - Contract.Assert(this.m_genitiveAbbreviatedMonthNames.Length == 13, + Debug.Assert(this.m_genitiveAbbreviatedMonthNames.Length == 13, "[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 abbreviated genitive month names in a year"); } return (this.m_genitiveAbbreviatedMonthNames); @@ -1596,7 +1597,7 @@ namespace System.Globalization if (this.genitiveMonthNames == null) { this.genitiveMonthNames = _cultureData.GenitiveMonthNames(this.Calendar.ID); - Contract.Assert(this.genitiveMonthNames.Length == 13, + Debug.Assert(this.genitiveMonthNames.Length == 13, "[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 genitive month names in a year"); } return (this.genitiveMonthNames); @@ -1613,9 +1614,9 @@ namespace System.Globalization { if (this.leapYearMonthNames == null) { - Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expected Calendar.ID > 0"); + Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expected Calendar.ID > 0"); this.leapYearMonthNames = _cultureData.LeapYearMonthNames(Calendar.ID); - Contract.Assert(this.leapYearMonthNames.Length == 13, + Debug.Assert(this.leapYearMonthNames.Length == 13, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expepcted 13 leap year month names"); } return (leapYearMonthNames); @@ -1807,9 +1808,9 @@ namespace System.Globalization // The resulting [] can get returned to the calling app, so clone it. private static string[] GetMergedPatterns(string[] patterns, string defaultPattern) { - Contract.Assert(patterns != null && patterns.Length > 0, + Debug.Assert(patterns != null && patterns.Length > 0, "[DateTimeFormatInfo.GetMergedPatterns]Expected array of at least one pattern"); - Contract.Assert(defaultPattern != null, + Debug.Assert(defaultPattern != null, "[DateTimeFormatInfo.GetMergedPatterns]Expected non null default string"); // If the default happens to be the first in the list just return (a cloned) copy @@ -1910,9 +1911,9 @@ namespace System.Globalization { if (this.allYearMonthPatterns == null) { - Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected Calendar.ID > 0"); + Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected Calendar.ID > 0"); this.allYearMonthPatterns = _cultureData.YearMonths(this.Calendar.ID); - Contract.Assert(this.allYearMonthPatterns.Length > 0, + Debug.Assert(this.allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected some year month patterns"); } @@ -1929,9 +1930,9 @@ namespace System.Globalization { if (allShortDatePatterns == null) { - Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected Calendar.ID > 0"); + Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected Calendar.ID > 0"); this.allShortDatePatterns = _cultureData.ShortDates(this.Calendar.ID); - Contract.Assert(this.allShortDatePatterns.Length > 0, + Debug.Assert(this.allShortDatePatterns.Length > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected some short date patterns"); } @@ -1947,9 +1948,9 @@ namespace System.Globalization { if (allLongDatePatterns == null) { - Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected Calendar.ID > 0"); + Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected Calendar.ID > 0"); this.allLongDatePatterns = _cultureData.LongDates(this.Calendar.ID); - Contract.Assert(this.allLongDatePatterns.Length > 0, + Debug.Assert(this.allLongDatePatterns.Length > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected some long date patterns"); } @@ -1966,7 +1967,7 @@ namespace System.Globalization if (this.allShortTimePatterns == null) { this.allShortTimePatterns = _cultureData.ShortTimes; - Contract.Assert(this.allShortTimePatterns.Length > 0, + Debug.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.UnclonedShortTimePatterns] Expected some short time patterns"); } @@ -1983,7 +1984,7 @@ namespace System.Globalization if (this.allLongTimePatterns == null) { this.allLongTimePatterns = _cultureData.LongTimes; - Contract.Assert(this.allLongTimePatterns.Length > 0, + Debug.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.UnclonedLongTimePatterns] Expected some long time patterns"); } @@ -2767,7 +2768,7 @@ namespace System.Globalization } while (i < str.Value.Length && (state != HebrewNumberParsingState.FoundEndOfHebrewNumber)); // When we are here, we are either at the end of the string, or we find a valid Hebrew number. - Contract.Assert(state == HebrewNumberParsingState.ContinueParsing || state == HebrewNumberParsingState.FoundEndOfHebrewNumber, + Debug.Assert(state == HebrewNumberParsingState.ContinueParsing || state == HebrewNumberParsingState.FoundEndOfHebrewNumber, "Invalid returned state from HebrewNumber.ParseByChar()"); if (state != HebrewNumberParsingState.FoundEndOfHebrewNumber) @@ -2802,7 +2803,7 @@ namespace System.Globalization tokenValue = 0; TokenHashValue value; - Contract.Assert(str.Index < str.Value.Length, "DateTimeFormatInfo.Tokenize(): start < value.Length"); + Debug.Assert(str.Index < str.Value.Length, "DateTimeFormatInfo.Tokenize(): start < value.Length"); char ch = str.m_current; bool isLetter = Char.IsLetter(ch); @@ -2925,7 +2926,7 @@ namespace System.Globalization } previousNode = temp; }; - Contract.Assert(false, "The hashtable is full. This should not happen."); + Debug.Assert(false, "The hashtable is full. This should not happen."); } private void InsertHash(TokenHashValue[] hashTable, String str, TokenType tokenType, int tokenValue) @@ -3013,7 +3014,7 @@ namespace System.Globalization hashcode += hashProbe; if (hashcode >= TOKEN_HASH_SIZE) hashcode -= TOKEN_HASH_SIZE; } while (i < TOKEN_HASH_SIZE); - Contract.Assert(false, "The hashtable is full. This should not happen."); + Debug.Assert(false, "The hashtable is full. This should not happen."); } private bool CompareStringIgnoreCaseOptimized(string string1, int offset1, int length1, string string2, int offset2, int length2) diff --git a/src/mscorlib/corefx/System/Globalization/HebrewCalendar.cs b/src/mscorlib/corefx/System/Globalization/HebrewCalendar.cs index c43cd78..1c7f85e 100644 --- a/src/mscorlib/corefx/System/Globalization/HebrewCalendar.cs +++ b/src/mscorlib/corefx/System/Globalization/HebrewCalendar.cs @@ -4,6 +4,7 @@ using System; using System.Text; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Globalization @@ -603,7 +604,7 @@ namespace System.Globalization // is true. // NumDays -= (long)(s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + lunarDate.month] - lunarDate.day); - Contract.Assert(NumDays >= 1, "NumDays >= 1"); + Debug.Assert(NumDays >= 1, "NumDays >= 1"); // If NumDays is 1, then we are done. Otherwise, find the correct Hebrew month // and day. @@ -827,7 +828,7 @@ namespace System.Globalization int hebrewYearType = GetHebrewYearType(year, era); CheckHebrewMonthValue(year, month, era); - Contract.Assert(hebrewYearType >= 1 && hebrewYearType <= 6, + Debug.Assert(hebrewYearType >= 1 && hebrewYearType <= 6, "hebrewYearType should be from 1 to 6, but now hebrewYearType = " + hebrewYearType + " for hebrew year " + year); int monthDays = s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + month]; if (monthDays == 0) diff --git a/src/mscorlib/corefx/System/Globalization/HebrewNumber.cs b/src/mscorlib/corefx/System/Globalization/HebrewNumber.cs index 8fc264b..66996d9 100644 --- a/src/mscorlib/corefx/System/Globalization/HebrewNumber.cs +++ b/src/mscorlib/corefx/System/Globalization/HebrewNumber.cs @@ -110,7 +110,7 @@ namespace System.Globalization Number -= 5000; } - Contract.Assert(Number > 0 && Number <= 999, "Number is out of range."); ; + Debug.Assert(Number > 0 && Number <= 999, "Number is out of range."); ; // // Get the Hundreds. diff --git a/src/mscorlib/corefx/System/Globalization/LocaleData.Unix.cs b/src/mscorlib/corefx/System/Globalization/LocaleData.Unix.cs index 690a461..d4c58d8 100644 --- a/src/mscorlib/corefx/System/Globalization/LocaleData.Unix.cs +++ b/src/mscorlib/corefx/System/Globalization/LocaleData.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Diagnostics; using System.Diagnostics.Contracts; // This file contains the handling of Windows OS specific culture features. @@ -4424,7 +4425,7 @@ namespace System.Globalization int right = s_lcids.Length - 1; int index; - Contract.Assert(s_lcids.Length == s_lcidToCultureNameIndices.Length); + Debug.Assert(s_lcids.Length == s_lcidToCultureNameIndices.Length); while (left <= right) { @@ -4433,7 +4434,7 @@ namespace System.Globalization if (culture == s_lcids[index]) { int indexToLocaleNamesIndices = s_lcidToCultureNameIndices[index]; - Contract.Assert(indexToLocaleNamesIndices < s_localeNamesIndices.Length - 1); + Debug.Assert(indexToLocaleNamesIndices < s_localeNamesIndices.Length - 1); return c_localeNames.Substring(s_localeNamesIndices[indexToLocaleNamesIndices], s_localeNamesIndices[indexToLocaleNamesIndices + 1] - @@ -4460,7 +4461,7 @@ namespace System.Globalization return -1; } - Contract.Assert((s_localeNamesIndices.Length-1 == (s_nameIndexToNumericData.Length/NUMERIC_LOCALE_DATA_COUNT_PER_ROW)) && + Debug.Assert((s_localeNamesIndices.Length-1 == (s_nameIndexToNumericData.Length/NUMERIC_LOCALE_DATA_COUNT_PER_ROW)) && index < s_localeNamesIndices.Length); return s_nameIndexToNumericData[index * NUMERIC_LOCALE_DATA_COUNT_PER_ROW + (int) part]; @@ -4474,7 +4475,7 @@ namespace System.Globalization return null; } - Contract.Assert(s_localeNamesIndices.Length-1 == (c_threeLetterWindowsLanguageName.Length / 3)); + Debug.Assert(s_localeNamesIndices.Length-1 == (c_threeLetterWindowsLanguageName.Length / 3)); return c_threeLetterWindowsLanguageName.Substring(index * 3, 3); } @@ -4486,7 +4487,7 @@ namespace System.Globalization return ""; // fallback to invariant } - Contract.Assert(indexToIndicesTable < s_localeNamesIndices.Length-1); + Debug.Assert(indexToIndicesTable < s_localeNamesIndices.Length-1); return c_localeNames.Substring(s_localeNamesIndices[indexToIndicesTable], s_localeNamesIndices[indexToIndicesTable+1] - s_localeNamesIndices[indexToIndicesTable]); @@ -4511,7 +4512,7 @@ namespace System.Globalization int index; int result; - Contract.Assert(s_localeNamesIndices[s_localeNamesIndices.Length - 1] == c_localeNames.Length); + Debug.Assert(s_localeNamesIndices[s_localeNamesIndices.Length - 1] == c_localeNames.Length); name = CultureData.AnsiToLower(name); @@ -4521,7 +4522,7 @@ namespace System.Globalization { index = ((right - left) / 2) + left; - Contract.Assert(index < s_localeNamesIndices.Length - 1); + Debug.Assert(index < s_localeNamesIndices.Length - 1); result = CompareOrdinal(name, c_localeNames, s_localeNamesIndices[index], s_localeNamesIndices[index + 1] - s_localeNamesIndices[index]); if (result == 0) { @@ -4540,7 +4541,7 @@ namespace System.Globalization // Walk the remaining elements (it'll be 3 or fewer). for (; left <= right; left++) { - Contract.Assert(left < s_localeNamesIndices.Length - 1); + Debug.Assert(left < s_localeNamesIndices.Length - 1); if (CompareOrdinal(name, c_localeNames, s_localeNamesIndices[left], s_localeNamesIndices[left + 1] - s_localeNamesIndices[left]) == 0) { return (left); diff --git a/src/mscorlib/corefx/System/Globalization/PersianCalendar.cs b/src/mscorlib/corefx/System/Globalization/PersianCalendar.cs index 30269a0..c735204 100644 --- a/src/mscorlib/corefx/System/Globalization/PersianCalendar.cs +++ b/src/mscorlib/corefx/System/Globalization/PersianCalendar.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Globalization @@ -180,7 +181,7 @@ namespace System.Globalization private static int MonthFromOrdinalDay(int ordinalDay) { - Contract.Assert(ordinalDay <= 366); + Debug.Assert(ordinalDay <= 366); int index = 0; while (ordinalDay > DaysToMonth[index]) index++; @@ -190,7 +191,7 @@ namespace System.Globalization private static int DaysInPreviousMonths(int month) { - Contract.Assert(1 <= month && month <= 12); + Debug.Assert(1 <= month && month <= 12); --month; // months are one based but for calculations use 0 based return DaysToMonth[month]; } @@ -221,7 +222,7 @@ namespace System.Globalization long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(NumDays); int y = (int)(Math.Floor(((yearStart - PersianEpoch) / CalendricalCalculationsHelper.MeanTropicalYearInDays) + 0.5)) + 1; - Contract.Assert(y >= 1); + Debug.Assert(y >= 1); if (part == DatePartYear) { @@ -240,16 +241,16 @@ namespace System.Globalization } int m = MonthFromOrdinalDay(ordinalDay); - Contract.Assert(ordinalDay >= 1); - Contract.Assert(m >= 1 && m <= 12); + Debug.Assert(ordinalDay >= 1); + Debug.Assert(m >= 1 && m <= 12); if (part == DatePartMonth) { return m; } int d = ordinalDay - DaysInPreviousMonths(m); - Contract.Assert(1 <= d); - Contract.Assert(d <= 31); + Debug.Assert(1 <= d); + Debug.Assert(d <= 31); // // Calculate the Persian Day. @@ -385,7 +386,7 @@ namespace System.Globalization int daysInMonth = DaysToMonth[month] - DaysToMonth[month - 1]; if ((month == MonthsPerYear) && !IsLeapYear(year)) { - Contract.Assert(daysInMonth == 30); + Debug.Assert(daysInMonth == 30); --daysInMonth; } return daysInMonth; diff --git a/src/mscorlib/corefx/System/Globalization/RegionInfo.cs b/src/mscorlib/corefx/System/Globalization/RegionInfo.cs index 5e33294..e09db6f 100644 --- a/src/mscorlib/corefx/System/Globalization/RegionInfo.cs +++ b/src/mscorlib/corefx/System/Globalization/RegionInfo.cs @@ -15,6 +15,7 @@ //////////////////////////////////////////////////////////////////////////// using System; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.Serialization; @@ -185,7 +186,7 @@ namespace System.Globalization { get { - Contract.Assert(_name != null, "Expected RegionInfo._name to be populated already"); + Debug.Assert(_name != null, "Expected RegionInfo._name to be populated already"); return (_name); } } diff --git a/src/mscorlib/corefx/System/Globalization/SortKey.cs b/src/mscorlib/corefx/System/Globalization/SortKey.cs index ccb1e8f..fc151fa 100644 --- a/src/mscorlib/corefx/System/Globalization/SortKey.cs +++ b/src/mscorlib/corefx/System/Globalization/SortKey.cs @@ -16,6 +16,7 @@ namespace System.Globalization { using System; using System.Runtime.CompilerServices; using System.Runtime.Serialization; + using System.Diagnostics; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] @@ -125,8 +126,8 @@ namespace System.Globalization { byte[] key1Data = sortkey1._keyData; byte[] key2Data = sortkey2._keyData; - Contract.Assert(key1Data != null, "key1Data != null"); - Contract.Assert(key2Data != null, "key2Data != null"); + Debug.Assert(key1Data != null, "key1Data != null"); + Debug.Assert(key2Data != null, "key2Data != null"); if (key1Data.Length == 0) { diff --git a/src/mscorlib/corefx/System/Globalization/StringInfo.cs b/src/mscorlib/corefx/System/Globalization/StringInfo.cs index 1acef44..b2ded9f 100644 --- a/src/mscorlib/corefx/System/Globalization/StringInfo.cs +++ b/src/mscorlib/corefx/System/Globalization/StringInfo.cs @@ -13,6 +13,7 @@ //////////////////////////////////////////////////////////////////////////// using System; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.Serialization; @@ -213,8 +214,8 @@ namespace System.Globalization internal static int GetCurrentTextElementLen(string str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount) { - Contract.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); - Contract.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); + Debug.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); + Debug.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); if (index + currentCharCount == len) { // This is the last character/surrogate in the string. diff --git a/src/mscorlib/corefx/System/Globalization/TextElementEnumerator.cs b/src/mscorlib/corefx/System/Globalization/TextElementEnumerator.cs index 487ef11..0cc397f 100644 --- a/src/mscorlib/corefx/System/Globalization/TextElementEnumerator.cs +++ b/src/mscorlib/corefx/System/Globalization/TextElementEnumerator.cs @@ -11,6 +11,7 @@ //////////////////////////////////////////////////////////////////////////// using System.Collections; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.Serialization; @@ -42,9 +43,9 @@ namespace System.Globalization internal TextElementEnumerator(String str, int startIndex, int strLen) { - Contract.Assert(str != null, "TextElementEnumerator(): str != null"); - Contract.Assert(startIndex >= 0 && strLen >= 0, "TextElementEnumerator(): startIndex >= 0 && strLen >= 0"); - Contract.Assert(strLen >= startIndex, "TextElementEnumerator(): strLen >= startIndex"); + Debug.Assert(str != null, "TextElementEnumerator(): str != null"); + Debug.Assert(startIndex >= 0 && strLen >= 0, "TextElementEnumerator(): startIndex >= 0 && strLen >= 0"); + Debug.Assert(strLen >= startIndex, "TextElementEnumerator(): strLen >= startIndex"); _str = str; _startIndex = startIndex; _strLen = strLen; diff --git a/src/mscorlib/corefx/System/Globalization/TextInfo.Unix.cs b/src/mscorlib/corefx/System/Globalization/TextInfo.Unix.cs index 8490057..3d9b777 100644 --- a/src/mscorlib/corefx/System/Globalization/TextInfo.Unix.cs +++ b/src/mscorlib/corefx/System/Globalization/TextInfo.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; using System.Text; @@ -35,7 +36,7 @@ namespace System.Globalization [SecuritySafeCritical] private unsafe string ChangeCase(string s, bool toUpper) { - Contract.Assert(s != null); + Debug.Assert(s != null); if (s.Length == 0) { @@ -93,7 +94,7 @@ namespace System.Globalization private bool NeedsTurkishCasing(string localeName) { - Contract.Assert(localeName != null); + Debug.Assert(localeName != null); return CultureInfo.GetCultureInfo(localeName).CompareInfo.Compare("\u0131", "I", CompareOptions.IgnoreCase) == 0; } diff --git a/src/mscorlib/corefx/System/Globalization/TextInfo.Windows.cs b/src/mscorlib/corefx/System/Globalization/TextInfo.Windows.cs index 238c512..07dbcc1 100644 --- a/src/mscorlib/corefx/System/Globalization/TextInfo.Windows.cs +++ b/src/mscorlib/corefx/System/Globalization/TextInfo.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Globalization @@ -35,7 +36,7 @@ namespace System.Globalization private unsafe string ChangeCase(string s, bool toUpper) { - Contract.Assert(s != null); + Debug.Assert(s != null); // // Get the length of the string. @@ -80,7 +81,7 @@ namespace System.Globalization throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - Contract.Assert(ret == nLengthInput, "Expected getting the same length of the original string"); + Debug.Assert(ret == nLengthInput, "Expected getting the same length of the original string"); return result; } } diff --git a/src/mscorlib/corefx/System/Globalization/TextInfo.cs b/src/mscorlib/corefx/System/Globalization/TextInfo.cs index 44c0759..bcb8cd6 100644 --- a/src/mscorlib/corefx/System/Globalization/TextInfo.cs +++ b/src/mscorlib/corefx/System/Globalization/TextInfo.cs @@ -13,6 +13,7 @@ //////////////////////////////////////////////////////////////////////////// using System; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime; using System.Runtime.CompilerServices; @@ -582,7 +583,7 @@ namespace System.Globalization private static int AddNonLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen) { - Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!"); + Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!"); if (charLen == 2) { // Surrogate pair @@ -598,7 +599,7 @@ namespace System.Globalization private int AddTitlecaseLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen) { - Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!"); + Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!"); // for surrogate pairs do a simple ToUpper operation on the substring if (charLen == 2) @@ -735,7 +736,7 @@ namespace System.Globalization private unsafe int GetCaseInsensitiveHashCodeSlow(String str) { - Contract.Assert(str != null); + Debug.Assert(str != null); string upper = ToUpper(str); diff --git a/src/mscorlib/corefx/System/Globalization/UmAlQuraCalendar.cs b/src/mscorlib/corefx/System/Globalization/UmAlQuraCalendar.cs index 3ab516e..01974ad 100644 --- a/src/mscorlib/corefx/System/Globalization/UmAlQuraCalendar.cs +++ b/src/mscorlib/corefx/System/Globalization/UmAlQuraCalendar.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Globalization @@ -317,9 +318,9 @@ namespace System.Globalization =========================ConvertHijriToGregorian============================*/ private static void ConvertHijriToGregorian(int HijriYear, int HijriMonth, int HijriDay, ref int yg, ref int mg, ref int dg) { - Contract.Assert((HijriYear >= MinCalendarYear) && (HijriYear <= MaxCalendarYear), "Hijri year is out of range."); - Contract.Assert(HijriMonth >= 1, "Hijri month is out of range."); - Contract.Assert(HijriDay >= 1, "Hijri day is out of range."); + Debug.Assert((HijriYear >= MinCalendarYear) && (HijriYear <= MaxCalendarYear), "Hijri year is out of range."); + Debug.Assert(HijriMonth >= 1, "Hijri month is out of range."); + Debug.Assert(HijriDay >= 1, "Hijri day is out of range."); int index, b, nDays = HijriDay - 1; DateTime dt; @@ -417,7 +418,7 @@ namespace System.Globalization TimeSpan ts; int yh1 = 0, mh1 = 0, dh1 = 0; - Contract.Assert((time.Ticks >= minDate.Ticks) && (time.Ticks <= maxDate.Ticks), "Gregorian date is out of range."); + Debug.Assert((time.Ticks >= minDate.Ticks) && (time.Ticks <= maxDate.Ticks), "Gregorian date is out of range."); // Find the index where we should start our search by quessing the Hijri year that we will be in HijriYearInfo. // A Hijri year is 354 or 355 days. Use 355 days so that we will search from a lower index. @@ -630,7 +631,7 @@ namespace System.Globalization { int days = 0, b; - Contract.Assert((year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range."); + Debug.Assert((year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range."); b = s_hijriYearInfo[year - MinCalendarYear].HijriMonthsLengthFlags; @@ -639,7 +640,7 @@ namespace System.Globalization days = days + 29 + (b & 1); /* Add the months lengths before mh */ b = b >> 1; } - Contract.Assert((days == 354) || (days == 355), "Hijri year has to be 354 or 355 days."); + Debug.Assert((days == 354) || (days == 355), "Hijri year has to be 354 or 355 days."); return days; } diff --git a/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs b/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs index 89fc670..1ff2ff1 100644 --- a/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs +++ b/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; @@ -22,7 +23,7 @@ namespace Internal.Runtime.Augments private Thread AsThread() { - Contract.Assert(this is Thread); + Debug.Assert(this is Thread); return (Thread)this; } @@ -103,7 +104,7 @@ namespace Internal.Runtime.Augments #if FEATURE_COMINTEROP_APARTMENT_SUPPORT return (ApartmentState)GetApartmentStateNative(); #else // !FEATURE_COMINTEROP_APARTMENT_SUPPORT - Contract.Assert(false); // the Thread class in CoreFX should have handled this case + Debug.Assert(false); // the Thread class in CoreFX should have handled this case return ApartmentState.MTA; #endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT } @@ -118,7 +119,7 @@ namespace Internal.Runtime.Augments #if FEATURE_COMINTEROP_APARTMENT_SUPPORT return SetApartmentStateHelper(state, false); #else // !FEATURE_COMINTEROP_APARTMENT_SUPPORT - Contract.Assert(false); // the Thread class in CoreFX should have handled this case + Debug.Assert(false); // the Thread class in CoreFX should have handled this case return false; #endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT } @@ -156,7 +157,7 @@ namespace Internal.Runtime.Augments [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public void DisableComObjectEagerCleanup() { - Contract.Assert(false); // the Thread class in CoreFX should have handled this case + Debug.Assert(false); // the Thread class in CoreFX should have handled this case } #endif // FEATURE_COMINTEROP diff --git a/src/mscorlib/src/System/AppDomain.cs b/src/mscorlib/src/System/AppDomain.cs index 0ad755f..fe524c4 100644 --- a/src/mscorlib/src/System/AppDomain.cs +++ b/src/mscorlib/src/System/AppDomain.cs @@ -35,6 +35,7 @@ namespace System using System.Text; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; #if FEATURE_EXCEPTION_NOTIFICATIONS using System.Runtime.ExceptionServices; @@ -319,7 +320,7 @@ namespace System if (s_flags == 0) s_flags = nGetAppXFlags(); - Contract.Assert(s_flags != 0); + Debug.Assert(s_flags != 0); return s_flags; } } @@ -394,7 +395,7 @@ namespace System /// private void CreateAppDomainManager() { - Contract.Assert(_domainManager == null, "_domainManager == null"); + Debug.Assert(_domainManager == null, "_domainManager == null"); AppDomainSetup adSetup = FusionStore; #if FEATURE_VERSIONING @@ -498,7 +499,7 @@ namespace System // for perf, we don't intialize the _compatFlags dictionary when we don't need to. However, we do need to make a // note that we've run this method, because IsCompatibilityFlagsSet needs to return different values for the // case where the compat flags have been setup. - Contract.Assert(!_compatFlagsInitialized); + Debug.Assert(!_compatFlagsInitialized); _compatFlagsInitialized = true; CompatibilitySwitches.InitializeSwitches(); @@ -522,7 +523,7 @@ namespace System TargetFrameworkAttribute[] attrs = (TargetFrameworkAttribute[])assembly.GetCustomAttributes(typeof(TargetFrameworkAttribute)); if (attrs != null && attrs.Length > 0) { - Contract.Assert(attrs.Length == 1); + Debug.Assert(attrs.Length == 1); targetFrameworkName = attrs[0].FrameworkName; _FusionStore.TargetFrameworkName = targetFrameworkName; } @@ -690,8 +691,8 @@ namespace System /// private void SetAppDomainManagerType(string assembly, string type) { - Contract.Assert(assembly != null, "assembly != null"); - Contract.Assert(type != null, "type != null"); + Debug.Assert(assembly != null, "assembly != null"); + Debug.Assert(type != null, "type != null"); SetAppDomainManagerType(GetNativeHandle(), assembly, type); } @@ -1714,7 +1715,7 @@ namespace System case (int) AppDomainSetup.LoaderInformation.ApplicationNameValue: return FusionStore.ApplicationName; default: - Contract.Assert(false, "Need to handle new LoaderInformation value in AppDomain.GetData()"); + Debug.Assert(false, "Need to handle new LoaderInformation value in AppDomain.GetData()"); return null; } } @@ -1967,7 +1968,7 @@ namespace System internal AppDomainSetup FusionStore { get { - Contract.Assert(_FusionStore != null, + Debug.Assert(_FusionStore != null, "Fusion store has not been correctly setup in this domain"); return _FusionStore; } @@ -2315,7 +2316,7 @@ namespace System private void SetupLoaderOptimization(LoaderOptimization policy) { if(policy != LoaderOptimization.NotSpecified) { - Contract.Assert(FusionStore.LoaderOptimization == LoaderOptimization.NotSpecified, + Debug.Assert(FusionStore.LoaderOptimization == LoaderOptimization.NotSpecified, "It is illegal to change the Loader optimization on a domain"); FusionStore.LoaderOptimization = policy; diff --git a/src/mscorlib/src/System/AppDomainSetup.cs b/src/mscorlib/src/System/AppDomainSetup.cs index 2fa0159..fc8a64c 100644 --- a/src/mscorlib/src/System/AppDomainSetup.cs +++ b/src/mscorlib/src/System/AppDomainSetup.cs @@ -21,6 +21,7 @@ namespace System using System.Security; using System.Security.Policy; using Path = System.IO.Path; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Collections.Generic; @@ -970,7 +971,7 @@ namespace System if(String.IsNullOrEmpty(s)) return -1; - Contract.Assert('A' == ACTAG_APP_BASE_URL[0] , "Assumption violated"); + Debug.Assert('A' == ACTAG_APP_BASE_URL[0] , "Assumption violated"); if (s[0]=='A' && s == ACTAG_APP_BASE_URL) return (int)LoaderInformation.ApplicationBaseValue; diff --git a/src/mscorlib/src/System/Array.cs b/src/mscorlib/src/System/Array.cs index a18468c..7bb6ebb 100644 --- a/src/mscorlib/src/System/Array.cs +++ b/src/mscorlib/src/System/Array.cs @@ -19,6 +19,7 @@ namespace System { using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Security; + using System.Diagnostics; using System.Security.Permissions; using System.Diagnostics.Contracts; @@ -567,7 +568,7 @@ namespace System { private static int GetMedian(int low, int hi) { // Note both may be negative, if we are dealing with arrays w/ negative lower bounds. Contract.Requires(low <= hi); - Contract.Assert( hi - low >= 0, "Length overflow!"); + Debug.Assert( hi - low >= 0, "Length overflow!"); return low + ((hi - low) >> 1); } @@ -2320,7 +2321,7 @@ namespace System { private int _endIndex; // cache array length, since it's a little slow. internal SZArrayEnumerator(Array array) { - Contract.Assert(array.Rank == 1 && array.GetLowerBound(0) == 0, "SZArrayEnumerator only works on single dimension arrays w/ a lower bound of zero."); + Debug.Assert(array.Rank == 1 && array.GetLowerBound(0) == 0, "SZArrayEnumerator only works on single dimension arrays w/ a lower bound of zero."); _array = array; _index = -1; _endIndex = array.Length; @@ -2478,7 +2479,7 @@ namespace System { sealed class SZArrayHelper { // It is never legal to instantiate this class. private SZArrayHelper() { - Contract.Assert(false, "Hey! How'd I get here?"); + Debug.Assert(false, "Hey! How'd I get here?"); } // ----------------------------------------------------------- @@ -2594,7 +2595,7 @@ namespace System { internal SZGenericArrayEnumerator(T[] array, int endIndex) { // We allow passing null array in case of empty enumerator. - Contract.Assert(array != null || endIndex == -1, "endIndex should be -1 in the case of a null array (for the empty enumerator)."); + Debug.Assert(array != null || endIndex == -1, "endIndex should be -1 in the case of a null array (for the empty enumerator)."); _array = array; _index = -1; _endIndex = endIndex; diff --git a/src/mscorlib/src/System/ArraySegment.cs b/src/mscorlib/src/System/ArraySegment.cs index 676452a..b767e7b 100644 --- a/src/mscorlib/src/System/ArraySegment.cs +++ b/src/mscorlib/src/System/ArraySegment.cs @@ -16,6 +16,7 @@ using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System @@ -64,7 +65,7 @@ namespace System { get { - Contract.Assert( (null == _array && 0 == _offset && 0 == _count) + Debug.Assert( (null == _array && 0 == _offset && 0 == _count) || (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length), "ArraySegment is invalid"); @@ -83,7 +84,7 @@ namespace System // after reading each field out of an ArraySegment into their stack. Contract.Ensures(Contract.Result() >= 0); - Contract.Assert( (null == _array && 0 == _offset && 0 == _count) + Debug.Assert( (null == _array && 0 == _offset && 0 == _count) || (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length), "ArraySegment is invalid"); @@ -102,7 +103,7 @@ namespace System // after reading each field out of an ArraySegment into their stack. Contract.Ensures(Contract.Result() >= 0); - Contract.Assert( (null == _array && 0 == _offset && 0 == _count) + Debug.Assert( (null == _array && 0 == _offset && 0 == _count) || (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length), "ArraySegment is invalid"); @@ -193,7 +194,7 @@ namespace System int index = System.Array.IndexOf(_array, item, _offset, _count); - Contract.Assert(index == -1 || + Debug.Assert(index == -1 || (index >= _offset && index < _offset + _count)); return index >= 0 ? index - _offset : -1; @@ -255,7 +256,7 @@ namespace System int index = System.Array.IndexOf(_array, item, _offset, _count); - Contract.Assert(index == -1 || + Debug.Assert(index == -1 || (index >= _offset && index < _offset + _count)); return index >= 0; diff --git a/src/mscorlib/src/System/Attribute.cs b/src/mscorlib/src/System/Attribute.cs index 713369f..e77450e 100644 --- a/src/mscorlib/src/System/Attribute.cs +++ b/src/mscorlib/src/System/Attribute.cs @@ -10,6 +10,7 @@ namespace System { using System.Collections.Generic; using System.Runtime.InteropServices; using System.Globalization; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; using System.Security.Permissions; @@ -636,7 +637,7 @@ namespace System { return element.IsDefined(attributeType, false); default: - Contract.Assert(false, "Invalid type for ParameterInfo member in Attribute class"); + Debug.Assert(false, "Invalid type for ParameterInfo member in Attribute class"); throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParamInfo")); } } @@ -889,7 +890,7 @@ namespace System { // Attributes can only contain single-dimension arrays, so we don't need to worry about // multidimensional arrays. - Contract.Assert(thisValueArray.Rank == 1 && thatValueArray.Rank == 1); + Debug.Assert(thisValueArray.Rank == 1 && thatValueArray.Rank == 1); for (int j = 0; j < thisValueArray.Length; j++) { if (!AreFieldValuesEqual(thisValueArray.GetValue(j), thatValueArray.GetValue(j))) @@ -903,7 +904,7 @@ namespace System { // An object of type Attribute will cause a stack overflow. // However, this should never happen because custom attributes cannot contain values other than // constants, single-dimensional arrays and typeof expressions. - Contract.Assert(!(thisValue is Attribute)); + Debug.Assert(!(thisValue is Attribute)); if (!thisValue.Equals(thatValue)) return false; } diff --git a/src/mscorlib/src/System/BitConverter.cs b/src/mscorlib/src/System/BitConverter.cs index 6fbec2a..3a6d1c0 100644 --- a/src/mscorlib/src/System/BitConverter.cs +++ b/src/mscorlib/src/System/BitConverter.cs @@ -15,6 +15,7 @@ namespace System { using System; using System.Runtime.CompilerServices; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; @@ -337,7 +338,7 @@ namespace System { } private static char GetHexValue(int i) { - Contract.Assert( i >=0 && i <16, "i is out of range."); + Debug.Assert( i >=0 && i <16, "i is out of range."); if (i<10) { return (char)(i + '0'); } diff --git a/src/mscorlib/src/System/Buffer.cs b/src/mscorlib/src/System/Buffer.cs index 4821ba6..eee2a81 100644 --- a/src/mscorlib/src/System/Buffer.cs +++ b/src/mscorlib/src/System/Buffer.cs @@ -11,6 +11,7 @@ namespace System { using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; using System.Runtime; @@ -47,7 +48,7 @@ namespace System { // internal unsafe static int IndexOfByte(byte* src, byte value, int index, int count) { - Contract.Assert(src != null, "src should not be null"); + Debug.Assert(src != null, "src should not be null"); byte* pByte = src + index; @@ -206,8 +207,8 @@ namespace System { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal unsafe static void Memcpy(byte[] dest, int destIndex, byte* src, int srcIndex, int len) { - Contract.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!"); - Contract.Assert(dest.Length - destIndex >= len, "not enough bytes in dest"); + Debug.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!"); + Debug.Assert(dest.Length - destIndex >= len, "not enough bytes in dest"); // If dest has 0 elements, the fixed statement will throw an // IndexOutOfRangeException. Special-case 0-byte copies. if (len==0) @@ -220,8 +221,8 @@ namespace System { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal unsafe static void Memcpy(byte* pDest, int destIndex, byte[] src, int srcIndex, int len) { - Contract.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!"); - Contract.Assert(src.Length - srcIndex >= len, "not enough bytes in src"); + Debug.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!"); + Debug.Assert(src.Length - srcIndex >= len, "not enough bytes in src"); // If dest has 0 elements, the fixed statement will throw an // IndexOutOfRangeException. Special-case 0-byte copies. if (len==0) @@ -248,7 +249,7 @@ namespace System { #else // ARM [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] internal unsafe static void Memcpy(byte* dest, byte* src, int len) { - Contract.Assert(len >= 0, "Negative length in memcopy!"); + Debug.Assert(len >= 0, "Negative length in memcopy!"); Memmove(dest, src, (uint)len); } #endif // ARM @@ -509,7 +510,7 @@ namespace System { // We know due to the above switch-case that this loop will always run 1 iteration; max // bytes we copy before checking is 23 (7 to align the pointers, 16 for 1 iteration) so // the switch handles lengths 0-22. - Contract.Assert(end >= 7 && i <= end); + Debug.Assert(end >= 7 && i <= end); // This is separated out into a different variable, so the i + 16 addition can be // performed at the start of the pipeline and the loop condition does not have diff --git a/src/mscorlib/src/System/Char.cs b/src/mscorlib/src/System/Char.cs index b571fa8..b9c9305 100644 --- a/src/mscorlib/src/System/Char.cs +++ b/src/mscorlib/src/System/Char.cs @@ -18,6 +18,7 @@ namespace System { using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; + using System.Diagnostics; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] @@ -86,7 +87,7 @@ namespace System { // Return the Unicode category for Unicode character <= 0x00ff. private static UnicodeCategory GetLatin1UnicodeCategory(char ch) { - Contract.Assert(IsLatin1(ch), "Char.GetLatin1UnicodeCategory(): ch should be <= 007f"); + Debug.Assert(IsLatin1(ch), "Char.GetLatin1UnicodeCategory(): ch should be <= 007f"); return (UnicodeCategory)(categoryForLatin1[(int)ch]); } diff --git a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs index 0eb2546..6f46589 100644 --- a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs +++ b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs @@ -1905,7 +1905,7 @@ namespace System.Collections.Concurrent [Conditional("DEBUG")] private void Assert(bool condition) { - Contract.Assert(condition); + Debug.Assert(condition); } /// diff --git a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs index d815ae9..4069a6b 100644 --- a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs +++ b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs @@ -77,7 +77,7 @@ namespace System.Collections.Concurrent int index = 0; foreach (T element in collection) { - Contract.Assert(index >= 0 && index < SEGMENT_SIZE); + Debug.Assert(index >= 0 && index < SEGMENT_SIZE); localTail.UnsafeAdd(element); index++; @@ -125,7 +125,7 @@ namespace System.Collections.Concurrent [OnDeserialized] private void OnDeserialized(StreamingContext context) { - Contract.Assert(m_serializationArray != null); + Debug.Assert(m_serializationArray != null); InitializeFromCollection(m_serializationArray); m_serializationArray = null; } @@ -689,7 +689,7 @@ namespace System.Collections.Concurrent m_array = new T[SEGMENT_SIZE]; m_state = new VolatileBool[SEGMENT_SIZE]; //all initialized to false m_high = -1; - Contract.Assert(index >= 0); + Debug.Assert(index >= 0); m_index = index; m_source = source; } @@ -721,7 +721,7 @@ namespace System.Collections.Concurrent /// internal void UnsafeAdd(T value) { - Contract.Assert(m_high < SEGMENT_SIZE - 1); + Debug.Assert(m_high < SEGMENT_SIZE - 1); m_high++; m_array[m_high] = value; m_state[m_high].m_value = true; @@ -737,7 +737,7 @@ namespace System.Collections.Concurrent /// the reference to the new Segment internal Segment UnsafeGrow() { - Contract.Assert(m_high >= SEGMENT_SIZE - 1); + Debug.Assert(m_high >= SEGMENT_SIZE - 1); Segment newSegment = new Segment(m_index + 1, m_source); //m_index is Int64, we don't need to worry about overflow m_next = newSegment; return newSegment; @@ -753,7 +753,7 @@ namespace System.Collections.Concurrent //no CAS is needed, since there is no contention (other threads are blocked, busy waiting) Segment newSegment = new Segment(m_index + 1, m_source); //m_index is Int64, we don't need to worry about overflow m_next = newSegment; - Contract.Assert(m_source.m_tail == this); + Debug.Assert(m_source.m_tail == this); m_source.m_tail = m_next; } @@ -860,7 +860,7 @@ namespace System.Collections.Concurrent { spinLocal.SpinOnce(); } - Contract.Assert(m_source.m_head == this); + Debug.Assert(m_source.m_head == this); m_source.m_head = m_next; } return true; diff --git a/src/mscorlib/src/System/Collections/Concurrent/PartitionerStatic.cs b/src/mscorlib/src/System/Collections/Concurrent/PartitionerStatic.cs index 5a7f8f4..a946abf 100644 --- a/src/mscorlib/src/System/Collections/Concurrent/PartitionerStatic.cs +++ b/src/mscorlib/src/System/Collections/Concurrent/PartitionerStatic.cs @@ -14,6 +14,7 @@ using System.Collections.Generic; using System.Security.Permissions; using System.Threading; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; @@ -428,7 +429,7 @@ namespace System.Collections.Concurrent //perform deferred allocating of the local variables. if (m_localOffset == null) { - Contract.Assert(m_currentChunkSize == null); + Debug.Assert(m_currentChunkSize == null); m_localOffset = new SharedInt(-1); m_currentChunkSize = new SharedInt(0); m_doublingCountdown = CHUNK_DOUBLING_RATE; @@ -446,7 +447,7 @@ namespace System.Collections.Concurrent { // The second part of the || condition is necessary to handle the case when MoveNext() is called // after a previous MoveNext call returned false. - Contract.Assert(m_localOffset.Value == m_currentChunkSize.Value - 1 || m_currentChunkSize.Value == 0); + Debug.Assert(m_localOffset.Value == m_currentChunkSize.Value - 1 || m_currentChunkSize.Value == 0); //set the requested chunk size to a proper value int requestedChunkSize; @@ -467,11 +468,11 @@ namespace System.Collections.Concurrent // Decrement your doubling countdown m_doublingCountdown--; - Contract.Assert(requestedChunkSize > 0 && requestedChunkSize <= m_maxChunkSize); + Debug.Assert(requestedChunkSize > 0 && requestedChunkSize <= m_maxChunkSize); //GrabNextChunk will update the value of m_currentChunkSize if (GrabNextChunk(requestedChunkSize)) { - Contract.Assert(m_currentChunkSize.Value <= requestedChunkSize && m_currentChunkSize.Value > 0); + Debug.Assert(m_currentChunkSize.Value <= requestedChunkSize && m_currentChunkSize.Value > 0); m_localOffset.Value = 0; return true; } @@ -712,10 +713,10 @@ namespace System.Collections.Concurrent /// internal bool GrabChunk_Single(KeyValuePair[] destArray, int requestedChunkSize, ref int actualNumElementsGrabbed) { - Contract.Assert(m_useSingleChunking, "Expected m_useSingleChecking to be true"); - Contract.Assert(requestedChunkSize == 1, "Got requested chunk size of " + requestedChunkSize + " when single-chunking was on"); - Contract.Assert(actualNumElementsGrabbed == 0, "Expected actualNumElementsGrabbed == 0, instead it is " + actualNumElementsGrabbed); - Contract.Assert(destArray.Length == 1, "Expected destArray to be of length 1, instead its length is " + destArray.Length); + Debug.Assert(m_useSingleChunking, "Expected m_useSingleChecking to be true"); + Debug.Assert(requestedChunkSize == 1, "Got requested chunk size of " + requestedChunkSize + " when single-chunking was on"); + Debug.Assert(actualNumElementsGrabbed == 0, "Expected actualNumElementsGrabbed == 0, instead it is " + actualNumElementsGrabbed); + Debug.Assert(destArray.Length == 1, "Expected destArray to be of length 1, instead its length is " + destArray.Length); lock (m_sharedLock) { @@ -761,8 +762,8 @@ namespace System.Collections.Concurrent /// internal bool GrabChunk_Buffered(KeyValuePair[] destArray, int requestedChunkSize, ref int actualNumElementsGrabbed) { - Contract.Assert(requestedChunkSize > 0); - Contract.Assert(!m_useSingleChunking, "Did not expect to be in single-chunking mode"); + Debug.Assert(requestedChunkSize > 0); + Debug.Assert(!m_useSingleChunking, "Did not expect to be in single-chunking mode"); TryCopyFromFillBuffer(destArray, requestedChunkSize, ref actualNumElementsGrabbed); @@ -800,7 +801,7 @@ namespace System.Collections.Concurrent while( m_activeCopiers > 0) sw.SpinOnce(); } - Contract.Assert(m_sharedIndex != null); //already been allocated in MoveNext() before calling GrabNextChunk + Debug.Assert(m_sharedIndex != null); //already been allocated in MoveNext() before calling GrabNextChunk // Now's the time to actually enumerate the source @@ -937,7 +938,7 @@ namespace System.Collections.Concurrent /// override protected bool GrabNextChunk(int requestedChunkSize) { - Contract.Assert(requestedChunkSize > 0); + Debug.Assert(requestedChunkSize > 0); if (HasNoElementsLeft) { @@ -970,8 +971,8 @@ namespace System.Collections.Concurrent { //we only set it from false to true once //we should never set it back in any circumstances - Contract.Assert(value); - Contract.Assert(!m_hasNoElementsLeft.Value); + Debug.Assert(value); + Debug.Assert(!m_hasNoElementsLeft.Value); m_hasNoElementsLeft.Value = true; } } @@ -985,8 +986,8 @@ namespace System.Collections.Concurrent { throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext")); } - Contract.Assert(m_localList != null); - Contract.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value); + Debug.Assert(m_localList != null); + Debug.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value); return (m_localList[m_localOffset.Value]); } } @@ -1124,11 +1125,11 @@ namespace System.Collections.Concurrent /// override protected bool GrabNextChunk(int requestedChunkSize) { - Contract.Assert(requestedChunkSize > 0); + Debug.Assert(requestedChunkSize > 0); while (!HasNoElementsLeft) { - Contract.Assert(m_sharedIndex != null); + Debug.Assert(m_sharedIndex != null); // use the new Volatile.Read method because it is cheaper than Interlocked.Read on AMD64 architecture long oldSharedIndex = Volatile.Read(ref m_sharedIndex.Value); @@ -1170,13 +1171,13 @@ namespace System.Collections.Concurrent { get { - Contract.Assert(m_sharedIndex != null); + Debug.Assert(m_sharedIndex != null); // use the new Volatile.Read method because it is cheaper than Interlocked.Read on AMD64 architecture return Volatile.Read(ref m_sharedIndex.Value) >= SourceCount - 1; } set { - Contract.Assert(false); + Debug.Assert(false); } } @@ -1265,7 +1266,7 @@ namespace System.Collections.Concurrent throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext")); } - Contract.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value); + Debug.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value); return new KeyValuePair(m_startIndex + m_localOffset.Value, m_sharedReader[m_startIndex + m_localOffset.Value]); } @@ -1349,7 +1350,7 @@ namespace System.Collections.Concurrent throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext")); } - Contract.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value); + Debug.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value); return new KeyValuePair(m_startIndex + m_localOffset.Value, m_sharedReader[m_startIndex + m_localOffset.Value]); } @@ -1536,7 +1537,7 @@ namespace System.Collections.Concurrent internal StaticIndexRangePartitionerForIList(IList list) : base() { - Contract.Assert(list != null); + Debug.Assert(list != null); m_list = list; } override protected int SourceCount @@ -1562,7 +1563,7 @@ namespace System.Collections.Concurrent internal StaticIndexRangePartitionForIList(IList list, int startIndex, int endIndex) : base(startIndex, endIndex) { - Contract.Assert(startIndex >= 0 && endIndex <= list.Count - 1); + Debug.Assert(startIndex >= 0 && endIndex <= list.Count - 1); m_list = list; } @@ -1576,7 +1577,7 @@ namespace System.Collections.Concurrent throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext")); } - Contract.Assert(m_offset >= m_startIndex && m_offset <= m_endIndex); + Debug.Assert(m_offset >= m_startIndex && m_offset <= m_endIndex); return (new KeyValuePair(m_offset, m_list[m_offset])); } } @@ -1594,7 +1595,7 @@ namespace System.Collections.Concurrent internal StaticIndexRangePartitionerForArray(TSource[] array) : base() { - Contract.Assert(array != null); + Debug.Assert(array != null); m_array = array; } override protected int SourceCount @@ -1619,7 +1620,7 @@ namespace System.Collections.Concurrent internal StaticIndexRangePartitionForArray(TSource[] array, int startIndex, int endIndex) : base(startIndex, endIndex) { - Contract.Assert(startIndex >= 0 && endIndex <= array.Length - 1); + Debug.Assert(startIndex >= 0 && endIndex <= array.Length - 1); m_array = array; } @@ -1633,7 +1634,7 @@ namespace System.Collections.Concurrent throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext")); } - Contract.Assert(m_offset >= m_startIndex && m_offset <= m_endIndex); + Debug.Assert(m_offset >= m_startIndex && m_offset <= m_endIndex); return (new KeyValuePair(m_offset, m_array[m_offset])); } } @@ -1705,7 +1706,7 @@ namespace System.Collections.Concurrent } else { - Contract.Assert((DEFAULT_BYTES_PER_CHUNK % IntPtr.Size) == 0, "bytes per chunk should be a multiple of pointer size"); + Debug.Assert((DEFAULT_BYTES_PER_CHUNK % IntPtr.Size) == 0, "bytes per chunk should be a multiple of pointer size"); chunkSize = (DEFAULT_BYTES_PER_CHUNK / IntPtr.Size); } return chunkSize; diff --git a/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs b/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs index 5872874..298ac3e 100644 --- a/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs +++ b/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs @@ -17,6 +17,7 @@ namespace System.Collections.Generic using System; using System.Globalization; using System.Runtime.CompilerServices; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.Versioning; @@ -89,8 +90,8 @@ namespace System.Collections.Generic public void Sort(T[] keys, int index, int length, IComparer comparer) { - Contract.Assert(keys != null, "Check the arguments in the caller!"); - Contract.Assert( index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); + Debug.Assert(keys != null, "Check the arguments in the caller!"); + Debug.Assert( index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. @@ -134,9 +135,9 @@ namespace System.Collections.Generic internal static void Sort(T[] keys, int index, int length, Comparison comparer) { - Contract.Assert(keys != null, "Check the arguments in the caller!"); - Contract.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); - Contract.Assert(comparer != null, "Check the arguments in the caller!"); + Debug.Assert(keys != null, "Check the arguments in the caller!"); + Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); + Debug.Assert(comparer != null, "Check the arguments in the caller!"); // Add a try block here to detect bogus comparisons try @@ -379,8 +380,8 @@ namespace System.Collections.Generic public void Sort(T[] keys, int index, int length, IComparer comparer) { - Contract.Assert(keys != null, "Check the arguments in the caller!"); - Contract.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); + Debug.Assert(keys != null, "Check the arguments in the caller!"); + Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); try { @@ -405,8 +406,8 @@ namespace System.Collections.Generic public int BinarySearch(T[] array, int index, int length, T value, IComparer comparer) { - Contract.Assert(array != null, "Check the arguments in the caller!"); - Contract.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); + Debug.Assert(array != null, "Check the arguments in the caller!"); + Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); try { @@ -703,8 +704,8 @@ namespace System.Collections.Generic public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer comparer) { - Contract.Assert(keys != null, "Check the arguments in the caller!"); // Precondition on interface method - Contract.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); + Debug.Assert(keys != null, "Check the arguments in the caller!"); // Precondition on interface method + Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. @@ -958,8 +959,8 @@ namespace System.Collections.Generic { public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer comparer) { - Contract.Assert(keys != null, "Check the arguments in the caller!"); - Contract.Assert( index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); + Debug.Assert(keys != null, "Check the arguments in the caller!"); + Debug.Assert( index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. diff --git a/src/mscorlib/src/System/Collections/Generic/Comparer.cs b/src/mscorlib/src/System/Collections/Generic/Comparer.cs index 481b3e1..4f06b0a 100644 --- a/src/mscorlib/src/System/Collections/Generic/Comparer.cs +++ b/src/mscorlib/src/System/Collections/Generic/Comparer.cs @@ -7,6 +7,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; //using System.Globalization; using System.Runtime.CompilerServices; @@ -195,7 +196,7 @@ namespace System.Collections.Generic { public Int32EnumComparer() { - Contract.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!"); + Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!"); } // Used by the serialization engine. @@ -230,7 +231,7 @@ namespace System.Collections.Generic { public UInt32EnumComparer() { - Contract.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!"); + Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!"); } // Used by the serialization engine. @@ -261,7 +262,7 @@ namespace System.Collections.Generic { public Int64EnumComparer() { - Contract.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!"); + Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!"); } // Used by the serialization engine. @@ -292,7 +293,7 @@ namespace System.Collections.Generic { public UInt64EnumComparer() { - Contract.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!"); + Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!"); } // Used by the serialization engine. diff --git a/src/mscorlib/src/System/Collections/Generic/Dictionary.cs b/src/mscorlib/src/System/Collections/Generic/Dictionary.cs index 9409ff5..dc50530 100644 --- a/src/mscorlib/src/System/Collections/Generic/Dictionary.cs +++ b/src/mscorlib/src/System/Collections/Generic/Dictionary.cs @@ -459,7 +459,7 @@ namespace System.Collections.Generic { } private void Resize(int newSize, bool forceNewHashCodes) { - Contract.Assert(newSize >= entries.Length); + Debug.Assert(newSize >= entries.Length); int[] newBuckets = new int[newSize]; for (int i = 0; i < newBuckets.Length; i++) newBuckets[i] = -1; Entry[] newEntries = new Entry[newSize]; diff --git a/src/mscorlib/src/System/Collections/Generic/List.cs b/src/mscorlib/src/System/Collections/Generic/List.cs index 9e77906..3e2947f 100644 --- a/src/mscorlib/src/System/Collections/Generic/List.cs +++ b/src/mscorlib/src/System/Collections/Generic/List.cs @@ -1029,8 +1029,8 @@ namespace System.Collections.Generic { private void AddEnumerable(IEnumerable enumerable) { - Contract.Assert(enumerable != null); - Contract.Assert(!(enumerable is ICollection), "We should have optimized for this beforehand."); + Debug.Assert(enumerable != null); + Debug.Assert(!(enumerable is ICollection), "We should have optimized for this beforehand."); using (IEnumerator en = enumerable.GetEnumerator()) { diff --git a/src/mscorlib/src/System/Collections/Hashtable.cs b/src/mscorlib/src/System/Collections/Hashtable.cs index d74991e..0b3a6b0 100644 --- a/src/mscorlib/src/System/Collections/Hashtable.cs +++ b/src/mscorlib/src/System/Collections/Hashtable.cs @@ -287,7 +287,7 @@ namespace System.Collections { loadsize = (int)(this.loadFactor * hashsize); isWriterInProgress = false; // Based on the current algorithm, loadsize must be less than hashsize. - Contract.Assert( loadsize < hashsize, "Invalid hashtable loadsize!"); + Debug.Assert( loadsize < hashsize, "Invalid hashtable loadsize!"); } // Constructs a new hashtable with the given initial capacity and load @@ -441,7 +441,7 @@ namespace System.Collections { // Removes all entries from this hashtable. [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public virtual void Clear() { - Contract.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously! Don't do that - use Hashtable.Synchronized."); + Debug.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously! Don't do that - use Hashtable.Synchronized."); if (count == 0 && occupancy == 0) return; @@ -752,7 +752,7 @@ namespace System.Collections { isWriterInProgress = false; // minimun size of hashtable is 3 now and maximum loadFactor is 0.72 now. - Contract.Assert(loadsize < newsize, "Our current implementaion means this is not possible."); + Debug.Assert(loadsize < newsize, "Our current implementaion means this is not possible."); return; } @@ -804,7 +804,7 @@ namespace System.Collections { // protected virtual bool KeyEquals(Object item, Object key) { - Contract.Assert(key != null, "key can't be null here!"); + Debug.Assert(key != null, "key can't be null here!"); if( Object.ReferenceEquals(buckets, item)) { return false; } @@ -955,13 +955,13 @@ namespace System.Collections { // If you see this assert, make sure load factor & count are reasonable. // Then verify that our double hash function (h2, described at top of file) // meets the requirements described above. You should never see this assert. - Contract.Assert(false, "hash table insert failed! Load factor too high, or our double hashing function is incorrect."); + Debug.Assert(false, "hash table insert failed! Load factor too high, or our double hashing function is incorrect."); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HashInsertFailed")); } private void putEntry (bucket[] newBuckets, Object key, Object nvalue, int hashcode) { - Contract.Assert(hashcode >= 0, "hashcode >= 0"); // make sure collision bit (sign bit) wasn't set. + Debug.Assert(hashcode >= 0, "hashcode >= 0"); // make sure collision bit (sign bit) wasn't set. uint seed = (uint) hashcode; uint incr = (uint)(1 + ((seed * HashPrime) % ((uint)newBuckets.Length - 1))); @@ -993,7 +993,7 @@ namespace System.Collections { throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key")); } Contract.EndContractBlock(); - Contract.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously! Don't do that - use Hashtable.Synchronized."); + Debug.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously! Don't do that - use Hashtable.Synchronized."); uint seed; uint incr; @@ -1659,7 +1659,7 @@ namespace System.Collections { // Note that this check works even when _items.Length overflowed thanks to the (uint) cast if ((uint)newSize > MaxPrimeArrayLength && MaxPrimeArrayLength > oldSize) { - Contract.Assert( MaxPrimeArrayLength == GetPrime(MaxPrimeArrayLength), "Invalid MaxPrimeArrayLength"); + Debug.Assert( MaxPrimeArrayLength == GetPrime(MaxPrimeArrayLength), "Invalid MaxPrimeArrayLength"); return MaxPrimeArrayLength; } @@ -1678,7 +1678,7 @@ namespace System.Collections { public static IEqualityComparer GetRandomizedEqualityComparer(object comparer) { - Contract.Assert(comparer == null || comparer == System.Collections.Generic.EqualityComparer.Default || comparer is IWellKnownStringEqualityComparer); + Debug.Assert(comparer == null || comparer == System.Collections.Generic.EqualityComparer.Default || comparer is IWellKnownStringEqualityComparer); if(comparer == null) { return new System.Collections.Generic.RandomizedObjectEqualityComparer(); @@ -1694,7 +1694,7 @@ namespace System.Collections { return cmp.GetRandomizedEqualityComparer(); } - Contract.Assert(false, "Missing case in GetRandomizedEqualityComparer!"); + Debug.Assert(false, "Missing case in GetRandomizedEqualityComparer!"); return null; } @@ -1731,7 +1731,7 @@ namespace System.Collections { if(data == null) { data = new byte[bufferSize]; - Contract.Assert(bufferSize % 8 == 0, "We increment our current index by 8, so our buffer size must be a multiple of 8"); + Debug.Assert(bufferSize % 8 == 0, "We increment our current index by 8, so our buffer size must be a multiple of 8"); } Microsoft.Win32.Win32Native.Random(true, data, data.Length); diff --git a/src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs b/src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs index 7313d71..b6fe6de 100644 --- a/src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs +++ b/src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs @@ -53,7 +53,7 @@ namespace System.Collections.ObjectModel /// new private List Items { get { - Contract.Assert(base.Items is List); + Debug.Assert(base.Items is List); return (List)base.Items; } @@ -233,7 +233,7 @@ namespace System.Collections.ObjectModel } private void RemoveKey(TKey key) { - Contract.Assert(key != null, "key shouldn't be null!"); + Debug.Assert(key != null, "key shouldn't be null!"); if (dict != null) { dict.Remove(key); } diff --git a/src/mscorlib/src/System/Collections/SortedList.cs b/src/mscorlib/src/System/Collections/SortedList.cs index 6ffd0b0..0f6ab62 100644 --- a/src/mscorlib/src/System/Collections/SortedList.cs +++ b/src/mscorlib/src/System/Collections/SortedList.cs @@ -211,7 +211,7 @@ namespace System.Collections { } else { // size can only be zero here. - Contract.Assert( _size == 0, "Size is not zero"); + Debug.Assert( _size == 0, "Size is not zero"); keys = emptyArray; values = emptyArray; } diff --git a/src/mscorlib/src/System/Convert.cs b/src/mscorlib/src/System/Convert.cs index 055911d..0e14f93 100644 --- a/src/mscorlib/src/System/Convert.cs +++ b/src/mscorlib/src/System/Convert.cs @@ -19,6 +19,7 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; +using System.Diagnostics; using System.Diagnostics.Contracts; @@ -146,13 +147,13 @@ namespace System { #if _DEBUG private static bool TriggerAsserts = DoAsserts(); private static bool DoAsserts() { - Contract.Assert(ConvertTypes!=null, "[Convert.cctor]ConvertTypes!=null"); - Contract.Assert(ConvertTypes.Length == ((int)TypeCode.String + 1), "[Convert.cctor]ConvertTypes.Length == ((int)TypeCode.String + 1)"); - Contract.Assert(ConvertTypes[(int)TypeCode.Empty]==typeof(System.Empty), + Debug.Assert(ConvertTypes!=null, "[Convert.cctor]ConvertTypes!=null"); + Debug.Assert(ConvertTypes.Length == ((int)TypeCode.String + 1), "[Convert.cctor]ConvertTypes.Length == ((int)TypeCode.String + 1)"); + Debug.Assert(ConvertTypes[(int)TypeCode.Empty]==typeof(System.Empty), "[Convert.cctor]ConvertTypes[(int)TypeCode.Empty]==typeof(System.Empty)"); - Contract.Assert(ConvertTypes[(int)TypeCode.String]==typeof(String), + Debug.Assert(ConvertTypes[(int)TypeCode.String]==typeof(String), "[Convert.cctor]ConvertTypes[(int)TypeCode.String]==typeof(System.String)"); - Contract.Assert(ConvertTypes[(int)TypeCode.Int32]==typeof(int), + Debug.Assert(ConvertTypes[(int)TypeCode.Int32]==typeof(int), "[Convert.cctor]ConvertTypes[(int)TypeCode.Int32]==typeof(int)"); return true; } @@ -2422,7 +2423,7 @@ namespace System { // The validity of parameters much be checked by callers, thus we are Critical here. - Contract.Assert(0 <= inputLength); + Debug.Assert(0 <= inputLength); // We need to get rid of any trailing white spaces. // Otherwise we would be rejecting input such as "abc= ": @@ -2437,7 +2438,7 @@ namespace System { // Compute the output length: Int32 resultLength = FromBase64_ComputeResultLength(inputPtr, inputLength); - Contract.Assert(0 <= resultLength); + Debug.Assert(0 <= resultLength); // resultLength can be zero. We will still enter FromBase64_Decode and process the input. // It may either simply write no bytes (e.g. input = " ") or throw (e.g. input = "ab"). @@ -2571,12 +2572,12 @@ namespace System { }} // unchecked while // 'd be nice to have an assert that we never get here, but CS0162: Unreachable code detected. - // Contract.Assert(false, "We only leave the above loop by jumping; should never get here."); + // Debug.Assert(false, "We only leave the above loop by jumping; should never get here."); // We jump here out of the loop if we hit an '=': _EqualityCharEncountered: - Contract.Assert(currCode == intEq); + Debug.Assert(currCode == intEq); // Recall that inputPtr is now one position past where '=' was read. // '=' can only be at the last input pos: @@ -2655,7 +2656,7 @@ namespace System { const UInt32 intEq = (UInt32) '='; const UInt32 intSpace = (UInt32) ' '; - Contract.Assert(0 <= inputLength); + Debug.Assert(0 <= inputLength); Char* inputEndPtr = inputPtr + inputLength; Int32 usefulInputLength = inputLength; @@ -2678,11 +2679,11 @@ namespace System { } } - Contract.Assert(0 <= usefulInputLength); + Debug.Assert(0 <= usefulInputLength); // For legal input, we can assume that 0 <= padding < 3. But it may be more for illegal input. // We will notice it at decode when we see a '=' at the wrong place. - Contract.Assert(0 <= padding); + Debug.Assert(0 <= padding); // Perf: reuse the variable that stored the number of '=' to store the number of bytes encoded by the // last group that contains the '=': diff --git a/src/mscorlib/src/System/DateTimeOffset.cs b/src/mscorlib/src/System/DateTimeOffset.cs index fedc5f9..5bdaa18 100644 --- a/src/mscorlib/src/System/DateTimeOffset.cs +++ b/src/mscorlib/src/System/DateTimeOffset.cs @@ -11,6 +11,7 @@ namespace System { using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Security.Permissions; + using System.Diagnostics; using System.Diagnostics.Contracts; // DateTimeOffset is a value type that consists of a DateTime and a time zone offset, @@ -750,7 +751,7 @@ namespace System { private static DateTime ValidateDate(DateTime dateTime, TimeSpan offset) { // The key validation is that both the UTC and clock times fit. The clock time is validated // by the DateTime constructor. - Contract.Assert(offset.Ticks >= MinOffset && offset.Ticks <= MaxOffset, "Offset not validated."); + Debug.Assert(offset.Ticks >= MinOffset && offset.Ticks <= MaxOffset, "Offset not validated."); // This operation cannot overflow because offset should have already been validated to be within // 14 hours and the DateTime instance is more than that distance from the boundaries of Int64. Int64 utcTicks = dateTime.Ticks - offset.Ticks; diff --git a/src/mscorlib/src/System/DefaultBinder.cs b/src/mscorlib/src/System/DefaultBinder.cs index 248148a..b4681c4 100644 --- a/src/mscorlib/src/System/DefaultBinder.cs +++ b/src/mscorlib/src/System/DefaultBinder.cs @@ -14,6 +14,7 @@ namespace System { using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; using CultureInfo = System.Globalization.CultureInfo; //Marked serializable even though it has no state. @@ -982,7 +983,7 @@ namespace System { int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType); if (hierarchyDepth1 == hierarchyDepth2) { - Contract.Assert(cur1.IsStatic != cur2.IsStatic, "hierarchyDepth1 == hierarchyDepth2"); + Debug.Assert(cur1.IsStatic != cur2.IsStatic, "hierarchyDepth1 == hierarchyDepth2"); return 0; } else if (hierarchyDepth1 < hierarchyDepth2) diff --git a/src/mscorlib/src/System/Delegate.cs b/src/mscorlib/src/System/Delegate.cs index f0961ec..bca88c1 100644 --- a/src/mscorlib/src/System/Delegate.cs +++ b/src/mscorlib/src/System/Delegate.cs @@ -12,6 +12,7 @@ namespace System { using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -627,7 +628,7 @@ namespace System { internal static Delegate CreateDelegateInternal(RuntimeType rtType, RuntimeMethodInfo rtMethod, Object firstArgument, DelegateBindingFlags flags, ref StackCrawlMark stackMark) { - Contract.Assert((flags & DelegateBindingFlags.SkipSecurityChecks) == 0); + Debug.Assert((flags & DelegateBindingFlags.SkipSecurityChecks) == 0); #if FEATURE_APPX bool nonW8PMethod = (rtMethod.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0; diff --git a/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs b/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs index 0e0005c..27f4f4c 100644 --- a/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs +++ b/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs @@ -32,6 +32,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; @@ -287,7 +288,7 @@ namespace System.Diagnostics.Contracts { /// /// Expression to assume will always be true. /// - /// At runtime this is equivalent to an . + /// At runtime this is equivalent to an . /// [Pure] [Conditional("DEBUG")] @@ -308,7 +309,7 @@ namespace System.Diagnostics.Contracts { /// Expression to assume will always be true. /// If it is not a constant string literal, then the contract may not be understood by tools. /// - /// At runtime this is equivalent to an . + /// At runtime this is equivalent to an . /// [Pure] [Conditional("DEBUG")] diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/ActivityTracker.cs b/src/mscorlib/src/System/Diagnostics/Eventing/ActivityTracker.cs index 64906f1..1a1f5fa 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/ActivityTracker.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/ActivityTracker.cs @@ -72,7 +72,7 @@ namespace System.Diagnostics.Tracing } - Contract.Assert((options & EventActivityOptions.Disable) == 0); + Debug.Assert((options & EventActivityOptions.Disable) == 0); var currentActivity = m_current.Value; var fullActivityName = NormalizeActivityName(providerName, activityName, task); @@ -191,7 +191,7 @@ namespace System.Diagnostics.Tracing else { orphan.m_stopped = 1; - Contract.Assert(orphan.m_stopped != 0); + Debug.Assert(orphan.m_stopped != 0); } orphan = orphan.m_creator; } @@ -524,8 +524,8 @@ namespace System.Diagnostics.Tracing /// private static unsafe void WriteNibble(ref byte* ptr, byte* endPtr, uint value) { - Contract.Assert(0 <= value && value < 16); - Contract.Assert(ptr < endPtr); + Debug.Assert(0 <= value && value < 16); + Debug.Assert(ptr < endPtr); if (*ptr != 0) *ptr++ |= (byte)value; diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs index 545e3e6..ce0fcb6 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs @@ -457,7 +457,7 @@ namespace System.Diagnostics.Tracing } if (providerInstance->NextOffset == 0) break; - Contract.Assert(0 <= providerInstance->NextOffset && providerInstance->NextOffset < buffSize); + Debug.Assert(0 <= providerInstance->NextOffset && providerInstance->NextOffset < buffSize); var structBase = (byte*)providerInstance; providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&structBase[providerInstance->NextOffset]; } @@ -1120,7 +1120,7 @@ namespace System.Diagnostics.Tracing if (childActivityID != null) { // activity transfers are supported only for events that specify the Send or Receive opcode - Contract.Assert((EventOpcode)eventDescriptor.Opcode == EventOpcode.Send || + Debug.Assert((EventOpcode)eventDescriptor.Opcode == EventOpcode.Send || (EventOpcode)eventDescriptor.Opcode == EventOpcode.Receive || (EventOpcode)eventDescriptor.Opcode == EventOpcode.Start || (EventOpcode)eventDescriptor.Opcode == EventOpcode.Stop); @@ -1187,7 +1187,7 @@ namespace System.Diagnostics.Tracing } private static int bitindex(uint n) { - Contract.Assert(bitcount(n) == 1); + Debug.Assert(bitcount(n) == 1); int idx = 0; while ((n & (1 << idx)) == 0) idx++; diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs index 5c4e031..aa0d8d7 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs @@ -1127,7 +1127,7 @@ namespace System.Diagnostics.Tracing { try { - Contract.Assert(m_eventData != null); // You must have initialized this if you enabled the source. + Debug.Assert(m_eventData != null); // You must have initialized this if you enabled the source. if (relatedActivityId != null) ValidateEventOpcodeForTransfer(ref m_eventData[eventId], m_eventData[eventId].Name); @@ -1357,7 +1357,7 @@ namespace System.Diagnostics.Tracing #if FEATURE_ACTIVITYSAMPLING internal void WriteStringToListener(EventListener listener, string msg, SessionMask m) { - Contract.Assert(listener == null || (uint)m == (uint)SessionMask.FromId(0)); + Debug.Assert(listener == null || (uint)m == (uint)SessionMask.FromId(0)); if (m_eventSourceEnabled) { @@ -1489,7 +1489,7 @@ namespace System.Diagnostics.Tracing } #endif // FEATURE_MANAGED_ETW - Contract.Assert(!m_eventSourceEnabled); // We can't be enabled until we are completely initted. + Debug.Assert(!m_eventSourceEnabled); // We can't be enabled until we are completely initted. // We are logically completely initialized at this point. m_completelyInited = true; } @@ -1870,7 +1870,7 @@ namespace System.Diagnostics.Tracing { try { - Contract.Assert(m_eventData != null); // You must have initialized this if you enabled the source. + Debug.Assert(m_eventData != null); // You must have initialized this if you enabled the source. if (childActivityID != null) { ValidateEventOpcodeForTransfer(ref m_eventData[eventId], m_eventData[eventId].Name); @@ -2150,7 +2150,7 @@ namespace System.Diagnostics.Tracing Exception lastThrownException = null; for (EventDispatcher dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next) { - Contract.Assert(dispatcher.m_EventEnabled != null); + Debug.Assert(dispatcher.m_EventEnabled != null); if (eventId == -1 || dispatcher.m_EventEnabled[eventId]) { #if FEATURE_ACTIVITYSAMPLING @@ -2580,7 +2580,7 @@ namespace System.Diagnostics.Tracing { // PRECONDITION: We should be holding the EventListener.EventListenersLock // We defer commands until we are completely inited. This allows error messages to be sent. - Contract.Assert(m_completelyInited); + Debug.Assert(m_completelyInited); #if FEATURE_MANAGED_ETW if (m_provider == null) // If we failed to construct @@ -2592,7 +2592,7 @@ namespace System.Diagnostics.Tracing try { EnsureDescriptorsInitialized(); - Contract.Assert(m_eventData != null); + Debug.Assert(m_eventData != null); // Find the per-EventSource dispatcher corresponding to registered dispatcher commandArgs.dispatcher = GetDispatcher(commandArgs.listener); @@ -2651,7 +2651,7 @@ namespace System.Diagnostics.Tracing // hasn't changed. // sesisonId = SessionMask.MAX when one of the legacy ETW sessions changed // 0 <= perEventSourceSessionId < SessionMask.MAX for activity-tracing aware sessions - Contract.Assert(commandArgs.perEventSourceSessionId >= -1 && commandArgs.perEventSourceSessionId <= SessionMask.MAX); + Debug.Assert(commandArgs.perEventSourceSessionId >= -1 && commandArgs.perEventSourceSessionId <= SessionMask.MAX); // Send the manifest if we are enabling an ETW session if (bSessionEnable && commandArgs.dispatcher == null) @@ -2706,7 +2706,7 @@ namespace System.Diagnostics.Tracing // things like log messages, or test if keywords are enabled in the callback. if (commandArgs.enable) { - Contract.Assert(m_eventData != null); + Debug.Assert(m_eventData != null); m_eventSourceEnabled = true; } @@ -2794,9 +2794,9 @@ namespace System.Diagnostics.Tracing } // These are not used for non-update commands and thus should always be 'default' values - // Contract.Assert(enable == true); - // Contract.Assert(level == EventLevel.LogAlways); - // Contract.Assert(matchAnyKeyword == EventKeywords.None); + // Debug.Assert(enable == true); + // Debug.Assert(level == EventLevel.LogAlways); + // Debug.Assert(matchAnyKeyword == EventKeywords.None); this.OnEventCommand(commandArgs); var eventCommandCallback = m_eventCommandExecuted; @@ -2994,7 +2994,7 @@ namespace System.Diagnostics.Tracing private void EnsureDescriptorsInitialized() { #if !ES_BUILD_STANDALONE - Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); + Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); #endif if (m_eventData == null) { @@ -3010,9 +3010,9 @@ namespace System.Diagnostics.Tracing if (eventSourceGuid.Equals(Guid.Empty) || eventSourceName == null || eventData == null || manifest == null) { // GetMetadata failed, so we have to set it via reflection. - Contract.Assert(m_rawManifest == null); + Debug.Assert(m_rawManifest == null); m_rawManifest = CreateManifestAndDescriptors(this.GetType(), Name, this); - Contract.Assert(m_eventData != null); + Debug.Assert(m_eventData != null); } else @@ -3064,7 +3064,7 @@ namespace System.Diagnostics.Tracing if (rawManifest == null) return false; - Contract.Assert(!SelfDescribingEvents); + Debug.Assert(!SelfDescribingEvents); #if FEATURE_MANAGED_ETW fixed (byte* dataPtr = rawManifest) @@ -3168,7 +3168,7 @@ namespace System.Diagnostics.Tracing { Attribute attr = null; - Contract.Assert(data.ConstructorArguments.Count <= 1); + Debug.Assert(data.ConstructorArguments.Count <= 1); if (data.ConstructorArguments.Count == 1) { @@ -3455,7 +3455,7 @@ namespace System.Diagnostics.Tracing int startEventId = eventAttribute.EventId - 1; if (eventData != null && startEventId < eventData.Length) { - Contract.Assert(0 <= startEventId); // Since we reserve id 0, we know that id-1 is <= 0 + Debug.Assert(0 <= startEventId); // Since we reserve id 0, we know that id-1 is <= 0 EventMetadata startEventMetadata = eventData[startEventId]; // If you remove the Stop and add a Start does that name match the Start Event's Name? @@ -3718,7 +3718,7 @@ namespace System.Diagnostics.Tracing // We give a task to things if they don't have one. // TODO this is moderately expensive (N*N). We probably should not even bother.... - Contract.Assert(eventAttribute.Task != EventTask.None || eventAttribute.Opcode != EventOpcode.Info); + Debug.Assert(eventAttribute.Task != EventTask.None || eventAttribute.Opcode != EventOpcode.Info); for (int idx = 0; idx < eventData.Length; ++idx) { // skip unused Event IDs. @@ -3900,7 +3900,7 @@ namespace System.Diagnostics.Tracing goto default; break; default: - /* Contract.Assert(false, "Warning: User validation code sub-optimial: Unsuported opcode " + instrs[idx] + + /* Debug.Assert(false, "Warning: User validation code sub-optimial: Unsuported opcode " + instrs[idx] + " at " + idx + " in method " + method.Name); */ return -1; } @@ -3983,7 +3983,7 @@ namespace System.Diagnostics.Tracing { get { - Contract.Assert(((m_config & EventSourceSettings.EtwManifestEventFormat) != 0) != + Debug.Assert(((m_config & EventSourceSettings.EtwManifestEventFormat) != 0) != ((m_config & EventSourceSettings.EtwSelfDescribingEventFormat) != 0)); return (m_config & EventSourceSettings.EtwSelfDescribingEventFormat) != 0; } @@ -4005,7 +4005,7 @@ namespace System.Diagnostics.Tracing #if FEATURE_ACTIVITYSAMPLING private void ReportActivitySamplingInfo(EventListener listener, SessionMask sessions) { - Contract.Assert(listener == null || (uint)sessions == (uint)SessionMask.FromId(0)); + Debug.Assert(listener == null || (uint)sessions == (uint)SessionMask.FromId(0)); for (int perEventSourceSessionId = 0; perEventSourceSessionId < SessionMask.MAX; ++perEventSourceSessionId) { @@ -4016,7 +4016,7 @@ namespace System.Diagnostics.Tracing if (listener == null) { EtwSession etwSession = m_etwSessionIdMap[perEventSourceSessionId]; - Contract.Assert(etwSession != null); + Debug.Assert(etwSession != null); af = etwSession.m_activityFilter; } else @@ -4474,7 +4474,7 @@ namespace System.Diagnostics.Tracing private static void RemoveReferencesToListenerInEventSources(EventListener listenerToRemove) { #if !ES_BUILD_STANDALONE - Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); + Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); #endif // Foreach existing EventSource in the appdomain foreach (WeakReference eventSourceRef in s_EventSources) @@ -4494,7 +4494,7 @@ namespace System.Diagnostics.Tracing EventDispatcher cur = prev.m_Next; if (cur == null) { - Contract.Assert(false, "EventSource did not have a registered EventListener!"); + Debug.Assert(false, "EventSource did not have a registered EventListener!"); break; } if (cur.m_Listener == listenerToRemove) @@ -4534,13 +4534,13 @@ namespace System.Diagnostics.Tracing EventSource eventSource = eventSourceRef.Target as EventSource; if (eventSource == null) continue; - Contract.Assert(eventSource.m_id == id, "Unexpected event source ID."); + Debug.Assert(eventSource.m_id == id, "Unexpected event source ID."); // None listeners on eventSources exist in the dispatcher list. EventDispatcher dispatcher = eventSource.m_Dispatchers; while (dispatcher != null) { - Contract.Assert(allListeners.ContainsKey(dispatcher.m_Listener), "EventSource has a listener not on the global list."); + Debug.Assert(allListeners.ContainsKey(dispatcher.m_Listener), "EventSource has a listener not on the global list."); dispatcher = dispatcher.m_Next; } @@ -4550,7 +4550,7 @@ namespace System.Diagnostics.Tracing dispatcher = eventSource.m_Dispatchers; for (;;) { - Contract.Assert(dispatcher != null, "Listener is not on all eventSources."); + Debug.Assert(dispatcher != null, "Listener is not on all eventSources."); if (dispatcher.m_Listener == listener) break; dispatcher = dispatcher.m_Next; @@ -4808,7 +4808,7 @@ namespace System.Diagnostics.Tracing if (m_payloadNames == null) { // Self described events are identified by id -1. - Contract.Assert(EventId != -1); + Debug.Assert(EventId != -1); var names = new List(); foreach (var parameter in m_eventSource.m_eventData[EventId].Parameters) @@ -5237,7 +5237,7 @@ namespace System.Diagnostics.Tracing public static void DisableFilter(ref ActivityFilter filterList, EventSource source) { #if !ES_BUILD_STANDALONE - Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); + Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); #endif if (filterList == null) @@ -5305,7 +5305,7 @@ namespace System.Diagnostics.Tracing string startEvents) { #if !ES_BUILD_STANDALONE - Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); + Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); #endif // first remove all filters associated with 'source' @@ -5399,7 +5399,7 @@ namespace System.Diagnostics.Tracing EventSource source, int eventId) { - Contract.Assert(filterList != null && filterList.m_activeActivities != null); + Debug.Assert(filterList != null && filterList.m_activeActivities != null); bool shouldBeLogged = false; if (triggeringEvent) { @@ -5490,10 +5490,10 @@ namespace System.Diagnostics.Tracing /// unsafe public static void FlowActivityIfNeeded(ActivityFilter filterList, Guid* currentActivityId, Guid* childActivityID) { - Contract.Assert(childActivityID != null); + Debug.Assert(childActivityID != null); var activeActivities = GetActiveActivities(filterList); - Contract.Assert(activeActivities != null); + Debug.Assert(activeActivities != null); // take currentActivityId == null to mean we *know* the current activity is "active" if (currentActivityId != null && !activeActivities.ContainsKey(*currentActivityId)) @@ -5550,7 +5550,7 @@ namespace System.Diagnostics.Tracing public void Dispose() { #if !ES_BUILD_STANDALONE - Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); + Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); #endif // m_myActivityDelegate is still alive (held by the static EventSource.s_activityDying). // Therefore we are ok to take a dependency on m_myActivityDelegate being valid even @@ -5577,7 +5577,7 @@ namespace System.Diagnostics.Tracing m_samplingFreq = samplingFreq; m_next = existingFilter; - Contract.Assert(existingFilter == null || + Debug.Assert(existingFilter == null || (existingFilter.m_activeActivities == null) == (existingFilter.m_rootActiveActivities == null)); // if this is the first filter we add for this session, we need to create a new @@ -5651,10 +5651,10 @@ namespace System.Diagnostics.Tracing private static bool EnableFilter(ref ActivityFilter filterList, EventSource source, int perEventSourceSessionId, int eventId, int samplingFreq) { #if !ES_BUILD_STANDALONE - Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); + Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); #endif - Contract.Assert(samplingFreq > 0); - Contract.Assert(eventId >= 0); + Debug.Assert(samplingFreq > 0); + Debug.Assert(eventId >= 0); filterList = new ActivityFilter(source, perEventSourceSessionId, eventId, samplingFreq, filterList); @@ -5785,7 +5785,7 @@ namespace System.Diagnostics.Tracing public static void RemoveEtwSession(EtwSession etwSession) { - Contract.Assert(etwSession != null); + Debug.Assert(etwSession != null); if (s_etwSessions == null || etwSession == null) return; @@ -5866,7 +5866,7 @@ namespace System.Diagnostics.Tracing public static SessionMask FromId(int perEventSourceSessionId) { - Contract.Assert(perEventSourceSessionId < MAX); + Debug.Assert(perEventSourceSessionId < MAX); return new SessionMask((uint)1 << perEventSourceSessionId); } @@ -5884,12 +5884,12 @@ namespace System.Diagnostics.Tracing { get { - Contract.Assert(perEventSourceSessionId < MAX); + Debug.Assert(perEventSourceSessionId < MAX); return (m_mask & (1 << perEventSourceSessionId)) != 0; } set { - Contract.Assert(perEventSourceSessionId < MAX); + Debug.Assert(perEventSourceSessionId < MAX); if (value) m_mask |= ((uint)1 << perEventSourceSessionId); else m_mask &= ~((uint)1 << perEventSourceSessionId); } @@ -6120,7 +6120,7 @@ namespace System.Diagnostics.Tracing private EventChannelType EventChannelToChannelType(EventChannel channel) { #if !ES_BUILD_STANDALONE - Contract.Assert(channel >= EventChannel.Admin && channel <= EventChannel.Debug); + Debug.Assert(channel >= EventChannel.Admin && channel <= EventChannel.Debug); #endif return (EventChannelType)((int)channel - (int)EventChannel.Admin + (int)EventChannelType.Admin); } @@ -6163,8 +6163,8 @@ namespace System.Diagnostics.Tracing #endif public void StartEvent(string eventName, EventAttribute eventAttribute) { - Contract.Assert(numParams == 0); - Contract.Assert(this.eventName == null); + Debug.Assert(numParams == 0); + Debug.Assert(this.eventName == null); this.eventName = eventName; numParams = 0; byteArrArgIndices = null; diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs index a894d89..5967ad6 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Collections; +using System.Diagnostics; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; @@ -26,7 +27,7 @@ namespace System.Diagnostics.Tracing { internal EventPayload(List payloadNames, List payloadValues) { - Contract.Assert(payloadNames.Count == payloadValues.Count); + Debug.Assert(payloadNames.Count == payloadValues.Count); m_names = payloadNames; m_values = payloadValues; diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs index 0f34d95..3ea7812 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs @@ -1,5 +1,6 @@ using System.Reflection; using System.Runtime.InteropServices; +using System.Diagnostics; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; @@ -132,7 +133,7 @@ namespace System.Diagnostics.Tracing { get { - Contract.Assert(_scalarLength == 0, "This ReflectedValue refers to an unboxed value type, not a reference type or boxed value type."); + Debug.Assert(_scalarLength == 0, "This ReflectedValue refers to an unboxed value type, not a reference type or boxed value type."); return _reference; } } @@ -141,7 +142,7 @@ namespace System.Diagnostics.Tracing { get { - Contract.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type"); + Debug.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type"); return _scalar; } } @@ -150,7 +151,7 @@ namespace System.Diagnostics.Tracing { get { - Contract.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type"); + Debug.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type"); return _scalarLength; } } diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs index e51aff0..901a0ed 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.Reflection; +using System.Diagnostics; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; @@ -269,7 +270,7 @@ namespace System.Diagnostics.Tracing : base(type) { var typeArgs = type.GenericTypeArguments; - Contract.Assert(typeArgs.Length == 1); + Debug.Assert(typeArgs.Length == 1); this.valueInfo = TraceLoggingTypeInfo.GetInstance(typeArgs[0], recursionCheck); this.hasValueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("HasValue")); this.valueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("Value")); diff --git a/src/mscorlib/src/System/Enum.cs b/src/mscorlib/src/System/Enum.cs index f06e28f..d39e005 100644 --- a/src/mscorlib/src/System/Enum.cs +++ b/src/mscorlib/src/System/Enum.cs @@ -9,6 +9,7 @@ using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System @@ -69,7 +70,7 @@ namespace System case CorElementType.U8: return (*(ulong*)pValue).ToString("X16", null); default: - Contract.Assert(false, "Invalid Object type in Format"); + Debug.Assert(false, "Invalid Object type in Format"); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } } @@ -104,7 +105,7 @@ namespace System return ((UInt64)(Int64)value).ToString("X16", null); // All unsigned types will be directly cast default: - Contract.Assert(false, "Invalid Object type in Format"); + Debug.Assert(false, "Invalid Object type in Format"); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } } @@ -155,7 +156,7 @@ namespace System String[] names = entry.Names; ulong[] values = entry.Values; - Contract.Assert(names.Length == values.Length); + Debug.Assert(names.Length == values.Length); int index = values.Length - 1; StringBuilder retval = new StringBuilder(); @@ -243,7 +244,7 @@ namespace System break; // All unsigned types will be directly cast default: - Contract.Assert(false, "Invalid Object type in ToUInt64"); + Debug.Assert(false, "Invalid Object type in ToUInt64"); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } @@ -322,7 +323,7 @@ namespace System return m_innerException; default: - Contract.Assert(false, "Unknown EnumParseFailure: " + m_failure); + Debug.Assert(false, "Unknown EnumParseFailure: " + m_failure); return new ArgumentException(Environment.GetResourceString("Arg_EnumValueNotFound")); } } @@ -757,7 +758,7 @@ namespace System case CorElementType.U: return *(UIntPtr*)pValue; default: - Contract.Assert(false, "Invalid primitive type"); + Debug.Assert(false, "Invalid primitive type"); return null; } } @@ -809,7 +810,7 @@ namespace System return *(uint*)pValue; } default: - Contract.Assert(false, "Invalid primitive type"); + Debug.Assert(false, "Invalid primitive type"); return 0; } } @@ -866,7 +867,7 @@ namespace System case CorElementType.U: return (*(UIntPtr*)pValue).GetHashCode(); default: - Contract.Assert(false, "Invalid primitive type"); + Debug.Assert(false, "Invalid primitive type"); return 0; } } @@ -922,7 +923,7 @@ namespace System else { // assert valid return code (3) - Contract.Assert(ret == retInvalidEnumType, "Enum.InternalCompareTo return code was invalid"); + Debug.Assert(ret == retInvalidEnumType, "Enum.InternalCompareTo return code was invalid"); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } @@ -1030,7 +1031,7 @@ namespace System return TypeCode.Char; } - Contract.Assert(false, "Unknown underlying type."); + Debug.Assert(false, "Unknown underlying type."); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } diff --git a/src/mscorlib/src/System/Environment.cs b/src/mscorlib/src/System/Environment.cs index febf465..1580180 100644 --- a/src/mscorlib/src/System/Environment.cs +++ b/src/mscorlib/src/System/Environment.cs @@ -91,7 +91,7 @@ namespace System { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] internal String GetResourceString(String key) { if (key == null || key.Length == 0) { - Contract.Assert(false, "Environment::GetResourceString with null or empty key. Bug in caller, or weird recursive loading problem?"); + Debug.Assert(false, "Environment::GetResourceString with null or empty key. Bug in caller, or weird recursive loading problem?"); return "[Resource lookup failed - null or empty resource name]"; } @@ -182,7 +182,7 @@ namespace System { String s = rh.SystemResMgr.GetString(key, null); rh.currentlyLoading.RemoveAt(rh.currentlyLoading.Count - 1); // Pop - Contract.Assert(s!=null, "Managed resource string lookup failed. Was your resource name misspelled? Did you rebuild mscorlib after adding a resource to resources.txt? Debug this w/ cordbg and bug whoever owns the code that called Environment.GetResourceString. Resource name was: \""+key+"\""); + Debug.Assert(s!=null, "Managed resource string lookup failed. Was your resource name misspelled? Did you rebuild mscorlib after adding a resource to resources.txt? Debug this w/ cordbg and bug whoever owns the code that called Environment.GetResourceString. Resource name was: \""+key+"\""); userData.m_retVal = s; } @@ -308,7 +308,7 @@ namespace System { get { StringBuilder sb = new StringBuilder(Path.MaxPath); int r = Win32Native.GetSystemDirectory(sb, Path.MaxPath); - Contract.Assert(r < Path.MaxPath, "r < Path.MaxPath"); + Debug.Assert(r < Path.MaxPath, "r < Path.MaxPath"); if (r==0) __Error.WinIOError(); String path = sb.ToString(); @@ -322,7 +322,7 @@ namespace System { get { StringBuilder sb = new StringBuilder(Path.MaxPath); int r = Win32Native.GetWindowsDirectory(sb, Path.MaxPath); - Contract.Assert(r < Path.MaxPath, "r < Path.MaxPath"); + Debug.Assert(r < Path.MaxPath, "r < Path.MaxPath"); if (r==0) __Error.WinIOError(); String path = sb.ToString(); @@ -631,7 +631,7 @@ namespace System { Version v = new Version(osvi.MajorVersion, osvi.MinorVersion, osvi.BuildNumber, (osviEx.ServicePackMajor << 16) |osviEx.ServicePackMinor); m_os = new OperatingSystem(id, v, osvi.CSDVersion); } - Contract.Assert(m_os != null, "m_os != null"); + Debug.Assert(m_os != null, "m_os != null"); return m_os; } } diff --git a/src/mscorlib/src/System/Exception.cs b/src/mscorlib/src/System/Exception.cs index 881c9a3..a8ee328 100644 --- a/src/mscorlib/src/System/Exception.cs +++ b/src/mscorlib/src/System/Exception.cs @@ -451,7 +451,7 @@ namespace System { result.Append(separator); result.Append(rci.ToString()); } else { - Contract.Assert(methBase is MethodInfo, "[Exception.GetExceptionMethodString]methBase is MethodInfo"); + Debug.Assert(methBase is MethodInfo, "[Exception.GetExceptionMethodString]methBase is MethodInfo"); RuntimeMethodInfo rmi = (RuntimeMethodInfo)methBase; Type t = rmi.DeclaringType; result.Append((int)MemberTypes.Method); @@ -472,7 +472,7 @@ namespace System { } private MethodBase GetExceptionMethodFromString() { - Contract.Assert(_exceptionMethodString != null, "Method string cannot be NULL!"); + Debug.Assert(_exceptionMethodString != null, "Method string cannot be NULL!"); String[] args = _exceptionMethodString.Split(new char[]{'\0', '\n'}); if (args.Length!=5) { throw new SerializationException(); @@ -559,7 +559,7 @@ namespace System { // often created in the VM with AllocateObject instead if the managed construtor) // If you are adding code to use a SafeSerializationManager from an mscorlib exception, update // this assert to ensure that it fails when that exception's _safeSerializationManager is NULL - Contract.Assert(((_safeSerializationManager != null) || (this.GetType().Assembly == typeof(object).Assembly)), + Debug.Assert(((_safeSerializationManager != null) || (this.GetType().Assembly == typeof(object).Assembly)), "User defined exceptions must have a valid _safeSerializationManager"); // Handle serializing any transparent or partial trust subclass data diff --git a/src/mscorlib/src/System/Globalization/Calendar.cs b/src/mscorlib/src/System/Globalization/Calendar.cs index c2e809f..d046038 100644 --- a/src/mscorlib/src/System/Globalization/Calendar.cs +++ b/src/mscorlib/src/System/Globalization/Calendar.cs @@ -7,6 +7,7 @@ namespace System.Globalization { using System.Runtime.CompilerServices; using System.Globalization; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; // This abstract class represents a calendar. A calendar reckons time in @@ -229,7 +230,7 @@ namespace System.Globalization { get { // The following code assumes that the current era value can not be -1. if (m_currentEraValue == -1) { - Contract.Assert(BaseCalendarID > 0, "[Calendar.CurrentEraValue] Expected ID > 0"); + Debug.Assert(BaseCalendarID > 0, "[Calendar.CurrentEraValue] Expected ID > 0"); m_currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra; } return (m_currentEraValue); @@ -529,7 +530,7 @@ namespace System.Globalization { // this value can be less than 0. It's fine since we are making it positive again in calculating offset. int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7); int offset = (dayForJan1 - firstDayOfWeek + 14) % 7; - Contract.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0"); + Debug.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0"); return ((dayOfYear + offset) / 7 + 1); } diff --git a/src/mscorlib/src/System/Globalization/CalendarData.cs b/src/mscorlib/src/System/Globalization/CalendarData.cs index 7f21c1f..6f583fb 100644 --- a/src/mscorlib/src/System/Globalization/CalendarData.cs +++ b/src/mscorlib/src/System/Globalization/CalendarData.cs @@ -9,6 +9,7 @@ namespace System.Globalization using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; // // List of calendar data @@ -121,7 +122,7 @@ namespace System.Globalization this.bUseUserOverrides = bUseUserOverrides; if (!nativeGetCalendarData(this, localeName, calendarId)) { - Contract.Assert(false, "[CalendarData] nativeGetCalendarData call isn't expected to fail for calendar " + calendarId + " locale " +localeName); + Debug.Assert(false, "[CalendarData] nativeGetCalendarData call isn't expected to fail for calendar " + calendarId + " locale " +localeName); // Something failed, try invariant for missing parts // This is really not good, but we don't want the callers to crash. diff --git a/src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs b/src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs index 7084511..1113cd5 100644 --- a/src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs +++ b/src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs @@ -5,6 +5,7 @@ namespace System.Globalization { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; internal class CalendricalCalculationsHelper @@ -153,7 +154,7 @@ namespace System.Globalization // the following formulas defines a polynomial function which gives us the amount that the earth is slowing down for specific year ranges static double DefaultEphemerisCorrection(int gregorianYear) { - Contract.Assert(gregorianYear < 1620 || 2020 <= gregorianYear); + Debug.Assert(gregorianYear < 1620 || 2020 <= gregorianYear); long january1stOfYear = GetNumberOfDays(new DateTime(gregorianYear, 1, 1)); double daysSinceStartOf1810 = january1stOfYear - StartOf1810; double x = TwelveHours + daysSinceStartOf1810; @@ -162,34 +163,34 @@ namespace System.Globalization static double EphemerisCorrection1988to2019(int gregorianYear) { - Contract.Assert(1988 <= gregorianYear && gregorianYear <= 2019); + Debug.Assert(1988 <= gregorianYear && gregorianYear <= 2019); return (double)(gregorianYear - 1933) / SecondsPerDay; } static double EphemerisCorrection1900to1987(int gregorianYear) { - Contract.Assert(1900 <= gregorianYear && gregorianYear <= 1987); + Debug.Assert(1900 <= gregorianYear && gregorianYear <= 1987); double centuriesFrom1900 = CenturiesFrom1900(gregorianYear); return PolynomialSum(Coefficients1900to1987, centuriesFrom1900); } static double EphemerisCorrection1800to1899(int gregorianYear) { - Contract.Assert(1800 <= gregorianYear && gregorianYear <= 1899); + Debug.Assert(1800 <= gregorianYear && gregorianYear <= 1899); double centuriesFrom1900 = CenturiesFrom1900(gregorianYear); return PolynomialSum(Coefficients1800to1899, centuriesFrom1900); } static double EphemerisCorrection1700to1799(int gregorianYear) { - Contract.Assert(1700 <= gregorianYear && gregorianYear <= 1799); + Debug.Assert(1700 <= gregorianYear && gregorianYear <= 1799); double yearsSince1700 = gregorianYear - 1700; return PolynomialSum(Coefficients1700to1799, yearsSince1700) / SecondsPerDay; } static double EphemerisCorrection1620to1699(int gregorianYear) { - Contract.Assert(1620 <= gregorianYear && gregorianYear <= 1699); + Debug.Assert(1620 <= gregorianYear && gregorianYear <= 1699); double yearsSince1600 = gregorianYear - 1600; return PolynomialSum(Coefficients1620to1699, yearsSince1600) / SecondsPerDay; } @@ -216,7 +217,7 @@ namespace System.Globalization } } - Contract.Assert(false, "Not expected to come here"); + Debug.Assert(false, "Not expected to come here"); return DefaultEphemerisCorrection(year); } @@ -405,7 +406,7 @@ namespace System.Globalization break; } } - Contract.Assert(day != upperBoundNewYearDay); + Debug.Assert(day != upperBoundNewYearDay); return day - 1; } diff --git a/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs b/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs index d26e04b..2822b41 100644 --- a/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs +++ b/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs @@ -23,6 +23,7 @@ namespace System.Globalization { using System.Runtime.Versioning; using System.Reflection; using System.Security; + using System.Diagnostics; using System.Diagnostics.Contracts; @@ -137,8 +138,8 @@ namespace System.Globalization { //////////////////////////////////////////////////////////////////////// internal static int InternalConvertToUtf32(String s, int index) { - Contract.Assert(s != null, "s != null"); - Contract.Assert(index >= 0 && index < s.Length, "index < s.Length"); + Debug.Assert(s != null, "s != null"); + Debug.Assert(index >= 0 && index < s.Length, "index < s.Length"); if (index < s.Length - 1) { int temp1 = (int)s[index] - HIGH_SURROGATE_START; if (temp1 >= 0 && temp1 <= 0x3ff) { @@ -175,9 +176,9 @@ namespace System.Globalization { //////////////////////////////////////////////////////////////////////// internal static int InternalConvertToUtf32(String s, int index, out int charLength) { - Contract.Assert(s != null, "s != null"); - Contract.Assert(s.Length > 0, "s.Length > 0"); - Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length"); + Debug.Assert(s != null, "s != null"); + Debug.Assert(s.Length > 0, "s.Length > 0"); + Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length"); charLength = 1; if (index < s.Length - 1) { int temp1 = (int)s[index] - HIGH_SURROGATE_START; @@ -203,8 +204,8 @@ namespace System.Globalization { internal static bool IsWhiteSpace(String s, int index) { - Contract.Assert(s != null, "s!=null"); - Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length"); + Debug.Assert(s != null, "s!=null"); + Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length"); UnicodeCategory uc = GetUnicodeCategory(s, index); // In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator". @@ -240,7 +241,7 @@ namespace System.Globalization { // Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character // internal unsafe static double InternalGetNumericValue(int ch) { - Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); + Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); // Get the level 2 item from the highest 12 bit (8 - 19) of ch. ushort index = s_pNumericLevel1Index[ch >> 8]; // Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table. @@ -272,7 +273,7 @@ namespace System.Globalization { // Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character // internal unsafe static DigitValues* InternalGetDigitValues(int ch) { - Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); + Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); // Get the level 2 item from the highest 12 bit (8 - 19) of ch. ushort index = s_pNumericLevel1Index[ch >> 8]; // Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table. @@ -432,7 +433,7 @@ namespace System.Globalization { //////////////////////////////////////////////////////////////////////// internal unsafe static byte InternalGetCategoryValue(int ch, int offset) { - Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); + Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); // Get the level 2 item from the highest 12 bit (8 - 19) of ch. ushort index = s_pCategoryLevel1Index[ch >> 8]; // Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table. @@ -446,7 +447,7 @@ namespace System.Globalization { // Make sure that OtherNotAssigned is the last category in UnicodeCategory. // If that changes, change the following assertion as well. // - //Contract.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category"); + //Debug.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category"); return (uc); } @@ -478,8 +479,8 @@ namespace System.Globalization { //////////////////////////////////////////////////////////////////////// internal static UnicodeCategory InternalGetUnicodeCategory(String value, int index) { - Contract.Assert(value != null, "value can not be null"); - Contract.Assert(index < value.Length, "index < value.Length"); + Debug.Assert(value != null, "value can not be null"); + Debug.Assert(index < value.Length, "index < value.Length"); return (InternalGetUnicodeCategory(InternalConvertToUtf32(value, index))); } @@ -492,15 +493,15 @@ namespace System.Globalization { //////////////////////////////////////////////////////////////////////// internal static UnicodeCategory InternalGetUnicodeCategory(String str, int index, out int charLength) { - Contract.Assert(str != null, "str can not be null"); - Contract.Assert(str.Length > 0, "str.Length > 0");; - Contract.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length"); + Debug.Assert(str != null, "str can not be null"); + Debug.Assert(str.Length > 0, "str.Length > 0");; + Debug.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length"); return (InternalGetUnicodeCategory(InternalConvertToUtf32(str, index, out charLength))); } internal static bool IsCombiningCategory(UnicodeCategory uc) { - Contract.Assert(uc >= 0, "uc >= 0"); + Debug.Assert(uc >= 0, "uc >= 0"); return ( uc == UnicodeCategory.NonSpacingMark || uc == UnicodeCategory.SpacingCombiningMark || diff --git a/src/mscorlib/src/System/Globalization/CompareInfo.cs b/src/mscorlib/src/System/Globalization/CompareInfo.cs index aed3983..dcf1f32 100644 --- a/src/mscorlib/src/System/Globalization/CompareInfo.cs +++ b/src/mscorlib/src/System/Globalization/CompareInfo.cs @@ -32,6 +32,7 @@ namespace System.Globalization { using System.Security.Permissions; using Microsoft.Win32; using System.Security; + using System.Diagnostics; using System.Diagnostics.Contracts; // @@ -290,7 +291,7 @@ namespace System.Globalization { #if FEATURE_USE_LCID // This is merely for serialization compatibility with Whidbey/Orcas, it can go away when we don't want that compat any more. culture = CultureInfo.GetCultureInfo(this.Name).LCID; // This is the lcid of the constructing culture (still have to dereference to get target sort) - Contract.Assert(m_name != null, "CompareInfo.OnSerializing - expected m_name to be set already"); + Debug.Assert(m_name != null, "CompareInfo.OnSerializing - expected m_name to be set already"); #endif } @@ -320,7 +321,7 @@ namespace System.Globalization { { get { - Contract.Assert(m_name != null, "CompareInfo.Name Expected m_name to be set"); + Debug.Assert(m_name != null, "CompareInfo.Name Expected m_name to be set"); return (m_sortName); } } @@ -346,7 +347,7 @@ namespace System.Globalization { // some NLS VM functions can handle COMPARE_OPTIONS_ORDINAL // in which case options should be simply cast to int instead of using this function // Does not look like the best approach to me but for now I am going to leave it as it is - Contract.Assert(options != CompareOptions.OrdinalIgnoreCase, "[CompareInfo.GetNativeCompareFlags]CompareOptions.OrdinalIgnoreCase should be handled separately"); + Debug.Assert(options != CompareOptions.OrdinalIgnoreCase, "[CompareInfo.GetNativeCompareFlags]CompareOptions.OrdinalIgnoreCase should be handled separately"); // Use "linguistic casing" by default (load the culture's casing exception tables) int nativeCompareFlags = NORM_LINGUISTIC_CASING; @@ -361,7 +362,7 @@ namespace System.Globalization { // Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; } - Contract.Assert(((options & ~(CompareOptions.IgnoreCase | + Debug.Assert(((options & ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreSymbols | @@ -369,7 +370,7 @@ namespace System.Globalization { CompareOptions.StringSort)) == 0) || (options == CompareOptions.Ordinal), "[CompareInfo.GetNativeCompareFlags]Expected all flags to be handled"); - Contract.Assert((nativeCompareFlags & RESERVED_FIND_ASCII_STRING) == 0, "[CompareInfo.GetNativeCompareFlags] RESERVED_FIND_ASCII_STRING shouldn't be set here"); + Debug.Assert((nativeCompareFlags & RESERVED_FIND_ASCII_STRING) == 0, "[CompareInfo.GetNativeCompareFlags] RESERVED_FIND_ASCII_STRING shouldn't be set here"); return nativeCompareFlags; } diff --git a/src/mscorlib/src/System/Globalization/CultureData.cs b/src/mscorlib/src/System/Globalization/CultureData.cs index f39ffbc..0bcb796 100644 --- a/src/mscorlib/src/System/Globalization/CultureData.cs +++ b/src/mscorlib/src/System/Globalization/CultureData.cs @@ -13,6 +13,7 @@ namespace System.Globalization using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; @@ -791,7 +792,7 @@ namespace System.Globalization private static bool IsReplacementCultureName(String name) { - Contract.Assert(name != null, "IsReplacementCultureName(): name should not be null"); + Debug.Assert(name != null, "IsReplacementCultureName(): name should not be null"); String[] replacementCultureNames = s_replacementCultureNames; if (replacementCultureNames == null) { @@ -801,7 +802,7 @@ namespace System.Globalization } // Even if we don't have any replacement cultures, the returned replacementCultureNames will still an empty string array, not null. - Contract.Assert(name != null, "IsReplacementCultureName(): replacementCultureNames should not be null"); + Debug.Assert(name != null, "IsReplacementCultureName(): replacementCultureNames should not be null"); Array.Sort(replacementCultureNames); s_replacementCultureNames = replacementCultureNames; } @@ -825,7 +826,7 @@ namespace System.Globalization { get { - Contract.Assert(this.sRealName != null, "[CultureData.CultureName] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(this.sRealName != null, "[CultureData.CultureName] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already"); // since windows doesn't know about zh-CHS and zh-CHT, // we leave sRealName == zh-Hanx but we still need to // pretend that it was zh-CHX. @@ -853,7 +854,7 @@ namespace System.Globalization { get { - // Contract.Assert(this.sName != null, + // Debug.Assert(this.sName != null, // "[CultureData.SNAME] Expected this.sName to be populated by COMNlsInfo::nativeInitCultureData already"); if (this.sName == null) { @@ -985,7 +986,7 @@ namespace System.Globalization get { // This got populated when ComNlsInfo::nativeInitCultureData told us we had a culture - Contract.Assert(this.sSpecificCulture != null, "[CultureData.SSPECIFICCULTURE] Expected this.sSpecificCulture to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(this.sSpecificCulture != null, "[CultureData.SSPECIFICCULTURE] Expected this.sSpecificCulture to be populated by COMNlsInfo::nativeInitCultureData already"); return this.sSpecificCulture; } } @@ -1844,7 +1845,7 @@ namespace System.Globalization // We then have to copy that list to a new array of the right size. // Default calendar should be first int[] calendarInts = new int[23]; - Contract.Assert(this.sWindowsName != null, "[CultureData.CalendarIds] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(this.sWindowsName != null, "[CultureData.CalendarIds] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); int count = CalendarData.nativeGetCalendars(this.sWindowsName, this.bUseOverrides, calendarInts); // See if we had a calendar to add. @@ -1916,7 +1917,7 @@ namespace System.Globalization internal CalendarData GetCalendar(int calendarId) { - Contract.Assert(calendarId > 0 && calendarId <= CalendarData.MAX_CALENDARS, + Debug.Assert(calendarId > 0 && calendarId <= CalendarData.MAX_CALENDARS, "[CultureData.GetCalendar] Expect calendarId to be in a valid range"); // arrays are 0 based, calendarIds are 1 based @@ -1935,7 +1936,7 @@ namespace System.Globalization // Make sure that calendar has data if (calendarData == null || UseUserOverride) { - Contract.Assert(this.sWindowsName != null, "[CultureData.GetCalendar] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(this.sWindowsName != null, "[CultureData.GetCalendar] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); calendarData = new CalendarData(this.sWindowsName, calendarId, this.UseUserOverride); calendars[calendarIndex] = calendarData; } @@ -1980,7 +1981,7 @@ namespace System.Globalization { if (this.iReadingLayout == undef) { - Contract.Assert(this.sRealName != null, "[CultureData.IsRightToLeft] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(this.sRealName != null, "[CultureData.IsRightToLeft] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already"); this.iReadingLayout = DoGetLocaleInfoInt(LOCALE_IREADINGLAYOUT); } @@ -2157,7 +2158,7 @@ namespace System.Globalization { if (this.iLanguage == 0) { - Contract.Assert(this.sRealName != null, "[CultureData.ILANGUAGE] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(this.sRealName != null, "[CultureData.ILANGUAGE] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already"); this.iLanguage = LocaleNameToLCID(this.sRealName); } return this.iLanguage; @@ -2213,21 +2214,21 @@ namespace System.Globalization // All of our era names internal String[] EraNames(int calendarId) { - Contract.Assert(calendarId > 0, "[CultureData.saEraNames] Expected Calendar.ID > 0"); + Debug.Assert(calendarId > 0, "[CultureData.saEraNames] Expected Calendar.ID > 0"); return this.GetCalendar(calendarId).saEraNames; } internal String[] AbbrevEraNames(int calendarId) { - Contract.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0"); + Debug.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0"); return this.GetCalendar(calendarId).saAbbrevEraNames; } internal String[] AbbreviatedEnglishEraNames(int calendarId) { - Contract.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0"); + Debug.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0"); return this.GetCalendar(calendarId).saAbbrevEnglishEraNames; } @@ -2484,8 +2485,8 @@ namespace System.Globalization private static int IndexOfTimePart(string format, int startIndex, string timeParts) { - Contract.Assert(startIndex >= 0, "startIndex cannot be negative"); - Contract.Assert(timeParts.IndexOfAny(new char[] { '\'', '\\' }) == -1, "timeParts cannot include quote characters"); + Debug.Assert(startIndex >= 0, "startIndex cannot be negative"); + Debug.Assert(timeParts.IndexOfAny(new char[] { '\'', '\\' }) == -1, "timeParts cannot include quote characters"); bool inQuote = false; for (int i = startIndex; i < format.Length; ++i) { @@ -2522,7 +2523,7 @@ namespace System.Globalization string DoGetLocaleInfo(uint lctype) { - Contract.Assert(this.sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(this.sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); return DoGetLocaleInfo(this.sWindowsName, lctype); } @@ -2537,7 +2538,7 @@ namespace System.Globalization } // Ask OS for data - Contract.Assert(localeName != null, "[CultureData.DoGetLocaleInfo] Expected localeName to be not be null"); + Debug.Assert(localeName != null, "[CultureData.DoGetLocaleInfo] Expected localeName to be not be null"); string result = CultureInfo.nativeGetLocaleInfoEx(localeName, lctype); if (result == null) { @@ -2558,7 +2559,7 @@ namespace System.Globalization // Ask OS for data, note that we presume it returns success, so we have to know that // sWindowsName is valid before calling. - Contract.Assert(this.sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(this.sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); int result = CultureInfo.nativeGetLocaleInfoExInt(this.sWindowsName, lctype); return result; @@ -2567,7 +2568,7 @@ namespace System.Globalization String[] DoEnumTimeFormats() { // Note that this gets overrides for us all the time - Contract.Assert(this.sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(this.sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(this.sWindowsName, 0, UseUserOverride)); return result; @@ -2576,7 +2577,7 @@ namespace System.Globalization String[] DoEnumShortTimeFormats() { // Note that this gets overrides for us all the time - Contract.Assert(this.sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(this.sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(this.sWindowsName, TIME_NOSECONDS, UseUserOverride)); return result; @@ -2638,7 +2639,7 @@ namespace System.Globalization // // Ask native side for our data. // - Contract.Assert(this.sWindowsName != null, "[CultureData.GetNFIValues] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(this.sWindowsName != null, "[CultureData.GetNFIValues] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); CultureData.nativeGetNumberFormatInfoValues(this.sWindowsName, nfi, UseUserOverride); } diff --git a/src/mscorlib/src/System/Globalization/CultureInfo.cs b/src/mscorlib/src/System/Globalization/CultureInfo.cs index fe5f8aa..fd9b0ed 100644 --- a/src/mscorlib/src/System/Globalization/CultureInfo.cs +++ b/src/mscorlib/src/System/Globalization/CultureInfo.cs @@ -39,6 +39,7 @@ namespace System.Globalization { using System.Security.Permissions; using System.Reflection; using Microsoft.Win32; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Resources; @@ -403,13 +404,13 @@ namespace System.Globalization { // e.g. for es-ES_tradnl: v2 puts es-ES in m_name; v4 puts es-ES_tradnl if (m_name == null || IsAlternateSortLcid(cultureID)) { - Contract.Assert(cultureID >=0, "[CultureInfo.OnDeserialized] cultureID >= 0"); + Debug.Assert(cultureID >=0, "[CultureInfo.OnDeserialized] cultureID >= 0"); InitializeFromCultureId(cultureID, m_useUserOverride); } else { #endif - Contract.Assert(m_name != null, "[CultureInfo.OnDeserialized] m_name != null"); + Debug.Assert(m_name != null, "[CultureInfo.OnDeserialized] m_name != null"); this.m_cultureData = CultureData.GetCultureData(m_name, m_useUserOverride); if (this.m_cultureData == null) @@ -476,14 +477,14 @@ namespace System.Globalization { // For Silverlight, the answer is always no. internal bool IsSafeCrossDomain { get { - Contract.Assert(m_createdDomainID != 0, "[CultureInfo.IsSafeCrossDomain] m_createdDomainID != 0"); + Debug.Assert(m_createdDomainID != 0, "[CultureInfo.IsSafeCrossDomain] m_createdDomainID != 0"); return m_isSafeCrossDomain; } } internal int CreatedDomainID { get { - Contract.Assert(m_createdDomainID != 0, "[CultureInfo.CreatedDomain] m_createdDomainID != 0"); + Debug.Assert(m_createdDomainID != 0, "[CultureInfo.CreatedDomain] m_createdDomainID != 0"); return m_createdDomainID; } } @@ -634,7 +635,7 @@ namespace System.Globalization { } internal static bool VerifyCultureName(CultureInfo culture, bool throwException) { - Contract.Assert(culture!=null, "[CultureInfo.VerifyCultureName]culture!=null"); + Debug.Assert(culture!=null, "[CultureInfo.VerifyCultureName]culture!=null"); //If we have an instance of one of our CultureInfos, the user can't have changed the //name and we know that all names are valid in files. @@ -1041,7 +1042,7 @@ namespace System.Globalization { get { Contract.Ensures(Contract.Result() != null); - Contract.Assert(m_name != null, "[CultureInfo.DisplayName]Always expect m_name to be set"); + Debug.Assert(m_name != null, "[CultureInfo.DisplayName]Always expect m_name to be set"); return m_cultureData.SLOCALIZEDDISPLAYNAME; } @@ -1234,7 +1235,7 @@ namespace System.Globalization { { Contract.Ensures(Contract.Result() != null); - Contract.Assert(m_name != null, "[CultureInfo.ToString]Always expect m_name to be set"); + Debug.Assert(m_name != null, "[CultureInfo.ToString]Always expect m_name to be set"); return m_name; } @@ -1374,7 +1375,7 @@ namespace System.Globalization { //This function exists as a shortcut to prevent us from loading all of the non-gregorian //calendars unless they're required. internal static Calendar GetCalendarInstanceRare(int calType) { - Contract.Assert(calType!=Calendar.CAL_GREGORIAN, "calType!=Calendar.CAL_GREGORIAN"); + Debug.Assert(calType!=Calendar.CAL_GREGORIAN, "calType!=Calendar.CAL_GREGORIAN"); switch (calType) { case Calendar.CAL_GREGORIAN_US: // Gregorian (U.S.) calendar @@ -1426,7 +1427,7 @@ namespace System.Globalization { get { Contract.Ensures(Contract.Result() != null); if (calendar == null) { - Contract.Assert(this.m_cultureData.CalendarIds.Length > 0, "this.m_cultureData.CalendarIds.Length > 0"); + Debug.Assert(this.m_cultureData.CalendarIds.Length > 0, "this.m_cultureData.CalendarIds.Length > 0"); // Get the default calendar for this culture. Note that the value can be // from registry if this is a user default culture. Calendar newObj = this.m_cultureData.DefaultCalendar; @@ -1887,7 +1888,7 @@ namespace System.Globalization { private static String GetDefaultLocaleName(int localeType) { - Contract.Assert(localeType == LOCALE_USER_DEFAULT || localeType == LOCALE_SYSTEM_DEFAULT, "[CultureInfo.GetDefaultLocaleName] localeType must be LOCALE_USER_DEFAULT or LOCALE_SYSTEM_DEFAULT"); + Debug.Assert(localeType == LOCALE_USER_DEFAULT || localeType == LOCALE_SYSTEM_DEFAULT, "[CultureInfo.GetDefaultLocaleName] localeType must be LOCALE_USER_DEFAULT or LOCALE_SYSTEM_DEFAULT"); string localeName = null; if(InternalGetDefaultLocaleName(localeType, JitHelpers.GetStringHandleOnStack(ref localeName))) diff --git a/src/mscorlib/src/System/Globalization/DateTimeFormat.cs b/src/mscorlib/src/System/Globalization/DateTimeFormat.cs index 10aa1cf..c6e0591 100644 --- a/src/mscorlib/src/System/Globalization/DateTimeFormat.cs +++ b/src/mscorlib/src/System/Globalization/DateTimeFormat.cs @@ -11,6 +11,7 @@ namespace System { using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; + using System.Diagnostics; using System.Diagnostics.Contracts; /* @@ -171,12 +172,12 @@ namespace System { // //////////////////////////////////////////////////////////////////////////// internal static void FormatDigits(StringBuilder outputBuffer, int value, int len) { - Contract.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0"); + Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0"); FormatDigits(outputBuffer, value, len, false); } internal unsafe static void FormatDigits(StringBuilder outputBuffer, int value, int len, bool overrideLengthLimit) { - Contract.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0"); + Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0"); // Limit the use of this function to be two-digits, so that we have the same behavior // as RTM bits. @@ -222,7 +223,7 @@ namespace System { private static String FormatDayOfWeek(int dayOfWeek, int repeat, DateTimeFormatInfo dtfi) { - Contract.Assert(dayOfWeek >= 0 && dayOfWeek <= 6, "dayOfWeek >= 0 && dayOfWeek <= 6"); + Debug.Assert(dayOfWeek >= 0 && dayOfWeek <= 6, "dayOfWeek >= 0 && dayOfWeek <= 6"); if (repeat == 3) { return (dtfi.GetAbbreviatedDayName((DayOfWeek)dayOfWeek)); @@ -234,7 +235,7 @@ namespace System { private static String FormatMonth(int month, int repeatCount, DateTimeFormatInfo dtfi) { - Contract.Assert(month >=1 && month <= 12, "month >=1 && month <= 12"); + Debug.Assert(month >=1 && month <= 12, "month >=1 && month <= 12"); if (repeatCount == 3) { return (dtfi.GetAbbreviatedMonthName(month)); @@ -275,7 +276,7 @@ namespace System { */ private static String FormatHebrewMonthName(DateTime time, int month, int repeatCount, DateTimeFormatInfo dtfi) { - Contract.Assert(repeatCount != 3 || repeatCount != 4, "repeateCount should be 3 or 4"); + Debug.Assert(repeatCount != 3 || repeatCount != 4, "repeateCount should be 3 or 4"); if (dtfi.Calendar.IsLeapYear(dtfi.Calendar.GetYear(time))) { // This month is in a leap year return (dtfi.internalGetMonthName(month, MonthNameStyles.LeapYear, (repeatCount == 3))); @@ -1044,7 +1045,7 @@ namespace System { index++; } - Contract.Assert(val == 0, "DateTimeFormat.AppendNumber(): digits less than size of val"); + Debug.Assert(val == 0, "DateTimeFormat.AppendNumber(): digits less than size of val"); } internal static String[] GetAllDateTimes(DateTime dateTime, char format, DateTimeFormatInfo dtfi) diff --git a/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs b/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs index f9b5ddf..14cdeb6 100644 --- a/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs +++ b/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs @@ -14,6 +14,7 @@ namespace System.Globalization { using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; + using System.Diagnostics; using System.Diagnostics.Contracts; // @@ -230,7 +231,7 @@ namespace System.Globalization { { // Get the abbreviated day names for our current calendar this.abbreviatedDayNames = this.m_cultureData.AbbreviatedDayNames(Calendar.ID); - Contract.Assert(this.abbreviatedDayNames.Length == 7, "[DateTimeFormatInfo.GetAbbreviatedDayOfWeekNames] Expected 7 day names in a week"); + Debug.Assert(this.abbreviatedDayNames.Length == 7, "[DateTimeFormatInfo.GetAbbreviatedDayOfWeekNames] Expected 7 day names in a week"); } return (this.abbreviatedDayNames); } @@ -253,7 +254,7 @@ namespace System.Globalization { { // Get the super short day names for our current calendar this.m_superShortDayNames = this.m_cultureData.SuperShortDayNames(Calendar.ID); - Contract.Assert(this.m_superShortDayNames.Length == 7, "[DateTimeFormatInfo.internalGetSuperShortDayNames] Expected 7 day names in a week"); + Debug.Assert(this.m_superShortDayNames.Length == 7, "[DateTimeFormatInfo.internalGetSuperShortDayNames] Expected 7 day names in a week"); } return (this.m_superShortDayNames); } @@ -270,7 +271,7 @@ namespace System.Globalization { { // Get the day names for our current calendar this.dayNames = this.m_cultureData.DayNames(Calendar.ID); - Contract.Assert(this.dayNames.Length == 7, "[DateTimeFormatInfo.GetDayOfWeekNames] Expected 7 day names in a week"); + Debug.Assert(this.dayNames.Length == 7, "[DateTimeFormatInfo.GetDayOfWeekNames] Expected 7 day names in a week"); } return (this.dayNames); } @@ -287,7 +288,7 @@ namespace System.Globalization { { // Get the month names for our current calendar this.abbreviatedMonthNames = this.m_cultureData.AbbreviatedMonthNames(Calendar.ID); - Contract.Assert(this.abbreviatedMonthNames.Length == 12 || this.abbreviatedMonthNames.Length == 13, + Debug.Assert(this.abbreviatedMonthNames.Length == 12 || this.abbreviatedMonthNames.Length == 13, "[DateTimeFormatInfo.GetAbbreviatedMonthNames] Expected 12 or 13 month names in a year"); } return (this.abbreviatedMonthNames); @@ -306,7 +307,7 @@ namespace System.Globalization { { // Get the month names for our current calendar this.monthNames = this.m_cultureData.MonthNames(Calendar.ID); - Contract.Assert(this.monthNames.Length == 12 || this.monthNames.Length == 13, + Debug.Assert(this.monthNames.Length == 12 || this.monthNames.Length == 13, "[DateTimeFormatInfo.GetMonthNames] Expected 12 or 13 month names in a year"); } @@ -339,7 +340,7 @@ namespace System.Globalization { // Silverlight 2.0 never took a snapshot of the user's overridable properties // This has a substantial performance impact so skip when CoreCLR Contract.Requires(cultureData != null); - Contract.Assert(calendarID > 0, "[DateTimeFormatInfo.Populate] Expected Calendar.ID > 0"); + Debug.Assert(calendarID > 0, "[DateTimeFormatInfo.Populate] Expected Calendar.ID > 0"); if (this.firstDayOfWeek == -1) { this.firstDayOfWeek = cultureData.IFIRSTDAYOFWEEK; } if (this.calendarWeekRule == -1) { this.calendarWeekRule = cultureData.IFIRSTWEEKOFYEAR; } @@ -350,19 +351,19 @@ namespace System.Globalization { if (this.dateSeparator == null) { this.dateSeparator = cultureData.DateSeparator(calendarID); } this.allLongTimePatterns = this.m_cultureData.LongTimes; - Contract.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long time patterns"); + Debug.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long time patterns"); this.allShortTimePatterns = this.m_cultureData.ShortTimes; - Contract.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short time patterns"); + Debug.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short time patterns"); this.allLongDatePatterns = cultureData.LongDates(calendarID); - Contract.Assert(this.allLongDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long date patterns"); + Debug.Assert(this.allLongDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long date patterns"); this.allShortDatePatterns = cultureData.ShortDates(calendarID); - Contract.Assert(this.allShortDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short date patterns"); + Debug.Assert(this.allShortDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short date patterns"); this.allYearMonthPatterns = cultureData.YearMonths(calendarID); - Contract.Assert(this.allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some year month patterns"); + Debug.Assert(this.allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some year month patterns"); } #region Serialization @@ -546,7 +547,7 @@ namespace System.Globalization { this.amDesignator = this.m_cultureData.SAM1159; } - Contract.Assert(this.amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null"); + Debug.Assert(this.amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null"); return (this.amDesignator); } @@ -570,7 +571,7 @@ namespace System.Globalization { get { Contract.Ensures(Contract.Result() != null); - Contract.Assert(this.calendar != null, "DateTimeFormatInfo.Calendar: calendar != null"); + Debug.Assert(this.calendar != null, "DateTimeFormatInfo.Calendar: calendar != null"); return (this.calendar); } @@ -806,7 +807,7 @@ namespace System.Globalization { { if (this.m_abbrevEnglishEraNames == null) { - Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.AbbreviatedEnglishEraNames] Expected Calendar.ID > 0"); + Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.AbbreviatedEnglishEraNames] Expected Calendar.ID > 0"); this.m_abbrevEnglishEraNames = this.m_cultureData.AbbreviatedEnglishEraNames(Calendar.ID); } return (this.m_abbrevEnglishEraNames); @@ -825,7 +826,7 @@ namespace System.Globalization { this.dateSeparator = this.m_cultureData.DateSeparator(Calendar.ID); } - Contract.Assert(this.dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null"); + Debug.Assert(this.dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null"); return (this.dateSeparator); } @@ -854,7 +855,7 @@ namespace System.Globalization { this.firstDayOfWeek = this.m_cultureData.IFIRSTDAYOFWEEK; } - Contract.Assert(this.firstDayOfWeek != -1, "DateTimeFormatInfo.FirstDayOfWeek, firstDayOfWeek != -1"); + Debug.Assert(this.firstDayOfWeek != -1, "DateTimeFormatInfo.FirstDayOfWeek, firstDayOfWeek != -1"); return ((DayOfWeek)this.firstDayOfWeek); } @@ -881,7 +882,7 @@ namespace System.Globalization { this.calendarWeekRule = this.m_cultureData.IFIRSTWEEKOFYEAR; } - Contract.Assert(this.calendarWeekRule != -1, "DateTimeFormatInfo.CalendarWeekRule, calendarWeekRule != -1"); + Debug.Assert(this.calendarWeekRule != -1, "DateTimeFormatInfo.CalendarWeekRule, calendarWeekRule != -1"); return ((CalendarWeekRule)this.calendarWeekRule); } @@ -1012,10 +1013,10 @@ namespace System.Globalization { { if (this.monthDayPattern == null) { - Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.MonthDayPattern] Expected calID > 0"); + Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.MonthDayPattern] Expected calID > 0"); this.monthDayPattern = this.m_cultureData.MonthDay(Calendar.ID); } - Contract.Assert(this.monthDayPattern != null, "DateTimeFormatInfo.MonthDayPattern, monthDayPattern != null"); + Debug.Assert(this.monthDayPattern != null, "DateTimeFormatInfo.MonthDayPattern, monthDayPattern != null"); return (this.monthDayPattern); } @@ -1042,7 +1043,7 @@ namespace System.Globalization { this.pmDesignator = this.m_cultureData.SPM2359; } - Contract.Assert(this.pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null"); + Debug.Assert(this.pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null"); return (this.pmDesignator); } @@ -1263,7 +1264,7 @@ namespace System.Globalization { timeSeparator = this.m_cultureData.TimeSeparator; } - Contract.Assert(this.timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null"); + Debug.Assert(this.timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null"); return (timeSeparator); } @@ -1540,7 +1541,7 @@ namespace System.Globalization { if (this.m_genitiveAbbreviatedMonthNames == null) { this.m_genitiveAbbreviatedMonthNames = this.m_cultureData.AbbreviatedGenitiveMonthNames(this.Calendar.ID); - Contract.Assert(this.m_genitiveAbbreviatedMonthNames.Length == 13, + Debug.Assert(this.m_genitiveAbbreviatedMonthNames.Length == 13, "[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 abbreviated genitive month names in a year"); } return (this.m_genitiveAbbreviatedMonthNames); @@ -1549,7 +1550,7 @@ namespace System.Globalization { if (this.genitiveMonthNames == null) { this.genitiveMonthNames = this.m_cultureData.GenitiveMonthNames(this.Calendar.ID); - Contract.Assert(this.genitiveMonthNames.Length == 13, + Debug.Assert(this.genitiveMonthNames.Length == 13, "[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 genitive month names in a year"); } return (this.genitiveMonthNames); @@ -1565,9 +1566,9 @@ namespace System.Globalization { internal String[] internalGetLeapYearMonthNames(/*bool abbreviated*/) { if (this.leapYearMonthNames == null) { - Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expected Calendar.ID > 0"); + Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expected Calendar.ID > 0"); this.leapYearMonthNames = this.m_cultureData.LeapYearMonthNames(Calendar.ID); - Contract.Assert(this.leapYearMonthNames.Length == 13, + Debug.Assert(this.leapYearMonthNames.Length == 13, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expepcted 13 leap year month names"); } return (leapYearMonthNames); @@ -1760,9 +1761,9 @@ namespace System.Globalization { // The resulting [] can get returned to the calling app, so clone it. private static string[] GetMergedPatterns(string [] patterns, string defaultPattern) { - Contract.Assert(patterns != null && patterns.Length > 0, + Debug.Assert(patterns != null && patterns.Length > 0, "[DateTimeFormatInfo.GetMergedPatterns]Expected array of at least one pattern"); - Contract.Assert(defaultPattern != null, + Debug.Assert(defaultPattern != null, "[DateTimeFormatInfo.GetMergedPatterns]Expected non null default string"); // If the default happens to be the first in the list just return (a cloned) copy @@ -1859,9 +1860,9 @@ namespace System.Globalization { { if (this.allYearMonthPatterns == null) { - Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected Calendar.ID > 0"); + Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected Calendar.ID > 0"); this.allYearMonthPatterns = this.m_cultureData.YearMonths(this.Calendar.ID); - Contract.Assert(this.allYearMonthPatterns.Length > 0, + Debug.Assert(this.allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected some year month patterns"); } @@ -1878,9 +1879,9 @@ namespace System.Globalization { { if (allShortDatePatterns == null) { - Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected Calendar.ID > 0"); + Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected Calendar.ID > 0"); this.allShortDatePatterns = this.m_cultureData.ShortDates(this.Calendar.ID); - Contract.Assert(this.allShortDatePatterns.Length > 0, + Debug.Assert(this.allShortDatePatterns.Length > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected some short date patterns"); } @@ -1896,9 +1897,9 @@ namespace System.Globalization { { if (allLongDatePatterns == null) { - Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected Calendar.ID > 0"); + Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected Calendar.ID > 0"); this.allLongDatePatterns = this.m_cultureData.LongDates(this.Calendar.ID); - Contract.Assert(this.allLongDatePatterns.Length > 0, + Debug.Assert(this.allLongDatePatterns.Length > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected some long date patterns"); } @@ -1915,7 +1916,7 @@ namespace System.Globalization { if (this.allShortTimePatterns == null) { this.allShortTimePatterns = this.m_cultureData.ShortTimes; - Contract.Assert(this.allShortTimePatterns.Length > 0, + Debug.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.UnclonedShortTimePatterns] Expected some short time patterns"); } @@ -1932,7 +1933,7 @@ namespace System.Globalization { if (this.allLongTimePatterns == null) { this.allLongTimePatterns = this.m_cultureData.LongTimes; - Contract.Assert(this.allLongTimePatterns.Length > 0, + Debug.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.UnclonedLongTimePatterns] Expected some long time patterns"); } @@ -2653,7 +2654,7 @@ namespace System.Globalization { } while (i < str.Value.Length && (state != HebrewNumberParsingState.FoundEndOfHebrewNumber)); // When we are here, we are either at the end of the string, or we find a valid Hebrew number. - Contract.Assert(state == HebrewNumberParsingState.ContinueParsing || state == HebrewNumberParsingState.FoundEndOfHebrewNumber, + Debug.Assert(state == HebrewNumberParsingState.ContinueParsing || state == HebrewNumberParsingState.FoundEndOfHebrewNumber, "Invalid returned state from HebrewNumber.ParseByChar()"); if (state != HebrewNumberParsingState.FoundEndOfHebrewNumber) { @@ -2679,7 +2680,7 @@ namespace System.Globalization { tokenValue = 0; TokenHashValue value; - Contract.Assert(str.Index < str.Value.Length, "DateTimeFormatInfo.Tokenize(): start < value.Length"); + Debug.Assert(str.Index < str.Value.Length, "DateTimeFormatInfo.Tokenize(): start < value.Length"); char ch = str.m_current; bool isLetter = Char.IsLetter(ch); @@ -2788,7 +2789,7 @@ namespace System.Globalization { } previousNode = temp; } ; - Contract.Assert(false, "The hashtable is full. This should not happen."); + Debug.Assert(false, "The hashtable is full. This should not happen."); } void InsertHash(TokenHashValue[] hashTable, String str, TokenType tokenType, int tokenValue) { @@ -2859,7 +2860,7 @@ namespace System.Globalization { hashcode += hashProbe; if (hashcode >= TOKEN_HASH_SIZE) hashcode -= TOKEN_HASH_SIZE; } while (i < TOKEN_HASH_SIZE); - Contract.Assert(false, "The hashtable is full. This should not happen."); + Debug.Assert(false, "The hashtable is full. This should not happen."); } } // class DateTimeFormatInfo diff --git a/src/mscorlib/src/System/Globalization/DateTimeParse.cs b/src/mscorlib/src/System/Globalization/DateTimeParse.cs index 4364852..363747c 100644 --- a/src/mscorlib/src/System/Globalization/DateTimeParse.cs +++ b/src/mscorlib/src/System/Globalization/DateTimeParse.cs @@ -104,7 +104,7 @@ namespace System { return false; } - Contract.Assert(dtfi != null, "dtfi == null"); + Debug.Assert(dtfi != null, "dtfi == null"); return DoStrictParse(s, format, style, dtfi, ref result); } @@ -186,7 +186,7 @@ namespace System { return false; } - Contract.Assert(dtfi != null, "dtfi == null"); + Debug.Assert(dtfi != null, "dtfi == null"); // // Do a loop through the provided formats and see if we can parse succesfully in @@ -536,8 +536,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, // Wrong number of digits return false; } - Contract.Assert(hourOffset >= 0 && hourOffset <= 99, "hourOffset >= 0 && hourOffset <= 99"); - Contract.Assert(minuteOffset >= 0 && minuteOffset <= 99, "minuteOffset >= 0 && minuteOffset <= 99"); + Debug.Assert(hourOffset >= 0 && hourOffset <= 99, "hourOffset >= 0 && hourOffset <= 99"); + Debug.Assert(minuteOffset >= 0 && minuteOffset <= 99, "minuteOffset >= 0 && minuteOffset <= 99"); if (minuteOffset < 0 || minuteOffset >= 60) { return false; } @@ -1911,7 +1911,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, private static Boolean GetTimeOfNN(DateTimeFormatInfo dtfi, ref DateTimeResult result, ref DateTimeRawInfo raw) { - Contract.Assert(raw.numCount >= 2, "raw.numCount >= 2"); + Debug.Assert(raw.numCount >= 2, "raw.numCount >= 2"); if ((result.flags & ParseFlags.HaveTime) != 0) { // Multiple times in the input string result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null); @@ -1931,7 +1931,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null); return false; } - Contract.Assert(raw.numCount >= 3, "raw.numCount >= 3"); + Debug.Assert(raw.numCount >= 3, "raw.numCount >= 3"); result.Hour = raw.GetNumber(0); result.Minute = raw.GetNumber(1); result.Second = raw.GetNumber(2); @@ -2301,7 +2301,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, return false; } - Contract.Assert(dtfi != null, "dtfi == null"); + Debug.Assert(dtfi != null, "dtfi == null"); #if _LOGGING DTFITrace(dtfi); @@ -2564,7 +2564,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, } else { // No time zone and no Assume flags, so DateTimeKind.Unspecified is fine - Contract.Assert(result.parsedDate.Kind == DateTimeKind.Unspecified, "result.parsedDate.Kind == DateTimeKind.Unspecified"); + Debug.Assert(result.parsedDate.Kind == DateTimeKind.Unspecified, "result.parsedDate.Kind == DateTimeKind.Unspecified"); return true; } } @@ -2854,9 +2854,9 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, } internal static bool ParseDigits(ref __DTString str, int minDigitLen, int maxDigitLen, out int result) { - Contract.Assert(minDigitLen > 0, "minDigitLen > 0"); - Contract.Assert(maxDigitLen < 9, "maxDigitLen < 9"); - Contract.Assert(minDigitLen <= maxDigitLen, "minDigitLen <= maxDigitLen"); + Debug.Assert(minDigitLen > 0, "minDigitLen > 0"); + Debug.Assert(maxDigitLen < 9, "maxDigitLen < 9"); + Debug.Assert(minDigitLen <= maxDigitLen, "minDigitLen <= maxDigitLen"); result = 0; int startingIndex = str.Index; int tokenLength = 0; @@ -4123,7 +4123,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, case ParseFailureKind.FormatBadDateTimeCalendar: return new FormatException(Environment.GetResourceString(result.failureMessageID, result.calendar)); default: - Contract.Assert(false, "Unkown DateTimeParseFailure: " + result); + Debug.Assert(false, "Unkown DateTimeParseFailure: " + result); return null; } @@ -4345,7 +4345,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, } internal bool Advance(int count) { - Contract.Assert(Index + count <= len, "__DTString::Advance: Index + count <= len"); + Debug.Assert(Index + count <= len, "__DTString::Advance: Index + count <= len"); Index += count; if (Index < len) { m_current = Value[Index]; @@ -4638,7 +4638,7 @@ Start: // Get the current character. // internal char GetChar() { - Contract.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len"); + Debug.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len"); return (Value[Index]); } @@ -4646,8 +4646,8 @@ Start: // Convert the current character to a digit, and return it. // internal int GetDigit() { - Contract.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len"); - Contract.Assert(DateTimeParse.IsDigit(Value[Index]), "IsDigit(Value[Index])"); + Debug.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len"); + Debug.Assert(DateTimeParse.IsDigit(Value[Index]), "IsDigit(Value[Index])"); return (Value[Index] - '0'); } @@ -4780,7 +4780,7 @@ Start: return sub; } int number = ch - '0'; - Contract.Assert(number >= 0 && number <= 9, "number >= 0 && number <= 9"); + Debug.Assert(number >= 0 && number <= 9, "number >= 0 && number <= 9"); sub.value = sub.value * 10 + number; } else { @@ -4799,8 +4799,8 @@ Start: } internal void ConsumeSubString(DTSubString sub) { - Contract.Assert(sub.index == Index, "sub.index == Index"); - Contract.Assert(sub.index + sub.length <= len, "sub.index + sub.length <= len"); + Debug.Assert(sub.index == Index, "sub.index == Index"); + Debug.Assert(sub.index + sub.length <= len, "sub.index + sub.length <= len"); Index = sub.index + sub.length; if (Index < len) { m_current = Value[Index]; diff --git a/src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs b/src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs index 1405e41..0fce2e5 100644 --- a/src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs +++ b/src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Text; @@ -82,7 +83,7 @@ namespace System.Globalization break; } - Contract.Assert(item == null || item.CodePage == codepage, "item.CodePage needs to equal the specified codepage"); + Debug.Assert(item == null || item.CodePage == codepage, "item.CodePage needs to equal the specified codepage"); return item; } @@ -91,7 +92,7 @@ namespace System.Globalization #if DEBUG static EncodingTable() { - Contract.Assert( + Debug.Assert( s_encodingDataTable.Count == EncodingTableCapacity, string.Format(CultureInfo.InvariantCulture, "EncodingTable s_encodingDataTable's initial capacity (EncodingTableCapacity) is incorrect.{0}Expected (s_encodingDataTable.Count): {1}, Actual (EncodingTableCapacity): {2}", diff --git a/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs b/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs index 14322d8..0810d67 100644 --- a/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs +++ b/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs @@ -15,6 +15,7 @@ namespace System.Globalization { using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.IO; + using System.Diagnostics; using System.Diagnostics.Contracts; @@ -33,8 +34,8 @@ namespace System.Globalization { // // ---------------------------------------------------------------------------------------------------- internal unsafe static byte* GetGlobalizationResourceBytePtr(Assembly assembly, String tableName) { - Contract.Assert(assembly != null, "assembly can not be null. This should be generally the "+System.CoreLib.Name+" assembly."); - Contract.Assert(tableName != null, "table name can not be null"); + Debug.Assert(assembly != null, "assembly can not be null. This should be generally the "+System.CoreLib.Name+" assembly."); + Debug.Assert(tableName != null, "table name can not be null"); Stream stream = assembly.GetManifestResourceStream(tableName); UnmanagedMemoryStream bytesStream = stream as UnmanagedMemoryStream; @@ -45,7 +46,7 @@ namespace System.Globalization { } } - Contract.Assert( + Debug.Assert( false, String.Format( CultureInfo.CurrentCulture, diff --git a/src/mscorlib/src/System/Globalization/HebrewCalendar.cs b/src/mscorlib/src/System/Globalization/HebrewCalendar.cs index 3772b0b..44cbdb8 100644 --- a/src/mscorlib/src/System/Globalization/HebrewCalendar.cs +++ b/src/mscorlib/src/System/Globalization/HebrewCalendar.cs @@ -5,6 +5,7 @@ namespace System.Globalization { using System; using System.Text; + using System.Diagnostics; using System.Diagnostics.Contracts; //////////////////////////////////////////////////////////////////////////// @@ -607,7 +608,7 @@ namespace System.Globalization { // is true. // NumDays -= (long)(LunarMonthLen[hebrewYearType, lunarDate.month] - lunarDate.day); - Contract.Assert(NumDays >= 1, "NumDays >= 1"); + Debug.Assert(NumDays >= 1, "NumDays >= 1"); // If NumDays is 1, then we are done. Otherwise, find the correct Hebrew month // and day. @@ -811,7 +812,7 @@ namespace System.Globalization { int hebrewYearType = GetHebrewYearType(year, era); CheckHebrewMonthValue(year, month, era); - Contract.Assert(hebrewYearType>= 1 && hebrewYearType <= 6, + Debug.Assert(hebrewYearType>= 1 && hebrewYearType <= 6, "hebrewYearType should be from 1 to 6, but now hebrewYearType = " + hebrewYearType + " for hebrew year " + year); int monthDays = LunarMonthLen[hebrewYearType, month]; if (monthDays == 0) { diff --git a/src/mscorlib/src/System/Globalization/HebrewNumber.cs b/src/mscorlib/src/System/Globalization/HebrewNumber.cs index cf05955..5517cb1 100644 --- a/src/mscorlib/src/System/Globalization/HebrewNumber.cs +++ b/src/mscorlib/src/System/Globalization/HebrewNumber.cs @@ -6,6 +6,7 @@ namespace System.Globalization { using System; using System.Text; + using System.Diagnostics; using System.Diagnostics.Contracts; //////////////////////////////////////////////////////////////////////////// @@ -98,7 +99,7 @@ namespace System.Globalization { Number -= 5000; } - Contract.Assert(Number > 0 && Number <= 999, "Number is out of range.");; + Debug.Assert(Number > 0 && Number <= 999, "Number is out of range.");; // // Get the Hundreds. diff --git a/src/mscorlib/src/System/Globalization/IdnMapping.cs b/src/mscorlib/src/System/Globalization/IdnMapping.cs index d2a216c..b161851 100644 --- a/src/mscorlib/src/System/Globalization/IdnMapping.cs +++ b/src/mscorlib/src/System/Globalization/IdnMapping.cs @@ -65,6 +65,7 @@ namespace System.Globalization using System.Text; using System.Runtime.Versioning; using System.Runtime.InteropServices; + using System.Diagnostics; using System.Diagnostics.Contracts; // IdnMapping class used to map names to Punycode @@ -160,7 +161,7 @@ namespace System.Globalization // Cannot be null terminated (normalization won't help us with this one, and // may have returned false before checking the whole string above) - Contract.Assert(unicode.Length >= 1, "[IdnMapping.GetAscii]Expected 0 length strings to fail before now."); + Debug.Assert(unicode.Length >= 1, "[IdnMapping.GetAscii]Expected 0 length strings to fail before now."); if (unicode[unicode.Length - 1] <= 0x1f) { throw new ArgumentException( @@ -507,7 +508,7 @@ namespace System.Globalization static char encode_digit(int d) { - Contract.Assert(d >= 0 && d < punycodeBase, "[IdnMapping.encode_digit]Expected 0 <= d < punycodeBase"); + Debug.Assert(d >= 0 && d < punycodeBase, "[IdnMapping.encode_digit]Expected 0 <= d < punycodeBase"); // 26-35 map to ASCII 0-9 if (d > 25) return (char)(d - 26 + '0'); @@ -544,7 +545,7 @@ namespace System.Globalization uint k; delta = firsttime ? delta / damp : delta / 2; - Contract.Assert(numpoints != 0, "[IdnMapping.adapt]Expected non-zero numpoints."); + Debug.Assert(numpoints != 0, "[IdnMapping.adapt]Expected non-zero numpoints."); delta += delta / numpoints; for (k = 0; delta > ((punycodeBase - tmin) * tmax) / 2; k += punycodeBase) @@ -552,7 +553,7 @@ namespace System.Globalization delta /= punycodeBase - tmin; } - Contract.Assert(delta + skew != 0, "[IdnMapping.adapt]Expected non-zero delta+skew."); + Debug.Assert(delta + skew != 0, "[IdnMapping.adapt]Expected non-zero delta+skew."); return (int)(k + (punycodeBase - tmin + 1) * delta / (delta + skew)); } @@ -602,7 +603,7 @@ namespace System.Globalization { // Find end of this segment iNextDot = unicode.IndexOfAny(M_Dots, iAfterLastDot); - Contract.Assert(iNextDot <= unicode.Length, "[IdnMapping.punycode_encode]IndexOfAny is broken"); + Debug.Assert(iNextDot <= unicode.Length, "[IdnMapping.punycode_encode]IndexOfAny is broken"); if (iNextDot < 0) iNextDot = unicode.Length; @@ -652,7 +653,7 @@ namespace System.Globalization for (basicCount = iAfterLastDot; basicCount < iNextDot; basicCount++) { // Can't be lonely surrogate because it would've thrown in normalization - Contract.Assert(Char.IsLowSurrogate(unicode, basicCount) == false, + Debug.Assert(Char.IsLowSurrogate(unicode, basicCount) == false, "[IdnMapping.punycode_encode]Unexpected low surrogate"); // Double check our bidi rules @@ -736,7 +737,7 @@ namespace System.Globalization /* Increase delta enough to advance the decoder's */ /* state to , but guard against overflow: */ delta += (int)((m - n) * ((numProcessed - numSurrogatePairs) + 1)); - Contract.Assert(delta > 0, "[IdnMapping.cs]1 punycode_encode - delta overflowed int"); + Debug.Assert(delta > 0, "[IdnMapping.cs]1 punycode_encode - delta overflowed int"); n = m; for (j = iAfterLastDot; j < iNextDot; j+= IsSupplementary(test) ? 2 : 1) @@ -750,7 +751,7 @@ namespace System.Globalization if (test < n) { delta++; - Contract.Assert(delta > 0, "[IdnMapping.cs]2 punycode_encode - delta overflowed int"); + Debug.Assert(delta > 0, "[IdnMapping.cs]2 punycode_encode - delta overflowed int"); } if (test == n) @@ -762,7 +763,7 @@ namespace System.Globalization int t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias; if (q < t) break; - Contract.Assert(punycodeBase != t, "[IdnMapping.punycode_encode]Expected punycodeBase (36) to be != t"); + Debug.Assert(punycodeBase != t, "[IdnMapping.punycode_encode]Expected punycodeBase (36) to be != t"); int mod; q = Math.DivRem(q - t, punycodeBase - t, out mod); @@ -783,7 +784,7 @@ namespace System.Globalization } ++delta; ++n; - Contract.Assert(delta > 0, "[IdnMapping.cs]3 punycode_encode - delta overflowed int"); + Debug.Assert(delta > 0, "[IdnMapping.cs]3 punycode_encode - delta overflowed int"); } } @@ -974,7 +975,7 @@ namespace System.Globalization // decode the digit from the next char int digit = decode_digit(ascii[asciiIndex++]); - Contract.Assert(w > 0, "[IdnMapping.punycode_decode]Expected w > 0"); + Debug.Assert(w > 0, "[IdnMapping.punycode_decode]Expected w > 0"); if (digit > (maxint - i) / w) throw new ArgumentException(Environment.GetResourceString( "Argument_IdnBadPunycode"), nameof(ascii)); @@ -983,7 +984,7 @@ namespace System.Globalization int t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias; if (digit < t) break; - Contract.Assert(punycodeBase != t, "[IdnMapping.punycode_decode]Expected t != punycodeBase (36)"); + Debug.Assert(punycodeBase != t, "[IdnMapping.punycode_decode]Expected t != punycodeBase (36)"); if (w > maxint / (punycodeBase - t)) throw new ArgumentException(Environment.GetResourceString( "Argument_IdnBadPunycode"), nameof(ascii)); @@ -995,7 +996,7 @@ namespace System.Globalization /* i was supposed to wrap around from output.Length to 0, */ /* incrementing n each time, so we'll fix that now: */ - Contract.Assert((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1 > 0, + Debug.Assert((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1 > 0, "[IdnMapping.punycode_decode]Expected to have added > 0 characters this segment"); if (i / ((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1) > maxint - n) throw new ArgumentException(Environment.GetResourceString( diff --git a/src/mscorlib/src/System/Globalization/PersianCalendar.cs b/src/mscorlib/src/System/Globalization/PersianCalendar.cs index ff15699..e61a007 100644 --- a/src/mscorlib/src/System/Globalization/PersianCalendar.cs +++ b/src/mscorlib/src/System/Globalization/PersianCalendar.cs @@ -4,6 +4,7 @@ namespace System.Globalization { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; //////////////////////////////////////////////////////////////////////////// @@ -185,7 +186,7 @@ namespace System.Globalization { static int MonthFromOrdinalDay(int ordinalDay) { - Contract.Assert(ordinalDay <= 366); + Debug.Assert(ordinalDay <= 366); int index = 0; while (ordinalDay > DaysToMonth[index]) index++; @@ -195,7 +196,7 @@ namespace System.Globalization { static int DaysInPreviousMonths(int month) { - Contract.Assert(1 <= month && month <= 12); + Debug.Assert(1 <= month && month <= 12); --month; // months are one based but for calculations use 0 based return DaysToMonth[month]; } @@ -225,7 +226,7 @@ namespace System.Globalization { long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(NumDays); int y = (int)(Math.Floor(((yearStart - PersianEpoch) / CalendricalCalculationsHelper.MeanTropicalYearInDays) + 0.5)) + 1; - Contract.Assert(y >= 1); + Debug.Assert(y >= 1); if (part == DatePartYear) { @@ -244,16 +245,16 @@ namespace System.Globalization { } int m = MonthFromOrdinalDay(ordinalDay); - Contract.Assert(ordinalDay >= 1); - Contract.Assert(m >= 1 && m <= 12); + Debug.Assert(ordinalDay >= 1); + Debug.Assert(m >= 1 && m <= 12); if (part == DatePartMonth) { return m; } int d = ordinalDay - DaysInPreviousMonths(m); - Contract.Assert(1 <= d); - Contract.Assert(d <= 31); + Debug.Assert(1 <= d); + Debug.Assert(d <= 31); // // Calculate the Persian Day. @@ -377,7 +378,7 @@ namespace System.Globalization { int daysInMonth = DaysToMonth[month] - DaysToMonth[month - 1]; if ((month == MonthsPerYear) && !IsLeapYear(year)) { - Contract.Assert(daysInMonth == 30); + Debug.Assert(daysInMonth == 30); --daysInMonth; } return daysInMonth; diff --git a/src/mscorlib/src/System/Globalization/RegionInfo.cs b/src/mscorlib/src/System/Globalization/RegionInfo.cs index 9430c56..4bed875 100644 --- a/src/mscorlib/src/System/Globalization/RegionInfo.cs +++ b/src/mscorlib/src/System/Globalization/RegionInfo.cs @@ -19,6 +19,7 @@ namespace System.Globalization { using System; using System.Runtime.Serialization; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -212,7 +213,7 @@ namespace System.Globalization { //////////////////////////////////////////////////////////////////////// public virtual String Name { get { - Contract.Assert(m_name != null, "Expected RegionInfo.m_name to be populated already"); + Debug.Assert(m_name != null, "Expected RegionInfo.m_name to be populated already"); return (m_name); } } diff --git a/src/mscorlib/src/System/Globalization/SortKey.cs b/src/mscorlib/src/System/Globalization/SortKey.cs index 62207c2..9c35f48 100644 --- a/src/mscorlib/src/System/Globalization/SortKey.cs +++ b/src/mscorlib/src/System/Globalization/SortKey.cs @@ -16,6 +16,7 @@ namespace System.Globalization { using System; using System.Runtime.CompilerServices; using System.Runtime.Serialization; + using System.Diagnostics; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] @@ -126,8 +127,8 @@ namespace System.Globalization { byte[] key1Data = sortkey1.m_KeyData; byte[] key2Data = sortkey2.m_KeyData; - Contract.Assert(key1Data!=null, "key1Data!=null"); - Contract.Assert(key2Data!=null, "key2Data!=null"); + Debug.Assert(key1Data!=null, "key1Data!=null"); + Debug.Assert(key2Data!=null, "key2Data!=null"); if (key1Data.Length == 0) { if (key2Data.Length == 0) { diff --git a/src/mscorlib/src/System/Globalization/StringInfo.cs b/src/mscorlib/src/System/Globalization/StringInfo.cs index 40b2f92..d86e115 100644 --- a/src/mscorlib/src/System/Globalization/StringInfo.cs +++ b/src/mscorlib/src/System/Globalization/StringInfo.cs @@ -17,6 +17,7 @@ namespace System.Globalization { using System; using System.Runtime.Serialization; using System.Security.Permissions; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -206,8 +207,8 @@ namespace System.Globalization { internal static int GetCurrentTextElementLen(String str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount) { - Contract.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); - Contract.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); + Debug.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); + Debug.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); if (index + currentCharCount == len) { // This is the last character/surrogate in the string. diff --git a/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs b/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs index 5f47f5f..049ccf6 100644 --- a/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs +++ b/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs @@ -15,6 +15,7 @@ using System.Runtime.Serialization; namespace System.Globalization { using System.Collections; + using System.Diagnostics; using System.Diagnostics.Contracts; // @@ -43,9 +44,9 @@ namespace System.Globalization { internal TextElementEnumerator(String str, int startIndex, int strLen) { - Contract.Assert(str != null, "TextElementEnumerator(): str != null"); - Contract.Assert(startIndex >= 0 && strLen >= 0, "TextElementEnumerator(): startIndex >= 0 && strLen >= 0"); - Contract.Assert(strLen >= startIndex, "TextElementEnumerator(): strLen >= startIndex"); + Debug.Assert(str != null, "TextElementEnumerator(): str != null"); + Debug.Assert(startIndex >= 0 && strLen >= 0, "TextElementEnumerator(): startIndex >= 0 && strLen >= 0"); + Debug.Assert(strLen >= startIndex, "TextElementEnumerator(): strLen >= startIndex"); this.str = str; this.startIndex = startIndex; this.strLen = strLen; diff --git a/src/mscorlib/src/System/Globalization/TextInfo.cs b/src/mscorlib/src/System/Globalization/TextInfo.cs index 8731221..c8108e4 100644 --- a/src/mscorlib/src/System/Globalization/TextInfo.cs +++ b/src/mscorlib/src/System/Globalization/TextInfo.cs @@ -24,6 +24,7 @@ namespace System.Globalization { using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security.Permissions; + using System.Diagnostics; using System.Diagnostics.Contracts; @@ -229,16 +230,16 @@ namespace System.Globalization { // The underlying unmanaged code will assert the sanity of arguments. internal static unsafe int CompareOrdinalIgnoreCaseEx(String strA, int indexA, String strB, int indexB, int lengthA, int lengthB ) { - Contract.Assert(strA.Length >= indexA + lengthA, "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strA.Length >= indexA + lengthA"); - Contract.Assert(strB.Length >= indexB + lengthB, "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strB.Length >= indexB + lengthB"); + Debug.Assert(strA.Length >= indexA + lengthA, "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strA.Length >= indexA + lengthA"); + Debug.Assert(strB.Length >= indexB + lengthB, "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strB.Length >= indexB + lengthB"); return InternalCompareStringOrdinalIgnoreCase(strA, indexA, strB, indexB, lengthA, lengthB); } internal static int IndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count) { - Contract.Assert(source != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated source != null"); - Contract.Assert(value != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated value != null"); - Contract.Assert(startIndex + count <= source.Length, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex + count <= source.Length"); + Debug.Assert(source != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated source != null"); + Debug.Assert(value != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated value != null"); + Debug.Assert(startIndex + count <= source.Length, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex + count <= source.Length"); // We return 0 if both inputs are empty strings if (source.Length == 0 && value.Length == 0) @@ -265,7 +266,7 @@ namespace System.Globalization { for (; startIndex <= maxStartIndex; startIndex++) { // We should always have the same or more characters left to search than our actual pattern - Contract.Assert(end - startIndex >= value.Length); + Debug.Assert(end - startIndex >= value.Length); // since this is an ordinal comparison, we can assume that the lengths must match if (CompareOrdinalIgnoreCaseEx(source, startIndex, value, 0, value.Length, value.Length) == 0) { @@ -279,10 +280,10 @@ namespace System.Globalization { internal static int LastIndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count) { - Contract.Assert(source != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated source != null"); - Contract.Assert(value != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated value != null"); - Contract.Assert(startIndex - count+1 >= 0, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex - count+1 >= 0"); - Contract.Assert(startIndex <= source.Length, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex <= source.Length"); + Debug.Assert(source != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated source != null"); + Debug.Assert(value != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated value != null"); + Debug.Assert(startIndex - count+1 >= 0, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex - count+1 >= 0"); + Debug.Assert(startIndex <= source.Length, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex <= source.Length"); // If value is Empty, the return value is startIndex if (value.Length == 0) @@ -784,7 +785,7 @@ namespace System.Globalization { private static int AddNonLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen) { - Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!"); + Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!"); if (charLen == 2) { // Surrogate pair @@ -801,7 +802,7 @@ namespace System.Globalization { private int AddTitlecaseLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen) { - Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!"); + Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!"); // for surrogate pairs do a simple ToUpper operation on the substring if (charLen == 2) diff --git a/src/mscorlib/src/System/Globalization/TimeSpanFormat.cs b/src/mscorlib/src/System/Globalization/TimeSpanFormat.cs index cf6ed95..e5e615f 100644 --- a/src/mscorlib/src/System/Globalization/TimeSpanFormat.cs +++ b/src/mscorlib/src/System/Globalization/TimeSpanFormat.cs @@ -6,6 +6,7 @@ namespace System.Globalization { using System.Text; using System; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; @@ -142,7 +143,7 @@ namespace System.Globalization { // internal static String FormatCustomized(TimeSpan value, String format, DateTimeFormatInfo dtfi) { - Contract.Assert(dtfi != null, "dtfi == null"); + Debug.Assert(dtfi != null, "dtfi == null"); int day = (int)(value._ticks / TimeSpan.TicksPerDay); long time = value._ticks % TimeSpan.TicksPerDay; @@ -368,7 +369,7 @@ namespace System.Globalization { case '\"': if (inQuote && (quote == format[i])) { /* we were in a quote and found a matching exit quote, so we are outside a quote now */ - Contract.Assert(field >= 0 && field <= 5, "field >= 0 && field <= 5"); + Debug.Assert(field >= 0 && field <= 5, "field >= 0 && field <= 5"); if (field >= 0 && field <= 5) { literals[field] = sb.ToString(); sb.Length = 0; @@ -388,7 +389,7 @@ namespace System.Globalization { } break; case '%': - Contract.Assert(false, "Unexpected special token '%', Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); + Debug.Assert(false, "Unexpected special token '%', Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); goto default; case '\\': if (!inQuote) { @@ -398,7 +399,7 @@ namespace System.Globalization { goto default; case 'd': if (!inQuote) { - Contract.Assert((field == 0 && sb.Length == 0) || field == 1, + Debug.Assert((field == 0 && sb.Length == 0) || field == 1, "field == 0 || field == 1, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 1; // DayHourSep dd++; @@ -406,7 +407,7 @@ namespace System.Globalization { break; case 'h': if (!inQuote) { - Contract.Assert((field == 1 && sb.Length == 0) || field == 2, + Debug.Assert((field == 1 && sb.Length == 0) || field == 2, "field == 1 || field == 2, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 2; // HourMinuteSep hh++; @@ -414,7 +415,7 @@ namespace System.Globalization { break; case 'm': if (!inQuote) { - Contract.Assert((field == 2 && sb.Length == 0) || field == 3, + Debug.Assert((field == 2 && sb.Length == 0) || field == 3, "field == 2 || field == 3, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 3; // MinuteSecondSep mm++; @@ -422,7 +423,7 @@ namespace System.Globalization { break; case 's': if (!inQuote) { - Contract.Assert((field == 3 && sb.Length == 0) || field == 4, + Debug.Assert((field == 3 && sb.Length == 0) || field == 4, "field == 3 || field == 4, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 4; // SecondFractionSep ss++; @@ -431,7 +432,7 @@ namespace System.Globalization { case 'f': case 'F': if (!inQuote) { - Contract.Assert((field == 4 && sb.Length == 0) || field == 5, + Debug.Assert((field == 4 && sb.Length == 0) || field == 5, "field == 4 || field == 5, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 5; // End ff++; @@ -443,14 +444,14 @@ namespace System.Globalization { } } - Contract.Assert(field == 5); + Debug.Assert(field == 5); AppCompatLiteral = MinuteSecondSep + SecondFractionSep; - Contract.Assert(0 < dd && dd < 3, "0 < dd && dd < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); - Contract.Assert(0 < hh && hh < 3, "0 < hh && hh < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); - Contract.Assert(0 < mm && mm < 3, "0 < mm && mm < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); - Contract.Assert(0 < ss && ss < 3, "0 < ss && ss < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); - Contract.Assert(0 < ff && ff < 8, "0 < ff && ff < 8, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); + Debug.Assert(0 < dd && dd < 3, "0 < dd && dd < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); + Debug.Assert(0 < hh && hh < 3, "0 < hh && hh < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); + Debug.Assert(0 < mm && mm < 3, "0 < mm && mm < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); + Debug.Assert(0 < ss && ss < 3, "0 < ss && ss < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); + Debug.Assert(0 < ff && ff < 8, "0 < ff && ff < 8, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); if (useInvariantFieldLengths) { dd = 2; diff --git a/src/mscorlib/src/System/Globalization/TimeSpanParse.cs b/src/mscorlib/src/System/Globalization/TimeSpanParse.cs index 41221a5..d83c5fa 100644 --- a/src/mscorlib/src/System/Globalization/TimeSpanParse.cs +++ b/src/mscorlib/src/System/Globalization/TimeSpanParse.cs @@ -53,6 +53,7 @@ namespace System.Globalization { using System.Text; using System; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; @@ -126,10 +127,10 @@ namespace System.Globalization { } public bool IsInvalidNumber(int maxValue, int maxPrecision) { - Contract.Assert(ttt == TTT.Num); - Contract.Assert(num > -1); - Contract.Assert(maxValue > 0); - Contract.Assert(maxPrecision == maxFractionDigits || maxPrecision == unlimitedDigits); + Debug.Assert(ttt == TTT.Num); + Debug.Assert(num > -1); + Debug.Assert(maxValue > 0); + Debug.Assert(maxPrecision == maxFractionDigits || maxPrecision == unlimitedDigits); if (num > maxValue) return true; @@ -163,7 +164,7 @@ namespace System.Globalization { } // used by the parsing routines that operate on standard-formats internal TimeSpanToken GetNextToken() { - Contract.Assert(m_pos > -1); + Debug.Assert(m_pos > -1); TimeSpanToken tok = new TimeSpanToken(); char ch = CurrentChar; @@ -374,7 +375,7 @@ namespace System.Globalization { private const int MaxNumericTokens = 5; internal void Init(DateTimeFormatInfo dtfi) { - Contract.Assert(dtfi != null); + Debug.Assert(dtfi != null); lastSeenTTT = TTT.None; tokenCount = 0; @@ -416,7 +417,7 @@ namespace System.Globalization { } lastSeenTTT = tok.ttt; - Contract.Assert(tokenCount == (SepCount + NumCount), "tokenCount == (SepCount + NumCount)"); + Debug.Assert(tokenCount == (SepCount + NumCount), "tokenCount == (SepCount + NumCount)"); return true; } @@ -486,7 +487,7 @@ namespace System.Globalization { return new OverflowException(Environment.GetResourceString(m_failureMessageID)); default: - Contract.Assert(false, "Unknown TimeSpanParseFailure: " + m_failure); + Debug.Assert(false, "Unknown TimeSpanParseFailure: " + m_failure); return new FormatException(Environment.GetResourceString("Format_InvalidString")); } } @@ -1158,8 +1159,8 @@ namespace System.Globalization { // Actions: Parse the TimeSpan instance using the specified format. Used by TryParseExactTimeSpan. // private static Boolean TryParseByFormat(String input, String format, TimeSpanStyles styles, ref TimeSpanResult result) { - Contract.Assert(input != null, "input != null"); - Contract.Assert(format != null, "format != null"); + Debug.Assert(input != null, "input != null"); + Debug.Assert(format != null, "format != null"); bool seenDD = false; // already processed days? bool seenHH = false; // already processed hours? diff --git a/src/mscorlib/src/System/Globalization/UmAlQuraCalendar.cs b/src/mscorlib/src/System/Globalization/UmAlQuraCalendar.cs index 8379c88..06e7c7d 100644 --- a/src/mscorlib/src/System/Globalization/UmAlQuraCalendar.cs +++ b/src/mscorlib/src/System/Globalization/UmAlQuraCalendar.cs @@ -4,6 +4,7 @@ namespace System.Globalization { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; @@ -338,9 +339,9 @@ namespace System.Globalization { =========================ConvertHijriToGregorian============================*/ static void ConvertHijriToGregorian(int HijriYear, int HijriMonth, int HijriDay, ref int yg, ref int mg, ref int dg) { - Contract.Assert( (HijriYear >= MinCalendarYear) && (HijriYear <= MaxCalendarYear), "Hijri year is out of range."); - Contract.Assert( HijriMonth >= 1, "Hijri month is out of range."); - Contract.Assert( HijriDay >= 1, "Hijri day is out of range."); + Debug.Assert( (HijriYear >= MinCalendarYear) && (HijriYear <= MaxCalendarYear), "Hijri year is out of range."); + Debug.Assert( HijriMonth >= 1, "Hijri month is out of range."); + Debug.Assert( HijriDay >= 1, "Hijri day is out of range."); int index, b, nDays = HijriDay-1; DateTime dt; @@ -430,7 +431,7 @@ namespace System.Globalization { TimeSpan ts; int yh1=0, mh1=0, dh1=0; - Contract.Assert((time.Ticks >= minDate.Ticks) && (time.Ticks <= maxDate.Ticks), "Gregorian date is out of range."); + Debug.Assert((time.Ticks >= minDate.Ticks) && (time.Ticks <= maxDate.Ticks), "Gregorian date is out of range."); // Find the index where we should start our search by quessing the Hijri year that we will be in HijriYearInfo. // A Hijri year is 354 or 355 days. Use 355 days so that we will search from a lower index. @@ -631,7 +632,7 @@ namespace System.Globalization { { int days = 0, b; - Contract.Assert( (year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range."); + Debug.Assert( (year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range."); b = HijriYearInfo[year-MinCalendarYear].HijriMonthsLengthFlags; @@ -640,7 +641,7 @@ namespace System.Globalization { days += 29 + (b & 0x1); b = b >> 1; } - Contract.Assert((days == 354)||(days == 355), "Hijri year has to be 354 or 355 days."); + Debug.Assert((days == 354)||(days == 355), "Hijri year has to be 354 or 355 days."); return days; } diff --git a/src/mscorlib/src/System/Guid.cs b/src/mscorlib/src/System/Guid.cs index d36d44e..e2e36ba 100644 --- a/src/mscorlib/src/System/Guid.cs +++ b/src/mscorlib/src/System/Guid.cs @@ -10,6 +10,7 @@ namespace System { using Microsoft.Win32; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; + using System.Diagnostics; using System.Diagnostics.Contracts; // Represents a Globally Unique Identifier. @@ -185,7 +186,7 @@ namespace System { } internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument, string failureArgumentName, Exception innerException) { - Contract.Assert(failure != ParseFailureKind.NativeException, "ParseFailureKind.NativeException should not be used with this overload"); + Debug.Assert(failure != ParseFailureKind.NativeException, "ParseFailureKind.NativeException should not be used with this overload"); m_failure = failure; m_failureMessageID = failureMessageID; m_failureMessageFormatArgument = failureMessageFormatArgument; @@ -214,7 +215,7 @@ namespace System { return m_innerException; default: - Contract.Assert(false, "Unknown GuidParseFailure: " + m_failure); + Debug.Assert(false, "Unknown GuidParseFailure: " + m_failure); return new FormatException(Environment.GetResourceString("Format_GuidUnrecognized")); } } diff --git a/src/mscorlib/src/System/IAppDomainPauseManager.cs b/src/mscorlib/src/System/IAppDomainPauseManager.cs index 49fd9a6..902a79b 100644 --- a/src/mscorlib/src/System/IAppDomainPauseManager.cs +++ b/src/mscorlib/src/System/IAppDomainPauseManager.cs @@ -46,7 +46,7 @@ namespace System public void Paused() { - Contract.Assert(!isPaused); + Debug.Assert(!isPaused); if(ResumeEvent == null) ResumeEvent = new ManualResetEvent(false); @@ -63,7 +63,7 @@ namespace System public void Resuming() { - Contract.Assert(isPaused); + Debug.Assert(isPaused); isPaused = false; ResumeEvent.Set(); } diff --git a/src/mscorlib/src/System/IO/BinaryReader.cs b/src/mscorlib/src/System/IO/BinaryReader.cs index b5be364..4145a7f 100644 --- a/src/mscorlib/src/System/IO/BinaryReader.cs +++ b/src/mscorlib/src/System/IO/BinaryReader.cs @@ -19,6 +19,7 @@ namespace System.IO { using System.Runtime; using System.Text; using System.Globalization; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; @@ -73,7 +74,7 @@ namespace System.IO { m_isMemoryStream = (m_stream.GetType() == typeof(MemoryStream)); m_leaveOpen = leaveOpen; - Contract.Assert(m_decoder!=null, "[BinaryReader.ctor]m_decoder!=null"); + Debug.Assert(m_decoder!=null, "[BinaryReader.ctor]m_decoder!=null"); } public virtual Stream BaseStream { @@ -173,7 +174,7 @@ namespace System.IO { if (m_stream==null) __Error.FileNotOpen(); // read directly from MemoryStream buffer MemoryStream mStream = m_stream as MemoryStream; - Contract.Assert(mStream != null, "m_stream as MemoryStream != null"); + Debug.Assert(mStream != null, "m_stream as MemoryStream != null"); return mStream.InternalReadInt32(); } @@ -319,7 +320,7 @@ namespace System.IO { private int InternalReadChars(char[] buffer, int index, int count) { Contract.Requires(buffer != null); Contract.Requires(index >= 0 && count >= 0); - Contract.Assert(m_stream != null); + Debug.Assert(m_stream != null); int numBytes = 0; int charsRemaining = count; @@ -351,7 +352,7 @@ namespace System.IO { if (m_isMemoryStream) { MemoryStream mStream = m_stream as MemoryStream; - Contract.Assert(mStream != null, "m_stream as MemoryStream != null"); + Debug.Assert(mStream != null, "m_stream as MemoryStream != null"); position = mStream.InternalGetPosition(); numBytes = mStream.InternalEmulateRead(numBytes); @@ -367,7 +368,7 @@ namespace System.IO { return (count - charsRemaining); } - Contract.Assert(byteBuffer != null, "expected byteBuffer to be non-null"); + Debug.Assert(byteBuffer != null, "expected byteBuffer to be non-null"); checked { @@ -394,7 +395,7 @@ namespace System.IO { } // this should never fail - Contract.Assert(charsRemaining >= 0, "We read too many characters."); + Debug.Assert(charsRemaining >= 0, "We read too many characters."); // we may have read fewer than the number of characters requested if end of stream reached // or if the encoding makes the char count too big for the buffer (e.g. fallback sequence) @@ -443,7 +444,7 @@ namespace System.IO { return -1; } - Contract.Assert(numBytes == 1 || numBytes == 2, "BinaryReader::InternalReadOneChar assumes it's reading one or 2 bytes only."); + Debug.Assert(numBytes == 1 || numBytes == 2, "BinaryReader::InternalReadOneChar assumes it's reading one or 2 bytes only."); try { @@ -460,7 +461,7 @@ namespace System.IO { throw; } - Contract.Assert(charsRead < 2, "InternalReadOneChar - assuming we only got 0 or 1 char, not 2!"); + Debug.Assert(charsRead < 2, "InternalReadOneChar - assuming we only got 0 or 1 char, not 2!"); // Console.WriteLine("That became: " + charsRead + " characters."); } if (charsRead == 0) diff --git a/src/mscorlib/src/System/IO/BinaryWriter.cs b/src/mscorlib/src/System/IO/BinaryWriter.cs index 46275ec..f99b4d3 100644 --- a/src/mscorlib/src/System/IO/BinaryWriter.cs +++ b/src/mscorlib/src/System/IO/BinaryWriter.cs @@ -17,6 +17,7 @@ using System; using System.Runtime; using System.Runtime.Serialization; using System.Text; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.IO { @@ -182,7 +183,7 @@ namespace System.IO { throw new ArgumentException(Environment.GetResourceString("Arg_SurrogatesNotAllowedAsSingleChar")); Contract.EndContractBlock(); - Contract.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)"); + Debug.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)"); int numBytes = 0; fixed(byte * pBytes = _buffer) { numBytes = _encoder.GetBytes(&ch, 1, pBytes, _buffer.Length, flush: true); @@ -354,7 +355,7 @@ namespace System.IO { if (len <= _largeByteBuffer.Length) { - //Contract.Assert(len == _encoding.GetBytes(chars, 0, chars.Length, _largeByteBuffer, 0), "encoding's GetByteCount & GetBytes gave different answers! encoding type: "+_encoding.GetType().Name); + //Debug.Assert(len == _encoding.GetBytes(chars, 0, chars.Length, _largeByteBuffer, 0), "encoding's GetByteCount & GetBytes gave different answers! encoding type: "+_encoding.GetType().Name); _encoding.GetBytes(value, 0, value.Length, _largeByteBuffer, 0); OutStream.Write(_largeByteBuffer, 0, len); } @@ -389,14 +390,14 @@ namespace System.IO { } #if _DEBUG totalBytes += byteLen; - Contract.Assert (totalBytes <= len && byteLen <= _largeByteBuffer.Length, "BinaryWriter::Write(String) - More bytes encoded than expected!"); + Debug.Assert (totalBytes <= len && byteLen <= _largeByteBuffer.Length, "BinaryWriter::Write(String) - More bytes encoded than expected!"); #endif OutStream.Write(_largeByteBuffer, 0, byteLen); charStart += charCount; numLeft -= charCount; } #if _DEBUG - Contract.Assert(totalBytes == len, "BinaryWriter::Write(String) - Didn't write out all the bytes!"); + Debug.Assert(totalBytes == len, "BinaryWriter::Write(String) - Didn't write out all the bytes!"); #endif } } diff --git a/src/mscorlib/src/System/IO/Directory.cs b/src/mscorlib/src/System/IO/Directory.cs index 1caec73..5eb3fc8 100644 --- a/src/mscorlib/src/System/IO/Directory.cs +++ b/src/mscorlib/src/System/IO/Directory.cs @@ -21,6 +21,7 @@ using System.Security.Permissions; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.IO @@ -294,7 +295,7 @@ namespace System.IO catch (IOException) { } catch (UnauthorizedAccessException) { - Contract.Assert(false, "Ignore this assert and send a repro to Microsoft. This assert was tracking purposes only."); + Debug.Assert(false, "Ignore this assert and send a repro to Microsoft. This assert was tracking purposes only."); } return false; } diff --git a/src/mscorlib/src/System/IO/DirectoryInfo.cs b/src/mscorlib/src/System/IO/DirectoryInfo.cs index 45447e0..22adc4f 100644 --- a/src/mscorlib/src/System/IO/DirectoryInfo.cs +++ b/src/mscorlib/src/System/IO/DirectoryInfo.cs @@ -26,6 +26,7 @@ using System.Runtime.InteropServices; using System.Globalization; using System.Runtime.Serialization; using System.Runtime.Versioning; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.IO @@ -94,7 +95,7 @@ namespace System.IO #endif //FEATURE_CORESYSTEM internal DirectoryInfo(String fullPath, bool junk) { - Contract.Assert(PathInternal.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!"); + Debug.Assert(PathInternal.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!"); // Fast path when we know a DirectoryInfo exists. OriginalPath = Path.GetFileName(fullPath); @@ -542,8 +543,8 @@ namespace System.IO private static String GetDisplayName(String originalPath, String fullPath) { - Contract.Assert(originalPath != null); - Contract.Assert(fullPath != null); + Debug.Assert(originalPath != null); + Debug.Assert(fullPath != null); String displayName = ""; @@ -561,7 +562,7 @@ namespace System.IO private static String GetDirName(String fullPath) { - Contract.Assert(fullPath != null); + Debug.Assert(fullPath != null); String dirName = null; if (fullPath.Length > 3) diff --git a/src/mscorlib/src/System/IO/File.cs b/src/mscorlib/src/System/IO/File.cs index f98f13f..826766d 100644 --- a/src/mscorlib/src/System/IO/File.cs +++ b/src/mscorlib/src/System/IO/File.cs @@ -21,6 +21,7 @@ using System.Security; using System.Text; using Microsoft.Win32.SafeHandles; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.IO @@ -314,7 +315,7 @@ namespace System.IO // After normalizing, check whether path ends in directory separator. // Otherwise, FillAttributeInfo removes it and we may return a false positive. // GetFullPath should never return null - Contract.Assert(path != null, "File.Exists: GetFullPath returned null"); + Debug.Assert(path != null, "File.Exists: GetFullPath returned null"); if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[path.Length - 1])) { return false; @@ -986,7 +987,7 @@ namespace System.IO catch { // if we're already returning an error, don't throw another one. if (!error) { - Contract.Assert(false, "File::FillAttributeInfo - FindClose failed!"); + Debug.Assert(false, "File::FillAttributeInfo - FindClose failed!"); __Error.WinIOError(); } } diff --git a/src/mscorlib/src/System/IO/FileInfo.cs b/src/mscorlib/src/System/IO/FileInfo.cs index 23cf9cc..7e00a80 100644 --- a/src/mscorlib/src/System/IO/FileInfo.cs +++ b/src/mscorlib/src/System/IO/FileInfo.cs @@ -23,6 +23,7 @@ using System.Text; using System.Runtime.Serialization; using System.Globalization; using System.Runtime.Versioning; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.IO @@ -93,7 +94,7 @@ namespace System.IO #endif //FEATURE_CORESYSTEM internal FileInfo(String fullPath, bool ignoreThis) { - Contract.Assert(PathInternal.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!"); + Debug.Assert(PathInternal.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!"); _name = Path.GetFileName(fullPath); OriginalPath = _name; FullPath = fullPath; diff --git a/src/mscorlib/src/System/IO/FileSystemEnumerable.cs b/src/mscorlib/src/System/IO/FileSystemEnumerable.cs index 48415d5..e3ad368 100644 --- a/src/mscorlib/src/System/IO/FileSystemEnumerable.cs +++ b/src/mscorlib/src/System/IO/FileSystemEnumerable.cs @@ -23,6 +23,7 @@ using System.Text; using System.Runtime.InteropServices; using System.Globalization; using System.Runtime.Versioning; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Threading; @@ -251,7 +252,7 @@ namespace System.IO private void CommonInit() { - Contract.Assert(searchCriteria != null && searchData != null, "searchCriteria and searchData should be initialized"); + Debug.Assert(searchCriteria != null && searchData != null, "searchCriteria and searchData should be initialized"); // Execute searchCriteria against the current directory String searchPath = Path.Combine(searchData.fullPath, searchCriteria); @@ -393,12 +394,12 @@ namespace System.IO } case STATE_SEARCH_NEXT_DIR: { - Contract.Assert(searchData.searchOption != SearchOption.TopDirectoryOnly, "should not reach this code path if searchOption == TopDirectoryOnly"); + Debug.Assert(searchData.searchOption != SearchOption.TopDirectoryOnly, "should not reach this code path if searchOption == TopDirectoryOnly"); // Traverse directory structure. We need to get '*' while (searchStack.Count > 0) { searchData = searchStack[0]; - Contract.Assert((searchData.fullPath != null), "fullpath can't be null!"); + Debug.Assert((searchData.fullPath != null), "fullpath can't be null!"); searchStack.RemoveAt(0); // Traverse the subdirs @@ -605,7 +606,7 @@ namespace System.IO } else { - Contract.Assert(fullSearchString.Length > fullPathMod.Length); + Debug.Assert(fullSearchString.Length > fullPathMod.Length); searchCriteria = fullSearchString.Substring(fullPathMod.Length + 1); } return searchCriteria; @@ -653,7 +654,7 @@ namespace System.IO { bool includeFile = _includeFiles && FileSystemEnumerableHelpers.IsFile(result.FindData); bool includeDir = _includeDirs && FileSystemEnumerableHelpers.IsDir(result.FindData); - Contract.Assert(!(includeFile && includeDir), result.FindData.cFileName + ": current item can't be both file and dir!"); + Debug.Assert(!(includeFile && includeDir), result.FindData.cFileName + ": current item can't be both file and dir!"); return (includeFile || includeDir); } @@ -711,7 +712,7 @@ namespace System.IO { bool includeFile = FileSystemEnumerableHelpers.IsFile(result.FindData); bool includeDir = FileSystemEnumerableHelpers.IsDir(result.FindData); - Contract.Assert(!(includeFile && includeDir), result.FindData.cFileName + ": current item can't be both file and dir!"); + Debug.Assert(!(includeFile && includeDir), result.FindData.cFileName + ": current item can't be both file and dir!"); return (includeDir || includeFile); } @@ -735,7 +736,7 @@ namespace System.IO } else { - Contract.Assert(isFile); + Debug.Assert(isFile); String name = result.FullPath; FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, name); diff --git a/src/mscorlib/src/System/IO/MemoryStream.cs b/src/mscorlib/src/System/IO/MemoryStream.cs index 137c8a6..5dde00d 100644 --- a/src/mscorlib/src/System/IO/MemoryStream.cs +++ b/src/mscorlib/src/System/IO/MemoryStream.cs @@ -19,6 +19,7 @@ using System; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Threading; using System.Threading.Tasks; @@ -259,7 +260,7 @@ namespace System.IO { if (n > count) n = count; if (n < 0) n = 0; - Contract.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1. + Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1. _position += n; return n; } @@ -342,7 +343,7 @@ namespace System.IO { if (n <= 0) return 0; - Contract.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1. + Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1. if (n <= 8) { @@ -379,7 +380,7 @@ namespace System.IO { { int n = Read(buffer, offset, count); var t = _lastReadTask; - Contract.Assert(t == null || t.Status == TaskStatus.RanToCompletion, + Debug.Assert(t == null || t.Status == TaskStatus.RanToCompletion, "Expected that a stored last task completed successfully"); return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult(n)); } @@ -504,7 +505,7 @@ namespace System.IO { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin")); } - Contract.Assert(_position >= 0, "_position >= 0"); + Debug.Assert(_position >= 0, "_position >= 0"); return _position; } @@ -527,7 +528,7 @@ namespace System.IO { EnsureWriteable(); // Origin wasn't publicly exposed above. - Contract.Assert(MemStreamMaxLength == Int32.MaxValue); // Check parameter validation logic in this method if this fails. + Debug.Assert(MemStreamMaxLength == Int32.MaxValue); // Check parameter validation logic in this method if this fails. if (value > (Int32.MaxValue - _origin)) { throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength")); } diff --git a/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs b/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs index a9b04b2..890669f 100644 --- a/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs +++ b/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs @@ -15,6 +15,7 @@ ===========================================================*/ using System; using System.Runtime.InteropServices; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.IO { @@ -28,7 +29,7 @@ namespace System.IO { internal PinnedBufferMemoryStream(byte[] array) { - Contract.Assert(array != null, "Array can't be null"); + Debug.Assert(array != null, "Array can't be null"); int len = array.Length; // Handle 0 length byte arrays specially. diff --git a/src/mscorlib/src/System/IO/Stream.cs b/src/mscorlib/src/System/IO/Stream.cs index d3d90f7..f1a3198 100644 --- a/src/mscorlib/src/System/IO/Stream.cs +++ b/src/mscorlib/src/System/IO/Stream.cs @@ -24,6 +24,7 @@ using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Security; using System.Security.Permissions; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Reflection; @@ -341,7 +342,7 @@ namespace System.IO { // As we're currently inside of it, we can get the current task // and grab the parameters from it. var thisTask = Task.InternalCurrent as ReadWriteTask; - Contract.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask"); + Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask"); try { @@ -489,7 +490,7 @@ namespace System.IO { // As we're currently inside of it, we can get the current task // and grab the parameters from it. var thisTask = Task.InternalCurrent as ReadWriteTask; - Contract.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask"); + Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask"); try { @@ -522,20 +523,20 @@ namespace System.IO { private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask) { - Contract.Assert(readWriteTask != null); // Should be Contract.Requires, but CCRewrite is doing a poor job with + Debug.Assert(readWriteTask != null); // Should be Contract.Requires, but CCRewrite is doing a poor job with // preconditions in async methods that await. - Contract.Assert(asyncWaiter != null); // Ditto + Debug.Assert(asyncWaiter != null); // Ditto // If the wait has already completed, run the task. if (asyncWaiter.IsCompleted) { - Contract.Assert(asyncWaiter.IsRanToCompletion, "The semaphore wait should always complete successfully."); + Debug.Assert(asyncWaiter.IsRanToCompletion, "The semaphore wait should always complete successfully."); RunReadWriteTask(readWriteTask); } else // Otherwise, wait for our turn, and then run the task. { asyncWaiter.ContinueWith((t, state) => { - Contract.Assert(t.IsRanToCompletion, "The semaphore wait should always complete successfully."); + Debug.Assert(t.IsRanToCompletion, "The semaphore wait should always complete successfully."); var rwt = (ReadWriteTask)state; rwt._stream.RunReadWriteTask(rwt); // RunReadWriteTask(readWriteTask); }, readWriteTask, default(CancellationToken), TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); @@ -545,7 +546,7 @@ namespace System.IO { private void RunReadWriteTask(ReadWriteTask readWriteTask) { Contract.Requires(readWriteTask != null); - Contract.Assert(_activeReadWriteTask == null, "Expected no other readers or writers"); + Debug.Assert(_activeReadWriteTask == null, "Expected no other readers or writers"); // Schedule the task. ScheduleAndStart must happen after the write to _activeReadWriteTask to avoid a race. // Internally, we're able to directly call ScheduleAndStart rather than Start, avoiding @@ -559,7 +560,7 @@ namespace System.IO { private void FinishTrackingAsyncOperation() { _activeReadWriteTask = null; - Contract.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here."); + Debug.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here."); _asyncActiveSemaphore.Release(); } @@ -586,7 +587,7 @@ namespace System.IO { try { writeTask.GetAwaiter().GetResult(); // block until completion, then propagate any exceptions - Contract.Assert(writeTask.Status == TaskStatus.RanToCompletion); + Debug.Assert(writeTask.Status == TaskStatus.RanToCompletion); } finally { diff --git a/src/mscorlib/src/System/IO/StreamReader.cs b/src/mscorlib/src/System/IO/StreamReader.cs index d74dccf..c8a5026 100644 --- a/src/mscorlib/src/System/IO/StreamReader.cs +++ b/src/mscorlib/src/System/IO/StreamReader.cs @@ -18,6 +18,7 @@ using System; using System.Text; using System.Runtime.InteropServices; using System.Runtime.Versioning; +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Security.Permissions; @@ -432,7 +433,7 @@ namespace System.IO // Trims n bytes from the front of the buffer. private void CompressBuffer(int n) { - Contract.Assert(byteLen >= n, "CompressBuffer was called with a number of bytes greater than the current buffer length. Are two threads using this StreamReader at the same time?"); + Debug.Assert(byteLen >= n, "CompressBuffer was called with a number of bytes greater than the current buffer length. Are two threads using this StreamReader at the same time?"); Buffer.InternalBlockCopy(byteBuffer, n, byteBuffer, 0, byteLen - n); byteLen -= n; } @@ -500,7 +501,7 @@ namespace System.IO if (!_checkPreamble) return _checkPreamble; - Contract.Assert(bytePos <= _preamble.Length, "_compressPreamble was called with the current bytePos greater than the preamble buffer length. Are two threads using this StreamReader at the same time?"); + Debug.Assert(bytePos <= _preamble.Length, "_compressPreamble was called with the current bytePos greater than the preamble buffer length. Are two threads using this StreamReader at the same time?"); int len = (byteLen >= (_preamble.Length))? (_preamble.Length - bytePos) : (byteLen - bytePos); for(int i=0; i= 0, "Stream.Read returned a negative number! This is a bug in your stream class."); + Debug.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class."); if (len == 0) { // EOF but we might have buffered bytes from previous @@ -586,9 +587,9 @@ namespace System.IO byteLen += len; } else { - Contract.Assert(bytePos == 0, "bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?"); + Debug.Assert(bytePos == 0, "bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?"); byteLen = stream.Read(byteBuffer, 0, byteBuffer.Length); - Contract.Assert(byteLen >= 0, "Stream.Read returned a negative number! This is a bug in your stream class."); + Debug.Assert(byteLen >= 0, "Stream.Read returned a negative number! This is a bug in your stream class."); if (byteLen == 0) // We're at EOF return charLen; @@ -648,12 +649,12 @@ namespace System.IO readToUserBuffer = desiredChars >= _maxCharsPerBuffer; do { - Contract.Assert(charsRead == 0); + Debug.Assert(charsRead == 0); if (_checkPreamble) { - Contract.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?"); + Debug.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?"); int len = stream.Read(byteBuffer, bytePos, byteBuffer.Length - bytePos); - Contract.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class."); + Debug.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class."); if (len == 0) { // EOF but we might have buffered bytes from previous @@ -675,11 +676,11 @@ namespace System.IO byteLen += len; } else { - Contract.Assert(bytePos == 0, "bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?"); + Debug.Assert(bytePos == 0, "bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?"); byteLen = stream.Read(byteBuffer, 0, byteBuffer.Length); - Contract.Assert(byteLen >= 0, "Stream.Read returned a negative number! This is a bug in your stream class."); + Debug.Assert(byteLen >= 0, "Stream.Read returned a negative number! This is a bug in your stream class."); if (byteLen == 0) // EOF break; @@ -955,14 +956,14 @@ namespace System.IO // We break out of the loop if the stream is blocked (EOF is reached). do { - Contract.Assert(n == 0); + Debug.Assert(n == 0); if (CheckPreamble_Prop) { - Contract.Assert(BytePos_Prop <= Preamble_Prop.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?"); + Debug.Assert(BytePos_Prop <= Preamble_Prop.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?"); int tmpBytePos = BytePos_Prop; int len = await tmpStream.ReadAsync(tmpByteBuffer, tmpBytePos, tmpByteBuffer.Length - tmpBytePos).ConfigureAwait(false); - Contract.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class."); + Debug.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class."); if (len == 0) { @@ -983,7 +984,7 @@ namespace System.IO } // How can part of the preamble yield any chars? - Contract.Assert(n == 0); + Debug.Assert(n == 0); IsBlocked_Prop = true; break; @@ -995,11 +996,11 @@ namespace System.IO } else { - Contract.Assert(BytePos_Prop == 0, "_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?"); + Debug.Assert(BytePos_Prop == 0, "_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?"); ByteLen_Prop = await tmpStream.ReadAsync(tmpByteBuffer, 0, tmpByteBuffer.Length).ConfigureAwait(false); - Contract.Assert(ByteLen_Prop >= 0, "Stream.Read returned a negative number! This is a bug in your stream class."); + Debug.Assert(ByteLen_Prop >= 0, "Stream.Read returned a negative number! This is a bug in your stream class."); if (ByteLen_Prop == 0) // EOF { @@ -1029,7 +1030,7 @@ namespace System.IO readToUserBuffer = count >= MaxCharsPerBuffer_Prop; } - Contract.Assert(n == 0); + Debug.Assert(n == 0); CharPos_Prop = 0; if (readToUserBuffer) @@ -1037,7 +1038,7 @@ namespace System.IO n += Decoder_Prop.GetChars(tmpByteBuffer, 0, ByteLen_Prop, buffer, index + charsRead); // Why did the bytes yield no chars? - Contract.Assert(n > 0); + Debug.Assert(n > 0); CharLen_Prop = 0; // StreamReader's buffer is empty. } @@ -1046,7 +1047,7 @@ namespace System.IO n = Decoder_Prop.GetChars(tmpByteBuffer, 0, ByteLen_Prop, CharBuffer_Prop, 0); // Why did the bytes yield no chars? - Contract.Assert(n > 0); + Debug.Assert(n > 0); CharLen_Prop += n; // Number of chars in StreamReader's buffer. } @@ -1183,10 +1184,10 @@ namespace System.IO ByteLen_Prop = 0; do { if (CheckPreamble_Prop) { - Contract.Assert(BytePos_Prop <= Preamble_Prop.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?"); + Debug.Assert(BytePos_Prop <= Preamble_Prop.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?"); int tmpBytePos = BytePos_Prop; int len = await tmpStream.ReadAsync(tmpByteBuffer, tmpBytePos, tmpByteBuffer.Length - tmpBytePos).ConfigureAwait(false); - Contract.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class."); + Debug.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class."); if (len == 0) { // EOF but we might have buffered bytes from previous @@ -1204,9 +1205,9 @@ namespace System.IO ByteLen_Prop += len; } else { - Contract.Assert(BytePos_Prop == 0, "_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?"); + Debug.Assert(BytePos_Prop == 0, "_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?"); ByteLen_Prop = await tmpStream.ReadAsync(tmpByteBuffer, 0, tmpByteBuffer.Length).ConfigureAwait(false); - Contract.Assert(ByteLen_Prop >= 0, "Stream.Read returned a negative number! Bug in stream class."); + Debug.Assert(ByteLen_Prop >= 0, "Stream.Read returned a negative number! Bug in stream class."); if (ByteLen_Prop == 0) // We're at EOF return CharLen_Prop; diff --git a/src/mscorlib/src/System/IO/StreamWriter.cs b/src/mscorlib/src/System/IO/StreamWriter.cs index d95121a..470e891 100644 --- a/src/mscorlib/src/System/IO/StreamWriter.cs +++ b/src/mscorlib/src/System/IO/StreamWriter.cs @@ -21,6 +21,7 @@ using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Permissions; using System.Runtime.Serialization; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Threading.Tasks; @@ -335,7 +336,7 @@ namespace System.IO if (charPos == charLen) Flush(false, false); int n = charLen - charPos; if (n > count) n = count; - Contract.Assert(n > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a race condition in user code."); + Debug.Assert(n > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a race condition in user code."); Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char)); charPos += n; index += n; @@ -361,7 +362,7 @@ namespace System.IO if (charPos == charLen) Flush(false, false); int n = charLen - charPos; if (n > count) n = count; - Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code."); + Debug.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code."); Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char)); charPos += n; index += n; @@ -383,7 +384,7 @@ namespace System.IO if (charPos == charLen) Flush(false, false); int n = charLen - charPos; if (n > count) n = count; - Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code."); + Debug.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code."); value.CopyTo(index, charBuffer, charPos, n); charPos += n; index += n; @@ -425,7 +426,7 @@ namespace System.IO { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); - Contract.Assert(_this.charPos == 0); + Debug.Assert(_this.charPos == 0); charPos = 0; } @@ -438,7 +439,7 @@ namespace System.IO { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); - Contract.Assert(_this.charPos == 0); + Debug.Assert(_this.charPos == 0); charPos = 0; } @@ -449,7 +450,7 @@ namespace System.IO if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); - Contract.Assert(_this.charPos == 0); + Debug.Assert(_this.charPos == 0); charPos = 0; } @@ -501,7 +502,7 @@ namespace System.IO { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); - Contract.Assert(_this.charPos == 0); + Debug.Assert(_this.charPos == 0); charPos = 0; } @@ -509,7 +510,7 @@ namespace System.IO if (n > count) n = count; - Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code."); + Debug.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code."); value.CopyTo(index, charBuffer, charPos, n); @@ -524,7 +525,7 @@ namespace System.IO { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); - Contract.Assert(_this.charPos == 0); + Debug.Assert(_this.charPos == 0); charPos = 0; } @@ -535,7 +536,7 @@ namespace System.IO if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); - Contract.Assert(_this.charPos == 0); + Debug.Assert(_this.charPos == 0); charPos = 0; } @@ -590,14 +591,14 @@ namespace System.IO { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); - Contract.Assert(_this.charPos == 0); + Debug.Assert(_this.charPos == 0); charPos = 0; } int n = charLen - charPos; if (n > count) n = count; - Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code."); + Debug.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code."); Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char)); @@ -612,7 +613,7 @@ namespace System.IO { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); - Contract.Assert(_this.charPos == 0); + Debug.Assert(_this.charPos == 0); charPos = 0; } @@ -623,7 +624,7 @@ namespace System.IO if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); - Contract.Assert(_this.charPos == 0); + Debug.Assert(_this.charPos == 0); charPos = 0; } diff --git a/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs b/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs index 6149dbc..4208ebf 100644 --- a/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs +++ b/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs @@ -19,6 +19,7 @@ using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Security.Permissions; using Microsoft.Win32.SafeHandles; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.IO { @@ -1131,9 +1132,9 @@ namespace System.IO { } private byte InternalReadByte(Int64 position) { - Contract.Assert(CanRead, "UMA not readable"); - Contract.Assert(position >= 0, "position less than 0"); - Contract.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)"); + Debug.Assert(CanRead, "UMA not readable"); + Debug.Assert(position >= 0, "position less than 0"); + Debug.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)"); byte result; unsafe { @@ -1153,9 +1154,9 @@ namespace System.IO { } private void InternalWrite(Int64 position, byte value) { - Contract.Assert(CanWrite, "UMA not writable"); - Contract.Assert(position >= 0, "position less than 0"); - Contract.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)"); + Debug.Assert(CanWrite, "UMA not writable"); + Debug.Assert(position >= 0, "position less than 0"); + Debug.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)"); unsafe { byte* pointer = null; diff --git a/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs b/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs index 7ddfb46..f73b5d0 100644 --- a/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs +++ b/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs @@ -19,6 +19,7 @@ using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Threading; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Threading.Tasks; @@ -387,7 +388,7 @@ namespace System.IO { int nInt = (int) n; // Safe because n <= count, which is an Int32 if (nInt < 0) return 0; // _position could be beyond EOF - Contract.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1. + Debug.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1. unsafe { @@ -445,7 +446,7 @@ namespace System.IO { } catch (Exception ex) { - Contract.Assert(! (ex is OperationCanceledException)); + Debug.Assert(! (ex is OperationCanceledException)); return Task.FromException(ex); } } @@ -513,7 +514,7 @@ namespace System.IO { } long finalPos = Interlocked.Read(ref _position); - Contract.Assert(finalPos >= 0, "_position >= 0"); + Debug.Assert(finalPos >= 0, "_position >= 0"); return finalPos; } @@ -643,7 +644,7 @@ namespace System.IO { } catch (Exception ex) { - Contract.Assert(! (ex is OperationCanceledException)); + Debug.Assert(! (ex is OperationCanceledException)); return Task.FromException(ex); } } diff --git a/src/mscorlib/src/System/Lazy.cs b/src/mscorlib/src/System/Lazy.cs index 3f8151c..85cbb98 100644 --- a/src/mscorlib/src/System/Lazy.cs +++ b/src/mscorlib/src/System/Lazy.cs @@ -87,7 +87,7 @@ namespace System // 2- Flag to m_threadSafeObj if ExecutionAndPublication mode and the value is known to be initialized static readonly Func ALREADY_INVOKED_SENTINEL = delegate { - Contract.Assert(false, "ALREADY_INVOKED_SENTINEL should never be invoked."); + Debug.Assert(false, "ALREADY_INVOKED_SENTINEL should never be invoked."); return default(T); }; @@ -333,7 +333,7 @@ namespace System } LazyInternalExceptionHolder exc = m_boxed as LazyInternalExceptionHolder; - Contract.Assert(exc != null); + Debug.Assert(exc != null); exc.m_edi.Throw(); } @@ -382,7 +382,7 @@ namespace System if (threadSafeObj != (object)ALREADY_INVOKED_SENTINEL) Monitor.Enter(threadSafeObj, ref lockTaken); else - Contract.Assert(m_boxed != null); + Debug.Assert(m_boxed != null); if (m_boxed == null) { @@ -396,7 +396,7 @@ namespace System if (boxed == null) // it is not Boxed, so it is a LazyInternalExceptionHolder { LazyInternalExceptionHolder exHolder = m_boxed as LazyInternalExceptionHolder; - Contract.Assert(exHolder != null); + Debug.Assert(exHolder != null); exHolder.m_edi.Throw(); } } @@ -407,7 +407,7 @@ namespace System Monitor.Exit(threadSafeObj); } } - Contract.Assert(boxed != null); + Debug.Assert(boxed != null); return boxed.m_value; } diff --git a/src/mscorlib/src/System/MulticastDelegate.cs b/src/mscorlib/src/System/MulticastDelegate.cs index 1c35d46..a7b244c 100644 --- a/src/mscorlib/src/System/MulticastDelegate.cs +++ b/src/mscorlib/src/System/MulticastDelegate.cs @@ -9,6 +9,7 @@ namespace System using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.Serialization; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Reflection.Emit; @@ -108,7 +109,7 @@ namespace System // Since this is a MulticastDelegate and we know // the types are the same, obj should also be a // MulticastDelegate - Contract.Assert(obj is MulticastDelegate, "Shouldn't have failed here since we already checked the types are the same!"); + Debug.Assert(obj is MulticastDelegate, "Shouldn't have failed here since we already checked the types are the same!"); var d = JitHelpers.UnsafeCast(obj); if (_invocationCount != (IntPtr)0) @@ -145,7 +146,7 @@ namespace System } else { - Contract.Assert((_invocationList as Object[]) != null, "empty invocation list on multicast delegate"); + Debug.Assert((_invocationList as Object[]) != null, "empty invocation list on multicast delegate"); return InvocationListEquals(d); } } @@ -176,7 +177,7 @@ namespace System // Recursive function which will check for equality of the invocation list. private bool InvocationListEquals(MulticastDelegate d) { - Contract.Assert(d != null && (_invocationList as Object[]) != null, "bogus delegate in multicast list comparison"); + Debug.Assert(d != null && (_invocationList as Object[]) != null, "bogus delegate in multicast list comparison"); Object[] invocationList = _invocationList as Object[]; if (d._invocationCount != _invocationCount) return false; @@ -247,7 +248,7 @@ namespace System { if (_invocationCount != (IntPtr)0) { - Contract.Assert(!IsUnmanagedFunctionPtr(), "dynamic method and unmanaged fntptr delegate combined"); + Debug.Assert(!IsUnmanagedFunctionPtr(), "dynamic method and unmanaged fntptr delegate combined"); // must be a secure/wrapper one, unwrap and save MulticastDelegate d = (MulticastDelegate)_invocationList; d._methodBase = dynamicMethod; diff --git a/src/mscorlib/src/System/Number.cs b/src/mscorlib/src/System/Number.cs index 1f2e79e..3412c02 100644 --- a/src/mscorlib/src/System/Number.cs +++ b/src/mscorlib/src/System/Number.cs @@ -11,6 +11,7 @@ namespace System { using System.Runtime.Versioning; using System.Security; using System.Text; + using System.Diagnostics; using System.Diagnostics.Contracts; // The Number class implements methods for formatting and parsing @@ -384,7 +385,7 @@ namespace System { return false; } Char* p = number.digits; - Contract.Assert(p != null, ""); + Debug.Assert(p != null, ""); UInt32 n = 0; while (--i >= 0) { @@ -403,7 +404,7 @@ namespace System { newN += (UInt32)((*p - 'A') + 10); } else { - Contract.Assert(*p >= 'a' && *p <= 'f', ""); + Debug.Assert(*p >= 'a' && *p <= 'f', ""); newN += (UInt32)((*p - 'a') + 10); } } @@ -428,7 +429,7 @@ namespace System { return false; } Char* p = number.digits; - Contract.Assert(p != null, ""); + Debug.Assert(p != null, ""); UInt64 n = 0; while (--i >= 0) { @@ -447,7 +448,7 @@ namespace System { newN += (UInt64)((*p - 'A') + 10); } else { - Contract.Assert(*p >= 'a' && *p <= 'f', ""); + Debug.Assert(*p >= 'a' && *p <= 'f', ""); newN += (UInt64)((*p - 'a') + 10); } } @@ -476,7 +477,7 @@ namespace System { return false; } char * p = number.digits; - Contract.Assert(p != null, ""); + Debug.Assert(p != null, ""); Int32 n = 0; while (--i >= 0) { if ((UInt32)n > (0x7FFFFFFF / 10)) { @@ -509,7 +510,7 @@ namespace System { return false; } char* p = number.digits; - Contract.Assert(p != null, ""); + Debug.Assert(p != null, ""); Int64 n = 0; while (--i >= 0) { if ((UInt64)n > (0x7FFFFFFFFFFFFFFF / 10)) { @@ -542,7 +543,7 @@ namespace System { return false; } char* p = number.digits; - Contract.Assert(p != null, ""); + Debug.Assert(p != null, ""); UInt32 n = 0; while (--i >= 0) { if (n > (0xFFFFFFFF / 10)) { @@ -569,7 +570,7 @@ namespace System { return false; } char * p = number.digits; - Contract.Assert(p != null, ""); + Debug.Assert(p != null, ""); UInt64 n = 0; while (--i >= 0) { if (n > (0xFFFFFFFFFFFFFFFF / 10)) { @@ -595,7 +596,7 @@ namespace System { } } private unsafe static char * MatchChars(char* p, char* str) { - Contract.Assert(p != null && str != null, ""); + Debug.Assert(p != null && str != null, ""); if (*str == '\0') { return null; @@ -959,7 +960,7 @@ namespace System { throw new ArgumentNullException(nameof(String)); } Contract.EndContractBlock(); - Contract.Assert(info != null, ""); + Debug.Assert(info != null, ""); fixed (char* stringPointer = str) { char * p = stringPointer; if (!ParseNumber(ref p, options, ref number, null, info , parseDecimal) @@ -1133,7 +1134,7 @@ namespace System { if (str == null) { return false; } - Contract.Assert(numfmt != null, ""); + Debug.Assert(numfmt != null, ""); fixed (char* stringPointer = str) { char * p = stringPointer; diff --git a/src/mscorlib/src/System/Progress.cs b/src/mscorlib/src/System/Progress.cs index a8b48fd..72c43c3 100644 --- a/src/mscorlib/src/System/Progress.cs +++ b/src/mscorlib/src/System/Progress.cs @@ -48,7 +48,7 @@ namespace System // sync ctx reference identity issues where the sync ctx for one thread could be Current on another. // If there is no current context, we use a default instance targeting the ThreadPool. m_synchronizationContext = SynchronizationContext.CurrentNoFlow ?? ProgressStatics.DefaultContext; - Contract.Assert(m_synchronizationContext != null); + Debug.Assert(m_synchronizationContext != null); m_invokeHandlers = new SendOrPostCallback(InvokeHandlers); } diff --git a/src/mscorlib/src/System/Reflection/Associates.cs b/src/mscorlib/src/System/Reflection/Associates.cs index 290a629..9eaf74a 100644 --- a/src/mscorlib/src/System/Reflection/Associates.cs +++ b/src/mscorlib/src/System/Reflection/Associates.cs @@ -8,6 +8,7 @@ namespace System.Reflection { using System; using System.Collections.Generic; + using System.Diagnostics; using System.Diagnostics.Contracts; internal static class Associates @@ -43,8 +44,8 @@ namespace System.Reflection if (MetadataToken.IsNullToken(tkMethod)) return null; - Contract.Assert(declaredType != null); - Contract.Assert(reflectedType != null); + Debug.Assert(declaredType != null); + Debug.Assert(reflectedType != null); bool isInherited = declaredType != reflectedType; @@ -62,7 +63,7 @@ namespace System.Reflection } RuntimeMethodHandleInternal associateMethodHandle = ModuleHandle.ResolveMethodHandleInternalCore(RuntimeTypeHandle.GetModule(declaredType), tkMethod, genericArgumentHandles, genericArgumentCount, null, 0); - Contract.Assert(!associateMethodHandle.IsNullHandle(), "Failed to resolve associateRecord methodDef token"); + Debug.Assert(!associateMethodHandle.IsNullHandle(), "Failed to resolve associateRecord methodDef token"); if (isInherited) { diff --git a/src/mscorlib/src/System/Reflection/CustomAttribute.cs b/src/mscorlib/src/System/Reflection/CustomAttribute.cs index b27430d..e568a17 100644 --- a/src/mscorlib/src/System/Reflection/CustomAttribute.cs +++ b/src/mscorlib/src/System/Reflection/CustomAttribute.cs @@ -65,7 +65,7 @@ namespace System.Reflection #region Internal Static Members internal static IList GetCustomAttributesInternal(RuntimeType target) { - Contract.Assert(target != null); + Debug.Assert(target != null); IList cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); @@ -87,7 +87,7 @@ namespace System.Reflection internal static IList GetCustomAttributesInternal(RuntimeFieldInfo target) { - Contract.Assert(target != null); + Debug.Assert(target != null); IList cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); @@ -109,7 +109,7 @@ namespace System.Reflection internal static IList GetCustomAttributesInternal(RuntimeMethodInfo target) { - Contract.Assert(target != null); + Debug.Assert(target != null); IList cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); @@ -131,28 +131,28 @@ namespace System.Reflection internal static IList GetCustomAttributesInternal(RuntimeConstructorInfo target) { - Contract.Assert(target != null); + Debug.Assert(target != null); return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); } internal static IList GetCustomAttributesInternal(RuntimeEventInfo target) { - Contract.Assert(target != null); + Debug.Assert(target != null); return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); } internal static IList GetCustomAttributesInternal(RuntimePropertyInfo target) { - Contract.Assert(target != null); + Debug.Assert(target != null); return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); } internal static IList GetCustomAttributesInternal(RuntimeModule target) { - Contract.Assert(target != null); + Debug.Assert(target != null); if (target.IsResource()) return new List(); @@ -162,7 +162,7 @@ namespace System.Reflection internal static IList GetCustomAttributesInternal(RuntimeAssembly target) { - Contract.Assert(target != null); + Debug.Assert(target != null); IList cad = GetCustomAttributes((RuntimeModule)target.ManifestModule, RuntimeAssembly.GetToken(target.GetNativeHandle())); @@ -184,7 +184,7 @@ namespace System.Reflection internal static IList GetCustomAttributesInternal(RuntimeParameterInfo target) { - Contract.Assert(target != null); + Debug.Assert(target != null); IList cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); @@ -825,7 +825,7 @@ namespace System.Reflection private static object CanonicalizeValue(object value) { - Contract.Assert(value != null); + Debug.Assert(value != null); if (value.GetType().IsEnum) { @@ -1019,8 +1019,8 @@ namespace System.Reflection throw new ArgumentNullException(nameof(customAttributeModule)); Contract.EndContractBlock(); - Contract.Assert(customAttributeCtorParameters != null); - Contract.Assert(customAttributeNamedParameters != null); + Debug.Assert(customAttributeCtorParameters != null); + Debug.Assert(customAttributeNamedParameters != null); if (customAttributeCtorParameters.Length != 0 || customAttributeNamedParameters.Length != 0) { @@ -1361,7 +1361,7 @@ namespace System.Reflection else { type = type.DeclaringType as RuntimeType; - Contract.Assert(type != null); + Debug.Assert(type != null); } } @@ -1557,7 +1557,7 @@ namespace System.Reflection if (attributeFilterType != null) { - Contract.Assert(attributeCtorToken == 0); + Debug.Assert(attributeCtorToken == 0); MetadataImport scope = decoratedModule.MetadataImport; RuntimeType attributeType; @@ -1580,8 +1580,8 @@ namespace System.Reflection } else { - Contract.Assert(attributeFilterType == null); - Contract.Assert(!MetadataToken.IsNullToken(attributeCtorToken)); + Debug.Assert(attributeFilterType == null); + Debug.Assert(!MetadataToken.IsNullToken(attributeCtorToken)); for (int i = 0; i < car.Length; i++) { @@ -1881,7 +1881,7 @@ namespace System.Reflection else { // We need to relax this when we add support for other types of decorated tokens. - Contract.Assert(decoratedToken.IsModule || decoratedToken.IsAssembly, + Debug.Assert(decoratedToken.IsModule || decoratedToken.IsAssembly, "The decoratedToken must be either an assembly, a module, a type, or a member."); } @@ -2058,11 +2058,11 @@ namespace System.Reflection { // If any of these are invariants are no longer true will have to // re-architect the PCA product logic and test cases -- you've been warned! - Contract.Assert(pca.BaseType == (RuntimeType)typeof(Attribute), "Pseudo CA Error"); + Debug.Assert(pca.BaseType == (RuntimeType)typeof(Attribute), "Pseudo CA Error"); AttributeUsageAttribute usage = CustomAttribute.GetAttributeUsage(pca); - Contract.Assert(usage.Inherited == false, "Pseudo CA Error"); + Debug.Assert(usage.Inherited == false, "Pseudo CA Error"); //AllowMultiple is true for TypeForwardedToAttribute - //Contract.Assert(usage.AllowMultiple == false, "Pseudo CA Error"); + //Debug.Assert(usage.AllowMultiple == false, "Pseudo CA Error"); } #endregion diff --git a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs index 41c1d31..a7d1718 100644 --- a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs @@ -189,7 +189,7 @@ namespace System.Reflection.Emit internal ModuleBuilder GetModuleBuilder(InternalModuleBuilder module) { Contract.Requires(module != null); - Contract.Assert(this.InternalAssembly == module.Assembly); + Debug.Assert(this.InternalAssembly == module.Assembly); lock(SyncRoot) { @@ -516,7 +516,7 @@ namespace System.Reflection.Emit BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.DefineDynamicModule( " + name + " )"); - Contract.Assert(m_assemblyData != null, "m_assemblyData is null in DefineDynamicModuleInternal"); + Debug.Assert(m_assemblyData != null, "m_assemblyData is null in DefineDynamicModuleInternal"); ModuleBuilder dynModule; ISymbolWriter writer = null; diff --git a/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs index ecbb811..1577f11 100644 --- a/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs @@ -22,6 +22,7 @@ namespace System.Reflection.Emit { using System.Security.Permissions; using System.Runtime.InteropServices; using System.Globalization; + using System.Diagnostics; using System.Diagnostics.Contracts; [HostProtection(MayLeakOnAbort = true)] @@ -353,7 +354,7 @@ namespace System.Reflection.Emit { writer.Write((byte)CustomAttributeEncoding.Double); break; default: - Contract.Assert(false, "Invalid primitive type"); + Debug.Assert(false, "Invalid primitive type"); break; } } @@ -437,7 +438,7 @@ namespace System.Reflection.Emit { writer.Write((ulong)value); break; default: - Contract.Assert(false, "Invalid enum base type"); + Debug.Assert(false, "Invalid enum base type"); break; } } @@ -515,7 +516,7 @@ namespace System.Reflection.Emit { writer.Write((double)value); break; default: - Contract.Assert(false, "Invalid primitive type"); + Debug.Assert(false, "Invalid primitive type"); break; } } diff --git a/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs b/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs index 7d44fd9..9e1d829 100644 --- a/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs +++ b/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs @@ -16,6 +16,7 @@ namespace System.Reflection.Emit using System.Collections.Generic; using System.Security.Permissions; using System.Threading; + using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Security; @@ -360,7 +361,7 @@ namespace System.Reflection.Emit // SignatureHelper. if (opcode.StackBehaviourPop == StackBehaviour.Varpop) { - Contract.Assert(opcode.Equals(OpCodes.Calli), + Debug.Assert(opcode.Equals(OpCodes.Calli), "Unexpected opcode encountered for StackBehaviour VarPop."); // Pop the arguments.. stackchange -= signature.ArgumentCount; diff --git a/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs b/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs index 94f65fc..1b8c97d 100644 --- a/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs +++ b/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs @@ -15,6 +15,7 @@ namespace System.Reflection.Emit using System.Threading; using System.Runtime.CompilerServices; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; @@ -322,7 +323,7 @@ namespace System.Reflection.Emit if (transparentMethod) { - Contract.Assert(owner == null && m == null, "owner and m cannot be set for transparent methods"); + Debug.Assert(owner == null && m == null, "owner and m cannot be set for transparent methods"); m_module = GetDynamicMethodsModule(); if (skipVisibility) { @@ -335,9 +336,9 @@ namespace System.Reflection.Emit } else { - Contract.Assert(m != null || owner != null, "PerformSecurityCheck should ensure that either m or owner is set"); - Contract.Assert(m == null || !m.Equals(s_anonymouslyHostedDynamicMethodsModule), "The user cannot explicitly use this assembly"); - Contract.Assert(m == null || owner == null, "m and owner cannot both be set"); + Debug.Assert(m != null || owner != null, "PerformSecurityCheck should ensure that either m or owner is set"); + Debug.Assert(m == null || !m.Equals(s_anonymouslyHostedDynamicMethodsModule), "The user cannot explicitly use this assembly"); + Debug.Assert(m == null || owner == null, "m and owner cannot both be set"); if (m != null) m_module = m.ModuleHandle.GetRuntimeModule(); // this returns the underlying module for all RuntimeModule and ModuleBuilder objects. diff --git a/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs b/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs index 5ed2173..ed0763b 100644 --- a/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs +++ b/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs @@ -12,6 +12,7 @@ namespace System.Reflection.Emit using System.Reflection; using System.Security.Permissions; using System.Globalization; + using System.Diagnostics; using System.Diagnostics.Contracts; [ClassInterface(ClassInterfaceType.None)] @@ -410,7 +411,7 @@ namespace System.Reflection.Emit { if (m_RelocFixupCount == 0) { - Contract.Assert(m_RelocFixupList == null); + Debug.Assert(m_RelocFixupList == null); return null; } @@ -646,7 +647,7 @@ namespace System.Reflection.Emit // SignatureHelper. if (opcode.StackBehaviourPop == StackBehaviour.Varpop) { - Contract.Assert(opcode.Equals(OpCodes.Calli), + Debug.Assert(opcode.Equals(OpCodes.Calli), "Unexpected opcode encountered for StackBehaviour VarPop."); // Pop the arguments.. stackchange -= signature.ArgumentCount; @@ -679,7 +680,7 @@ namespace System.Reflection.Emit if (opcode.StackBehaviourPush == StackBehaviour.Varpush) { // Instruction must be one of call or callvirt. - Contract.Assert(opcode.Equals(OpCodes.Call) || + Debug.Assert(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt), "Unexpected opcode encountered for StackBehaviour of VarPush."); stackchange++; @@ -687,7 +688,7 @@ namespace System.Reflection.Emit if (opcode.StackBehaviourPop == StackBehaviour.Varpop) { // Instruction must be one of call, callvirt or newobj. - Contract.Assert(opcode.Equals(OpCodes.Call) || + Debug.Assert(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj), "Unexpected opcode encountered for StackBehaviour of VarPop."); @@ -1439,7 +1440,7 @@ namespace System.Reflection.Emit m_catchAddr[m_currentCatch] = -1; if (m_currentCatch > 0) { - Contract.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1"); + Debug.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1"); m_catchEndAddr[m_currentCatch-1] = catchorfilterAddr; } } @@ -1456,7 +1457,7 @@ namespace System.Reflection.Emit { if (m_type[m_currentCatch] != Filter) { - Contract.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1"); + Debug.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1"); m_catchEndAddr[m_currentCatch-1] = catchEndAddr; } } @@ -1498,9 +1499,9 @@ namespace System.Reflection.Emit } internal void Done(int endAddr) { - Contract.Assert(m_currentCatch > 0,"m_currentCatch > 0"); - Contract.Assert(m_catchAddr[m_currentCatch-1] > 0,"m_catchAddr[m_currentCatch-1] > 0"); - Contract.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1"); + Debug.Assert(m_currentCatch > 0,"m_currentCatch > 0"); + Debug.Assert(m_catchAddr[m_currentCatch-1] > 0,"m_catchAddr[m_currentCatch-1] > 0"); + Debug.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1"); m_catchEndAddr[m_currentCatch-1] = endAddr; m_currentState = State_Done; } @@ -1563,8 +1564,8 @@ namespace System.Reflection.Emit // not having a nesting relation. internal bool IsInner(__ExceptionInfo exc) { Contract.Requires(exc != null); - Contract.Assert(m_currentCatch > 0,"m_currentCatch > 0"); - Contract.Assert(exc.m_currentCatch > 0,"exc.m_currentCatch > 0"); + Debug.Assert(m_currentCatch > 0,"m_currentCatch > 0"); + Debug.Assert(exc.m_currentCatch > 0,"exc.m_currentCatch > 0"); int exclast = exc.m_currentCatch - 1; int last = m_currentCatch - 1; @@ -1573,7 +1574,7 @@ namespace System.Reflection.Emit return true; else if (exc.m_catchEndAddr[exclast] == m_catchEndAddr[last]) { - Contract.Assert(exc.GetEndAddress() != GetEndAddress(), + Debug.Assert(exc.GetEndAddress() != GetEndAddress(), "exc.GetEndAddress() != GetEndAddress()"); if (exc.GetEndAddress() > GetEndAddress()) return true; @@ -1785,7 +1786,7 @@ namespace System.Reflection.Emit // make sure that arrays are large enough to hold addition info i = FindDocument(document); - Contract.Assert(i < m_DocumentCount, "Bad document look up!"); + Debug.Assert(i < m_DocumentCount, "Bad document look up!"); m_Documents[i].AddLineNumberInfo(document, iOffset, iStartLine, iStartColumn, iEndLine, iEndColumn); } @@ -1873,7 +1874,7 @@ namespace System.Reflection.Emit int iEndLine, int iEndColumn) { - Contract.Assert(document == m_document, "Bad document look up!"); + Debug.Assert(document == m_document, "Bad document look up!"); // make sure that arrays are large enough to hold addition info EnsureCapacity(); diff --git a/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs index eda8546..8defdfa 100644 --- a/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs @@ -16,6 +16,7 @@ namespace System.Reflection.Emit using System.Collections.Generic; using System.Security.Permissions; using System.Runtime.InteropServices; + using System.Diagnostics; using System.Diagnostics.Contracts; [HostProtection(MayLeakOnAbort = true)] @@ -366,7 +367,7 @@ namespace System.Reflection.Emit } else { - Contract.Assert(false, "We should never get here!"); + Debug.Assert(false, "We should never get here!"); return null; } } @@ -762,15 +763,15 @@ namespace System.Reflection.Emit m_containingType.m_lastTokenizedMethod = i; } - Contract.Assert(currentMethod == this, "We should have found this method in m_containingType.m_listMethods"); - Contract.Assert(currentToken.Token != 0, "The token should not be 0"); + Debug.Assert(currentMethod == this, "We should have found this method in m_containingType.m_listMethods"); + Debug.Assert(currentToken.Token != 0, "The token should not be 0"); return currentToken; } private MethodToken GetTokenNoLock() { - Contract.Assert(m_tkMethod.Token == 0, "m_tkMethod should not have been initialized"); + Debug.Assert(m_tkMethod.Token == 0, "m_tkMethod should not have been initialized"); int sigLength; byte[] sigBytes = GetMethodSignature().InternalGetSignature(out sigLength); @@ -1442,13 +1443,13 @@ namespace System.Reflection.Emit internal ExceptionHandler(int tryStartOffset, int tryEndOffset, int filterOffset, int handlerStartOffset, int handlerEndOffset, int kind, int exceptionTypeToken) { - Contract.Assert(tryStartOffset >= 0); - Contract.Assert(tryEndOffset >= 0); - Contract.Assert(filterOffset >= 0); - Contract.Assert(handlerStartOffset >= 0); - Contract.Assert(handlerEndOffset >= 0); - Contract.Assert(IsValidKind((ExceptionHandlingClauseOptions)kind)); - Contract.Assert(kind != (int)ExceptionHandlingClauseOptions.Clause || (exceptionTypeToken & 0x00FFFFFF) != 0); + Debug.Assert(tryStartOffset >= 0); + Debug.Assert(tryEndOffset >= 0); + Debug.Assert(filterOffset >= 0); + Debug.Assert(handlerStartOffset >= 0); + Debug.Assert(handlerEndOffset >= 0); + Debug.Assert(IsValidKind((ExceptionHandlingClauseOptions)kind)); + Debug.Assert(kind != (int)ExceptionHandlingClauseOptions.Clause || (exceptionTypeToken & 0x00FFFFFF) != 0); m_tryStartOffset = tryStartOffset; m_tryEndOffset = tryEndOffset; diff --git a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs index 7cfe625..46ea6cd 100644 --- a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs @@ -12,7 +12,6 @@ namespace System.Reflection.Emit using System.Diagnostics.SymbolStore; using System.Globalization; using System.Reflection; - using System.Diagnostics; using System.IO; using System.Resources; using System.Security; @@ -22,6 +21,7 @@ namespace System.Reflection.Emit using System.Threading; using System.Runtime.Versioning; using System.Runtime.CompilerServices; + using System.Diagnostics; using System.Diagnostics.Contracts; internal sealed class InternalModuleBuilder : RuntimeModule @@ -182,7 +182,7 @@ namespace System.Reflection.Emit private int GetMemberRefOfMethodInfo(int tr, RuntimeMethodInfo method) { - Contract.Assert(method != null); + Debug.Assert(method != null); #if FEATURE_APPX if (ContainingAssemblyBuilder.ProfileAPICheck) @@ -197,7 +197,7 @@ namespace System.Reflection.Emit private int GetMemberRefOfMethodInfo(int tr, RuntimeConstructorInfo method) { - Contract.Assert(method != null); + Debug.Assert(method != null); #if FEATURE_APPX if (ContainingAssemblyBuilder.ProfileAPICheck) @@ -216,7 +216,7 @@ namespace System.Reflection.Emit private int GetMemberRefOfFieldInfo(int tkType, RuntimeTypeHandle declaringType, RuntimeFieldInfo runtimeField) { - Contract.Assert(runtimeField != null); + Debug.Assert(runtimeField != null); #if FEATURE_APPX if (ContainingAssemblyBuilder.ProfileAPICheck) @@ -341,8 +341,8 @@ namespace System.Reflection.Emit typeName = UnmangleTypeName(typeName); } - Contract.Assert(!type.IsByRef, "Must not be ByRef."); - Contract.Assert(!type.IsGenericType || type.IsGenericTypeDefinition, "Must not have generic arguments."); + Debug.Assert(!type.IsByRef, "Must not be ByRef."); + Debug.Assert(!type.IsGenericType || type.IsGenericTypeDefinition, "Must not have generic arguments."); #if FEATURE_APPX if (ContainingAssemblyBuilder.ProfileAPICheck) @@ -544,11 +544,11 @@ namespace System.Reflection.Emit } else { - Contract.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); + Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); if (method.IsGenericMethod) { - Contract.Assert(masmi != null); + Debug.Assert(masmi != null); methDef = masmi.GetGenericMethodDefinition(); methDef = methDef.Module.ResolveMethod( @@ -1061,10 +1061,10 @@ namespace System.Reflection.Emit EnumBuilder enumBuilder = DefineEnumNoLock(name, visibility, underlyingType); // This enum is not generic, nested, and cannot have any element type. - Contract.Assert(name == enumBuilder.FullName); + Debug.Assert(name == enumBuilder.FullName); // Replace the TypeBuilder object in m_TypeBuilderDict with this EnumBuilder object. - Contract.Assert(enumBuilder.m_typeBuilder == m_TypeBuilderDict[name]); + Debug.Assert(enumBuilder.m_typeBuilder == m_TypeBuilderDict[name]); m_TypeBuilderDict[name] = enumBuilder; return enumBuilder; @@ -1554,7 +1554,7 @@ namespace System.Reflection.Emit if (method.IsGenericMethod) { // Constructors cannot be generic. - Contract.Assert(methodInfo != null); + Debug.Assert(methodInfo != null); // Given M unbind to M MethodInfo methodInfoUnbound = methodInfo; diff --git a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs index 9ab1f2c..96e60d9 100644 --- a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs +++ b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs @@ -9,6 +9,7 @@ namespace System.Reflection.Emit { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.IO; @@ -55,7 +56,7 @@ namespace System.Reflection.Emit // each assembly). internal virtual void ModifyModuleName(String strModuleName) { - Contract.Assert(m_strModuleName == AssemblyBuilder.MANIFEST_MODULE_NAME, "Changing names for non-manifest module"); + Debug.Assert(m_strModuleName == AssemblyBuilder.MANIFEST_MODULE_NAME, "Changing names for non-manifest module"); InitNames(strModuleName, null /*strFileName*/); } diff --git a/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs b/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs index a22df56..c40035b 100644 --- a/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs +++ b/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs @@ -8,6 +8,7 @@ namespace System.Reflection.Emit { using System.Text; using System; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.CompilerServices; @@ -313,7 +314,7 @@ namespace System.Reflection.Emit AddElementType(CorElementType.CModOpt); int token = m_module.GetTypeToken(t).Token; - Contract.Assert(!MetadataToken.IsNullToken(token)); + Debug.Assert(!MetadataToken.IsNullToken(token)); AddToken(token); } } @@ -336,7 +337,7 @@ namespace System.Reflection.Emit AddElementType(CorElementType.CModReqd); int token = m_module.GetTypeToken(t).Token; - Contract.Assert(!MetadataToken.IsNullToken(token)); + Debug.Assert(!MetadataToken.IsNullToken(token)); AddToken(token); } } diff --git a/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs index 8572637..f6c1018 100644 --- a/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs @@ -10,13 +10,13 @@ namespace System.Reflection.Emit { using System.Reflection; using System.Security; using System.Security.Permissions; - using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Collections.Generic; using CultureInfo = System.Globalization.CultureInfo; using System.Threading; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; @@ -404,7 +404,7 @@ namespace System.Reflection.Emit { } else // must be a runtime Enum Type { - Contract.Assert(destType is RuntimeType, "destType is not a runtime type, an EnumBuilder, or a TypeBuilder."); + Debug.Assert(destType is RuntimeType, "destType is not a runtime type, an EnumBuilder, or a TypeBuilder."); underlyingType = Enum.GetUnderlyingType(destType); diff --git a/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs b/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs index 5b36e0e..aaaffc0 100644 --- a/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs +++ b/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs @@ -11,6 +11,7 @@ namespace System.Reflection.Emit using System.Collections; using System.Collections.Generic; using System.Globalization; + using System.Diagnostics; using System.Diagnostics.Contracts; internal sealed class MethodOnTypeBuilderInstantiation : MethodInfo @@ -30,7 +31,7 @@ namespace System.Reflection.Emit #region Constructor internal MethodOnTypeBuilderInstantiation(MethodInfo method, TypeBuilderInstantiation type) { - Contract.Assert(method is MethodBuilder || method is RuntimeMethodInfo); + Debug.Assert(method is MethodBuilder || method is RuntimeMethodInfo); m_method = method; m_type = type; @@ -60,7 +61,7 @@ namespace System.Reflection.Emit return mb.MetadataTokenInternal; else { - Contract.Assert(m_method is RuntimeMethodInfo); + Debug.Assert(m_method is RuntimeMethodInfo); return m_method.MetadataToken; } } @@ -122,7 +123,7 @@ namespace System.Reflection.Emit #region Constructor internal ConstructorOnTypeBuilderInstantiation(ConstructorInfo constructor, TypeBuilderInstantiation type) { - Contract.Assert(constructor is ConstructorBuilder || constructor is RuntimeConstructorInfo); + Debug.Assert(constructor is ConstructorBuilder || constructor is RuntimeConstructorInfo); m_ctor = constructor; m_type = type; @@ -157,7 +158,7 @@ namespace System.Reflection.Emit return cb.MetadataTokenInternal; else { - Contract.Assert(m_ctor is RuntimeConstructorInfo); + Debug.Assert(m_ctor is RuntimeConstructorInfo); return m_ctor.MetadataToken; } } @@ -231,7 +232,7 @@ namespace System.Reflection.Emit #region Constructor internal FieldOnTypeBuilderInstantiation(FieldInfo field, TypeBuilderInstantiation type) { - Contract.Assert(field is FieldBuilder || field is RuntimeFieldInfo); + Debug.Assert(field is FieldBuilder || field is RuntimeFieldInfo); m_field = field; m_type = type; @@ -258,7 +259,7 @@ namespace System.Reflection.Emit return fb.MetadataTokenInternal; else { - Contract.Assert(m_field is RuntimeFieldInfo); + Debug.Assert(m_field is RuntimeFieldInfo); return m_field.MetadataToken; } } diff --git a/src/mscorlib/src/System/Reflection/EventInfo.cs b/src/mscorlib/src/System/Reflection/EventInfo.cs index d801bcb..0eabb9d 100644 --- a/src/mscorlib/src/System/Reflection/EventInfo.cs +++ b/src/mscorlib/src/System/Reflection/EventInfo.cs @@ -120,7 +120,7 @@ namespace System.Reflection throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotSupportedOnWinRTEvent")); // Must be a normal non-WinRT event - Contract.Assert(addMethod.ReturnType == typeof(void)); + Debug.Assert(addMethod.ReturnType == typeof(void)); #endif // FEATURE_COMINTEROP addMethod.Invoke(target, new object[] { handler }); @@ -137,13 +137,13 @@ namespace System.Reflection #if FEATURE_COMINTEROP ParameterInfo[] parameters = removeMethod.GetParametersNoCopy(); - Contract.Assert(parameters != null && parameters.Length == 1); + Debug.Assert(parameters != null && parameters.Length == 1); if (parameters[0].ParameterType == typeof(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotSupportedOnWinRTEvent")); // Must be a normal non-WinRT event - Contract.Assert(parameters[0].ParameterType.BaseType == typeof(MulticastDelegate)); + Debug.Assert(parameters[0].ParameterType.BaseType == typeof(MulticastDelegate)); #endif // FEATURE_COMINTEROP removeMethod.Invoke(target, new object[] { handler }); @@ -215,7 +215,7 @@ namespace System.Reflection { Contract.Requires(declaredType != null); Contract.Requires(reflectedTypeCache != null); - Contract.Assert(!reflectedTypeCache.IsGlobal); + Debug.Assert(!reflectedTypeCache.IsGlobal); MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport; diff --git a/src/mscorlib/src/System/Reflection/MethodBody.cs b/src/mscorlib/src/System/Reflection/MethodBody.cs index 81d7a9e..4634623 100644 --- a/src/mscorlib/src/System/Reflection/MethodBody.cs +++ b/src/mscorlib/src/System/Reflection/MethodBody.cs @@ -7,6 +7,7 @@ using System; using System.Globalization; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Reflection @@ -160,7 +161,7 @@ namespace System.Reflection #endregion #region Public Members - public virtual Type LocalType { get { Contract.Assert(m_type != null, "type must be set!"); return m_type; } } + public virtual Type LocalType { get { Debug.Assert(m_type != null, "type must be set!"); return m_type; } } public virtual bool IsPinned { get { return m_isPinned != 0; } } public virtual int LocalIndex { get { return m_localIndex; } } #endregion diff --git a/src/mscorlib/src/System/Reflection/MethodInfo.cs b/src/mscorlib/src/System/Reflection/MethodInfo.cs index 52d9d3a..39387b1 100644 --- a/src/mscorlib/src/System/Reflection/MethodInfo.cs +++ b/src/mscorlib/src/System/Reflection/MethodInfo.cs @@ -213,8 +213,8 @@ namespace System.Reflection { Contract.Ensures(!m_handle.IsNull()); - Contract.Assert(!handle.IsNullHandle()); - Contract.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle)); + Debug.Assert(!handle.IsNullHandle()); + Debug.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle)); m_bindingFlags = bindingFlags; m_declaringType = declaringType; diff --git a/src/mscorlib/src/System/Reflection/ParameterInfo.cs b/src/mscorlib/src/System/Reflection/ParameterInfo.cs index 5d19bdc..6592e5a 100644 --- a/src/mscorlib/src/System/Reflection/ParameterInfo.cs +++ b/src/mscorlib/src/System/Reflection/ParameterInfo.cs @@ -8,6 +8,7 @@ namespace System.Reflection { using System; using System.Collections.Generic; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.Serialization; @@ -237,7 +238,7 @@ namespace System.Reflection #region Static Members internal unsafe static ParameterInfo[] GetParameters(IRuntimeMethodInfo method, MemberInfo member, Signature sig) { - Contract.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); + Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); ParameterInfo dummy; return GetParameters(method, member, sig, out dummy, false); @@ -245,7 +246,7 @@ namespace System.Reflection internal unsafe static ParameterInfo GetReturnParameter(IRuntimeMethodInfo method, MemberInfo member, Signature sig) { - Contract.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); + Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); ParameterInfo returnParameter; GetParameters(method, member, sig, out returnParameter, true); @@ -363,7 +364,7 @@ namespace System.Reflection get { MethodBase result = m_originalMember != null ? m_originalMember : MemberImpl as MethodBase; - Contract.Assert(result != null); + Debug.Assert(result != null); return result; } } @@ -420,7 +421,7 @@ namespace System.Reflection // The original owner should always be a method, because this method is only used to // change the owner from a method to a property. m_originalMember = accessor.MemberImpl as MethodBase; - Contract.Assert(m_originalMember != null); + Debug.Assert(m_originalMember != null); // Populate all the caches -- we inherit this behavior from RTM NameImpl = accessor.Name; @@ -440,8 +441,8 @@ namespace System.Reflection int position, ParameterAttributes attributes, MemberInfo member) { Contract.Requires(member != null); - Contract.Assert(MdToken.IsNullToken(tkParamDef) == scope.Equals(MetadataImport.EmptyImport)); - Contract.Assert(MdToken.IsNullToken(tkParamDef) || MdToken.IsTokenOfType(tkParamDef, MetadataTokenType.ParamDef)); + Debug.Assert(MdToken.IsNullToken(tkParamDef) == scope.Equals(MetadataImport.EmptyImport)); + Debug.Assert(MdToken.IsNullToken(tkParamDef) || MdToken.IsTokenOfType(tkParamDef, MetadataTokenType.ParamDef)); PositionImpl = position; MemberImpl = member; @@ -483,7 +484,7 @@ namespace System.Reflection else parameterType = m_signature.Arguments[PositionImpl]; - Contract.Assert(parameterType != null); + Debug.Assert(parameterType != null); // different thread could only write ClassImpl to the same value, so a race condition is not a problem here ClassImpl = parameterType; } @@ -559,7 +560,7 @@ namespace System.Reflection // returns DBNull.Value if the parameter doesn't have a default value private Object GetDefaultValueInternal(bool raw) { - Contract.Assert(!m_noMetadata); + Debug.Assert(!m_noMetadata); if (m_noDefaultValue) return DBNull.Value; diff --git a/src/mscorlib/src/System/Reflection/PropertyInfo.cs b/src/mscorlib/src/System/Reflection/PropertyInfo.cs index 79f838f..e31b378 100644 --- a/src/mscorlib/src/System/Reflection/PropertyInfo.cs +++ b/src/mscorlib/src/System/Reflection/PropertyInfo.cs @@ -176,7 +176,7 @@ namespace System.Reflection { Contract.Requires(declaredType != null); Contract.Requires(reflectedTypeCache != null); - Contract.Assert(!reflectedTypeCache.IsGlobal); + Debug.Assert(!reflectedTypeCache.IsGlobal); MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport; diff --git a/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs b/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs index eba471b..76bf000 100644 --- a/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs +++ b/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs @@ -23,6 +23,7 @@ namespace System.Resources { using System.Runtime.Versioning; using System.Text; using System.Threading; + using System.Diagnostics; using System.Diagnostics.Contracts; internal class FileBasedResourceGroveler : IResourceGroveler @@ -31,7 +32,7 @@ namespace System.Resources { public FileBasedResourceGroveler(ResourceManager.ResourceManagerMediator mediator) { - Contract.Assert(mediator != null, "mediator shouldn't be null; check caller"); + Debug.Assert(mediator != null, "mediator shouldn't be null; check caller"); _mediator = mediator; } @@ -40,7 +41,7 @@ namespace System.Resources { // manifest-based classes. Want to continue tightening the design to get rid of unused params. public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary localResourceSets, bool tryParents, bool createIfNotExists, ref StackCrawlMark stackMark) { - Contract.Assert(culture != null, "culture shouldn't be null; check caller"); + Debug.Assert(culture != null, "culture shouldn't be null; check caller"); String fileName = null; ResourceSet rs = null; @@ -88,8 +89,8 @@ namespace System.Resources { private String FindResourceFile(CultureInfo culture, String fileName) { - Contract.Assert(culture != null, "culture shouldn't be null; check caller"); - Contract.Assert(fileName != null, "fileName shouldn't be null; check caller"); + Debug.Assert(culture != null, "culture shouldn't be null; check caller"); + Debug.Assert(fileName != null, "fileName shouldn't be null; check caller"); // If we have a moduleDir, check there first. Get module fully // qualified name, append path to that. @@ -128,7 +129,7 @@ namespace System.Resources { // for perf and working set reasons. private ResourceSet CreateResourceSet(String file) { - Contract.Assert(file != null, "file shouldn't be null; check caller"); + Debug.Assert(file != null, "file shouldn't be null; check caller"); if (_mediator.UserResourceSet == null) { diff --git a/src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs b/src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs index b80b412..78e961a 100644 --- a/src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs +++ b/src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs @@ -26,6 +26,7 @@ namespace System.Resources { using System.Runtime.Versioning; using System.Text; using System.Threading; + using System.Diagnostics; using System.Diagnostics.Contracts; using Microsoft.Win32; @@ -54,8 +55,8 @@ namespace System.Resources { [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary localResourceSets, bool tryParents, bool createIfNotExists, ref StackCrawlMark stackMark) { - Contract.Assert(culture != null, "culture shouldn't be null; check caller"); - Contract.Assert(localResourceSets != null, "localResourceSets shouldn't be null; check caller"); + Debug.Assert(culture != null, "culture shouldn't be null; check caller"); + Debug.Assert(localResourceSets != null, "localResourceSets shouldn't be null; check caller"); ResourceSet rs = null; Stream stream = null; @@ -151,7 +152,7 @@ namespace System.Resources { internal static CultureInfo GetNeutralResourcesLanguage(Assembly a, ref UltimateResourceFallbackLocation fallbackLocation) { - Contract.Assert(a != null, "assembly != null"); + Debug.Assert(a != null, "assembly != null"); string cultureName = null; short fallback = 0; if (GetNeutralResourcesLanguageAttribute(((RuntimeAssembly)a).GetNativeHandle(), @@ -179,7 +180,7 @@ namespace System.Resources { // fires, please fix the build process for the BCL directory. if (a == typeof(Object).Assembly) { - Contract.Assert(false, System.CoreLib.Name+"'s NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + cultureName + "\" Exception: " + e); + Debug.Assert(false, System.CoreLib.Name+"'s NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + cultureName + "\" Exception: " + e); return CultureInfo.InvariantCulture; } @@ -195,7 +196,7 @@ namespace System.Resources { // This method could use some refactoring. One thing at a time. internal ResourceSet CreateResourceSet(Stream store, Assembly assembly) { - Contract.Assert(store != null, "I need a Stream!"); + Debug.Assert(store != null, "I need a Stream!"); // Check to see if this is a Stream the ResourceManager understands, // and check for the correct resource reader type. if (store.CanSeek && store.Length > 4) @@ -275,7 +276,7 @@ namespace System.Resources { Type resSetType; if (_mediator.UserResourceSet == null) { - Contract.Assert(resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here."); + Debug.Assert(resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here."); resSetType = Type.GetType(resSetTypeName, true, false); } else @@ -442,14 +443,14 @@ namespace System.Resources { int hr = fle._HResult; if (hr != Win32Native.MakeHRFromErrorCode(Win32Native.ERROR_ACCESS_DENIED)) { - Contract.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + " with error code 0x" + hr.ToString("X", CultureInfo.InvariantCulture) + Environment.NewLine + "Exception: " + fle); + Debug.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + " with error code 0x" + hr.ToString("X", CultureInfo.InvariantCulture) + Environment.NewLine + "Exception: " + fle); } } // Don't throw for zero-length satellite assemblies, for compat with v1 catch (BadImageFormatException bife) { - Contract.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + Environment.NewLine + "Exception: " + bife); + Debug.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + Environment.NewLine + "Exception: " + bife); } return satellite; @@ -463,8 +464,8 @@ namespace System.Resources { // and causes partially trusted localized apps to fail. private bool CanUseDefaultResourceClasses(String readerTypeName, String resSetTypeName) { - Contract.Assert(readerTypeName != null, "readerTypeName shouldn't be null; check caller"); - Contract.Assert(resSetTypeName != null, "resSetTypeName shouldn't be null; check caller"); + Debug.Assert(readerTypeName != null, "readerTypeName shouldn't be null; check caller"); + Debug.Assert(resSetTypeName != null, "resSetTypeName shouldn't be null; check caller"); if (_mediator.UserResourceSet != null) return false; @@ -530,7 +531,7 @@ namespace System.Resources { if (_mediator.MainAssembly == typeof(Object).Assembly && _mediator.BaseName.Equals(System.CoreLib.Name)) { // This would break CultureInfo & all our exceptions. - Contract.Assert(false, "Couldn't get " + System.CoreLib.Name+ResourceManager.ResFileExtension + " from "+System.CoreLib.Name+"'s assembly" + Environment.NewLine + Environment.NewLine + "Are you building the runtime on your machine? Chances are the BCL directory didn't build correctly. Type 'build -c' in the BCL directory. If you get build errors, look at buildd.log. If you then can't figure out what's wrong (and you aren't changing the assembly-related metadata code), ask a BCL dev.\n\nIf you did NOT build the runtime, you shouldn't be seeing this and you've found a bug."); + Debug.Assert(false, "Couldn't get " + System.CoreLib.Name+ResourceManager.ResFileExtension + " from "+System.CoreLib.Name+"'s assembly" + Environment.NewLine + Environment.NewLine + "Are you building the runtime on your machine? Chances are the BCL directory didn't build correctly. Type 'build -c' in the BCL directory. If you get build errors, look at buildd.log. If you then can't figure out what's wrong (and you aren't changing the assembly-related metadata code), ask a BCL dev.\n\nIf you did NOT build the runtime, you shouldn't be seeing this and you've found a bug."); // We cannot continue further - simply FailFast. string mesgFailFast = System.CoreLib.Name + ResourceManager.ResFileExtension + " couldn't be found! Large parts of the BCL won't work!"; diff --git a/src/mscorlib/src/System/Resources/ResourceManager.cs b/src/mscorlib/src/System/Resources/ResourceManager.cs index 6e3bd07..15f6af7 100644 --- a/src/mscorlib/src/System/Resources/ResourceManager.cs +++ b/src/mscorlib/src/System/Resources/ResourceManager.cs @@ -30,6 +30,7 @@ namespace System.Resources { using Microsoft.Win32; using System.Collections.Generic; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; #if FEATURE_APPX @@ -630,7 +631,7 @@ namespace System.Resources { [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable protected virtual ResourceSet InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents) { - Contract.Assert(culture != null, "culture != null"); + Debug.Assert(culture != null, "culture != null"); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return InternalGetResourceSet(culture,createIfNotExists,tryParents, ref stackMark); @@ -754,7 +755,7 @@ namespace System.Resources { Object[] attrs = a.GetCustomAttributes(typeof(SatelliteContractVersionAttribute), false); if (attrs.Length == 0) return null; - Contract.Assert(attrs.Length == 1, "Cannot have multiple instances of SatelliteContractVersionAttribute on an assembly!"); + Debug.Assert(attrs.Length == 1, "Cannot have multiple instances of SatelliteContractVersionAttribute on an assembly!"); v = ((SatelliteContractVersionAttribute)attrs[0]).Version; } Version ver; @@ -767,7 +768,7 @@ namespace System.Resources { // If this assert fires, please fix the build process for the // BCL directory. if (a == typeof(Object).Assembly) { - Contract.Assert(false, System.CoreLib.Name+"'s SatelliteContractVersionAttribute is a malformed version string!"); + Debug.Assert(false, System.CoreLib.Name+"'s SatelliteContractVersionAttribute is a malformed version string!"); return null; } @@ -795,7 +796,7 @@ namespace System.Resources { String typeName2, AssemblyName asmName2) { - Contract.Assert(asmTypeName1 != null, "asmTypeName1 was unexpectedly null"); + Debug.Assert(asmTypeName1 != null, "asmTypeName1 was unexpectedly null"); // First, compare type names int comma = asmTypeName1.IndexOf(','); @@ -848,10 +849,10 @@ namespace System.Resources { #if FEATURE_APPX private string GetStringFromPRI(String stringName, String startingCulture, String neutralResourcesCulture) { - Contract.Assert(_bUsingModernResourceManagement); - Contract.Assert(_WinRTResourceManager != null); - Contract.Assert(_PRIonAppXInitialized); - Contract.Assert(AppDomain.IsAppXModel()); + Debug.Assert(_bUsingModernResourceManagement); + Debug.Assert(_WinRTResourceManager != null); + Debug.Assert(_PRIonAppXInitialized); + Debug.Assert(AppDomain.IsAppXModel()); if (stringName.Length == 0) return null; @@ -945,11 +946,11 @@ namespace System.Resources { private void SetAppXConfiguration() { - Contract.Assert(_bUsingModernResourceManagement == false); // Only this function writes to this member + Debug.Assert(_bUsingModernResourceManagement == false); // Only this function writes to this member #if FEATURE_APPX - Contract.Assert(_WinRTResourceManager == null); // Only this function writes to this member - Contract.Assert(_PRIonAppXInitialized == false); // Only this function writes to this member - Contract.Assert(_PRIExceptionInfo == null); // Only this function writes to this member + Debug.Assert(_WinRTResourceManager == null); // Only this function writes to this member + Debug.Assert(_PRIonAppXInitialized == false); // Only this function writes to this member + Debug.Assert(_PRIExceptionInfo == null); // Only this function writes to this member bool bUsingSatelliteAssembliesUnderAppX = false; diff --git a/src/mscorlib/src/System/Resources/ResourceReader.cs b/src/mscorlib/src/System/Resources/ResourceReader.cs index b2c3719..89cfdb1 100644 --- a/src/mscorlib/src/System/Resources/ResourceReader.cs +++ b/src/mscorlib/src/System/Resources/ResourceReader.cs @@ -31,6 +31,7 @@ namespace System.Resources { using System.Globalization; using System.Configuration.Assemblies; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; // Provides the default implementation of IResourceReader, reading @@ -66,7 +67,7 @@ namespace System.Resources { internal static bool CanCache(ResourceTypeCode value) { - Contract.Assert(value >= 0, "negative ResourceTypeCode. What?"); + Debug.Assert(value >= 0, "negative ResourceTypeCode. What?"); return value <= ResourceTypeCode.LastPrimitive; } } @@ -255,8 +256,8 @@ namespace System.Resources { private unsafe int GetNameHash(int index) { - Contract.Assert(index >=0 && index < _numResources, "Bad index into hash array. index: "+index); - Contract.Assert((_ums == null && _nameHashes != null && _nameHashesPtr == null) || + Debug.Assert(index >=0 && index < _numResources, "Bad index into hash array. index: "+index); + Debug.Assert((_ums == null && _nameHashes != null && _nameHashesPtr == null) || (_ums != null && _nameHashes == null && _nameHashesPtr != null), "Internal state mangled."); if (_ums == null) return _nameHashes[index]; @@ -266,8 +267,8 @@ namespace System.Resources { private unsafe int GetNamePosition(int index) { - Contract.Assert(index >=0 && index < _numResources, "Bad index into name position array. index: "+index); - Contract.Assert((_ums == null && _namePositions != null && _namePositionsPtr == null) || + Debug.Assert(index >=0 && index < _numResources, "Bad index into name position array. index: "+index); + Debug.Assert((_ums == null && _namePositions != null && _namePositionsPtr == null) || (_ums != null && _namePositions == null && _namePositionsPtr != null), "Internal state mangled."); int r; if (_ums == null) @@ -303,7 +304,7 @@ namespace System.Resources { // This does a binary search through the names. internal int FindPosForResource(String name) { - Contract.Assert(_store != null, "ResourceReader is closed!"); + Debug.Assert(_store != null, "ResourceReader is closed!"); int hash = FastResourceComparer.HashFunction(name); BCLDebug.Log("RESMGRFILEFORMAT", "FindPosForResource for "+name+" hash: "+hash.ToString("x", CultureInfo.InvariantCulture)); // Binary search over the hashes. Use the _namePositions array to @@ -384,7 +385,7 @@ namespace System.Resources { // so no one else can cause us to seek in the stream. private unsafe bool CompareStringEqualsName(String name) { - Contract.Assert(_store != null, "ResourceReader is closed!"); + Debug.Assert(_store != null, "ResourceReader is closed!"); int byteLen = _store.Read7BitEncodedInt(); if (byteLen < 0) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_NegativeStringLength")); @@ -421,7 +422,7 @@ namespace System.Resources { // index. The parameter is NOT a virtual offset. private unsafe String AllocateStringForNameIndex(int index, out int dataOffset) { - Contract.Assert(_store != null, "ResourceReader is closed!"); + Debug.Assert(_store != null, "ResourceReader is closed!"); byte[] bytes; int byteLen; long nameVA = GetNamePosition(index); @@ -485,7 +486,7 @@ namespace System.Resources { // index. The parameter is NOT a virtual offset. private Object GetValueForNameIndex(int index) { - Contract.Assert(_store != null, "ResourceReader is closed!"); + Debug.Assert(_store != null, "ResourceReader is closed!"); long nameVA = GetNamePosition(index); lock(this) { _store.BaseStream.Seek(nameVA + _nameSectionOffset, SeekOrigin.Begin); @@ -510,7 +511,7 @@ namespace System.Resources { // no one can cause us to do a seek in here. internal String LoadString(int pos) { - Contract.Assert(_store != null, "ResourceReader is closed!"); + Debug.Assert(_store != null, "ResourceReader is closed!"); _store.BaseStream.Seek(_dataSectionOffset+pos, SeekOrigin.Begin); String s = null; int typeIndex = _store.Read7BitEncodedInt(); @@ -563,8 +564,8 @@ namespace System.Resources { // no one can cause us to do a seek in here. internal Object LoadObjectV1(int pos) { - Contract.Assert(_store != null, "ResourceReader is closed!"); - Contract.Assert(_version == 1, ".resources file was not a V1 .resources file!"); + Debug.Assert(_store != null, "ResourceReader is closed!"); + Debug.Assert(_version == 1, ".resources file was not a V1 .resources file!"); try { // mega try-catch performs exceptionally bad on x64; factored out body into @@ -638,8 +639,8 @@ namespace System.Resources { internal Object LoadObjectV2(int pos, out ResourceTypeCode typeCode) { - Contract.Assert(_store != null, "ResourceReader is closed!"); - Contract.Assert(_version >= 2, ".resources file was not a V2 (or higher) .resources file!"); + Debug.Assert(_store != null, "ResourceReader is closed!"); + Debug.Assert(_version >= 2, ".resources file was not a V2 (or higher) .resources file!"); try { // mega try-catch performs exceptionally bad on x64; factored out body into @@ -735,7 +736,7 @@ namespace System.Resources { byte[] bytes = new byte[len]; int r = _ums.Read(bytes, 0, len); - Contract.Assert(r == len, "ResourceReader needs to use a blocking read here. (Call _store.ReadBytes(len)?)"); + Debug.Assert(r == len, "ResourceReader needs to use a blocking read here. (Call _store.ReadBytes(len)?)"); return bytes; } @@ -827,7 +828,7 @@ namespace System.Resources { // for the default resource file format. private void ReadResources() { - Contract.Assert(_store != null, "ResourceReader is closed!"); + Debug.Assert(_store != null, "ResourceReader is closed!"); #if FEATURE_SERIALIZATION BinaryFormatter bf = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.File | StreamingContextStates.Persistence)); _typeLimitingBinder = new TypeLimitingDeserializationBinder(); @@ -1068,7 +1069,7 @@ namespace System.Resources { _store.BaseStream.Position = oldPos; } } - Contract.Assert(_typeTable[typeIndex] != null, "Should have found a type!"); + Debug.Assert(_typeTable[typeIndex] != null, "Should have found a type!"); return _typeTable[typeIndex]; } @@ -1179,10 +1180,10 @@ namespace System.Resources { Array.Sort(sortedDataPositions); int index = Array.BinarySearch(sortedDataPositions, dataPos); - Contract.Assert(index >= 0 && index < _numResources, "Couldn't find data position within sorted data positions array!"); + Debug.Assert(index >= 0 && index < _numResources, "Couldn't find data position within sorted data positions array!"); long nextData = (index < _numResources - 1) ? sortedDataPositions[index + 1] + _dataSectionOffset : _store.BaseStream.Length; int len = (int) (nextData - (dataPos + _dataSectionOffset)); - Contract.Assert(len >= 0 && len <= (int) _store.BaseStream.Length - dataPos + _dataSectionOffset, "Length was negative or outside the bounds of the file!"); + Debug.Assert(len >= 0 && len <= (int) _store.BaseStream.Length - dataPos + _dataSectionOffset, "Length was negative or outside the bounds of the file!"); // Read type code then byte[] _store.BaseStream.Position = _dataSectionOffset + dataPos; @@ -1206,12 +1207,12 @@ namespace System.Resources { { Contract.Requires(typeCode >= 0, "can't be negative"); if (typeCode < ResourceTypeCode.StartOfUserTypes) { - Contract.Assert(!String.Equals(typeCode.ToString(), "LastPrimitive"), "Change ResourceTypeCode metadata order so LastPrimitive isn't what Enum.ToString prefers."); + Debug.Assert(!String.Equals(typeCode.ToString(), "LastPrimitive"), "Change ResourceTypeCode metadata order so LastPrimitive isn't what Enum.ToString prefers."); return "ResourceTypeCode." + typeCode.ToString(); } else { int typeIndex = typeCode - ResourceTypeCode.StartOfUserTypes; - Contract.Assert(typeIndex >= 0 && typeIndex < _typeTable.Length, "TypeCode is broken or corrupted!"); + Debug.Assert(typeIndex >= 0 && typeIndex < _typeTable.Length, "TypeCode is broken or corrupted!"); long oldPos = _store.BaseStream.Position; try { _store.BaseStream.Position = _typeNamePositions[typeIndex]; diff --git a/src/mscorlib/src/System/Resources/RuntimeResourceSet.cs b/src/mscorlib/src/System/Resources/RuntimeResourceSet.cs index 9033f76..a94ac82 100644 --- a/src/mscorlib/src/System/Resources/RuntimeResourceSet.cs +++ b/src/mscorlib/src/System/Resources/RuntimeResourceSet.cs @@ -20,6 +20,7 @@ namespace System.Resources { using System.Globalization; using System.Reflection; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; // A RuntimeResourceSet stores all the resources defined in one @@ -310,7 +311,7 @@ namespace System.Resources { } if (dataPos != -1 && value == null) { - Contract.Assert(dataPos >= 0, "data section offset cannot be negative!"); + Debug.Assert(dataPos >= 0, "data section offset cannot be negative!"); // Normally calling LoadString or LoadObject requires // taking a lock. Note that in this case, we took a // lock on the entire RuntimeResourceSet, which is @@ -371,7 +372,7 @@ namespace System.Resources { Reader.Close(); } else { - Contract.Assert(ignoreCase, "This should only happen for case-insensitive lookups"); + Debug.Assert(ignoreCase, "This should only happen for case-insensitive lookups"); ResourceReader.ResourceEnumerator en = _defaultReader.GetEnumeratorInternal(); while (en.MoveNext()) { // Note: Always ask for the resource key before the data position. diff --git a/src/mscorlib/src/System/Resources/__FastResourceComparer.cs b/src/mscorlib/src/System/Resources/__FastResourceComparer.cs index f84a616..e0911fa 100644 --- a/src/mscorlib/src/System/Resources/__FastResourceComparer.cs +++ b/src/mscorlib/src/System/Resources/__FastResourceComparer.cs @@ -17,6 +17,7 @@ namespace System.Resources { using System; using System.Collections; using System.Collections.Generic; + using System.Diagnostics; using System.Diagnostics.Contracts; internal sealed class FastResourceComparer : IComparer, IEqualityComparer, IComparer, IEqualityComparer @@ -80,8 +81,8 @@ namespace System.Resources { // little endian unicode. Pass in the number of valid chars. public unsafe static int CompareOrdinal(String a, byte[] bytes, int bCharLength) { - Contract.Assert(a != null && bytes != null, "FastResourceComparer::CompareOrdinal must have non-null params"); - Contract.Assert(bCharLength * 2 <= bytes.Length, "FastResourceComparer::CompareOrdinal - numChars is too big!"); + Debug.Assert(a != null && bytes != null, "FastResourceComparer::CompareOrdinal must have non-null params"); + Debug.Assert(bCharLength * 2 <= bytes.Length, "FastResourceComparer::CompareOrdinal - numChars is too big!"); // This is a managed version of strcmp, but I can't take advantage // of a terminating 0, unlike strcmp in C. int i = 0; @@ -115,9 +116,9 @@ namespace System.Resources { // The byte* must point to little endian Unicode characters. internal unsafe static int CompareOrdinal(byte* a, int byteLen, String b) { - Contract.Assert((byteLen & 1) == 0, "CompareOrdinal is expecting a UTF-16 string length, which must be even!"); - Contract.Assert(a != null && b != null, "Null args not allowed."); - Contract.Assert(byteLen >= 0, "byteLen must be non-negative."); + Debug.Assert((byteLen & 1) == 0, "CompareOrdinal is expecting a UTF-16 string length, which must be even!"); + Debug.Assert(a != null && b != null, "Null args not allowed."); + Debug.Assert(byteLen >= 0, "byteLen must be non-negative."); int r = 0; int i = 0; diff --git a/src/mscorlib/src/System/RtType.cs b/src/mscorlib/src/System/RtType.cs index acb6127..168beef 100644 --- a/src/mscorlib/src/System/RtType.cs +++ b/src/mscorlib/src/System/RtType.cs @@ -220,7 +220,7 @@ namespace System // Currently the callers of UsesStringComparison assume that if it returns false // then the match always succeeds and can be skipped. Assert that this is maintained. - Contract.Assert(retVal || RequiresStringComparison()); + Debug.Assert(retVal || RequiresStringComparison()); return retVal; } @@ -241,7 +241,7 @@ namespace System public uint GetHashToMatch() { - Contract.Assert(RequiresStringComparison()); + Debug.Assert(RequiresStringComparison()); return m_nameHash; } @@ -532,7 +532,7 @@ namespace System // Grow the list by exactly one element in this case to avoid null entries at the end. // - Contract.Assert(false); + Debug.Assert(false); newSize = cachedMembers.Length + 1; } @@ -547,7 +547,7 @@ namespace System cachedMembers = cachedMembers2; } - Contract.Assert(cachedMembers[freeSlotIndex] == null); + Debug.Assert(cachedMembers[freeSlotIndex] == null); cachedMembers[freeSlotIndex] = newMemberInfo; freeSlotIndex++; } @@ -564,7 +564,7 @@ namespace System ListBuilder list = new ListBuilder(); RuntimeType declaringType = ReflectedType; - Contract.Assert(declaringType != null); + Debug.Assert(declaringType != null); if (RuntimeTypeHandle.IsInterface(declaringType)) { @@ -576,7 +576,7 @@ namespace System { if (!RuntimeMethodHandle.MatchesNameHash(methodHandle, filter.GetHashToMatch())) { - Contract.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle))); + Debug.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle))); continue; } @@ -585,10 +585,10 @@ namespace System } #region Loop through all methods on the interface - Contract.Assert(!methodHandle.IsNullHandle()); + Debug.Assert(!methodHandle.IsNullHandle()); // Except for .ctor, .cctor, IL_STUB*, and static methods, all interface methods should be abstract, virtual, and non-RTSpecialName. // Note that this assumption will become invalid when we add support for non-abstract or static methods on interfaces. - Contract.Assert( + Debug.Assert( (RuntimeMethodHandle.GetAttributes(methodHandle) & (MethodAttributes.RTSpecialName | MethodAttributes.Abstract | MethodAttributes.Virtual)) == (MethodAttributes.Abstract | MethodAttributes.Virtual) || (RuntimeMethodHandle.GetAttributes(methodHandle) & MethodAttributes.Static) == MethodAttributes.Static || RuntimeMethodHandle.GetName(methodHandle).Equals(".ctor") || @@ -636,7 +636,7 @@ namespace System { if (!RuntimeMethodHandle.MatchesNameHash(methodHandle, filter.GetHashToMatch())) { - Contract.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle))); + Debug.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle))); continue; } @@ -645,13 +645,13 @@ namespace System } #region Loop through all methods on the current type - Contract.Assert(!methodHandle.IsNullHandle()); + Debug.Assert(!methodHandle.IsNullHandle()); MethodAttributes methodAttributes = RuntimeMethodHandle.GetAttributes(methodHandle); MethodAttributes methodAccess = methodAttributes & MethodAttributes.MemberAccessMask; #region Continue if this is a constructor - Contract.Assert( + Debug.Assert( (RuntimeMethodHandle.GetAttributes(methodHandle) & MethodAttributes.RTSpecialName) == 0 || RuntimeMethodHandle.GetName(methodHandle).Equals(".ctor") || RuntimeMethodHandle.GetName(methodHandle).Equals(".cctor")); @@ -683,7 +683,7 @@ namespace System #region Continue if this is a virtual and is already overridden if (isVirtual) { - Contract.Assert( + Debug.Assert( (methodAttributes & MethodAttributes.Abstract) != 0 || (methodAttributes & MethodAttributes.Virtual) != 0 || RuntimeMethodHandle.GetDeclaringType(methodHandle) != declaringType); @@ -700,7 +700,7 @@ namespace System } else { - Contract.Assert((methodAttributes & (MethodAttributes.Virtual | MethodAttributes.Abstract)) == 0); + Debug.Assert((methodAttributes & (MethodAttributes.Virtual | MethodAttributes.Abstract)) == 0); } #endregion @@ -745,7 +745,7 @@ namespace System { if (!RuntimeMethodHandle.MatchesNameHash(methodHandle, filter.GetHashToMatch())) { - Contract.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle))); + Debug.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle))); continue; } @@ -755,13 +755,13 @@ namespace System MethodAttributes methodAttributes = RuntimeMethodHandle.GetAttributes(methodHandle); - Contract.Assert(!methodHandle.IsNullHandle()); + Debug.Assert(!methodHandle.IsNullHandle()); if ((methodAttributes & MethodAttributes.RTSpecialName) == 0) continue; // Constructors should not be virtual or abstract - Contract.Assert( + Debug.Assert( (methodAttributes & MethodAttributes.Abstract) == 0 && (methodAttributes & MethodAttributes.Virtual) == 0); @@ -871,7 +871,7 @@ namespace System { if (!RuntimeFieldHandle.MatchesNameHash(runtimeFieldHandle, filter.GetHashToMatch())) { - Contract.Assert(!filter.Match(RuntimeFieldHandle.GetUtf8Name(runtimeFieldHandle))); + Debug.Assert(!filter.Match(RuntimeFieldHandle.GetUtf8Name(runtimeFieldHandle))); continue; } @@ -879,7 +879,7 @@ namespace System continue; } - Contract.Assert(!runtimeFieldHandle.IsNullHandle()); + Debug.Assert(!runtimeFieldHandle.IsNullHandle()); FieldAttributes fieldAttributes = RuntimeFieldHandle.GetAttributes(runtimeFieldHandle); FieldAttributes fieldAccess = fieldAttributes & FieldAttributes.FieldAccessMask; @@ -926,8 +926,8 @@ namespace System for (int i = 0; i < tkFields.Length; i++) { int tkField = tkFields[i]; - Contract.Assert(MdToken.IsTokenOfType(tkField, MetadataTokenType.FieldDef)); - Contract.Assert(!MdToken.IsNullToken(tkField)); + Debug.Assert(MdToken.IsTokenOfType(tkField, MetadataTokenType.FieldDef)); + Debug.Assert(!MdToken.IsNullToken(tkField)); FieldAttributes fieldAttributes; scope.GetFieldDefProps(tkField, out fieldAttributes); @@ -1033,7 +1033,7 @@ namespace System continue; } - Contract.Assert(interfaceType.IsInterface); + Debug.Assert(interfaceType.IsInterface); list.Add(interfaceType); } } @@ -1201,8 +1201,8 @@ namespace System int tkEvent = tkEvents[i]; bool isPrivate; - Contract.Assert(!MdToken.IsNullToken(tkEvent)); - Contract.Assert(MdToken.IsTokenOfType(tkEvent, MetadataTokenType.Event)); + Debug.Assert(!MdToken.IsNullToken(tkEvent)); + Debug.Assert(MdToken.IsTokenOfType(tkEvent, MetadataTokenType.Event)); if (filter.RequiresStringComparison()) { @@ -1250,7 +1250,7 @@ namespace System // is called in Populate after this returns. RuntimeType declaringType = ReflectedType; - Contract.Assert(declaringType != null); + Debug.Assert(declaringType != null); ListBuilder list = new ListBuilder(); @@ -1304,7 +1304,7 @@ namespace System int numVirtuals = RuntimeTypeHandle.GetNumVirtuals(declaringType); - Contract.Assert((declaringType.IsInterface && usedSlots == null && csPropertyInfos == null) || + Debug.Assert((declaringType.IsInterface && usedSlots == null && csPropertyInfos == null) || (!declaringType.IsInterface && usedSlots != null && usedSlots.Length >= numVirtuals)); for (int i = 0; i < tkProperties.Length; i++) @@ -1312,14 +1312,14 @@ namespace System int tkProperty = tkProperties[i]; bool isPrivate; - Contract.Assert(!MdToken.IsNullToken(tkProperty)); - Contract.Assert(MdToken.IsTokenOfType(tkProperty, MetadataTokenType.Property)); + Debug.Assert(!MdToken.IsNullToken(tkProperty)); + Debug.Assert(MdToken.IsTokenOfType(tkProperty, MetadataTokenType.Property)); if (filter.RequiresStringComparison()) { if (!ModuleHandle.ContainsPropertyMatchingHash(declaringModuleHandle, tkProperty, filter.GetHashToMatch())) { - Contract.Assert(!filter.Match(declaringType.GetRuntimeModule().MetadataImport.GetName(tkProperty))); + Debug.Assert(!filter.Match(declaringType.GetRuntimeModule().MetadataImport.GetName(tkProperty))); continue; } @@ -1364,7 +1364,7 @@ namespace System if (slot < numVirtuals) { - Contract.Assert(associateMethod.IsVirtual); + Debug.Assert(associateMethod.IsVirtual); if (usedSlots[slot] == true) continue; else @@ -1450,7 +1450,7 @@ namespace System return Populate(name, listType, cacheType); default: - Contract.Assert(listType == MemberListType.All); + Debug.Assert(listType == MemberListType.All); if (Volatile.Read(ref m_cacheComplete)) return m_allMembers; @@ -1615,7 +1615,7 @@ namespace System { // Use void as a marker of null enclosing type RuntimeType enclosingType = RuntimeTypeHandle.GetDeclaringType(GetRuntimeType()); - Contract.Assert(enclosingType != typeof(void)); + Debug.Assert(enclosingType != typeof(void)); m_enclosingType = enclosingType ?? (RuntimeType)typeof(void); } @@ -1814,7 +1814,7 @@ namespace System internal unsafe static MethodBase GetMethodBase(RuntimeType reflectedType, RuntimeMethodHandleInternal methodHandle) { - Contract.Assert(!methodHandle.IsNullHandle()); + Debug.Assert(!methodHandle.IsNullHandle()); if (RuntimeMethodHandle.IsDynamicMethod(methodHandle)) { @@ -2092,7 +2092,7 @@ namespace System name = fullname.Substring(nsDelimiter + 1, nameLength); else name = ""; - Contract.Assert(fullname.Equals(ns + "." + name)); + Debug.Assert(fullname.Equals(ns + "." + name)); } else { @@ -2184,7 +2184,7 @@ namespace System // Most of the plural GetXXX methods allow prefix lookups while the singular GetXXX methods mostly do not. private static bool FilterApplyPrefixLookup(MemberInfo memberInfo, string name, bool ignoreCase) { - Contract.Assert(name != null); + Debug.Assert(name != null); if (ignoreCase) { @@ -2290,7 +2290,7 @@ namespace System Type type, BindingFlags bindingFlags, string name, bool prefixLookup, string ns) { Contract.Requires((object)type != null); - Contract.Assert(type is RuntimeType); + Debug.Assert(type is RuntimeType); bool isPublic = type.IsNestedPublic || type.IsPublic; bool isStatic = false; @@ -2375,7 +2375,7 @@ namespace System { // If Binding flags did not include varargs we would have filtered this vararg method. // This Invariant established during callConv check. - Contract.Assert((callConv & CallingConventions.VarArgs) != 0); + Debug.Assert((callConv & CallingConventions.VarArgs) != 0); } #endregion } @@ -2567,7 +2567,7 @@ namespace System cache = existingCache; } - Contract.Assert(cache != null); + Debug.Assert(cache != null); return cache; } } @@ -2814,7 +2814,7 @@ namespace System events.CopyTo(members, i); i += events.Count; fields.CopyTo(members, i); i += fields.Count; nestedTypes.CopyTo(members, i); i += nestedTypes.Count; - Contract.Assert(i == members.Length); + Debug.Assert(i == members.Length); return members; } @@ -2836,8 +2836,8 @@ namespace System RuntimeTypeHandle ifaceRtTypeHandle = ifaceRtType.GetTypeHandleInternal(); GetTypeHandleInternal().VerifyInterfaceIsImplemented(ifaceRtTypeHandle); - Contract.Assert(ifaceType.IsInterface); // VerifyInterfaceIsImplemented enforces this invariant - Contract.Assert(!IsInterface); // VerifyInterfaceIsImplemented enforces this invariant + Debug.Assert(ifaceType.IsInterface); // VerifyInterfaceIsImplemented enforces this invariant + Debug.Assert(!IsInterface); // VerifyInterfaceIsImplemented enforces this invariant // SZArrays implement the methods on IList`1, IEnumerable`1, and ICollection`1 with // SZArrayHelper and some runtime magic. We don't have accurate interface maps for them. @@ -2858,7 +2858,7 @@ namespace System // GetMethodBase will convert this to the instantiating/unboxing stub if necessary MethodBase ifaceMethodBase = RuntimeType.GetMethodBase(ifaceRtType, ifaceRtMethodHandle); - Contract.Assert(ifaceMethodBase is RuntimeMethodInfo); + Debug.Assert(ifaceMethodBase is RuntimeMethodInfo); im.InterfaceMethods[i] = (MethodInfo)ifaceMethodBase; // If the slot is -1, then virtual stub dispatch is active. @@ -2871,7 +2871,7 @@ namespace System // GetMethodBase will convert this to the instantiating/unboxing stub if necessary MethodBase rtTypeMethodBase = RuntimeType.GetMethodBase(this, classRtMethodHandle); // a class may not implement all the methods of an interface (abstract class) so null is a valid value - Contract.Assert(rtTypeMethodBase == null || rtTypeMethodBase is RuntimeMethodInfo); + Debug.Assert(rtTypeMethodBase == null || rtTypeMethodBase is RuntimeMethodInfo); im.TargetMethods[i] = (MethodInfo)rtTypeMethodBase; } @@ -3205,7 +3205,7 @@ namespace System events.CopyTo(compressMembers, i); i += events.Count; fields.CopyTo(compressMembers, i); i += fields.Count; nestedTypes.CopyTo(compressMembers, i); i += nestedTypes.Count; - Contract.Assert(i == compressMembers.Length); + Debug.Assert(i == compressMembers.Length); return compressMembers; } @@ -3955,7 +3955,7 @@ namespace System { // Since this cannot be a generic parameter, we use RuntimeTypeHandle.IsValueType here // because it is faster than RuntimeType.IsValueType - Contract.Assert(!IsGenericParameter); + Debug.Assert(!IsGenericParameter); Type type = value.GetType(); @@ -4224,7 +4224,7 @@ namespace System } else { - Contract.Assert(IsSetField); + Debug.Assert(IsSetField); if (providedArgs == null) throw new ArgumentNullException(nameof(providedArgs)); @@ -4243,7 +4243,7 @@ namespace System FieldInfo selFld = null; FieldInfo[] flds = GetMember(name, MemberTypes.Field, bindingFlags) as FieldInfo[]; - Contract.Assert(flds != null); + Debug.Assert(flds != null); if (flds.Length == 1) { @@ -4366,16 +4366,16 @@ namespace System #region Preconditions if (isGetProperty) { - Contract.Assert(!IsSetField); + Debug.Assert(!IsSetField); if (isSetProperty) throw new ArgumentException(Environment.GetResourceString("Arg_PropSetGet"), nameof(bindingFlags)); } else { - Contract.Assert(isSetProperty); + Debug.Assert(isSetProperty); - Contract.Assert(!IsGetField); + Debug.Assert(!IsGetField); if ((bindingFlags & BindingFlags.InvokeMethod) != 0) throw new ArgumentException(Environment.GetResourceString("Arg_PropSetInvoke"), nameof(bindingFlags)); @@ -4397,7 +4397,7 @@ namespace System for(int i = 0; i < semiFinalists.Length; i ++) { MethodInfo semiFinalist = semiFinalists[i]; - Contract.Assert(semiFinalist != null); + Debug.Assert(semiFinalist != null); if (!FilterApplyMethodInfo((RuntimeMethodInfo)semiFinalist, bindingFlags, CallingConventions.Any, new Type[argCnt])) continue; @@ -4420,7 +4420,7 @@ namespace System if (results != null) { - Contract.Assert(results.Count > 1); + Debug.Assert(results.Count > 1); finalists = new MethodInfo[results.Count]; results.CopyTo(finalists); } @@ -4428,7 +4428,7 @@ namespace System } #endregion - Contract.Assert(finalists == null || finalist != null); + Debug.Assert(finalists == null || finalist != null); #region BindingFlags.GetProperty or BindingFlags.SetProperty if (finalist == null && isGetProperty || isSetProperty) @@ -4474,7 +4474,7 @@ namespace System if (results != null) { - Contract.Assert(results.Count > 1); + Debug.Assert(results.Count > 1); finalists = new MethodInfo[results.Count]; results.CopyTo(finalists); } @@ -4816,7 +4816,7 @@ namespace System if (args.Length != 0) { - Contract.Assert((invokeMethod.CallingConvention & CallingConventions.VarArgs) == + Debug.Assert((invokeMethod.CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs); throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("NotSupported_CallToVarArg"))); @@ -4887,7 +4887,7 @@ namespace System { if (!ace.m_type.IsValueType) { - Contract.Assert(!ace.m_hCtorMethodHandle.IsNullHandle(), "Expected the default ctor method handle for a reference type."); + Debug.Assert(!ace.m_hCtorMethodHandle.IsNullHandle(), "Expected the default ctor method handle for a reference type."); if (delegateCtorInfo == null) InitializeDelegateCreator(); @@ -5006,7 +5006,7 @@ namespace System Object instance = RuntimeTypeHandle.Allocate(this); // if m_ctor is null, this type doesn't have a default ctor - Contract.Assert(ace.m_ctor != null || this.IsValueType); + Debug.Assert(ace.m_ctor != null || this.IsValueType); if (ace.m_ctor != null) { @@ -5261,7 +5261,7 @@ namespace System.Reflection } else { - Contract.Assert(!hit.Equals(key), "Key was already in CerHashtable! Potential race condition (or bug) in the Reflection cache?"); + Debug.Assert(!hit.Equals(key), "Key was already in CerHashtable! Potential race condition (or bug) in the Reflection cache?"); index++; if (index >= keys.Length) diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs b/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs index ce1c07a..2723fcf 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs @@ -111,7 +111,7 @@ namespace System.Runtime.CompilerServices { AsyncMethodBuilderCore.MoveNextRunner runnerToInitialize = null; var continuation = m_coreState.GetCompletionAction(AsyncCausalityTracer.LoggingOn ? this.Task : null, ref runnerToInitialize); - Contract.Assert(continuation != null, "GetCompletionAction should always return a valid action."); + Debug.Assert(continuation != null, "GetCompletionAction should always return a valid action."); // If this is our first await, such that we've not yet boxed the state machine, do so now. if (m_coreState.m_stateMachine == null) @@ -157,7 +157,7 @@ namespace System.Runtime.CompilerServices { AsyncMethodBuilderCore.MoveNextRunner runnerToInitialize = null; var continuation = m_coreState.GetCompletionAction(AsyncCausalityTracer.LoggingOn ? this.Task : null, ref runnerToInitialize); - Contract.Assert(continuation != null, "GetCompletionAction should always return a valid action."); + Debug.Assert(continuation != null, "GetCompletionAction should always return a valid action."); // If this is our first await, such that we've not yet boxed the state machine, do so now. if (m_coreState.m_stateMachine == null) @@ -229,7 +229,7 @@ namespace System.Runtime.CompilerServices /// Notifies the current synchronization context that the operation completed. private void NotifySynchronizationContextOfCompletion() { - Contract.Assert(m_synchronizationContext != null, "Must only be used with a non-null context."); + Debug.Assert(m_synchronizationContext != null, "Must only be used with a non-null context."); try { m_synchronizationContext.OperationCompleted(); @@ -499,7 +499,7 @@ namespace System.Runtime.CompilerServices { AsyncMethodBuilderCore.MoveNextRunner runnerToInitialize = null; var continuation = m_coreState.GetCompletionAction(AsyncCausalityTracer.LoggingOn ? this.Task : null, ref runnerToInitialize); - Contract.Assert(continuation != null, "GetCompletionAction should always return a valid action."); + Debug.Assert(continuation != null, "GetCompletionAction should always return a valid action."); // If this is our first await, such that we've not yet boxed the state machine, do so now. if (m_coreState.m_stateMachine == null) @@ -539,7 +539,7 @@ namespace System.Runtime.CompilerServices { AsyncMethodBuilderCore.MoveNextRunner runnerToInitialize = null; var continuation = m_coreState.GetCompletionAction(AsyncCausalityTracer.LoggingOn ? this.Task : null, ref runnerToInitialize); - Contract.Assert(continuation != null, "GetCompletionAction should always return a valid action."); + Debug.Assert(continuation != null, "GetCompletionAction should always return a valid action."); // If this is our first await, such that we've not yet boxed the state machine, do so now. if (m_coreState.m_stateMachine == null) @@ -590,7 +590,7 @@ namespace System.Runtime.CompilerServices if (task == null) { m_task = GetTaskForResult(result); - Contract.Assert(m_task != null, "GetTaskForResult should never return null"); + Debug.Assert(m_task != null, "GetTaskForResult should never return null"); } // Slow path: complete the existing task. else @@ -813,7 +813,7 @@ namespace System.Runtime.CompilerServices /// Creates an array of cached tasks for the values in the range [INCLUSIVE_MIN,EXCLUSIVE_MAX). private static Task[] CreateInt32Tasks() { - Contract.Assert(EXCLUSIVE_INT32_MAX >= INCLUSIVE_INT32_MIN, "Expected max to be at least min"); + Debug.Assert(EXCLUSIVE_INT32_MAX >= INCLUSIVE_INT32_MIN, "Expected max to be at least min"); var tasks = new Task[EXCLUSIVE_INT32_MAX - INCLUSIVE_INT32_MIN]; for (int i = 0; i < tasks.Length; i++) { @@ -897,7 +897,7 @@ namespace System.Runtime.CompilerServices /// An Action to provide to the awaiter. internal Action GetCompletionAction(Task taskForTracing, ref MoveNextRunner runnerToInitialize) { - Contract.Assert(m_defaultContextAction == null || m_stateMachine != null, + Debug.Assert(m_defaultContextAction == null || m_stateMachine != null, "Expected non-null m_stateMachine on non-null m_defaultContextAction"); // Alert a listening debugger that we can't make forward progress unless it slips threads. @@ -920,7 +920,7 @@ namespace System.Runtime.CompilerServices action = m_defaultContextAction; if (action != null) { - Contract.Assert(m_stateMachine != null, "If the delegate was set, the state machine should have been as well."); + Debug.Assert(m_stateMachine != null, "If the delegate was set, the state machine should have been as well."); return action; } @@ -986,8 +986,8 @@ namespace System.Runtime.CompilerServices m_stateMachine = stateMachine; m_stateMachine.SetStateMachine(m_stateMachine); - Contract.Assert(runner.m_stateMachine == null, "The runner's state machine should not yet have been populated."); - Contract.Assert(m_stateMachine != null, "The builder's state machine field should have been initialized."); + Debug.Assert(runner.m_stateMachine == null, "The runner's state machine should not yet have been populated."); + Debug.Assert(m_stateMachine != null, "The builder's state machine field should have been initialized."); // Now that we have the state machine, store it into the runner that the action delegate points to. // And return the action. @@ -1045,7 +1045,7 @@ namespace System.Runtime.CompilerServices /// Invokes MoveNext under the provided context. internal void RunWithCapturedContext() { - Contract.Assert(m_stateMachine != null, "The state machine must have been set before calling Run."); + Debug.Assert(m_stateMachine != null, "The state machine must have been set before calling Run."); if (m_context != null) { @@ -1078,7 +1078,7 @@ namespace System.Runtime.CompilerServices /// Invokes MoveNext under the default context. internal void RunWithDefaultContext() { - Contract.Assert(m_stateMachine != null, "The state machine must have been set before calling Run."); + Debug.Assert(m_stateMachine != null, "The state machine must have been set before calling Run."); ExecutionContext.Run(ExecutionContext.PreAllocatedDefault, InvokeMoveNextCallback, m_stateMachine, preserveSyncCtx: true); } diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs index 39a4c86..7bfaa7a 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs @@ -6,6 +6,7 @@ // Note: If you add a new ctor overloads you need to update ParameterInfo.RawDefaultValue using System.Reflection; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Collections.Generic; @@ -57,16 +58,16 @@ namespace System.Runtime.CompilerServices if (namedArgument.MemberInfo.Name.Equals("Value")) { // This is not possible because Decimal cannot be represented directly in the metadata. - Contract.Assert(false, "Decimal cannot be represented directly in the metadata."); + Debug.Assert(false, "Decimal cannot be represented directly in the metadata."); return (Decimal)namedArgument.TypedValue.Value; } } ParameterInfo[] parameters = attr.Constructor.GetParameters(); - Contract.Assert(parameters.Length == 5); + Debug.Assert(parameters.Length == 5); System.Collections.Generic.IList args = attr.ConstructorArguments; - Contract.Assert(args.Count == 5); + Debug.Assert(args.Count == 5); if (parameters[2].ParameterType == typeof(uint)) { diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs index f077487..61aa077 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs @@ -141,7 +141,7 @@ namespace System.Runtime.CompilerServices if (!task.IsCompleted) { bool taskCompleted = task.InternalWait(Timeout.Infinite, default(CancellationToken)); - Contract.Assert(taskCompleted, "With an infinite timeout, the task should have always completed."); + Debug.Assert(taskCompleted, "With an infinite timeout, the task should have always completed."); } // Now that we're done, alert the debugger if so requested @@ -169,7 +169,7 @@ namespace System.Runtime.CompilerServices if (oceEdi != null) { oceEdi.Throw(); - Contract.Assert(false, "Throw() should have thrown"); + Debug.Assert(false, "Throw() should have thrown"); } throw new TaskCanceledException(task); @@ -180,12 +180,12 @@ namespace System.Runtime.CompilerServices if (edis.Count > 0) { edis[0].Throw(); - Contract.Assert(false, "Throw() should have thrown"); + Debug.Assert(false, "Throw() should have thrown"); break; // Necessary to compile: non-reachable, but compiler can't determine that } else { - Contract.Assert(false, "There should be exceptions if we're Faulted."); + Debug.Assert(false, "There should be exceptions if we're Faulted."); throw task.Exception; } } diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs b/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs index 6c0f97d..c1346f7 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs @@ -11,6 +11,7 @@ using System; using System.Threading; using System.Runtime; using System.Runtime.Versioning; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Security; @@ -98,7 +99,7 @@ namespace System.Runtime.CompilerServices { static internal T UnsafeCast(Object o) where T : class { T ret = UnsafeCastInternal(o); - Contract.Assert(ret == (o as T), "Invalid use of JitHelpers.UnsafeCast!"); + Debug.Assert(ret == (o as T), "Invalid use of JitHelpers.UnsafeCast!"); return ret; } @@ -113,7 +114,7 @@ namespace System.Runtime.CompilerServices { static internal int UnsafeEnumCast(T val) where T : struct // Actually T must be 4 byte (or less) enum { - Contract.Assert(typeof(T).IsEnum + Debug.Assert(typeof(T).IsEnum && (Enum.GetUnderlyingType(typeof(T)) == typeof(int) || Enum.GetUnderlyingType(typeof(T)) == typeof(uint) || Enum.GetUnderlyingType(typeof(T)) == typeof(short) @@ -133,7 +134,7 @@ namespace System.Runtime.CompilerServices { static internal long UnsafeEnumCastLong(T val) where T : struct // Actually T must be 8 byte enum { - Contract.Assert(typeof(T).IsEnum + Debug.Assert(typeof(T).IsEnum && (Enum.GetUnderlyingType(typeof(T)) == typeof(long) || Enum.GetUnderlyingType(typeof(T)) == typeof(ulong)), "Error, T must be an 8 byte enum JitHelpers.UnsafeEnumCastLong!"); @@ -152,7 +153,7 @@ namespace System.Runtime.CompilerServices { static internal IntPtr UnsafeCastToStackPointer(ref T val) { IntPtr p = UnsafeCastToStackPointerInternal(ref val); - Contract.Assert(IsAddressInStack(p), "Pointer not in the stack!"); + Debug.Assert(IsAddressInStack(p), "Pointer not in the stack!"); return p; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs b/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs index 08d3694..2de7304 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs @@ -8,6 +8,7 @@ namespace System.Runtime.InteropServices{ using System; using System.Reflection; + using System.Diagnostics; using System.Diagnostics.Contracts; [AttributeUsage(AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] @@ -573,7 +574,7 @@ namespace System.Runtime.InteropServices{ { // The user may have supplied a bad type name string causing this TypeLoadException // Regardless, we return the bad type name - Contract.Assert(marshalTypeName != null); + Debug.Assert(marshalTypeName != null); } return new MarshalAsAttribute( diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs b/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs index d6f913e..3a79650 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs @@ -29,6 +29,7 @@ namespace System.Runtime.InteropServices using System.Runtime.Versioning; using Win32Native = Microsoft.Win32.Win32Native; using Microsoft.Win32.SafeHandles; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices.ComTypes; @@ -2032,10 +2033,10 @@ namespace System.Runtime.InteropServices { // Retrieve the PROGID string from the ProgIdAttribute. IList caConstructorArgs = cas[i].ConstructorArguments; - Contract.Assert(caConstructorArgs.Count == 1, "caConstructorArgs.Count == 1"); + Debug.Assert(caConstructorArgs.Count == 1, "caConstructorArgs.Count == 1"); CustomAttributeTypedArgument progIdConstructorArg = caConstructorArgs[0]; - Contract.Assert(progIdConstructorArg.ArgumentType == typeof(String), "progIdConstructorArg.ArgumentType == typeof(String)"); + Debug.Assert(progIdConstructorArg.ArgumentType == typeof(String), "progIdConstructorArg.ArgumentType == typeof(String)"); String strProgId = (String)progIdConstructorArg.Value; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/RegistrationServices.cs b/src/mscorlib/src/System/Runtime/InteropServices/RegistrationServices.cs index 6752635..0105866 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/RegistrationServices.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/RegistrationServices.cs @@ -29,6 +29,7 @@ namespace System.Runtime.InteropServices { using System.Runtime.CompilerServices; using System.Globalization; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; [Flags] @@ -289,7 +290,7 @@ namespace System.Runtime.InteropServices { // If the type is derived from a tdImport class and has the same GUID as the // imported class, then it represents a COM type. Type baseComImportType = GetBaseComImportType(type); - Contract.Assert(baseComImportType != null, "baseComImportType != null"); + Debug.Assert(baseComImportType != null, "baseComImportType != null"); if (Marshal.GenerateGuidForType(type) == Marshal.GenerateGuidForType(baseComImportType)) return true; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs index cf326c5..eba67ae 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs @@ -75,6 +75,7 @@ using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using Microsoft.Win32.SafeHandles; +using System.Diagnostics; using System.Diagnostics.Contracts; @@ -384,7 +385,7 @@ using System.Diagnostics.Contracts; [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private static InvalidOperationException NotInitialized() { - Contract.Assert(false, "Uninitialized SafeBuffer! Someone needs to call Initialize before using this instance!"); + Debug.Assert(false, "Uninitialized SafeBuffer! Someone needs to call Initialize before using this instance!"); return new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MustCallInitialize")); } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventProviderWriter.cs b/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventProviderWriter.cs index 58f70e5..160a0ab 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventProviderWriter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventProviderWriter.cs @@ -10,6 +10,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { using System.Reflection.Emit; using System.Collections; using System.Threading; + using System.Diagnostics; using System.Diagnostics.Contracts; internal class EventProviderWriter @@ -96,34 +97,34 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { // Find the delegate on the event sink helper. FieldInfo DelegateField = SinkHelperClass.GetField( "m_" + SrcItfMethod.Name + "Delegate" ); - Contract.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper"); + Debug.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper"); // Find the cookie on the event sink helper. FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" ); - Contract.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper"); + Debug.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper"); // Retrieve the sink helper's constructor. ConstructorInfo SinkHelperCons = SinkHelperClass.GetConstructor(EventProviderWriter.DefaultLookup | BindingFlags.NonPublic, null, Array.Empty(), null ); - Contract.Assert(SinkHelperCons != null, "Unable to find the constructor for the sink helper"); + Debug.Assert(SinkHelperCons != null, "Unable to find the constructor for the sink helper"); // Retrieve the IConnectionPoint.Advise method. MethodInfo CPAdviseMethod = typeof(IConnectionPoint).GetMethod( "Advise" ); - Contract.Assert(CPAdviseMethod != null, "Unable to find the method ConnectionPoint.Advise"); + Debug.Assert(CPAdviseMethod != null, "Unable to find the method ConnectionPoint.Advise"); // Retrieve the ArrayList.Add method. aParamTypes = new Type[1]; aParamTypes[0] = typeof(Object); MethodInfo ArrayListAddMethod = typeof(ArrayList).GetMethod( "Add", aParamTypes, null ); - Contract.Assert(ArrayListAddMethod != null, "Unable to find the method ArrayList.Add"); + Debug.Assert(ArrayListAddMethod != null, "Unable to find the method ArrayList.Add"); // Retrieve the Monitor.Enter() method. MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod( "Enter", MonitorEnterParamTypes, null ); - Contract.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()"); + Debug.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()"); // Retrieve the Monitor.Exit() method. aParamTypes[0] = typeof(Object); MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null ); - Contract.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()"); + Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()"); // Define the add_XXX method. Type[] parameterTypes; @@ -239,51 +240,51 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { // Find the delegate on the event sink helper. FieldInfo DelegateField = SinkHelperClass.GetField( "m_" + SrcItfMethod.Name + "Delegate" ); - Contract.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper"); + Debug.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper"); // Find the cookie on the event sink helper. FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" ); - Contract.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper"); + Debug.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper"); // Retrieve the ArrayList.RemoveAt method. aParamTypes = new Type[1]; aParamTypes[0] = typeof(Int32); MethodInfo ArrayListRemoveMethod = typeof(ArrayList).GetMethod( "RemoveAt", aParamTypes, null ); - Contract.Assert(ArrayListRemoveMethod != null, "Unable to find the method ArrayList.RemoveAt()"); + Debug.Assert(ArrayListRemoveMethod != null, "Unable to find the method ArrayList.RemoveAt()"); // Retrieve the ArrayList.Item property get method. PropertyInfo ArrayListItemProperty = typeof(ArrayList).GetProperty( "Item" ); - Contract.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item"); + Debug.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item"); MethodInfo ArrayListItemGetMethod = ArrayListItemProperty.GetGetMethod(); - Contract.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item"); + Debug.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item"); // Retrieve the ArrayList.Count property get method. PropertyInfo ArrayListSizeProperty = typeof(ArrayList).GetProperty( "Count" ); - Contract.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count"); + Debug.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count"); MethodInfo ArrayListSizeGetMethod = ArrayListSizeProperty.GetGetMethod(); - Contract.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count"); + Debug.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count"); // Retrieve the Delegate.Equals() method. aParamTypes[0] = typeof(Delegate); MethodInfo DelegateEqualsMethod = typeof(Delegate).GetMethod( "Equals", aParamTypes, null ); - Contract.Assert(DelegateEqualsMethod != null, "Unable to find the method Delegate.Equlals()"); + Debug.Assert(DelegateEqualsMethod != null, "Unable to find the method Delegate.Equlals()"); // Retrieve the Monitor.Enter() method. MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod("Enter", MonitorEnterParamTypes, null); - Contract.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()"); + Debug.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()"); // Retrieve the Monitor.Exit() method. aParamTypes[0] = typeof(Object); MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null ); - Contract.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()"); + Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()"); // Retrieve the ConnectionPoint.Unadvise() method. MethodInfo CPUnadviseMethod = typeof(IConnectionPoint).GetMethod( "Unadvise" ); - Contract.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()"); + Debug.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()"); // Retrieve the Marshal.ReleaseComObject() method. MethodInfo ReleaseComObjectMethod = typeof(Marshal).GetMethod( "ReleaseComObject" ); - Contract.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()"); + Debug.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()"); // Define the remove_XXX method. Type[] parameterTypes; @@ -463,7 +464,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { { // Retrieve the constructor info for the array list's default constructor. ConstructorInfo DefaultArrayListCons = typeof(ArrayList).GetConstructor(EventProviderWriter.DefaultLookup, null, Array.Empty(), null ); - Contract.Assert(DefaultArrayListCons != null, "Unable to find the constructor for class ArrayList"); + Debug.Assert(DefaultArrayListCons != null, "Unable to find the constructor for class ArrayList"); // Temp byte array for Guid ubyte[] rgByteGuid = new ubyte[16]; @@ -472,11 +473,11 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { Type[] aParamTypes = new Type[1]; aParamTypes[0] = typeof(Byte[]); ConstructorInfo ByteArrayGUIDCons = typeof(Guid).GetConstructor(EventProviderWriter.DefaultLookup, null, aParamTypes, null ); - Contract.Assert(ByteArrayGUIDCons != null, "Unable to find the constructor for GUID that accepts a string as argument"); + Debug.Assert(ByteArrayGUIDCons != null, "Unable to find the constructor for GUID that accepts a string as argument"); // Retrieve the IConnectionPointContainer.FindConnectionPoint() method. MethodInfo CPCFindCPMethod = typeof(IConnectionPointContainer).GetMethod( "FindConnectionPoint" ); - Contract.Assert(CPCFindCPMethod != null, "Unable to find the method ConnectionPointContainer.FindConnectionPoint()"); + Debug.Assert(CPCFindCPMethod != null, "Unable to find the method ConnectionPointContainer.FindConnectionPoint()"); // Define the Init method itself. MethodBuilder Meth = OutputTypeBuilder.DefineMethod( @@ -553,7 +554,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { { // Retrieve the constructor info for the base class's constructor. ConstructorInfo DefaultBaseClsCons = typeof(Object).GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, Array.Empty(), null ); - Contract.Assert(DefaultBaseClsCons != null, "Unable to find the object's public default constructor"); + Debug.Assert(DefaultBaseClsCons != null, "Unable to find the object's public default constructor"); // Define the default constructor. MethodAttributes ctorAttributes = MethodAttributes.SpecialName | (DefaultBaseClsCons.Attributes & MethodAttributes.MemberAccessMask); @@ -584,37 +585,37 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { { // Find the cookie on the event sink helper. FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" ); - Contract.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper"); + Debug.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper"); // Retrieve the ArrayList.Item property get method. PropertyInfo ArrayListItemProperty = typeof(ArrayList).GetProperty( "Item" ); - Contract.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item"); + Debug.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item"); MethodInfo ArrayListItemGetMethod = ArrayListItemProperty.GetGetMethod(); - Contract.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item"); + Debug.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item"); // Retrieve the ArrayList.Count property get method. PropertyInfo ArrayListSizeProperty = typeof(ArrayList).GetProperty( "Count" ); - Contract.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count"); + Debug.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count"); MethodInfo ArrayListSizeGetMethod = ArrayListSizeProperty.GetGetMethod(); - Contract.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count"); + Debug.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count"); // Retrieve the ConnectionPoint.Unadvise() method. MethodInfo CPUnadviseMethod = typeof(IConnectionPoint).GetMethod( "Unadvise" ); - Contract.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()"); + Debug.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()"); // Retrieve the Marshal.ReleaseComObject() method. MethodInfo ReleaseComObjectMethod = typeof(Marshal).GetMethod( "ReleaseComObject" ); - Contract.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()"); + Debug.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()"); // Retrieve the Monitor.Enter() method. MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod("Enter", MonitorEnterParamTypes, null); - Contract.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()"); + Debug.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()"); // Retrieve the Monitor.Exit() method. Type[] aParamTypes = new Type[1]; aParamTypes[0] = typeof(Object); MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null ); - Contract.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()"); + Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()"); // Define the Finalize method itself. MethodBuilder Meth = OutputTypeBuilder.DefineMethod( "Finalize", MethodAttributes.Public | MethodAttributes.Virtual, null, null ); @@ -743,7 +744,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { { // Retrieve the method info for GC.SuppressFinalize(). MethodInfo SuppressFinalizeMethod = typeof(GC).GetMethod("SuppressFinalize"); - Contract.Assert(SuppressFinalizeMethod != null, "Unable to find the GC.SuppressFinalize"); + Debug.Assert(SuppressFinalizeMethod != null, "Unable to find the GC.SuppressFinalize"); // Define the Finalize method itself. MethodBuilder Meth = OutputTypeBuilder.DefineMethod( "Dispose", MethodAttributes.Public | MethodAttributes.Virtual, null, null ); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventSinkHelperWriter.cs b/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventSinkHelperWriter.cs index 0367e79..862419c 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventSinkHelperWriter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventSinkHelperWriter.cs @@ -8,6 +8,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { using System.Reflection; using System.Reflection.Emit; using System.Collections; + using System.Diagnostics; using System.Diagnostics.Contracts; internal class EventSinkHelperWriter { @@ -65,7 +66,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { // Retrieve the delegate type from the add_XXX method. MethodInfo AddMeth = m_EventItfType.GetMethod( "add_" + aMethods[cMethods].Name ); ParameterInfo[] aParams = AddMeth.GetParameters(); - Contract.Assert(aParams.Length == 1, "All event interface methods must take a single delegate derived type and have a void return type"); + Debug.Assert(aParams.Length == 1, "All event interface methods must take a single delegate derived type and have a void return type"); Type DelegateCls = aParams[0].ParameterType; // Define the delegate instance field. @@ -119,7 +120,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { { // Retrieve the method info for the invoke method on the delegate. MethodInfo DelegateInvokeMethod = DelegateCls.GetMethod( "Invoke" ); - Contract.Assert(DelegateInvokeMethod != null, "Unable to find method Delegate.Invoke()"); + Debug.Assert(DelegateInvokeMethod != null, "Unable to find method Delegate.Invoke()"); // Retrieve the return type. Type ReturnType = Method.ReturnType; @@ -229,7 +230,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { if ( ReturnType == typeof(IntPtr) ) il.Emit( OpCodes.Ldc_I4_0 ); else - Contract.Assert(false, "Unexpected type for Primitive type."); + Debug.Assert(false, "Unexpected type for Primitive type."); break; } } @@ -254,7 +255,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen { { // Retrieve the constructor info for the base classe's constructor. ConstructorInfo DefaultBaseClsCons = typeof(Object).GetConstructor(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, Array.Empty(), null ); - Contract.Assert(DefaultBaseClsCons != null, "Unable to find the constructor for class " + m_InputType.Name); + Debug.Assert(DefaultBaseClsCons != null, "Unable to find the constructor for class " + m_InputType.Name); // Define the default constructor. MethodBuilder Cons = OutputTypeBuilder.DefineMethod( ".ctor", diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs index 8eb7090..e3c6a92 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs @@ -9,6 +9,7 @@ using System.Runtime; using System.Security; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -27,7 +28,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private BindableVectorToCollectionAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // int Count { get } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs index 7bc36a1..d6e50f5 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs @@ -9,6 +9,7 @@ using System.Runtime; using System.Security; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -27,7 +28,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private BindableVectorToListAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // object this[int index] { get } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs index 65b4704..9705b61 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs @@ -6,6 +6,7 @@ using System; using System.Collections; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Reflection; using System.Security; @@ -55,7 +56,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { Contract.Requires(wrapper != null); IReference reference = (IReference) wrapper; - Contract.Assert(reference != null, "CLRIReferenceImpl::UnboxHelper - QI'ed for IReference<"+typeof(T)+">, but that failed."); + Debug.Assert(reference != null, "CLRIReferenceImpl::UnboxHelper - QI'ed for IReference<"+typeof(T)+">, but that failed."); return reference.Value; } } @@ -216,7 +217,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { Contract.Requires(wrapper != null); IReferenceArray reference = (IReferenceArray)wrapper; - Contract.Assert(reference != null, "CLRIReferenceArrayImpl::UnboxHelper - QI'ed for IReferenceArray<" + typeof(T) + ">, but that failed."); + Debug.Assert(reference != null, "CLRIReferenceArrayImpl::UnboxHelper - QI'ed for IReferenceArray<" + typeof(T) + ">, but that failed."); T[] marshaled = reference.Value; return marshaled; } @@ -301,7 +302,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime return Activator.CreateInstance(specificType, new Object[] { propType.Value, obj }); } - Contract.Assert(false, "We should not see non-WinRT type here"); + Debug.Assert(false, "We should not see non-WinRT type here"); return null; } @@ -313,7 +314,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime Type type = obj.GetType().GetElementType(); - Contract.Assert(obj.Rank == 1 && obj.GetLowerBound(0) == 0 && !type.IsArray); + Debug.Assert(obj.Rank == 1 && obj.GetLowerBound(0) == 0 && !type.IsArray); if (type == typeof(int)) return new CLRIReferenceArrayImpl(PropertyType.Int32Array, (int[])obj); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs index 3840e18..d575201 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs @@ -7,6 +7,7 @@ using System; using System.Security; using System.Reflection; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -122,7 +123,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // We can safely skip access check because this is only used in full trust scenarios. // And we have already verified that the property accessor is public. - Contract.Assert(AppDomain.CurrentDomain.PermissionSet.IsUnrestricted()); + Debug.Assert(AppDomain.CurrentDomain.PermissionSet.IsUnrestricted()); return rtMethod.UnsafeInvoke(target, BindingFlags.Default, null, args, null); } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs index 1a173a6..24e5777 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs @@ -10,6 +10,7 @@ using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -28,7 +29,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private DictionaryToMapAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // V Lookup(K key) @@ -66,7 +67,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal IReadOnlyDictionary GetView() { IDictionary _this = JitHelpers.UnsafeCast>(this); - Contract.Assert(_this != null); + Debug.Assert(_this != null); // Note: This dictionary is not really read-only - you could QI for a modifiable // dictionary. We gain some perf by doing this. We believe this is acceptable. diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs index 7df55f4..3f9d516 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs @@ -7,6 +7,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -25,7 +26,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private EnumerableToIterableAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // This method is invoked when First is called on a managed implementation of IIterable. @@ -40,7 +41,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private EnumerableToBindableIterableAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } internal sealed class NonGenericToGenericEnumerator : IEnumerator diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs index b78e1f8..4c6169a 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs @@ -7,6 +7,7 @@ using System; using System.Security; using System.Collections; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; @@ -27,7 +28,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private IDisposableToIClosableAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } public void Close() @@ -42,7 +43,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private IClosableToIDisposableAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } private void Dispose() diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs index 5ede9d6..a7424da 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs @@ -28,7 +28,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private IMapViewToIReadOnlyDictionaryAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // V this[K key] { get } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs index ef52a50..b185b41 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs @@ -28,7 +28,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private IReadOnlyDictionaryToIMapViewAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // V Lookup(K key) diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs index ddb8912..431d162 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs @@ -28,7 +28,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private IReadOnlyListToIVectorViewAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // T GetAt(uint index) diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs index 9e32168..37f2130 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs @@ -30,7 +30,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private IVectorViewToIReadOnlyListAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // T this[int index] { get } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs index a5fe29c..e219a86 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs @@ -7,6 +7,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -28,7 +29,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private IterableToEnumerableAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // This method is invoked when GetEnumerator is called on a WinRT-backed implementation of IEnumerable. @@ -68,7 +69,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private BindableIterableToEnumerableAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } private sealed class NonGenericToGenericIterator : IIterator diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs index 901befc..b9fe115 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs @@ -10,6 +10,7 @@ using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -28,7 +29,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private ListToBindableVectorAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // object GetAt(uint index) diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs index af6ed4e..b73f4d7 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs @@ -10,6 +10,7 @@ using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -28,7 +29,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private ListToVectorAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // T GetAt(uint index) @@ -58,7 +59,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal IReadOnlyList GetView() { IList _this = JitHelpers.UnsafeCast>(this); - Contract.Assert(_this != null); + Debug.Assert(_this != null); // Note: This list is not really read-only - you could QI for a modifiable // list. We gain some perf by doing this. We believe this is acceptable. diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs index 4f79b55..f11260e 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs @@ -8,6 +8,7 @@ using System; using System.Security; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -29,7 +30,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private MapToCollectionAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // int Count { get } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs index 89d1573..981972c 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs @@ -8,6 +8,7 @@ using System; using System.Security; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -26,7 +27,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private MapToDictionaryAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // V this[K key] { get } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs index 2dd3419..a3715da 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs @@ -8,6 +8,7 @@ using System; using System.Security; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -29,7 +30,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private MapViewToReadOnlyCollectionAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // int Count { get } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs index 89f1022..898f1a6 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs @@ -8,6 +8,7 @@ using System; using System.Security; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -26,7 +27,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private VectorToCollectionAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // int Count { get } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs index 76cfda3..3e33248 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs @@ -8,6 +8,7 @@ using System; using System.Security; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -26,7 +27,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private VectorToListAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // T this[int index] { get } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs index 451446e..6b7785d 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs @@ -8,6 +8,7 @@ using System; using System.Security; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -26,7 +27,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private VectorViewToReadOnlyCollectionAdapter() { - Contract.Assert(false, "This class is never instantiated"); + Debug.Assert(false, "This class is never instantiated"); } // int Count { get } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs index 3f075d7..a7ad491 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.CompilerServices; @@ -535,7 +536,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime private static object GetInstanceKey(Action removeMethod) { object target = removeMethod.Target; - Contract.Assert(target == null || Marshal.IsComObject(target), "Must be null or a RCW"); + Debug.Assert(target == null || Marshal.IsComObject(target), "Must be null or a RCW"); if (target == null) return removeMethod.Method.DeclaringType; @@ -712,7 +713,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Note that inside TryGetValueWithValueEquality we assumes that any delegate // with the same value equality would have the same hash code object key = registrationTokens.FindEquivalentKeyUnsafe(handler, out tokens); - Contract.Assert((key != null && tokens != null) || (key == null && tokens == null), + Debug.Assert((key != null && tokens != null) || (key == null && tokens == null), "key and tokens must be both null or non-null"); if (tokens == null) { @@ -898,7 +899,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal void ReleaseReaderLock() { EnterMyLock(); - Contract.Assert(owners > 0, "ReleasingReaderLock: releasing lock and no read lock taken"); + Debug.Assert(owners > 0, "ReleasingReaderLock: releasing lock and no read lock taken"); --owners; ExitAndWakeUpAppropriateWaiters(); } @@ -906,7 +907,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal void ReleaseWriterLock() { EnterMyLock(); - Contract.Assert(owners == -1, "Calling ReleaseWriterLock when no write lock is held"); + Debug.Assert(owners == -1, "Calling ReleaseWriterLock when no write lock is held"); owners++; ExitAndWakeUpAppropriateWaiters(); } @@ -918,8 +919,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime /// set 'waitEvent' /// private void LazyCreateEvent(ref EventWaitHandle waitEvent, bool makeAutoResetEvent) { - Contract.Assert(myLock != 0, "Lock must be held"); - Contract.Assert(waitEvent == null, "Wait event must be null"); + Debug.Assert(myLock != 0, "Lock must be held"); + Debug.Assert(waitEvent == null, "Wait event must be null"); ExitMyLock(); EventWaitHandle newEvent; @@ -938,7 +939,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime /// private void WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, int millisecondsTimeout) { - Contract.Assert(myLock != 0, "Lock must be held"); + Debug.Assert(myLock != 0, "Lock must be held"); waitEvent.Reset(); numWaiters++; @@ -966,7 +967,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime /// private void ExitAndWakeUpAppropriateWaiters() { - Contract.Assert(myLock != 0, "Lock must be held"); + Debug.Assert(myLock != 0, "Lock must be held"); if (owners == 0 && numWriteWaiters > 0) { @@ -1002,7 +1003,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime } private void ExitMyLock() { - Contract.Assert(myLock != 0, "Exiting spin lock that is not held"); + Debug.Assert(myLock != 0, "Exiting spin lock that is not held"); myLock = 0; } }; diff --git a/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs b/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs index 03fdbe3..bd87d90 100644 --- a/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs +++ b/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs @@ -22,6 +22,7 @@ using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Security.Permissions; using System.Runtime.Versioning; +using System.Diagnostics; using System.Diagnostics.Contracts; /* @@ -282,7 +283,7 @@ namespace System.Runtime break; default: - Contract.Assert(false, "Fell through switch statement!"); + Debug.Assert(false, "Fell through switch statement!"); break; } } diff --git a/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs b/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs index 7544a0b..27c3f15 100644 --- a/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs +++ b/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs @@ -29,6 +29,7 @@ namespace System.Runtime.Serialization { using System.IO; using System.Text; using System.Globalization; + using System.Diagnostics; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] @@ -97,7 +98,7 @@ namespace System.Runtime.Serialization { FieldInfo [] typeFields; RuntimeType parentType; - Contract.Assert((object)type != null, "[GetAllSerializableMembers]type!=null"); + Debug.Assert((object)type != null, "[GetAllSerializableMembers]type!=null"); if (type.IsInterface) { return new MemberInfo[0]; @@ -400,7 +401,7 @@ namespace System.Runtime.Serialization { } if (mi.MemberType==MemberTypes.Field) { - Contract.Assert(mi is RuntimeFieldInfo || mi is SerializationFieldInfo, + Debug.Assert(mi is RuntimeFieldInfo || mi is SerializationFieldInfo, "[FormatterServices.GetObjectData]mi is RuntimeFieldInfo || mi is SerializationFieldInfo."); RtFieldInfo rfi = mi as RtFieldInfo; diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationFieldInfo.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationFieldInfo.cs index 464f770..82536ce 100644 --- a/src/mscorlib/src/System/Runtime/Serialization/SerializationFieldInfo.cs +++ b/src/mscorlib/src/System/Runtime/Serialization/SerializationFieldInfo.cs @@ -21,6 +21,7 @@ namespace System.Runtime.Serialization { using System; using System.Reflection; using System.Globalization; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Threading; @@ -35,8 +36,8 @@ namespace System.Runtime.Serialization { public override int MetadataToken { get { return m_field.MetadataToken; } } internal SerializationFieldInfo(RuntimeFieldInfo field, String namePrefix) { - Contract.Assert(field!=null, "[SerializationFieldInfo.ctor]field!=null"); - Contract.Assert(namePrefix!=null, "[SerializationFieldInfo.ctor]namePrefix!=null"); + Debug.Assert(field!=null, "[SerializationFieldInfo.ctor]field!=null"); + Debug.Assert(namePrefix!=null, "[SerializationFieldInfo.ctor]namePrefix!=null"); m_field = field; m_serializationName = String.Concat(namePrefix, FakeNameSeparatorString, m_field.Name); diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs index 92a6ce6..55909c8 100644 --- a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs +++ b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs @@ -19,6 +19,7 @@ namespace System.Runtime.Serialization using System.Reflection; using System.Runtime.Remoting; using System.Globalization; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; using System.Runtime.CompilerServices; @@ -228,7 +229,7 @@ namespace System.Runtime.Serialization private void ExpandArrays() { int newSize; - Contract.Assert(m_members.Length == m_currMember, "[SerializationInfo.ExpandArrays]m_members.Length == m_currMember"); + Debug.Assert(m_members.Length == m_currMember, "[SerializationInfo.ExpandArrays]m_members.Length == m_currMember"); newSize = (m_currMember * 2); @@ -407,9 +408,9 @@ namespace System.Runtime.Serialization // its ObjectManager implementation, but it should not be exposed out of a contract. public void UpdateValue(String name, Object value, Type type) { - Contract.Assert(null != name, "[SerializationInfo.UpdateValue]name!=null"); - Contract.Assert(null != value, "[SerializationInfo.UpdateValue]value!=null"); - Contract.Assert(null != (object)type, "[SerializationInfo.UpdateValue]type!=null"); + Debug.Assert(null != name, "[SerializationInfo.UpdateValue]name!=null"); + Debug.Assert(null != value, "[SerializationInfo.UpdateValue]value!=null"); + Debug.Assert(null != (object)type, "[SerializationInfo.UpdateValue]type!=null"); int index = FindElement(name); if (index < 0) @@ -458,11 +459,11 @@ namespace System.Runtime.Serialization throw new SerializationException(Environment.GetResourceString("Serialization_NotFound", name)); } - Contract.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index=0, "[SerializationInfoEnumerator.ctor]numItems>=0"); - Contract.Assert(members.Length>=numItems, "[SerializationInfoEnumerator.ctor]members.Length>=numItems"); - Contract.Assert(info.Length>=numItems, "[SerializationInfoEnumerator.ctor]info.Length>=numItems"); - Contract.Assert(types.Length>=numItems, "[SerializationInfoEnumerator.ctor]types.Length>=numItems"); + Debug.Assert(members!=null, "[SerializationInfoEnumerator.ctor]members!=null"); + Debug.Assert(info!=null, "[SerializationInfoEnumerator.ctor]info!=null"); + Debug.Assert(types!=null, "[SerializationInfoEnumerator.ctor]types!=null"); + Debug.Assert(numItems>=0, "[SerializationInfoEnumerator.ctor]numItems>=0"); + Debug.Assert(members.Length>=numItems, "[SerializationInfoEnumerator.ctor]members.Length>=numItems"); + Debug.Assert(info.Length>=numItems, "[SerializationInfoEnumerator.ctor]info.Length>=numItems"); + Debug.Assert(types.Length>=numItems, "[SerializationInfoEnumerator.ctor]types.Length>=numItems"); m_members = members; m_data = info; diff --git a/src/mscorlib/src/System/Security/BuiltInPermissionSets.cs b/src/mscorlib/src/System/Security/BuiltInPermissionSets.cs index 2818416..4853957 100644 --- a/src/mscorlib/src/System/Security/BuiltInPermissionSets.cs +++ b/src/mscorlib/src/System/Security/BuiltInPermissionSets.cs @@ -6,6 +6,7 @@ // using System; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security.Permissions; using Microsoft.Win32; @@ -247,7 +248,7 @@ namespace System.Security private static NamedPermissionSet GetOrDeserializePermissionSet(ref NamedPermissionSet permissionSet, string permissionSetXml) { - Contract.Assert(!String.IsNullOrEmpty(permissionSetXml)); + Debug.Assert(!String.IsNullOrEmpty(permissionSetXml)); return permissionSet.Copy() as NamedPermissionSet; } } diff --git a/src/mscorlib/src/System/Security/CodeAccessPermission.cs b/src/mscorlib/src/System/Security/CodeAccessPermission.cs index 90b1201..70504d9 100644 --- a/src/mscorlib/src/System/Security/CodeAccessPermission.cs +++ b/src/mscorlib/src/System/Security/CodeAccessPermission.cs @@ -13,7 +13,7 @@ namespace System.Security using System.Collections; using System.Text; using System; - using System.Diagnostics; + using System.Diagnostics; using System.Diagnostics.Contracts; using IUnrestrictedPermission = System.Security.Permissions.IUnrestrictedPermission; @@ -78,7 +78,7 @@ namespace System.Security // without having to create objects. // The security annotation fxcop rule that flags all methods with a Demand() has logic // which checks for methods named Demand in types that implement IPermission or IStackWalk. - Contract.Assert(new StackFrame().GetMethod().Name.Equals("Demand"), "This method needs to be named Demand"); + Debug.Assert(new StackFrame().GetMethod().Name.Equals("Demand"), "This method needs to be named Demand"); StackCrawlMark stackMark = StackCrawlMark.LookForMyCallersCaller; CodeAccessSecurityEngine.SpecialDemand(permissionType, ref stackMark); @@ -104,7 +104,7 @@ namespace System.Security // without having to new a PermissionSet. // The security annotation fxcop rule that flags all methods with an Assert() has logic // which checks for methods named Assert in types that implement IPermission or IStackWalk. - Contract.Assert(new StackFrame().GetMethod().Name.Equals("Assert"), "This method needs to be named Assert"); + Debug.Assert(new StackFrame().GetMethod().Name.Equals("Assert"), "This method needs to be named Assert"); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; SecurityRuntime.AssertAllPossible(ref stackMark); @@ -203,26 +203,26 @@ namespace System.Security internal bool CheckDemand(CodeAccessPermission grant) { - Contract.Assert( grant == null || grant.GetType().Equals( this.GetType() ), "CheckDemand not defined for permissions of different type" ); + Debug.Assert( grant == null || grant.GetType().Equals( this.GetType() ), "CheckDemand not defined for permissions of different type" ); return IsSubsetOf( grant ); } internal bool CheckPermitOnly(CodeAccessPermission permitted) { - Contract.Assert( permitted == null || permitted.GetType().Equals( this.GetType() ), "CheckPermitOnly not defined for permissions of different type" ); + Debug.Assert( permitted == null || permitted.GetType().Equals( this.GetType() ), "CheckPermitOnly not defined for permissions of different type" ); return IsSubsetOf( permitted ); } internal bool CheckDeny(CodeAccessPermission denied) { - Contract.Assert( denied == null || denied.GetType().Equals( this.GetType() ), "CheckDeny not defined for permissions of different type" ); + Debug.Assert( denied == null || denied.GetType().Equals( this.GetType() ), "CheckDeny not defined for permissions of different type" ); IPermission intersectPerm = Intersect(denied); return (intersectPerm == null || intersectPerm.IsSubsetOf(null)); } internal bool CheckAssert(CodeAccessPermission asserted) { - Contract.Assert( asserted == null || asserted.GetType().Equals( this.GetType() ), "CheckPermitOnly not defined for permissions of different type" ); + Debug.Assert( asserted == null || asserted.GetType().Equals( this.GetType() ), "CheckPermitOnly not defined for permissions of different type" ); return IsSubsetOf( asserted ); } } diff --git a/src/mscorlib/src/System/Security/CodeAccessSecurityEngine.cs b/src/mscorlib/src/System/Security/CodeAccessSecurityEngine.cs index 0bdb9b7..d86897c 100644 --- a/src/mscorlib/src/System/Security/CodeAccessSecurityEngine.cs +++ b/src/mscorlib/src/System/Security/CodeAccessSecurityEngine.cs @@ -15,6 +15,7 @@ namespace System.Security { using System.Globalization; using System.Security.Policy; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; // Used in DemandInternal, to remember the result of previous demands @@ -98,7 +99,7 @@ namespace System.Security { private static void ThrowSecurityException(Object assemblyOrString, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed) #pragma warning restore 618 { - Contract.Assert((assemblyOrString == null || assemblyOrString is RuntimeAssembly || assemblyOrString is String), "Must pass in an Assembly object or String object here"); + Debug.Assert((assemblyOrString == null || assemblyOrString is RuntimeAssembly || assemblyOrString is String), "Must pass in an Assembly object or String object here"); if (assemblyOrString == null || assemblyOrString is RuntimeAssembly) ThrowSecurityException((RuntimeAssembly)assemblyOrString, granted, refused, rmh, action, demand, permThatFailed); @@ -137,7 +138,7 @@ namespace System.Security { // To reduce the amount of ifdef-code-churn, a dummy arg is used for the first parameter - instead of a CompressedStack object, // we use a System.Object that should always be null. If we tried to change the signature of the function, there will need to be // corresponding changes in VM (metasig.h, mscorlib.h, securitystackwalk.cpp, number of elements in the arg array, etc.) - Contract.Assert(notUsed == null, "Should not reach here with a non-null first arg which is the CompressedStack"); + Debug.Assert(notUsed == null, "Should not reach here with a non-null first arg which is the CompressedStack"); CheckSetHelper(grants, refused, demands, rmh, (Object)asm, action, true); } @@ -154,7 +155,7 @@ namespace System.Security { bool throwException) #pragma warning restore 618 { - Contract.Assert(demands != null, "Should not reach here with a null demand set"); + Debug.Assert(demands != null, "Should not reach here with a null demand set"); IPermission permThatFailed = null; if (grants != null) @@ -236,7 +237,7 @@ namespace System.Security { // To reduce the amount of ifdef-code-churn, a dummy arg is used for the first parameter - instead of a CompressedStack object, // we use a System.Object that should always be null. If we tried to change the signature of the function, there will need to be // corresponding changes in VM (metasig.h, mscorlib.h, securitystackwalk.cpp, number of elements in the arg array, etc.) - Contract.Assert(notUsed == null, "Should not reach here with a non-null first arg which is the CompressedStack"); + Debug.Assert(notUsed == null, "Should not reach here with a non-null first arg which is the CompressedStack"); CheckHelper(grantedSet, refusedSet, demand, permToken, rmh, (Object)asm, action, true); } #endif // FEATURE_COMPRESSEDSTACK @@ -252,7 +253,7 @@ namespace System.Security { #pragma warning restore 618 { // We should never get here with a null demand - Contract.Assert(demand != null, "Should not reach here with a null demand"); + Debug.Assert(demand != null, "Should not reach here with a null demand"); if (permToken == null) permToken = PermissionToken.GetToken(demand); @@ -281,7 +282,7 @@ namespace System.Security { // If we aren't unrestricted, there is a refused set, or our permission is not of the unrestricted // variety, we need to do the proper callback. - Contract.Assert(demand != null,"demand != null"); + Debug.Assert(demand != null,"demand != null"); // Find the permission of matching type in the permission set. diff --git a/src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs b/src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs index 5e9dab8..0ef5afd 100644 --- a/src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs +++ b/src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs @@ -12,6 +12,7 @@ namespace System.Security { using System.Globalization; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; #if !FEATURE_PAL using Microsoft.Win32.SafeHandles; @@ -263,7 +264,7 @@ namespace System.Security { PermissionSet permSet; // If the demand is null, there is no need to continue - Contract.Assert(demand != null && !demand.CheckDemand(null), "Empty demands should have been filtered out by this point"); + Debug.Assert(demand != null && !demand.CheckDemand(null), "Empty demands should have been filtered out by this point"); // decode imperative if (GetPermitOnly(fDeclarative) != null) diff --git a/src/mscorlib/src/System/Security/PermissionListSet.cs b/src/mscorlib/src/System/Security/PermissionListSet.cs index cb2ac30..093542a 100644 --- a/src/mscorlib/src/System/Security/PermissionListSet.cs +++ b/src/mscorlib/src/System/Security/PermissionListSet.cs @@ -23,6 +23,7 @@ namespace System.Security using System.Threading; using System.Collections; using System.Collections.Generic; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -59,7 +60,7 @@ namespace System.Security } internal void UpdateDomainPLS (PermissionSet grantSet, PermissionSet deniedSet) { - Contract.Assert(m_permSetTriples == null, "m_permSetTriples != null"); + Debug.Assert(m_permSetTriples == null, "m_permSetTriples != null"); if (m_firstPermSetTriple == null) m_firstPermSetTriple = new PermissionSetTriple(); @@ -410,7 +411,7 @@ namespace System.Security internal bool CheckDemandNoThrow(CodeAccessPermission demand) { // AppDomain permissions - no asserts. So there should only be one triple to work with - Contract.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet"); + Debug.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet"); @@ -425,7 +426,7 @@ namespace System.Security internal bool CheckSetDemandNoThrow(PermissionSet pSet) { // AppDomain permissions - no asserts. So there should only be one triple to work with - Contract.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet"); + Debug.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet"); return m_firstPermSetTriple.CheckSetDemandNoThrow(pSet); @@ -487,7 +488,7 @@ namespace System.Security /// set of flags to check (See PermissionType) private bool CheckFlags(int flags) { - Contract.Assert(flags != 0, "Invalid permission flag demand"); + Debug.Assert(flags != 0, "Invalid permission flag demand"); bool check = true; diff --git a/src/mscorlib/src/System/Security/PermissionSet.cs b/src/mscorlib/src/System/Security/PermissionSet.cs index ed98e47..11ca02a 100644 --- a/src/mscorlib/src/System/Security/PermissionSet.cs +++ b/src/mscorlib/src/System/Security/PermissionSet.cs @@ -21,6 +21,7 @@ namespace System.Security { using System.Text; using System.Globalization; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -115,7 +116,7 @@ namespace System.Security { [OnSerialized] private void OnSerialized(StreamingContext context) { - Contract.Assert(false, "PermissionSet does not support serialization on CoreCLR"); + Debug.Assert(false, "PermissionSet does not support serialization on CoreCLR"); } #endif // _DEBUG @@ -461,7 +462,7 @@ namespace System.Security { IPermission targetPerm = target.GetPermission(i); #if _DEBUG PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i ); - Contract.Assert(targetPerm == null || (token.m_type & PermissionTokenType.DontKnow) == 0, "Token not properly initialized"); + Debug.Assert(targetPerm == null || (token.m_type & PermissionTokenType.DontKnow) == 0, "Token not properly initialized"); #endif if (target.m_Unrestricted) @@ -573,7 +574,7 @@ namespace System.Security { internal void CheckDecoded( CodeAccessPermission demandedPerm, PermissionToken tokenDemandedPerm ) { - Contract.Assert( demandedPerm != null, "Expected non-null value" ); + Debug.Assert( demandedPerm != null, "Expected non-null value" ); if (this.m_allPermissionsDecoded || this.m_permSet == null) return; @@ -581,7 +582,7 @@ namespace System.Security { if (tokenDemandedPerm == null) tokenDemandedPerm = PermissionToken.GetToken( demandedPerm ); - Contract.Assert( tokenDemandedPerm != null, "Unable to find token for demanded permission" ); + Debug.Assert( tokenDemandedPerm != null, "Unable to find token for demanded permission" ); CheckDecoded( tokenDemandedPerm.m_index ); } @@ -596,7 +597,7 @@ namespace System.Security { internal void CheckDecoded(PermissionSet demandedSet) { - Contract.Assert(demandedSet != null, "Expected non-null value"); + Debug.Assert(demandedSet != null, "Expected non-null value"); if (this.m_allPermissionsDecoded || this.m_permSet == null) return; @@ -663,7 +664,7 @@ namespace System.Security { if ((token.m_type & PermissionTokenType.IUnrestricted) != 0) { this.m_permSet.SetItem( i, otherPerm.Copy() ); - Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); + Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); } } } @@ -760,7 +761,7 @@ namespace System.Security { if ((token.m_type & PermissionTokenType.IUnrestricted) != 0) { pset.m_permSet.SetItem( i, otherPerm.Copy() ); - Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); + Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); } } } @@ -775,7 +776,7 @@ namespace System.Security { if ((token.m_type & PermissionTokenType.IUnrestricted) != 0) { pset.m_permSet.SetItem( i, thisPerm.Copy() ); - Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); + Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); } } } @@ -790,7 +791,7 @@ namespace System.Security { else intersectPerm = thisPerm.Intersect( otherPerm ); pset.m_permSet.SetItem( i, intersectPerm ); - Contract.Assert( intersectPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); + Debug.Assert( intersectPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); } } @@ -937,7 +938,7 @@ namespace System.Security { if (((token.m_type & PermissionTokenType.IUnrestricted) == 0) || !pset.m_Unrestricted) { pset.m_permSet.SetItem( i, otherPerm.Copy() ); - Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); + Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); } } } @@ -949,7 +950,7 @@ namespace System.Security { if (((token.m_type & PermissionTokenType.IUnrestricted) == 0) || !pset.m_Unrestricted) { pset.m_permSet.SetItem( i, thisPerm.Copy() ); - Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); + Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); } } } @@ -963,7 +964,7 @@ namespace System.Security { else unionPerm = thisPerm.Union( otherPerm ); pset.m_permSet.SetItem( i, unionPerm ); - Contract.Assert( unionPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); + Debug.Assert( unionPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); } } @@ -1356,8 +1357,8 @@ namespace System.Security { // Internal routine used by CreateSerialized to add a permission to the set private static void MergePermission(IPermission perm, bool separateCasFromNonCas, ref PermissionSet casPset, ref PermissionSet nonCasPset) { - Contract.Assert(casPset == null || !casPset.IsReadOnly); - Contract.Assert(nonCasPset == null || !nonCasPset.IsReadOnly); + Debug.Assert(casPset == null || !casPset.IsReadOnly); + Debug.Assert(nonCasPset == null || !nonCasPset.IsReadOnly); if (perm == null) return; @@ -1400,7 +1401,7 @@ namespace System.Security { for (int i = 0; i < attrs.Length; i++) { #pragma warning disable 618 - Contract.Assert(i == 0 || ((SecurityAttribute)attrs[i]).m_action == ((SecurityAttribute)attrs[i - 1]).m_action, "Mixed SecurityActions"); + Debug.Assert(i == 0 || ((SecurityAttribute)attrs[i]).m_action == ((SecurityAttribute)attrs[i - 1]).m_action, "Mixed SecurityActions"); #pragma warning restore 618 if (attrs[i] is PermissionSetAttribute) { @@ -1429,7 +1430,7 @@ namespace System.Security { MergePermission(perm, serialize, ref casPset, ref nonCasPset); } } - Contract.Assert(serialize || nonCasPset == null, "We shouldn't separate nonCAS permissions unless fSerialize is true"); + Debug.Assert(serialize || nonCasPset == null, "We shouldn't separate nonCAS permissions unless fSerialize is true"); // // Filter HostProtection permission. In the VM, some optimizations are done based upon these @@ -1453,7 +1454,7 @@ namespace System.Security { nonCasPset = null; } - Contract.Assert(!serialize, "Cannot serialize permission sets on CoreCLR"); + Debug.Assert(!serialize, "Cannot serialize permission sets on CoreCLR"); return null; } @@ -1475,7 +1476,7 @@ namespace System.Security { internal static PermissionSet RemoveRefusedPermissionSet(PermissionSet assertSet, PermissionSet refusedSet, out bool bFailedToCompress) { - Contract.Assert((assertSet == null || !assertSet.IsUnrestricted()), "Cannot be unrestricted here"); + Debug.Assert((assertSet == null || !assertSet.IsUnrestricted()), "Cannot be unrestricted here"); PermissionSet retPs = null; bFailedToCompress = false; if (assertSet == null) @@ -1531,7 +1532,7 @@ namespace System.Security { internal static void RemoveAssertedPermissionSet(PermissionSet demandSet, PermissionSet assertSet, out PermissionSet alteredDemandSet) { - Contract.Assert(!assertSet.IsUnrestricted(), "Cannot call this function if assertSet is unrestricted"); + Debug.Assert(!assertSet.IsUnrestricted(), "Cannot call this function if assertSet is unrestricted"); alteredDemandSet = null; PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(demandSet); diff --git a/src/mscorlib/src/System/Security/PermissionSetTriple.cs b/src/mscorlib/src/System/Security/PermissionSetTriple.cs index 25e0177..56eb229 100644 --- a/src/mscorlib/src/System/Security/PermissionSetTriple.cs +++ b/src/mscorlib/src/System/Security/PermissionSetTriple.cs @@ -19,6 +19,7 @@ namespace System.Security using System.Security; using System.Security.Permissions; using System.Runtime.InteropServices; + using System.Diagnostics; using System.Diagnostics.Contracts; @@ -88,7 +89,7 @@ namespace System.Security PermissionSetTriple retTriple = null; if (in_a != null) { - Contract.Assert((!in_a.IsUnrestricted() || RefusedSet == null), "Cannot be unrestricted or refused must be null"); + Debug.Assert((!in_a.IsUnrestricted() || RefusedSet == null), "Cannot be unrestricted or refused must be null"); // if we're already asserting in_a, nothing to do if (in_a.IsSubsetOf(AssertSet)) return null; @@ -231,14 +232,14 @@ namespace System.Security internal bool CheckDemandNoThrow(CodeAccessPermission demand, PermissionToken permToken) { - Contract.Assert(AssertSet == null, "AssertSet not null"); + Debug.Assert(AssertSet == null, "AssertSet not null"); #pragma warning disable 618 return CodeAccessSecurityEngine.CheckHelper(GrantSet, RefusedSet, demand, permToken, RuntimeMethodHandleInternal.EmptyHandle, null, SecurityAction.Demand, false); #pragma warning restore 618 } internal bool CheckSetDemandNoThrow(PermissionSet demandSet) { - Contract.Assert(AssertSet == null, "AssertSet not null"); + Debug.Assert(AssertSet == null, "AssertSet not null"); #pragma warning disable 618 return CodeAccessSecurityEngine.CheckSetHelper(GrantSet, RefusedSet, demandSet, RuntimeMethodHandleInternal.EmptyHandle, null, SecurityAction.Demand, false); diff --git a/src/mscorlib/src/System/Security/PermissionToken.cs b/src/mscorlib/src/System/Security/PermissionToken.cs index 3d69fdc..5c6a322 100644 --- a/src/mscorlib/src/System/Security/PermissionToken.cs +++ b/src/mscorlib/src/System/Security/PermissionToken.cs @@ -12,6 +12,7 @@ namespace System.Security using System.Threading; using System.Globalization; using System.Runtime.CompilerServices; + using System.Diagnostics; using System.Diagnostics.Contracts; [Flags] @@ -96,7 +97,7 @@ namespace System.Security static internal TokenBasedSet s_tokenSet = new TokenBasedSet(); internal static bool IsMscorlibClassName (string className) { - Contract.Assert( c_mscorlibName == ((RuntimeAssembly)Assembly.GetExecutingAssembly()).GetSimpleName(), + Debug.Assert( c_mscorlibName == ((RuntimeAssembly)Assembly.GetExecutingAssembly()).GetSimpleName(), System.CoreLib.Name+" name mismatch" ); // If the class name does not look like a fully qualified name, we cannot simply determine if it's @@ -228,7 +229,7 @@ namespace System.Security internal PermissionToken GetToken(Type cls, IPermission perm) { - Contract.Assert( cls != null, "Must pass in valid type" ); + Debug.Assert( cls != null, "Must pass in valid type" ); IntPtr typePtr = cls.TypeHandle.Value; object tok = m_handleTable[typePtr]; @@ -284,12 +285,12 @@ namespace System.Security { if (perm != null) { - Contract.Assert( !(perm is IBuiltInPermission), "This should not be called for built-ins" ); + Debug.Assert( !(perm is IBuiltInPermission), "This should not be called for built-ins" ); ((PermissionToken)tok).m_type = PermissionTokenType.IUnrestricted; } else { - Contract.Assert( cls.GetInterface( "System.Security.Permissions.IBuiltInPermission" ) == null, "This shoudl not be called for built-ins" ); + Debug.Assert( cls.GetInterface( "System.Security.Permissions.IBuiltInPermission" ) == null, "This shoudl not be called for built-ins" ); if (cls.GetInterface(s_unrestrictedPermissionInferfaceName) != null) ((PermissionToken)tok).m_type = PermissionTokenType.IUnrestricted; else diff --git a/src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs b/src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs index 5ac0609..34b9f1e 100644 --- a/src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs +++ b/src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs @@ -14,6 +14,7 @@ namespace System.Security.Permissions using System.Globalization; using System.Runtime.Serialization; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -1006,7 +1007,7 @@ namespace System.Security.Permissions return this.IsEmpty() ? null : this.Copy(); } - Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" ); + Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" ); if (this.m_allFiles || operand.m_allFiles) { @@ -1023,7 +1024,7 @@ namespace System.Security.Permissions return null; } - Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" ); + Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" ); if (this.m_allFiles) { @@ -1097,7 +1098,7 @@ namespace System.Security.Permissions return true; } - Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" ); + Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" ); if (!((m_pathDiscovery && this.m_set.IsSubsetOfPathDiscovery( operand.m_set )) || this.m_set.IsSubsetOf( operand.m_set ))) { @@ -1185,7 +1186,7 @@ namespace System.Security.Permissions FileIOAccess operand = obj as FileIOAccess; if(operand == null) return (IsEmpty() && obj == null); - Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" ); + Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" ); if(m_pathDiscovery) { if(this.m_allFiles && operand.m_allFiles) diff --git a/src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs b/src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs index 927097c..d4f1c27 100644 --- a/src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs +++ b/src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs @@ -11,6 +11,7 @@ namespace System.Security.Permissions { #endif using System.Security.Util; using System.Globalization; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -542,7 +543,7 @@ namespace System.Security.Permissions { if (current != null) { if (String.Equals(current.Tag, "AccessEntry")) { int iMax = current.m_lAttributes.Count; - Contract.Assert(iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly"); + Debug.Assert(iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly"); string keyStore = null; string providerName = null; int providerType = -1; diff --git a/src/mscorlib/src/System/Security/Policy/EvidenceBase.cs b/src/mscorlib/src/System/Security/Policy/EvidenceBase.cs index 3875793..7fef1de 100644 --- a/src/mscorlib/src/System/Security/Policy/EvidenceBase.cs +++ b/src/mscorlib/src/System/Security/Policy/EvidenceBase.cs @@ -7,6 +7,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.IO; using System.Runtime.InteropServices; @@ -78,9 +79,9 @@ namespace System.Security.Policy internal LegacyEvidenceWrapper(object legacyEvidence) { - Contract.Assert(legacyEvidence != null); - Contract.Assert(legacyEvidence.GetType() != typeof(EvidenceBase), "Attempt to wrap an EvidenceBase in a LegacyEvidenceWrapper"); - Contract.Assert(legacyEvidence.GetType().IsSerializable, "legacyEvidence.GetType().IsSerializable"); + Debug.Assert(legacyEvidence != null); + Debug.Assert(legacyEvidence.GetType() != typeof(EvidenceBase), "Attempt to wrap an EvidenceBase in a LegacyEvidenceWrapper"); + Debug.Assert(legacyEvidence.GetType().IsSerializable, "legacyEvidence.GetType().IsSerializable"); m_legacyEvidence = legacyEvidence; } @@ -141,7 +142,7 @@ namespace System.Security.Policy { get { - Contract.Assert(m_legacyEvidenceList.Count > 0, "No items in LegacyEvidenceList, cannot tell what type they are"); + Debug.Assert(m_legacyEvidenceList.Count > 0, "No items in LegacyEvidenceList, cannot tell what type they are"); ILegacyEvidenceAdapter adapter = m_legacyEvidenceList[0] as ILegacyEvidenceAdapter; return adapter == null ? m_legacyEvidenceList[0].GetType() : adapter.EvidenceType; @@ -150,10 +151,10 @@ namespace System.Security.Policy public void Add(EvidenceBase evidence) { - Contract.Assert(evidence != null); - Contract.Assert(m_legacyEvidenceList.Count == 0 || EvidenceType == evidence.GetType() || (evidence is LegacyEvidenceWrapper && (evidence as LegacyEvidenceWrapper).EvidenceType == EvidenceType), + Debug.Assert(evidence != null); + Debug.Assert(m_legacyEvidenceList.Count == 0 || EvidenceType == evidence.GetType() || (evidence is LegacyEvidenceWrapper && (evidence as LegacyEvidenceWrapper).EvidenceType == EvidenceType), "LegacyEvidenceList must be homogeonous"); - Contract.Assert(evidence.GetType() != typeof(LegacyEvidenceList), + Debug.Assert(evidence.GetType() != typeof(LegacyEvidenceList), "Attempt to add a legacy evidence list to another legacy evidence list"); m_legacyEvidenceList.Add(evidence); diff --git a/src/mscorlib/src/System/Security/Policy/EvidenceTypeDescriptor.cs b/src/mscorlib/src/System/Security/Policy/EvidenceTypeDescriptor.cs index bccf392..8deb145 100644 --- a/src/mscorlib/src/System/Security/Policy/EvidenceTypeDescriptor.cs +++ b/src/mscorlib/src/System/Security/Policy/EvidenceTypeDescriptor.cs @@ -41,7 +41,7 @@ namespace System.Security.Policy /// private EvidenceTypeDescriptor(EvidenceTypeDescriptor descriptor) { - Contract.Assert(descriptor != null); + Debug.Assert(descriptor != null); m_hostCanGenerate = descriptor.m_hostCanGenerate; @@ -68,9 +68,9 @@ namespace System.Security.Policy set { - Contract.Assert(value != null); + Debug.Assert(value != null); #if _DEBUG - Contract.Assert(CheckEvidenceType(value), "Incorrect type of AssemblyEvidence set"); + Debug.Assert(CheckEvidenceType(value), "Incorrect type of AssemblyEvidence set"); #endif m_assemblyEvidence = value; } @@ -85,7 +85,7 @@ namespace System.Security.Policy set { - Contract.Assert(value, "Attempt to clear the Generated flag"); + Debug.Assert(value, "Attempt to clear the Generated flag"); m_generated = value; } } @@ -99,7 +99,7 @@ namespace System.Security.Policy set { - Contract.Assert(value, "Attempt to clear HostCanGenerate flag"); + Debug.Assert(value, "Attempt to clear HostCanGenerate flag"); m_hostCanGenerate = value; } } @@ -113,9 +113,9 @@ namespace System.Security.Policy set { - Contract.Assert(value != null); + Debug.Assert(value != null); #if _DEBUG - Contract.Assert(CheckEvidenceType(value), "Incorrect type of HostEvidence set"); + Debug.Assert(CheckEvidenceType(value), "Incorrect type of HostEvidence set"); #endif m_hostEvidence = value; } @@ -127,7 +127,7 @@ namespace System.Security.Policy /// private bool CheckEvidenceType(EvidenceBase evidence) { - Contract.Assert(evidence != null); + Debug.Assert(evidence != null); ILegacyEvidenceAdapter legacyAdapter = evidence as ILegacyEvidenceAdapter; Type storedType = legacyAdapter == null ? evidence.GetType() : legacyAdapter.EvidenceType; @@ -150,8 +150,8 @@ namespace System.Security.Policy /// internal void SetEvidenceType(Type evidenceType) { - Contract.Assert(evidenceType != null); - Contract.Assert(m_evidenceType == null, "Attempt to reset evidence type"); + Debug.Assert(evidenceType != null); + Debug.Assert(m_evidenceType == null, "Attempt to reset evidence type"); m_evidenceType = evidenceType; } diff --git a/src/mscorlib/src/System/Security/Policy/Site.cs b/src/mscorlib/src/System/Security/Policy/Site.cs index 937bb27..14a95e1 100644 --- a/src/mscorlib/src/System/Security/Policy/Site.cs +++ b/src/mscorlib/src/System/Security/Policy/Site.cs @@ -10,6 +10,7 @@ // using System; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Security.Permissions; @@ -34,7 +35,7 @@ namespace System.Security.Policy private Site(SiteString name) { - Contract.Assert(name != null); + Debug.Assert(name != null); m_name = name; } diff --git a/src/mscorlib/src/System/Security/Policy/URL.cs b/src/mscorlib/src/System/Security/Policy/URL.cs index baa5b1c..3541124 100644 --- a/src/mscorlib/src/System/Security/Policy/URL.cs +++ b/src/mscorlib/src/System/Security/Policy/URL.cs @@ -14,6 +14,7 @@ namespace System.Security.Policy { using System.Security.Util; using UrlIdentityPermission = System.Security.Permissions.UrlIdentityPermission; using System.Runtime.Serialization; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -42,7 +43,7 @@ namespace System.Security.Policy { private Url(Url url) { - Contract.Assert(url != null); + Debug.Assert(url != null); m_url = url.m_url; } diff --git a/src/mscorlib/src/System/Security/Policy/Zone.cs b/src/mscorlib/src/System/Security/Policy/Zone.cs index 7bcb4b9..a9f5d84 100644 --- a/src/mscorlib/src/System/Security/Policy/Zone.cs +++ b/src/mscorlib/src/System/Security/Policy/Zone.cs @@ -17,6 +17,7 @@ namespace System.Security.Policy using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Runtime.Serialization; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -39,7 +40,7 @@ namespace System.Security.Policy private Zone(Zone zone) { - Contract.Assert(zone != null); + Debug.Assert(zone != null); m_zone = zone.m_zone; } diff --git a/src/mscorlib/src/System/Security/SecurityContext.cs b/src/mscorlib/src/System/Security/SecurityContext.cs index bc22345..674c041 100644 --- a/src/mscorlib/src/System/Security/SecurityContext.cs +++ b/src/mscorlib/src/System/Security/SecurityContext.cs @@ -27,6 +27,7 @@ namespace System.Security #endif // FEATURE_CORRUPTING_EXCEPTIONS using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; // This enum must be kept in sync with the SecurityContextSource enum in the VM @@ -86,8 +87,8 @@ namespace System.Security if (currEC != null) { - Contract.Assert(currEC == Thread.CurrentThread.GetMutableExecutionContext(), "SecurityContextSwitcher used from another thread"); - Contract.Assert(currSC == currEC.SecurityContext, "SecurityContextSwitcher context mismatch"); + Debug.Assert(currEC == Thread.CurrentThread.GetMutableExecutionContext(), "SecurityContextSwitcher used from another thread"); + Debug.Assert(currSC == currEC.SecurityContext, "SecurityContextSwitcher context mismatch"); // restore the saved security context currEC.SecurityContext = prevSC.DangerousGetRawSecurityContext(); @@ -95,7 +96,7 @@ namespace System.Security else { // caller must have already restored the ExecutionContext - Contract.Assert(Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsSame(prevSC)); + Debug.Assert(Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsSame(prevSC)); } currSC = null; // this will prevent the switcher object being used again @@ -284,7 +285,7 @@ namespace System.Security // and automatically goes away when the callback returns. WindowsIdentity.SafeRevertToSelf(ref stackMark); // Ensure we have reverted to the state we entered in. - Contract.Assert(GetCurrentWI(Thread.CurrentThread.GetExecutionContextReader()) == null); + Debug.Assert(GetCurrentWI(Thread.CurrentThread.GetExecutionContextReader()) == null); } } else @@ -409,7 +410,7 @@ namespace System.Security /// internal SecurityContext CreateMutableCopy() { - Contract.Assert(!this.isNewCapture); + Debug.Assert(!this.isNewCapture); SecurityContext sc = new SecurityContext(); sc._disableFlow = this._disableFlow; diff --git a/src/mscorlib/src/System/Security/SecurityElement.cs b/src/mscorlib/src/System/Security/SecurityElement.cs index 39cd4fb..f57665b 100644 --- a/src/mscorlib/src/System/Security/SecurityElement.cs +++ b/src/mscorlib/src/System/Security/SecurityElement.cs @@ -14,6 +14,7 @@ namespace System.Security using System.Globalization; using System.IO; using System.Security.Permissions; + using System.Diagnostics; using System.Diagnostics.Contracts; internal enum SecurityElementType @@ -158,7 +159,7 @@ namespace System.Security Hashtable hashtable = new Hashtable( m_lAttributes.Count/2 ); int iMax = m_lAttributes.Count; - Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); + Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); for (int i = 0; i < iMax; i += 2) { @@ -283,7 +284,7 @@ namespace System.Security else { int iMax = m_lAttributes.Count; - Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); + Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); for (int i = 0; i < iMax; i += 2) { @@ -387,7 +388,7 @@ namespace System.Security else { int iMax = m_lAttributes.Count; - Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); + Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); if (iMax != other.m_lAttributes.Count) return false; @@ -482,7 +483,7 @@ namespace System.Security private static String GetEscapeSequence( char c ) { int iMax = s_escapeStringPairs.Length; - Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); + Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); for (int i = 0; i < iMax; i += 2) { @@ -493,7 +494,7 @@ namespace System.Security return strEscValue; } - Contract.Assert( false, "Unable to find escape sequence for this character" ); + Debug.Assert( false, "Unable to find escape sequence for this character" ); return c.ToString(); } @@ -544,7 +545,7 @@ namespace System.Security int maxCompareLength = str.Length - index; int iMax = s_escapeStringPairs.Length; - Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); + Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); for (int i = 0; i < iMax; i += 2) { @@ -603,7 +604,7 @@ namespace System.Security while (true); // C# reports a warning if I leave this in, but I still kinda want to just in case. - // Contract.Assert( false, "If you got here, the execution engine or compiler is really confused" ); + // Debug.Assert( false, "If you got here, the execution engine or compiler is really confused" ); // return str; } @@ -656,7 +657,7 @@ namespace System.Security func( obj, " " ); int iMax = m_lAttributes.Count; - Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); + Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); for (int i = 0; i < iMax; i += 2) { @@ -760,7 +761,7 @@ namespace System.Security // the one we are asked for int iMax = m_lAttributes.Count; - Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); + Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); for (int i = 0; i < iMax; i += 2) { diff --git a/src/mscorlib/src/System/Security/Util/StringExpressionSet.cs b/src/mscorlib/src/System/Security/Util/StringExpressionSet.cs index 379fe04..8a12235 100644 --- a/src/mscorlib/src/System/Security/Util/StringExpressionSet.cs +++ b/src/mscorlib/src/System/Security/Util/StringExpressionSet.cs @@ -12,6 +12,7 @@ namespace System.Security.Util { using System.Globalization; using System.Runtime.Versioning; using System.IO; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -182,7 +183,7 @@ namespace System.Security.Util { public void AddExpressions( ArrayList exprArrayList, bool checkForDuplicates) { - Contract.Assert( m_throwOnRelative, "This should only be called when throw on relative is set" ); + Debug.Assert( m_throwOnRelative, "This should only be called when throw on relative is set" ); m_expressionsArray = null; m_expressions = null; diff --git a/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs b/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs index 45f9176..8589fa7 100644 --- a/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs +++ b/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs @@ -9,6 +9,7 @@ namespace System.Security.Util using System.Security.Permissions; using System.Runtime.Serialization; using System.Threading; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; @@ -397,7 +398,7 @@ namespace System.Security.Util } else { - Contract.Assert( (thisObj == null || otherObj == null), "Permission cannot be in both TokenBasedSets" ); + Debug.Assert( (thisObj == null || otherObj == null), "Permission cannot be in both TokenBasedSets" ); } } return unionSet; diff --git a/src/mscorlib/src/System/Security/Util/XMLUtil.cs b/src/mscorlib/src/System/Security/Util/XMLUtil.cs index e5798c2..3a1aaa3 100644 --- a/src/mscorlib/src/System/Security/Util/XMLUtil.cs +++ b/src/mscorlib/src/System/Security/Util/XMLUtil.cs @@ -25,6 +25,7 @@ namespace System.Security.Util { using System.Threading; using System.Globalization; using System.Reflection; + using System.Diagnostics; using System.Diagnostics.Contracts; internal static class XMLUtil @@ -61,7 +62,7 @@ namespace System.Security.Util { if ( typename == null ) typename = type.FullName; - Contract.Assert( type.FullName.Equals( typename ), "Incorrect class name passed! Was : " + typename + " Shoule be: " + type.FullName); + Debug.Assert( type.FullName.Equals( typename ), "Incorrect class name passed! Was : " + typename + " Shoule be: " + type.FullName); element.AddAttribute( "class", typename + ", " + type.Module.Assembly.FullName.Replace( '\"', '\'' ) ); } diff --git a/src/mscorlib/src/System/Security/securestring.cs b/src/mscorlib/src/System/Security/securestring.cs index f4216d2..548126f 100644 --- a/src/mscorlib/src/System/Security/securestring.cs +++ b/src/mscorlib/src/System/Security/securestring.cs @@ -14,6 +14,7 @@ namespace System.Security { using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using Microsoft.Win32.SafeHandles; + using System.Diagnostics; using System.Diagnostics.Contracts; public sealed class SecureString: IDisposable { @@ -293,7 +294,7 @@ namespace System.Security { throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexString")); } Contract.EndContractBlock(); - Contract.Assert(index <= Int32.MaxValue / sizeof(char)); + Debug.Assert(index <= Int32.MaxValue / sizeof(char)); EnsureNotDisposed(); EnsureNotReadOnly(); @@ -315,7 +316,7 @@ namespace System.Security { private int BufferLength { [System.Security.SecurityCritical] // auto-generated get { - Contract.Assert(m_buffer != null, "Buffer is not initialized!"); + Debug.Assert(m_buffer != null, "Buffer is not initialized!"); return m_buffer.Length; } } @@ -377,7 +378,7 @@ namespace System.Security { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private static uint GetAlignedSize( int size) { - Contract.Assert(size >= 0, "size must be non-negative"); + Debug.Assert(size >= 0, "size must be non-negative"); uint alignedSize = ((uint)size / BlockSize) * BlockSize; if( (size % BlockSize != 0) || size == 0) { // if size is 0, set allocated size to blocksize @@ -449,8 +450,8 @@ namespace System.Security { [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] private void ProtectMemory() { - Contract.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!"); - Contract.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!"); + Debug.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!"); + Debug.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!"); if( m_length == 0 || m_encrypted) { return; @@ -650,8 +651,8 @@ namespace System.Security { [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private void UnProtectMemory() { - Contract.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!"); - Contract.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!"); + Debug.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!"); + Debug.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!"); if( m_length == 0) { return; @@ -733,7 +734,7 @@ namespace System.Security { source.AcquirePointer(ref sourcePtr); target.AcquirePointer(ref targetPtr); - Contract.Assert(Win32Native.SysStringLen((IntPtr)targetPtr) >= Win32Native.SysStringLen((IntPtr)sourcePtr), "Target buffer is not large enough!"); + Debug.Assert(Win32Native.SysStringLen((IntPtr)targetPtr) >= Win32Native.SysStringLen((IntPtr)sourcePtr), "Target buffer is not large enough!"); Buffer.Memcpy(targetPtr, sourcePtr, (int) Win32Native.SysStringLen((IntPtr)sourcePtr) * 2); } diff --git a/src/mscorlib/src/System/SharedStatics.cs b/src/mscorlib/src/System/SharedStatics.cs index 25388af..cbc5c35 100644 --- a/src/mscorlib/src/System/SharedStatics.cs +++ b/src/mscorlib/src/System/SharedStatics.cs @@ -19,6 +19,7 @@ namespace System using System.Security.Util; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; + using System.Diagnostics; using System.Diagnostics.Contracts; internal sealed class SharedStatics @@ -57,7 +58,7 @@ namespace System } } - Contract.Assert(_sharedStatics._Remoting_Identity_IDGuid != null, + Debug.Assert(_sharedStatics._Remoting_Identity_IDGuid != null, "_sharedStatics._Remoting_Identity_IDGuid != null"); return _sharedStatics._Remoting_Identity_IDGuid; } @@ -85,7 +86,7 @@ namespace System internal static ulong MemoryFailPointReservedMemory { get { - Contract.Assert(Volatile.Read(ref _sharedStatics._memFailPointReservedMemory) >= 0, "Process-wide MemoryFailPoint reserved memory was negative!"); + Debug.Assert(Volatile.Read(ref _sharedStatics._memFailPointReservedMemory) >= 0, "Process-wide MemoryFailPoint reserved memory was negative!"); return (ulong) Volatile.Read(ref _sharedStatics._memFailPointReservedMemory); } } diff --git a/src/mscorlib/src/System/String.Comparison.cs b/src/mscorlib/src/System/String.Comparison.cs index 88c2080..da99170 100644 --- a/src/mscorlib/src/System/String.Comparison.cs +++ b/src/mscorlib/src/System/String.Comparison.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; @@ -34,7 +35,7 @@ namespace System int charA = *a; int charB = *b; - Contract.Assert((charA | charB) <= 0x7F, "strings have to be ASCII"); + Debug.Assert((charA | charB) <= 0x7F, "strings have to be ASCII"); // uppercase both chars - notice that we need just one compare per char if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20; @@ -150,7 +151,7 @@ namespace System #if BIT64 // Single int read aligns pointers for the following long reads // No length check needed as this method is called when length >= 2 - Contract.Assert(length >= 2); + Debug.Assert(length >= 2); if (*(int*)a != *(int*)b) goto ReturnFalse; length -= 2; a += 2; b += 2; @@ -196,7 +197,7 @@ namespace System // NOTE: This may be subject to change if eliminating the check // in the callers makes them small enough to be inlined by the JIT - Contract.Assert(strA.m_firstChar == strB.m_firstChar, + Debug.Assert(strA.m_firstChar == strB.m_firstChar, "For performance reasons, callers of this method should " + "check/short-circuit beforehand if the first char is the same."); @@ -304,7 +305,7 @@ namespace System if (*a != *b) return *a - *b; DiffOffset1: - Contract.Assert(*(a + 1) != *(b + 1), "This char must be different if we reach here!"); + Debug.Assert(*(a + 1) != *(b + 1), "This char must be different if we reach here!"); return *(a + 1) - *(b + 1); } } @@ -1002,8 +1003,8 @@ namespace System internal int GetLegacyNonRandomizedHashCode() { unsafe { fixed (char* src = &m_firstChar) { - Contract.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'"); - Contract.Assert( ((int)src)%4 == 0, "Managed string should start at 4 bytes boundary"); + Debug.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'"); + Debug.Assert( ((int)src)%4 == 0, "Managed string should start at 4 bytes boundary"); #if BIT64 int hash1 = 5381; #else // !BIT64 (32) diff --git a/src/mscorlib/src/System/String.Manipulation.cs b/src/mscorlib/src/System/String.Manipulation.cs index 97121f6..194b4f8 100644 --- a/src/mscorlib/src/System/String.Manipulation.cs +++ b/src/mscorlib/src/System/String.Manipulation.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; @@ -165,8 +166,8 @@ namespace System { string s = strings[i]; - Contract.Assert(s != null); - Contract.Assert(position <= totalLength - s.Length, "We didn't allocate enough space for the result string!"); + Debug.Assert(s != null); + Debug.Assert(position <= totalLength - s.Length, "We didn't allocate enough space for the result string!"); FillStringChecked(result, position, s); position += s.Length; @@ -737,8 +738,8 @@ namespace System { // If the separator is null, it is converted to an empty string before entering this function. // Even for empty strings, fixed should never return null (it should return a pointer to a null char). - Contract.Assert(separator != null); - Contract.Assert(separatorLength >= 0); + Debug.Assert(separator != null); + Debug.Assert(separatorLength >= 0); if (value == null) { @@ -1304,7 +1305,7 @@ namespace System } // we must have at least one slot left to fill in the last string. - Contract.Assert(arrIndex < maxItems); + Debug.Assert(arrIndex < maxItems); //Handle the last string at the end of the array if there is one. if (currIndex< Length) { @@ -1328,7 +1329,7 @@ namespace System // sepList -- an array of ints for split char indicies. //-------------------------------------------------------------------- private unsafe int MakeSeparatorList(char* separators, int separatorsLength, int[] sepList) { - Contract.Assert(separatorsLength >= 0, "separatorsLength >= 0"); + Debug.Assert(separatorsLength >= 0, "separatorsLength >= 0"); int foundCount=0; if (separators == null || separatorsLength == 0) { @@ -1366,7 +1367,7 @@ namespace System // sepList -- an array of ints for split string indicies. //-------------------------------------------------------------------- private unsafe int MakeSeparatorList(string separator, int[] sepList) { - Contract.Assert(!string.IsNullOrEmpty(separator), "!string.IsNullOrEmpty(separator)"); + Debug.Assert(!string.IsNullOrEmpty(separator), "!string.IsNullOrEmpty(separator)"); int foundCount = 0; int sepListCount = sepList.Length; @@ -1395,7 +1396,7 @@ namespace System // lengthList -- an array of ints for split string lengths. //-------------------------------------------------------------------- private unsafe int MakeSeparatorList(String[] separators, int[] sepList, int[] lengthList) { - Contract.Assert(separators != null && separators.Length > 0, "separators != null && separators.Length > 0"); + Debug.Assert(separators != null && separators.Length > 0, "separators != null && separators.Length > 0"); int foundCount = 0; int sepListCount = sepList.Length; @@ -1465,8 +1466,8 @@ namespace System } unsafe string InternalSubString(int startIndex, int length) { - Contract.Assert( startIndex >= 0 && startIndex <= this.Length, "StartIndex is out of range!"); - Contract.Assert( length >= 0 && startIndex <= this.Length - length, "length is out of range!"); + Debug.Assert( startIndex >= 0 && startIndex <= this.Length, "StartIndex is out of range!"); + Debug.Assert( length >= 0 && startIndex <= this.Length - length, "length is out of range!"); String result = FastAllocateString(length); diff --git a/src/mscorlib/src/System/String.cs b/src/mscorlib/src/System/String.cs index 44565dc..f9162ff 100644 --- a/src/mscorlib/src/System/String.cs +++ b/src/mscorlib/src/System/String.cs @@ -24,6 +24,7 @@ namespace System { using System.Runtime.InteropServices; using System.Runtime.Versioning; using Microsoft.Win32; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; @@ -82,7 +83,7 @@ namespace System { for(int i = 0; i < length; i++) { int c = inBuff[i]; - Contract.Assert(c <= 0x7F, "string has to be ASCII"); + Debug.Assert(c <= 0x7F, "string has to be ASCII"); // uppercase - notice that we need just one compare if ((uint)(c - 'a') <= (uint)('z' - 'a')) c -= 0x20; @@ -90,7 +91,7 @@ namespace System { outBuff[i] = (char)c; } - Contract.Assert(outBuff[length]=='\0', "outBuff[length]=='\0'"); + Debug.Assert(outBuff[length]=='\0', "outBuff[length]=='\0'"); } return strOut; } @@ -255,7 +256,7 @@ namespace System { // Get our string length int stringLength = encoding.GetCharCount(bytes, byteLength, null); - Contract.Assert(stringLength >= 0, "stringLength >= 0"); + Debug.Assert(stringLength >= 0, "stringLength >= 0"); // They gave us an empty string if they needed one // 0 bytelength might be possible if there's something in an encoder @@ -266,7 +267,7 @@ namespace System { fixed(char* pTempChars = &s.m_firstChar) { int doubleCheck = encoding.GetChars(bytes, byteLength, pTempChars, stringLength, null); - Contract.Assert(stringLength == doubleCheck, + Debug.Assert(stringLength == doubleCheck, "Expected encoding.GetChars to return same length as encoding.GetCharCount"); } @@ -294,7 +295,7 @@ namespace System { unsafe internal int ConvertToAnsi(byte *pbNativeBuffer, int cbNativeBuffer, bool fBestFit, bool fThrowOnUnmappableChar) { - Contract.Assert(cbNativeBuffer >= (Length + 1) * Marshal.SystemMaxDBCSCharSize, "Insufficient buffer length passed to ConvertToAnsi"); + Debug.Assert(cbNativeBuffer >= (Length + 1) * Marshal.SystemMaxDBCSCharSize, "Insufficient buffer length passed to ConvertToAnsi"); const uint CP_ACP = 0; int nb; @@ -519,7 +520,7 @@ namespace System { end += 2; } - Contract.Assert(end[0] == 0 || end[1] == 0); + Debug.Assert(end[0] == 0 || end[1] == 0); if (end[0] != 0) end++; #else // !BIT64 // Based on https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord @@ -576,7 +577,7 @@ namespace System { #endif // !BIT64 FoundZero: - Contract.Assert(*end == 0); + Debug.Assert(*end == 0); int count = (int)(end - ptr); @@ -593,7 +594,7 @@ namespace System { throw new ArgumentException(Environment.GetResourceString("Arg_MustBeStringPtrNotAtom")); #endif // FEATURE_PAL - Contract.Assert(this == null, "this == null"); // this is the string constructor, we allocate it + Debug.Assert(this == null, "this == null"); // this is the string constructor, we allocate it try { int count = wcslen(ptr); @@ -620,7 +621,7 @@ namespace System { throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex")); } Contract.EndContractBlock(); - Contract.Assert(this == null, "this == null"); // this is the string constructor, we allocate it + Debug.Assert(this == null, "this == null"); // this is the string constructor, we allocate it char *pFrom = ptr + startIndex; if (pFrom < ptr) { diff --git a/src/mscorlib/src/System/StubHelpers.cs b/src/mscorlib/src/System/StubHelpers.cs index 806c19b..26a2276 100644 --- a/src/mscorlib/src/System/StubHelpers.cs +++ b/src/mscorlib/src/System/StubHelpers.cs @@ -16,6 +16,7 @@ namespace System.StubHelpers { #endif // FEATURE_COMINTEROP using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; + using System.Diagnostics; using System.Diagnostics.Contracts; [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] @@ -479,19 +480,19 @@ namespace System.StubHelpers { { static internal IntPtr ConvertToNative(string strManaged) { - Contract.Assert(false, "NYI"); + Debug.Assert(false, "NYI"); return IntPtr.Zero; } static internal unsafe string ConvertToManaged(IntPtr bstr) { - Contract.Assert(false, "NYI"); + Debug.Assert(false, "NYI"); return null; } static internal void ClearNative(IntPtr pNative) { - Contract.Assert(false, "NYI"); + Debug.Assert(false, "NYI"); } } // class WSTRBufferMarshaler @@ -587,7 +588,7 @@ namespace System.StubHelpers { internal static void ClearNative(IntPtr hstring) { - Contract.Assert(Environment.IsWinRTSupported); + Debug.Assert(Environment.IsWinRTSupported); if (hstring != IntPtr.Zero) { @@ -906,7 +907,7 @@ namespace System.StubHelpers { internal static unsafe void ClearNativeContents_Type(IntPtr pNativeHome, int cElements) { - Contract.Assert(Environment.IsWinRTSupported); + Debug.Assert(Environment.IsWinRTSupported); TypeNameNative *pNativeTypeArray = *(TypeNameNative **)pNativeHome; if (pNativeTypeArray != null) @@ -1123,7 +1124,7 @@ namespace System.StubHelpers { ptr, allocSize, IsBestFit(dwFlags), IsThrowOn(dwFlags)); - Contract.Assert(length < allocSize, "Expected a length less than the allocated size"); + Debug.Assert(length < allocSize, "Expected a length less than the allocated size"); } if (IsOut(dwFlags)) { @@ -1420,7 +1421,7 @@ namespace System.StubHelpers { internal static unsafe void ClearNative(TypeNameNative *pNativeType) { - Contract.Assert(Environment.IsWinRTSupported); + Debug.Assert(Environment.IsWinRTSupported); if (pNativeType->typeName != IntPtr.Zero) { @@ -1463,7 +1464,7 @@ namespace System.StubHelpers { // S_OK should be marshaled as null. WinRT API's should not return S_FALSE by convention. // We've chosen to treat S_FALSE as success and return null. - Contract.Assert(e != null || hr == 0 || hr == 1, "Unexpected HRESULT - it is a success HRESULT (without the high bit set) other than S_OK & S_FALSE."); + Debug.Assert(e != null || hr == 0 || hr == 1, "Unexpected HRESULT - it is a success HRESULT (without the high bit set) other than S_OK & S_FALSE."); return e; } } // class HResultExceptionMarshaler diff --git a/src/mscorlib/src/System/Text/ASCIIEncoding.cs b/src/mscorlib/src/System/Text/ASCIIEncoding.cs index ac85801..fc7589f 100644 --- a/src/mscorlib/src/System/Text/ASCIIEncoding.cs +++ b/src/mscorlib/src/System/Text/ASCIIEncoding.cs @@ -7,6 +7,7 @@ namespace System.Text using System; using System.Runtime.Serialization; using System.Security.Permissions; + using System.Diagnostics; using System.Diagnostics.Contracts; // ASCIIEncoding @@ -149,11 +150,11 @@ namespace System.Text internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(charCount >= 0, "[ASCIIEncoding.GetByteCount]count is negative"); - Contract.Assert(chars != null, "[ASCIIEncoding.GetByteCount]chars is null"); + Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetByteCount]count is negative"); + Debug.Assert(chars != null, "[ASCIIEncoding.GetByteCount]chars is null"); // Assert because we shouldn't be able to have a null encoder. - Contract.Assert(encoderFallback != null, "[ASCIIEncoding.GetByteCount]Attempting to use null fallback encoder"); + Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetByteCount]Attempting to use null fallback encoder"); char charLeftOver = (char)0; EncoderReplacementFallback fallback = null; @@ -167,7 +168,7 @@ namespace System.Text if (encoder != null) { charLeftOver = encoder.charLeftOver; - Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), + Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; @@ -186,7 +187,7 @@ namespace System.Text } // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert - Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || + Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetByteCount]Expected empty fallback buffer"); // if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0) @@ -223,8 +224,8 @@ namespace System.Text // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { - Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate"); - Contract.Assert(encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder"); + Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate"); + Debug.Assert(encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder"); // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback @@ -274,7 +275,7 @@ namespace System.Text byteCount++; } - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetByteCount]Expected Empty fallback buffer"); return byteCount; @@ -284,13 +285,13 @@ namespace System.Text byte* bytes, int byteCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(bytes != null, "[ASCIIEncoding.GetBytes]bytes is null"); - Contract.Assert(byteCount >= 0, "[ASCIIEncoding.GetBytes]byteCount is negative"); - Contract.Assert(chars != null, "[ASCIIEncoding.GetBytes]chars is null"); - Contract.Assert(charCount >= 0, "[ASCIIEncoding.GetBytes]charCount is negative"); + Debug.Assert(bytes != null, "[ASCIIEncoding.GetBytes]bytes is null"); + Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetBytes]byteCount is negative"); + Debug.Assert(chars != null, "[ASCIIEncoding.GetBytes]chars is null"); + Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. - Contract.Assert(encoderFallback != null, "[ASCIIEncoding.GetBytes]Attempting to use null encoder fallback"); + Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetBytes]Attempting to use null encoder fallback"); // Get any left over characters char charLeftOver = (char)0; @@ -322,11 +323,11 @@ namespace System.Text fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true); } - Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), + Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetBytes]leftover character should be high surrogate"); // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert - Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || + Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetBytes]Expected empty fallback buffer"); // if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer && @@ -405,7 +406,7 @@ namespace System.Text if (charLeftOver > 0) { // Initialize the buffer - Contract.Assert(encoder != null, + Debug.Assert(encoder != null, "[ASCIIEncoding.GetBytes]Expected non null encoder if we have surrogate left over"); fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true); @@ -459,7 +460,7 @@ namespace System.Text // didn't use this char, we'll throw or use buffer if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false) { - Contract.Assert(chars > charStart || bytes == byteStart, + Debug.Assert(chars > charStart || bytes == byteStart, "[ASCIIEncoding.GetBytes]Expected chars to have advanced already."); chars--; // don't use last char } @@ -488,7 +489,7 @@ namespace System.Text encoder.m_charsUsed = (int)(chars - charStart); } - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 || + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 || (encoder != null && !encoder.m_throwOnOverflow ), "[ASCIIEncoding.GetBytes]Expected Empty fallback buffer at end"); @@ -499,8 +500,8 @@ namespace System.Text internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder) { // Just assert, we're called internally so these should be safe, checked already - Contract.Assert(bytes != null, "[ASCIIEncoding.GetCharCount]bytes is null"); - Contract.Assert(count >= 0, "[ASCIIEncoding.GetCharCount]byteCount is negative"); + Debug.Assert(bytes != null, "[ASCIIEncoding.GetCharCount]bytes is null"); + Debug.Assert(count >= 0, "[ASCIIEncoding.GetCharCount]byteCount is negative"); // ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using DecoderReplacementFallback fallback = null; @@ -510,7 +511,7 @@ namespace System.Text else { fallback = decoder.Fallback as DecoderReplacementFallback; - Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || + Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetCharCount]Expected empty fallback buffer"); } @@ -561,7 +562,7 @@ namespace System.Text } // Fallback buffer must be empty - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetCharCount]Expected Empty fallback buffer"); // Converted sequence is same length as input @@ -572,10 +573,10 @@ namespace System.Text char* chars, int charCount, DecoderNLS decoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(bytes != null, "[ASCIIEncoding.GetChars]bytes is null"); - Contract.Assert(byteCount >= 0, "[ASCIIEncoding.GetChars]byteCount is negative"); - Contract.Assert(chars != null, "[ASCIIEncoding.GetChars]chars is null"); - Contract.Assert(charCount >= 0, "[ASCIIEncoding.GetChars]charCount is negative"); + Debug.Assert(bytes != null, "[ASCIIEncoding.GetChars]bytes is null"); + Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetChars]byteCount is negative"); + Debug.Assert(chars != null, "[ASCIIEncoding.GetChars]chars is null"); + Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetChars]charCount is negative"); // Do it fast way if using ? replacement fallback byte* byteEnd = bytes + byteCount; @@ -592,7 +593,7 @@ namespace System.Text else { fallback = decoder.Fallback as DecoderReplacementFallback; - Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || + Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetChars]Expected empty fallback buffer"); } @@ -660,7 +661,7 @@ namespace System.Text if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars)) { // May or may not throw, but we didn't get this byte - Contract.Assert(bytes > byteStart || chars == charStart, + Debug.Assert(bytes > byteStart || chars == charStart, "[ASCIIEncoding.GetChars]Expected bytes to have advanced already (fallback case)"); bytes--; // unused byte fallbackBuffer.InternalReset(); // Didn't fall this back @@ -673,7 +674,7 @@ namespace System.Text // Make sure we have buffer space if (chars >= charEnd) { - Contract.Assert(bytes > byteStart || chars == charStart, + Debug.Assert(bytes > byteStart || chars == charStart, "[ASCIIEncoding.GetChars]Expected bytes to have advanced already (normal case)"); bytes--; // unused byte ThrowCharsOverflow(decoder, chars == charStart); // throw? @@ -690,7 +691,7 @@ namespace System.Text decoder.m_bytesUsed = (int)(bytes - byteStart); // Expect Empty fallback buffer for GetChars - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetChars]Expected Empty fallback buffer"); return (int)(chars - charStart); diff --git a/src/mscorlib/src/System/Text/BaseCodePageEncoding.cs b/src/mscorlib/src/System/Text/BaseCodePageEncoding.cs index f80f8e6..0a42237 100644 --- a/src/mscorlib/src/System/Text/BaseCodePageEncoding.cs +++ b/src/mscorlib/src/System/Text/BaseCodePageEncoding.cs @@ -6,6 +6,7 @@ namespace System.Text { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.InteropServices; @@ -175,7 +176,7 @@ namespace System.Text { // Make sure to get the base stuff too This throws if info is null SerializeEncoding(info, context); - Contract.Assert(info!=null, "[BaseCodePageEncoding.GetObjectData] Expected null info to throw"); + Debug.Assert(info!=null, "[BaseCodePageEncoding.GetObjectData] Expected null info to throw"); // Just need Everett maxCharSize (BaseCodePageEncoding) or m_maxByteSize (MLangBaseCodePageEncoding) info.AddValue(m_bUseMlangTypeForSerialization ? "m_maxByteSize" : "maxCharSize", @@ -238,7 +239,7 @@ namespace System.Text if (pCodePage == null) return 0; - Contract.Assert(pCodePage->ByteCount == 1 || pCodePage->ByteCount == 2, + Debug.Assert(pCodePage->ByteCount == 1 || pCodePage->ByteCount == 2, "[BaseCodePageEncoding] Code page (" + codePage + ") has invalid byte size (" + pCodePage->ByteCount + ") in table"); // Return what it says for byte count return pCodePage->ByteCount; @@ -257,7 +258,7 @@ namespace System.Text // This gets shared memory for our map. If its can't, it gives us clean memory. Byte *pMemorySection = EncodingTable.nativeCreateOpenFileMapping(strName, iSize, out mappedFileHandle); - Contract.Assert(pMemorySection != null, + Debug.Assert(pMemorySection != null, "[BaseCodePageEncoding.GetSharedMemory] Expected non-null memory section to be opened"); // If that failed, we have to die. @@ -295,7 +296,7 @@ namespace System.Text // Read in our best fit table if necessary if (arrayUnicodeBestFit == null) ReadBestFitTable(); - Contract.Assert(arrayUnicodeBestFit != null, + Debug.Assert(arrayUnicodeBestFit != null, "[BaseCodePageEncoding.GetBestFitUnicodeToBytesData]Expected non-null arrayUnicodeBestFit"); // Normally we don't have any best fit data. @@ -307,7 +308,7 @@ namespace System.Text // Read in our best fit table if necessary if (arrayBytesBestFit == null) ReadBestFitTable(); - Contract.Assert(arrayBytesBestFit != null, + Debug.Assert(arrayBytesBestFit != null, "[BaseCodePageEncoding.GetBestFitBytesToUnicodeData]Expected non-null arrayBytesBestFit"); // Normally we don't have any best fit data. diff --git a/src/mscorlib/src/System/Text/CodePageEncoding.cs b/src/mscorlib/src/System/Text/CodePageEncoding.cs index 5e76946..7805c65 100644 --- a/src/mscorlib/src/System/Text/CodePageEncoding.cs +++ b/src/mscorlib/src/System/Text/CodePageEncoding.cs @@ -11,6 +11,7 @@ namespace System.Text using System; using System.Runtime.Serialization; using System.Security.Permissions; + using System.Diagnostics; using System.Diagnostics.Contracts; /*=================================CodePageEncoding================================== @@ -95,7 +96,7 @@ namespace System.Text void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // We cannot ever call this. - Contract.Assert(false, "Didn't expect to make it to CodePageEncoding ISerializable.GetObjectData"); + Debug.Assert(false, "Didn't expect to make it to CodePageEncoding ISerializable.GetObjectData"); throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException")); } @@ -127,7 +128,7 @@ namespace System.Text void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // We cannot ever call this. - Contract.Assert(false, "Didn't expect to make it to CodePageEncoding.Decoder.GetObjectData"); + Debug.Assert(false, "Didn't expect to make it to CodePageEncoding.Decoder.GetObjectData"); throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException")); } } diff --git a/src/mscorlib/src/System/Text/DBCSCodePageEncoding.cs b/src/mscorlib/src/System/Text/DBCSCodePageEncoding.cs index 5d2f68f..28b85d5 100644 --- a/src/mscorlib/src/System/Text/DBCSCodePageEncoding.cs +++ b/src/mscorlib/src/System/Text/DBCSCodePageEncoding.cs @@ -6,6 +6,7 @@ namespace System.Text { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Text; using System.Threading; @@ -55,7 +56,7 @@ namespace System.Text internal DBCSCodePageEncoding(SerializationInfo info, StreamingContext context) : base(0) { // Actually this can't ever get called, CodePageEncoding is our proxy - Contract.Assert(false, "Didn't expect to make it to DBCSCodePageEncoding serialization constructor"); + Debug.Assert(false, "Didn't expect to make it to DBCSCodePageEncoding serialization constructor"); throw new ArgumentNullException("this"); } @@ -90,7 +91,7 @@ namespace System.Text protected override unsafe void LoadManagedCodePage() { // Should be loading OUR code page - Contract.Assert(pCodePage->CodePage == this.dataTableCodePage, + Debug.Assert(pCodePage->CodePage == this.dataTableCodePage, "[DBCSCodePageEncoding.LoadManagedCodePage]Expected to load data table code page"); // Make sure we're really a 1 byte code page @@ -113,7 +114,7 @@ namespace System.Text byteCountUnknown++; // We use fallback encoder, which uses ?, which so far all of our tables do as well - Contract.Assert(bytesUnknown == 0x3f, + Debug.Assert(bytesUnknown == 0x3f, "[DBCSCodePageEncoding.LoadManagedCodePage]Expected 0x3f (?) as unknown byte character"); // Get our mapped section (bytes to allocate = 2 bytes per 65536 Unicode chars + 2 bytes per 65536 DBCS chars) @@ -127,7 +128,7 @@ namespace System.Text // If its cached (& filled in) we don't have to do anything else if (*mapCodePageCached != 0) { - Contract.Assert(((*mapCodePageCached == this.dataTableCodePage && this.bFlagDataTable) || + Debug.Assert(((*mapCodePageCached == this.dataTableCodePage && this.bFlagDataTable) || (*mapCodePageCached == this.CodePage && !this.bFlagDataTable)), "[DBCSCodePageEncoding.LoadManagedCodePage]Expected mapped section cached page flag to be set to data table or regular code page."); @@ -181,7 +182,7 @@ namespace System.Text else if (input == LEAD_BYTE_CHAR) // 0xfffe { // Lead byte mark - Contract.Assert(bytePosition < 0x100, "[DBCSCodePageEncoding.LoadManagedCodePage]expected lead byte to be < 0x100"); + Debug.Assert(bytePosition < 0x100, "[DBCSCodePageEncoding.LoadManagedCodePage]expected lead byte to be < 0x100"); useBytes = bytePosition; // input stays 0xFFFE } @@ -398,7 +399,7 @@ namespace System.Text // If they're out of order we need to sort them. if (bOutOfOrder) { - Contract.Assert((arrayTemp.Length / 2) < 20, + Debug.Assert((arrayTemp.Length / 2) < 20, "[DBCSCodePageEncoding.ReadBestFitTable]Expected small best fit table < 20 for code page " + CodePage + ", not " + arrayTemp.Length / 2); for (int i = 0; i < arrayTemp.Length - 2; i+=2) @@ -506,7 +507,7 @@ namespace System.Text // We can't do this assert for CP 51932 & 50220 because they aren't // calling CleanUpBytes() for best fit. All the string stuff here // also makes this assert slow. - // Contract.Assert(arrayTemp[iBestFitCount-1] != (char)0xFFFD, String.Format( + // Debug.Assert(arrayTemp[iBestFitCount-1] != (char)0xFFFD, String.Format( // "[DBCSCodePageEncoding.ReadBestFitTable] No valid Unicode value {0:X4} for round trip bytes {1:X4}, encoding {2}", // (int)mapBytesToUnicode[input], (int)input, CodePage)); } @@ -528,11 +529,11 @@ namespace System.Text internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(count >= 0, "[DBCSCodePageEncoding.GetByteCount]count is negative"); - Contract.Assert(chars != null, "[DBCSCodePageEncoding.GetByteCount]chars is null"); + Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetByteCount]count is negative"); + Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetByteCount]chars is null"); // Assert because we shouldn't be able to have a null encoder. - Contract.Assert(encoderFallback != null, "[DBCSCodePageEncoding.GetByteCount]Attempting to use null fallback"); + Debug.Assert(encoderFallback != null, "[DBCSCodePageEncoding.GetByteCount]Attempting to use null fallback"); CheckMemorySection(); @@ -558,8 +559,8 @@ namespace System.Text // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { - Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[DBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate"); - Contract.Assert(encoder != null, + Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[DBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate"); + Debug.Assert(encoder != null, "[DBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver"); // Since left over char was a surrogate, it'll have to be fallen back. @@ -619,13 +620,13 @@ namespace System.Text byte* bytes, int byteCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(bytes != null, "[DBCSCodePageEncoding.GetBytes]bytes is null"); - Contract.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetBytes]byteCount is negative"); - Contract.Assert(chars != null, "[DBCSCodePageEncoding.GetBytes]chars is null"); - Contract.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetBytes]charCount is negative"); + Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetBytes]bytes is null"); + Debug.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetBytes]byteCount is negative"); + Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetBytes]chars is null"); + Debug.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. - Contract.Assert(encoderFallback != null, "[DBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback"); + Debug.Assert(encoderFallback != null, "[DBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback"); CheckMemorySection(); @@ -643,7 +644,7 @@ namespace System.Text if (encoder != null) { charLeftOver = encoder.charLeftOver; - Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), + Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[DBCSCodePageEncoding.GetBytes]leftover character should be high surrogate"); // Go ahead and get the fallback buffer (need leftover fallback if converting) @@ -658,7 +659,7 @@ namespace System.Text // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { - Contract.Assert(encoder != null, + Debug.Assert(encoder != null, "[DBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver"); // Since left over char was a surrogate, it'll have to be fallen back. @@ -691,7 +692,7 @@ namespace System.Text if (fallbackBuffer == null) { // Initialize the buffer - Contract.Assert(encoder == null, + Debug.Assert(encoder == null, "[DBCSCodePageEncoding.GetBytes]Expected delayed create fallback only if no encoder."); fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, true); @@ -713,7 +714,7 @@ namespace System.Text // didn't use this char, we'll throw or use buffer if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false) { - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (double byte case)"); chars--; // don't use last char } @@ -732,7 +733,7 @@ namespace System.Text // didn't use this char, we'll throw or use buffer if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false) { - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (single byte case)"); chars--; // don't use last char } @@ -760,7 +761,7 @@ namespace System.Text // If we're not converting we must not have a fallback buffer // (We don't really have a way to clear none-encoder using fallbacks however) -// Contract.Assert((encoder == null || encoder.m_throwOnOverflow) && +// Debug.Assert((encoder == null || encoder.m_throwOnOverflow) && // (fallbackBuffer == null || fallbackBuffer.Remaining == 0), // "[DBCSEncoding.GetBytes]Expected empty fallback buffer at end if not converting"); @@ -771,8 +772,8 @@ namespace System.Text internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { // Just assert, we're called internally so these should be safe, checked already - Contract.Assert(bytes != null, "[DBCSCodePageEncoding.GetCharCount]bytes is null"); - Contract.Assert(count >= 0, "[DBCSCodePageEncoding.GetCharCount]byteCount is negative"); + Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetCharCount]bytes is null"); + Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetCharCount]byteCount is negative"); CheckMemorySection(); @@ -788,7 +789,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for count) - Contract.Assert(decoder == null || + Debug.Assert(decoder == null || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at start"); @@ -806,7 +807,7 @@ namespace System.Text } - Contract.Assert(fallbackBuffer == null, + Debug.Assert(fallbackBuffer == null, "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer"); fallbackBuffer = decoder.FallbackBuffer; fallbackBuffer.InternalInitialize(bytes, null); @@ -830,7 +831,7 @@ namespace System.Text charCount--; // We'll need a fallback - Contract.Assert(fallbackBuffer == null, + Debug.Assert(fallbackBuffer == null, "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer for unknown pair"); fallbackBuffer = decoder.FallbackBuffer; fallbackBuffer.InternalInitialize(byteEnd - count, null); @@ -905,7 +906,7 @@ namespace System.Text } // Shouldn't have anything in fallback buffer for GetChars - Contract.Assert(decoder == null || !decoder.m_throwOnOverflow || + Debug.Assert(decoder == null || !decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at end"); @@ -917,10 +918,10 @@ namespace System.Text char* chars, int charCount, DecoderNLS baseDecoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(bytes != null, "[DBCSCodePageEncoding.GetChars]bytes is null"); - Contract.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetChars]byteCount is negative"); - Contract.Assert(chars != null, "[DBCSCodePageEncoding.GetChars]chars is null"); - Contract.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetChars]charCount is negative"); + Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetChars]bytes is null"); + Debug.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetChars]byteCount is negative"); + Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetChars]chars is null"); + Debug.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetChars]charCount is negative"); CheckMemorySection(); @@ -938,7 +939,7 @@ namespace System.Text DecoderFallbackBuffer fallbackBuffer = null; // Shouldn't have anything in fallback buffer for GetChars - Contract.Assert(decoder == null || !decoder.m_throwOnOverflow || + Debug.Assert(decoder == null || !decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start"); @@ -957,7 +958,7 @@ namespace System.Text // Well, we're flushing, so use '?' or fallback // fallback leftover byte - Contract.Assert(fallbackBuffer == null, + Debug.Assert(fallbackBuffer == null, "[DBCSCodePageEncoding.GetChars]Expected empty fallback"); fallbackBuffer = decoder.FallbackBuffer; fallbackBuffer.InternalInitialize(bytes, charEnd); @@ -982,7 +983,7 @@ namespace System.Text char cDecoder = mapBytesToUnicode[iBytes]; if (cDecoder == UNKNOWN_CHAR_FLAG && iBytes != 0) { - Contract.Assert(fallbackBuffer == null, + Debug.Assert(fallbackBuffer == null, "[DBCSCodePageEncoding.GetChars]Expected empty fallback for two bytes"); fallbackBuffer = decoder.FallbackBuffer; fallbackBuffer.InternalInitialize(byteEnd - byteCount, charEnd); @@ -1060,7 +1061,7 @@ namespace System.Text if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars)) { // May or may not throw, but we didn't get these byte(s) - Contract.Assert(bytes >= byteStart + byteBuffer.Length, + Debug.Assert(bytes >= byteStart + byteBuffer.Length, "[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for fallback"); bytes-=byteBuffer.Length; // didn't use these byte(s) fallbackBuffer.InternalReset(); // Didn't fall this back @@ -1074,12 +1075,12 @@ namespace System.Text if (chars >= charEnd) { // May or may not throw, but we didn't get these byte(s) - Contract.Assert(bytes > byteStart, + Debug.Assert(bytes > byteStart, "[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for lead byte"); bytes--; // unused byte if (iBytes >= 0x100) { - Contract.Assert(bytes > byteStart, + Debug.Assert(bytes > byteStart, "[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for trail byte"); bytes--; // 2nd unused byte } @@ -1105,7 +1106,7 @@ namespace System.Text } // Shouldn't have anything in fallback buffer for GetChars - Contract.Assert(decoder == null || !decoder.m_throwOnOverflow || + Debug.Assert(decoder == null || !decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at end"); diff --git a/src/mscorlib/src/System/Text/Decoder.cs b/src/mscorlib/src/System/Text/Decoder.cs index 3a6e877..0ebbacd 100644 --- a/src/mscorlib/src/System/Text/Decoder.cs +++ b/src/mscorlib/src/System/Text/Decoder.cs @@ -7,6 +7,7 @@ namespace System.Text using System.Runtime.Serialization; using System.Text; using System; + using System.Diagnostics; using System.Diagnostics.Contracts; // A Decoder is used to decode a sequence of blocks of bytes into a // sequence of blocks of characters. Following instantiation of a decoder, @@ -216,7 +217,7 @@ namespace System.Text // Do the work int result = GetChars(arrByte, 0, byteCount, arrChar, 0, flush); - Contract.Assert(result <= charCount, "Returned more chars than we have space for"); + Debug.Assert(result <= charCount, "Returned more chars than we have space for"); // Copy the char array // WARNING: We MUST make sure that we don't copy too many chars. We can't diff --git a/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs b/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs index 0537379..6389b4b 100644 --- a/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs +++ b/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs @@ -10,6 +10,7 @@ namespace System.Text using System; using System.Text; using System.Threading; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -101,7 +102,7 @@ namespace System.Text public override bool Fallback(byte[] bytesUnknown, int index) { // We expect no previous fallback in our buffer - Contract.Assert(iCount < 1, "[DecoderReplacementFallbackBuffer.Fallback] Calling fallback without a previously empty buffer"); + Debug.Assert(iCount < 1, "[DecoderReplacementFallbackBuffer.Fallback] Calling fallback without a previously empty buffer"); cBestFit = TryBestFit(bytesUnknown); if (cBestFit == '\0') @@ -210,7 +211,7 @@ namespace System.Text if (cTest == cCheck) { // We found it - Contract.Assert(index + 1 < oFallback.arrayBestFit.Length, + Debug.Assert(index + 1 < oFallback.arrayBestFit.Length, "[InternalDecoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array"); return oFallback.arrayBestFit[index + 1]; } @@ -231,7 +232,7 @@ namespace System.Text if (oFallback.arrayBestFit[index] == cCheck) { // We found it - Contract.Assert(index + 1 < oFallback.arrayBestFit.Length, + Debug.Assert(index + 1 < oFallback.arrayBestFit.Length, "[InternalDecoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array"); return oFallback.arrayBestFit[index + 1]; } diff --git a/src/mscorlib/src/System/Text/DecoderFallback.cs b/src/mscorlib/src/System/Text/DecoderFallback.cs index cd7fbbc..42483a7 100644 --- a/src/mscorlib/src/System/Text/DecoderFallback.cs +++ b/src/mscorlib/src/System/Text/DecoderFallback.cs @@ -7,6 +7,7 @@ using System; using System.Security; using System.Threading; using System.Globalization; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Text @@ -148,7 +149,7 @@ namespace System.Text // for (int i = 0; i < count; i++) // bytesUnknown[i] = *(bytes++); - Contract.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize"); + Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize"); // See if there's a fallback character and we have an output buffer then copy our string. if (this.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length))) @@ -208,7 +209,7 @@ namespace System.Text // for (int i = 0; i < count; i++) // bytesUnknown[i] = *(bytes++); - Contract.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize"); + Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize"); // See if there's a fallback character and we have an output buffer then copy our string. if (this.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length))) diff --git a/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs b/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs index c19479d..77c8560 100644 --- a/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs +++ b/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs @@ -5,6 +5,7 @@ namespace System.Text { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -156,7 +157,7 @@ namespace System.Text } // Now make sure its in the expected range - Contract.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0, + Debug.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0, "Index exceeds buffer range"); return strDefault[fallbackIndex]; diff --git a/src/mscorlib/src/System/Text/Encoder.cs b/src/mscorlib/src/System/Text/Encoder.cs index 82a22f4..b9d4581 100644 --- a/src/mscorlib/src/System/Text/Encoder.cs +++ b/src/mscorlib/src/System/Text/Encoder.cs @@ -7,6 +7,7 @@ namespace System.Text using System.Runtime.Serialization; using System.Text; using System; + using System.Diagnostics; using System.Diagnostics.Contracts; // An Encoder is used to encode a sequence of blocks of characters into // a sequence of blocks of bytes. Following instantiation of an encoder, @@ -209,7 +210,7 @@ namespace System.Text // Do the work int result = GetBytes(arrChar, 0, charCount, arrByte, 0, flush); - Contract.Assert(result <= byteCount, "Returned more bytes than we have space for"); + Debug.Assert(result <= byteCount, "Returned more bytes than we have space for"); // Copy the byte array // WARNING: We MUST make sure that we don't copy too many bytes. We can't diff --git a/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs b/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs index f22d318..c5f82a2 100644 --- a/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs +++ b/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs @@ -11,6 +11,7 @@ namespace System.Text using System.Globalization; using System.Text; using System.Threading; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -103,7 +104,7 @@ namespace System.Text // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. // Shouldn't be able to get here for all of our code pages, table would have to be messed up. - Contract.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); + Debug.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); iCount = iSize = 1; cBestFit = TryBestFit(charUnknown); @@ -130,7 +131,7 @@ namespace System.Text // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. 0 is processing last character, < 0 is not falling back // Shouldn't be able to get here, table would have to be messed up. - Contract.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); + Debug.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); // Go ahead and get our fallback, surrogates don't have best fit cBestFit = '?'; @@ -211,7 +212,7 @@ namespace System.Text if (cTest == cUnknown) { // We found it - Contract.Assert(index + 1 < oFallback.arrayBestFit.Length, + Debug.Assert(index + 1 < oFallback.arrayBestFit.Length, "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array"); return oFallback.arrayBestFit[index + 1]; } @@ -232,7 +233,7 @@ namespace System.Text if (oFallback.arrayBestFit[index] == cUnknown) { // We found it - Contract.Assert(index + 1 < oFallback.arrayBestFit.Length, + Debug.Assert(index + 1 < oFallback.arrayBestFit.Length, "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array"); return oFallback.arrayBestFit[index + 1]; } diff --git a/src/mscorlib/src/System/Text/EncoderFallback.cs b/src/mscorlib/src/System/Text/EncoderFallback.cs index 8b2510d..db2bf93 100644 --- a/src/mscorlib/src/System/Text/EncoderFallback.cs +++ b/src/mscorlib/src/System/Text/EncoderFallback.cs @@ -5,6 +5,7 @@ using System; using System.Security; using System.Threading; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Text @@ -162,7 +163,7 @@ namespace System.Text internal unsafe virtual bool InternalFallback(char ch, ref char* chars) { // Shouldn't have null charStart - Contract.Assert(charStart != null, + Debug.Assert(charStart != null, "[EncoderFallback.InternalFallbackBuffer]Fallback buffer is not initialized"); // Get our index, remember chars was preincremented to point at next char, so have to -1 diff --git a/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs b/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs index 84dbd90..604cddf 100644 --- a/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs +++ b/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs @@ -6,6 +6,7 @@ namespace System.Text { using System; using System.Runtime; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -189,7 +190,7 @@ namespace System.Text } // Now make sure its in the expected range - Contract.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0, + Debug.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0, "Index exceeds buffer range"); return strDefault[fallbackIndex]; diff --git a/src/mscorlib/src/System/Text/Encoding.cs b/src/mscorlib/src/System/Text/Encoding.cs index 13073f8..b2284d7 100644 --- a/src/mscorlib/src/System/Text/Encoding.cs +++ b/src/mscorlib/src/System/Text/Encoding.cs @@ -15,6 +15,7 @@ namespace System.Text using System.Security.Permissions; using System.Threading; using System.Text; + using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using Win32Native = Microsoft.Win32.Win32Native; @@ -472,7 +473,7 @@ namespace System.Text result = GetEncodingCodePage(codepage) ?? GetEncodingRare(codepage); } - Contract.Assert(result != null, "result != null"); + Debug.Assert(result != null, "result != null"); encodings.Add(key, result); } @@ -512,7 +513,7 @@ namespace System.Text #if FEATURE_CODEPAGES_FILE private static Encoding GetEncodingRare(int codepage) { - Contract.Assert(codepage != 0 && codepage != 1200 && codepage != 1201 && codepage != 65001, + Debug.Assert(codepage != 0 && codepage != 1200 && codepage != 1201 && codepage != 65001, "[Encoding.GetEncodingRare]This code page (" + codepage + ") isn't supported by GetEncodingRare!"); Encoding result; switch (codepage) @@ -973,7 +974,7 @@ namespace System.Text int byteCount = GetByteCount(s); byte[] bytes = new byte[byteCount]; int bytesReceived = GetBytes(s, 0, s.Length, bytes, 0); - Contract.Assert(byteCount == bytesReceived); + Debug.Assert(byteCount == bytesReceived); return bytes; } @@ -1039,7 +1040,7 @@ namespace System.Text // Do the work int result = GetBytes(arrChar, 0, charCount, arrByte, 0); - Contract.Assert(result <= byteCount, "[Encoding.GetBytes]Returned more bytes than we have space for"); + Debug.Assert(result <= byteCount, "[Encoding.GetBytes]Returned more bytes than we have space for"); // Copy the byte array // WARNING: We MUST make sure that we don't copy too many bytes. We can't @@ -1195,7 +1196,7 @@ namespace System.Text // Do the work int result = GetChars(arrByte, 0, byteCount, arrChar, 0); - Contract.Assert(result <= charCount, "[Encoding.GetChars]Returned more chars than we have space for"); + Debug.Assert(result <= charCount, "[Encoding.GetChars]Returned more chars than we have space for"); // Copy the char array // WARNING: We MUST make sure that we don't copy too many chars. We can't @@ -1786,7 +1787,7 @@ namespace System.Text // If we're getting chars or getting char count we don't expect to have // to remember fallbacks between calls (so it should be empty) - Contract.Assert(fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer.Remaining == 0, "[Encoding.EncodingCharBuffer.EncodingCharBuffer]Expected empty fallback buffer for getchars/charcount"); fallbackBuffer.InternalInitialize(bytes, charEnd); } @@ -1851,7 +1852,7 @@ namespace System.Text // but we'll double check just to make sure. internal unsafe byte GetNextByte() { - Contract.Assert(bytes < byteEnd, "[EncodingCharBuffer.GetNextByte]Expected more date"); + Debug.Assert(bytes < byteEnd, "[EncodingCharBuffer.GetNextByte]Expected more date"); if (bytes >= byteEnd) return 0; return *(bytes++); @@ -1968,7 +1969,7 @@ namespace System.Text internal unsafe bool AddByte(byte b, int moreBytesExpected) { - Contract.Assert(moreBytesExpected >= 0, "[EncodingByteBuffer.AddByte]expected non-negative moreBytesExpected"); + Debug.Assert(moreBytesExpected >= 0, "[EncodingByteBuffer.AddByte]expected non-negative moreBytesExpected"); if (bytes != null) { if (bytes >= byteEnd - moreBytesExpected) @@ -2025,7 +2026,7 @@ namespace System.Text fallbackBuffer.MovePrevious(); // don't use last fallback else { - Contract.Assert(chars > charStart || + Debug.Assert(chars > charStart || ((bThrow == true) && (bytes == byteStart)), "[EncodingByteBuffer.MovePrevious]expected previous data or throw"); if (chars > charStart) diff --git a/src/mscorlib/src/System/Text/EncodingForwarder.cs b/src/mscorlib/src/System/Text/EncodingForwarder.cs index 6a0db2b..9a8dd26 100644 --- a/src/mscorlib/src/System/Text/EncodingForwarder.cs +++ b/src/mscorlib/src/System/Text/EncodingForwarder.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; @@ -35,7 +36,7 @@ namespace System.Text { // Validate parameters - Contract.Assert(encoding != null); // this parameter should only be affected internally, so just do a debug check here + Debug.Assert(encoding != null); // this parameter should only be affected internally, so just do a debug check here if (chars == null) { throw new ArgumentNullException(nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); @@ -61,7 +62,7 @@ namespace System.Text public unsafe static int GetByteCount(Encoding encoding, string s) { - Contract.Assert(encoding != null); + Debug.Assert(encoding != null); if (s == null) { string paramName = encoding is ASCIIEncoding ? "chars" : nameof(s); // ASCIIEncoding calls the string chars @@ -84,7 +85,7 @@ namespace System.Text public unsafe static int GetByteCount(Encoding encoding, char* chars, int count) { - Contract.Assert(encoding != null); + Debug.Assert(encoding != null); if (chars == null) { throw new ArgumentNullException(nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); @@ -101,7 +102,7 @@ namespace System.Text public unsafe static int GetBytes(Encoding encoding, string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { - Contract.Assert(encoding != null); + Debug.Assert(encoding != null); if (s == null || bytes == null) { string stringName = encoding is ASCIIEncoding ? "chars" : nameof(s); // ASCIIEncoding calls the first parameter chars @@ -137,7 +138,7 @@ namespace System.Text public unsafe static int GetBytes(Encoding encoding, char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { - Contract.Assert(encoding != null); + Debug.Assert(encoding != null); if (chars == null || bytes == null) { throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); @@ -177,7 +178,7 @@ namespace System.Text public unsafe static int GetBytes(Encoding encoding, char* chars, int charCount, byte* bytes, int byteCount) { - Contract.Assert(encoding != null); + Debug.Assert(encoding != null); if (bytes == null || chars == null) { throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); @@ -193,7 +194,7 @@ namespace System.Text public unsafe static int GetCharCount(Encoding encoding, byte[] bytes, int index, int count) { - Contract.Assert(encoding != null); + Debug.Assert(encoding != null); if (bytes == null) { throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); @@ -219,7 +220,7 @@ namespace System.Text public unsafe static int GetCharCount(Encoding encoding, byte* bytes, int count) { - Contract.Assert(encoding != null); + Debug.Assert(encoding != null); if (bytes == null) { throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); @@ -235,7 +236,7 @@ namespace System.Text public unsafe static int GetChars(Encoding encoding, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { - Contract.Assert(encoding != null); + Debug.Assert(encoding != null); if (bytes == null || chars == null) { throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); @@ -273,7 +274,7 @@ namespace System.Text public unsafe static int GetChars(Encoding encoding, byte* bytes, int byteCount, char* chars, int charCount) { - Contract.Assert(encoding != null); + Debug.Assert(encoding != null); if (bytes == null || chars == null) { throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); @@ -289,7 +290,7 @@ namespace System.Text public unsafe static string GetString(Encoding encoding, byte[] bytes, int index, int count) { - Contract.Assert(encoding != null); + Debug.Assert(encoding != null); if (bytes == null) { throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); diff --git a/src/mscorlib/src/System/Text/GB18030Encoding.cs b/src/mscorlib/src/System/Text/GB18030Encoding.cs index da5ea84..8ed52a6 100644 --- a/src/mscorlib/src/System/Text/GB18030Encoding.cs +++ b/src/mscorlib/src/System/Text/GB18030Encoding.cs @@ -85,6 +85,7 @@ namespace System.Text { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Text; using System.Runtime.InteropServices; @@ -128,7 +129,7 @@ namespace System.Text { // Set up our base, also throws if info was empty DeserializeEncoding(info, context); - Contract.Assert(info!=null, "[GB18030Encoding(Serialization...)] Expected null info to throw"); + Debug.Assert(info!=null, "[GB18030Encoding(Serialization...)] Expected null info to throw"); // Already build our code page, fallbacks & read only, so we're good to go! } @@ -138,7 +139,7 @@ namespace System.Text { // Make sure to get the base stuff too This throws if info is null SerializeEncoding(info, context); - Contract.Assert(info!=null, "[GB18030.GetObjectData] Expected null info to throw"); + Debug.Assert(info!=null, "[GB18030.GetObjectData] Expected null info to throw"); // Everett doesn't need more than the basics } @@ -193,7 +194,7 @@ namespace System.Text // It was GB 18030 4 byte data, next characters are 4 byte sequences. while (data > 0) { - Contract.Assert(count4Byte <= GBLast4ByteCode, + Debug.Assert(count4Byte <= GBLast4ByteCode, "[GB18030Encoding.LoadManagedCodePage] Found too many 4 byte codes in data table."); // Set the 4 byte -> Unicode value @@ -211,11 +212,11 @@ namespace System.Text } // unicodeCount should've wrapped back to 0 - Contract.Assert(unicodeCount == 0, + Debug.Assert(unicodeCount == 0, "[GB18030Encoding.LoadManagedCodePage] Expected unicodeCount to wrap around to 0 as all chars were processed"); // We should've read in GBLast4ByteCode 4 byte sequences - Contract.Assert(count4Byte == GBLast4ByteCode + 1, + Debug.Assert(count4Byte == GBLast4ByteCode + 1, "[GB18030Encoding.LoadManagedCodePage] Expected 0x99FB to be last 4 byte offset, found 0x" + count4Byte.ToString("X4", CultureInfo.InvariantCulture)); // Need to flag ourselves saying we've built this CP. @@ -251,13 +252,13 @@ namespace System.Text { // Just need to ASSERT, this is called by something else internal that checked parameters already // We'll allow null bytes as a count -// Contract.Assert(bytes != null, "[GB18030Encoding.GetBytes]bytes is null"); - Contract.Assert(byteCount >= 0, "[GB18030Encoding.GetBytes]byteCount is negative"); - Contract.Assert(chars != null, "[GB18030Encoding.GetBytes]chars is null"); - Contract.Assert(charCount >= 0, "[GB18030Encoding.GetBytes]charCount is negative"); +// Debug.Assert(bytes != null, "[GB18030Encoding.GetBytes]bytes is null"); + Debug.Assert(byteCount >= 0, "[GB18030Encoding.GetBytes]byteCount is negative"); + Debug.Assert(chars != null, "[GB18030Encoding.GetBytes]chars is null"); + Debug.Assert(charCount >= 0, "[GB18030Encoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. - Contract.Assert(encoderFallback != null, "[GB18030Encoding.GetBytes]Attempting to use null encoder fallback"); + Debug.Assert(encoderFallback != null, "[GB18030Encoding.GetBytes]Attempting to use null encoder fallback"); // Get any left over characters char charLeftOver = (char)0; @@ -280,7 +281,7 @@ namespace System.Text // Have to check for charLeftOver if (charLeftOver != 0) { - Contract.Assert(Char.IsHighSurrogate(charLeftOver), + Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[GB18030Encoding.GetBytes] leftover character should be high surrogate, not 0x" + ((int)charLeftOver).ToString("X4", CultureInfo.InvariantCulture)); // If our next char isn't a low surrogate, then we need to do fallback. @@ -310,7 +311,7 @@ namespace System.Text offset /= 0x7e; byte byte2 = (byte)((offset % 0x0a) + 0x30); offset /= 0x0a; - Contract.Assert(offset < 0x6f, + Debug.Assert(offset < 0x6f, "[GB18030Encoding.GetBytes](1) Expected offset < 0x6f, not 0x" + offset.ToString("X2", CultureInfo.InvariantCulture)); charLeftOver = (char)0; @@ -360,7 +361,7 @@ namespace System.Text iBytes /= 0x7e; byte byte2 = (byte)((iBytes % 0x0a) + 0x30); iBytes /= 0x0a; - Contract.Assert(iBytes < 0x7e, + Debug.Assert(iBytes < 0x7e, "[GB18030Encoding.GetBytes]Expected iBytes < 0x7e, not 0x" + iBytes.ToString("X2", CultureInfo.InvariantCulture)); if (!buffer.AddByte((byte)(iBytes + 0x81), byte2, byte3, byte4)) break; @@ -438,10 +439,10 @@ namespace System.Text { // Just need to ASSERT, this is called by something else internal that checked parameters already // We'll allow null chars as a count - Contract.Assert(bytes != null, "[GB18030Encoding.GetChars]bytes is null"); - Contract.Assert(byteCount >= 0, "[GB18030Encoding.GetChars]byteCount is negative"); -// Contract.Assert(chars != null, "[GB18030Encoding.GetChars]chars is null"); - Contract.Assert(charCount >= 0, "[GB18030Encoding.GetChars]charCount is negative"); + Debug.Assert(bytes != null, "[GB18030Encoding.GetChars]bytes is null"); + Debug.Assert(byteCount >= 0, "[GB18030Encoding.GetChars]byteCount is negative"); +// Debug.Assert(chars != null, "[GB18030Encoding.GetChars]chars is null"); + Debug.Assert(charCount >= 0, "[GB18030Encoding.GetChars]charCount is negative"); // Fix our decoder GB18030Decoder decoder = (GB18030Decoder)baseDecoder; diff --git a/src/mscorlib/src/System/Text/ISCIIEncoding.cs b/src/mscorlib/src/System/Text/ISCIIEncoding.cs index 42a7eb7..751b821 100644 --- a/src/mscorlib/src/System/Text/ISCIIEncoding.cs +++ b/src/mscorlib/src/System/Text/ISCIIEncoding.cs @@ -9,6 +9,7 @@ namespace System.Text { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.Serialization; @@ -72,7 +73,7 @@ namespace System.Text defaultCodePage = codePage - 57000; // Legal windows code pages are between Devanagari and Punjabi - Contract.Assert(defaultCodePage >= CodeDevanagari && defaultCodePage <= CodePunjabi, + Debug.Assert(defaultCodePage >= CodeDevanagari && defaultCodePage <= CodePunjabi, "[ISCIIEncoding] Code page (" + codePage + " isn't supported by ISCIIEncoding!"); // This shouldn't really be possible @@ -86,7 +87,7 @@ namespace System.Text { // Actually this can't ever get called, MLangCodePageEncoding is our proxy // (In Everett this was done by MLang) - Contract.Assert(false, "Didn't expect to make it to ISCIIEncoding serialization constructor"); + Debug.Assert(false, "Didn't expect to make it to ISCIIEncoding serialization constructor"); throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException")); } @@ -95,7 +96,7 @@ namespace System.Text { // Make sure to get the base stuff too This throws if info is null SerializeEncoding(info, context); - Contract.Assert(info!=null, "[ISCIIEncoding.GetObjectData] Expected null info to throw"); + Debug.Assert(info!=null, "[ISCIIEncoding.GetObjectData] Expected null info to throw"); // Just need Everett MLangCodePageEncoding maxCharSize info.AddValue("m_maxByteSize", 2); @@ -165,10 +166,10 @@ namespace System.Text byte* bytes, int byteCount, EncoderNLS baseEncoder) { // Allow null bytes for counting - Contract.Assert(chars != null, "[ISCIIEncoding.GetBytes]chars!=null"); -// Contract.Assert(bytes != null, "[ISCIIEncoding.GetBytes]bytes!=null"); - Contract.Assert(charCount >=0, "[ISCIIEncoding.GetBytes]charCount >=0"); - Contract.Assert(byteCount >=0, "[ISCIIEncoding.GetBytes]byteCount >=0"); + Debug.Assert(chars != null, "[ISCIIEncoding.GetBytes]chars!=null"); +// Debug.Assert(bytes != null, "[ISCIIEncoding.GetBytes]bytes!=null"); + Debug.Assert(charCount >=0, "[ISCIIEncoding.GetBytes]charCount >=0"); + Debug.Assert(byteCount >=0, "[ISCIIEncoding.GetBytes]byteCount >=0"); // Need the ISCII Encoder ISCIIEncoder encoder = (ISCIIEncoder) baseEncoder; @@ -265,7 +266,7 @@ namespace System.Text // See if our code page ("font" in ISCII spec) has to change // (This if doesn't add character, just changes character set) - Contract.Assert(indicScript!=0, "[ISCIIEncoding.GetBytes]expected an indic script value"); + Debug.Assert(indicScript!=0, "[ISCIIEncoding.GetBytes]expected an indic script value"); if (indicScript != currentCodePage) { // It changed, spit out the ATR @@ -276,7 +277,7 @@ namespace System.Text currentCodePage = indicScript; // We only know how to map from Unicode to pages from Devanagari to Punjabi (2 to 11) - Contract.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi, + Debug.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi, "[ISCIIEncoding.GetBytes]Code page (" + currentCodePage + " shouldn't appear in ISCII from Unicode table!"); } @@ -291,7 +292,7 @@ namespace System.Text if (indicTwoBytes != 0) { // This one needs another byte - Contract.Assert((indicTwoBytes >> 12) > 0 && (indicTwoBytes >> 12) <= 3, + Debug.Assert((indicTwoBytes >> 12) > 0 && (indicTwoBytes >> 12) <= 3, "[ISCIIEncoding.GetBytes]Expected indicTwoBytes from 1-3, not " + (indicTwoBytes >> 12)); // Already did buffer checking, but... @@ -355,10 +356,10 @@ namespace System.Text { // Just need to ASSERT, this is called by something else internal that checked parameters already // Allow null chars for counting - Contract.Assert(bytes != null, "[ISCIIEncoding.GetChars]bytes is null"); - Contract.Assert(byteCount >= 0, "[ISCIIEncoding.GetChars]byteCount is negative"); -// Contract.Assert(chars != null, "[ISCIIEncoding.GetChars]chars is null"); - Contract.Assert(charCount >= 0, "[ISCIIEncoding.GetChars]charCount is negative"); + Debug.Assert(bytes != null, "[ISCIIEncoding.GetChars]bytes is null"); + Debug.Assert(byteCount >= 0, "[ISCIIEncoding.GetChars]byteCount is negative"); +// Debug.Assert(chars != null, "[ISCIIEncoding.GetChars]chars is null"); + Debug.Assert(charCount >= 0, "[ISCIIEncoding.GetChars]charCount is negative"); // Need the ISCII Decoder ISCIIDecoder decoder = (ISCIIDecoder) baseDecoder; @@ -390,7 +391,7 @@ namespace System.Text // Get our current code page index (some code pages are dups) int currentCodePageIndex = -1; - Contract.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi, + Debug.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi, "[ISCIIEncoding.GetChars]Decoder code page must be >= Devanagari and <= Punjabi, not " + currentCodePage); if (currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi) @@ -410,7 +411,7 @@ namespace System.Text bLastSpecial = false; // One and only one of our flags should be set - Contract.Assert(((bLastVirama ? 1 : 0) + (bLastATR ? 1 : 0) + + Debug.Assert(((bLastVirama ? 1 : 0) + (bLastATR ? 1 : 0) + (bLastDevenagariStressAbbr ? 1 : 0) + ((cLastCharForNextNukta > 0) ? 1 : 0)) == 1, String.Format(CultureInfo.InvariantCulture, @@ -471,10 +472,10 @@ namespace System.Text bLastATR = false; // we know we can't have any of these other modes - Contract.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in bLastATR mode"); - Contract.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in bLastATR mode"); - Contract.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastATR mode"); - Contract.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastATR mode"); + Debug.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in bLastATR mode"); + Debug.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in bLastATR mode"); + Debug.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastATR mode"); + Debug.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastATR mode"); // Keep processing this byte } @@ -503,10 +504,10 @@ namespace System.Text bLastVirama = false; // We know we can't have any of these other modes - Contract.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in bLastVirama mode"); - Contract.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in bLastVirama mode"); - Contract.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastVirama mode"); - Contract.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastVirama mode"); + Debug.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in bLastVirama mode"); + Debug.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in bLastVirama mode"); + Debug.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastVirama mode"); + Debug.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastVirama mode"); } else if (bLastDevenagariStressAbbr) { @@ -539,15 +540,15 @@ namespace System.Text // (last character was added when mode was set) bLastDevenagariStressAbbr = false; - Contract.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in bLastDevenagariStressAbbr mode"); - Contract.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in bLastDevenagariStressAbbr mode"); - Contract.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastDevenagariStressAbbr mode"); - Contract.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastDevenagariStressAbbr mode"); + Debug.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in bLastDevenagariStressAbbr mode"); + Debug.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in bLastDevenagariStressAbbr mode"); + Debug.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastDevenagariStressAbbr mode"); + Debug.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastDevenagariStressAbbr mode"); } else { // We were checking for next char being a nukta - Contract.Assert(cLastCharForNextNukta > 0 && cLastCharForNoNextNukta > 0, + Debug.Assert(cLastCharForNextNukta > 0 && cLastCharForNoNextNukta > 0, "[ISCIIEncoding.GetChars]No other special case found, but cLastCharFor(No)NextNukta variable(s) aren't set."); // We'll either add combined char or last char @@ -569,14 +570,14 @@ namespace System.Text // Keep processing this byte, turn off mode. cLastCharForNextNukta = cLastCharForNoNextNukta = '\0'; - Contract.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in cLastCharForNextNukta mode"); - Contract.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in cLastCharForNextNukta mode"); - Contract.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in cLastCharForNextNukta mode"); + Debug.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in cLastCharForNextNukta mode"); + Debug.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in cLastCharForNextNukta mode"); + Debug.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in cLastCharForNextNukta mode"); } } // Now bLastSpecial should be false and all flags false. - Contract.Assert (!bLastSpecial && !bLastDevenagariStressAbbr && !bLastVirama && !bLastATR && + Debug.Assert (!bLastSpecial && !bLastDevenagariStressAbbr && !bLastVirama && !bLastATR && cLastCharForNextNukta == '\0', "[ISCIIEncoding.GetChars]No special state for last code point should exist at this point."); @@ -595,7 +596,7 @@ namespace System.Text continue; } - Contract.Assert (currentCodePageIndex != -1, "[ISCIIEncoding.GetChars]Expected valid currentCodePageIndex != -1"); + Debug.Assert (currentCodePageIndex != -1, "[ISCIIEncoding.GetChars]Expected valid currentCodePageIndex != -1"); char ch = IndicMapping[currentCodePageIndex, 0, b - MultiByteBegin]; char cAlt = IndicMapping[currentCodePageIndex, 1, b - MultiByteBegin]; @@ -641,7 +642,7 @@ namespace System.Text } // We must be the Devenagari special case for F0, B8 & F0, BF - Contract.Assert(currentCodePage == CodeDevanagari && b == DevenagariExt, + Debug.Assert(currentCodePage == CodeDevanagari && b == DevenagariExt, String.Format(CultureInfo.InvariantCulture, "[ISCIIEncoding.GetChars] Devenagari special case must {0} not {1} or in Devanagari code page {2} not {3}.", DevenagariExt, b, CodeDevanagari, currentCodePage)); @@ -696,7 +697,7 @@ namespace System.Text cLastCharForNoNextNukta != '\0' || bLastATR || bLastDevenagariStressAbbr) { // Either not flushing or had state (from convert) - Contract.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow, + Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow, "[ISCIIEncoding.GetChars]Expected no state or not converting or not flushing"); decoder.currentCodePage = currentCodePage; decoder.bLastVirama = bLastVirama; diff --git a/src/mscorlib/src/System/Text/ISO2022Encoding.cs b/src/mscorlib/src/System/Text/ISO2022Encoding.cs index 46b1803..fca579f 100644 --- a/src/mscorlib/src/System/Text/ISO2022Encoding.cs +++ b/src/mscorlib/src/System/Text/ISO2022Encoding.cs @@ -28,6 +28,7 @@ namespace System.Text { using System.Globalization; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Text; using System.Runtime.InteropServices; @@ -63,7 +64,7 @@ namespace System.Text internal ISO2022Encoding(SerializationInfo info, StreamingContext context) : base(info, context) { // Actually this can't ever get called, CodePageEncoding is our proxy - Contract.Assert(false, "Didn't expect to make it to DBCSCodePageEncoding serialization constructor"); + Debug.Assert(false, "Didn't expect to make it to DBCSCodePageEncoding serialization constructor"); throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException")); } @@ -120,7 +121,7 @@ namespace System.Text strFormat = "CodePage_{0}_{1}_{2}_{3}_{4}_HZ"; break; default: - Contract.Assert(false, "[ISO2022Encoding.GetMemorySectionName] Don't expect to get here for code page " + this.CodePage); + Debug.Assert(false, "[ISO2022Encoding.GetMemorySectionName] Don't expect to get here for code page " + this.CodePage); strFormat = "CodePage_{0}_{1}_{2}_{3}_{4}"; break; } @@ -263,8 +264,8 @@ namespace System.Text internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(count >= 0, "[ISO2022Encoding.GetByteCount]count is negative"); - Contract.Assert(chars != null, "[ISO2022Encoding.GetByteCount]chars is null"); + Debug.Assert(count >= 0, "[ISO2022Encoding.GetByteCount]count is negative"); + Debug.Assert(chars != null, "[ISO2022Encoding.GetByteCount]chars is null"); // Just call GetBytes with null byte* to get count return GetBytes(chars, count, null, 0, baseEncoder); @@ -274,12 +275,12 @@ namespace System.Text byte* bytes, int byteCount, EncoderNLS baseEncoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(chars != null, "[ISO2022Encoding.GetBytes]chars is null"); - Contract.Assert(byteCount >= 0, "[ISO2022Encoding.GetBytes]byteCount is negative"); - Contract.Assert(charCount >= 0, "[ISO2022Encoding.GetBytes]charCount is negative"); + Debug.Assert(chars != null, "[ISO2022Encoding.GetBytes]chars is null"); + Debug.Assert(byteCount >= 0, "[ISO2022Encoding.GetBytes]byteCount is negative"); + Debug.Assert(charCount >= 0, "[ISO2022Encoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. - Contract.Assert(encoderFallback != null, "[ISO2022Encoding.GetBytes]Attempting to use null encoder fallback"); + Debug.Assert(encoderFallback != null, "[ISO2022Encoding.GetBytes]Attempting to use null encoder fallback"); // Fix our encoder ISO2022Encoder encoder = (ISO2022Encoder)baseEncoder; @@ -314,8 +315,8 @@ namespace System.Text internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { // Just assert, we're called internally so these should be safe, checked already - Contract.Assert(bytes != null, "[ISO2022Encoding.GetCharCount]bytes is null"); - Contract.Assert(count >= 0, "[ISO2022Encoding.GetCharCount]byteCount is negative"); + Debug.Assert(bytes != null, "[ISO2022Encoding.GetCharCount]bytes is null"); + Debug.Assert(count >= 0, "[ISO2022Encoding.GetCharCount]byteCount is negative"); // Just call getChars with null char* to get count return GetChars(bytes, count, null, 0, baseDecoder); @@ -325,9 +326,9 @@ namespace System.Text char* chars, int charCount, DecoderNLS baseDecoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(bytes != null, "[ISO2022Encoding.GetChars]bytes is null"); - Contract.Assert(byteCount >= 0, "[ISO2022Encoding.GetChars]byteCount is negative"); - Contract.Assert(charCount >= 0, "[ISO2022Encoding.GetChars]charCount is negative"); + Debug.Assert(bytes != null, "[ISO2022Encoding.GetChars]bytes is null"); + Debug.Assert(byteCount >= 0, "[ISO2022Encoding.GetChars]byteCount is negative"); + Debug.Assert(charCount >= 0, "[ISO2022Encoding.GetChars]charCount is negative"); // Fix our decoder ISO2022Decoder decoder = (ISO2022Decoder)baseDecoder; @@ -351,7 +352,7 @@ namespace System.Text iCount = GetCharsCP52936( bytes, byteCount, chars, charCount, decoder); break; default: - Contract.Assert(false, "[ISO2022Encoding.GetChars] had unexpected code page"); + Debug.Assert(false, "[ISO2022Encoding.GetChars] had unexpected code page"); break; } @@ -414,7 +415,7 @@ namespace System.Text // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { - Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP5022xJP]leftover character should be high surrogate"); + Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP5022xJP]leftover character should be high surrogate"); // It has to be a high surrogate, which we don't support, so it has to be a fallback buffer.Fallback(charLeftOver); @@ -475,7 +476,7 @@ namespace System.Text else { // 50221 does halfwidth katakana by escape sequence - Contract.Assert(CodePage == 50221, "[ISO2022Encoding.GetBytesCP5022xJP]Expected Code Page 50221"); + Debug.Assert(CodePage == 50221, "[ISO2022Encoding.GetBytesCP5022xJP]Expected Code Page 50221"); // Add our escape sequence if (!buffer.AddByte(ESCAPE, unchecked((byte)'('), unchecked((byte)'I'))) @@ -656,7 +657,7 @@ namespace System.Text // We may have a l left over character from last time, try and process it. if (charLeftOver > 0) { - Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP50225KR]leftover character should be high surrogate"); + Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP50225KR]leftover character should be high surrogate"); // It has to be a high surrogate, which we don't support, so it has to be a fallback buffer.Fallback(charLeftOver); @@ -756,7 +757,7 @@ namespace System.Text if (!encoder.MustFlush || encoder.charLeftOver != (char)0) { // We should be not flushing or converting - Contract.Assert(!encoder.MustFlush || !encoder.m_throwOnOverflow, + Debug.Assert(!encoder.MustFlush || !encoder.m_throwOnOverflow, "[ISO2022Encoding.GetBytesCP50225KR]Expected no left over data or not flushing or not converting"); encoder.shiftInOutMode = shiftOutMode; } @@ -803,7 +804,7 @@ namespace System.Text // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { - Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP52936]leftover character should be high surrogate"); + Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP52936]leftover character should be high surrogate"); // It has to be a high surrogate, which we don't support, so it has to be a fallback buffer.Fallback(charLeftOver); @@ -1128,7 +1129,7 @@ namespace System.Text if (!decoder.MustFlush || escapeCount != 0) { // Either not flushing or had state (from convert) - Contract.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow, + Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow, "[ISO2022Encoding.GetCharsCP5022xJP]Expected no state or not converting or not flushing"); decoder.currentMode = currentMode; @@ -1222,7 +1223,7 @@ namespace System.Text private byte DecrementEscapeBytes(ref byte[] bytes, ref int count) { - Contract.Assert(count > 0, "[ISO2022Encoding.DecrementEscapeBytes]count > 0"); + Debug.Assert(count > 0, "[ISO2022Encoding.DecrementEscapeBytes]count > 0"); // Decrement our count count--; @@ -1429,7 +1430,7 @@ namespace System.Text if (!decoder.MustFlush || escapeCount != 0) { // Either not flushing or had state (from convert) - Contract.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow, + Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow, "[ISO2022Encoding.GetCharsCP50225KR]Expected no state or not converting or not flushing"); decoder.currentMode = currentMode; @@ -1487,8 +1488,8 @@ namespace System.Text private unsafe int GetCharsCP52936(byte* bytes, int byteCount, char* chars, int charCount, ISO2022Decoder decoder) { - Contract.Assert(byteCount >=0, "[ISO2022Encoding.GetCharsCP52936]count >=0"); - Contract.Assert(bytes!=null, "[ISO2022Encoding.GetCharsCP52936]bytes!=null"); + Debug.Assert(byteCount >=0, "[ISO2022Encoding.GetCharsCP52936]count >=0"); + Debug.Assert(bytes!=null, "[ISO2022Encoding.GetCharsCP52936]bytes!=null"); // Get our info. Encoding.EncodingCharBuffer buffer = new Encoding.EncodingCharBuffer( @@ -1599,7 +1600,7 @@ namespace System.Text if (currentMode != ISO2022Modes.ModeASCII) { // Should be ModeHZ - Contract.Assert(currentMode == ISO2022Modes.ModeHZ, "[ISO2022Encoding.GetCharsCP52936]Expected ModeHZ"); + Debug.Assert(currentMode == ISO2022Modes.ModeHZ, "[ISO2022Encoding.GetCharsCP52936]Expected ModeHZ"); char cm; // Everett allowed characters < 0x20 to be passed as if they were ASCII @@ -1724,7 +1725,7 @@ namespace System.Text else { // Either not flushing or had state (from convert) - Contract.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow, + Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow, "[ISO2022Encoding.GetCharsCP52936]Expected no state or not converting or not flushing"); decoder.currentMode = currentMode; diff --git a/src/mscorlib/src/System/Text/Latin1Encoding.cs b/src/mscorlib/src/System/Text/Latin1Encoding.cs index 5872583..56a6c1f 100644 --- a/src/mscorlib/src/System/Text/Latin1Encoding.cs +++ b/src/mscorlib/src/System/Text/Latin1Encoding.cs @@ -5,6 +5,7 @@ namespace System.Text { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.InteropServices; @@ -47,7 +48,7 @@ namespace System.Text { // Make sure to get the base stuff too This throws if info is null SerializeEncoding(info, context); - Contract.Assert(info!=null, "[Latin1Encoding.GetObjectData] Expected null info to throw"); + Debug.Assert(info!=null, "[Latin1Encoding.GetObjectData] Expected null info to throw"); // In Everett this is a CodePageEncoding, so it needs maxCharSize info.AddValue("CodePageEncoding+maxCharSize", 1); @@ -63,11 +64,11 @@ namespace System.Text internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(charCount >= 0, "[Latin1Encoding.GetByteCount]count is negative"); - Contract.Assert(chars != null, "[Latin1Encoding.GetByteCount]chars is null"); + Debug.Assert(charCount >= 0, "[Latin1Encoding.GetByteCount]count is negative"); + Debug.Assert(chars != null, "[Latin1Encoding.GetByteCount]chars is null"); // Assert because we shouldn't be able to have a null encoder. - Contract.Assert(encoderFallback != null, "[Latin1Encoding.GetByteCount]Attempting to use null fallback encoder"); + Debug.Assert(encoderFallback != null, "[Latin1Encoding.GetByteCount]Attempting to use null fallback encoder"); char charLeftOver = (char)0; @@ -77,13 +78,13 @@ namespace System.Text if (encoder != null) { charLeftOver = encoder.charLeftOver; - Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), + Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[Latin1Encoding.GetByteCount]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; // Verify that we have no fallbackbuffer, for Latin1 its always empty, so just assert - Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || + Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[Latin1CodePageEncoding.GetByteCount]Expected empty fallback buffer"); } @@ -120,7 +121,7 @@ namespace System.Text if (charLeftOver > 0) { // Initialize the buffer - Contract.Assert(encoder != null, + Debug.Assert(encoder != null, "[Latin1Encoding.GetByteCount]Expected encoder if we have charLeftOver"); fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false); @@ -169,7 +170,7 @@ namespace System.Text byteCount++; } - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[Latin1Encoding.GetByteCount]Expected Empty fallback buffer"); return byteCount; @@ -179,13 +180,13 @@ namespace System.Text byte* bytes, int byteCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(bytes != null, "[Latin1Encoding.GetBytes]bytes is null"); - Contract.Assert(byteCount >= 0, "[Latin1Encoding.GetBytes]byteCount is negative"); - Contract.Assert(chars != null, "[Latin1Encoding.GetBytes]chars is null"); - Contract.Assert(charCount >= 0, "[Latin1Encoding.GetBytes]charCount is negative"); + Debug.Assert(bytes != null, "[Latin1Encoding.GetBytes]bytes is null"); + Debug.Assert(byteCount >= 0, "[Latin1Encoding.GetBytes]byteCount is negative"); + Debug.Assert(chars != null, "[Latin1Encoding.GetBytes]chars is null"); + Debug.Assert(charCount >= 0, "[Latin1Encoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. - Contract.Assert(encoderFallback != null, "[Latin1Encoding.GetBytes]Attempting to use null encoder fallback"); + Debug.Assert(encoderFallback != null, "[Latin1Encoding.GetBytes]Attempting to use null encoder fallback"); // Get any left over characters & check fast or slower fallback type char charLeftOver = (char)0; @@ -194,11 +195,11 @@ namespace System.Text { charLeftOver = encoder.charLeftOver; fallback = encoder.Fallback as EncoderReplacementFallback; - Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), + Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[Latin1Encoding.GetBytes]leftover character should be high surrogate"); // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert - Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || + Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[Latin1CodePageEncoding.GetBytes]Expected empty fallback buffer"); } @@ -281,7 +282,7 @@ namespace System.Text { // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback - Contract.Assert(encoder != null, + Debug.Assert(encoder != null, "[Latin1Encoding.GetBytes]Expected encoder if we have charLeftOver"); fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true); @@ -335,7 +336,7 @@ namespace System.Text { // Didn't use this char, throw it. Chars should've advanced by now // If we had encoder fallback data it would've thrown before the loop - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[Latin1Encoding.GetBytes]Expected chars to have advanced (fallback case)"); chars--; fallbackBuffer.InternalReset(); @@ -353,11 +354,11 @@ namespace System.Text if (bytes >= byteEnd) { // didn't use this char, we'll throw or use buffer - Contract.Assert(fallbackBuffer == null || fallbackBuffer.bFallingBack == false, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.bFallingBack == false, "[Latin1Encoding.GetBytes]Expected fallback to have throw initially if insufficient space"); if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false) { - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[Latin1Encoding.GetBytes]Expected chars to have advanced (fallback case)"); chars--; // don't use last char } @@ -382,7 +383,7 @@ namespace System.Text encoder.m_charsUsed = (int)(chars - charStart); } - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[Latin1Encoding.GetBytes]Expected Empty fallback buffer"); return (int)(bytes - byteStart); @@ -392,8 +393,8 @@ namespace System.Text internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder) { // Just assert, we're called internally so these should be safe, checked already - Contract.Assert(bytes != null, "[Latin1Encoding.GetCharCount]bytes is null"); - Contract.Assert(count >= 0, "[Latin1Encoding.GetCharCount]byteCount is negative"); + Debug.Assert(bytes != null, "[Latin1Encoding.GetCharCount]bytes is null"); + Debug.Assert(count >= 0, "[Latin1Encoding.GetCharCount]byteCount is negative"); // Just return length, SBCS stay the same length because they don't map to surrogate // pairs and we don't have to fallback because all latin1Encoding code points are unicode @@ -404,10 +405,10 @@ namespace System.Text char* chars, int charCount, DecoderNLS decoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(bytes != null, "[Latin1Encoding.GetChars]bytes is null"); - Contract.Assert(byteCount >= 0, "[Latin1Encoding.GetChars]byteCount is negative"); - Contract.Assert(chars != null, "[Latin1Encoding.GetChars]chars is null"); - Contract.Assert(charCount >= 0, "[Latin1Encoding.GetChars]charCount is negative"); + Debug.Assert(bytes != null, "[Latin1Encoding.GetChars]bytes is null"); + Debug.Assert(byteCount >= 0, "[Latin1Encoding.GetChars]byteCount is negative"); + Debug.Assert(chars != null, "[Latin1Encoding.GetChars]chars is null"); + Debug.Assert(charCount >= 0, "[Latin1Encoding.GetChars]charCount is negative"); // Need byteCount chars, otherwise too small buffer if (charCount < byteCount) diff --git a/src/mscorlib/src/System/Text/MLangCodePageEncoding.cs b/src/mscorlib/src/System/Text/MLangCodePageEncoding.cs index f83bd41..a82db91 100644 --- a/src/mscorlib/src/System/Text/MLangCodePageEncoding.cs +++ b/src/mscorlib/src/System/Text/MLangCodePageEncoding.cs @@ -13,6 +13,7 @@ namespace System.Text using System; using System.Runtime.Serialization; using System.Security.Permissions; + using System.Diagnostics; using System.Diagnostics.Contracts; /*=================================MLangCodePageEncoding================================== @@ -97,7 +98,7 @@ namespace System.Text void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // We cannot ever call this. - Contract.Assert(false, "Didn't expect to make it to MLangCodePageEncoding ISerializable.GetObjectData"); + Debug.Assert(false, "Didn't expect to make it to MLangCodePageEncoding ISerializable.GetObjectData"); throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException")); } @@ -129,7 +130,7 @@ namespace System.Text void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // We cannot ever call this. - Contract.Assert(false, "Didn't expect to make it to MLangCodePageEncoding.MLangEncoder.GetObjectData"); + Debug.Assert(false, "Didn't expect to make it to MLangCodePageEncoding.MLangEncoder.GetObjectData"); throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException")); } } @@ -163,7 +164,7 @@ namespace System.Text void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // We cannot ever call this. - Contract.Assert(false, "Didn't expect to make it to MLangCodePageEncoding.MLangDecoder.GetObjectData"); + Debug.Assert(false, "Didn't expect to make it to MLangCodePageEncoding.MLangDecoder.GetObjectData"); throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException")); } } diff --git a/src/mscorlib/src/System/Text/Normalization.Windows.cs b/src/mscorlib/src/System/Text/Normalization.Windows.cs index 60e0764..b2faf0d 100644 --- a/src/mscorlib/src/System/Text/Normalization.Windows.cs +++ b/src/mscorlib/src/System/Text/Normalization.Windows.cs @@ -11,6 +11,7 @@ namespace System.Text using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; // This internal class wraps up our normalization behavior @@ -242,7 +243,7 @@ namespace System.Text { // Do appropriate stuff for the individual errors: case ERROR_INSUFFICIENT_BUFFER: - Contract.Assert(iLength > cBuffer.Length, "Buffer overflow should have iLength > cBuffer.Length"); + Debug.Assert(iLength > cBuffer.Length, "Buffer overflow should have iLength > cBuffer.Length"); continue; case ERROR_INVALID_PARAMETER: diff --git a/src/mscorlib/src/System/Text/SBCSCodePageEncoding.cs b/src/mscorlib/src/System/Text/SBCSCodePageEncoding.cs index 7211911..8b07149 100644 --- a/src/mscorlib/src/System/Text/SBCSCodePageEncoding.cs +++ b/src/mscorlib/src/System/Text/SBCSCodePageEncoding.cs @@ -6,6 +6,7 @@ namespace System.Text { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Text; using System.Threading; @@ -47,7 +48,7 @@ namespace System.Text internal SBCSCodePageEncoding(SerializationInfo info, StreamingContext context) : base(0) { // Actually this can't ever get called, CodePageEncoding is our proxy - Contract.Assert(false, "Didn't expect to make it to SBCSCodePageEncoding serialization constructor"); + Debug.Assert(false, "Didn't expect to make it to SBCSCodePageEncoding serialization constructor"); throw new ArgumentNullException("this"); } @@ -66,7 +67,7 @@ namespace System.Text protected override unsafe void LoadManagedCodePage() { // Should be loading OUR code page - Contract.Assert(pCodePage->CodePage == this.dataTableCodePage, + Debug.Assert(pCodePage->CodePage == this.dataTableCodePage, "[SBCSCodePageEncoding.LoadManagedCodePage]Expected to load data table code page"); // Make sure we're really a 1 byte code page @@ -89,7 +90,7 @@ namespace System.Text // If its cached (& filled in) we don't have to do anything else if (*mapCodePageCached != 0) { - Contract.Assert(*mapCodePageCached == this.dataTableCodePage, + Debug.Assert(*mapCodePageCached == this.dataTableCodePage, "[DBCSCodePageEncoding.LoadManagedCodePage]Expected mapped section cached page to be same as data table code page. Cached : " + *mapCodePageCached + " Expected:" + this.dataTableCodePage); @@ -172,7 +173,7 @@ namespace System.Text while ((byteTemp = *((ushort*)pData)) != 0) { - Contract.Assert(arrayTemp[byteTemp] == UNKNOWN_CHAR, String.Format(CultureInfo.InvariantCulture, + Debug.Assert(arrayTemp[byteTemp] == UNKNOWN_CHAR, String.Format(CultureInfo.InvariantCulture, "[SBCSCodePageEncoding::ReadBestFitTable] Expected unallocated byte (not 0x{2:X2}) for best fit byte at 0x{0:X2} for code page {1}", byteTemp, CodePage, (int)arrayTemp[byteTemp])); pData += 2; @@ -273,7 +274,7 @@ namespace System.Text arrayTemp[iBestFitCount++] = mapBytesToUnicode[input]; // This won't work if it won't round trip. - Contract.Assert(arrayTemp[iBestFitCount-1] != (char)0, + Debug.Assert(arrayTemp[iBestFitCount-1] != (char)0, String.Format(CultureInfo.InvariantCulture, "[SBCSCodePageEncoding.ReadBestFitTable] No valid Unicode value {0:X4} for round trip bytes {1:X4}, encoding {2}", (int)mapBytesToUnicode[input], (int)input, CodePage)); @@ -294,11 +295,11 @@ namespace System.Text internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(count >= 0, "[SBCSCodePageEncoding.GetByteCount]count is negative"); - Contract.Assert(chars != null, "[SBCSCodePageEncoding.GetByteCount]chars is null"); + Debug.Assert(count >= 0, "[SBCSCodePageEncoding.GetByteCount]count is negative"); + Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetByteCount]chars is null"); // Assert because we shouldn't be able to have a null encoder. - Contract.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetByteCount]Attempting to use null fallback"); + Debug.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetByteCount]Attempting to use null fallback"); CheckMemorySection(); @@ -310,12 +311,12 @@ namespace System.Text if (encoder != null) { charLeftOver = encoder.charLeftOver; - Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), + Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[SBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; // Verify that we have no fallbackbuffer, actually for SBCS this is always empty, so just assert - Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || + Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[SBCSCodePageEncoding.GetByteCount]Expected empty fallback buffer at start"); } @@ -354,7 +355,7 @@ namespace System.Text { // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback - Contract.Assert(encoder != null, "[SBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver"); + Debug.Assert(encoder != null, "[SBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver"); fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false); @@ -405,7 +406,7 @@ namespace System.Text byteCount++; } - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetByteCount]Expected Empty fallback buffer at end"); return (int)byteCount; @@ -415,13 +416,13 @@ namespace System.Text byte* bytes, int byteCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(bytes != null, "[SBCSCodePageEncoding.GetBytes]bytes is null"); - Contract.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetBytes]byteCount is negative"); - Contract.Assert(chars != null, "[SBCSCodePageEncoding.GetBytes]chars is null"); - Contract.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetBytes]charCount is negative"); + Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetBytes]bytes is null"); + Debug.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetBytes]byteCount is negative"); + Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetBytes]chars is null"); + Debug.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. - Contract.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback"); + Debug.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback"); CheckMemorySection(); @@ -433,12 +434,12 @@ namespace System.Text if (encoder != null) { charLeftOver = encoder.charLeftOver; - Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), + Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[SBCSCodePageEncoding.GetBytes]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; // Verify that we have no fallbackbuffer, for SBCS its always empty, so just assert - Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || + Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[SBCSCodePageEncoding.GetBytes]Expected empty fallback buffer at start"); // if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer && @@ -535,7 +536,7 @@ namespace System.Text { // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback - Contract.Assert(encoder != null, "[SBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver"); + Debug.Assert(encoder != null, "[SBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver"); fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true); @@ -588,7 +589,7 @@ namespace System.Text if (fallbackBuffer.Remaining > byteEnd - bytes) { // Didn't use this char, reset it - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[SBCSCodePageEncoding.GetBytes]Expected chars to have advanced (fallback)"); chars--; fallbackBuffer.InternalReset(); @@ -605,11 +606,11 @@ namespace System.Text if (bytes >= byteEnd) { // didn't use this char, we'll throw or use buffer - Contract.Assert(fallbackBuffer == null || fallbackBuffer.bFallingBack == false, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.bFallingBack == false, "[SBCSCodePageEncoding.GetBytes]Expected to NOT be falling back"); if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false) { - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[SBCSCodePageEncoding.GetBytes]Expected chars to have advanced (normal)"); chars--; // don't use last char } @@ -635,7 +636,7 @@ namespace System.Text } // Expect Empty fallback buffer for SBCS - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetBytes]Expected Empty fallback buffer at end"); return (int)(bytes - byteStart); @@ -645,8 +646,8 @@ namespace System.Text internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder) { // Just assert, we're called internally so these should be safe, checked already - Contract.Assert(bytes != null, "[SBCSCodePageEncoding.GetCharCount]bytes is null"); - Contract.Assert(count >= 0, "[SBCSCodePageEncoding.GetCharCount]byteCount is negative"); + Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetCharCount]bytes is null"); + Debug.Assert(count >= 0, "[SBCSCodePageEncoding.GetCharCount]byteCount is negative"); CheckMemorySection(); @@ -665,7 +666,7 @@ namespace System.Text { fallback = decoder.Fallback as DecoderReplacementFallback; bUseBestFit = decoder.Fallback.IsMicrosoftBestFitFallback; - Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || + Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[SBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start"); } @@ -718,7 +719,7 @@ namespace System.Text } // Fallback buffer must be empty - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetCharCount]Expected Empty fallback buffer at end"); // Converted sequence is same length as input @@ -729,10 +730,10 @@ namespace System.Text char* chars, int charCount, DecoderNLS decoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(bytes != null, "[SBCSCodePageEncoding.GetChars]bytes is null"); - Contract.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetChars]byteCount is negative"); - Contract.Assert(chars != null, "[SBCSCodePageEncoding.GetChars]chars is null"); - Contract.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetChars]charCount is negative"); + Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetChars]bytes is null"); + Debug.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetChars]byteCount is negative"); + Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetChars]chars is null"); + Debug.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetChars]charCount is negative"); CheckMemorySection(); @@ -756,7 +757,7 @@ namespace System.Text { fallback = decoder.Fallback as DecoderReplacementFallback; bUseBestFit = decoder.Fallback.IsMicrosoftBestFitFallback; - Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || + Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[SBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start"); } @@ -836,7 +837,7 @@ namespace System.Text } // Use fallback buffer - Contract.Assert(bytes > byteStart, + Debug.Assert(bytes > byteStart, "[SBCSCodePageEncoding.GetChars]Expected bytes to have advanced already (unknown byte)"); byteBuffer[0] = *(bytes - 1); // Fallback adds fallback to chars, but doesn't increment chars unless the whole thing fits. @@ -854,7 +855,7 @@ namespace System.Text // Make sure we have buffer space if (chars >= charEnd) { - Contract.Assert(bytes > byteStart, + Debug.Assert(bytes > byteStart, "[SBCSCodePageEncoding.GetChars]Expected bytes to have advanced already (known byte)"); bytes--; // unused byte ThrowCharsOverflow(decoder, bytes == byteStart); // throw? @@ -871,7 +872,7 @@ namespace System.Text decoder.m_bytesUsed = (int)(bytes - byteStart); // Expect Empty fallback buffer for GetChars - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetChars]Expected Empty fallback buffer at end"); return (int)(chars - charStart); diff --git a/src/mscorlib/src/System/Text/StringBuilder.cs b/src/mscorlib/src/System/Text/StringBuilder.cs index 5504fd2..f20146f 100644 --- a/src/mscorlib/src/System/Text/StringBuilder.cs +++ b/src/mscorlib/src/System/Text/StringBuilder.cs @@ -20,6 +20,7 @@ namespace System.Text { using System.Security; using System.Threading; using System.Globalization; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Collections.Generic; @@ -262,21 +263,21 @@ namespace System.Text { for (; ; ) { // All blocks have copy of the maxCapacity. - Contract.Assert(currentBlock.m_MaxCapacity == maxCapacity, "Bad maxCapacity"); - Contract.Assert(currentBlock.m_ChunkChars != null, "Empty Buffer"); + Debug.Assert(currentBlock.m_MaxCapacity == maxCapacity, "Bad maxCapacity"); + Debug.Assert(currentBlock.m_ChunkChars != null, "Empty Buffer"); - Contract.Assert(currentBlock.m_ChunkLength <= currentBlock.m_ChunkChars.Length, "Out of range length"); - Contract.Assert(currentBlock.m_ChunkLength >= 0, "Negative length"); - Contract.Assert(currentBlock.m_ChunkOffset >= 0, "Negative offset"); + Debug.Assert(currentBlock.m_ChunkLength <= currentBlock.m_ChunkChars.Length, "Out of range length"); + Debug.Assert(currentBlock.m_ChunkLength >= 0, "Negative length"); + Debug.Assert(currentBlock.m_ChunkOffset >= 0, "Negative offset"); StringBuilder prevBlock = currentBlock.m_ChunkPrevious; if (prevBlock == null) { - Contract.Assert(currentBlock.m_ChunkOffset == 0, "First chunk's offset is not 0"); + Debug.Assert(currentBlock.m_ChunkOffset == 0, "First chunk's offset is not 0"); break; } // There are no gaps in the blocks. - Contract.Assert(currentBlock.m_ChunkOffset == prevBlock.m_ChunkOffset + prevBlock.m_ChunkLength, "There is a gap between chunks!"); + Debug.Assert(currentBlock.m_ChunkOffset == prevBlock.m_ChunkOffset + prevBlock.m_ChunkLength, "There is a gap between chunks!"); currentBlock = prevBlock; } } @@ -473,7 +474,7 @@ namespace System.Text { { m_ChunkLength = 0; m_ChunkOffset = 0; - Contract.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity"); + Debug.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity"); return; } @@ -495,7 +496,7 @@ namespace System.Text { int newLen = originalCapacity - chunk.m_ChunkOffset; char[] newArray = new char[newLen]; - Contract.Assert(newLen > chunk.m_ChunkChars.Length, "the new chunk should be larger than the one it is replacing"); + Debug.Assert(newLen > chunk.m_ChunkChars.Length, "the new chunk should be larger than the one it is replacing"); Array.Copy(chunk.m_ChunkChars, newArray, chunk.m_ChunkLength); m_ChunkChars = newArray; @@ -505,7 +506,7 @@ namespace System.Text { m_ChunkLength = value - chunk.m_ChunkOffset; VerifyClassInvariant(); } - Contract.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity"); + Debug.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity"); } } @@ -577,7 +578,7 @@ namespace System.Text { { m_ChunkLength = idx; ExpandByABlock(repeatCount); - Contract.Assert(m_ChunkLength == 0, "Expand should create a new block"); + Debug.Assert(m_ChunkLength == 0, "Expand should create a new block"); idx = 0; } } @@ -815,7 +816,7 @@ namespace System.Text { if (insertingChars > MaxCapacity - this.Length) { throw new OutOfMemoryException(); } - Contract.Assert(insertingChars + this.Length < Int32.MaxValue); + Debug.Assert(insertingChars + this.Length < Int32.MaxValue); StringBuilder chunk; int indexInChunk; @@ -1722,7 +1723,7 @@ namespace System.Text { chunk = FindChunkForIndex(index); indexInChunk = index - chunk.m_ChunkOffset; - Contract.Assert(chunk != null || count == 0, "Chunks ended prematurely"); + Debug.Assert(chunk != null || count == 0, "Chunks ended prematurely"); } } VerifyClassInvariant(); @@ -1812,7 +1813,7 @@ namespace System.Text { // Expand the builder to add another chunk. int restLength = valueCount - firstLength; ExpandByABlock(restLength); - Contract.Assert(m_ChunkLength == 0, "Expand did not make a new block"); + Debug.Assert(m_ChunkLength == 0, "Expand did not make a new block"); // Copy the second chunk ThreadSafeCopy(value + firstLength, m_ChunkChars, 0, restLength); @@ -1876,9 +1877,9 @@ namespace System.Text { break; int gapEnd = replacements[i]; - Contract.Assert(gapStart < sourceChunk.m_ChunkChars.Length, "gap starts at end of buffer. Should not happen"); - Contract.Assert(gapStart <= gapEnd, "negative gap size"); - Contract.Assert(gapEnd <= sourceChunk.m_ChunkLength, "gap too big"); + Debug.Assert(gapStart < sourceChunk.m_ChunkChars.Length, "gap starts at end of buffer. Should not happen"); + Debug.Assert(gapStart <= gapEnd, "negative gap size"); + Debug.Assert(gapEnd <= sourceChunk.m_ChunkLength, "gap too big"); if (delta != 0) // can skip the sliding of gaps if source an target string are the same size. { // Copy the gap data between the current replacement and the the next replacement @@ -1888,7 +1889,7 @@ namespace System.Text { else { targetIndexInChunk += gapEnd - gapStart; - Contract.Assert(targetIndexInChunk <= targetChunk.m_ChunkLength, "gap not in chunk"); + Debug.Assert(targetIndexInChunk <= targetChunk.m_ChunkLength, "gap not in chunk"); } } @@ -1940,7 +1941,7 @@ namespace System.Text { for (; ; ) { int lengthInChunk = chunk.m_ChunkLength - indexInChunk; - Contract.Assert(lengthInChunk >= 0, "index not in chunk"); + Debug.Assert(lengthInChunk >= 0, "index not in chunk"); int lengthToCopy = Math.Min(lengthInChunk, count); ThreadSafeCopy(value, chunk.m_ChunkChars, indexInChunk, lengthToCopy); @@ -2031,13 +2032,13 @@ namespace System.Text { /// private StringBuilder FindChunkForIndex(int index) { - Contract.Assert(0 <= index && index <= Length, "index not in string"); + Debug.Assert(0 <= index && index <= Length, "index not in string"); StringBuilder ret = this; while (ret.m_ChunkOffset > index) ret = ret.m_ChunkPrevious; - Contract.Assert(ret != null, "index not in string"); + Debug.Assert(ret != null, "index not in string"); return ret; } @@ -2048,13 +2049,13 @@ namespace System.Text { /// private StringBuilder FindChunkForByte(int byteIndex) { - Contract.Assert(0 <= byteIndex && byteIndex <= Length*sizeof(char), "Byte Index not in string"); + Debug.Assert(0 <= byteIndex && byteIndex <= Length*sizeof(char), "Byte Index not in string"); StringBuilder ret = this; while (ret.m_ChunkOffset*sizeof(char) > byteIndex) ret = ret.m_ChunkPrevious; - Contract.Assert(ret != null, "Byte Index not in string"); + Debug.Assert(ret != null, "Byte Index not in string"); return ret; } @@ -2140,8 +2141,8 @@ namespace System.Text { private void MakeRoom(int index, int count, out StringBuilder chunk, out int indexInChunk, bool doneMoveFollowingChars) { VerifyClassInvariant(); - Contract.Assert(count > 0, "Count must be strictly positive"); - Contract.Assert(index >= 0, "Index can't be negative"); + Debug.Assert(count > 0, "Count must be strictly positive"); + Debug.Assert(index >= 0, "Index can't be negative"); if (count + Length > m_MaxCapacity || count + Length < count) throw new ArgumentOutOfRangeException("requiredLength", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity")); @@ -2206,8 +2207,8 @@ namespace System.Text { /// private StringBuilder(int size, int maxCapacity, StringBuilder previousBlock) { - Contract.Assert(size > 0, "size not positive"); - Contract.Assert(maxCapacity > 0, "maxCapacity not positive"); + Debug.Assert(size > 0, "size not positive"); + Debug.Assert(maxCapacity > 0, "maxCapacity not positive"); m_ChunkChars = new char[size]; m_MaxCapacity = maxCapacity; m_ChunkPrevious = previousBlock; @@ -2223,7 +2224,7 @@ namespace System.Text { private void Remove(int startIndex, int count, out StringBuilder chunk, out int indexInChunk) { VerifyClassInvariant(); - Contract.Assert(startIndex >= 0 && startIndex < Length, "startIndex not in string"); + Debug.Assert(startIndex >= 0 && startIndex < Length, "startIndex not in string"); int endIndex = startIndex + count; @@ -2252,7 +2253,7 @@ namespace System.Text { } chunk = chunk.m_ChunkPrevious; } - Contract.Assert(chunk != null, "fell off beginning of string!"); + Debug.Assert(chunk != null, "fell off beginning of string!"); int copyTargetIndexInChunk = indexInChunk; int copyCount = endChunk.m_ChunkLength - endIndexInChunk; @@ -2282,7 +2283,7 @@ namespace System.Text { if (copyTargetIndexInChunk != endIndexInChunk) // Sometimes no move is necessary ThreadSafeCopy(endChunk.m_ChunkChars, endIndexInChunk, endChunk.m_ChunkChars, copyTargetIndexInChunk, copyCount); - Contract.Assert(chunk != null, "fell off beginning of string!"); + Debug.Assert(chunk != null, "fell off beginning of string!"); VerifyClassInvariant(); } } diff --git a/src/mscorlib/src/System/Text/SurrogateEncoder.cs b/src/mscorlib/src/System/Text/SurrogateEncoder.cs index 8d5073c..bbfa180 100644 --- a/src/mscorlib/src/System/Text/SurrogateEncoder.cs +++ b/src/mscorlib/src/System/Text/SurrogateEncoder.cs @@ -12,6 +12,7 @@ namespace System.Text using System; using System.Runtime.Serialization; using System.Security.Permissions; + using System.Diagnostics; using System.Diagnostics.Contracts; /*=================================SurrogateEncoder================================== @@ -48,7 +49,7 @@ namespace System.Text void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // We cannot ever call this. - Contract.Assert(false, "Didn't expect to make it to SurrogateEncoder.GetObjectData"); + Debug.Assert(false, "Didn't expect to make it to SurrogateEncoder.GetObjectData"); throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException")); } } diff --git a/src/mscorlib/src/System/Text/UTF32Encoding.cs b/src/mscorlib/src/System/Text/UTF32Encoding.cs index cf612b8..a7ac1d8 100644 --- a/src/mscorlib/src/System/Text/UTF32Encoding.cs +++ b/src/mscorlib/src/System/Text/UTF32Encoding.cs @@ -10,6 +10,7 @@ namespace System.Text { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; // Encodes text into and out of UTF-32. UTF-32 is a way of writing @@ -180,8 +181,8 @@ namespace System.Text internal override unsafe int GetByteCount(char *chars, int count, EncoderNLS encoder) { - Contract.Assert(chars!=null, "[UTF32Encoding.GetByteCount]chars!=null"); - Contract.Assert(count >=0, "[UTF32Encoding.GetByteCount]count >=0"); + Debug.Assert(chars!=null, "[UTF32Encoding.GetByteCount]chars!=null"); + Debug.Assert(count >=0, "[UTF32Encoding.GetByteCount]count >=0"); char* end = chars + count; char* charStart = chars; @@ -243,7 +244,7 @@ namespace System.Text // We are missing our low surrogate, decrement chars and fallback the high surrogate // The high surrogate may have come from the encoder, but nothing else did. - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[UTF32Encoding.GetByteCount]Expected chars to have advanced if no low surrogate"); chars--; @@ -296,7 +297,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetByteCount // (don't have to check m_throwOnOverflow for count) - Contract.Assert(fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer.Remaining == 0, "[UTF32Encoding.GetByteCount]Expected empty fallback buffer at end"); // Return our count @@ -306,10 +307,10 @@ namespace System.Text internal override unsafe int GetBytes(char *chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { - Contract.Assert(chars!=null, "[UTF32Encoding.GetBytes]chars!=null"); - Contract.Assert(bytes!=null, "[UTF32Encoding.GetBytes]bytes!=null"); - Contract.Assert(byteCount >=0, "[UTF32Encoding.GetBytes]byteCount >=0"); - Contract.Assert(charCount >=0, "[UTF32Encoding.GetBytes]charCount >=0"); + Debug.Assert(chars!=null, "[UTF32Encoding.GetBytes]chars!=null"); + Debug.Assert(bytes!=null, "[UTF32Encoding.GetBytes]bytes!=null"); + Debug.Assert(byteCount >=0, "[UTF32Encoding.GetBytes]byteCount >=0"); + Debug.Assert(charCount >=0, "[UTF32Encoding.GetBytes]charCount >=0"); char* charStart = chars; char* charEnd = chars + charCount; @@ -378,7 +379,7 @@ namespace System.Text { // If we don't have enough room, then either we should've advanced a while // or we should have bytes==byteStart and throw below - Contract.Assert(chars > charStart + 1 || bytes == byteStart, + Debug.Assert(chars > charStart + 1 || bytes == byteStart, "[UnicodeEncoding.GetBytes]Expected chars to have when no room to add surrogate pair"); chars-=2; // Aren't using those 2 chars } @@ -406,7 +407,7 @@ namespace System.Text // We are missing our low surrogate, decrement chars and fallback the high surrogate // The high surrogate may have come from the encoder, but nothing else did. - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[UTF32Encoding.GetBytes]Expected chars to have advanced if no low surrogate"); chars--; @@ -447,7 +448,7 @@ namespace System.Text else { // Must've advanced already - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[UTF32Encoding.GetBytes]Expected chars to have advanced if normal character"); chars--; // Aren't using this char } @@ -481,7 +482,7 @@ namespace System.Text } // Fix our encoder if we have one - Contract.Assert(highSurrogate == 0 || (encoder != null && !encoder.MustFlush), + Debug.Assert(highSurrogate == 0 || (encoder != null && !encoder.MustFlush), "[UTF32Encoding.GetBytes]Expected encoder to be flushed."); if (encoder != null) @@ -499,8 +500,8 @@ namespace System.Text internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { - Contract.Assert(bytes!=null, "[UTF32Encoding.GetCharCount]bytes!=null"); - Contract.Assert(count >=0, "[UTF32Encoding.GetCharCount]count >=0"); + Debug.Assert(bytes!=null, "[UTF32Encoding.GetCharCount]bytes!=null"); + Debug.Assert(count >=0, "[UTF32Encoding.GetCharCount]count >=0"); UTF32Decoder decoder = (UTF32Decoder)baseDecoder; @@ -525,7 +526,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for chars or count) - Contract.Assert(fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer.Remaining == 0, "[UTF32Encoding.GetCharCount]Expected empty fallback buffer at start"); } else @@ -632,7 +633,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for chars or count) - Contract.Assert(fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer.Remaining == 0, "[UTF32Encoding.GetCharCount]Expected empty fallback buffer at end"); // Return our count @@ -642,10 +643,10 @@ namespace System.Text internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { - Contract.Assert(chars!=null, "[UTF32Encoding.GetChars]chars!=null"); - Contract.Assert(bytes!=null, "[UTF32Encoding.GetChars]bytes!=null"); - Contract.Assert(byteCount >=0, "[UTF32Encoding.GetChars]byteCount >=0"); - Contract.Assert(charCount >=0, "[UTF32Encoding.GetChars]charCount >=0"); + Debug.Assert(chars!=null, "[UTF32Encoding.GetChars]chars!=null"); + Debug.Assert(bytes!=null, "[UTF32Encoding.GetChars]bytes!=null"); + Debug.Assert(byteCount >=0, "[UTF32Encoding.GetChars]byteCount >=0"); + Debug.Assert(charCount >=0, "[UTF32Encoding.GetChars]charCount >=0"); UTF32Decoder decoder = (UTF32Decoder)baseDecoder; @@ -672,7 +673,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetChars // (don't have to check m_throwOnOverflow for chars) - Contract.Assert(fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer.Remaining == 0, "[UTF32Encoding.GetChars]Expected empty fallback buffer at start"); } else @@ -733,7 +734,7 @@ namespace System.Text // Couldn't fallback, throw or wait til next time // We either read enough bytes for bytes-=4 to work, or we're // going to throw in ThrowCharsOverflow because chars == charStart - Contract.Assert(bytes >= byteStart + 4 || chars == charStart, + Debug.Assert(bytes >= byteStart + 4 || chars == charStart, "[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (bad surrogate)"); bytes-=4; // get back to where we were iChar=0; // Remembering nothing @@ -757,7 +758,7 @@ namespace System.Text // Throwing or stopping // We either read enough bytes for bytes-=4 to work, or we're // going to throw in ThrowCharsOverflow because chars == charStart - Contract.Assert(bytes >= byteStart + 4 || chars == charStart, + Debug.Assert(bytes >= byteStart + 4 || chars == charStart, "[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (surrogate)"); bytes-=4; // get back to where we were iChar=0; // Remembering nothing @@ -774,7 +775,7 @@ namespace System.Text // Throwing or stopping // We either read enough bytes for bytes-=4 to work, or we're // going to throw in ThrowCharsOverflow because chars == charStart - Contract.Assert(bytes >= byteStart + 4 || chars == charStart, + Debug.Assert(bytes >= byteStart + 4 || chars == charStart, "[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (normal char)"); bytes-=4; // get back to where we were iChar=0; // Remembering nothing @@ -838,7 +839,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetChars // (don't have to check m_throwOnOverflow for chars) - Contract.Assert(fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer.Remaining == 0, "[UTF32Encoding.GetChars]Expected empty fallback buffer at end"); // Return our count diff --git a/src/mscorlib/src/System/Text/UTF7Encoding.cs b/src/mscorlib/src/System/Text/UTF7Encoding.cs index d9a7484..624ca73 100644 --- a/src/mscorlib/src/System/Text/UTF7Encoding.cs +++ b/src/mscorlib/src/System/Text/UTF7Encoding.cs @@ -11,6 +11,7 @@ namespace System.Text using System; using System.Runtime.Serialization; using System.Security.Permissions; + using System.Diagnostics; using System.Diagnostics.Contracts; @@ -252,8 +253,8 @@ namespace System.Text internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder) { - Contract.Assert(chars!=null, "[UTF7Encoding.GetByteCount]chars!=null"); - Contract.Assert(count >=0, "[UTF7Encoding.GetByteCount]count >=0"); + Debug.Assert(chars!=null, "[UTF7Encoding.GetByteCount]chars!=null"); + Debug.Assert(count >=0, "[UTF7Encoding.GetByteCount]count >=0"); // Just call GetBytes with bytes == null return GetBytes(chars, count, null, 0, baseEncoder); @@ -262,9 +263,9 @@ namespace System.Text internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS baseEncoder) { - Contract.Assert(byteCount >=0, "[UTF7Encoding.GetBytes]byteCount >=0"); - Contract.Assert(chars!=null, "[UTF7Encoding.GetBytes]chars!=null"); - Contract.Assert(charCount >=0, "[UTF7Encoding.GetBytes]charCount >=0"); + Debug.Assert(byteCount >=0, "[UTF7Encoding.GetBytes]byteCount >=0"); + Debug.Assert(chars!=null, "[UTF7Encoding.GetBytes]chars!=null"); + Debug.Assert(charCount >=0, "[UTF7Encoding.GetBytes]charCount >=0"); // Get encoder info UTF7Encoding.Encoder encoder = (UTF7Encoding.Encoder)baseEncoder; @@ -401,8 +402,8 @@ namespace System.Text internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { - Contract.Assert(count >=0, "[UTF7Encoding.GetCharCount]count >=0"); - Contract.Assert(bytes!=null, "[UTF7Encoding.GetCharCount]bytes!=null"); + Debug.Assert(count >=0, "[UTF7Encoding.GetCharCount]count >=0"); + Debug.Assert(bytes!=null, "[UTF7Encoding.GetCharCount]bytes!=null"); // Just call GetChars with null char* to do counting return GetChars(bytes, count, null, 0, baseDecoder); @@ -411,9 +412,9 @@ namespace System.Text internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { - Contract.Assert(byteCount >=0, "[UTF7Encoding.GetChars]byteCount >=0"); - Contract.Assert(bytes!=null, "[UTF7Encoding.GetChars]bytes!=null"); - Contract.Assert(charCount >=0, "[UTF7Encoding.GetChars]charCount >=0"); + Debug.Assert(byteCount >=0, "[UTF7Encoding.GetChars]byteCount >=0"); + Debug.Assert(bytes!=null, "[UTF7Encoding.GetChars]bytes!=null"); + Debug.Assert(charCount >=0, "[UTF7Encoding.GetChars]charCount >=0"); // Might use a decoder UTF7Encoding.Decoder decoder = (UTF7Encoding.Decoder) baseDecoder; @@ -432,7 +433,7 @@ namespace System.Text bitCount = decoder.bitCount; firstByte = decoder.firstByte; - Contract.Assert(firstByte == false || decoder.bitCount <= 0, + Debug.Assert(firstByte == false || decoder.bitCount <= 0, "[UTF7Encoding.GetChars]If remembered bits, then first byte flag shouldn't be set"); } @@ -815,8 +816,8 @@ namespace System.Text public override bool Fallback(byte[] bytesUnknown, int index) { // We expect no previous fallback in our buffer - Contract.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.Fallback] Can't have recursive fallbacks"); - Contract.Assert(bytesUnknown.Length == 1, "[DecoderUTF7FallbackBuffer.Fallback] Only possible fallback case should be 1 unknown byte"); + Debug.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.Fallback] Can't have recursive fallbacks"); + Debug.Assert(bytesUnknown.Length == 1, "[DecoderUTF7FallbackBuffer.Fallback] Only possible fallback case should be 1 unknown byte"); // Go ahead and get our fallback cFallback = (char)bytesUnknown[0]; @@ -874,7 +875,7 @@ namespace System.Text // array, and we might need the index, hence the byte* { // We expect no previous fallback in our buffer - Contract.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.InternalFallback] Can't have recursive fallbacks"); + Debug.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.InternalFallback] Can't have recursive fallbacks"); if (bytes.Length != 1) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex")); diff --git a/src/mscorlib/src/System/Text/UTF8Encoding.cs b/src/mscorlib/src/System/Text/UTF8Encoding.cs index 7d05092..ba19649 100644 --- a/src/mscorlib/src/System/Text/UTF8Encoding.cs +++ b/src/mscorlib/src/System/Text/UTF8Encoding.cs @@ -21,6 +21,7 @@ namespace System.Text using System.Globalization; using System.Runtime.Serialization; using System.Security.Permissions; + using System.Diagnostics; using System.Diagnostics.Contracts; // Encodes text into and out of UTF-8. UTF-8 is a way of writing @@ -249,7 +250,7 @@ namespace System.Text } else { // Case of surrogates in the fallback. if (fallbackBuffer != null && fallbackBuffer.bFallingBack) { - Contract.Assert(ch >= 0xD800 && ch <= 0xDBFF, + Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF, "[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture)); ch = fallbackBuffer.InternalGetNextChar(); @@ -281,7 +282,7 @@ namespace System.Text } if (ch > 0) { - Contract.Assert(ch >= 0xD800 && ch <= 0xDBFF, + Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF, "[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture)); // use separate helper variables for local contexts so that the jit optimizations @@ -552,7 +553,7 @@ namespace System.Text } #endif - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[UTF8Encoding.GetByteCount]Expected Empty fallback buffer"); return byteCount; @@ -582,10 +583,10 @@ namespace System.Text internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS baseEncoder) { - Contract.Assert(chars!=null, "[UTF8Encoding.GetBytes]chars!=null"); - Contract.Assert(byteCount >=0, "[UTF8Encoding.GetBytes]byteCount >=0"); - Contract.Assert(charCount >=0, "[UTF8Encoding.GetBytes]charCount >=0"); - Contract.Assert(bytes!=null, "[UTF8Encoding.GetBytes]bytes!=null"); + Debug.Assert(chars!=null, "[UTF8Encoding.GetBytes]chars!=null"); + Debug.Assert(byteCount >=0, "[UTF8Encoding.GetBytes]byteCount >=0"); + Debug.Assert(charCount >=0, "[UTF8Encoding.GetBytes]charCount >=0"); + Debug.Assert(bytes!=null, "[UTF8Encoding.GetBytes]bytes!=null"); UTF8Encoder encoder = null; @@ -634,7 +635,7 @@ namespace System.Text } else { // Case of leftover surrogates in the fallback buffer if (fallbackBuffer != null && fallbackBuffer.bFallingBack) { - Contract.Assert(ch >= 0xD800 && ch <= 0xDBFF, + Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF, "[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture)); int cha = ch; @@ -662,7 +663,7 @@ namespace System.Text if (ch > 0) { // We have a high surrogate left over from a previous loop. - Contract.Assert(ch >= 0xD800 && ch <= 0xDBFF, + Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF, "[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture)); // use separate helper variables for local contexts so that the jit optimizations @@ -759,7 +760,7 @@ namespace System.Text if (ch > 0xFFFF) pSrc--; // Was surrogate, didn't use 2nd part either } - Contract.Assert(pSrc >= chars || pTarget == bytes, + Debug.Assert(pSrc >= chars || pTarget == bytes, "[UTF8Encoding.GetBytes]Expected pSrc to be within buffer or to throw with insufficient room."); ThrowBytesOverflow(encoder, pTarget == bytes); // Throw if we must ch = 0; // Nothing left over (we backed up to start of pair if supplimentary) @@ -981,7 +982,7 @@ namespace System.Text pTarget++; } - Contract.Assert(pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetBytes]pTarget <= pAllocatedBufferEnd"); + Debug.Assert(pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetBytes]pTarget <= pAllocatedBufferEnd"); #endif // FASTLOOP @@ -992,14 +993,14 @@ namespace System.Text // Do we have to set the encoder bytes? if (encoder != null) { - Contract.Assert(!encoder.MustFlush || ch == 0, + Debug.Assert(!encoder.MustFlush || ch == 0, "[UTF8Encoding.GetBytes] Expected no mustflush or 0 leftover ch " + ch.ToString("X2", CultureInfo.InvariantCulture)); encoder.surrogateChar = ch; encoder.m_charsUsed = (int)(pSrc - chars); } - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 || + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 || baseEncoder == null || !baseEncoder.m_throwOnOverflow, "[UTF8Encoding.GetBytes]Expected empty fallback buffer if not converting"); @@ -1023,8 +1024,8 @@ namespace System.Text // kept the same as much as possible internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { - Contract.Assert(count >=0, "[UTF8Encoding.GetCharCount]count >=0"); - Contract.Assert(bytes!=null, "[UTF8Encoding.GetCharCount]bytes!=null"); + Debug.Assert(count >=0, "[UTF8Encoding.GetCharCount]count >=0"); + Debug.Assert(bytes!=null, "[UTF8Encoding.GetCharCount]bytes!=null"); // Initialize stuff byte *pSrc = bytes; @@ -1043,7 +1044,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for count) - Contract.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, + Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[UTF8Encoding.GetCharCount]Expected empty fallback buffer at start"); } @@ -1078,7 +1079,7 @@ namespace System.Text ch = (ch << 6) | (cha & 0x3F); if ((ch & FinalByte) == 0) { - Contract.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0, + Debug.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0, "[UTF8Encoding.GetChars]Invariant volation"); if ((ch & SupplimentarySeq) != 0) { @@ -1399,7 +1400,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for count) - Contract.Assert(fallback == null || fallback.Remaining == 0, + Debug.Assert(fallback == null || fallback.Remaining == 0, "[UTF8Encoding.GetCharCount]Expected empty fallback buffer at end"); return charCount; @@ -1418,10 +1419,10 @@ namespace System.Text internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { - Contract.Assert(chars!=null, "[UTF8Encoding.GetChars]chars!=null"); - Contract.Assert(byteCount >=0, "[UTF8Encoding.GetChars]count >=0"); - Contract.Assert(charCount >=0, "[UTF8Encoding.GetChars]charCount >=0"); - Contract.Assert(bytes!=null, "[UTF8Encoding.GetChars]bytes!=null"); + Debug.Assert(chars!=null, "[UTF8Encoding.GetChars]chars!=null"); + Debug.Assert(byteCount >=0, "[UTF8Encoding.GetChars]count >=0"); + Debug.Assert(charCount >=0, "[UTF8Encoding.GetChars]charCount >=0"); + Debug.Assert(bytes!=null, "[UTF8Encoding.GetChars]bytes!=null"); byte *pSrc = bytes; char *pTarget = chars; @@ -1438,7 +1439,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetChars // (don't have to check m_throwOnOverflow for chars, we always use all or none so always should be empty) - Contract.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, + Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[UTF8Encoding.GetChars]Expected empty fallback buffer at start"); } @@ -1473,7 +1474,7 @@ namespace System.Text if ((ch & FinalByte) == 0) { // Not at last byte yet - Contract.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0, + Debug.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0, "[UTF8Encoding.GetChars]Invariant volation"); if ((ch & SupplimentarySeq) != 0) { @@ -1536,14 +1537,14 @@ namespace System.Text { // Ran out of buffer space // Need to throw an exception? - Contract.Assert(pSrc >= bytes || pTarget == chars, + Debug.Assert(pSrc >= bytes || pTarget == chars, "[UTF8Encoding.GetChars]Expected to throw or remain in byte buffer after fallback"); fallback.InternalReset(); ThrowCharsOverflow(baseDecoder, pTarget == chars); ch = 0; break; } - Contract.Assert(pSrc >= bytes, + Debug.Assert(pSrc >= bytes, "[UTF8Encoding.GetChars]Expected invalid byte sequence to have remained within the byte array"); ch = 0; continue; @@ -1629,7 +1630,7 @@ namespace System.Text // Throw that we don't have enough room (pSrc could be < chars if we had started to process // a 4 byte sequence alredy) - Contract.Assert(pSrc >= bytes || pTarget == chars, + Debug.Assert(pSrc >= bytes || pTarget == chars, "[UTF8Encoding.GetChars]Expected pSrc to be within input buffer or throw due to no output]"); ThrowCharsOverflow(baseDecoder, pTarget == chars); @@ -1883,7 +1884,7 @@ namespace System.Text } #endif // FASTLOOP - Contract.Assert(pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetChars]pTarget <= pAllocatedBufferEnd"); + Debug.Assert(pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetChars]pTarget <= pAllocatedBufferEnd"); // no pending bits at this point ch = 0; @@ -1910,7 +1911,7 @@ namespace System.Text // This'll back us up the appropriate # of bytes if we didn't get anywhere if (!FallbackInvalidByteSequence(ref pSrc, ch, fallback, ref pTarget)) { - Contract.Assert(pSrc >= bytes || pTarget == chars, + Debug.Assert(pSrc >= bytes || pTarget == chars, "[UTF8Encoding.GetChars]Expected to throw or remain in byte buffer while flushing"); // Ran out of buffer space @@ -1918,7 +1919,7 @@ namespace System.Text fallback.InternalReset(); ThrowCharsOverflow(baseDecoder, pTarget == chars); } - Contract.Assert(pSrc >= bytes, + Debug.Assert(pSrc >= bytes, "[UTF8Encoding.GetChars]Expected flushing invalid byte sequence to have remained within the byte array"); ch = 0; } @@ -1929,7 +1930,7 @@ namespace System.Text // If we're storing flush data we expect all bits to be used or else // we're stuck in the middle of a conversion - Contract.Assert(!baseDecoder.MustFlush || ch == 0 || !baseDecoder.m_throwOnOverflow, + Debug.Assert(!baseDecoder.MustFlush || ch == 0 || !baseDecoder.m_throwOnOverflow, "[UTF8Encoding.GetChars]Expected no must flush or no left over bits or no throw on overflow."); // Remember our leftover bits. @@ -1940,7 +1941,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetChars // (don't have to check m_throwOnOverflow for chars) - Contract.Assert(fallback == null || fallback.Remaining == 0, + Debug.Assert(fallback == null || fallback.Remaining == 0, "[UTF8Encoding.GetChars]Expected empty fallback buffer at end"); return PtrDiff(pTarget, chars); diff --git a/src/mscorlib/src/System/Text/UnicodeEncoding.cs b/src/mscorlib/src/System/Text/UnicodeEncoding.cs index 43caf57..25255c3 100644 --- a/src/mscorlib/src/System/Text/UnicodeEncoding.cs +++ b/src/mscorlib/src/System/Text/UnicodeEncoding.cs @@ -12,6 +12,7 @@ namespace System.Text using System.Globalization; using System.Runtime.Serialization; using System.Security.Permissions; + using System.Diagnostics; using System.Diagnostics.Contracts; @@ -185,8 +186,8 @@ namespace System.Text internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder) { - Contract.Assert(chars!=null, "[UnicodeEncoding.GetByteCount]chars!=null"); - Contract.Assert(count >= 0, "[UnicodeEncoding.GetByteCount]count >=0"); + Debug.Assert(chars!=null, "[UnicodeEncoding.GetByteCount]chars!=null"); + Debug.Assert(count >= 0, "[UnicodeEncoding.GetByteCount]count >=0"); // Start by assuming each char gets 2 bytes int byteCount = count << 1; @@ -335,7 +336,7 @@ namespace System.Text // Unwind the current character, this should be safe because we // don't have leftover data in the fallback, so chars must have // advanced already. - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[UnicodeEncoding.GetByteCount]Expected chars to have advanced in unexpected high surrogate"); chars--; @@ -402,7 +403,7 @@ namespace System.Text // Rewind the current character, fallback previous character. // this should be safe because we don't have leftover data in the // fallback, so chars must have advanced already. - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[UnicodeEncoding.GetByteCount]Expected chars to have advanced when expected low surrogate"); chars--; @@ -468,7 +469,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetByteCount // (don't have to check m_throwOnOverflow for count) - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[UnicodeEncoding.GetByteCount]Expected empty fallback buffer at end"); // Don't remember fallbackBuffer.encoder for counting @@ -478,10 +479,10 @@ namespace System.Text internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { - Contract.Assert(chars!=null, "[UnicodeEncoding.GetBytes]chars!=null"); - Contract.Assert(byteCount >=0, "[UnicodeEncoding.GetBytes]byteCount >=0"); - Contract.Assert(charCount >=0, "[UnicodeEncoding.GetBytes]charCount >=0"); - Contract.Assert(bytes!=null, "[UnicodeEncoding.GetBytes]bytes!=null"); + Debug.Assert(chars!=null, "[UnicodeEncoding.GetBytes]chars!=null"); + Debug.Assert(byteCount >=0, "[UnicodeEncoding.GetBytes]byteCount >=0"); + Debug.Assert(charCount >=0, "[UnicodeEncoding.GetBytes]charCount >=0"); + Debug.Assert(bytes!=null, "[UnicodeEncoding.GetBytes]bytes!=null"); char charLeftOver = (char)0; char ch; @@ -685,7 +686,7 @@ namespace System.Text // Unwind the current character, this should be safe because we // don't have leftover data in the fallback, so chars must have // advanced already. - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[UnicodeEncoding.GetBytes]Expected chars to have advanced in unexpected high surrogate"); chars--; @@ -751,7 +752,7 @@ namespace System.Text { // If we don't have enough room, then either we should've advanced a while // or we should have bytes==byteStart and throw below - Contract.Assert(chars > charStart + 1 || bytes == byteStart, + Debug.Assert(chars > charStart + 1 || bytes == byteStart, "[UnicodeEncoding.GetBytes]Expected chars to have when no room to add surrogate pair"); chars-=2; // Didn't use either surrogate } @@ -780,7 +781,7 @@ namespace System.Text // Rewind the current character, fallback previous character. // this should be safe because we don't have leftover data in the // fallback, so chars must have advanced already. - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[UnicodeEncoding.GetBytes]Expected chars to have advanced after expecting low surrogate"); chars--; @@ -814,7 +815,7 @@ namespace System.Text { // Lonely charLeftOver (from previous call) would've been caught up above, // so this must be a case where we've already read an input char. - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[UnicodeEncoding.GetBytes]Expected chars to have advanced for failed fallback"); chars--; // Not using this char } @@ -882,10 +883,10 @@ namespace System.Text // Remember charLeftOver if we must, or clear it if we're flushing // (charLeftOver should be 0 if we're flushing) - Contract.Assert((encoder != null && !encoder.MustFlush) || charLeftOver == (char)0, + Debug.Assert((encoder != null && !encoder.MustFlush) || charLeftOver == (char)0, "[UnicodeEncoding.GetBytes] Expected no left over characters if flushing"); - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 || + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 || encoder == null || !encoder.m_throwOnOverflow, "[UnicodeEncoding.GetBytes]Expected empty fallback buffer if not converting"); @@ -897,8 +898,8 @@ namespace System.Text internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { - Contract.Assert(bytes!=null, "[UnicodeEncoding.GetCharCount]bytes!=null"); - Contract.Assert(count >= 0, "[UnicodeEncoding.GetCharCount]count >=0"); + Debug.Assert(bytes!=null, "[UnicodeEncoding.GetCharCount]bytes!=null"); + Debug.Assert(count >= 0, "[UnicodeEncoding.GetCharCount]count >=0"); UnicodeEncoding.Decoder decoder = (UnicodeEncoding.Decoder)baseDecoder; @@ -937,7 +938,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for count) - Contract.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, + Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[UnicodeEncoding.GetCharCount]Expected empty fallback buffer at start"); } @@ -1227,7 +1228,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for count) - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[UnicodeEncoding.GetCharCount]Expected empty fallback buffer at end"); return charCount; @@ -1236,10 +1237,10 @@ namespace System.Text internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder ) { - Contract.Assert(chars!=null, "[UnicodeEncoding.GetChars]chars!=null"); - Contract.Assert(byteCount >=0, "[UnicodeEncoding.GetChars]byteCount >=0"); - Contract.Assert(charCount >=0, "[UnicodeEncoding.GetChars]charCount >=0"); - Contract.Assert(bytes!=null, "[UnicodeEncoding.GetChars]bytes!=null"); + Debug.Assert(chars!=null, "[UnicodeEncoding.GetChars]chars!=null"); + Debug.Assert(byteCount >=0, "[UnicodeEncoding.GetChars]byteCount >=0"); + Debug.Assert(charCount >=0, "[UnicodeEncoding.GetChars]charCount >=0"); + Debug.Assert(bytes!=null, "[UnicodeEncoding.GetChars]bytes!=null"); UnicodeEncoding.Decoder decoder = (UnicodeEncoding.Decoder)baseDecoder; @@ -1255,7 +1256,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetChars // (don't have to check m_throwOnOverflow for chars) - Contract.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, + Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[UnicodeEncoding.GetChars]Expected empty fallback buffer at start"); } @@ -1413,7 +1414,7 @@ namespace System.Text { // couldn't fall back lonely surrogate // We either advanced bytes or chars should == charStart and throw below - Contract.Assert(bytes >= byteStart + 2 || chars == charStart, + Debug.Assert(bytes >= byteStart + 2 || chars == charStart, "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (bad surrogate)"); bytes-=2; // didn't use these 2 bytes fallbackBuffer.InternalReset(); @@ -1462,7 +1463,7 @@ namespace System.Text { // couldn't fall back lonely surrogate // We either advanced bytes or chars should == charStart and throw below - Contract.Assert(bytes >= byteStart + 2 || chars == charStart, + Debug.Assert(bytes >= byteStart + 2 || chars == charStart, "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (lonely surrogate)"); bytes-=2; // didn't use these 2 bytes fallbackBuffer.InternalReset(); @@ -1479,7 +1480,7 @@ namespace System.Text { // couldn't find room for this surrogate pair // We either advanced bytes or chars should == charStart and throw below - Contract.Assert(bytes >= byteStart + 2 || chars == charStart, + Debug.Assert(bytes >= byteStart + 2 || chars == charStart, "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (surrogate pair)"); bytes-=2; // didn't use these 2 bytes ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output @@ -1521,7 +1522,7 @@ namespace System.Text { // couldn't fall back high surrogate, or char that would be next // We either advanced bytes or chars should == charStart and throw below - Contract.Assert(bytes >= byteStart + 2 || chars == charStart, + Debug.Assert(bytes >= byteStart + 2 || chars == charStart, "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (no low surrogate)"); bytes-=2; // didn't use these 2 bytes fallbackBuffer.InternalReset(); @@ -1538,7 +1539,7 @@ namespace System.Text { // 2 bytes couldn't fall back // We either advanced bytes or chars should == charStart and throw below - Contract.Assert(bytes >= byteStart + 2 || chars == charStart, + Debug.Assert(bytes >= byteStart + 2 || chars == charStart, "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (normal)"); bytes-=2; // didn't use these bytes ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output @@ -1583,7 +1584,7 @@ namespace System.Text { // 2 bytes couldn't fall back // We either advanced bytes or chars should == charStart and throw below - Contract.Assert(bytes >= byteStart + 2 || chars == charStart, + Debug.Assert(bytes >= byteStart + 2 || chars == charStart, "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (decoder)"); bytes-=2; // didn't use these bytes if (lastByte >= 0) @@ -1636,7 +1637,7 @@ namespace System.Text // Remember our decoder if we must if (decoder != null) { - Contract.Assert((decoder.MustFlush == false) || ((lastChar == (char)0) && (lastByte == -1)), + Debug.Assert((decoder.MustFlush == false) || ((lastChar == (char)0) && (lastByte == -1)), "[UnicodeEncoding.GetChars] Expected no left over chars or bytes if flushing" // + " " + ((int)lastChar).ToString("X4") + " " + lastByte.ToString("X2") ); @@ -1651,7 +1652,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetChars // (don't have to check m_throwOnOverflow for count or chars) - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[UnicodeEncoding.GetChars]Expected empty fallback buffer at end"); return (int)(chars - charStart); diff --git a/src/mscorlib/src/System/Threading/AsyncLocal.cs b/src/mscorlib/src/System/Threading/AsyncLocal.cs index cd2fc4e..6ed1545 100644 --- a/src/mscorlib/src/System/Threading/AsyncLocal.cs +++ b/src/mscorlib/src/System/Threading/AsyncLocal.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; @@ -73,7 +74,7 @@ namespace System.Threading void IAsyncLocal.OnValueChanged(object previousValueObj, object currentValueObj, bool contextChanged) { - Contract.Assert(m_valueChangedHandler != null); + Debug.Assert(m_valueChangedHandler != null); T previousValue = previousValueObj == null ? default(T) : (T)previousValueObj; T currentValue = currentValueObj == null ? default(T) : (T)currentValueObj; m_valueChangedHandler(new AsyncLocalValueChangedArgs(previousValue, currentValue, contextChanged)); @@ -461,7 +462,7 @@ namespace System.Threading multi.UnsafeStore(index++, pair.Key, pair.Value); } } - Contract.Assert(index == MultiElementAsyncLocalValueMap.MaxMultiElements); + Debug.Assert(index == MultiElementAsyncLocalValueMap.MaxMultiElements); return multi; } else @@ -474,7 +475,7 @@ namespace System.Threading map[pair.Key] = pair.Value; } } - Contract.Assert(map.Count == count - 1); + Debug.Assert(map.Count == count - 1); return map; } } diff --git a/src/mscorlib/src/System/Threading/CancellationToken.cs b/src/mscorlib/src/System/Threading/CancellationToken.cs index 4009982..fc76798 100644 --- a/src/mscorlib/src/System/Threading/CancellationToken.cs +++ b/src/mscorlib/src/System/Threading/CancellationToken.cs @@ -8,9 +8,9 @@ #pragma warning disable 0420 // turn off 'a reference to a volatile field will not be treated as volatile' during CAS. using System; -using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Permissions; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime; using System.Runtime.CompilerServices; @@ -167,7 +167,7 @@ namespace System.Threading private static void ActionToActionObjShunt(object obj) { Action action = obj as Action; - Contract.Assert(action != null, "Expected an Action here"); + Debug.Assert(action != null, "Expected an Action here"); action(); } diff --git a/src/mscorlib/src/System/Threading/CancellationTokenSource.cs b/src/mscorlib/src/System/Threading/CancellationTokenSource.cs index a0b82db..d1f0039 100644 --- a/src/mscorlib/src/System/Threading/CancellationTokenSource.cs +++ b/src/mscorlib/src/System/Threading/CancellationTokenSource.cs @@ -11,6 +11,7 @@ using System.Security; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Security.Permissions; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime; @@ -629,7 +630,7 @@ namespace System.Threading } // the CancellationToken has already checked that the token is cancelable before calling this method. - Contract.Assert(CanBeCanceled, "Cannot register for uncancelable token src"); + Debug.Assert(CanBeCanceled, "Cannot register for uncancelable token src"); // if not canceled, register the event handlers // if canceled already, run the callback synchronously @@ -730,7 +731,7 @@ namespace System.Threading // - After transition, no more delegates will be added to the // - list of handlers, and hence it can be consumed and cleared at leisure by ExecuteCallbackHandlers. ExecuteCallbackHandlers(throwOnFirstException); - Contract.Assert(IsCancellationCompleted, "Expected cancellation to have finished"); + Debug.Assert(IsCancellationCompleted, "Expected cancellation to have finished"); } } @@ -742,8 +743,8 @@ namespace System.Threading /// private void ExecuteCallbackHandlers(bool throwOnFirstException) { - Contract.Assert(IsCancellationRequested, "ExecuteCallbackHandlers should only be called after setting IsCancellationRequested->true"); - Contract.Assert(ThreadIDExecutingCallbacks != -1, "ThreadIDExecutingCallbacks should have been set."); + Debug.Assert(IsCancellationRequested, "ExecuteCallbackHandlers should only be called after setting IsCancellationRequested->true"); + Debug.Assert(ThreadIDExecutingCallbacks != -1, "ThreadIDExecutingCallbacks should have been set."); // Design decision: call the delegates in LIFO order so that callbacks fire 'deepest first'. // This is intended to help with nesting scenarios so that child enlisters cancel before their parents. @@ -791,7 +792,7 @@ namespace System.Threading var wsc = m_executingCallback as CancellationCallbackInfo.WithSyncContext; if (wsc != null) { - Contract.Assert(wsc.TargetSyncContext != null, "Should only have derived CCI if non-null SyncCtx"); + Debug.Assert(wsc.TargetSyncContext != null, "Should only have derived CCI if non-null SyncCtx"); wsc.TargetSyncContext.Send(CancellationCallbackCoreWork_OnSyncContext, args); // CancellationCallbackCoreWork_OnSyncContext may have altered ThreadIDExecutingCallbacks, so reset it. ThreadIDExecutingCallbacks = Thread.CurrentThread.ManagedThreadId; @@ -828,7 +829,7 @@ namespace System.Threading if (exceptionList != null) { - Contract.Assert(exceptionList.Count > 0, "Expected exception count > 0"); + Debug.Assert(exceptionList.Count > 0, "Expected exception count > 0"); throw new AggregateException(exceptionList); } } @@ -1060,7 +1061,7 @@ namespace System.Threading private static void ExecutionContextCallback(object obj) { CancellationCallbackInfo callbackInfo = obj as CancellationCallbackInfo; - Contract.Assert(callbackInfo != null); + Debug.Assert(callbackInfo != null); callbackInfo.Callback(callbackInfo.StateForCallback); } } @@ -1144,14 +1145,14 @@ namespace System.Threading start = 0; curr.m_freeCount--; // Too many free elements; fix up. } - Contract.Assert(start >= 0 && start < c, "start is outside of bounds"); + Debug.Assert(start >= 0 && start < c, "start is outside of bounds"); // Now walk the array until we find a free slot (or reach the end). for (int i = 0; i < c; i++) { // If the slot is null, try to CAS our element into it. int tryIndex = (start + i) % c; - Contract.Assert(tryIndex >= 0 && tryIndex < curr.m_elements.Length, "tryIndex is outside of bounds"); + Debug.Assert(tryIndex >= 0 && tryIndex < curr.m_elements.Length, "tryIndex is outside of bounds"); if (curr.m_elements[tryIndex] == null && Interlocked.CompareExchange(ref curr.m_elements[tryIndex], element, null) == null) { @@ -1190,8 +1191,8 @@ namespace System.Threading internal SparselyPopulatedArrayAddInfo(SparselyPopulatedArrayFragment source, int index) { - Contract.Assert(source != null); - Contract.Assert(index >= 0 && index < source.Length); + Debug.Assert(source != null); + Debug.Assert(index >= 0 && index < source.Length); m_source = source; m_index = index; } diff --git a/src/mscorlib/src/System/Threading/CountdownEvent.cs b/src/mscorlib/src/System/Threading/CountdownEvent.cs index 2e62216..f984fb3 100644 --- a/src/mscorlib/src/System/Threading/CountdownEvent.cs +++ b/src/mscorlib/src/System/Threading/CountdownEvent.cs @@ -11,10 +11,10 @@ // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; -using System.Diagnostics; using System.Security.Permissions; using System.Runtime.InteropServices; using System.Threading; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Threading @@ -186,7 +186,7 @@ namespace System.Threading public bool Signal() { ThrowIfDisposed(); - Contract.Assert(m_event != null); + Debug.Assert(m_event != null); if (m_currentCount <= 0) { @@ -233,7 +233,7 @@ namespace System.Threading } ThrowIfDisposed(); - Contract.Assert(m_event != null); + Debug.Assert(m_event != null); int observedCount; SpinWait spin = new SpinWait(); @@ -267,7 +267,7 @@ namespace System.Threading return true; } - Contract.Assert(m_currentCount >= 0, "latch was decremented below zero"); + Debug.Assert(m_currentCount >= 0, "latch was decremented below zero"); return false; } diff --git a/src/mscorlib/src/System/Threading/ExecutionContext.cs b/src/mscorlib/src/System/Threading/ExecutionContext.cs index b5c92f7..5ea9942 100644 --- a/src/mscorlib/src/System/Threading/ExecutionContext.cs +++ b/src/mscorlib/src/System/Threading/ExecutionContext.cs @@ -23,6 +23,7 @@ namespace System.Threading using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; @@ -36,7 +37,7 @@ namespace System.Threading internal void Undo(Thread currentThread) { - Contract.Assert(currentThread == Thread.CurrentThread); + Debug.Assert(currentThread == Thread.CurrentThread); // The common case is that these have not changed, so avoid the cost of a write if not needed. if (currentThread.SynchronizationContext != m_sc) @@ -106,7 +107,7 @@ namespace System.Threading private ExecutionContext ShallowClone(bool isFlowSuppressed) { - Contract.Assert(isFlowSuppressed != m_isFlowSuppressed); + Debug.Assert(isFlowSuppressed != m_isFlowSuppressed); if (!isFlowSuppressed && m_localValues == Default.m_localValues && @@ -181,7 +182,7 @@ namespace System.Threading internal static void Restore(Thread currentThread, ExecutionContext executionContext) { - Contract.Assert(currentThread == Thread.CurrentThread); + Debug.Assert(currentThread == Thread.CurrentThread); ExecutionContext previous = currentThread.ExecutionContext ?? Default; currentThread.ExecutionContext = executionContext; @@ -198,7 +199,7 @@ namespace System.Threading static internal void EstablishCopyOnWriteScope(Thread currentThread, ref ExecutionContextSwitcher ecsw) { - Contract.Assert(currentThread == Thread.CurrentThread); + Debug.Assert(currentThread == Thread.CurrentThread); ecsw.m_ec = currentThread.ExecutionContext; ecsw.m_sc = currentThread.SynchronizationContext; @@ -207,9 +208,9 @@ namespace System.Threading [HandleProcessCorruptedStateExceptions] private static void OnContextChanged(ExecutionContext previous, ExecutionContext current) { - Contract.Assert(previous != null); - Contract.Assert(current != null); - Contract.Assert(previous != current); + Debug.Assert(previous != null); + Debug.Assert(current != null); + Debug.Assert(previous != current); foreach (IAsyncLocal local in previous.m_localChangeNotifications) { @@ -281,7 +282,7 @@ namespace System.Threading { if (hadPreviousValue) { - Contract.Assert(Array.IndexOf(newChangeNotifications, local) >= 0); + Debug.Assert(Array.IndexOf(newChangeNotifications, local) >= 0); } else { @@ -361,7 +362,7 @@ namespace System.Threading internal void Initialize(Thread currentThread) { - Contract.Assert(currentThread == Thread.CurrentThread); + Debug.Assert(currentThread == Thread.CurrentThread); _thread = currentThread; } diff --git a/src/mscorlib/src/System/Threading/LazyInitializer.cs b/src/mscorlib/src/System/Threading/LazyInitializer.cs index c8e74e3..36f2cec 100644 --- a/src/mscorlib/src/System/Threading/LazyInitializer.cs +++ b/src/mscorlib/src/System/Threading/LazyInitializer.cs @@ -12,6 +12,7 @@ using System.Security.Permissions; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Threading { @@ -149,7 +150,7 @@ namespace System.Threading } Interlocked.CompareExchange(ref target, value, null); - Contract.Assert(target != null); + Debug.Assert(target != null); return target; } diff --git a/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs b/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs index a95e368..dc83fac 100644 --- a/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs +++ b/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs @@ -13,10 +13,10 @@ // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; -using System.Diagnostics; using System.Security.Permissions; using System.Threading; using System.Runtime.InteropServices; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Threading @@ -144,8 +144,8 @@ namespace System.Threading private set { - Contract.Assert(value >= 0, "SpinCount is a restricted-width integer. The value supplied is outside the legal range."); - Contract.Assert(value <= SpinCountState_MaxValue, "SpinCount is a restricted-width integer. The value supplied is outside the legal range."); + Debug.Assert(value >= 0, "SpinCount is a restricted-width integer. The value supplied is outside the legal range."); + Debug.Assert(value <= SpinCountState_MaxValue, "SpinCount is a restricted-width integer. The value supplied is outside the legal range."); // Don't worry about thread safety because it's set one time from the constructor m_combinedState = (m_combinedState & ~SpinCountState_BitMask) | (value << SpinCountState_ShiftCount); } @@ -164,7 +164,7 @@ namespace System.Threading set { //setting to <0 would indicate an internal flaw, hence Assert is appropriate. - Contract.Assert(value >= 0, "NumWaiters should never be less than zero. This indicates an internal error."); + Debug.Assert(value >= 0, "NumWaiters should never be less than zero. This indicates an internal error."); // it is possible for the max number of waiters to be exceeded via user-code, hence we use a real exception here. if (value >= NumWaitersState_MaxValue) @@ -242,8 +242,8 @@ namespace System.Threading this.m_combinedState = initialState ? (1 << SignalledState_ShiftCount) : 0; //the spinCount argument has been validated by the ctors. //but we now sanity check our predefined constants. - Contract.Assert(DEFAULT_SPIN_SP >= 0, "Internal error - DEFAULT_SPIN_SP is outside the legal range."); - Contract.Assert(DEFAULT_SPIN_SP <= SpinCountState_MaxValue, "Internal error - DEFAULT_SPIN_SP is outside the legal range."); + Debug.Assert(DEFAULT_SPIN_SP >= 0, "Internal error - DEFAULT_SPIN_SP is outside the legal range."); + Debug.Assert(DEFAULT_SPIN_SP <= SpinCountState_MaxValue, "Internal error - DEFAULT_SPIN_SP is outside the legal range."); SpinCount = PlatformHelper.IsSingleProcessor ? DEFAULT_SPIN_SP : spinCount; @@ -295,7 +295,7 @@ namespace System.Threading bool currentIsSet = IsSet; if (currentIsSet != preInitializeIsSet) { - Contract.Assert(currentIsSet, + Debug.Assert(currentIsSet, "The only safe concurrent transition is from unset->set: detected set->unset."); // We saw it as unsignaled, but it has since become set. @@ -337,7 +337,7 @@ namespace System.Threading // If there are waiting threads, we need to pulse them. if (Waiters > 0) { - Contract.Assert(m_lock != null); //if waiters>0, then m_lock has already been created. + Debug.Assert(m_lock != null); //if waiters>0, then m_lock has already been created. lock (m_lock) { @@ -738,8 +738,8 @@ namespace System.Threading private static void CancellationTokenCallback(object obj) { ManualResetEventSlim mre = obj as ManualResetEventSlim; - Contract.Assert(mre != null, "Expected a ManualResetEventSlim"); - Contract.Assert(mre.m_lock != null); //the lock should have been created before this callback is registered for use. + Debug.Assert(mre != null, "Expected a ManualResetEventSlim"); + Debug.Assert(mre.m_lock != null); //the lock should have been created before this callback is registered for use. lock (mre.m_lock) { Monitor.PulseAll(mre.m_lock); // awaken all waiters @@ -759,7 +759,7 @@ namespace System.Threading { SpinWait sw = new SpinWait(); - Contract.Assert((newBits | updateBitsMask) == updateBitsMask, "newBits do not fall within the updateBitsMask."); + Debug.Assert((newBits | updateBitsMask) == updateBitsMask, "newBits do not fall within the updateBitsMask."); do { diff --git a/src/mscorlib/src/System/Threading/Monitor.cs b/src/mscorlib/src/System/Threading/Monitor.cs index 610be48..bb0c592 100644 --- a/src/mscorlib/src/System/Threading/Monitor.cs +++ b/src/mscorlib/src/System/Threading/Monitor.cs @@ -24,6 +24,7 @@ namespace System.Threading { using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; [HostProtection(Synchronization=true, ExternalThreading=true)] @@ -53,7 +54,7 @@ namespace System.Threading { ThrowLockTakenException(); ReliableEnter(obj, ref lockTaken); - Contract.Assert(lockTaken); + Debug.Assert(lockTaken); } private static void ThrowLockTakenException() diff --git a/src/mscorlib/src/System/Threading/Mutex.cs b/src/mscorlib/src/System/Threading/Mutex.cs index 5126e22..dba5df0 100644 --- a/src/mscorlib/src/System/Threading/Mutex.cs +++ b/src/mscorlib/src/System/Threading/Mutex.cs @@ -24,6 +24,7 @@ namespace System.Threading using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Security; + using System.Diagnostics; using System.Diagnostics.Contracts; [HostProtection(Synchronization=true, ExternalThreading=true)] @@ -107,7 +108,7 @@ namespace System.Threading [PrePrepareMethod] internal MutexTryCodeHelper(bool initiallyOwned,MutexCleanupInfo cleanupInfo, String name, Win32Native.SECURITY_ATTRIBUTES secAttrs, Mutex mutex) { - Contract.Assert(name == null || name.Length != 0); + Debug.Assert(name == null || name.Length != 0); m_initiallyOwned = initiallyOwned; m_cleanupInfo = cleanupInfo; diff --git a/src/mscorlib/src/System/Threading/Overlapped.cs b/src/mscorlib/src/System/Threading/Overlapped.cs index a04a476..2b192c7 100644 --- a/src/mscorlib/src/System/Threading/Overlapped.cs +++ b/src/mscorlib/src/System/Threading/Overlapped.cs @@ -33,6 +33,7 @@ namespace System.Threading using System.Security; using System.Security.Permissions; using System.Runtime.ConstrainedExecution; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Collections.Concurrent; @@ -83,7 +84,7 @@ namespace System.Threading static internal void IOCompletionCallback_Context(Object state) { _IOCompletionCallback helper = (_IOCompletionCallback)state; - Contract.Assert(helper != null,"_IOCompletionCallback cannot be null"); + Debug.Assert(helper != null,"_IOCompletionCallback cannot be null"); helper._ioCompletionCallback(helper._errorCode, helper._numBytes, helper._pOVERLAP); } @@ -162,10 +163,10 @@ namespace System.Threading m_iocbHelper = null; m_overlapped = null; m_userObject = null; - Contract.Assert(m_pinSelf.IsNull(), "OverlappedData has not been freed: m_pinSelf"); + Debug.Assert(m_pinSelf.IsNull(), "OverlappedData has not been freed: m_pinSelf"); m_pinSelf = (IntPtr)0; m_userObjectInternal = (IntPtr)0; - Contract.Assert(m_AppDomainId == 0 || m_AppDomainId == AppDomain.CurrentDomain.Id, "OverlappedData is not in the current domain"); + Debug.Assert(m_AppDomainId == 0 || m_AppDomainId == AppDomain.CurrentDomain.Id, "OverlappedData is not in the current domain"); m_AppDomainId = 0; m_nativeOverlapped.EventHandle = (IntPtr)0; m_isArray = 0; diff --git a/src/mscorlib/src/System/Threading/Semaphore.cs b/src/mscorlib/src/System/Threading/Semaphore.cs index ca6008c..1eac4aa 100644 --- a/src/mscorlib/src/System/Threading/Semaphore.cs +++ b/src/mscorlib/src/System/Threading/Semaphore.cs @@ -4,6 +4,7 @@ using Microsoft.Win32; using Microsoft.Win32.SafeHandles; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.IO; using System.Runtime.InteropServices; @@ -95,9 +96,9 @@ namespace System.Threading #endif } - Contract.Assert(initialCount >= 0); - Contract.Assert(maximumCount >= 1); - Contract.Assert(initialCount <= maximumCount); + Debug.Assert(initialCount >= 0); + Debug.Assert(maximumCount >= 1); + Debug.Assert(initialCount <= maximumCount); return Win32Native.CreateSemaphore(null, initialCount, maximumCount, name); } diff --git a/src/mscorlib/src/System/Threading/SemaphoreSlim.cs b/src/mscorlib/src/System/Threading/SemaphoreSlim.cs index ef120f8..a04e43d 100644 --- a/src/mscorlib/src/System/Threading/SemaphoreSlim.cs +++ b/src/mscorlib/src/System/Threading/SemaphoreSlim.cs @@ -92,7 +92,7 @@ namespace System.Threading void IThreadPoolWorkItem.ExecuteWorkItem() { bool setSuccessfully = TrySetResult(true); - Contract.Assert(setSuccessfully, "Should have been able to complete task"); + Debug.Assert(setSuccessfully, "Should have been able to complete task"); } void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae) { /* nop */ } @@ -370,7 +370,7 @@ namespace System.Threading // then block on (once we've released the lock). if (m_asyncHead != null) { - Contract.Assert(m_asyncTail != null, "tail should not be null if head isn't"); + Debug.Assert(m_asyncTail != null, "tail should not be null if head isn't"); asyncWaitTask = WaitAsync(millisecondsTimeout, cancellationToken); } // There are no async waiters, so we can proceed with normal synchronous waiting. @@ -402,7 +402,7 @@ namespace System.Threading // defer to synchronous waiters in priority, which means that if it's possible an asynchronous // waiter didn't get released because a synchronous waiter was present, we need to ensure // that synchronous waiter succeeds so that they have a chance to release. - Contract.Assert(!waitSuccessful || m_currentCount > 0, + Debug.Assert(!waitSuccessful || m_currentCount > 0, "If the wait was successful, there should be count available."); if (m_currentCount > 0) { @@ -636,7 +636,7 @@ namespace System.Threading // the semaphore or when the timeout expired or cancellation was requested. else { - Contract.Assert(m_currentCount == 0, "m_currentCount should never be negative"); + Debug.Assert(m_currentCount == 0, "m_currentCount should never be negative"); var asyncWaiter = CreateAndAddAsyncWaiter(); return (millisecondsTimeout == Timeout.Infinite && !cancellationToken.CanBeCanceled) ? asyncWaiter : @@ -649,7 +649,7 @@ namespace System.Threading /// The created task. private TaskNode CreateAndAddAsyncWaiter() { - Contract.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held"); + Debug.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held"); // Create the task var task = new TaskNode(); @@ -657,13 +657,13 @@ namespace System.Threading // Add it to the linked list if (m_asyncHead == null) { - Contract.Assert(m_asyncTail == null, "If head is null, so too should be tail"); + Debug.Assert(m_asyncTail == null, "If head is null, so too should be tail"); m_asyncHead = task; m_asyncTail = task; } else { - Contract.Assert(m_asyncTail != null, "If head is not null, neither should be tail"); + Debug.Assert(m_asyncTail != null, "If head is not null, neither should be tail"); m_asyncTail.Next = task; task.Prev = m_asyncTail; m_asyncTail = task; @@ -679,7 +679,7 @@ namespace System.Threading private bool RemoveAsyncWaiter(TaskNode task) { Contract.Requires(task != null, "Expected non-null task"); - Contract.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held"); + Debug.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held"); // Is the task in the list? To be in the list, either it's the head or it has a predecessor that's in the list. bool wasInList = m_asyncHead == task || task.Prev != null; @@ -689,7 +689,7 @@ namespace System.Threading if (task.Prev != null) task.Prev.Next = task.Next; if (m_asyncHead == task) m_asyncHead = task.Next; if (m_asyncTail == task) m_asyncTail = task.Prev; - Contract.Assert((m_asyncHead == null) == (m_asyncTail == null), "Head is null iff tail is null"); + Debug.Assert((m_asyncHead == null) == (m_asyncTail == null), "Head is null iff tail is null"); // Make sure not to leak task.Next = task.Prev = null; @@ -704,8 +704,8 @@ namespace System.Threading /// The task to return to the caller. private async Task WaitUntilCountOrTimeoutAsync(TaskNode asyncWaiter, int millisecondsTimeout, CancellationToken cancellationToken) { - Contract.Assert(asyncWaiter != null, "Waiter should have been constructed"); - Contract.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held"); + Debug.Assert(asyncWaiter != null, "Waiter should have been constructed"); + Debug.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held"); // Wait until either the task is completed, timeout occurs, or cancellation is requested. // We need to ensure that the Task.Delay task is appropriately cleaned up if the await @@ -810,7 +810,7 @@ namespace System.Threading // waits are canceled, but the wait code path will handle that. if (m_asyncHead != null) { - Contract.Assert(m_asyncTail != null, "tail should not be null if head isn't null"); + Debug.Assert(m_asyncTail != null, "tail should not be null if head isn't null"); int maxAsyncToRelease = currentCount - waitCount; while (maxAsyncToRelease > 0 && m_asyncHead != null) { @@ -893,7 +893,7 @@ namespace System.Threading private static void CancellationTokenCanceledEventHandler(object obj) { SemaphoreSlim semaphore = obj as SemaphoreSlim; - Contract.Assert(semaphore != null, "Expected a SemaphoreSlim"); + Debug.Assert(semaphore != null, "Expected a SemaphoreSlim"); lock (semaphore.m_lockObj) { Monitor.PulseAll(semaphore.m_lockObj); //wake up all waiters. diff --git a/src/mscorlib/src/System/Threading/SpinLock.cs b/src/mscorlib/src/System/Threading/SpinLock.cs index fbd90a4..998ea38 100644 --- a/src/mscorlib/src/System/Threading/SpinLock.cs +++ b/src/mscorlib/src/System/Threading/SpinLock.cs @@ -12,11 +12,11 @@ // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; -using System.Diagnostics; using System.Security.Permissions; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Threading @@ -122,7 +122,7 @@ namespace System.Threading if (!enableThreadOwnerTracking) { m_owner |= LOCK_ID_DISABLE_MASK; - Contract.Assert(!IsThreadOwnerTrackingEnabled, "property should be false by now"); + Debug.Assert(!IsThreadOwnerTrackingEnabled, "property should be false by now"); } } @@ -352,7 +352,7 @@ namespace System.Threading int newOwner = (observedOwner & WAITERS_MASK) == 0 ? // Gets the number of waiters, if zero observedOwner | 1 // don't decrement it. just set the lock bit, it is zzero because a previous call of Exit(false) ehich corrupted the waiters : (observedOwner - 2) | 1; // otherwise decrement the waiters and set the lock bit - Contract.Assert((newOwner & WAITERS_MASK) >= 0); + Debug.Assert((newOwner & WAITERS_MASK) >= 0); if (Interlocked.CompareExchange(ref m_owner, newOwner, observedOwner, ref lockTaken) == observedOwner) { @@ -380,7 +380,7 @@ namespace System.Threading int newOwner = (observedOwner & WAITERS_MASK) == 0 ? // Gets the number of waiters, if zero observedOwner | 1 // don't decrement it. just set the lock bit, it is zzero because a previous call of Exit(false) ehich corrupted the waiters : (observedOwner - 2) | 1; // otherwise decrement the waiters and set the lock bit - Contract.Assert((newOwner & WAITERS_MASK) >= 0); + Debug.Assert((newOwner & WAITERS_MASK) >= 0); if (Interlocked.CompareExchange(ref m_owner, newOwner, observedOwner, ref lockTaken) == observedOwner) { @@ -427,7 +427,7 @@ namespace System.Threading if ((observedOwner & WAITERS_MASK) == 0) return; // don't decrement the waiters if it's corrupted by previous call of Exit(false) if (Interlocked.CompareExchange(ref m_owner, observedOwner - 2, observedOwner) == observedOwner) { - Contract.Assert(!IsThreadOwnerTrackingEnabled); // Make sure the waiters never be negative which will cause the thread tracking bit to be flipped + Debug.Assert(!IsThreadOwnerTrackingEnabled); // Make sure the waiters never be negative which will cause the thread tracking bit to be flipped break; } spinner.SpinOnce(); @@ -440,7 +440,7 @@ namespace System.Threading /// private void ContinueTryEnterWithThreadTracking(int millisecondsTimeout, uint startTime, ref bool lockTaken) { - Contract.Assert(IsThreadOwnerTrackingEnabled); + Debug.Assert(IsThreadOwnerTrackingEnabled); int lockUnowned = 0; // We are using thread IDs to mark ownership. Snap the thread ID and check for recursion. diff --git a/src/mscorlib/src/System/Threading/SpinWait.cs b/src/mscorlib/src/System/Threading/SpinWait.cs index cf10fef..da913ea 100644 --- a/src/mscorlib/src/System/Threading/SpinWait.cs +++ b/src/mscorlib/src/System/Threading/SpinWait.cs @@ -14,6 +14,7 @@ using System; using System.Runtime.ConstrainedExecution; using System.Security.Permissions; using System.Threading; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; @@ -193,7 +194,7 @@ namespace System.Threading #endif SpinUntil(condition, Timeout.Infinite); #if DEBUG - Contract.Assert(result); + Debug.Assert(result); #endif } @@ -300,7 +301,7 @@ namespace System.Threading s_lastProcessorCountRefreshTicks = now; } - Contract.Assert(procCount > 0 && procCount <= 64, + Debug.Assert(procCount > 0 && procCount <= 64, "Processor count not within the expected range (1 - 64)."); return procCount; @@ -341,7 +342,7 @@ namespace System.Threading public static int UpdateTimeOut(uint startTime, int originalWaitMillisecondsTimeout) { // The function must be called in case the time out is not infinite - Contract.Assert(originalWaitMillisecondsTimeout != Timeout.Infinite); + Debug.Assert(originalWaitMillisecondsTimeout != Timeout.Infinite); uint elapsedMilliseconds = (GetTime() - startTime); diff --git a/src/mscorlib/src/System/Threading/SynchronizationContext.cs b/src/mscorlib/src/System/Threading/SynchronizationContext.cs index 737ef7d..5531597 100644 --- a/src/mscorlib/src/System/Threading/SynchronizationContext.cs +++ b/src/mscorlib/src/System/Threading/SynchronizationContext.cs @@ -24,6 +24,7 @@ namespace System.Threading using System.Runtime.ConstrainedExecution; using System.Reflection; using System.Security; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; @@ -207,8 +208,8 @@ namespace System.Threading #if FEATURE_APPX private static SynchronizationContext GetWinRTContext() { - Contract.Assert(Environment.IsWinRTSupported); - Contract.Assert(AppDomain.IsAppXModel()); + Debug.Assert(Environment.IsWinRTSupported); + Debug.Assert(AppDomain.IsAppXModel()); // // We call into the VM to get the dispatcher. This is because: diff --git a/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs b/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs index a356412..ec7c5aa 100644 --- a/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs +++ b/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs @@ -152,7 +152,7 @@ namespace System.Threading.Tasks s_TracerFactory = (WFD.IAsyncCausalityTracerStatics)factory; EventRegistrationToken token = s_TracerFactory.add_TracingStatusChanged(new EventHandler(TracingStatusChangedHandler)); - Contract.Assert(token != default(EventRegistrationToken), "EventRegistrationToken is null"); + Debug.Assert(token != default(EventRegistrationToken), "EventRegistrationToken is null"); } catch (Exception ex) { diff --git a/src/mscorlib/src/System/Threading/Tasks/BeginEndAwaitableAdapter.cs b/src/mscorlib/src/System/Threading/Tasks/BeginEndAwaitableAdapter.cs index fb00789..71eb787 100644 --- a/src/mscorlib/src/System/Threading/Tasks/BeginEndAwaitableAdapter.cs +++ b/src/mscorlib/src/System/Threading/Tasks/BeginEndAwaitableAdapter.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.IO; using System.Runtime.CompilerServices; @@ -62,9 +63,9 @@ internal sealed class BeginEndAwaitableAdapter : ICriticalNotifyCompletion { /// It expects that an BeginEndAwaitableAdapter instance was supplied to the APM Begin method as the object state. public readonly static AsyncCallback Callback = (asyncResult) => { - Contract.Assert(asyncResult != null); - Contract.Assert(asyncResult.IsCompleted); - Contract.Assert(asyncResult.AsyncState is BeginEndAwaitableAdapter); + Debug.Assert(asyncResult != null); + Debug.Assert(asyncResult.IsCompleted); + Debug.Assert(asyncResult.AsyncState is BeginEndAwaitableAdapter); // Get the adapter object supplied as the "object state" to the Begin method BeginEndAwaitableAdapter adapter = (BeginEndAwaitableAdapter) asyncResult.AsyncState; @@ -81,7 +82,7 @@ internal sealed class BeginEndAwaitableAdapter : ICriticalNotifyCompletion { Action continuation = Interlocked.Exchange(ref adapter._continuation, CALLBACK_RAN); if (continuation != null) { - Contract.Assert(continuation != CALLBACK_RAN); + Debug.Assert(continuation != CALLBACK_RAN); continuation(); } }; @@ -110,7 +111,7 @@ internal sealed class BeginEndAwaitableAdapter : ICriticalNotifyCompletion { /// The continuation. public void UnsafeOnCompleted(Action continuation) { - Contract.Assert(continuation != null); + Debug.Assert(continuation != null); OnCompleted(continuation); } @@ -119,7 +120,7 @@ internal sealed class BeginEndAwaitableAdapter : ICriticalNotifyCompletion { /// The continuation. public void OnCompleted(Action continuation) { - Contract.Assert(continuation != null); + Debug.Assert(continuation != null); // If the continuation field is null, then set it to be the target continuation // so that when the operation completes, it'll invoke the continuation. If it's non-null, @@ -138,7 +139,7 @@ internal sealed class BeginEndAwaitableAdapter : ICriticalNotifyCompletion { /// The IAsyncResult for the operation. public IAsyncResult GetResult() { - Contract.Assert(_asyncResult != null && _asyncResult.IsCompleted); + Debug.Assert(_asyncResult != null && _asyncResult.IsCompleted); // Get the IAsyncResult IAsyncResult result = _asyncResult; diff --git a/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs b/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs index 4086191..48e0f4e 100644 --- a/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs +++ b/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs @@ -213,13 +213,13 @@ namespace System.Threading.Tasks ThreadPool.QueueUserWorkItem(state => { var localCs = (CompletionState)state; // don't use 'cs', as it'll force a closure - Contract.Assert(!localCs.Task.IsCompleted, "Completion should only happen once."); + Debug.Assert(!localCs.Task.IsCompleted, "Completion should only happen once."); var exceptions = localCs.m_exceptions; bool success = (exceptions != null && exceptions.Count > 0) ? localCs.TrySetException(exceptions) : localCs.TrySetResult(default(VoidTaskResult)); - Contract.Assert(success, "Expected to complete completion task."); + Debug.Assert(success, "Expected to complete completion task."); }, cs); } } @@ -336,7 +336,7 @@ namespace System.Threading.Tasks // Check to see if all tasks have completed and if completion has been requested. CleanupStateIfCompletingAndQuiesced(); } - else Contract.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing count must be the sentinel if it's not >= 0."); + else Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing count must be the sentinel if it's not >= 0."); } /// @@ -351,7 +351,7 @@ namespace System.Threading.Tasks try { // Note that we're processing exclusive tasks on the current thread - Contract.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId), + Debug.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId), "This thread should not yet be involved in this pair's processing."); m_threadProcessingMapping[Thread.CurrentThread.ManagedThreadId] = ProcessingMode.ProcessingExclusiveTask; @@ -372,7 +372,7 @@ namespace System.Threading.Tasks // We're no longer processing exclusive tasks on the current thread ProcessingMode currentMode; m_threadProcessingMapping.TryRemove(Thread.CurrentThread.ManagedThreadId, out currentMode); - Contract.Assert(currentMode == ProcessingMode.ProcessingExclusiveTask, + Debug.Assert(currentMode == ProcessingMode.ProcessingExclusiveTask, "Somehow we ended up escaping exclusive mode."); lock (ValueLock) @@ -382,7 +382,7 @@ namespace System.Threading.Tasks // There might be more concurrent tasks available, for example, if concurrent tasks arrived // after we exited the loop, or if we exited the loop while concurrent tasks were still // available but we hit our maxItemsPerTask limit. - Contract.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing mode should not have deviated from exclusive."); + Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing mode should not have deviated from exclusive."); m_processingCount = 0; ProcessAsyncIfNecessary(true); } @@ -400,7 +400,7 @@ namespace System.Threading.Tasks try { // Note that we're processing concurrent tasks on the current thread - Contract.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId), + Debug.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId), "This thread should not yet be involved in this pair's processing."); m_threadProcessingMapping[Thread.CurrentThread.ManagedThreadId] = ProcessingMode.ProcessingConcurrentTasks; @@ -432,7 +432,7 @@ namespace System.Threading.Tasks // We're no longer processing concurrent tasks on the current thread ProcessingMode currentMode; m_threadProcessingMapping.TryRemove(Thread.CurrentThread.ManagedThreadId, out currentMode); - Contract.Assert(currentMode == ProcessingMode.ProcessingConcurrentTasks, + Debug.Assert(currentMode == ProcessingMode.ProcessingConcurrentTasks, "Somehow we ended up escaping concurrent mode."); lock (ValueLock) @@ -442,7 +442,7 @@ namespace System.Threading.Tasks // There might be more concurrent tasks available, for example, if concurrent tasks arrived // after we exited the loop, or if we exited the loop while concurrent tasks were still // available but we hit our maxItemsPerTask limit. - Contract.Assert(m_processingCount > 0, "The procesing mode should not have deviated from concurrent."); + Debug.Assert(m_processingCount > 0, "The procesing mode should not have deviated from concurrent."); if (m_processingCount > 0) --m_processingCount; ProcessAsyncIfNecessary(true); } @@ -526,7 +526,7 @@ namespace System.Threading.Tasks /// The task to be queued. protected internal override void QueueTask(Task task) { - Contract.Assert(task != null, "Infrastructure should have provided a non-null task."); + Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); lock (m_pair.ValueLock) { // If the scheduler has already had completion requested, no new work is allowed to be scheduled @@ -542,7 +542,7 @@ namespace System.Threading.Tasks /// The task to be executed. internal void ExecuteTask(Task task) { - Contract.Assert(task != null, "Infrastructure should have provided a non-null task."); + Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); base.TryExecuteTask(task); } @@ -552,7 +552,7 @@ namespace System.Threading.Tasks /// true if the task could be executed; otherwise, false. protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { - Contract.Assert(task != null, "Infrastructure should have provided a non-null task."); + Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); // If the scheduler has had completion requested, no new work is allowed to be scheduled. // A non-locked read on m_completionRequested (in CompletionRequested) is acceptable here because: @@ -625,7 +625,7 @@ namespace System.Threading.Tasks } catch { - Contract.Assert(t.IsFaulted, "Task should be faulted due to the scheduler faulting it and throwing the exception."); + Debug.Assert(t.IsFaulted, "Task should be faulted due to the scheduler faulting it and throwing the exception."); var ignored = t.Exception; throw; } @@ -743,11 +743,11 @@ namespace System.Threading.Tasks exceptionThrown = false; } catch (SynchronizationLockException) { exceptionThrown = true; } - Contract.Assert(held == !exceptionThrown, "The locking scheme was not correctly followed."); + Debug.Assert(held == !exceptionThrown, "The locking scheme was not correctly followed."); } #endif #else - Contract.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed."); + Debug.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed."); #endif } diff --git a/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs b/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs index 838af04..974d427 100644 --- a/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs +++ b/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs @@ -15,6 +15,7 @@ using System.Security; using System.Security.Permissions; using System.Runtime.CompilerServices; using System.Threading; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.Versioning; @@ -841,7 +842,7 @@ namespace System.Threading.Tasks }, state); if (asyncResult.CompletedSynchronously) { - Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed."); + Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed."); FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false); } } @@ -962,7 +963,7 @@ namespace System.Threading.Tasks }, state); if (asyncResult.CompletedSynchronously) { - Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed."); + Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed."); FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false); } } @@ -1092,7 +1093,7 @@ namespace System.Threading.Tasks }, state); if (asyncResult.CompletedSynchronously) { - Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed."); + Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed."); FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false); } } @@ -1229,7 +1230,7 @@ namespace System.Threading.Tasks }, state); if (asyncResult.CompletedSynchronously) { - Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed."); + Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed."); FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false); } } @@ -1270,9 +1271,9 @@ namespace System.Threading.Tasks where TInstance : class { // Validate arguments, but only with asserts, as this is an internal only implementation. - Contract.Assert(thisRef != null, "Expected a non-null thisRef"); - Contract.Assert(beginMethod != null, "Expected a non-null beginMethod"); - Contract.Assert(endMethod != null, "Expected a non-null endMethod"); + Debug.Assert(thisRef != null, "Expected a non-null thisRef"); + Debug.Assert(beginMethod != null, "Expected a non-null beginMethod"); + Debug.Assert(endMethod != null, "Expected a non-null endMethod"); // Create the promise and start the operation. // No try/catch is necessary here as we want exceptions to bubble out, and because @@ -1285,7 +1286,7 @@ namespace System.Threading.Tasks // If it completed synchronously, we'll handle that here. if (asyncResult.CompletedSynchronously) { - Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed."); + Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed."); promise.Complete(thisRef, endMethod, asyncResult, requiresSynchronization: false); } @@ -1365,7 +1366,7 @@ namespace System.Threading.Tasks TInstance thisRef, Func endMethod, IAsyncResult asyncResult, bool requiresSynchronization) { - Contract.Assert(!IsCompleted, "The task should not have been completed yet."); + Debug.Assert(!IsCompleted, "The task should not have been completed yet."); // Run the end method and complete the task bool successfullySet = false; @@ -1394,7 +1395,7 @@ namespace System.Threading.Tasks { successfullySet = TrySetException(exc); } - Contract.Assert(successfullySet, "Expected the task to not yet be completed"); + Debug.Assert(successfullySet, "Expected the task to not yet be completed"); } } @@ -1741,7 +1742,7 @@ namespace System.Threading.Tasks } else { - Contract.Assert(continuationAction != null); + Debug.Assert(continuationAction != null); return starter.ContinueWith( // use a cached delegate @@ -1794,7 +1795,7 @@ namespace System.Threading.Tasks } else { - Contract.Assert(continuationAction != null); + Debug.Assert(continuationAction != null); return starter.ContinueWith( //the following delegate avoids closure capture as much as possible //completedTasks.Result == tasksCopy; @@ -2140,7 +2141,7 @@ namespace System.Threading.Tasks } else { - Contract.Assert(continuationAction != null); + Debug.Assert(continuationAction != null); return starter.ContinueWith( //the following delegate avoids closure capture as much as possible //completedTask.Result is the winning task; state == continuationAction @@ -2186,7 +2187,7 @@ namespace System.Threading.Tasks } else { - Contract.Assert(continuationAction != null); + Debug.Assert(continuationAction != null); return starter.ContinueWith( // Use a cached delegate GenericDelegateCache.CWAnyActionDelegate, diff --git a/src/mscorlib/src/System/Threading/Tasks/Parallel.cs b/src/mscorlib/src/System/Threading/Tasks/Parallel.cs index 914c7bf..ae78559 100644 --- a/src/mscorlib/src/System/Threading/Tasks/Parallel.cs +++ b/src/mscorlib/src/System/Threading/Tasks/Parallel.cs @@ -1031,9 +1031,9 @@ namespace System.Threading.Tasks Func bodyWithLocal, Func localInit, Action localFinally) { - Contract.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1, + Debug.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1, "expected exactly one body function to be supplied"); - Contract.Assert(bodyWithLocal != null || (localInit == null && localFinally == null), + Debug.Assert(bodyWithLocal != null || (localInit == null && localFinally == null), "thread local functions should only be supplied for loops w/ thread local bodies"); // Instantiate our result. Specifics will be filled in later. @@ -1157,12 +1157,12 @@ namespace System.Threading.Tasks if (bodyWithState != null) { - Contract.Assert(sharedPStateFlags != null); + Debug.Assert(sharedPStateFlags != null); state = new ParallelLoopState32(sharedPStateFlags); } else if (bodyWithLocal != null) { - Contract.Assert(sharedPStateFlags != null); + Debug.Assert(sharedPStateFlags != null); state = new ParallelLoopState32(sharedPStateFlags); if (localInit != null) { @@ -1346,9 +1346,9 @@ namespace System.Threading.Tasks Func bodyWithLocal, Func localInit, Action localFinally) { - Contract.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1, + Debug.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1, "expected exactly one body function to be supplied"); - Contract.Assert(bodyWithLocal != null || (localInit == null && localFinally == null), + Debug.Assert(bodyWithLocal != null || (localInit == null && localFinally == null), "thread local functions should only be supplied for loops w/ thread local bodies"); // Instantiate our result. Specifics will be filled in later. @@ -1471,12 +1471,12 @@ namespace System.Threading.Tasks if (bodyWithState != null) { - Contract.Assert(sharedPStateFlags != null); + Debug.Assert(sharedPStateFlags != null); state = new ParallelLoopState64(sharedPStateFlags); } else if (bodyWithLocal != null) { - Contract.Assert(sharedPStateFlags != null); + Debug.Assert(sharedPStateFlags != null); state = new ParallelLoopState64(sharedPStateFlags); // If a thread-local selector was supplied, invoke it. Otherwise, use the default. @@ -2214,10 +2214,10 @@ namespace System.Threading.Tasks Func bodyWithEverything, Func localInit, Action localFinally) { - Contract.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + + Debug.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithStateAndIndex == null ? 0 : 1) + (bodyWithStateAndLocal == null ? 0 : 1) + (bodyWithEverything == null ? 0 : 1)) == 1, "expected exactly one body function to be supplied"); - Contract.Assert((bodyWithStateAndLocal != null) || (bodyWithEverything != null) || (localInit == null && localFinally == null), + Debug.Assert((bodyWithStateAndLocal != null) || (bodyWithEverything != null) || (localInit == null && localFinally == null), "thread local functions should only be supplied for loops w/ thread local bodies"); // Before getting started, do a quick peek to see if we have been canceled already @@ -2278,8 +2278,8 @@ namespace System.Threading.Tasks Func bodyWithEverything, Func localInit, Action localFinally) { - Contract.Assert(array != null); - Contract.Assert(parallelOptions != null, "ForEachWorker(array): parallelOptions is null"); + Debug.Assert(array != null); + Debug.Assert(parallelOptions != null, "ForEachWorker(array): parallelOptions is null"); int from = array.GetLowerBound(0); int to = array.GetUpperBound(0) + 1; @@ -2337,8 +2337,8 @@ namespace System.Threading.Tasks Func bodyWithEverything, Func localInit, Action localFinally) { - Contract.Assert(list != null); - Contract.Assert(parallelOptions != null, "ForEachWorker(list): parallelOptions is null"); + Debug.Assert(list != null); + Debug.Assert(parallelOptions != null, "ForEachWorker(list): parallelOptions is null"); if (body != null) { @@ -3191,14 +3191,14 @@ namespace System.Threading.Tasks Func localInit, Action localFinally) { - Contract.Assert(((simpleBody == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + + Debug.Assert(((simpleBody == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithStateAndIndex == null ? 0 : 1) + (bodyWithStateAndLocal == null ? 0 : 1) + (bodyWithEverything == null ? 0 : 1)) == 1, "PartitionForEach: expected exactly one body function to be supplied"); - Contract.Assert((bodyWithStateAndLocal != null) || (bodyWithEverything != null) || (localInit == null && localFinally == null), + Debug.Assert((bodyWithStateAndLocal != null) || (bodyWithEverything != null) || (localInit == null && localFinally == null), "PartitionForEach: thread local functions should only be supplied for loops w/ thread local bodies"); OrderablePartitioner orderedSource = source as OrderablePartitioner; - Contract.Assert((orderedSource != null) || (bodyWithStateAndIndex == null && bodyWithEverything == null), + Debug.Assert((orderedSource != null) || (bodyWithStateAndIndex == null && bodyWithEverything == null), "PartitionForEach: bodies with indices are only allowable for OrderablePartitioner"); if (!source.SupportsDynamicPartitions) @@ -3401,7 +3401,7 @@ namespace System.Threading.Tasks else if (bodyWithStateAndLocal != null) localValue = bodyWithStateAndLocal(t, state, localValue); else - Contract.Assert(false, "PartitionerForEach: illegal body type in Partitioner handler"); + Debug.Assert(false, "PartitionerForEach: illegal body type in Partitioner handler"); // Any break, stop or exception causes us to halt @@ -3576,7 +3576,7 @@ namespace System.Threading.Tasks public bool LimitExceeded() { - Contract.Assert(m_timeLimit != 0, "Probably the default initializer for LoopTimer was used somewhere"); + Debug.Assert(m_timeLimit != 0, "Probably the default initializer for LoopTimer was used somewhere"); // comparing against the next expected time saves an addition operation here // Also we omit the comparison for wrap around here. The only side effect is one extra early yield every 38 days. diff --git a/src/mscorlib/src/System/Threading/Tasks/ParallelLoopState.cs b/src/mscorlib/src/System/Threading/Tasks/ParallelLoopState.cs index 4db3a9d..4e97555 100644 --- a/src/mscorlib/src/System/Threading/Tasks/ParallelLoopState.cs +++ b/src/mscorlib/src/System/Threading/Tasks/ParallelLoopState.cs @@ -47,7 +47,7 @@ namespace System.Threading.Tasks { get { - Contract.Assert(false); + Debug.Assert(false); throw new NotSupportedException( Environment.GetResourceString("ParallelState_NotSupportedException_UnsupportedMethod")); } @@ -104,7 +104,7 @@ namespace System.Threading.Tasks { get { - Contract.Assert(false); + Debug.Assert(false); throw new NotSupportedException( Environment.GetResourceString("ParallelState_NotSupportedException_UnsupportedMethod")); } @@ -152,7 +152,7 @@ namespace System.Threading.Tasks // Internal/virtual support for Break(). internal virtual void InternalBreak() { - Contract.Assert(false); + Debug.Assert(false); throw new NotSupportedException( Environment.GetResourceString("ParallelState_NotSupportedException_UnsupportedMethod")); } diff --git a/src/mscorlib/src/System/Threading/Tasks/ParallelRangeManager.cs b/src/mscorlib/src/System/Threading/Tasks/ParallelRangeManager.cs index c4b66c4..49f61a6 100644 --- a/src/mscorlib/src/System/Threading/Tasks/ParallelRangeManager.cs +++ b/src/mscorlib/src/System/Threading/Tasks/ParallelRangeManager.cs @@ -12,6 +12,7 @@ using System; using System.Threading; +using System.Diagnostics; using System.Diagnostics.Contracts; #pragma warning disable 0420 @@ -160,7 +161,7 @@ namespace System.Threading.Tasks bool bRetVal = FindNewWork(out nFromInclusiveLocal, out nToExclusiveLocal); - Contract.Assert((nFromInclusiveLocal <= Int32.MaxValue) && (nFromInclusiveLocal >= Int32.MinValue) && + Debug.Assert((nFromInclusiveLocal <= Int32.MaxValue) && (nFromInclusiveLocal >= Int32.MinValue) && (nToExclusiveLocal <= Int32.MaxValue) && (nToExclusiveLocal >= Int32.MinValue)); // convert to 32 bit before returning @@ -218,7 +219,7 @@ namespace System.Threading.Tasks // // find the actual number of index ranges we will need // - Contract.Assert((uSpan / uRangeSize) < Int32.MaxValue); + Debug.Assert((uSpan / uRangeSize) < Int32.MaxValue); int nNumRanges = (int)(uSpan / uRangeSize); @@ -251,7 +252,7 @@ namespace System.Threading.Tasks nCurrentIndex > nToExclusive) { // this should only happen at the last index - Contract.Assert(i == nNumRanges - 1); + Debug.Assert(i == nNumRanges - 1); nCurrentIndex = nToExclusive; } @@ -267,7 +268,7 @@ namespace System.Threading.Tasks /// internal RangeWorker RegisterNewWorker() { - Contract.Assert(m_indexRanges != null && m_indexRanges.Length != 0); + Debug.Assert(m_indexRanges != null && m_indexRanges.Length != 0); int nInitialRange = (Interlocked.Increment(ref m_nCurrentIndexRangeToAssign) - 1) % m_indexRanges.Length; diff --git a/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs b/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs index 462ee0a..6b9dfbb 100644 --- a/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs +++ b/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs @@ -140,10 +140,10 @@ namespace System.Threading.Tasks internal SingleProducerSingleConsumerQueue() { // Validate constants in ctor rather than in an explicit cctor that would cause perf degradation - Contract.Assert(INIT_SEGMENT_SIZE > 0, "Initial segment size must be > 0."); - Contract.Assert((INIT_SEGMENT_SIZE & (INIT_SEGMENT_SIZE - 1)) == 0, "Initial segment size must be a power of 2"); - Contract.Assert(INIT_SEGMENT_SIZE <= MAX_SEGMENT_SIZE, "Initial segment size should be <= maximum."); - Contract.Assert(MAX_SEGMENT_SIZE < Int32.MaxValue / 2, "Max segment size * 2 must be < Int32.MaxValue, or else overflow could occur."); + Debug.Assert(INIT_SEGMENT_SIZE > 0, "Initial segment size must be > 0."); + Debug.Assert((INIT_SEGMENT_SIZE & (INIT_SEGMENT_SIZE - 1)) == 0, "Initial segment size must be a power of 2"); + Debug.Assert(INIT_SEGMENT_SIZE <= MAX_SEGMENT_SIZE, "Initial segment size should be <= maximum."); + Debug.Assert(MAX_SEGMENT_SIZE < Int32.MaxValue / 2, "Max segment size * 2 must be < Int32.MaxValue, or else overflow could occur."); // Initialize the queue m_head = m_tail = new Segment(INIT_SEGMENT_SIZE); @@ -183,7 +183,7 @@ namespace System.Threading.Tasks } int newSegmentSize = m_tail.m_array.Length << 1; // double size - Contract.Assert(newSegmentSize > 0, "The max size should always be small enough that we don't overflow."); + Debug.Assert(newSegmentSize > 0, "The max size should always be small enough that we don't overflow."); if (newSegmentSize > MAX_SEGMENT_SIZE) newSegmentSize = MAX_SEGMENT_SIZE; var newSegment = new Segment(newSegmentSize); @@ -456,7 +456,7 @@ namespace System.Threading.Tasks /// The Count is not thread safe, so we need to acquire the lock. int IProducerConsumerQueue.GetCountSafe(object syncObj) { - Contract.Assert(syncObj != null, "The syncObj parameter is null."); + Debug.Assert(syncObj != null, "The syncObj parameter is null."); lock (syncObj) { return Count; diff --git a/src/mscorlib/src/System/Threading/Tasks/Task.cs b/src/mscorlib/src/System/Threading/Tasks/Task.cs index 84446f6..865ea13 100644 --- a/src/mscorlib/src/System/Threading/Tasks/Task.cs +++ b/src/mscorlib/src/System/Threading/Tasks/Task.cs @@ -339,7 +339,7 @@ namespace System.Threading.Tasks // (action,TCO). It should always be true. internal Task(object state, TaskCreationOptions creationOptions, bool promiseStyle) { - Contract.Assert(promiseStyle, "Promise CTOR: promiseStyle was false"); + Debug.Assert(promiseStyle, "Promise CTOR: promiseStyle was false"); // Check the creationOptions. We allow the AttachedToParent option to be specified for promise tasks. // Also allow RunContinuationsAsynchronously because this is the constructor called by TCS @@ -609,7 +609,7 @@ namespace System.Threading.Tasks InternalTaskOptions.ContinuationTask | InternalTaskOptions.LazyCancellation | InternalTaskOptions.QueuedByRuntime)); - Contract.Assert(illegalInternalOptions == 0, "TaskConstructorCore: Illegal internal options"); + Debug.Assert(illegalInternalOptions == 0, "TaskConstructorCore: Illegal internal options"); #endif // Throw exception if the user specifies both LongRunning and SelfReplicating @@ -620,8 +620,8 @@ namespace System.Threading.Tasks } // Assign options to m_stateAndOptionsFlag. - Contract.Assert(m_stateFlags == 0, "TaskConstructorCore: non-zero m_stateFlags"); - Contract.Assert((((int)creationOptions) | OptionsMask) == OptionsMask, "TaskConstructorCore: options take too many bits"); + Debug.Assert(m_stateFlags == 0, "TaskConstructorCore: non-zero m_stateFlags"); + Debug.Assert((((int)creationOptions) | OptionsMask) == OptionsMask, "TaskConstructorCore: options take too many bits"); var tmpFlags = (int)creationOptions | (int)internalOptions; if ((m_action == null) || ((internalOptions & InternalTaskOptions.ContinuationTask) != 0)) { @@ -649,7 +649,7 @@ namespace System.Threading.Tasks // we need to do this as the very last thing in the construction path, because the CT registration could modify m_stateFlags if (cancellationToken.CanBeCanceled) { - Contract.Assert((internalOptions & + Debug.Assert((internalOptions & (InternalTaskOptions.ChildReplica | InternalTaskOptions.SelfReplicating | InternalTaskOptions.ContinuationTask)) == 0, "TaskConstructorCore: Did not expect to see cancelable token for replica/replicating or continuation task."); @@ -743,7 +743,7 @@ namespace System.Threading.Tasks antecedentTask.RemoveContinuation(continuation); } } - Contract.Assert(targetTask != null, + Debug.Assert(targetTask != null, "targetTask should have been non-null, with the supplied argument being a task or a tuple containing one"); targetTask.InternalCancel(false); } @@ -766,7 +766,7 @@ namespace System.Threading.Tasks internal void PossiblyCaptureContext(ref StackCrawlMark stackMark) { - Contract.Assert(m_contingentProperties == null || m_contingentProperties.m_capturedContext == null, + Debug.Assert(m_contingentProperties == null || m_contingentProperties.m_capturedContext == null, "Captured an ExecutionContext when one was already captured."); // In the legacy .NET 3.5 build, we don't have the optimized overload of Capture() @@ -790,7 +790,7 @@ namespace System.Threading.Tasks // a read of the volatile m_stateFlags field. internal static TaskCreationOptions OptionsMethod(int flags) { - Contract.Assert((OptionsMask & 1) == 1, "OptionsMask needs a shift in Options.get"); + Debug.Assert((OptionsMask & 1) == 1, "OptionsMask needs a shift in Options.get"); return (TaskCreationOptions)(flags & OptionsMask); } @@ -840,7 +840,7 @@ namespace System.Threading.Tasks /// true to set the bit; false to unset the bit. internal void SetNotificationForWaitCompletion(bool enabled) { - Contract.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0, + Debug.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0, "Should only be used for promise-style tasks"); // hasn't been vetted on other kinds as there hasn't been a need if (enabled) @@ -848,7 +848,7 @@ namespace System.Threading.Tasks // Atomically set the END_AWAIT_NOTIFICATION bit bool success = AtomicStateUpdate(TASK_STATE_WAIT_COMPLETION_NOTIFICATION, TASK_STATE_COMPLETED_MASK | TASK_STATE_COMPLETION_RESERVED); - Contract.Assert(success, "Tried to set enabled on completed Task"); + Debug.Assert(success, "Tried to set enabled on completed Task"); } else { @@ -885,7 +885,7 @@ namespace System.Threading.Tasks /// true if any of the tasks require notification; otherwise, false. internal static bool AnyTaskRequiresNotifyDebuggerOfWaitCompletion(Task[] tasks) { - Contract.Assert(tasks != null, "Expected non-null array of tasks"); + Debug.Assert(tasks != null, "Expected non-null array of tasks"); foreach (var task in tasks) { if (task != null && @@ -925,7 +925,7 @@ namespace System.Threading.Tasks // bit was unset between the time that it was checked and this method was called. // It's so remote a chance that it's worth having the assert to protect against misuse. bool isWaitNotificationEnabled = IsWaitNotificationEnabled; - Contract.Assert(isWaitNotificationEnabled, "Should only be called if the wait completion bit is set."); + Debug.Assert(isWaitNotificationEnabled, "Should only be called if the wait completion bit is set."); return isWaitNotificationEnabled; } } @@ -945,7 +945,7 @@ namespace System.Threading.Tasks // It's theoretically possible but extremely rare that this assert could fire because the // bit was unset between the time that it was checked and this method was called. // It's so remote a chance that it's worth having the assert to protect against misuse. - Contract.Assert(IsWaitNotificationEnabled, "Should only be called if the wait completion bit is set."); + Debug.Assert(IsWaitNotificationEnabled, "Should only be called if the wait completion bit is set."); // Now that we're notifying the debugger, clear the bit. The debugger should do this anyway, // but this adds a bit of protection in case it fails to, and given that the debugger is involved, @@ -990,7 +990,7 @@ namespace System.Threading.Tasks /// internal void AddNewChild() { - Contract.Assert(Task.InternalCurrent == this || this.IsSelfReplicatingRoot, "Task.AddNewChild(): Called from an external context"); + Debug.Assert(Task.InternalCurrent == this || this.IsSelfReplicatingRoot, "Task.AddNewChild(): Called from an external context"); var props = EnsureContingentPropertiesInitialized(); @@ -1013,10 +1013,10 @@ namespace System.Threading.Tasks // We need to subtract that child from m_completionCountdown, or the parent will never complete. internal void DisregardChild() { - Contract.Assert(Task.InternalCurrent == this, "Task.DisregardChild(): Called from an external context"); + Debug.Assert(Task.InternalCurrent == this, "Task.DisregardChild(): Called from an external context"); var props = EnsureContingentPropertiesInitialized(); - Contract.Assert(props.m_completionCountdown >= 2, "Task.DisregardChild(): Expected parent count to be >= 2"); + Debug.Assert(props.m_completionCountdown >= 2, "Task.DisregardChild(): Expected parent count to be >= 2"); Interlocked.Decrement(ref props.m_completionCountdown); } @@ -1233,7 +1233,7 @@ namespace System.Threading.Tasks // Mark ourselves as "handled" to avoid crashing the finalizer thread if the caller neglects to // call Wait() on this task. // m_contingentProperties.m_exceptionsHolder *should* already exist after AddException() - Contract.Assert( + Debug.Assert( (m_contingentProperties != null) && (m_contingentProperties.m_exceptionsHolder != null) && (m_contingentProperties.m_exceptionsHolder.ContainsFaultList), @@ -1250,7 +1250,7 @@ namespace System.Threading.Tasks } else { - Contract.Assert((m_stateFlags & TASK_STATE_CANCELED) != 0, "Task.RunSynchronously: expected TASK_STATE_CANCELED to be set"); + Debug.Assert((m_stateFlags & TASK_STATE_CANCELED) != 0, "Task.RunSynchronously: expected TASK_STATE_CANCELED to be set"); // Can't call this method on canceled task. ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_RunSynchronously_TaskCompleted); } @@ -1401,7 +1401,7 @@ namespace System.Threading.Tasks // Only return an exception in faulted state (skip manufactured exceptions) // A "benevolent" race condition makes it possible to return null when IsFaulted is // true (i.e., if IsFaulted is set just after the check to IsFaulted above). - Contract.Assert((e == null) || IsFaulted, "Task.Exception_get(): returning non-null value when not Faulted"); + Debug.Assert((e == null) || IsFaulted, "Task.Exception_get(): returning non-null value when not Faulted"); return e; } @@ -1884,8 +1884,8 @@ namespace System.Threading.Tasks /// are not a problem. internal void ScheduleAndStart(bool needsProtection) { - Contract.Assert(m_taskScheduler != null, "expected a task scheduler to have been selected"); - Contract.Assert((m_stateFlags & TASK_STATE_STARTED) == 0, "task has already started"); + Debug.Assert(m_taskScheduler != null, "expected a task scheduler to have been selected"); + Debug.Assert((m_stateFlags & TASK_STATE_STARTED) == 0, "task has already started"); // Set the TASK_STATE_STARTED bit if (needsProtection) @@ -1939,7 +1939,7 @@ namespace System.Threading.Tasks if ((Options & (TaskCreationOptions)InternalTaskOptions.ContinuationTask) == 0) { // m_contingentProperties.m_exceptionsHolder *should* already exist after AddException() - Contract.Assert( + Debug.Assert( (m_contingentProperties != null) && (m_contingentProperties.m_exceptionsHolder != null) && (m_contingentProperties.m_exceptionsHolder.ContainsFaultList), @@ -1978,13 +1978,13 @@ namespace System.Threading.Tasks var eoAsEdi = exceptionObject as ExceptionDispatchInfo; var eoAsEnumerableEdi = exceptionObject as IEnumerable; - Contract.Assert( + Debug.Assert( eoAsException != null || eoAsEnumerableException != null || eoAsEdi != null || eoAsEnumerableEdi != null, "Task.AddException: Expected an Exception, ExceptionDispatchInfo, or an IEnumerable<> of one of those"); var eoAsOce = exceptionObject as OperationCanceledException; - Contract.Assert( + Debug.Assert( !representsCancellation || eoAsOce != null || (eoAsEdi != null && eoAsEdi.SourceException is OperationCanceledException), @@ -2075,7 +2075,7 @@ namespace System.Threading.Tasks { // There are exceptions; get the aggregate and optionally add the canceled // exception to the aggregate (if applicable). - Contract.Assert(m_contingentProperties != null); // ExceptionRecorded ==> m_contingentProperties != null + Debug.Assert(m_contingentProperties != null); // ExceptionRecorded ==> m_contingentProperties != null // No need to lock around this, as other logic prevents the consumption of exceptions // before they have been completely processed. @@ -2094,7 +2094,7 @@ namespace System.Threading.Tasks internal ReadOnlyCollection GetExceptionDispatchInfos() { bool exceptionsAvailable = IsFaulted && ExceptionRecorded; - Contract.Assert(exceptionsAvailable, "Must only be used when the task has faulted with exceptions."); + Debug.Assert(exceptionsAvailable, "Must only be used when the task has faulted with exceptions."); return exceptionsAvailable ? m_contingentProperties.m_exceptionsHolder.GetExceptionDispatchInfos() : new ReadOnlyCollection(new ExceptionDispatchInfo[0]); @@ -2104,7 +2104,7 @@ namespace System.Threading.Tasks /// The ExceptionDispatchInfo. May be null if no OCE was stored for the task. internal ExceptionDispatchInfo GetCancellationExceptionDispatchInfo() { - Contract.Assert(IsCanceled, "Must only be used when the task has canceled."); + Debug.Assert(IsCanceled, "Must only be used when the task has canceled."); return Volatile.Read(ref m_contingentProperties)?.m_exceptionsHolder?.GetCancellationExceptionDispatchInfo(); // may be null } @@ -2341,7 +2341,7 @@ namespace System.Threading.Tasks Contract.Requires(childTask != null); Contract.Requires(childTask.IsCompleted, "ProcessChildCompletion was called for an uncompleted task"); - Contract.Assert(childTask.m_contingentProperties?.m_parent == this, "ProcessChildCompletion should only be called for a child of this task"); + Debug.Assert(childTask.m_contingentProperties?.m_parent == this, "ProcessChildCompletion should only be called for a child of this task"); var props = Volatile.Read(ref m_contingentProperties); @@ -2401,11 +2401,11 @@ namespace System.Threading.Tasks { // Ensure any exceptions thrown by children are added to the parent. // In doing this, we are implicitly marking children as being "handled". - Contract.Assert(task.IsCompleted, "Expected all tasks in list to be completed"); + Debug.Assert(task.IsCompleted, "Expected all tasks in list to be completed"); if (task.IsFaulted && !task.IsExceptionObservedByParent) { TaskExceptionHolder exceptionHolder = Volatile.Read(ref task.m_contingentProperties).m_exceptionsHolder; - Contract.Assert(exceptionHolder != null); + Debug.Assert(exceptionHolder != null); // No locking necessary since child task is finished adding exceptions // and concurrent CreateExceptionObject() calls do not constitute @@ -2432,7 +2432,7 @@ namespace System.Threading.Tasks /// Whether the delegate was executed. internal void FinishThreadAbortedTask(bool bTAEAddedToExceptionHolder, bool delegateRan) { - Contract.Assert(!bTAEAddedToExceptionHolder || m_contingentProperties?.m_exceptionsHolder != null, + Debug.Assert(!bTAEAddedToExceptionHolder || m_contingentProperties?.m_exceptionsHolder != null, "FinishThreadAbortedTask() called on a task whose exception holder wasn't initialized"); // this will only be false for non-root self replicating task copies, because all of their exceptions go to the root task. @@ -2817,7 +2817,7 @@ namespace System.Threading.Tasks private static void ExecutionContextCallback(object obj) { Task task = obj as Task; - Contract.Assert(task != null, "expected a task object"); + Debug.Assert(task != null, "expected a task object"); task.Execute(); } @@ -2828,7 +2828,7 @@ namespace System.Threading.Tasks internal virtual void InnerInvoke() { // Invoke the delegate - Contract.Assert(m_action != null, "Null action in InnerInvoke()"); + Debug.Assert(m_action != null, "Null action in InnerInvoke()"); var action = m_action as Action; if (action != null) { @@ -2841,7 +2841,7 @@ namespace System.Threading.Tasks actionWithState(m_stateObject); return; } - Contract.Assert(false, "Invalid m_action in Task"); + Debug.Assert(false, "Invalid m_action in Task"); } /// @@ -2976,7 +2976,7 @@ namespace System.Threading.Tasks } else { - Contract.Assert(!flowExecutionContext, "We already determined we're not required to flow context."); + Debug.Assert(!flowExecutionContext, "We already determined we're not required to flow context."); if (!AddTaskContinuation(continuationAction, addBeforeOthers: false)) AwaitTaskContinuation.UnsafeScheduleAction(continuationAction, this); } @@ -3009,7 +3009,7 @@ namespace System.Threading.Tasks Wait(Timeout.Infinite, default(CancellationToken)); #if DEBUG - Contract.Assert(waitResult, "expected wait to succeed"); + Debug.Assert(waitResult, "expected wait to succeed"); #endif } @@ -3144,7 +3144,7 @@ namespace System.Threading.Tasks ThrowIfExceptional(true); } - Contract.Assert((m_stateFlags & TASK_STATE_FAULTED) == 0, "Task.Wait() completing when in Faulted state."); + Debug.Assert((m_stateFlags & TASK_STATE_FAULTED) == 0, "Task.Wait() completing when in Faulted state."); return true; } @@ -3220,7 +3220,7 @@ namespace System.Threading.Tasks } } - Contract.Assert(IsCompleted || millisecondsTimeout != Timeout.Infinite); + Debug.Assert(IsCompleted || millisecondsTimeout != Timeout.Infinite); // ETW event for Task Wait End if (etwIsEnabled) @@ -3415,7 +3415,7 @@ namespace System.Threading.Tasks if (bPopSucceeded) { // hitting this would mean something wrong with the AtomicStateUpdate above - Contract.Assert(!mustCleanup, "Possibly an invalid state transition call was made in InternalCancel()"); + Debug.Assert(!mustCleanup, "Possibly an invalid state transition call was made in InternalCancel()"); // Include TASK_STATE_DELEGATE_INVOKED in "illegal" bits to protect against the situation where // TS.TryDequeue() returns true but the task is still left on the queue. @@ -3455,8 +3455,8 @@ namespace System.Threading.Tasks { RecordInternalCancellationRequest(); - Contract.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0, "Task.RecordInternalCancellationRequest(CancellationToken) only valid for promise-style task"); - Contract.Assert(m_contingentProperties.m_cancellationToken == default(CancellationToken)); + Debug.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0, "Task.RecordInternalCancellationRequest(CancellationToken) only valid for promise-style task"); + Debug.Assert(m_contingentProperties.m_cancellationToken == default(CancellationToken)); // Store the supplied cancellation token as this task's token. // Waiting on this task will then result in an OperationCanceledException containing this token. @@ -3481,11 +3481,11 @@ namespace System.Threading.Tasks if (oce == null) { var edi = cancellationException as ExceptionDispatchInfo; - Contract.Assert(edi != null, "Expected either an OCE or an EDI"); + Debug.Assert(edi != null, "Expected either an OCE or an EDI"); oce = edi.SourceException as OperationCanceledException; - Contract.Assert(oce != null, "Expected EDI to contain an OCE"); + Debug.Assert(oce != null, "Expected EDI to contain an OCE"); } - Contract.Assert(oce.CancellationToken == tokenToRecord, + Debug.Assert(oce.CancellationToken == tokenToRecord, "Expected OCE's token to match the provided token."); #endif AddException(cancellationException, representsCancellation: true); @@ -3496,10 +3496,10 @@ namespace System.Threading.Tasks // And this method should be called at most once per task. internal void CancellationCleanupLogic() { - Contract.Assert((m_stateFlags & (TASK_STATE_CANCELED | TASK_STATE_COMPLETION_RESERVED)) != 0, "Task.CancellationCleanupLogic(): Task not canceled or reserved."); + Debug.Assert((m_stateFlags & (TASK_STATE_CANCELED | TASK_STATE_COMPLETION_RESERVED)) != 0, "Task.CancellationCleanupLogic(): Task not canceled or reserved."); // I'd like to do this, but there is a small window for a race condition. If someone calls Wait() between InternalCancel() and // here, that will set m_completionEvent, leading to a meaningless/harmless assertion. - //Contract.Assert((m_completionEvent == null) || !m_completionEvent.IsSet, "Task.CancellationCleanupLogic(): Completion event already set."); + //Debug.Assert((m_completionEvent == null) || !m_completionEvent.IsSet, "Task.CancellationCleanupLogic(): Completion event already set."); // This may have been set already, but we need to make sure. Interlocked.Exchange(ref m_stateFlags, m_stateFlags | TASK_STATE_CANCELED); @@ -3530,8 +3530,8 @@ namespace System.Threading.Tasks /// private void SetCancellationAcknowledged() { - Contract.Assert(this == Task.InternalCurrent, "SetCancellationAcknowledged() should only be called while this is still the current task"); - Contract.Assert(IsCancellationRequested, "SetCancellationAcknowledged() should not be called if the task's CT wasn't signaled"); + Debug.Assert(this == Task.InternalCurrent, "SetCancellationAcknowledged() should only be called while this is still the current task"); + Debug.Assert(IsCancellationRequested, "SetCancellationAcknowledged() should not be called if the task's CT wasn't signaled"); m_stateFlags |= TASK_STATE_CANCELLATIONACKNOWLEDGED; } @@ -3672,7 +3672,7 @@ namespace System.Threading.Tasks // Otherwise, it must be an ITaskCompletionAction, so invoke it. else { - Contract.Assert(currentContinuation is ITaskCompletionAction, "Expected continuation element to be Action, TaskContinuation, or ITaskContinuationAction"); + Debug.Assert(currentContinuation is ITaskCompletionAction, "Expected continuation element to be Action, TaskContinuation, or ITaskContinuationAction"); var action = (ITaskCompletionAction)currentContinuation; if (bCanInlineContinuations || !action.InvokeMayRunArbitraryCode) @@ -4718,7 +4718,7 @@ namespace System.Threading.Tasks // m_continuationObject is guaranteed at this point to be either a List or // s_taskCompletionSentinel. List list = m_continuationObject as List; - Contract.Assert((list != null) || (m_continuationObject == s_taskCompletionSentinel), + Debug.Assert((list != null) || (m_continuationObject == s_taskCompletionSentinel), "Expected m_continuationObject to be list or sentinel"); // If list is null, it can only mean that s_taskCompletionSentinel has been exchanged @@ -4861,7 +4861,7 @@ namespace System.Threading.Tasks WaitAll(tasks, Timeout.Infinite); #if DEBUG - Contract.Assert(waitResult, "expected wait to succeed"); + Debug.Assert(waitResult, "expected wait to succeed"); #endif } @@ -5122,7 +5122,7 @@ namespace System.Threading.Tasks // Now gather up and throw all of the exceptions. foreach (var task in tasks) AddExceptionsForCompletedTask(ref exceptions, task); - Contract.Assert(exceptions != null, "Should have seen at least one exception"); + Debug.Assert(exceptions != null, "Should have seen at least one exception"); ThrowHelper.ThrowAggregateException(exceptions); } @@ -5147,8 +5147,8 @@ namespace System.Threading.Tasks /// true if all of the tasks completed; otherwise, false. private static bool WaitAllBlockingCore(List tasks, int millisecondsTimeout, CancellationToken cancellationToken) { - Contract.Assert(tasks != null, "Expected a non-null list of tasks"); - Contract.Assert(tasks.Count > 0, "Expected at least one task"); + Debug.Assert(tasks != null, "Expected a non-null list of tasks"); + Debug.Assert(tasks.Count > 0, "Expected at least one task"); bool waitCompleted = false; var mres = new SetOnCountdownMres(tasks.Count); @@ -5194,14 +5194,14 @@ namespace System.Threading.Tasks internal SetOnCountdownMres(int count) { - Contract.Assert(count > 0, "Expected count > 0"); + Debug.Assert(count > 0, "Expected count > 0"); _count = count; } public void Invoke(Task completingTask) { if (Interlocked.Decrement(ref _count) == 0) Set(); - Contract.Assert(_count >= 0, "Count should never go below 0"); + Debug.Assert(_count >= 0, "Count should never go below 0"); } public bool InvokeMayRunArbitraryCode { get { return false; } } @@ -5292,7 +5292,7 @@ namespace System.Threading.Tasks public static int WaitAny(params Task[] tasks) { int waitResult = WaitAny(tasks, Timeout.Infinite); - Contract.Assert(tasks.Length == 0 || waitResult != -1, "expected wait to succeed"); + Debug.Assert(tasks.Length == 0 || waitResult != -1, "expected wait to succeed"); return waitResult; } @@ -5463,9 +5463,9 @@ namespace System.Threading.Tasks bool waitCompleted = firstCompleted.Wait(millisecondsTimeout, cancellationToken); if (waitCompleted) { - Contract.Assert(firstCompleted.Status == TaskStatus.RanToCompletion); + Debug.Assert(firstCompleted.Status == TaskStatus.RanToCompletion); signaledTaskIndex = Array.IndexOf(tasks, firstCompleted.Result); - Contract.Assert(signaledTaskIndex >= 0); + Debug.Assert(signaledTaskIndex >= 0); } } @@ -5509,7 +5509,7 @@ namespace System.Threading.Tasks var task = new Task(); bool succeeded = task.TrySetException(exception); - Contract.Assert(succeeded, "This should always succeed on a new task."); + Debug.Assert(succeeded, "This should always succeed on a new task."); return task; } @@ -5547,7 +5547,7 @@ namespace System.Threading.Tasks var task = new Task(); bool succeeded = task.TrySetCanceled(exception.CancellationToken, exception); - Contract.Assert(succeeded, "This should always succeed on a new task."); + Debug.Assert(succeeded, "This should always succeed on a new task."); return task; } @@ -6112,7 +6112,7 @@ namespace System.Threading.Tasks for (int i = 0; i < m_tasks.Length; i++) { var task = m_tasks[i]; - Contract.Assert(task != null, "Constituent task in WhenAll should never be null"); + Debug.Assert(task != null, "Constituent task in WhenAll should never be null"); if (task.IsFaulted) { @@ -6132,7 +6132,7 @@ namespace System.Threading.Tasks if (observedExceptions != null) { - Contract.Assert(observedExceptions.Count > 0, "Expected at least one exception"); + Debug.Assert(observedExceptions.Count > 0, "Expected at least one exception"); //We don't need to TraceOperationCompleted here because TrySetException will call Finish and we'll log it there @@ -6154,7 +6154,7 @@ namespace System.Threading.Tasks TrySetResult(default(VoidTaskResult)); } } - Contract.Assert(m_count >= 0, "Count should never go below 0"); + Debug.Assert(m_count >= 0, "Count should never go below 0"); } public bool InvokeMayRunArbitraryCode { get { return true; } } @@ -6359,7 +6359,7 @@ namespace System.Threading.Tasks for (int i = 0; i < m_tasks.Length; i++) { Task task = m_tasks[i]; - Contract.Assert(task != null, "Constituent task in WhenAll should never be null"); + Debug.Assert(task != null, "Constituent task in WhenAll should never be null"); if (task.IsFaulted) { @@ -6372,7 +6372,7 @@ namespace System.Threading.Tasks } else { - Contract.Assert(task.Status == TaskStatus.RanToCompletion); + Debug.Assert(task.Status == TaskStatus.RanToCompletion); results[i] = task.GetResultCore(waitCompletionNotification: false); // avoid Result, which would triggering debug notification } @@ -6384,7 +6384,7 @@ namespace System.Threading.Tasks if (observedExceptions != null) { - Contract.Assert(observedExceptions.Count > 0, "Expected at least one exception"); + Debug.Assert(observedExceptions.Count > 0, "Expected at least one exception"); //We don't need to TraceOperationCompleted here because TrySetException will call Finish and we'll log it there @@ -6406,7 +6406,7 @@ namespace System.Threading.Tasks TrySetResult(results); } } - Contract.Assert(m_count >= 0, "Count should never go below 0"); + Debug.Assert(m_count >= 0, "Count should never go below 0"); } public bool InvokeMayRunArbitraryCode { get { return true; } } @@ -6600,7 +6600,7 @@ namespace System.Threading.Tasks Task continuationTask = continuationObject as Task; if (continuationTask != null) { - Contract.Assert(continuationTask.m_action == null); + Debug.Assert(continuationTask.m_action == null); Delegate[] delegates = continuationTask.GetDelegateContinuationsForDebugger(); if (delegates != null) return delegates; @@ -7010,7 +7010,7 @@ namespace System.Threading.Tasks internal void EndInliningScope() { m_inliningDepth--; - Contract.Assert(m_inliningDepth >= 0, "Inlining depth count should never go negative."); + Debug.Assert(m_inliningDepth >= 0, "Inlining depth count should never go negative."); // do the right thing just in case... if (m_inliningDepth < 0) m_inliningDepth = 0; @@ -7133,10 +7133,10 @@ namespace System.Threading.Tasks case STATE_WAITING_ON_INNER_TASK: bool result = TrySetFromTask(completingTask, lookForOce: false); _state = STATE_DONE; // bump the state - Contract.Assert(result, "Expected TrySetFromTask from inner task to succeed"); + Debug.Assert(result, "Expected TrySetFromTask from inner task to succeed"); break; default: - Contract.Assert(false, "UnwrapPromise in illegal state"); + Debug.Assert(false, "UnwrapPromise in illegal state"); break; } } @@ -7161,7 +7161,7 @@ namespace System.Threading.Tasks private void ProcessCompletedOuterTask(Task task) { Contract.Requires(task != null && task.IsCompleted, "Expected non-null, completed outer task"); - Contract.Assert(_state == STATE_WAITING_ON_OUTER_TASK, "We're in the wrong state!"); + Debug.Assert(_state == STATE_WAITING_ON_OUTER_TASK, "We're in the wrong state!"); // Bump our state before proceeding any further _state = STATE_WAITING_ON_INNER_TASK; @@ -7173,7 +7173,7 @@ namespace System.Threading.Tasks case TaskStatus.Canceled: case TaskStatus.Faulted: bool result = TrySetFromTask(task, _lookForOce); - Contract.Assert(result, "Expected TrySetFromTask from outer task to succeed"); + Debug.Assert(result, "Expected TrySetFromTask from outer task to succeed"); break; // Otherwise, process the inner task it returned. diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs b/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs index 8b1dd2a..822ac9b 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs @@ -12,6 +12,7 @@ // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Collections.Generic; using System.Runtime.CompilerServices; @@ -209,9 +210,9 @@ namespace System.Threading.Tasks /// Unlike the public methods, this method doesn't currently validate that its arguments are correct. internal bool TrySetException(IEnumerable exceptions) { - Contract.Assert(exceptions != null); + Debug.Assert(exceptions != null); #if DEBUG - foreach(var edi in exceptions) Contract.Assert(edi != null, "Contents must be non-null"); + foreach(var edi in exceptions) Debug.Assert(edi != null, "Contents must be non-null"); #endif bool rval = m_task.TrySetException(exceptions); diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs b/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs index 5c3657f..70b9418d 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs @@ -11,6 +11,7 @@ // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Security; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.ExceptionServices; using System.Runtime.CompilerServices; @@ -45,7 +46,7 @@ namespace System.Threading.Tasks // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. var antecedent = m_antecedent; - Contract.Assert(antecedent != null, + Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationTaskFromTask."); m_antecedent = null; @@ -53,7 +54,7 @@ namespace System.Threading.Tasks antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate - Contract.Assert(m_action != null); + Debug.Assert(m_action != null); var action = m_action as Action; if (action != null) { @@ -66,7 +67,7 @@ namespace System.Threading.Tasks actionWithState(antecedent, m_stateObject); return; } - Contract.Assert(false, "Invalid m_action in ContinuationTaskFromTask"); + Debug.Assert(false, "Invalid m_action in ContinuationTaskFromTask"); } } @@ -93,7 +94,7 @@ namespace System.Threading.Tasks // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. var antecedent = m_antecedent; - Contract.Assert(antecedent != null, + Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationResultTaskFromTask."); m_antecedent = null; @@ -101,7 +102,7 @@ namespace System.Threading.Tasks antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate - Contract.Assert(m_action != null); + Debug.Assert(m_action != null); var func = m_action as Func; if (func != null) { @@ -114,7 +115,7 @@ namespace System.Threading.Tasks m_result = funcWithState(antecedent, m_stateObject); return; } - Contract.Assert(false, "Invalid m_action in ContinuationResultTaskFromTask"); + Debug.Assert(false, "Invalid m_action in ContinuationResultTaskFromTask"); } } @@ -141,7 +142,7 @@ namespace System.Threading.Tasks // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. var antecedent = m_antecedent; - Contract.Assert(antecedent != null, + Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationTaskFromResultTask."); m_antecedent = null; @@ -149,7 +150,7 @@ namespace System.Threading.Tasks antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate - Contract.Assert(m_action != null); + Debug.Assert(m_action != null); var action = m_action as Action>; if (action != null) { @@ -162,7 +163,7 @@ namespace System.Threading.Tasks actionWithState(antecedent, m_stateObject); return; } - Contract.Assert(false, "Invalid m_action in ContinuationTaskFromResultTask"); + Debug.Assert(false, "Invalid m_action in ContinuationTaskFromResultTask"); } } @@ -189,7 +190,7 @@ namespace System.Threading.Tasks // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. var antecedent = m_antecedent; - Contract.Assert(antecedent != null, + Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationResultTaskFromResultTask."); m_antecedent = null; @@ -197,7 +198,7 @@ namespace System.Threading.Tasks antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate - Contract.Assert(m_action != null); + Debug.Assert(m_action != null); var func = m_action as Func, TResult>; if (func != null) { @@ -210,7 +211,7 @@ namespace System.Threading.Tasks m_result = funcWithState(antecedent, m_stateObject); return; } - Contract.Assert(false, "Invalid m_action in ContinuationResultTaskFromResultTask"); + Debug.Assert(false, "Invalid m_action in ContinuationResultTaskFromResultTask"); } } @@ -238,7 +239,7 @@ namespace System.Threading.Tasks protected static void InlineIfPossibleOrElseQueue(Task task, bool needsProtection) { Contract.Requires(task != null); - Contract.Assert(task.m_taskScheduler != null); + Debug.Assert(task.m_taskScheduler != null); // Set the TASK_STATE_STARTED flag. This only needs to be done // if the task may be canceled or if someone else has a reference to it @@ -317,8 +318,8 @@ namespace System.Threading.Tasks /// Whether the continuation can be inlined. internal override void Run(Task completedTask, bool bCanInlineContinuationTask) { - Contract.Assert(completedTask != null); - Contract.Assert(completedTask.IsCompleted, "ContinuationTask.Run(): completedTask not completed"); + Debug.Assert(completedTask != null); + Debug.Assert(completedTask.IsCompleted, "ContinuationTask.Run(): completedTask not completed"); // Check if the completion status of the task works with the desired // activation criteria of the TaskContinuationOptions. @@ -396,7 +397,7 @@ namespace System.Threading.Tasks SynchronizationContext context, Action action, bool flowExecutionContext, ref StackCrawlMark stackMark) : base(action, flowExecutionContext, ref stackMark) { - Contract.Assert(context != null); + Debug.Assert(context != null); m_syncContext = context; } @@ -483,7 +484,7 @@ namespace System.Threading.Tasks TaskScheduler scheduler, Action action, bool flowExecutionContext, ref StackCrawlMark stackMark) : base(action, flowExecutionContext, ref stackMark) { - Contract.Assert(scheduler != null); + Debug.Assert(scheduler != null); m_scheduler = scheduler; } @@ -726,7 +727,7 @@ namespace System.Threading.Tasks protected void RunCallback(ContextCallback callback, object state, ref Task currentTask) { Contract.Requires(callback != null); - Contract.Assert(currentTask == Task.t_currentTask); + Debug.Assert(currentTask == Task.t_currentTask); // Pretend there's no current task, so that no task is seen as a parent // and TaskScheduler.Current does not reflect false information @@ -772,7 +773,7 @@ namespace System.Threading.Tasks /// internal static void RunOrScheduleAction(Action action, bool allowInlining, ref Task currentTask) { - Contract.Assert(currentTask == Task.t_currentTask); + Debug.Assert(currentTask == Task.t_currentTask); // If we're not allowed to run here, schedule the action if (!allowInlining || !IsValidLocationForInlining) @@ -840,7 +841,7 @@ namespace System.Threading.Tasks internal override Delegate[] GetDelegateContinuationsForDebugger() { - Contract.Assert(m_action != null); + Debug.Assert(m_action != null); return new Delegate[] { AsyncMethodBuilderCore.TryGetStateMachineForDebugger(m_action) }; } } diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs b/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs index b329b78..45817da 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs @@ -18,6 +18,7 @@ namespace System.Threading.Tasks using System; using System.Collections.Generic; using System.Collections.ObjectModel; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.ExceptionServices; using System.Security; @@ -197,12 +198,12 @@ namespace System.Threading.Tasks { Contract.Requires(exceptionObject != null, "Expected exceptionObject to be non-null."); - Contract.Assert(m_cancellationException == null, + Debug.Assert(m_cancellationException == null, "Expected SetCancellationException to be called only once."); // Breaking this assumption will overwrite a previously OCE, // and implies something may be wrong elsewhere, since there should only ever be one. - Contract.Assert(m_faultExceptions == null, + Debug.Assert(m_faultExceptions == null, "Expected SetCancellationException to be called before any faults were added."); // Breaking this assumption shouldn't hurt anything here, but it implies something may be wrong elsewhere. // If this changes, make sure to only conditionally mark as handled below. @@ -216,7 +217,7 @@ namespace System.Threading.Tasks else { var edi = exceptionObject as ExceptionDispatchInfo; - Contract.Assert(edi != null && edi.SourceException is OperationCanceledException, + Debug.Assert(edi != null && edi.SourceException is OperationCanceledException, "Expected an OCE or an EDI that contained an OCE"); m_cancellationException = edi; } @@ -237,7 +238,7 @@ namespace System.Threading.Tasks // Initialize the exceptions list if necessary. The list should be non-null iff it contains exceptions. var exceptions = m_faultExceptions; if (exceptions == null) m_faultExceptions = exceptions = new List(1); - else Contract.Assert(exceptions.Count > 0, "Expected existing exceptions list to have > 0 exceptions."); + else Debug.Assert(exceptions.Count > 0, "Expected existing exceptions list to have > 0 exceptions."); // Handle Exception by capturing it into an ExceptionDispatchInfo and storing that var exception = exceptionObject as Exception; @@ -265,13 +266,13 @@ namespace System.Threading.Tasks foreach (var exc in exColl) { #if DEBUG - Contract.Assert(exc != null, "No exceptions should be null"); + Debug.Assert(exc != null, "No exceptions should be null"); numExceptions++; #endif exceptions.Add(ExceptionDispatchInfo.Capture(exc)); } #if DEBUG - Contract.Assert(numExceptions > 0, "Collection should contain at least one exception."); + Debug.Assert(numExceptions > 0, "Collection should contain at least one exception."); #endif } else @@ -282,10 +283,10 @@ namespace System.Threading.Tasks { exceptions.AddRange(ediColl); #if DEBUG - Contract.Assert(exceptions.Count > 0, "There should be at least one dispatch info."); + Debug.Assert(exceptions.Count > 0, "There should be at least one dispatch info."); foreach(var tmp in exceptions) { - Contract.Assert(tmp != null, "No dispatch infos should be null"); + Debug.Assert(tmp != null, "No dispatch infos should be null"); } #endif } @@ -365,8 +366,8 @@ namespace System.Threading.Tasks internal AggregateException CreateExceptionObject(bool calledFromFinalizer, Exception includeThisException) { var exceptions = m_faultExceptions; - Contract.Assert(exceptions != null, "Expected an initialized list."); - Contract.Assert(exceptions.Count > 0, "Expected at least one exception."); + Debug.Assert(exceptions != null, "Expected an initialized list."); + Debug.Assert(exceptions.Count > 0, "Expected at least one exception."); // Mark as handled and aggregate the exceptions. MarkAsHandled(calledFromFinalizer); @@ -395,8 +396,8 @@ namespace System.Threading.Tasks internal ReadOnlyCollection GetExceptionDispatchInfos() { var exceptions = m_faultExceptions; - Contract.Assert(exceptions != null, "Expected an initialized list."); - Contract.Assert(exceptions.Count > 0, "Expected at least one exception."); + Debug.Assert(exceptions != null, "Expected an initialized list."); + Debug.Assert(exceptions.Count > 0, "Expected at least one exception."); MarkAsHandled(false); return new ReadOnlyCollection(exceptions); } @@ -411,7 +412,7 @@ namespace System.Threading.Tasks internal ExceptionDispatchInfo GetCancellationExceptionDispatchInfo() { var edi = m_cancellationException; - Contract.Assert(edi == null || edi.SourceException is OperationCanceledException, + Debug.Assert(edi == null || edi.SourceException is OperationCanceledException, "Expected the EDI to be for an OperationCanceledException"); return edi; } diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs b/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs index 699ab5a..9e3bd2e 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs @@ -18,6 +18,7 @@ using System.Security; using System.Security.Permissions; using System.Runtime.CompilerServices; using System.Threading; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Threading.Tasks @@ -1666,7 +1667,7 @@ namespace System.Threading.Tasks TrySetResult(_tasks); } - Contract.Assert(_count >= 0, "Count should never go below 0"); + Debug.Assert(_count >= 0, "Count should never go below 0"); } public bool InvokeMayRunArbitraryCode { get { return true; } } @@ -1746,7 +1747,7 @@ namespace System.Threading.Tasks TrySetResult(_tasks); } - Contract.Assert(_count >= 0, "Count should never go below 0"); + Debug.Assert(_count >= 0, "Count should never go below 0"); } public bool InvokeMayRunArbitraryCode { get { return true; } } @@ -2448,7 +2449,7 @@ namespace System.Threading.Tasks } bool success = TrySetResult(completingTask); - Contract.Assert(success, "Only one task should have gotten to this point, and thus this must be successful."); + Debug.Assert(success, "Only one task should have gotten to this point, and thus this must be successful."); // We need to remove continuations that may be left straggling on other tasks. // Otherwise, repeated calls to WhenAny using the same task could leak actions. diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs b/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs index f778698..6ff7ceb 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs @@ -573,7 +573,7 @@ namespace System.Threading.Tasks schedulers.CopyTo(arr, 0); foreach (var scheduler in arr) { - Contract.Assert(scheduler != null, "Table returned an incorrect Count or CopyTo failed"); + Debug.Assert(scheduler != null, "Table returned an incorrect Count or CopyTo failed"); int tmp = scheduler.Id; // force Ids for debugger } return arr; diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs b/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs index 02b130c..90743ae 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs @@ -22,6 +22,7 @@ // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.IO; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Threading.Tasks @@ -76,7 +77,7 @@ namespace System.Threading.Tasks if (twar != null) { task = twar.Task; - Contract.Assert(task != null, "TaskWrapperAsyncResult should never wrap a null Task."); + Debug.Assert(task != null, "TaskWrapperAsyncResult should never wrap a null Task."); } // Otherwise, the IAsyncResult should be a Task. else @@ -101,7 +102,7 @@ namespace System.Threading.Tasks if (twar != null) { task = twar.Task as Task; - Contract.Assert(twar.Task != null, "TaskWrapperAsyncResult should never wrap a null Task."); + Debug.Assert(twar.Task != null, "TaskWrapperAsyncResult should never wrap a null Task."); } // Otherwise, the IAsyncResult should be a Task. else diff --git a/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs b/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs index 892c611..5c6ca9b 100644 --- a/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs +++ b/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs @@ -13,6 +13,7 @@ using System; using System.Security; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Collections.Generic; using System.Text; @@ -39,7 +40,7 @@ namespace System.Threading.Tasks { Contract.Requires(obj != null, "TaskScheduler.LongRunningThreadWork: obj is null"); Task t = obj as Task; - Contract.Assert(t != null, "TaskScheduler.LongRunningThreadWork: t is null"); + Debug.Assert(t != null, "TaskScheduler.LongRunningThreadWork: t is null"); t.ExecuteEntry(false); } diff --git a/src/mscorlib/src/System/Threading/Tasks/future.cs b/src/mscorlib/src/System/Threading/Tasks/future.cs index d5b2bdb..5a25096 100644 --- a/src/mscorlib/src/System/Threading/Tasks/future.cs +++ b/src/mscorlib/src/System/Threading/Tasks/future.cs @@ -457,7 +457,7 @@ namespace System.Threading.Tasks internal bool TrySetResult(TResult result) { if (IsCompleted) return false; - Contract.Assert(m_action == null, "Task.TrySetResult(): non-null m_action"); + Debug.Assert(m_action == null, "Task.TrySetResult(): non-null m_action"); // "Reserve" the completion for this task, while making sure that: (1) No prior reservation // has been made, (2) The result has not already been set, (3) An exception has not previously @@ -497,7 +497,7 @@ namespace System.Threading.Tasks // the task, avoiding expensive completion paths, before the task is actually given to anyone. internal void DangerousSetResult(TResult result) { - Contract.Assert(!IsCompleted, "The promise must not yet be completed."); + Debug.Assert(!IsCompleted, "The promise must not yet be completed."); // If we have a parent, we need to notify it of the completion. Take the slow path to handle that. if (m_contingentProperties?.m_parent != null) @@ -505,7 +505,7 @@ namespace System.Threading.Tasks bool success = TrySetResult(result); // Nobody else has had a chance to complete this Task yet, so we should succeed. - Contract.Assert(success); + Debug.Assert(success); } else { @@ -539,7 +539,7 @@ namespace System.Threading.Tasks { get { - Contract.Assert(!IsWaitNotificationEnabledOrNotRanToCompletion, + Debug.Assert(!IsWaitNotificationEnabledOrNotRanToCompletion, "Should only be used when the task completed successfully and there's no wait notification enabled"); return m_result; } @@ -558,7 +558,7 @@ namespace System.Threading.Tasks if (!IsRanToCompletion) ThrowIfExceptional(includeTaskCanceledExceptions: true); // We shouldn't be here if the result has not been set. - Contract.Assert(IsRanToCompletion, "Task.Result getter: Expected result to have been set."); + Debug.Assert(IsRanToCompletion, "Task.Result getter: Expected result to have been set."); return m_result; } @@ -572,13 +572,13 @@ namespace System.Threading.Tasks // Called from TaskCompletionSource.SetException(IEnumerable). internal bool TrySetException(object exceptionObject) { - Contract.Assert(m_action == null, "Task.TrySetException(): non-null m_action"); + Debug.Assert(m_action == null, "Task.TrySetException(): non-null m_action"); // TCS.{Try}SetException() should have checked for this - Contract.Assert(exceptionObject != null, "Expected non-null exceptionObject argument"); + Debug.Assert(exceptionObject != null, "Expected non-null exceptionObject argument"); // Only accept these types. - Contract.Assert( + Debug.Assert( (exceptionObject is Exception) || (exceptionObject is IEnumerable) || (exceptionObject is ExceptionDispatchInfo) || (exceptionObject is IEnumerable), "Expected exceptionObject to be either Exception, ExceptionDispatchInfo, or IEnumerable<> of one of those"); @@ -620,10 +620,10 @@ namespace System.Threading.Tasks // This method is only valid for promise tasks. internal bool TrySetCanceled(CancellationToken tokenToRecord, object cancellationException) { - Contract.Assert(m_action == null, "Task.TrySetCanceled(): non-null m_action"); + Debug.Assert(m_action == null, "Task.TrySetCanceled(): non-null m_action"); #if DEBUG var ceAsEdi = cancellationException as ExceptionDispatchInfo; - Contract.Assert( + Debug.Assert( cancellationException == null || cancellationException is OperationCanceledException || (ceAsEdi != null && ceAsEdi.SourceException is OperationCanceledException), @@ -669,7 +669,7 @@ namespace System.Threading.Tasks internal override void InnerInvoke() { // Invoke the delegate - Contract.Assert(m_action != null); + Debug.Assert(m_action != null); var func = m_action as Func; if (func != null) { @@ -682,7 +682,7 @@ namespace System.Threading.Tasks m_result = funcWithState(m_stateObject); return; } - Contract.Assert(false, "Invalid m_action in Task"); + Debug.Assert(false, "Invalid m_action in Task"); } #region Await Support diff --git a/src/mscorlib/src/System/Threading/Thread.cs b/src/mscorlib/src/System/Threading/Thread.cs index bf78fd3..2022c05 100644 --- a/src/mscorlib/src/System/Threading/Thread.cs +++ b/src/mscorlib/src/System/Threading/Thread.cs @@ -19,7 +19,6 @@ namespace System.Threading { using System.Runtime; using System.Runtime.InteropServices; using System; - using System.Diagnostics; using System.Security.Permissions; using System.Security.Principal; using System.Globalization; @@ -29,6 +28,7 @@ namespace System.Threading { using System.Runtime.ConstrainedExecution; using System.Security; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; internal delegate Object InternalCrossContextDelegate(Object[] args); @@ -475,7 +475,7 @@ namespace System.Threading { private void SetStartHelper(Delegate start, int maxStackSize) { // We only support default stacks in CoreCLR - Contract.Assert(maxStackSize == 0); + Debug.Assert(maxStackSize == 0); ThreadHelper threadStartCallBack = new ThreadHelper(start); if(start is ThreadStart) diff --git a/src/mscorlib/src/System/Threading/ThreadLocal.cs b/src/mscorlib/src/System/Threading/ThreadLocal.cs index 1af377f..3495891 100644 --- a/src/mscorlib/src/System/Threading/ThreadLocal.cs +++ b/src/mscorlib/src/System/Threading/ThreadLocal.cs @@ -15,9 +15,9 @@ // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -using System.Diagnostics; using System.Collections.Generic; using System.Security.Permissions; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Threading @@ -193,7 +193,7 @@ namespace System.Threading if (id < 0 || !m_initialized) { - Contract.Assert(id >= 0 || !m_initialized, "expected id >= 0 if initialized"); + Debug.Assert(id >= 0 || !m_initialized, "expected id >= 0 if initialized"); // Handle double Dispose calls or disposal of an instance whose constructor threw an exception. return; @@ -550,7 +550,7 @@ namespace System.Threading /// private void GrowTable(ref LinkedSlotVolatile[] table, int minLength) { - Contract.Assert(table.Length < minLength); + Debug.Assert(table.Length < minLength); // Determine the size of the new table and allocate it. int newLen = GetNewTableSize(minLength); @@ -588,7 +588,7 @@ namespace System.Threading // Intentionally return a value that will result in an OutOfMemoryException return int.MaxValue; } - Contract.Assert(minSize > 0); + Debug.Assert(minSize > 0); // // Round up the size to the next power of 2 @@ -737,7 +737,7 @@ namespace System.Threading ~FinalizationHelper() { LinkedSlotVolatile[] slotArray = SlotArray; - Contract.Assert(slotArray != null); + Debug.Assert(slotArray != null); for (int i = 0; i < slotArray.Length; i++) { @@ -765,7 +765,7 @@ namespace System.Threading } // Since the list uses a dummy head node, the Previous reference should never be null. - Contract.Assert(linkedSlot.Previous != null); + Debug.Assert(linkedSlot.Previous != null); linkedSlot.Previous.Next = linkedSlot.Next; } } diff --git a/src/mscorlib/src/System/Threading/ThreadPool.cs b/src/mscorlib/src/System/Threading/ThreadPool.cs index 7ab8fb3..3af006b 100644 --- a/src/mscorlib/src/System/Threading/ThreadPool.cs +++ b/src/mscorlib/src/System/Threading/ThreadPool.cs @@ -36,6 +36,7 @@ namespace System.Threading using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Collections.Generic; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Tracing; @@ -169,7 +170,7 @@ namespace System.Threading // m_headIndex = m_headIndex & m_mask; m_tailIndex = tail = m_tailIndex & m_mask; - Contract.Assert(m_headIndex <= m_tailIndex); + Debug.Assert(m_headIndex <= m_tailIndex); } } finally @@ -231,7 +232,7 @@ namespace System.Threading IThreadPoolWorkItem unused; if (LocalPop(out unused)) { - Contract.Assert(unused == obj); + Debug.Assert(unused == obj); return true; } return false; @@ -430,23 +431,23 @@ namespace System.Threading upper = (i >> 16) & SixteenBits; lower = i & SixteenBits; - Contract.Assert(upper >= lower); - Contract.Assert(upper <= nodes.Length); - Contract.Assert(lower <= nodes.Length); - Contract.Assert(upper >= 0); - Contract.Assert(lower >= 0); + Debug.Assert(upper >= lower); + Debug.Assert(upper <= nodes.Length); + Debug.Assert(lower <= nodes.Length); + Debug.Assert(upper >= 0); + Debug.Assert(lower >= 0); } bool CompareExchangeIndexes(ref int prevUpper, int newUpper, ref int prevLower, int newLower) { - Contract.Assert(newUpper >= newLower); - Contract.Assert(newUpper <= nodes.Length); - Contract.Assert(newLower <= nodes.Length); - Contract.Assert(newUpper >= 0); - Contract.Assert(newLower >= 0); - Contract.Assert(newUpper >= prevUpper); - Contract.Assert(newLower >= prevLower); - Contract.Assert(newUpper == prevUpper ^ newLower == prevLower); + Debug.Assert(newUpper >= newLower); + Debug.Assert(newUpper <= nodes.Length); + Debug.Assert(newLower <= nodes.Length); + Debug.Assert(newUpper >= 0); + Debug.Assert(newLower >= 0); + Debug.Assert(newUpper >= prevUpper); + Debug.Assert(newLower >= prevLower); + Debug.Assert(newUpper == prevUpper ^ newLower == prevLower); int oldIndexes = (prevUpper << 16) | (prevLower & SixteenBits); int newIndexes = (newUpper << 16) | (newLower & SixteenBits); @@ -459,7 +460,7 @@ namespace System.Threading [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public QueueSegment() { - Contract.Assert(QueueSegmentLength <= SixteenBits); + Debug.Assert(QueueSegmentLength <= SixteenBits); nodes = new IThreadPoolWorkItem[QueueSegmentLength]; } @@ -482,7 +483,7 @@ namespace System.Threading // with a busy-wait loop, waiting for the element to become non-null. This implies // that we can never store null nodes in this data structure. // - Contract.Assert(null != node); + Debug.Assert(null != node); int upper, lower; GetIndexes(out upper, out lower); @@ -494,7 +495,7 @@ namespace System.Threading if (CompareExchangeIndexes(ref upper, upper + 1, ref lower, lower)) { - Contract.Assert(Volatile.Read(ref nodes[upper]) == null); + Debug.Assert(Volatile.Read(ref nodes[upper]) == null); Volatile.Write(ref nodes[upper], node); return true; } @@ -647,7 +648,7 @@ namespace System.Threading WorkStealingQueue wsq = tl.workStealingQueue; if (wsq.LocalPop(out callback)) - Contract.Assert(null != callback); + Debug.Assert(null != callback); if (null == callback) { @@ -656,7 +657,7 @@ namespace System.Threading { if (tail.TryDequeue(out callback)) { - Contract.Assert(null != callback); + Debug.Assert(null != callback); break; } @@ -686,7 +687,7 @@ namespace System.Threading otherQueue != wsq && otherQueue.TrySteal(out callback, ref missedSteal)) { - Contract.Assert(null != callback); + Debug.Assert(null != callback); break; } c--; @@ -844,7 +845,7 @@ namespace System.Threading } // we can never reach this point, but the C# compiler doesn't know that, because it doesn't know the ThreadAbortException will be reraised above. - Contract.Assert(false); + Debug.Assert(false); return true; } } @@ -882,7 +883,7 @@ namespace System.Threading IThreadPoolWorkItem cb = null; if (workStealingQueue.LocalPop(out cb)) { - Contract.Assert(null != cb); + Debug.Assert(null != cb); workQueue.Enqueue(cb, true); } else @@ -1148,7 +1149,7 @@ namespace System.Threading ~QueueUserWorkItemCallback() { - Contract.Assert( + Debug.Assert( executed != 0 || Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload(), "A QueueUserWorkItemCallback was never called!"); } @@ -1156,7 +1157,7 @@ namespace System.Threading void MarkExecuted(bool aborted) { GC.SuppressFinalize(this); - Contract.Assert( + Debug.Assert( 0 == Interlocked.Exchange(ref executed, 1) || aborted, "A QueueUserWorkItemCallback was called twice!"); } @@ -1202,7 +1203,7 @@ namespace System.Threading { QueueUserWorkItemCallback obj = (QueueUserWorkItemCallback)state; WaitCallback wc = obj.callback as WaitCallback; - Contract.Assert(null != wc); + Debug.Assert(null != wc); wc(obj.state); } } @@ -1219,7 +1220,7 @@ namespace System.Threading ~QueueUserWorkItemCallbackDefaultContext() { - Contract.Assert( + Debug.Assert( executed != 0 || Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload(), "A QueueUserWorkItemCallbackDefaultContext was never called!"); } @@ -1227,7 +1228,7 @@ namespace System.Threading void MarkExecuted(bool aborted) { GC.SuppressFinalize(this); - Contract.Assert( + Debug.Assert( 0 == Interlocked.Exchange(ref executed, 1) || aborted, "A QueueUserWorkItemCallbackDefaultContext was called twice!"); } @@ -1262,7 +1263,7 @@ namespace System.Threading { QueueUserWorkItemCallbackDefaultContext obj = (QueueUserWorkItemCallbackDefaultContext)state; WaitCallback wc = obj.callback as WaitCallback; - Contract.Assert(null != wc); + Debug.Assert(null != wc); obj.callback = null; wc(obj.state); } @@ -1312,7 +1313,7 @@ namespace System.Threading static internal void PerformWaitOrTimerCallback(Object state, bool timedOut) { _ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state; - Contract.Assert(helper != null, "Null state passed to PerformWaitOrTimerCallback!"); + Debug.Assert(helper != null, "Null state passed to PerformWaitOrTimerCallback!"); // call directly if it is an unsafe call OR EC flow is suppressed if (helper._executionContext == null) { @@ -1607,7 +1608,7 @@ namespace System.Threading internal static void UnsafeQueueCustomWorkItem(IThreadPoolWorkItem workItem, bool forceGlobal) { - Contract.Assert(null != workItem); + Debug.Assert(null != workItem); EnsureVMInitialized(); // @@ -1623,7 +1624,7 @@ namespace System.Threading // This method tries to take the target callback out of the current thread's queue. internal static bool TryPopCustomWorkItem(IThreadPoolWorkItem workItem) { - Contract.Assert(null != workItem); + Debug.Assert(null != workItem); if (!ThreadPoolGlobals.vmTpInitialized) return false; //Not initialized, so there's no way this workitem was ever queued. return ThreadPoolGlobals.workQueue.LocalFindAndPop(workItem); diff --git a/src/mscorlib/src/System/Threading/Timer.cs b/src/mscorlib/src/System/Threading/Timer.cs index c692892..02f7308 100644 --- a/src/mscorlib/src/System/Threading/Timer.cs +++ b/src/mscorlib/src/System/Threading/Timer.cs @@ -14,6 +14,7 @@ namespace System.Threading using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Diagnostics.Tracing; using Microsoft.Win32.SafeHandles; @@ -149,14 +150,14 @@ namespace System.Threading // A later update during resume will re-schedule if(m_pauseTicks != 0) { - Contract.Assert(!m_isAppDomainTimerScheduled); - Contract.Assert(m_appDomainTimer == null); + Debug.Assert(!m_isAppDomainTimerScheduled); + Debug.Assert(m_appDomainTimer == null); return true; } if (m_appDomainTimer == null || m_appDomainTimer.IsInvalid) { - Contract.Assert(!m_isAppDomainTimerScheduled); + Debug.Assert(!m_isAppDomainTimerScheduled); m_appDomainTimer = CreateAppDomainTimer(actualDuration); if (!m_appDomainTimer.IsInvalid) @@ -258,8 +259,8 @@ namespace System.Threading TimerQueueTimer timer = m_timers; while (timer != null) { - Contract.Assert(timer.m_dueTime != Timeout.UnsignedInfinite); - Contract.Assert(resumedTicks >= timer.m_startTicks); + Debug.Assert(timer.m_dueTime != Timeout.UnsignedInfinite); + Debug.Assert(resumedTicks >= timer.m_startTicks); uint elapsed; // How much of the timer dueTime has already elapsed @@ -332,7 +333,7 @@ namespace System.Threading TimerQueueTimer timer = m_timers; while (timer != null) { - Contract.Assert(timer.m_dueTime != Timeout.UnsignedInfinite); + Debug.Assert(timer.m_dueTime != Timeout.UnsignedInfinite); uint elapsed = (uint)(nowTicks - timer.m_startTicks); if (elapsed >= timer.m_dueTime) diff --git a/src/mscorlib/src/System/ThrowHelper.cs b/src/mscorlib/src/System/ThrowHelper.cs index 74a08cd..a534dec 100644 --- a/src/mscorlib/src/System/ThrowHelper.cs +++ b/src/mscorlib/src/System/ThrowHelper.cs @@ -39,6 +39,7 @@ namespace System { using Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.Serialization; + using System.Diagnostics; using System.Diagnostics.Contracts; [Pure] @@ -261,7 +262,7 @@ namespace System { // Second function in chain so as to not propergate the non-inlining to outside caller [MethodImpl(MethodImplOptions.NoInlining)] private static string GetArgumentNameInner(ExceptionArgument argument) { - Contract.Assert(Enum.IsDefined(typeof(ExceptionArgument), argument), + Debug.Assert(Enum.IsDefined(typeof(ExceptionArgument), argument), "The enum value is not defined, please check the ExceptionArgument Enum."); return argument.ToString(); @@ -280,7 +281,7 @@ namespace System { // Second function in chain so as to not propergate the non-inlining to outside caller [MethodImpl(MethodImplOptions.NoInlining)] private static string GetResourceStringInner(ExceptionResource resource) { - Contract.Assert(Enum.IsDefined(typeof(ExceptionResource), resource), + Debug.Assert(Enum.IsDefined(typeof(ExceptionResource), resource), "The enum value is not defined, please check the ExceptionResource Enum."); return Environment.GetResourceString(resource.ToString()); diff --git a/src/mscorlib/src/System/TimeZoneInfo.cs b/src/mscorlib/src/System/TimeZoneInfo.cs index 00514fa..72fc28f 100644 --- a/src/mscorlib/src/System/TimeZoneInfo.cs +++ b/src/mscorlib/src/System/TimeZoneInfo.cs @@ -297,7 +297,7 @@ namespace System { private AdjustmentRule[] GetFilledRules() { - Contract.Assert(m_adjustmentRules != null, "m_adjustmentRules expected to be not null"); + Debug.Assert(m_adjustmentRules != null, "m_adjustmentRules expected to be not null"); AdjustmentRule[] rules = new AdjustmentRule[m_adjustmentRules.Length]; for (int i = 0; i < m_adjustmentRules.Length; i++) @@ -2593,7 +2593,7 @@ namespace System { #if FEATURE_WIN32_REGISTRY throw new InvalidTimeZoneException(Environment.GetResourceString("InvalidTimeZone_InvalidRegistryData", id), e); #elif PLATFORM_UNIX - Contract.Assert(e is InvalidTimeZoneException, + Debug.Assert(e is InvalidTimeZoneException, "TryGetTimeZone must create an InvalidTimeZoneException when it returns TimeZoneInfoResult.InvalidTimeZoneException"); throw e; #endif diff --git a/src/mscorlib/src/System/Tuple.cs b/src/mscorlib/src/System/Tuple.cs index 6d41a8b..037b2ce 100644 --- a/src/mscorlib/src/System/Tuple.cs +++ b/src/mscorlib/src/System/Tuple.cs @@ -5,6 +5,7 @@ using System; using System.Text; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; // @@ -923,7 +924,7 @@ namespace System { case 7: return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer)); } - Contract.Assert(false, "Missed all cases for computing Tuple hash code"); + Debug.Assert(false, "Missed all cases for computing Tuple hash code"); return -1; } diff --git a/src/mscorlib/src/System/TypeNameParser.cs b/src/mscorlib/src/System/TypeNameParser.cs index e879a63..8445782 100644 --- a/src/mscorlib/src/System/TypeNameParser.cs +++ b/src/mscorlib/src/System/TypeNameParser.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.IO; using System.Reflection; @@ -123,7 +124,7 @@ namespace System string asmName = GetAssemblyName(); // GetAssemblyName never returns null - Contract.Assert(asmName != null); + Debug.Assert(asmName != null); if (asmName.Length > 0) { @@ -151,7 +152,7 @@ namespace System if (baseType == null) { // Cannot resolve the type. If throwOnError is true we should have already thrown. - Contract.Assert(throwOnError == false); + Debug.Assert(throwOnError == false); return null; } @@ -163,7 +164,7 @@ namespace System types = new Type[typeArguments.Length]; for (int i = 0; i < typeArguments.Length; i++) { - Contract.Assert(typeArguments[i] != null); + Debug.Assert(typeArguments[i] != null); using (TypeNameParser argParser = new TypeNameParser(typeArguments[i])) { @@ -173,7 +174,7 @@ namespace System if (types[i] == null) { // If throwOnError is true argParser.ConstructType should have already thrown. - Contract.Assert(throwOnError == false); + Debug.Assert(throwOnError == false); return null; } } diff --git a/src/mscorlib/src/System/Variant.cs b/src/mscorlib/src/System/Variant.cs index 52ec0ab..2a9593c 100644 --- a/src/mscorlib/src/System/Variant.cs +++ b/src/mscorlib/src/System/Variant.cs @@ -19,6 +19,7 @@ namespace System { using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -309,13 +310,13 @@ namespace System { { vt = VarEnum.VT_ERROR; obj = (Object)(((ErrorWrapper)obj).ErrorCode); - Contract.Assert(obj != null, "obj != null"); + Debug.Assert(obj != null, "obj != null"); } else if (obj is CurrencyWrapper) { vt = VarEnum.VT_CY; obj = (Object)(((CurrencyWrapper)obj).WrappedObject); - Contract.Assert(obj != null, "obj != null"); + Debug.Assert(obj != null, "obj != null"); } else if (obj is BStrWrapper) { diff --git a/src/mscorlib/src/System/Version.cs b/src/mscorlib/src/System/Version.cs index fd5b295..f2ef5d4 100644 --- a/src/mscorlib/src/System/Version.cs +++ b/src/mscorlib/src/System/Version.cs @@ -12,6 +12,7 @@ ===========================================================*/ namespace System { + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Text; using CultureInfo = System.Globalization.CultureInfo; @@ -100,7 +101,7 @@ namespace System { private Version(Version version) { - Contract.Assert(version != null); + Debug.Assert(version != null); _Major = version._Major; _Minor = version._Minor; @@ -257,7 +258,7 @@ namespace System { private const int ZERO_CHAR_VALUE = (int) '0'; private static void AppendPositiveNumber(int num, StringBuilder sb) { - Contract.Assert(num >= 0, "AppendPositiveNumber expect positive numbers"); + Debug.Assert(num >= 0, "AppendPositiveNumber expect positive numbers"); int index = sb.Length; int reminder; @@ -436,10 +437,10 @@ namespace System { } catch (OverflowException e) { return e; } - Contract.Assert(false, "Int32.Parse() did not throw exception but TryParse failed: " + m_exceptionArgument); + Debug.Assert(false, "Int32.Parse() did not throw exception but TryParse failed: " + m_exceptionArgument); return new FormatException(Environment.GetResourceString("Format_InvalidString")); default: - Contract.Assert(false, "Unmatched case in Version.GetVersionParseException() for value: " + m_failure); + Debug.Assert(false, "Unmatched case in Version.GetVersionParseException() for value: " + m_failure); return new ArgumentException(Environment.GetResourceString("Arg_VersionString")); } } diff --git a/src/mscorlib/src/System/WeakReference.cs b/src/mscorlib/src/System/WeakReference.cs index df3629f..d564852 100644 --- a/src/mscorlib/src/System/WeakReference.cs +++ b/src/mscorlib/src/System/WeakReference.cs @@ -16,6 +16,7 @@ namespace System { using System.Security.Permissions; using System.Runtime.CompilerServices; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] @@ -29,7 +30,7 @@ namespace System { // Migrating InheritanceDemands requires this default ctor, so we can mark it SafeCritical protected WeakReference() { - Contract.Assert(false, "WeakReference's protected default ctor should never be used!"); + Debug.Assert(false, "WeakReference's protected default ctor should never be used!"); throw new NotImplementedException(); } diff --git a/src/mscorlib/src/System/_LocalDataStore.cs b/src/mscorlib/src/System/_LocalDataStore.cs index b9659f6..a1fa488 100644 --- a/src/mscorlib/src/System/_LocalDataStore.cs +++ b/src/mscorlib/src/System/_LocalDataStore.cs @@ -17,6 +17,7 @@ namespace System { using System; using System.Threading; using System.Runtime.CompilerServices; + using System.Diagnostics; using System.Diagnostics.Contracts; // Helper class to aid removal of LocalDataStore from the LocalDataStoreMgr @@ -214,7 +215,7 @@ namespace System { int capacity = m_Manager.GetSlotTableLength(); // Validate that the specified capacity is larger than the current one. - Contract.Assert(capacity >= m_DataTable.Length, "LocalDataStore corrupted: capacity >= m_DataTable.Length"); + Debug.Assert(capacity >= m_DataTable.Length, "LocalDataStore corrupted: capacity >= m_DataTable.Length"); // Allocate the new data table. LocalDataStoreElement[] NewDataTable = new LocalDataStoreElement[capacity]; @@ -227,7 +228,7 @@ namespace System { } // Validate that there is enough space in the local data store now - Contract.Assert(slotIdx < m_DataTable.Length, "LocalDataStore corrupted: slotIdx < m_DataTable.Length"); + Debug.Assert(slotIdx < m_DataTable.Length, "LocalDataStore corrupted: slotIdx < m_DataTable.Length"); if (m_DataTable[slotIdx] == null) m_DataTable[slotIdx] = new LocalDataStoreElement(slot.Cookie);