1
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
2
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
5
using System.Collections.Generic;
6
using System.Diagnostics;
9
namespace ICSharpCode.NRefactory.Utils
12
/// An immutable stack.
14
/// Using 'foreach' on the stack will return the items from top to bottom (in the order they would be popped).
16
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
17
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
19
public sealed class ImmutableStack<T> : IEnumerable<T>
22
/// Gets the empty stack instance.
24
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "ImmutableStack is immutable")]
25
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")]
26
public static readonly ImmutableStack<T> Empty = new ImmutableStack<T>();
29
readonly ImmutableStack<T> next;
31
private ImmutableStack()
35
private ImmutableStack(T value, ImmutableStack<T> next)
42
/// Pushes an item on the stack. This does not modify the stack itself, but returns a new
43
/// one with the value pushed.
45
public ImmutableStack<T> Push(T item)
47
return new ImmutableStack<T>(item, this);
51
/// Gets the item on the top of the stack.
53
/// <exception cref="InvalidOperationException">The stack is empty.</exception>
57
throw new InvalidOperationException("Operation not valid on empty stack.");
62
/// Gets the item on the top of the stack.
63
/// Returns <c>default(T)</c> if the stack is empty.
65
public T PeekOrDefault()
71
/// Gets the stack with the top item removed.
73
/// <exception cref="InvalidOperationException">The stack is empty.</exception>
74
public ImmutableStack<T> Pop()
77
throw new InvalidOperationException("Operation not valid on empty stack.");
82
/// Gets if this stack is empty.
85
get { return next == null; }
89
/// Gets an enumerator that iterates through the stack top-to-bottom.
91
public IEnumerator<T> GetEnumerator()
93
ImmutableStack<T> t = this;
100
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
102
return this.GetEnumerator();
106
public override string ToString()
108
StringBuilder b = new StringBuilder("[Stack");
109
foreach (T val in this) {