-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathJSExportCodeGenerator.cs
More file actions
228 lines (189 loc) · 12 KB
/
JSExportCodeGenerator.cs
File metadata and controls
228 lines (189 loc) · 12 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
// 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.Linq;
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 JSExportCodeGenerator : JSCodeGenerator
{
private readonly BoundGenerators _marshallers;
private readonly JSExportCodeContext _context;
private readonly JSSignatureContext _signatureContext;
public JSExportCodeGenerator(
TargetFramework targetFramework,
Version targetFrameworkVersion,
ImmutableArray<TypePositionInfo> argTypes,
JSExportData attributeData,
JSSignatureContext signatureContext,
GeneratorDiagnosticsBag diagnosticsBag,
IMarshallingGeneratorFactory generatorFactory)
{
_signatureContext = signatureContext;
NativeToManagedStubCodeContext innerContext = new NativeToManagedStubCodeContext(targetFramework, targetFrameworkVersion, ReturnIdentifier, ReturnIdentifier);
_context = new JSExportCodeContext(attributeData, innerContext);
_marshallers = BoundGenerators.Create(argTypes, generatorFactory, _context, new EmptyJSGenerator(), out var bindingFailures);
diagnosticsBag.ReportGeneratorDiagnostics(bindingFailures);
if (_marshallers.ManagedReturnMarshaller.Generator.UsesNativeIdentifier(_marshallers.ManagedReturnMarshaller.TypeInfo, null))
{
// If we need a different native return identifier, then recreate the context with the correct identifier before we generate any code.
innerContext = new NativeToManagedStubCodeContext(targetFramework, targetFrameworkVersion, ReturnIdentifier, ReturnNativeIdentifier);
_context = new JSExportCodeContext(attributeData, innerContext);
}
// validate task + span mix
if (_marshallers.ManagedReturnMarshaller.TypeInfo.MarshallingAttributeInfo is JSMarshallingInfo(_, JSTaskTypeInfo))
{
BoundGenerator spanArg = _marshallers.SignatureMarshallers.FirstOrDefault(m => m.TypeInfo.MarshallingAttributeInfo is JSMarshallingInfo(_, JSSpanTypeInfo));
if (spanArg != default)
{
diagnosticsBag.ReportGeneratorDiagnostic(new GeneratorDiagnostic.NotSupported(spanArg.TypeInfo, _context)
{
NotSupportedDetails = SR.SpanAndTaskNotSupported
});
}
}
}
public BlockSyntax GenerateJSExportBody()
{
List<StatementSyntax> invoke = InvokeSyntax();
GeneratedStatements statements = GeneratedStatements.Create(_marshallers, _context);
bool shouldInitializeVariables = !statements.GuaranteedUnmarshal.IsEmpty || !statements.CleanupCallerAllocated.IsEmpty || !statements.CleanupCalleeAllocated.IsEmpty;
VariableDeclarations declarations = VariableDeclarations.GenerateDeclarationsForUnmanagedToManaged(_marshallers, _context, shouldInitializeVariables);
var setupStatements = new List<StatementSyntax>();
SetupSyntax(setupStatements);
if (!(statements.GuaranteedUnmarshal.IsEmpty && statements.CleanupCalleeAllocated.IsEmpty))
{
setupStatements.Add(MarshallerHelpers.Declare(PredefinedType(Token(SyntaxKind.BoolKeyword)), InvokeSucceededIdentifier, initializeToDefault: true));
}
setupStatements.AddRange(declarations.Initializations);
setupStatements.AddRange(declarations.Variables);
setupStatements.AddRange(statements.Setup);
var tryStatements = new List<StatementSyntax>();
tryStatements.AddRange(statements.Unmarshal);
tryStatements.AddRange(invoke);
if (!(statements.GuaranteedUnmarshal.IsEmpty && statements.CleanupCalleeAllocated.IsEmpty))
{
tryStatements.Add(ExpressionStatement(AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
IdentifierName(InvokeSucceededIdentifier),
LiteralExpression(SyntaxKind.TrueLiteralExpression))));
}
tryStatements.AddRange(statements.NotifyForSuccessfulInvoke);
tryStatements.AddRange(statements.PinnedMarshal);
tryStatements.AddRange(statements.Marshal);
List<StatementSyntax> allStatements = setupStatements;
// Wrap unmarshall, invocation and return value marshalling in try-catch.
// In case of exception, marshal exception instead of return value.
var tryInvokeAndMarshal = TryStatement(SingletonList(CatchClause()
.WithDeclaration(CatchDeclaration(IdentifierName(Constants.ExceptionGlobal)).WithIdentifier(Identifier("ex")))
.WithBlock(Block(SingletonList<StatementSyntax>(
ExpressionStatement(InvocationExpression(
MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(Constants.ArgumentException), IdentifierName(Constants.ToJSMethod)))
.WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(IdentifierName("ex")))))))))))
.WithBlock(Block(tryStatements));
List<StatementSyntax> finallyStatements = new List<StatementSyntax>();
if (!(statements.GuaranteedUnmarshal.IsEmpty && statements.CleanupCalleeAllocated.IsEmpty))
{
finallyStatements.Add(IfStatement(IdentifierName(InvokeSucceededIdentifier), Block(statements.GuaranteedUnmarshal.Concat(statements.CleanupCalleeAllocated))));
}
finallyStatements.AddRange(statements.CleanupCallerAllocated);
if (finallyStatements.Count > 0)
{
tryInvokeAndMarshal = TryStatement(Block(tryInvokeAndMarshal), default, FinallyClause(Block(finallyStatements)));
}
allStatements.Add(tryInvokeAndMarshal);
return Block(allStatements);
}
public static StatementSyntax[] GenerateJSExportArchitectureCheck()
{
return new StatementSyntax[]{
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))),
};
}
public StatementSyntax GenerateJSExportRegistration()
{
var signatureArgs = new List<ArgumentSyntax>
{
Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(_signatureContext.QualifiedMethodName))),
Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(_signatureContext.TypesHash))),
CreateSignaturesSyntax()
};
return ExpressionStatement(InvocationExpression(MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(Constants.JSFunctionSignatureGlobal), IdentifierName(Constants.BindCSFunctionMethod)))
.WithArgumentList(ArgumentList(SeparatedList(signatureArgs))));
}
private ArgumentSyntax CreateSignaturesSyntax()
{
var types = ((IJSMarshallingGenerator)_marshallers.ManagedReturnMarshaller.Generator).GenerateBind(_marshallers.ManagedReturnMarshaller.TypeInfo, _context)
.Concat(_marshallers.NativeParameterMarshallers.SelectMany(p => ((IJSMarshallingGenerator)p.Generator).GenerateBind(p.TypeInfo, _context)));
return Argument(ArrayCreationExpression(ArrayType(IdentifierName(Constants.JSMarshalerTypeGlobal))
.WithRankSpecifiers(SingletonList(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression())))))
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression, SeparatedList(types))));
}
private void SetupSyntax(List<StatementSyntax> statementsToUpdate)
{
foreach (BoundGenerator marshaller in _marshallers.NativeParameterMarshallers)
{
statementsToUpdate.Add(LocalDeclarationStatement(VariableDeclaration(marshaller.TypeInfo.ManagedType.Syntax)
.WithVariables(SingletonSeparatedList(VariableDeclarator(marshaller.TypeInfo.InstanceIdentifier)))));
}
statementsToUpdate.Add(LocalDeclarationStatement(VariableDeclaration(RefType(IdentifierName(Constants.JSMarshalerArgumentGlobal)))
.WithVariables(SingletonSeparatedList(VariableDeclarator(Identifier(Constants.ArgumentException))
.WithInitializer(EqualsValueClause(RefExpression(ElementAccessExpression(IdentifierName(Constants.ArgumentsBuffer))
.WithArgumentList(BracketedArgumentList(SingletonSeparatedList(
Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))))))))))));
statementsToUpdate.Add(LocalDeclarationStatement(VariableDeclaration(RefType(IdentifierName(Constants.JSMarshalerArgumentGlobal)))
.WithVariables(SingletonSeparatedList(VariableDeclarator(Identifier(Constants.ArgumentReturn))
.WithInitializer(EqualsValueClause(RefExpression(ElementAccessExpression(IdentifierName(Constants.ArgumentsBuffer))
.WithArgumentList(BracketedArgumentList(SingletonSeparatedList(
Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))))))))))));
}
private List<StatementSyntax> InvokeSyntax()
{
var statements = new List<StatementSyntax>();
var arguments = new List<ArgumentSyntax>();
// Generate code for each parameter for the current stage
foreach (BoundGenerator marshaller in _marshallers.NativeParameterMarshallers)
{
// convert arguments for invocation
statements.AddRange(marshaller.Generator.Generate(marshaller.TypeInfo, _context));
arguments.Add(Argument(IdentifierName(marshaller.TypeInfo.InstanceIdentifier)));
}
if (_marshallers.IsManagedVoidReturn)
{
statements.Add(ExpressionStatement(InvocationExpression(IdentifierName(_signatureContext.MethodName))
.WithArgumentList(ArgumentList(SeparatedList(arguments)))));
}
else
{
ExpressionSyntax invocation = InvocationExpression(IdentifierName(_signatureContext.MethodName))
.WithArgumentList(ArgumentList(SeparatedList(arguments)));
(string _, string nativeIdentifier) = _context.GetIdentifiers(_marshallers.ManagedReturnMarshaller.TypeInfo);
ExpressionStatementSyntax statement = ExpressionStatement(AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName(nativeIdentifier), invocation));
statements.Add(statement);
}
return statements;
}
public (ParameterListSyntax ParameterList, TypeSyntax ReturnType, AttributeListSyntax? ReturnTypeAttributes) GenerateTargetMethodSignatureData()
{
return _marshallers.GenerateTargetMethodSignatureData(_context);
}
}
}