Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,9 @@ internal static class Constants
public const string BindCSFunctionMethod = "BindManagedFunction";
public const string JSMarshalerTypeGlobal = "global::System.Runtime.InteropServices.JavaScript.JSMarshalerType";
public const string JSMarshalerTypeGlobalDot = "global::System.Runtime.InteropServices.JavaScript.JSMarshalerType.";
public const string SupportedOSPlatformAttribute = "global::System.Runtime.Versioning.SupportedOSPlatformAttribute";
public const string UnsupportedOSPlatformAttribute = "global::System.Runtime.Versioning.UnsupportedOSPlatformAttribute";
public const string SupportedOSPlatformAttributeShort = "System.Runtime.Versioning.SupportedOSPlatformAttribute";
public const string UnsupportedOSPlatformAttributeShort = "System.Runtime.Versioning.UnsupportedOSPlatformAttribute";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ internal sealed record IncrementalStubGenerationContext(
ContainingSyntax StubMethodSyntaxTemplate,
MethodSignatureDiagnosticLocations DiagnosticLocation,
JSImportData JSImportData,
bool HasExistingPlatformAttributes,
SequenceEqualImmutableArray<DiagnosticInfo> Diagnostics);

public static class StepNames
Expand Down Expand Up @@ -110,13 +111,32 @@ private static MemberDeclarationSyntax PrintGeneratedSource(
ContainingSyntax userDeclaredMethod,
JSSignatureContext stub,
ContainingSyntaxContext containingSyntaxContext,
bool hasExistingPlatformAttributes,
BlockSyntax stubCode)
{
// Create attribute lists for the stub method
var attributeLists = new List<AttributeListSyntax>();

// Add DebuggerNonUserCode attribute
attributeLists.Add(AttributeList(SingletonSeparatedList(
Attribute(IdentifierName(Constants.DebuggerNonUserCodeAttribute)))));

// Add SupportedOSPlatform("browser") attribute if user hasn't already specified platform attributes
if (!hasExistingPlatformAttributes)
{
attributeLists.Add(AttributeList(SingletonSeparatedList(
Attribute(
ParseName(Constants.SupportedOSPlatformAttribute),
AttributeArgumentList(SingletonSeparatedList(
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("browser")))))))));
}

// Create stub function
MethodDeclarationSyntax stubMethod = MethodDeclaration(stub.SignatureContext.StubReturnType, userDeclaredMethod.Identifier)
.AddAttributeLists(stub.SignatureContext.AdditionalAttributes.ToArray())
.WithAttributeLists(SingletonList(AttributeList(SingletonSeparatedList(
Attribute(IdentifierName(Constants.DebuggerNonUserCodeAttribute))))))
.WithAttributeLists(List(attributeLists))
.WithModifiers(StripTriviaFromModifiers(userDeclaredMethod.Modifiers))
.WithParameterList(ParameterList(SeparatedList(stub.SignatureContext.StubParameters)))
.WithBody(stubCode);
Expand Down Expand Up @@ -158,12 +178,21 @@ private static IncrementalStubGenerationContext CalculateStubInformation(
ct.ThrowIfCancellationRequested();
// Get any attributes of interest on the method
AttributeData? jsImportAttr = null;
bool hasExistingPlatformAttributes = false;
foreach (AttributeData attr in symbol.GetAttributes())
{
if (attr.AttributeClass is not null
&& attr.AttributeClass.ToDisplayString() == Constants.JSImportAttribute)
if (attr.AttributeClass is not null)
{
jsImportAttr = attr;
string attrName = attr.AttributeClass.ToDisplayString();
if (attrName == Constants.JSImportAttribute)
{
jsImportAttr = attr;
}
else if (attrName == Constants.SupportedOSPlatformAttributeShort ||
attrName == Constants.UnsupportedOSPlatformAttributeShort)
{
hasExistingPlatformAttributes = true;
}
}
}

Expand Down Expand Up @@ -193,6 +222,7 @@ private static IncrementalStubGenerationContext CalculateStubInformation(
methodSyntaxTemplate,
locations,
jsImportData,
hasExistingPlatformAttributes,
new SequenceEqualImmutableArray<DiagnosticInfo>(generatorDiagnostics.Diagnostics.ToImmutableArray()));
}

Expand Down Expand Up @@ -285,7 +315,7 @@ nativeOnlyParameterTemplate with

LocalFunctionStatementSyntax localFunction = GenerateInvokeFunction(LocalFunctionName, incrementalContext.SignatureContext, stubGenerator, hasReturn);

return (PrintGeneratedSource(incrementalContext.StubMethodSyntaxTemplate, incrementalContext.SignatureContext, incrementalContext.ContainingSyntaxContext, Block(bindStatement, code, localFunction)), incrementalContext.Diagnostics.Array.AddRange(diagnostics.Diagnostics));
return (PrintGeneratedSource(incrementalContext.StubMethodSyntaxTemplate, incrementalContext.SignatureContext, incrementalContext.ContainingSyntaxContext, incrementalContext.HasExistingPlatformAttributes, Block(bindStatement, code, localFunction)), incrementalContext.Diagnostics.Array.AddRange(diagnostics.Diagnostics));
}

private static IfStatementSyntax GenerateBindSyntax(JSImportData jsImportData, JSSignatureContext signatureContext, ArgumentSyntax signaturesArgument)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ public async Task ValidateGeneratedSourceOutput_AllAnnotatedParameters()
unsafe partial class Basic
{
[global::System.Diagnostics.DebuggerNonUserCode]
[global::System.Runtime.Versioning.SupportedOSPlatformAttribute("browser")]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that this is a kind of a breaking change (new warnings can appear in existing code), not sure if it needs to be announced/documented somewhere?

internal static partial void Annotated(object a1, long a2, long a3, global::System.Action a4, global::System.Func<int> a5, global::System.Span<byte> a6, global::System.ArraySegment<byte> a7, global::System.Threading.Tasks.Task<object> a8, object[] a9, global::System.DateTime a10, global::System.DateTimeOffset a11, global::System.Threading.Tasks.Task<global::System.DateTime> a12, global::System.Threading.Tasks.Task<global::System.DateTimeOffset> a13, global::System.Threading.Tasks.Task<long> a14, global::System.Threading.Tasks.Task<long> a15)
{
if (__signature_Annotated_1583225186 == null)
Expand Down Expand Up @@ -286,6 +287,7 @@ public async Task ValidateGeneratedSourceOutput_Return()
unsafe partial class Basic
{
[global::System.Diagnostics.DebuggerNonUserCode]
[global::System.Runtime.Versioning.SupportedOSPlatformAttribute("browser")]
public static partial global::System.Threading.Tasks.Task<int> Import1()
{
if (__signature_Import1_622134597 == null)
Expand Down Expand Up @@ -391,6 +393,137 @@ void __Stub(global::System.Runtime.InteropServices.JavaScript.JSMarshalerArgumen
await test.RunAsync();
}

[Fact]
public async Task ValidateGeneratedSourceOutput_SupportedOSPlatformAttribute()
{
string source = """
using System.Runtime.InteropServices.JavaScript;
partial class Basic
{
[JSImport("testFunction")]
public static partial void Import1();
}
""";

var test = new Test()
{
TestState =
{
Sources = { source },
GeneratedSources =
{
(typeof(Microsoft.Interop.JavaScript.JSImportGenerator),
"JSImports.g.cs",
SourceText.From("""
// <auto-generated/>
unsafe partial class Basic
{
[global::System.Diagnostics.DebuggerNonUserCode]
[global::System.Runtime.Versioning.SupportedOSPlatformAttribute("browser")]
public static partial void Import1()
{
if (__signature_Import1_19325221 == null)
{
__signature_Import1_19325221 = global::System.Runtime.InteropServices.JavaScript.JSFunctionBinding.BindJSFunction("testFunction", null, [global::System.Runtime.InteropServices.JavaScript.JSMarshalerType.Discard]);
}

{
global::System.Runtime.InteropServices.JavaScript.JSMarshalerArgument ____arg_exception_native;
global::System.Runtime.InteropServices.JavaScript.JSMarshalerArgument ____arg_return_native;
// Setup - Perform required setup.
global::System.Runtime.CompilerServices.Unsafe.SkipInit(out ____arg_return_native);
____arg_return_native.Initialize();
global::System.Runtime.CompilerServices.Unsafe.SkipInit(out ____arg_exception_native);
____arg_exception_native.Initialize();
{
__InvokeJSFunction(____arg_exception_native, ____arg_return_native);
}
}

[global::System.Diagnostics.DebuggerNonUserCode]
void __InvokeJSFunction(global::System.Runtime.InteropServices.JavaScript.JSMarshalerArgument ____arg_exception_native, global::System.Runtime.InteropServices.JavaScript.JSMarshalerArgument ____arg_return_native)
{
global::System.Runtime.InteropServices.JavaScript.JSFunctionBinding.InvokeJS(__signature_Import1_19325221, [____arg_exception_native, ____arg_return_native]);
}
}

static global::System.Runtime.InteropServices.JavaScript.JSFunctionBinding __signature_Import1_19325221;
}

""".ReplaceLineEndings("\r\n"), Encoding.UTF8)),
}
},
};

await test.RunAsync();
}

[Fact]
public async Task ValidateGeneratedSourceOutput_SupportedOSPlatformAttribute_NotAddedWhenUserHasIt()
{
string source = """
using System.Runtime.InteropServices.JavaScript;
using System.Runtime.Versioning;
partial class Basic
{
[JSImport("testFunction")]
[SupportedOSPlatform("browser")]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we test when the user's declaration has UnsupportedOSPlatform("browser") for example?

public static partial void Import1();
}
""";

var test = new Test()
{
TestState =
{
Sources = { source },
GeneratedSources =
{
(typeof(Microsoft.Interop.JavaScript.JSImportGenerator),
"JSImports.g.cs",
SourceText.From("""
// <auto-generated/>
unsafe partial class Basic
{
[global::System.Diagnostics.DebuggerNonUserCode]
public static partial void Import1()
{
if (__signature_Import1_19325221 == null)
{
__signature_Import1_19325221 = global::System.Runtime.InteropServices.JavaScript.JSFunctionBinding.BindJSFunction("testFunction", null, [global::System.Runtime.InteropServices.JavaScript.JSMarshalerType.Discard]);
}

{
global::System.Runtime.InteropServices.JavaScript.JSMarshalerArgument ____arg_exception_native;
global::System.Runtime.InteropServices.JavaScript.JSMarshalerArgument ____arg_return_native;
// Setup - Perform required setup.
global::System.Runtime.CompilerServices.Unsafe.SkipInit(out ____arg_return_native);
____arg_return_native.Initialize();
global::System.Runtime.CompilerServices.Unsafe.SkipInit(out ____arg_exception_native);
____arg_exception_native.Initialize();
{
__InvokeJSFunction(____arg_exception_native, ____arg_return_native);
}
}

[global::System.Diagnostics.DebuggerNonUserCode]
void __InvokeJSFunction(global::System.Runtime.InteropServices.JavaScript.JSMarshalerArgument ____arg_exception_native, global::System.Runtime.InteropServices.JavaScript.JSMarshalerArgument ____arg_return_native)
{
global::System.Runtime.InteropServices.JavaScript.JSFunctionBinding.InvokeJS(__signature_Import1_19325221, [____arg_exception_native, ____arg_return_native]);
}
}

static global::System.Runtime.InteropServices.JavaScript.JSFunctionBinding __signature_Import1_19325221;
}

""".ReplaceLineEndings("\r\n"), Encoding.UTF8)),
}
},
};

await test.RunAsync();
}

private sealed class Test : CSharpAnalyzerTest<EmptyDiagnosticAnalyzer, DefaultVerifier>
{
public Test()
Expand Down
Loading