-
Notifications
You must be signed in to change notification settings - Fork 4k
/
GeneratedNames.cs
550 lines (462 loc) · 21.4 KB
/
GeneratedNames.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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal static partial class GeneratedNames
{
internal const string SynthesizedLocalNamePrefix = "CS$";
internal const char DotReplacementInTypeNames = '-';
private const string SuffixSeparator = "__";
private const char IdSeparator = '_';
private const char GenerationSeparator = '#';
private const char LocalFunctionNameTerminator = '|';
internal static bool IsGeneratedMemberName(string memberName)
{
return memberName.Length > 0 && memberName[0] == '<';
}
internal static string MakeBackingFieldName(string propertyName)
{
Debug.Assert((char)GeneratedNameKind.AutoPropertyBackingField == 'k');
return "<" + propertyName + ">k__BackingField";
}
internal static string MakeIteratorFinallyMethodName(int iteratorState)
{
// we can pick any name, but we will try to do
// <>m__Finally1
// <>m__Finally2
// <>m__Finally3
// . . .
// that will roughly match native naming scheme and may also be easier when need to debug.
Debug.Assert((char)GeneratedNameKind.IteratorFinallyMethod == 'm');
return "<>m__Finally" + StringExtensions.GetNumeral(Math.Abs(iteratorState + 2));
}
internal static string MakeStaticLambdaDisplayClassName(int methodOrdinal, int generation)
{
return MakeMethodScopedSynthesizedName(GeneratedNameKind.LambdaDisplayClass, methodOrdinal, generation);
}
internal static string MakeLambdaDisplayClassName(int methodOrdinal, int generation, int closureOrdinal, int closureGeneration)
{
// -1 for singleton static lambdas
Debug.Assert(closureOrdinal >= -1);
Debug.Assert(methodOrdinal >= 0);
return MakeMethodScopedSynthesizedName(GeneratedNameKind.LambdaDisplayClass, methodOrdinal, generation, suffix: "DisplayClass", entityOrdinal: closureOrdinal, entityGeneration: closureGeneration);
}
internal static string MakeAnonymousTypeTemplateName(int index, int submissionSlotIndex, string moduleId)
{
var name = "<" + moduleId + ">f__AnonymousType" + StringExtensions.GetNumeral(index);
if (submissionSlotIndex >= 0)
{
name += "#" + StringExtensions.GetNumeral(submissionSlotIndex);
}
return name;
}
internal const string AnonymousNamePrefix = "<>f__AnonymousType";
internal static bool TryParseAnonymousTypeTemplateName(string name, out int index)
{
// No callers require anonymous types from net modules,
// so names with module id are ignored.
if (name.StartsWith(AnonymousNamePrefix, StringComparison.Ordinal))
{
if (int.TryParse(name.Substring(AnonymousNamePrefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out index))
{
return true;
}
}
index = -1;
return false;
}
internal static string MakeAnonymousTypeBackingFieldName(string propertyName)
{
return "<" + propertyName + ">i__Field";
}
internal static string MakeAnonymousTypeParameterName(string propertyName)
{
return "<" + propertyName + ">j__TPar";
}
internal static bool TryParseAnonymousTypeParameterName(string typeParameterName, out string propertyName)
{
if (typeParameterName.StartsWith("<", StringComparison.Ordinal) &&
typeParameterName.EndsWith(">j__TPar", StringComparison.Ordinal))
{
propertyName = typeParameterName.Substring(1, typeParameterName.Length - 9);
return true;
}
propertyName = null;
return false;
}
internal static string MakeStateMachineTypeName(string methodName, int methodOrdinal, int generation)
{
Debug.Assert(generation >= 0);
Debug.Assert(methodOrdinal >= -1);
return MakeMethodScopedSynthesizedName(GeneratedNameKind.StateMachineType, methodOrdinal, generation, methodName);
}
internal static string MakeBaseMethodWrapperName(int uniqueId)
{
Debug.Assert((char)GeneratedNameKind.BaseMethodWrapper == 'n');
return "<>n__" + StringExtensions.GetNumeral(uniqueId);
}
internal static string MakeLambdaMethodName(string methodName, int methodOrdinal, int methodGeneration, int lambdaOrdinal, int lambdaGeneration)
{
Debug.Assert(methodOrdinal >= -1);
Debug.Assert(methodGeneration >= 0);
Debug.Assert(lambdaOrdinal >= 0);
Debug.Assert(lambdaGeneration >= 0);
// The EE displays the containing method name and unique id in the stack trace,
// and uses it to find the original binding context.
return MakeMethodScopedSynthesizedName(GeneratedNameKind.LambdaMethod, methodOrdinal, methodGeneration, methodName, entityOrdinal: lambdaOrdinal, entityGeneration: lambdaGeneration);
}
internal static string MakeLambdaCacheFieldName(int methodOrdinal, int generation, int lambdaOrdinal, int lambdaGeneration)
{
Debug.Assert(methodOrdinal >= -1);
Debug.Assert(lambdaOrdinal >= 0);
return MakeMethodScopedSynthesizedName(GeneratedNameKind.LambdaCacheField, methodOrdinal, generation, entityOrdinal: lambdaOrdinal, entityGeneration: lambdaGeneration);
}
internal static string MakeLocalFunctionName(string methodName, string localFunctionName, int methodOrdinal, int methodGeneration, int lambdaOrdinal, int lambdaGeneration)
{
Debug.Assert(methodOrdinal >= -1);
Debug.Assert(methodGeneration >= 0);
Debug.Assert(lambdaOrdinal >= 0);
Debug.Assert(lambdaGeneration >= 0);
return MakeMethodScopedSynthesizedName(GeneratedNameKind.LocalFunction, methodOrdinal, methodGeneration, methodName, localFunctionName, LocalFunctionNameTerminator, lambdaOrdinal, lambdaGeneration);
}
private static string MakeMethodScopedSynthesizedName(
GeneratedNameKind kind,
int methodOrdinal,
int methodGeneration,
string methodNameOpt = null,
string suffix = null,
char suffixTerminator = default,
int entityOrdinal = -1,
int entityGeneration = -1)
{
Debug.Assert(methodOrdinal >= -1);
Debug.Assert(methodGeneration >= 0 || methodGeneration == -1 && methodOrdinal == -1);
Debug.Assert(entityOrdinal >= -1);
Debug.Assert(entityGeneration >= 0 || entityGeneration == -1 && entityOrdinal == -1);
Debug.Assert(entityGeneration == -1 || entityGeneration >= methodGeneration);
var result = PooledStringBuilder.GetInstance();
var builder = result.Builder;
builder.Append('<');
if (methodNameOpt != null)
{
builder.Append(methodNameOpt);
// CLR generally allows names with dots, however some APIs like IMetaDataImport
// can only return full type names combined with namespaces.
// see: http://msdn.microsoft.com/en-us/library/ms230143.aspx (IMetaDataImport::GetTypeDefProps)
// When working with such APIs, names with dots become ambiguous since metadata
// consumer cannot figure where namespace ends and actual type name starts.
// Therefore it is a good practice to avoid type names with dots.
// As a replacement use a character not allowed in C# identifier to avoid conflicts.
if (kind.IsTypeName())
{
builder.Replace('.', DotReplacementInTypeNames);
}
}
builder.Append('>');
builder.Append((char)kind);
if (suffix != null || methodOrdinal >= 0 || entityOrdinal >= 0)
{
builder.Append(SuffixSeparator);
builder.Append(suffix);
if (suffixTerminator != default)
{
builder.Append(suffixTerminator);
}
if (methodOrdinal >= 0)
{
builder.Append(methodOrdinal);
AppendOptionalGeneration(builder, methodGeneration);
}
if (entityOrdinal >= 0)
{
if (methodOrdinal >= 0)
{
builder.Append(IdSeparator);
}
builder.Append(entityOrdinal);
AppendOptionalGeneration(builder, entityGeneration);
}
}
return result.ToStringAndFree();
}
private static void AppendOptionalGeneration(StringBuilder builder, int generation)
{
if (generation > 0)
{
builder.Append(GenerationSeparator);
builder.Append(generation);
}
}
internal static string MakeHoistedLocalFieldName(SynthesizedLocalKind kind, int slotIndex, string localNameOpt = null)
{
Debug.Assert((localNameOpt != null) == (kind == SynthesizedLocalKind.UserDefined));
Debug.Assert(slotIndex >= 0);
Debug.Assert(kind.IsLongLived());
// Lambda display class local follows a different naming pattern.
// EE depends on the name format.
// There's logic in the EE to recognize locals that have been captured by a lambda
// and would have been hoisted for the state machine. Basically, we just hoist the local containing
// the instance of the lambda display class and retain its original name (rather than using an
// iterator local name). See FUNCBRECEE::ImportIteratorMethodInheritedLocals.
var result = PooledStringBuilder.GetInstance();
var builder = result.Builder;
builder.Append('<');
if (localNameOpt != null)
{
Debug.Assert(localNameOpt.IndexOf('.') == -1);
builder.Append(localNameOpt);
}
builder.Append('>');
if (kind == SynthesizedLocalKind.LambdaDisplayClass)
{
builder.Append((char)GeneratedNameKind.DisplayClassLocalOrField);
}
else if (kind == SynthesizedLocalKind.UserDefined)
{
builder.Append((char)GeneratedNameKind.HoistedLocalField);
}
else
{
builder.Append((char)GeneratedNameKind.HoistedSynthesizedLocalField);
}
builder.Append("__");
builder.Append(slotIndex + 1);
return result.ToStringAndFree();
}
// The type of generated name. See TryParseGeneratedName.
internal static GeneratedNameKind GetKind(string name)
{
GeneratedNameKind kind;
int openBracketOffset;
int closeBracketOffset;
return TryParseGeneratedName(name, out kind, out openBracketOffset, out closeBracketOffset) ? kind : GeneratedNameKind.None;
}
// Parse the generated name. Returns true for names of the form
// [CS$]<[middle]>c[__[suffix]] where [CS$] is included for certain
// generated names, where [middle] and [__[suffix]] are optional,
// and where c is a single character in [1-9a-z]
// (csharp\LanguageAnalysis\LIB\SpecialName.cpp).
internal static bool TryParseGeneratedName(
string name,
out GeneratedNameKind kind,
out int openBracketOffset,
out int closeBracketOffset)
{
openBracketOffset = -1;
if (name.StartsWith("CS$<", StringComparison.Ordinal))
{
openBracketOffset = 3;
}
else if (name.StartsWith("<", StringComparison.Ordinal))
{
openBracketOffset = 0;
}
if (openBracketOffset >= 0)
{
closeBracketOffset = name.IndexOfBalancedParenthesis(openBracketOffset, '>');
if (closeBracketOffset >= 0 && closeBracketOffset + 1 < name.Length)
{
int c = name[closeBracketOffset + 1];
if ((c >= '1' && c <= '9') || (c >= 'a' && c <= 'z')) // Note '0' is not special.
{
kind = (GeneratedNameKind)c;
return true;
}
}
}
kind = GeneratedNameKind.None;
openBracketOffset = -1;
closeBracketOffset = -1;
return false;
}
internal static bool TryParseSourceMethodNameFromGeneratedName(string generatedName, GeneratedNameKind requiredKind, out string methodName)
{
int openBracketOffset;
int closeBracketOffset;
GeneratedNameKind kind;
if (!TryParseGeneratedName(generatedName, out kind, out openBracketOffset, out closeBracketOffset))
{
methodName = null;
return false;
}
if (requiredKind != 0 && kind != requiredKind)
{
methodName = null;
return false;
}
methodName = generatedName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1);
if (kind.IsTypeName())
{
methodName = methodName.Replace(DotReplacementInTypeNames, '.');
}
return true;
}
internal static string AsyncAwaiterFieldName(int slotIndex)
{
Debug.Assert((char)GeneratedNameKind.AwaiterField == 'u');
return "<>u__" + StringExtensions.GetNumeral(slotIndex + 1);
}
// Extracts the slot index from a name of a field that stores hoisted variables or awaiters.
// Such a name ends with "__{slot index + 1}".
// Returned slot index is >= 0.
internal static bool TryParseSlotIndex(string fieldName, out int slotIndex)
{
int lastUnder = fieldName.LastIndexOf('_');
if (lastUnder - 1 < 0 || lastUnder == fieldName.Length || fieldName[lastUnder - 1] != '_')
{
slotIndex = -1;
return false;
}
if (int.TryParse(fieldName.Substring(lastUnder + 1), NumberStyles.None, CultureInfo.InvariantCulture, out slotIndex) && slotIndex >= 1)
{
slotIndex--;
return true;
}
slotIndex = -1;
return false;
}
internal static string MakeCachedFrameInstanceFieldName()
{
Debug.Assert((char)GeneratedNameKind.LambdaCacheField == '9');
return "<>9";
}
internal static string MakeSynthesizedLocalName(SynthesizedLocalKind kind, ref int uniqueId)
{
Debug.Assert(kind.IsLongLived());
// Lambda display class local has to be named. EE depends on the name format.
if (kind == SynthesizedLocalKind.LambdaDisplayClass)
{
return MakeLambdaDisplayLocalName(uniqueId++);
}
return null;
}
internal static string MakeSynthesizedInstrumentationPayloadLocalFieldName(int uniqueId)
{
return SynthesizedLocalNamePrefix + "InstrumentationPayload" + StringExtensions.GetNumeral(uniqueId);
}
internal static string MakeLambdaDisplayLocalName(int uniqueId)
{
Debug.Assert((char)GeneratedNameKind.DisplayClassLocalOrField == '8');
return SynthesizedLocalNamePrefix + "<>8__locals" + StringExtensions.GetNumeral(uniqueId);
}
internal static bool IsSynthesizedLocalName(string name)
{
return name.StartsWith(SynthesizedLocalNamePrefix, StringComparison.Ordinal);
}
internal static string MakeFixedFieldImplementationName(string fieldName)
{
// the native compiler adds numeric digits at the end. Roslyn does not.
Debug.Assert((char)GeneratedNameKind.FixedBufferField == 'e');
return "<" + fieldName + ">e__FixedBuffer";
}
internal static string MakeStateMachineStateFieldName()
{
// Microsoft.VisualStudio.VIL.VisualStudioHost.AsyncReturnStackFrame depends on this name.
Debug.Assert((char)GeneratedNameKind.StateMachineStateField == '1');
return "<>1__state";
}
internal static string MakeAsyncIteratorPromiseOfValueOrEndFieldName()
{
Debug.Assert((char)GeneratedNameKind.AsyncIteratorPromiseOfValueOrEndBackingField == 'v');
return "<>v__promiseOfValueOrEnd";
}
internal static string MakeAsyncIteratorCombinedTokensFieldName()
{
Debug.Assert((char)GeneratedNameKind.CombinedTokensField == 'x');
return "<>x__combinedTokens";
}
internal static string MakeIteratorCurrentFieldName()
{
Debug.Assert((char)GeneratedNameKind.IteratorCurrentBackingField == '2');
return "<>2__current";
}
internal static string MakeDisposeModeFieldName()
{
Debug.Assert((char)GeneratedNameKind.DisposeModeField == 'w');
return "<>w__disposeMode";
}
internal static string MakeIteratorCurrentThreadIdFieldName()
{
Debug.Assert((char)GeneratedNameKind.IteratorCurrentThreadIdField == 'l');
return "<>l__initialThreadId";
}
internal static string ThisProxyFieldName()
{
Debug.Assert((char)GeneratedNameKind.ThisProxyField == '4');
return "<>4__this";
}
internal static string StateMachineThisParameterProxyName()
{
return StateMachineParameterProxyFieldName(ThisProxyFieldName());
}
internal static string StateMachineParameterProxyFieldName(string parameterName)
{
Debug.Assert((char)GeneratedNameKind.StateMachineParameterProxyField == '3');
return "<>3__" + parameterName;
}
internal static string MakeDynamicCallSiteContainerName(int methodOrdinal, int localFunctionOrdinal, int generation)
{
return MakeMethodScopedSynthesizedName(GeneratedNameKind.DynamicCallSiteContainerType, methodOrdinal, generation,
suffix: localFunctionOrdinal != -1 ? localFunctionOrdinal.ToString() : null,
suffixTerminator: localFunctionOrdinal != -1 ? '_' : default);
}
internal static string MakeDynamicCallSiteFieldName(int uniqueId)
{
Debug.Assert((char)GeneratedNameKind.DynamicCallSiteField == 'p');
return "<>p__" + StringExtensions.GetNumeral(uniqueId);
}
/// <summary>
/// Produces name of the synthesized delegate symbol that encodes the parameter byref-ness and return type of the delegate.
/// The arity is appended via `N suffix in MetadataName calculation since the delegate is generic.
/// </summary>
internal static string MakeDynamicCallSiteDelegateName(BitVector byRefs, bool returnsVoid, int generation)
{
var pooledBuilder = PooledStringBuilder.GetInstance();
var builder = pooledBuilder.Builder;
builder.Append(returnsVoid ? "<>A" : "<>F");
if (!byRefs.IsNull)
{
builder.Append("{");
int i = 0;
foreach (int byRefIndex in byRefs.Words())
{
if (i > 0)
{
builder.Append(",");
}
builder.AppendFormat("{0:x8}", byRefIndex);
i++;
}
builder.Append("}");
Debug.Assert(i > 0);
}
AppendOptionalGeneration(builder, generation);
return pooledBuilder.ToStringAndFree();
}
internal static string AsyncBuilderFieldName()
{
// Microsoft.VisualStudio.VIL.VisualStudioHost.AsyncReturnStackFrame depends on this name.
Debug.Assert((char)GeneratedNameKind.AsyncBuilderField == 't');
return "<>t__builder";
}
internal static string ReusableHoistedLocalFieldName(int number)
{
Debug.Assert((char)GeneratedNameKind.ReusableHoistedLocalField == '7');
return "<>7__wrap" + StringExtensions.GetNumeral(number);
}
internal static string LambdaCopyParameterName(int ordinal)
{
return "<p" + StringExtensions.GetNumeral(ordinal) + ">";
}
}
}