/// <summary>Initializes a new instance of the <see cref="RangeIntersection{T}"/> struct.</summary> /// <param name="intersectionRange">The intersection range.</param> /// <param name="ranges">Intersecting ranges.</param> internal RangeIntersection( #region T4-dont-replace Range <T> intersectionRange, #endregion [NotNull] Range <T>[] ranges) { DebugCode.BugIf( ranges.Any(r => !r.HasIntersection(intersectionRange)), "Ranges should intersect intersectionRange."); IntersectionRange = intersectionRange; _ranges = ranges.AsReadOnly(); }
private void RunCore( IterationMode iterationMode, int repeatCount, List <Measurement> measurements) { DebugCode.BugIf(measurements.Count > 0, "measurements not empty."); DebugCode.BugIf(measurements.Capacity < repeatCount, "measurements capacity not set."); var action = iterationMode.IsIdle() ? IdleAction : MainAction; var resultIterationsCount = ResultIterationsCount; // TODO: reenable after https://github.com/dotnet/BenchmarkDotNet/issues/302#issuecomment-262057686 //if (!iterationMode.IsIdle()) // SetupAction?.Invoke(); ForceGcCollect(); if (ForceAllocations) // DONTTOUCH: DO NOT merge loops as it will produce inaccurate results for microbenchmarks. { for (var i = 0; i < repeatCount; i++) { ForceGcCollect(); var clock = Clock.Start(); action(resultIterationsCount); var clockSpan = clock.Stop(); measurements.Add( new Measurement(0, iterationMode, i + 1, 1, clockSpan.GetNanoseconds())); } } else { for (var i = 0; i < repeatCount; i++) { var clock = Clock.Start(); action(resultIterationsCount); var clockSpan = clock.Stop(); measurements.Add( new Measurement(0, iterationMode, i + 1, 1, clockSpan.GetNanoseconds())); } } ForceGcCollect(); // TODO: reenable after https://github.com/dotnet/BenchmarkDotNet/issues/302#issuecomment-262057686 //if (!iterationMode.IsIdle()) // CleanupAction?.Invoke(); }
public static bool IsSubClass([NotNull] this Type type, [NotNull] Type check) { Code.NotNull(type, nameof(type)); Code.NotNull(check, nameof(check)); if (type == check) { return(false); } while (true) { if (check.IsInterface) { // ReSharper disable once LoopCanBeConvertedToQuery foreach (var interfaceType in type.GetInterfaces()) { if (interfaceType == check || interfaceType.IsSubClass(check)) { return(true); } } } if (type.IsGenericType && !type.IsGenericTypeDefinition) { var definition = type.GetGenericTypeDefinition(); DebugCode.BugIf(definition == null, "definition == null"); if (definition == check || definition.IsSubClass(check)) { return(true); } } type = type.BaseType; if (type == null) { return(false); } if (type == check) { return(true); } } }
void WriteElementType(StringBuilder sb, Type t) { DebugCode.AssertState(t.IsArray || t.IsPointer || t.IsByRef, "Invalid type"); Write(sb, t.GetElementType()); if (t.IsArray) { sb.Append('['); sb.Append(',', t.GetArrayRank() - 1); sb.Append(']'); } else { sb.Append(t.IsPointer ? '*' : '&'); } }
private int FindEdge(Node node, char c, out Node edge) { edge = default; if (node.IsLeaf) { return(-1); } DebugCode.BugIf(node.Children == null, "node.Children == null"); var edgeIndex = node.Children.LowerBound(c, EdgeComparer); if (edgeIndex == node.Children.Count) { return(-1); } edge = GetNode(node.Children[edgeIndex]); return(edge.Length > 0 && InternalData[edge.Begin] == c ? edgeIndex : -1); }
private static void CopyDirectoryIfExists(string source, string target, bool overwrite = false) { DebugIoCode.IsWellFormedPath(source, nameof(source)); DebugIoCode.IsWellFormedPath(target, nameof(target)); source = PathHelpers.EnsureContainerPath(Path.GetFullPath(source)); target = PathHelpers.EnsureContainerPath(Path.GetFullPath(target)); if (!Directory.Exists(source)) { return; } if (!Directory.Exists(target)) { Directory.CreateDirectory(target); } foreach (var sourceDirectory in Directory.GetDirectories(source, "*", SearchOption.AllDirectories)) { DebugCode.BugIf( !sourceDirectory.Substring(0, source.Length).Equals(source, StringComparison.InvariantCultureIgnoreCase), $"GetDirectories() return invalid path. {sourceDirectory} is not a child of {source}"); var targetDirectory = Path.Combine(target, sourceDirectory.Substring(source.Length)); Directory.CreateDirectory(targetDirectory); } foreach (var sourceFile in Directory.GetFiles(source, "*", SearchOption.AllDirectories)) { DebugCode.BugIf( !sourceFile.Substring(0, source.Length).Equals(source, StringComparison.InvariantCultureIgnoreCase), $"GetFiles() return invalid path. {sourceFile} is not a child of {source}"); var targetFile = Path.Combine(target, sourceFile.Substring(source.Length)); if (overwrite || !File.Exists(targetFile)) { File.Copy(sourceFile, targetFile, overwrite); } } }
public string Print() { var sb = new StringBuilder(); var currentIndex = RootNodeIndex; #if LESSTHAN_NET45 var stack = new ListEx <StringLocation>(); #else var stack = new List <StringLocation>(); #endif for (;;) { PrintNodeWithPath(sb, currentIndex, stack); var node = GetNode(currentIndex); if (node.Children != null) { stack.Add(new StringLocation(currentIndex, node.Children.Count - 2)); currentIndex = node.Children[node.Children.Count - 1]; continue; } currentIndex = -1; while (stack.Count > 0) { var t = stack[stack.Count - 1]; stack.RemoveAt(stack.Count - 1); node = GetNode(t.Start); var nextChild = t.Length; if (nextChild >= 0) { DebugCode.BugIf(node.Children == null, "node.Children == null"); currentIndex = node.Children[nextChild]; stack.Add(new StringLocation(t.Start, nextChild - 1)); break; } } if (currentIndex == -1) { break; } } return(sb.ToString()); }
/// <summary>Workaround that enables usage of Microsoft.Diagnostics.Tracing.TraceEvent together with shadow copy assemblies.</summary> /// <remarks>SEE https://github.com/Microsoft/perfview/issues/292</remarks> public static void WorkaroundEnsureNativeDlls() { var etwAssembly = typeof(ETWTraceEventSource).Assembly; var location = Path.GetDirectoryName(etwAssembly.Location); var codebase = etwAssembly.GetAssemblyDirectory(); if (location != null && codebase != null && !location.Equals(codebase, StringComparison.InvariantCultureIgnoreCase)) { DebugCode.BugIf( Path.GetFullPath(location).ToUpperInvariant() == Path.GetFullPath(codebase).ToUpperInvariant(), "Path.GetFullPath(location).ToUpperInvariant() == Path.GetFullPath(codebase).ToUpperInvariant()"); CopyDirectoryIfExists( Path.Combine(codebase, "amd64"), Path.Combine(location, "amd64")); CopyDirectoryIfExists( Path.Combine(codebase, "x86"), Path.Combine(location, "x86")); } }
/// <summary> /// Returns custom attributes applied to provided type member. /// </summary> /// <param name="memberInfo">Type member.</param> /// <param name="inherit"><b>true</b> to search this member's inheritance chain to find the attributes; otherwise, <b>false</b>.</param> /// <typeparam name="T">The type of attribute to search for. Only attributes that are assignable to this member are returned.</typeparam> /// <returns>Array of custom attributes.</returns> public T[] GetAttributes <T>(MemberInfo memberInfo, bool inherit = true) where T : Attribute { var type = memberInfo.DeclaringType; DebugCode.AssertState(type != null, "type != null"); DebugCode.AssertState(type.FullName != null, "type.FullName != null"); if (_types.TryGetValue(type.FullName, out var t) || _types.TryGetValue(type.Name, out t)) { if (t.Members.TryGetValue(memberInfo.Name, out var m)) { return (m .GetAttribute(typeof(T)) .Select(a => (T)a.MakeAttribute(typeof(T))) .ToArray()); } } return(Array <T> .Empty); }
void WriteGenericArguments(StringBuilder sb, Type t) { DebugCode.AssertState(t.GetIsGenericType() && !t.GetIsGenericTypeDefinition(), "Invalid type"); sb.Append('['); var arguments = t.GetGenericArguments(); for (var i = 0; i < arguments.Length; i++) { if (i != 0) { sb.Append(','); } sb.Append('['); WriteFull(sb, arguments[i]); sb.Append(']'); } sb.Append(']'); }
/// <summary>Initializes a new instance of the <see cref="Message" /> class.</summary> /// <param name="runNumber">Number of the run the message belongs to.</param> /// <param name="runMessageNumber">Number of the message in the run.</param> /// <param name="elapsed">Time elapsed from the start of the benchmark.</param> /// <param name="messageSource">Source of the message.</param> /// <param name="messageSeverity">Severity of the message.</param> /// <param name="messageText">Text of the message.</param> /// <param name="hintText">Hints for the message.</param> public Message( int runNumber, int runMessageNumber, TimeSpan elapsed, MessageSource messageSource, MessageSeverity messageSeverity, [NotNull] string messageText, string hintText) { DebugCode.ValidCount(runNumber, nameof(runNumber)); DebugCode.ValidCount(runMessageNumber, nameof(runMessageNumber)); DebugCode.AssertArgument(elapsed > TimeSpan.Zero, nameof(messageSeverity), "Elapsed time should be positive."); DebugEnumCode.Defined(messageSource, nameof(messageSource)); DebugEnumCode.Defined(messageSeverity, nameof(messageSeverity)); Code.NotNullNorEmpty(messageText, nameof(messageText)); RunNumber = runNumber; RunMessageNumber = runMessageNumber; Elapsed = elapsed; MessageSource = messageSource; MessageSeverity = messageSeverity; MessageText = messageText; HintText = hintText; }
private void SetIndexes(int startIndex, int middleIndex, int endIndex) { DebugCode.BugIf(startIndex > middleIndex, "startIndex > middleIndex"); DebugCode.BugIf(middleIndex > endIndex, "middleIndex > endIndex"); if (startIndex == endIndex) { _treeIndexes[startIndex] = startIndex; } else if (startIndex == endIndex - 1) { DebugCode.BugIf(middleIndex != startIndex, "middleIndex != startIndex"); _treeIndexes[endIndex] = endIndex; _treeIndexes[startIndex] = MaxToIndex(startIndex, endIndex); } else if (startIndex == endIndex - 2) { DebugCode.BugIf(middleIndex != startIndex + 1, "middleIndex != startIndex + 1"); _treeIndexes[endIndex] = endIndex; _treeIndexes[startIndex] = MaxToIndex(startIndex, endIndex); _treeIndexes[middleIndex] = MaxToIndex(startIndex, MaxToIndex(middleIndex, endIndex)); } else { DebugCode.BugIf( middleIndex != startIndex + (endIndex - startIndex) / 2, "middleIndex != startIndex + (endIndex-startIndex) / 2"); var newMiddleA = startIndex + (middleIndex - 1 - startIndex) / 2; SetIndexes(startIndex, newMiddleA, middleIndex - 1); var newMiddleB = middleIndex + 1 + (endIndex - (middleIndex + 1)) / 2; SetIndexes(middleIndex + 1, newMiddleB, endIndex); _treeIndexes[middleIndex] = MaxToIndex(_treeIndexes[newMiddleA], MaxToIndex(middleIndex, _treeIndexes[newMiddleB])); } }
public DebugLine(string debugLine, DebugCode status) { this.debugLine = debugLine; this.status = status; }
private static string BufferToString(char[] buffer) { DebugCode.BugIf(buffer[buffer.Length - 1] != 0, "buffer[buffer.Length - 1] != 0"); return(new string(buffer, 0, buffer.Length - 1)); }
/// <summary>Indicates whether the current range is equal to another.</summary> /// <param name="other">A range to compare with this.</param> /// <returns> /// <c>True</c> if the current range is equal to the <paramref name="other"/> parameter; /// otherwise, false. /// </returns> public bool Equals(CompositeRange <T, TKey> other) { // TODO: BADCODE, rewrite if (IsEmpty) { return(other.IsEmpty); } if (other.IsEmpty) { return(false); } DebugCode.BugIf(_ranges == null, "_ranges == null"); DebugCode.BugIf(other._ranges == null, "other._ranges == null"); var otherRanges = other._ranges; if (_containingRange != other._containingRange || _ranges.Count != otherRanges.Count) { return(false); } var previousRange = Range <T> .Empty; var keys = new Dictionary <TKey, int>(); var nullKeysCount = 0; for (var i = 0; i < _ranges.Count; i++) { var currentWithoutKey = _ranges[i].WithoutKey(); // TODO: helper method to compare without key. if (!currentWithoutKey.Equals(otherRanges[i].WithoutKey())) { return(false); } if (currentWithoutKey != previousRange) { var sameKeys = nullKeysCount == 0 && keys.Values.All(a => a == 0); if (!sameKeys) { return(false); } keys.Clear(); nullKeysCount = 0; } var key = _ranges[i].Key; if (key == null) { nullKeysCount++; } else { keys[key] = keys.GetValueOrDefault(key) + 1; } var otherKey = otherRanges[i].Key; if (otherKey == null) { nullKeysCount--; } else { keys[otherKey] = keys.GetValueOrDefault(otherKey) - 1; } previousRange = currentWithoutKey; } return(nullKeysCount == 0 && keys.Values.All(a => a == 0)); }
/// <summary>Finds the next branching point</summary> private void FindBranchingPoint() { var branchNode = GetNode(_branchNodeIndex); var children = branchNode.Children; int childNodeIndex; Node activeEdge; if (_activeEdgeIndex != InvalidNodeIndex) { childNodeIndex = children[_activeEdgeIndex]; activeEdge = GetNode(childNodeIndex); } else { childNodeIndex = InvalidNodeIndex; activeEdge = default(Node); } for (;;) { if (_activeEdgeIndex == InvalidNodeIndex) { DebugCode.AssertState(activeLength_ == 0, "Invalid active state"); if (_currentOffset == _end) { return; } if (branchNode.IsLeaf) { // a new branch return; } var c = InternalData[_currentOffset]; var childIndex = children.LowerBound(c, EdgeComparer); if (childIndex == children.Count) { // a new branch return; } childNodeIndex = children[childIndex]; var edgeNode = GetNode(childNodeIndex); if (InternalData[edgeNode.Begin] != c) { // a new branch return; } activeLength_ = 1; _activeEdgeIndex = childIndex; activeEdge = edgeNode; ++_currentOffset; } var edgeOffset = activeEdge.Begin + activeLength_; var edgeEnd = activeEdge.End; for (;;) { if (edgeOffset == edgeEnd) { // end of the current edge reached _branchNodeIndex = childNodeIndex; branchNode = GetNode(_branchNodeIndex); children = branchNode.Children; _activeEdgeIndex = InvalidNodeIndex; activeEdge = default(Node); activeLength_ = 0; break; } if (_currentOffset == _end) { return; } if (InternalData[edgeOffset] != InternalData[_currentOffset]) { return; } ++activeLength_; ++_currentOffset; ++edgeOffset; } } }
private static string[] ParseCsv(TextReader reader, ref int lineNum, char separator) { var curChar = CharReader.Create(reader); if (curChar.IsEof) { return(null); // EOF reached } if (curChar.IsEol) { lineNum++; return(Array <string> .Empty); } var result = new List <string>(); StringBuilder curField = null; var state = ParserState.ExpectField; var column = 1; while (true) { var skip = false; while (!skip) { switch (state) { case ParserState.ExpectField: if (curChar.IsEof || curChar.IsEol) { if (result.Count > 0) // Special case - empty string not treated as single empty value { result.Add(""); } return(result.ToArray()); } if (curChar.Char == separator) { result.Add(""); state = ParserState.AfterField; break; } skip = true; if (curChar.IsWhitespace) { break; } curField = new StringBuilder(); if (curChar.IsDoubleQuota) { state = ParserState.QuotedField; break; } state = ParserState.Field; curField.Append(curChar.Char); break; case ParserState.Field: DebugCode.BugIf(curField == null, "curField should be not null"); if (curChar.IsEof || curChar.IsEol || curChar.Char == separator) { result.Add(curField.ToString().Trim()); state = ParserState.AfterField; break; } skip = true; curField.Append(curChar.Char); break; case ParserState.QuotedField: DebugCode.BugIf(curField == null, "curField should be not null"); if (curChar.IsEof) { throw new FormatException($"Unexpected EOF at line {lineNum} column {column}"); } skip = true; if (curChar.IsEol) { curField.Append("\r\n"); break; } if (curChar.IsDoubleQuota) { var peek = curChar.Peek(); if (peek.IsDoubleQuota) // Escaped '"' { curField.Append('"'); curChar = curChar.Next(); } else { result.Add(curField.ToString()); state = ParserState.AfterField; } break; } curField.Append(curChar.Char); break; case ParserState.AfterField: if (curChar.IsEof || curChar.IsEol) { return(result.ToArray()); } skip = true; if (curChar.IsWhitespace) { continue; } if (curChar.Char == separator) { state = ParserState.ExpectField; break; } throw new FormatException($"Unexpected char '{curChar.Char}' at line {lineNum} column {column}"); default: throw new ArgumentOutOfRangeException(); } } curChar = curChar.Next(); column++; if (curChar.IsEol) { lineNum++; column = 1; } } }
public DebugLine(string debugLine, DebugCode status) { this.debugLine = debugLine; this.status = status; }
public static string GetShortAssemblyQualifiedName([NotNull] this Type type) { Code.NotNull(type, nameof(type)); void WriteAssemblyName(StringBuilder sb, Type t) { sb.Append(", "); var index = -1; var assemblyFullName = t.Assembly.FullName; while (true) { index = assemblyFullName.IndexOf(',', index + 1); DebugCode.BugIf(index == 0, "Invalid assembly name"); if (index < 0) { sb.Append(assemblyFullName); return; } if (assemblyFullName[index - 1] != '\\') { sb.Append(assemblyFullName, 0, index); return; } } } void WriteGenericArguments(StringBuilder sb, Type t) { DebugCode.AssertState(t.IsGenericType && !t.IsGenericTypeDefinition, "Invalid type"); sb.Append('['); var arguments = t.GetGenericArguments(); for (var i = 0; i < arguments.Length; i++) { if (i != 0) { sb.Append(','); } sb.Append('['); WriteFull(sb, arguments[i]); sb.Append(']'); } sb.Append(']'); } void WriteElementType(StringBuilder sb, Type t) { DebugCode.AssertState(t.IsArray || t.IsPointer || t.IsByRef, "Invalid type"); Write(sb, t.GetElementType()); if (t.IsArray) { sb.Append('['); sb.Append(',', t.GetArrayRank() - 1); sb.Append(']'); } else { sb.Append(t.IsPointer ? '*' : '&'); } } void WriteType(StringBuilder sb, Type t) { if (t.DeclaringType != null) { WriteType(sb, t.DeclaringType); sb.Append('+'); } sb.Append(t.Name); } void Write(StringBuilder sb, Type t) { if (t.IsGenericType && !t.IsGenericTypeDefinition) { WriteType(sb, t); WriteGenericArguments(sb, t); } else if (t.IsArray || t.IsPointer || t.IsByRef) { WriteElementType(sb, t); } else { WriteType(sb, t); } } void WriteFull(StringBuilder sb, Type t) { if (t.Namespace.NotNullNorEmpty()) { sb.Append(t.Namespace); sb.Append('.'); } Write(sb, t); WriteAssemblyName(sb, t); } var builder = new StringBuilder(); WriteFull(builder, type); return(builder.ToString()); }
/// <summary> /// Write line to the console and raise the "LineWritten" event /// </summary> /// /// <param name="text">The debug line</param> /// <param name="code">The status</param> public static void WriteLine(string text, DebugCode code = DebugCode.None) { if (LineWritten != null) LineWritten(null, new DebugEventArgs(text, code)); }
/// <summary> /// Console Debug Args /// </summary> /// <param name="text">The debug line</param> /// <param name="code">The status</param> public DebugEventArgs(string text, DebugCode code) { this.Text = text; this.Code = code; }
/// <summary> /// Update the last written line /// </summary> /// <param name="text">The debug line</param> /// <param name="code">The status</param> public static void UpdateLine(string text, DebugCode code = DebugCode.None) { if (UpdateLastLine != null) UpdateLastLine(null, new DebugEventArgs(text, code)); }
private static Expression TransformInternal([CanBeNull] this Expression expr, [NotNull, InstantHandle] Func <Expression, Expression> func) { if (expr == null) { return(null); } { var ex = func(expr); if (ex != expr) { return(ex); } } switch (expr.NodeType) { case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.And: case ExpressionType.AndAlso: case ExpressionType.ArrayIndex: case ExpressionType.Assign: case ExpressionType.Coalesce: case ExpressionType.Divide: case ExpressionType.Equal: case ExpressionType.ExclusiveOr: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.LeftShift: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.Modulo: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.NotEqual: case ExpressionType.Or: case ExpressionType.OrElse: case ExpressionType.Power: case ExpressionType.RightShift: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: case ExpressionType.AddAssign: case ExpressionType.AndAssign: case ExpressionType.DivideAssign: case ExpressionType.ExclusiveOrAssign: case ExpressionType.LeftShiftAssign: case ExpressionType.ModuloAssign: case ExpressionType.MultiplyAssign: case ExpressionType.OrAssign: case ExpressionType.PowerAssign: case ExpressionType.RightShiftAssign: case ExpressionType.SubtractAssign: case ExpressionType.AddAssignChecked: case ExpressionType.MultiplyAssignChecked: case ExpressionType.SubtractAssignChecked: { var e = (BinaryExpression)expr; return(e.Update( TransformInternal(e.Left, func), (LambdaExpression)TransformInternal(e.Conversion, func), TransformInternal(e.Right, func))); } case ExpressionType.ArrayLength: case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.Not: case ExpressionType.Quote: case ExpressionType.TypeAs: case ExpressionType.UnaryPlus: case ExpressionType.Decrement: case ExpressionType.Increment: case ExpressionType.IsFalse: case ExpressionType.IsTrue: case ExpressionType.Throw: case ExpressionType.Unbox: case ExpressionType.PreIncrementAssign: case ExpressionType.PreDecrementAssign: case ExpressionType.PostIncrementAssign: case ExpressionType.PostDecrementAssign: case ExpressionType.OnesComplement: { var e = (UnaryExpression)expr; return(e.Update(TransformInternal(e.Operand, func))); } case ExpressionType.Call: { var e = (MethodCallExpression)expr; return(e.Update( TransformInternal(e.Object, func), TransformInternal(e.Arguments, func))); } case ExpressionType.Conditional: { var e = (ConditionalExpression)expr; return(e.Update( TransformInternal(e.Test, func), TransformInternal(e.IfTrue, func), TransformInternal(e.IfFalse, func))); } case ExpressionType.Invoke: { var e = (InvocationExpression)expr; return(e.Update( TransformInternal(e.Expression, func), TransformInternal(e.Arguments, func))); } case ExpressionType.Lambda: { var e = (LambdaExpression)expr; var b = TransformInternal(e.Body, func); var p = TransformInternal(e.Parameters, func); return(b != e.Body || !ReferenceEquals(p, e.Parameters) ? Expression.Lambda(expr.Type, b, p.ToArray()) : expr); } case ExpressionType.ListInit: { var e = (ListInitExpression)expr; return(e.Update( (NewExpression)TransformInternal(e.NewExpression, func), TransformInternal( e.Initializers, p => { var args = TransformInternal(p.Arguments, func); return !ReferenceEquals(args, p.Arguments) ? Expression.ElementInit(p.AddMethod, args) : p; }))); } case ExpressionType.MemberAccess: { var e = (MemberExpression)expr; DebugCode.BugIf(e.Expression == null, "e.Expression == null"); return(e.Update(TransformInternal(e.Expression, func))); } case ExpressionType.MemberInit: { MemberBinding Modify(MemberBinding b) { switch (b.BindingType) { case MemberBindingType.Assignment: { var ma = (MemberAssignment)b; return(ma.Update(TransformInternal(ma.Expression, func))); } case MemberBindingType.ListBinding: { var ml = (MemberListBinding)b; return(ml.Update(TransformInternal(ml.Initializers, p => { var args = TransformInternal(p.Arguments, func); return !ReferenceEquals(args, p.Arguments) ? Expression.ElementInit(p.AddMethod, args) : p; }))); } case MemberBindingType.MemberBinding: { var mm = (MemberMemberBinding)b; return(mm.Update(TransformInternal(mm.Bindings, Modify))); } } return(b); } var e = (MemberInitExpression)expr; return(e.Update( (NewExpression)TransformInternal(e.NewExpression, func), TransformInternal(e.Bindings, Modify))); } case ExpressionType.New: { var e = (NewExpression)expr; return(e.Update(TransformInternal(e.Arguments, func))); } case ExpressionType.NewArrayBounds: case ExpressionType.NewArrayInit: { var e = (NewArrayExpression)expr; return(e.Update(TransformInternal(e.Expressions, func))); } case ExpressionType.TypeEqual: case ExpressionType.TypeIs: { var e = (TypeBinaryExpression)expr; return(e.Update(TransformInternal(e.Expression, func))); } case ExpressionType.Block: { var e = (BlockExpression)expr; return(e.Update( TransformInternal(e.Variables, func), TransformInternal(e.Expressions, func))); } case ExpressionType.DebugInfo: case ExpressionType.Default: case ExpressionType.Extension: case ExpressionType.Constant: case ExpressionType.Parameter: return(expr); case ExpressionType.Dynamic: { var e = (DynamicExpression)expr; return(e.Update(TransformInternal(e.Arguments, func))); } case ExpressionType.Goto: { var e = (GotoExpression)expr; return(e.Update(e.Target, TransformInternal(e.Value, func))); } case ExpressionType.Index: { var e = (IndexExpression)expr; DebugCode.BugIf(e.Object == null, "e.Object == null"); return(e.Update( TransformInternal(e.Object, func), TransformInternal(e.Arguments, func))); } case ExpressionType.Label: { var e = (LabelExpression)expr; return(e.Update(e.Target, TransformInternal(e.DefaultValue, func))); } case ExpressionType.RuntimeVariables: { var e = (RuntimeVariablesExpression)expr; return(e.Update(TransformInternal(e.Variables, func))); } case ExpressionType.Loop: { var e = (LoopExpression)expr; return(e.Update(e.BreakLabel, e.ContinueLabel, TransformInternal(e.Body, func))); } case ExpressionType.Switch: { var e = (SwitchExpression)expr; return(e.Update( TransformInternal(e.SwitchValue, func), TransformInternal( e.Cases, cs => cs.Update(TransformInternal(cs.TestValues, func), TransformInternal(cs.Body, func))), TransformInternal(e.DefaultBody, func))); } case ExpressionType.Try: { var e = (TryExpression)expr; return(e.Update( TransformInternal(e.Body, func), TransformInternal( e.Handlers, h => h.Update( (ParameterExpression)TransformInternal(h.Variable, func), TransformInternal(h.Filter, func), TransformInternal(h.Body, func))), TransformInternal(e.Finally, func), TransformInternal(e.Fault, func))); } } throw new InvalidOperationException(); }
/// <summary>Creates a pending link</summary> /// <param name="toNodeIndex">The node to link to</param> private void CreatePendingLink(int toNodeIndex) { DebugCode.AssertState(LinkPending, "Pending link should be present"); _nodeLinks.Value[_pendingLinkIndexFrom] = toNodeIndex; _pendingLinkIndexFrom = InvalidNodeIndex; }
/// <summary>Inserts a new suffix at the current position</summary> private void InsertSuffix() { Node insertionNode; int insertionNodeIndex; var branchNode = GetNode(_branchNodeIndex); if (_activeEdgeIndex != InvalidNodeIndex) { var branchChildren = branchNode.Children; var edgeNodeIndex = branchChildren[_activeEdgeIndex]; // need to create a new internal node var edgeNode = GetNode(edgeNodeIndex); DebugCode.AssertState(activeLength_ < edgeNode.Length, "Invalid active state"); var newEdgeNode = new Node(edgeNode.Begin, edgeNode.Begin + activeLength_, false , new List <int> { edgeNodeIndex }); var newEdgeNodeIndex = AddNode(newEdgeNode); var updatedEdgeNode = new Node(newEdgeNode.End, edgeNode.End, edgeNode.IsTerminal , edgeNode.Children); UpdateNode(edgeNodeIndex, updatedEdgeNode); branchChildren[_activeEdgeIndex] = newEdgeNodeIndex; insertionNode = newEdgeNode; insertionNodeIndex = newEdgeNodeIndex; } else { DebugCode.AssertState(activeLength_ == 0, "Invalid active state"); insertionNode = branchNode; insertionNodeIndex = _branchNodeIndex; } // insert a new child edge var children = insertionNode.Children; int childNodeIndex; if (children == null) { children = new List <int>(); var insertionNodeEnd = insertionNode.End; var updatedNode = new Node(insertionNode.Begin, insertionNodeEnd, false, children); if (insertionNode.IsTerminal) { // Do a split. New children: an empty terminal node and a new suffix node (will be added later) var newTerminal = new Node(insertionNodeEnd, insertionNodeEnd, true); var newTerminalIndex = AddNode(newTerminal); children.Add(newTerminalIndex); } UpdateNode(insertionNodeIndex, updatedNode); // insertionNode = updatedNode not needed since insertionNode value is not used later childNodeIndex = children.Count; } else { childNodeIndex = _currentOffset == _end ? 0 // empty nodes always at the beginning : children.LowerBound(InternalData[_currentOffset], EdgeComparer); } // now we have a non-empty children and an insertion index // just do an insert var newNode = new Node(_currentOffset, _end, true); var newIndex = AddNode(newNode); children.Insert(childNodeIndex, newIndex); // create a link if needed if (LinkPending) { CreatePendingLink(insertionNodeIndex); } // and mask a branching node as link pending if it is not the root if (insertionNodeIndex != RootNodeIndex) { _pendingLinkIndexFrom = insertionNodeIndex; } }
/// <summary> /// Console Debug Args /// </summary> /// <param name="text">The debug line</param> /// <param name="code">The status</param> public DebugEventArgs(string text, DebugCode code) { this.Text = text; this.Code = code; }