forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJSImportStubContext.cs
More file actions
260 lines (218 loc) · 11.9 KB
/
JSImportStubContext.cs
File metadata and controls
260 lines (218 loc) · 11.9 KB
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace Microsoft.Interop.JavaScript
{
internal sealed class JSSignatureContext : IEquatable<JSSignatureContext>
{
private static SymbolDisplayFormat typeNameFormat { get; } = new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes
);
internal static readonly string GeneratorName = typeof(JSImportGenerator).Assembly.GetName().Name;
internal static readonly string GeneratorVersion = typeof(JSImportGenerator).Assembly.GetName().Version.ToString();
internal static bool MethodIsSkipLocalsInit(StubEnvironment env, IMethodSymbol method)
{
if (env.ModuleSkipLocalsInit)
{
return true;
}
if (method.GetAttributes().Any(IsSkipLocalsInitAttribute))
{
return true;
}
for (INamedTypeSymbol type = method.ContainingType; type is not null; type = type.ContainingType)
{
if (type.GetAttributes().Any(IsSkipLocalsInitAttribute))
{
return true;
}
}
// We check the module case earlier, so we don't need to do it here.
return false;
static bool IsSkipLocalsInitAttribute(AttributeData a)
=> a.AttributeClass?.ToDisplayString() == TypeNames.System_Runtime_CompilerServices_SkipLocalsInitAttribute;
}
public static JSSignatureContext Create(
IMethodSymbol method,
StubEnvironment env,
GeneratorDiagnostics diagnostics,
CancellationToken token)
{
// Cancel early if requested
token.ThrowIfCancellationRequested();
// Determine the namespace
string? stubTypeNamespace = null;
if (!(method.ContainingNamespace is null)
&& !method.ContainingNamespace.IsGlobalNamespace)
{
stubTypeNamespace = method.ContainingNamespace.ToString();
}
string stubTypeFullName = "";
// Determine containing type(s)
ImmutableArray<TypeDeclarationSyntax>.Builder containingTypes = ImmutableArray.CreateBuilder<TypeDeclarationSyntax>();
INamedTypeSymbol currType = method.ContainingType;
while (!(currType is null))
{
// Use the declaring syntax as a basis for this type declaration.
// Since we're generating source for the method, we know that the current type
// has to be declared in source.
TypeDeclarationSyntax typeDecl = (TypeDeclarationSyntax)currType.DeclaringSyntaxReferences[0].GetSyntax(token);
// Remove current members, attributes, and base list so we don't double declare them.
typeDecl = typeDecl.WithMembers(List<MemberDeclarationSyntax>())
.WithAttributeLists(List<AttributeListSyntax>())
.WithBaseList(null);
containingTypes.Add(typeDecl);
stubTypeFullName = currType.Name + (string.IsNullOrEmpty(stubTypeFullName) ? "" : ".") + stubTypeFullName;
currType = currType.ContainingType;
}
stubTypeFullName = stubTypeNamespace == null ? stubTypeFullName : (stubTypeNamespace + "." + stubTypeFullName);
(ImmutableArray<TypePositionInfo> typeInfos, IMarshallingGeneratorFactory generatorFactory) = GenerateTypeInformation(method, diagnostics, env);
ImmutableArray<AttributeListSyntax>.Builder additionalAttrs = ImmutableArray.CreateBuilder<AttributeListSyntax>();
if (env.TargetFramework != TargetFramework.Unknown)
{
// Define additional attributes for the stub definition.
additionalAttrs.Add(
AttributeList(
SingletonSeparatedList(
Attribute(ParseName(TypeNames.System_CodeDom_Compiler_GeneratedCodeAttribute),
AttributeArgumentList(
SeparatedList(
new[]
{
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(GeneratorName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(GeneratorVersion)))
}))))));
}
// there could be multiple method signatures with the same name, get unique signature name
uint hash = 17;
unchecked
{
foreach (var param in typeInfos)
{
hash = hash * 31 + (uint)param.ManagedType.FullTypeName.GetHashCode();
}
};
int typesHash = Math.Abs((int)hash);
var fullName = $"{method.ContainingType.ToDisplayString()}.{method.Name}";
string qualifiedName = GetFullyQualifiedMethodName(env, method);
return new JSSignatureContext()
{
StubReturnType = method.ReturnType.AsTypeSyntax(),
ElementTypeInformation = typeInfos,
StubTypeNamespace = stubTypeNamespace,
TypesHash = typesHash,
StubTypeFullName = stubTypeFullName,
StubContainingTypes = containingTypes.ToImmutable(),
AdditionalAttributes = additionalAttrs.ToImmutable(),
MethodName = fullName,
QualifiedMethodName = qualifiedName,
BindingName = "__signature_" + method.Name + "_" + typesHash,
GeneratorFactory = generatorFactory
};
}
private static string GetFullyQualifiedMethodName(StubEnvironment env, IMethodSymbol method)
{
// Mono style nested class name format.
string typeName = method.ContainingType.ToDisplayString(typeNameFormat).Replace(".", "/");
if (!method.ContainingType.ContainingNamespace.IsGlobalNamespace)
typeName = $"{method.ContainingType.ContainingNamespace.ToDisplayString()}.{typeName}";
return $"[{env.Compilation.AssemblyName}]{typeName}:{method.Name}";
}
private static (ImmutableArray<TypePositionInfo>, IMarshallingGeneratorFactory) GenerateTypeInformation(IMethodSymbol method, GeneratorDiagnostics diagnostics, StubEnvironment env)
{
var jsMarshallingAttributeParser = new JSMarshallingAttributeInfoParser(env.Compilation, diagnostics, method);
// Determine parameter and return types
ImmutableArray<TypePositionInfo>.Builder typeInfos = ImmutableArray.CreateBuilder<TypePositionInfo>();
for (int i = 0; i < method.Parameters.Length; i++)
{
IParameterSymbol param = method.Parameters[i];
MarshallingInfo marshallingInfo = NoMarshallingInfo.Instance;
MarshallingInfo jsMarshallingInfo = jsMarshallingAttributeParser.ParseMarshallingInfo(param.Type, param.GetAttributes(), marshallingInfo);
var typeInfo = TypePositionInfo.CreateForParameter(param, marshallingInfo, env.Compilation);
typeInfo = JSTypeInfo.CreateForType(typeInfo, param.Type, jsMarshallingInfo, env.Compilation);
typeInfo = typeInfo with
{
ManagedIndex = i,
NativeIndex = typeInfos.Count,
};
typeInfos.Add(typeInfo);
}
MarshallingInfo retMarshallingInfo = NoMarshallingInfo.Instance;
MarshallingInfo retJSMarshallingInfo = jsMarshallingAttributeParser.ParseMarshallingInfo(method.ReturnType, method.GetReturnTypeAttributes(), retMarshallingInfo);
var retTypeInfo = new TypePositionInfo(ManagedTypeInfo.CreateTypeInfoForTypeSymbol(method.ReturnType), retMarshallingInfo);
retTypeInfo = JSTypeInfo.CreateForType(retTypeInfo, method.ReturnType, retJSMarshallingInfo, env.Compilation);
retTypeInfo = retTypeInfo with
{
ManagedIndex = TypePositionInfo.ReturnIndex,
NativeIndex = TypePositionInfo.ReturnIndex,
MarshallingAttributeInfo = retJSMarshallingInfo,
};
typeInfos.Add(retTypeInfo);
var jsGeneratorFactory = new JSGeneratorFactory();
return (typeInfos.ToImmutable(), jsGeneratorFactory);
}
public ImmutableArray<TypePositionInfo> ElementTypeInformation { get; init; }
public string? StubTypeNamespace { get; init; }
public string? StubTypeFullName { get; init; }
public int TypesHash { get; init; }
public ImmutableArray<TypeDeclarationSyntax> StubContainingTypes { get; init; }
public TypeSyntax StubReturnType { get; init; }
public IEnumerable<ParameterSyntax> StubParameters
{
get
{
foreach (TypePositionInfo typeInfo in ElementTypeInformation)
{
if (typeInfo.ManagedIndex != TypePositionInfo.UnsetIndex
&& typeInfo.ManagedIndex != TypePositionInfo.ReturnIndex)
{
yield return Parameter(Identifier(typeInfo.InstanceIdentifier))
.WithType(typeInfo.ManagedType.Syntax)
.WithModifiers(TokenList(Token(typeInfo.RefKindSyntax)));
}
}
}
}
public ImmutableArray<AttributeListSyntax> AdditionalAttributes { get; init; }
public string MethodName { get; init; }
public string QualifiedMethodName { get; init; }
public string BindingName { get; init; }
public IMarshallingGeneratorFactory GeneratorFactory { get; init; }
public override bool Equals(object obj)
{
return obj is JSSignatureContext other && Equals(other);
}
public bool Equals(JSSignatureContext other)
{
// We don't check if the generator factories are equal since
// the generator factory is deterministically created based on the ElementTypeInformation and Options.
return other is not null
&& StubTypeNamespace == other.StubTypeNamespace
&& StubTypeFullName == other.StubTypeFullName
&& ElementTypeInformation.SequenceEqual(other.ElementTypeInformation)
&& StubContainingTypes.SequenceEqual(other.StubContainingTypes, (IEqualityComparer<TypeDeclarationSyntax>)SyntaxEquivalentComparer.Instance)
&& StubReturnType.IsEquivalentTo(other.StubReturnType)
&& AdditionalAttributes.SequenceEqual(other.AdditionalAttributes, (IEqualityComparer<AttributeListSyntax>)SyntaxEquivalentComparer.Instance)
;
}
public override int GetHashCode()
{
throw new UnreachableException();
}
}
}