-
Notifications
You must be signed in to change notification settings - Fork 4.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[draft][wasm] JSImport/JSExport prototype #64493
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
6 changes: 6 additions & 0 deletions
6
src/libraries/System.Private.Runtime.InteropServices.JavaScript/gen/Directory.Build.props
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
<Project> | ||
<PropertyGroup> | ||
<IsGeneratorProject>true</IsGeneratorProject> | ||
</PropertyGroup> | ||
<Import Project="..\Directory.Build.props" /> | ||
</Project> |
139 changes: 139 additions & 0 deletions
139
...vate.Runtime.InteropServices.JavaScript/gen/MarshalerGenerator/CommonJSMethodGenerator.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,139 @@ | ||
// 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 System.Text; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.CSharp; | ||
using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; | ||
|
||
|
||
namespace JavaScript.MarshalerGenerator | ||
{ | ||
internal class CommonJSMethodGenerator | ||
{ | ||
public StringBuilder prolog; | ||
public MethodDeclarationSyntax MethodSyntax; | ||
public TypeDeclarationSyntax TypeSyntax; | ||
public AttributeSyntax AttributeSyntax; | ||
public IMethodSymbol MethodSymbol; | ||
public IMethodSymbol AttributeSymbol; | ||
public AttributeData JSAttributeData; | ||
public JSMarshalerSig[] ParemeterSignatures; | ||
public JSMarshalerSig ReturnSignature; | ||
public MarshalerSelector MarshalerSelector; | ||
public string BoundFunctionName; | ||
public string AssemblyName; | ||
|
||
public ITypeSymbol ReturnType => MethodSymbol.ReturnType; | ||
public TypeSyntax ReturnTypeSyntax => ReturnType.AsTypeSyntax(); | ||
public string MethodName => MethodSymbol.Name; | ||
public bool HasCustomMarshalers => JSAttributeData.ConstructorArguments.Length > 1; | ||
public bool IsVoidMethod => ReturnType.SpecialType == SpecialType.System_Void; | ||
|
||
public void SelectMarshalers(Compilation compilation) | ||
{ | ||
JSMarshalerMetadata[] customMarshalers = null; | ||
if (HasCustomMarshalers) | ||
{ | ||
ImmutableArray<TypedConstant> marshalerTypes = JSAttributeData.ConstructorArguments[1].Values; | ||
customMarshalers = marshalerTypes.Select(mt => ExtractMarshalerMeta(compilation, mt)).ToArray(); | ||
} | ||
|
||
MarshalerSelector = new MarshalerSelector(compilation); | ||
ReturnSignature = MarshalerSelector.GetArgumentSignature(prolog, customMarshalers, MethodSymbol.ReturnType); | ||
for (int i = 0; i < MethodSymbol.Parameters.Length; i++) | ||
{ | ||
IParameterSymbol arg = MethodSymbol.Parameters[i]; | ||
ParemeterSignatures[i] = MarshalerSelector.GetArgumentSignature(prolog, customMarshalers, arg.Type); | ||
} | ||
AssemblyName = compilation.AssemblyName; | ||
} | ||
|
||
protected ArgumentSyntax CreateMarshallersSyntax() | ||
{ | ||
ArgumentSyntax marshallersArg; | ||
List<ITypeSymbol> marshalersTypes = HasCustomMarshalers | ||
? JSAttributeData.ConstructorArguments[1].Values.Select(a => (ITypeSymbol)a.Value).ToList() | ||
: new List<ITypeSymbol?>(); | ||
|
||
if (ReturnSignature.IsAuto) | ||
{ | ||
marshalersTypes.Add(ReturnSignature.MarshalerType); | ||
} | ||
marshalersTypes.AddRange(ParemeterSignatures.Where(s => s.IsAuto).Select(s => s.MarshalerType)); | ||
|
||
if (marshalersTypes.Count > 0) | ||
{ | ||
var marshalerInstances = marshalersTypes.Distinct(SymbolEqualityComparer.Default).Cast<ITypeSymbol>().Select(t => | ||
{ | ||
return ObjectCreationExpression(t.AsTypeSyntax()).WithArgumentList(ArgumentList()); | ||
}); | ||
marshallersArg = Argument(ImplicitArrayCreationExpression(InitializerExpression(SyntaxKind.ArrayInitializerExpression, SeparatedList<ExpressionSyntax>(marshalerInstances)))); | ||
} | ||
else | ||
{ | ||
marshallersArg = Argument(LiteralExpression(SyntaxKind.NullLiteralExpression)); | ||
} | ||
|
||
return marshallersArg; | ||
} | ||
|
||
protected static TypeDeclarationSyntax CreateTypeDeclarationWithoutTrivia(TypeDeclarationSyntax typeDeclaration) | ||
{ | ||
var mods = AddToModifiers(StripTriviaFromModifiers(typeDeclaration.Modifiers), SyntaxKind.UnsafeKeyword); | ||
return TypeDeclaration(typeDeclaration.Kind(), typeDeclaration.Identifier) | ||
.WithModifiers(mods); | ||
} | ||
|
||
protected static SyntaxTokenList AddToModifiers(SyntaxTokenList modifiers, SyntaxKind modifierToAdd) | ||
{ | ||
if (modifiers.IndexOf(modifierToAdd) >= 0) | ||
return modifiers; | ||
|
||
int idx = modifiers.IndexOf(SyntaxKind.PartialKeyword); | ||
return idx >= 0 | ||
? modifiers.Insert(idx, Token(modifierToAdd)) | ||
: modifiers.Add(Token(modifierToAdd)); | ||
} | ||
|
||
protected static SyntaxTokenList StripTriviaFromModifiers(SyntaxTokenList tokenList) | ||
{ | ||
SyntaxToken[] strippedTokens = new SyntaxToken[tokenList.Count]; | ||
for (int i = 0; i < tokenList.Count; i++) | ||
{ | ||
strippedTokens[i] = tokenList[i].WithoutTrivia(); | ||
} | ||
return new SyntaxTokenList(strippedTokens); | ||
} | ||
|
||
protected JSMarshalerMetadata ExtractMarshalerMeta(Compilation compilation, TypedConstant mt) | ||
{ | ||
try | ||
{ | ||
INamedTypeSymbol? marshalerType = compilation.GetTypeByMetadataName(mt.Value.ToString()); | ||
ITypeSymbol marshaledType = marshalerType.BaseType.TypeArguments[0]; | ||
|
||
var hasAfterJs = marshalerType.GetMembers("AfterToJavaScript").Length > 0; | ||
|
||
return new JSMarshalerMetadata | ||
{ | ||
MarshalerType = marshalerType, | ||
MarshaledType = marshaledType, | ||
ToManagedMethod = "MarshalToManaged", | ||
ToJsMethod = "MarshalToJs", | ||
AfterToJsMethod = hasAfterJs ? "AfterMarshalToJs" : null, | ||
}; | ||
} | ||
catch (Exception ex) | ||
{ | ||
prolog.AppendLine($"Failed when processing {mt.Value} \n" + ex.Message); | ||
return null; | ||
} | ||
} | ||
} | ||
} |
18 changes: 18 additions & 0 deletions
18
...ies/System.Private.Runtime.InteropServices.JavaScript/gen/MarshalerGenerator/Constants.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
|
||
namespace JavaScript.MarshalerGenerator | ||
{ | ||
internal static class Constants | ||
{ | ||
public const int JavaScriptMarshalerArgSize = 16; | ||
public const string JavaScriptMarshal = "System.Runtime.InteropServices.JavaScript.JavaScriptMarshal"; | ||
public const string JavaScriptPublic = "System.Runtime.InteropServices.JavaScript"; | ||
|
||
public const string JavaScriptMarshalGlobal = "global::" + JavaScriptMarshal; | ||
public const string JavaScriptMarshalerSignatureGlobal = "global::System.Runtime.InteropServices.JavaScript.JavaScriptMarshalerSignature"; | ||
public const string ModuleInitializerAttributeGlobal = "global::System.Runtime.CompilerServices.ModuleInitializerAttribute"; | ||
public const string DynamicDependencyAttributeGlobal = "global::System.Diagnostics.CodeAnalysis.DynamicDependencyAttribute"; | ||
} | ||
} |
112 changes: 112 additions & 0 deletions
112
...em.Private.Runtime.InteropServices.JavaScript/gen/MarshalerGenerator/JSExportGenerator.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System.Collections.Immutable; | ||
using System.Linq; | ||
using System.Text; | ||
using JavaScript.MarshalerGenerator; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.CSharp; | ||
using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
|
||
namespace System.Runtime.InteropServices.JavaScript | ||
{ | ||
[Generator] | ||
internal class JSExportGenerator : IIncrementalGenerator | ||
{ | ||
private const string AttributeFullName = "System.Runtime.InteropServices.JavaScript.JSExportAttribute"; | ||
private const string Category = "JSExport"; | ||
private const string Prefix = "JSExport"; | ||
#pragma warning disable RS2008 //TODO remove this | ||
public static DiagnosticDescriptor RequireStaticDD = new DiagnosticDescriptor(Prefix + "002", "JSExportAttribute requires static method", "JSExportAttribute requires static method", Category, DiagnosticSeverity.Error, true); | ||
public static void Debug(SourceProductionContext context, string message) | ||
{ | ||
var dd = new DiagnosticDescriptor(Prefix + "000", message, message, Category, DiagnosticSeverity.Warning, true); | ||
context.ReportDiagnostic(Diagnostic.Create(dd, Location.None)); | ||
} | ||
|
||
public void Initialize(IncrementalGeneratorInitializationContext context) | ||
{ | ||
IncrementalValuesProvider<JSExportMethodGenerator> methodDeclarations = context.SyntaxProvider | ||
.CreateSyntaxProvider( | ||
static (s, _) => IsMethodDeclarationWithAnyAttribute(s), | ||
static (ctx, _) => GetMethodDeclarationsWithMarshalerAttribute(ctx) | ||
) | ||
.Where(static m => m is not null); | ||
|
||
IncrementalValueProvider<(Compilation, ImmutableArray<JSExportMethodGenerator>)> compilationAndClasses = context.CompilationProvider.Combine(methodDeclarations.Collect()); | ||
|
||
context.RegisterSourceOutput(compilationAndClasses, static (spc, source) => Execute(source.Item1, source.Item2, spc)); | ||
} | ||
|
||
private static bool IsMethodDeclarationWithAnyAttribute(SyntaxNode node) | ||
=> node is MethodDeclarationSyntax m && m.AttributeLists.Count > 0; | ||
|
||
private static JSExportMethodGenerator GetMethodDeclarationsWithMarshalerAttribute(GeneratorSyntaxContext context) | ||
{ | ||
var methodSyntax = (MethodDeclarationSyntax)context.Node; | ||
|
||
foreach (AttributeListSyntax attributeListSyntax in methodSyntax.AttributeLists) | ||
{ | ||
foreach (AttributeSyntax attributeSyntax in attributeListSyntax.Attributes) | ||
{ | ||
IMethodSymbol attributeSymbol = context.SemanticModel.GetSymbolInfo(attributeSyntax).Symbol as IMethodSymbol; | ||
if (attributeSymbol != null) | ||
{ | ||
string fullName = attributeSymbol.ContainingType.ToDisplayString(); | ||
if (fullName == AttributeFullName) | ||
{ | ||
IMethodSymbol methodSymbol = context.SemanticModel.GetDeclaredSymbol(methodSyntax); | ||
var attributeData = methodSymbol.GetAttributes(); | ||
AttributeData JSExportData = attributeData.Where(d => d.AttributeClass.ToDisplayString() == AttributeFullName).Single(); | ||
|
||
|
||
var methodGenrator = new JSExportMethodGenerator(methodSyntax, attributeSyntax, methodSymbol, attributeSymbol, JSExportData); | ||
|
||
return methodGenrator; | ||
} | ||
} | ||
} | ||
} | ||
|
||
return null; | ||
} | ||
|
||
private static void Execute(Compilation compilation, ImmutableArray<JSExportMethodGenerator> methods, SourceProductionContext context) | ||
{ | ||
if (methods.IsDefaultOrEmpty) | ||
return; | ||
|
||
var fileText = new StringBuilder(); | ||
foreach (JSExportMethodGenerator method in methods) | ||
{ | ||
if (!method.MethodSymbol.IsStatic) | ||
{ | ||
context.ReportDiagnostic(Diagnostic.Create(RequireStaticDD, method.MethodSyntax.GetLocation())); | ||
continue; | ||
} | ||
try | ||
{ | ||
method.SelectMarshalers(compilation); | ||
|
||
string code = method.GenerateWrapper(); | ||
// this is just for debug | ||
fileText.AppendLine("/* " + method.MethodName + " " + DateTime.Now.ToString("o")); | ||
fileText.Append(method.prolog.ToString()); | ||
fileText.AppendLine("*/\n"); | ||
fileText.AppendLine(code); | ||
} | ||
catch (Exception ex) | ||
{ | ||
// this is just for debug | ||
fileText.AppendLine("/* " + method.MethodName + " " + DateTime.Now.ToString("o")); | ||
fileText.AppendLine(method.MethodSyntax.ToString()); | ||
fileText.Append(method.prolog.ToString()); | ||
fileText.AppendLine(ex.ToString()); | ||
fileText.AppendLine("*/"); | ||
} | ||
} | ||
context.AddSource("JSExport.g.cs", fileText.ToString()); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'd put .Private to the end so you can use same prefix for namespace aswell