-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathJSExportGenerator.cs
More file actions
425 lines (368 loc) · 23.2 KB
/
Copy pathJSExportGenerator.cs
File metadata and controls
425 lines (368 loc) · 23.2 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
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
// 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.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;
using System.Collections.Generic;
namespace Microsoft.Interop.JavaScript
{
[Generator]
public sealed class JSExportGenerator : IIncrementalGenerator
{
internal sealed record IncrementalStubGenerationContext(
JSSignatureContext SignatureContext,
ContainingSyntaxContext ContainingSyntaxContext,
ContainingSyntax StubMethodSyntaxTemplate,
MethodSignatureDiagnosticLocations DiagnosticLocation,
JSExportData JSExportData);
public static class StepNames
{
public const string CalculateStubInformation = nameof(CalculateStubInformation);
public const string GenerateSingleStub = nameof(GenerateSingleStub);
}
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var assemblyName = context.CompilationProvider.Select(static (c, _) => c.AssemblyName);
// Collect all methods adorned with JSExportAttribute
// (diagnostics for invalid methods are reported by the analyzer)
var methodsToGenerate = context.SyntaxProvider
.ForAttributeWithMetadataName(Constants.JSExportAttribute,
static (node, ct) => node is MethodDeclarationSyntax,
static (context, ct) => new { Syntax = (MethodDeclarationSyntax)context.TargetNode, Symbol = (IMethodSymbol)context.TargetSymbol })
.Where(static data =>
JSInteropDiagnosticsAnalyzer.GetDiagnosticIfInvalidMethodForGeneration(
data.Syntax, data.Symbol,
GeneratorDiagnostics.InvalidExportAttributedMethodSignature,
GeneratorDiagnostics.InvalidExportAttributedMethodContainingTypeMissingModifiers,
requiresImplementation: true) is null);
IncrementalValueProvider<StubEnvironment> stubEnvironment = context.CreateStubEnvironmentProvider();
IncrementalValuesProvider<(MemberDeclarationSyntax, StatementSyntax, AttributeListSyntax)> generateSingleStub = methodsToGenerate
.Combine(stubEnvironment)
.Select(static (data, ct) => new
{
data.Left.Syntax,
data.Left.Symbol,
Environment = data.Right,
})
.Select(
static (data, ct) => CalculateStubInformation(data.Syntax, data.Symbol, data.Environment, ct)
)
.WithTrackingName(StepNames.CalculateStubInformation)
.Select(
static (data, ct) => GenerateSource(data)
)
.WithComparer(Comparers.GeneratedSyntax3)
.WithTrackingName(StepNames.GenerateSingleStub);
IncrementalValueProvider<ImmutableArray<(StatementSyntax, AttributeListSyntax)>> regSyntax = generateSingleStub
.Select(
static (data, ct) => (data.Item2, data.Item3))
.Collect();
IncrementalValueProvider<string> registration = regSyntax
.Combine(assemblyName)
.Select(static (data, ct) => GenerateRegSource(data.Left, data.Right))
.Select(static (data, ct) => data.NormalizeWhitespace().ToFullString());
IncrementalValueProvider<ImmutableArray<(string, string)>> generated = generateSingleStub
.Combine(registration)
.Select(
static (data, ct) => (data.Left.Item1.NormalizeWhitespace().ToFullString(), data.Right))
.Collect();
context.RegisterSourceOutput(generated,
(context, generatedSources) =>
{
// Don't generate a file if we don't have to, to avoid the extra IDE overhead once we have generated
// files in play.
if (generatedSources.IsEmpty)
return;
StringBuilder source = new();
// Mark in source that the file is auto-generated.
source.Append("// <auto-generated/>\r\n");
// this is the assembly level registration
source.Append(generatedSources[0].Item2);
source.Append("\r\n");
// this is the method wrappers to be called from JS
foreach (var generated in generatedSources)
{
source.Append(generated.Item1);
source.Append("\r\n");
}
// Once https://github.com/dotnet/roslyn/issues/61326 is resolved, we can avoid the ToString() here.
context.AddSource("JSExports.g.cs", source.ToString());
});
}
private static MemberDeclarationSyntax PrintGeneratedSource(
ContainingSyntaxContext containingSyntaxContext,
BlockSyntax wrapperStatements, string wrapperName)
{
MemberDeclarationSyntax wrappperMethod = MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier(wrapperName))
.WithModifiers(TokenList(new[] { Token(SyntaxKind.InternalKeyword), Token(SyntaxKind.StaticKeyword), Token(SyntaxKind.UnsafeKeyword) }))
.WithAttributeLists(SingletonList(AttributeList(SingletonSeparatedList(
Attribute(IdentifierName(Constants.DebuggerNonUserCodeAttribute))))))
.WithParameterList(ParameterList(SingletonSeparatedList(
Parameter(Identifier(Constants.ArgumentsBuffer)).WithType(PointerType(ParseTypeName(Constants.JSMarshalerArgumentGlobal))))))
// The modifier above states the contract for callers; the body needs a context of its own.
.WithBody(wrapperStatements.WrapInUnsafeBlock());
MemberDeclarationSyntax toPrint = containingSyntaxContext.WrapMembersInContainingSyntax(wrappperMethod);
return toPrint;
}
private static JSExportData? ProcessJSExportAttribute(AttributeData attrData)
{
// Found the JSExport, but it has an error so report the error.
// This is most likely an issue with targeting an incorrect TFM.
if (attrData.AttributeClass?.TypeKind is null or TypeKind.Error)
{
return null;
}
return new JSExportData();
}
private static IncrementalStubGenerationContext CalculateStubInformation(
MethodDeclarationSyntax originalSyntax,
IMethodSymbol symbol,
StubEnvironment environment,
CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
// Get any attributes of interest on the method
AttributeData? jsExportAttr = null;
foreach (AttributeData attr in symbol.GetAttributes())
{
if (attr.AttributeClass is not null
&& attr.AttributeClass.ToDisplayString() == Constants.JSExportAttribute)
{
jsExportAttr = attr;
}
}
Debug.Assert(jsExportAttr is not null);
var locations = new MethodSignatureDiagnosticLocations(originalSyntax);
var generatorDiagnostics = new GeneratorDiagnosticsBag(new DescriptorProvider(), locations, SR.ResourceManager, typeof(FxResources.Microsoft.Interop.JavaScript.JSImportGenerator.SR));
// Process the JSExport attribute
JSExportData? jsExportData = ProcessJSExportAttribute(jsExportAttr!);
jsExportData ??= new JSExportData();
// Create the stub.
var signatureContext = JSSignatureContext.Create(symbol, environment, generatorDiagnostics, ct);
var containingTypeContext = new ContainingSyntaxContext(originalSyntax);
var methodSyntaxTemplate = new ContainingSyntax(originalSyntax.Modifiers, SyntaxKind.MethodDeclaration, originalSyntax.Identifier, originalSyntax.TypeParameterList);
return new IncrementalStubGenerationContext(
signatureContext,
containingTypeContext,
methodSyntaxTemplate,
locations,
jsExportData);
}
private static NamespaceDeclarationSyntax GenerateRegSource(
ImmutableArray<(StatementSyntax Registration, AttributeListSyntax Attribute)> methods, string assemblyName)
{
const string generatedNamespace = "System.Runtime.InteropServices.JavaScript";
const string initializerClass = "__GeneratedInitializer";
const string initializerName = "__Register_";
const string trimmingPreserveName = "__TrimmingPreserve_";
if (methods.IsEmpty) return NamespaceDeclaration(IdentifierName(generatedNamespace));
var registerStatements = new List<StatementSyntax>();
registerStatements.AddRange(GenerateJSExportArchitectureCheck());
var attributes = new List<AttributeListSyntax>();
foreach (var m in methods)
{
registerStatements.Add(m.Registration);
attributes.Add(m.Attribute);
}
FieldDeclarationSyntax field = FieldDeclaration(VariableDeclaration(PredefinedType(Token(SyntaxKind.BoolKeyword)))
.WithVariables(SingletonSeparatedList(
VariableDeclarator(Identifier("initialized")))))
.WithModifiers(TokenList(Token(SyntaxKind.StaticKeyword)))
.WithAttributeLists(SingletonList(AttributeList(SingletonSeparatedList(
Attribute(IdentifierName(Constants.ThreadStaticGlobal))))));
MemberDeclarationSyntax method = MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier(initializerName))
.WithAttributeLists(List(attributes))
.WithModifiers(TokenList(new[] { Token(SyntaxKind.StaticKeyword) }))
.WithBody(Block(registerStatements));
// HACK: protect the code from trimming with DynamicDependency attached to a ModuleInitializer
MemberDeclarationSyntax initializerMethod = MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier(trimmingPreserveName))
.WithAttributeLists(
SingletonList<AttributeListSyntax>(
AttributeList(
SeparatedList<AttributeSyntax>(
new SyntaxNodeOrToken[]{
Attribute(
IdentifierName(Constants.ModuleInitializerAttributeGlobal)),
Token(SyntaxKind.CommaToken),
Attribute(
IdentifierName(Constants.DynamicDependencyAttributeGlobal))
.WithArgumentList(
AttributeArgumentList(
SeparatedList<AttributeArgumentSyntax>(
new SyntaxNodeOrToken[]{
AttributeArgument(
BinaryExpression(
SyntaxKind.BitwiseOrExpression,
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(Constants.DynamicallyAccessedMemberTypesGlobal),
IdentifierName("PublicMethods")),
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(Constants.DynamicallyAccessedMemberTypesGlobal),
IdentifierName("NonPublicMethods")))),
Token(SyntaxKind.CommaToken),
AttributeArgument(
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal($"{generatedNamespace}.{initializerClass}"))
),
Token(SyntaxKind.CommaToken),
AttributeArgument(
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(assemblyName))
)
})))}))))
.WithModifiers(TokenList(new[] {
Token(SyntaxKind.StaticKeyword),
Token(SyntaxKind.InternalKeyword)
}))
.WithBody(Block());
var ns = NamespaceDeclaration(IdentifierName(generatedNamespace))
.WithMembers(
SingletonList<MemberDeclarationSyntax>(
// None of the members below name a pointer type, so the class needs no 'unsafe'
// modifier. Under the updated memory safety rules one on a type means nothing at
// all, and it never established a context for the members in the first place.
ClassDeclaration(initializerClass)
.WithMembers(List(new[] { field, initializerMethod, method }))
.WithAttributeLists(SingletonList(AttributeList(SingletonSeparatedList(
Attribute(IdentifierName(Constants.CompilerGeneratedAttributeGlobal)))
)))));
return ns;
}
private static StatementSyntax[] GenerateJSExportArchitectureCheck()
{
return [
IfStatement(
BinaryExpression(SyntaxKind.LogicalOrExpression,
IdentifierName("initialized"),
BinaryExpression(SyntaxKind.NotEqualsExpression,
IdentifierName(Constants.OSArchitectureGlobal),
IdentifierName(Constants.ArchitectureWasmGlobal))),
ReturnStatement()),
ExpressionStatement(
AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
IdentifierName("initialized"),
LiteralExpression(SyntaxKind.TrueLiteralExpression))),
];
}
private static (MemberDeclarationSyntax, StatementSyntax, AttributeListSyntax) GenerateSource(
IncrementalStubGenerationContext incrementalContext)
{
var diagnostics = new GeneratorDiagnosticsBag(new DescriptorProvider(), incrementalContext.DiagnosticLocation, SR.ResourceManager, typeof(FxResources.Microsoft.Interop.JavaScript.JSImportGenerator.SR));
// Generate stub code
ImmutableArray<TypePositionInfo> signatureElements = incrementalContext.SignatureContext.SignatureContext.ElementTypeInformation;
ImmutableArray<TypePositionInfo> allElements = signatureElements
.Add(new TypePositionInfo(
new ReferenceTypeInfo(Constants.ExceptionGlobal, Constants.ExceptionGlobal),
new JSMarshallingInfo(NoMarshallingInfo.Instance, new JSSimpleTypeInfo(KnownManagedType.Exception, ParseTypeName(Constants.ExceptionGlobal)))
{
JSType = System.Runtime.InteropServices.JavaScript.JSTypeFlags.Error,
})
{
InstanceIdentifier = Constants.ArgumentException,
ManagedIndex = TypePositionInfo.ExceptionIndex,
NativeIndex = signatureElements.Length, // Insert at the end of the argument list
RefKind = RefKind.Out, // We'll treat it as a separate out parameter.
});
for (int i = 0; i < allElements.Length; i++)
{
if (allElements[i].IsNativeReturnPosition && allElements[i].ManagedType != SpecialTypeInfo.Void)
{
// The runtime may partially initialize the native return value.
// To preserve this information, we must pass the native return value as an out parameter.
allElements = allElements.SetItem(i, allElements[i] with
{
ManagedIndex = TypePositionInfo.ReturnIndex,
NativeIndex = allElements.Length, // Insert at the end of the argument list
RefKind = RefKind.Out, // We'll treat it as a separate out parameter.
});
}
}
var stubGenerator = new UnmanagedToManagedStubGenerator(
allElements,
diagnostics,
new CompositeMarshallingGeneratorResolver(
new NoSpanAndTaskMixingResolver(),
new JSGeneratorResolver()));
var wrapperName = "__Wrapper_" + incrementalContext.StubMethodSyntaxTemplate.Identifier + "_" + incrementalContext.SignatureContext.TypesHash;
const string innerWrapperName = "__Stub";
BlockSyntax wrapperToInnerStubBlock = Block(
CreateWrapperToInnerStubCall(signatureElements, innerWrapperName),
GenerateInnerLocalFunction(incrementalContext, innerWrapperName, stubGenerator));
StatementSyntax registration = GenerateJSExportRegistration(incrementalContext.SignatureContext);
AttributeListSyntax registrationAttribute = AttributeList(SingletonSeparatedList(Attribute(IdentifierName(Constants.DynamicDependencyAttributeGlobal))
.WithArgumentList(AttributeArgumentList(SeparatedList(new[]{
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(wrapperName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(incrementalContext.SignatureContext.StubTypeFullName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(incrementalContext.SignatureContext.AssemblyName))),
}
)))));
return (PrintGeneratedSource(incrementalContext.ContainingSyntaxContext, wrapperToInnerStubBlock, wrapperName),
registration, registrationAttribute);
}
private static ExpressionStatementSyntax CreateWrapperToInnerStubCall(ImmutableArray<TypePositionInfo> signatureElements, string innerWrapperName)
{
List<ArgumentSyntax> arguments = [];
bool hasReturn = true;
foreach (var nativeArg in signatureElements.Where(e => e.NativeIndex != TypePositionInfo.UnsetIndex).OrderBy(e => e.NativeIndex))
{
if (nativeArg.IsNativeReturnPosition)
{
if (nativeArg.ManagedType == SpecialTypeInfo.Void)
{
hasReturn = false;
}
continue;
}
arguments.Add(
Argument(
ElementAccessExpression(
IdentifierName(Constants.ArgumentsBuffer),
BracketedArgumentList(SingletonSeparatedList(Argument(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(nativeArg.NativeIndex + 2))))))));
}
arguments.Add(Argument(IdentifierName(Constants.ArgumentsBuffer)));
if (hasReturn)
{
arguments.Add(
Argument(
BinaryExpression(
SyntaxKind.AddExpression,
IdentifierName(Constants.ArgumentsBuffer),
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))));
}
return ExpressionStatement(
InvocationExpression(IdentifierName(innerWrapperName))
.WithArgumentList(ArgumentList(SeparatedList(arguments))));
}
private static LocalFunctionStatementSyntax GenerateInnerLocalFunction(IncrementalStubGenerationContext context, string innerFunctionName, UnmanagedToManagedStubGenerator stubGenerator)
{
var (parameters, returnType, _) = stubGenerator.GenerateAbiMethodSignatureData();
return LocalFunctionStatement(
returnType,
innerFunctionName)
.WithBody(stubGenerator.GenerateStubBodyForMethod(IdentifierName(TypeNames.GlobalAlias + context.SignatureContext.MethodName)))
.WithParameterList(parameters)
.WithAttributeLists(SingletonList(AttributeList(SingletonSeparatedList(
Attribute(IdentifierName(Constants.DebuggerNonUserCodeAttribute))))));
}
private static ExpressionStatementSyntax GenerateJSExportRegistration(JSSignatureContext context)
{
var signatureArgs = new List<ArgumentSyntax>
{
Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(context.QualifiedMethodName))),
Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(context.TypesHash))),
SignatureBindingHelpers.CreateSignaturesArgument(context.SignatureContext.ElementTypeInformation, StubCodeContext.DefaultNativeToManagedStub)
};
return ExpressionStatement(InvocationExpression(MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(Constants.JSFunctionSignatureGlobal), IdentifierName(Constants.BindCSFunctionMethod)))
.WithArgumentList(ArgumentList(SeparatedList(signatureArgs))));
}
}
}