forked from MochiLibraries/Biohazrd
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCSharpCodeWriter.NamespaceHandling.cs
261 lines (207 loc) · 12.1 KB
/
CSharpCodeWriter.NamespaceHandling.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace Biohazrd.CSharp
{
partial class CSharpCodeWriter
{
private readonly SortedSet<string> UsingNamespaces = new SortedSet<string>(StringComparer.InvariantCulture);
private readonly Stack<NamespaceScope> NamespaceScopeStack = new();
private int TopNamespaceIndentLevel = 0;
public string? CurrentNamespace => NamespaceScopeStack.TryPeek(out NamespaceScope? currentNamespaceScope) ? currentNamespaceScope.FullNamespaceName : null;
public bool IsInNamespaceOrRoot => TopNamespaceIndentLevel == IndentLevel;
// Soft-ended namespaces are used to allow merging compatible namespaces written one after another
private readonly Queue<NamespaceScope> SoftEndedNamespaceScopes = new();
private bool SuppressSoftEndedNamespaceFlushOnWrite = false;
private void FlushEndedNamespaces()
{
while (SoftEndedNamespaceScopes.TryDequeue(out NamespaceScope? namespaceScope))
{ namespaceScope.ActuallyEndScope(); }
}
protected override void BeforeWrite()
{
if (!SuppressSoftEndedNamespaceFlushOnWrite)
{ FlushEndedNamespaces(); }
base.BeforeWrite();
}
protected override void BeforeFinish()
{
FlushEndedNamespaces();
base.BeforeFinish();
}
private bool IsChildNamespaceOf(string childNamespace, string parentNamespace, [NotNullWhen(true)] out string? commonPrefix)
// The . suffix ensures that dissimilar namespaces with a common root are not considered common
// (IE: This handles a type from InfectedDirectX.Direct3D12 referencing a type from InfectedDirectX.Direct3D)
=> $"{childNamespace}.".StartsWith(commonPrefix = $"{parentNamespace}.");
private bool IsChildNamespaceOf(string childNamespace, string parentNamespace)
=> IsChildNamespaceOf(childNamespace, parentNamespace, out _);
/// <summary>Adds a using statement for the specified namespace to the top of this file.</summary>
/// <remarks>
/// Does nothing if the specified namespace is null or is already in scope.
///
/// Using statements are automatically sorted and de-duplicated.
/// </remarks>
public void Using(string? fullNamespaceName)
{
if (fullNamespaceName is null)
{ return; }
if (fullNamespaceName.Length == 0)
{ throw new ArgumentException("The namespace name must not be empty.", nameof(fullNamespaceName)); }
fullNamespaceName = SanitizeNamespace(fullNamespaceName);
// If we're currently within the requested namespace, don't emit a using
if (CurrentNamespace is string currentNamespace && IsChildNamespaceOf(currentNamespace, fullNamespaceName))
{ return; }
UsingNamespaces.Add(fullNamespaceName);
}
/// <summary>Writes a scoped namespace block to the file</summary>
/// <param name="fullNamespaceName">The full name for the namespace, may be null to skip emitting a namespace scope.</param>
/// <remarks>If the file is currently writing into a namespace, the specified namespace must be a child of the current one.</remarks>
public NamespaceScope Namespace(string? fullNamespaceName)
{
if (fullNamespaceName is null)
{ return NamespaceScope.Null; }
if (fullNamespaceName.Length == 0)
{ throw new ArgumentException("The namespace name must not be empty.", nameof(fullNamespaceName)); }
fullNamespaceName = SanitizeNamespace(fullNamespaceName);
string? currentNamespace = CurrentNamespace;
// Figure out if this namespace causes any soft-ended namespaces to restore
ImmutableArray<NamespaceScope> revivedNamespaceScopes = ImmutableArray<NamespaceScope>.Empty;
while (SoftEndedNamespaceScopes.TryDequeue(out NamespaceScope? softEndedNamespace))
{
// If the soft-ended namespace is not a parent of the namespace we're writing, end it and check the next one
if (!IsChildNamespaceOf(fullNamespaceName, softEndedNamespace.FullNamespaceName))
{
softEndedNamespace.ActuallyEndScope();
continue;
}
// The reviving namespace becomes the "current" namespace since this namespace will be nested within it
currentNamespace = softEndedNamespace.FullNamespaceName;
// If this namespace matches exactly, it will be a direct revive rather than creating a new scope
int revivedNamespaceScopesCount = SoftEndedNamespaceScopes.Count;
bool isDirectRevive = false;
if (fullNamespaceName == softEndedNamespace.FullNamespaceName)
{ isDirectRevive = true; }
else
{ revivedNamespaceScopesCount++; }
// If the soft-ended namespace is a parent of our namespace, revive it and all remaining namespaces
// (We do all remaining because all remaining scopes should be parents of the current soft-ended scope and therefore also parents of the new namespace.)
ImmutableArray<NamespaceScope>.Builder revivedNamespaceScopesBuilder = ImmutableArray.CreateBuilder<NamespaceScope>(revivedNamespaceScopesCount);
if (!isDirectRevive)
{ revivedNamespaceScopesBuilder.Add(softEndedNamespace); }
while (SoftEndedNamespaceScopes.TryDequeue(out NamespaceScope? remainingScope))
{
Debug.Assert(IsChildNamespaceOf(fullNamespaceName, remainingScope.FullNamespaceName));
revivedNamespaceScopesBuilder.Add(remainingScope);
}
revivedNamespaceScopes = revivedNamespaceScopesBuilder.MoveToImmutable();
// Handle direct revive
if (isDirectRevive)
{
softEndedNamespace.Revive(revivedNamespaceScopes);
return softEndedNamespace;
}
}
// Make sure we're in a place where a namespace makes conceptual sense
if (!IsInNamespaceOrRoot)
{
Debug.Assert(IndentLevel > TopNamespaceIndentLevel); // If the indent level is below the top namespace indent level, our state is corrupted
throw new InvalidOperationException("The namespace cannot be changed in the current scope.");
}
// If we're currently within a namespace, ensure the specfied namespace is a child of the current one and figure out the partial namespace to write out
string partialNamespaceName = fullNamespaceName;
if (currentNamespace is not null)
{
// Special case: If the current namespace is exactly the requested namespace, don't enter a new scope
if (fullNamespaceName == currentNamespace)
{ return NamespaceScope.Null; }
string? parentNamespacePrefix;
if (!IsChildNamespaceOf(fullNamespaceName, currentNamespace, out parentNamespacePrefix))
{ throw new ArgumentException($"'{fullNamespaceName}' is not a child of the current namespace '{currentNamespace}'.", nameof(fullNamespaceName)); }
partialNamespaceName = fullNamespaceName.Substring(parentNamespacePrefix.Length);
}
return new NamespaceScope(this, fullNamespaceName, partialNamespaceName, revivedNamespaceScopes);
}
public sealed class NamespaceScope : IDisposable
{
private readonly CSharpCodeWriter? Writer;
private readonly int ExpectedIndentLevel;
internal string FullNamespaceName { get; }
private ImmutableArray<NamespaceScope> RevivedScopes;
internal static readonly NamespaceScope Null = new NamespaceScope();
private NamespaceScope()
{
Writer = null;
ExpectedIndentLevel = Int32.MinValue;
FullNamespaceName = "<NULL>";
}
internal NamespaceScope(CSharpCodeWriter writer, string fullNamespaceName, string partialNamespaceName, ImmutableArray<NamespaceScope> revivedScopes)
{
if (writer is null)
{ throw new ArgumentNullException(nameof(writer)); }
Writer = writer;
FullNamespaceName = fullNamespaceName;
RevivedScopes = revivedScopes;
Debug.Assert(RevivedScopes.All(s => s.RevivedScopes.IsEmpty), "Revived scopes should not have revived scopes!");
Writer.EnsureSeparation();
Writer.WriteLine($"namespace {partialNamespaceName}");
Writer.WriteLine("{");
Writer.NoSeparationNeededBeforeNextLine();
Writer.IndentLevel++;
ExpectedIndentLevel = Writer.IndentLevel;
// Make the current indent level as the top namespace indent level
Debug.Assert((Writer.TopNamespaceIndentLevel + 1) == Writer.IndentLevel);
Writer.TopNamespaceIndentLevel = Writer.IndentLevel;
Writer.NamespaceScopeStack.Push(this);
}
internal void Revive(ImmutableArray<NamespaceScope> otherRevivedScopes)
{
if (Writer is null)
{ throw new InvalidOperationException("The null scope cannot be revived."); }
if (Writer.NamespaceScopeStack.Contains(this) || !RevivedScopes.IsEmpty)
{ throw new InvalidOperationException("The scope is not in a state where it can be revived."); }
RevivedScopes = otherRevivedScopes;
Writer.NamespaceScopeStack.Push(this);
}
internal void ActuallyEndScope()
{
if (Writer is null)
{ throw new InvalidOperationException("The null scope should never be actually ended!"); }
if (Writer.IndentLevel != ExpectedIndentLevel)
{ throw new InvalidOperationException("Indent level is not where it should be to actually end this scope!"); }
Debug.Assert(Writer.IndentLevel == Writer.TopNamespaceIndentLevel);
Writer.IndentLevel--;
Writer.TopNamespaceIndentLevel--;
Debug.Assert(!Writer.SuppressSoftEndedNamespaceFlushOnWrite);
try
{
Writer.SuppressSoftEndedNamespaceFlushOnWrite = true;
Writer.WriteLine('}');
}
finally
{ Writer.SuppressSoftEndedNamespaceFlushOnWrite = false; }
}
void IDisposable.Dispose()
{
if (Writer is null)
{ return; }
if (Writer.NamespaceScopeStack.Peek() != this)
{ throw new InvalidOperationException("The current file namespace is not what it should be to end this scope!"); }
if ((Writer.IndentLevel - Writer.SoftEndedNamespaceScopes.Count) != ExpectedIndentLevel)
{ throw new InvalidOperationException("Indent level is not where it should be to end this scope!"); }
NamespaceScope poppedScope = Writer.NamespaceScopeStack.Pop();
Debug.Assert(poppedScope == this);
Writer.SoftEndedNamespaceScopes.Enqueue(this);
// Dispose of all revived scopes too
foreach (NamespaceScope revivedScope in RevivedScopes)
{ Writer.SoftEndedNamespaceScopes.Enqueue(revivedScope); }
// Clear our revived scopes list so we can be revived if needed
RevivedScopes = ImmutableArray<NamespaceScope>.Empty;
}
public override string ToString()
=> $"{nameof(NamespaceScope)}<{FullNamespaceName}>";
}
}
}