// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace ICSharpCode.NRefactory.Utils { /// /// An immutable stack. /// /// Using 'foreach' on the stack will return the items from top to bottom (in the order they would be popped). /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [Serializable] public sealed class ImmutableStack : IEnumerable { /// /// Gets the empty stack instance. /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "ImmutableStack is immutable")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static readonly ImmutableStack Empty = new ImmutableStack(); readonly T value; readonly ImmutableStack next; private ImmutableStack() { } private ImmutableStack(T value, ImmutableStack next) { this.value = value; this.next = next; } /// /// Pushes an item on the stack. This does not modify the stack itself, but returns a new /// one with the value pushed. /// public ImmutableStack Push(T item) { return new ImmutableStack(item, this); } /// /// Gets the item on the top of the stack. /// /// The stack is empty. public T Peek() { if (IsEmpty) throw new InvalidOperationException("Operation not valid on empty stack."); return value; } /// /// Gets the item on the top of the stack. /// Returns default(T) if the stack is empty. /// public T PeekOrDefault() { return value; } /// /// Gets the stack with the top item removed. /// /// The stack is empty. public ImmutableStack Pop() { if (IsEmpty) throw new InvalidOperationException("Operation not valid on empty stack."); return next; } /// /// Gets if this stack is empty. /// public bool IsEmpty { get { return next == null; } } /// /// Gets an enumerator that iterates through the stack top-to-bottom. /// public IEnumerator GetEnumerator() { ImmutableStack t = this; while (!t.IsEmpty) { yield return t.value; t = t.next; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// public override string ToString() { StringBuilder b = new StringBuilder("[Stack"); foreach (T val in this) { b.Append(' '); b.Append(val); } b.Append(']'); return b.ToString(); } } }