-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
LibraryImportGenerator.cs
545 lines (478 loc) · 28.6 KB
/
LibraryImportGenerator.cs
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
// 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.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
[assembly: System.Resources.NeutralResourcesLanguage("en-US")]
namespace Microsoft.Interop
{
[Generator]
public sealed class LibraryImportGenerator : IIncrementalGenerator
{
internal sealed record IncrementalStubGenerationContext(
SignatureContext SignatureContext,
ContainingSyntaxContext ContainingSyntaxContext,
ContainingSyntax StubMethodSyntaxTemplate,
MethodSignatureDiagnosticLocations DiagnosticLocation,
SequenceEqualImmutableArray<AttributeSyntax> ForwardedAttributes,
LibraryImportData LibraryImportData,
MarshallingGeneratorFactoryKey<(TargetFramework TargetFramework, Version Version, LibraryImportGeneratorOptions Options)> GeneratorFactoryKey,
SequenceEqualImmutableArray<DiagnosticInfo> Diagnostics);
public static class StepNames
{
public const string CalculateStubInformation = nameof(CalculateStubInformation);
public const string GenerateSingleStub = nameof(GenerateSingleStub);
}
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// Collect all methods adorned with LibraryImportAttribute
var attributedMethods = context.SyntaxProvider
.ForAttributeWithMetadataName(
TypeNames.LibraryImportAttribute,
static (node, ct) => node is MethodDeclarationSyntax,
static (context, ct) => context.TargetSymbol is IMethodSymbol methodSymbol
? new { Syntax = (MethodDeclarationSyntax)context.TargetNode, Symbol = methodSymbol }
: null)
.Where(
static modelData => modelData is not null);
// Validate if attributed methods can have source generated
var methodsWithDiagnostics = attributedMethods.Select(static (data, ct) =>
{
DiagnosticInfo? diagnostic = GetDiagnosticIfInvalidMethodForGeneration(data.Syntax, data.Symbol);
return diagnostic is not null
? DiagnosticOr<(MethodDeclarationSyntax Syntax, IMethodSymbol Symbol)>.From(diagnostic)
: DiagnosticOr<(MethodDeclarationSyntax Syntax, IMethodSymbol Symbol)>.From((data.Syntax, data.Symbol));
});
var methodsToGenerate = context.FilterAndReportDiagnostics(methodsWithDiagnostics);
// Compute generator options
IncrementalValueProvider<LibraryImportGeneratorOptions> stubOptions = context.AnalyzerConfigOptionsProvider
.Select(static (options, ct) => new LibraryImportGeneratorOptions(options.GlobalOptions));
IncrementalValueProvider<StubEnvironment> stubEnvironment = context.CreateStubEnvironmentProvider();
// Validate environment that is being used to generate stubs.
context.RegisterDiagnostics(stubEnvironment.Combine(attributedMethods.Collect()).SelectMany((data, ct) =>
{
if (data.Right.IsEmpty // no attributed methods
|| data.Left.Compilation.Options is CSharpCompilationOptions { AllowUnsafe: true } // Unsafe code enabled
|| data.Left.TargetFramework != TargetFramework.Net) // Non-.NET 5 scenarios use forwarders and don't need unsafe code
{
return ImmutableArray<DiagnosticInfo>.Empty;
}
return ImmutableArray.Create(DiagnosticInfo.Create(GeneratorDiagnostics.RequiresAllowUnsafeBlocks, null));
}));
IncrementalValuesProvider<(MemberDeclarationSyntax, ImmutableArray<DiagnosticInfo>)> generateSingleStub = methodsToGenerate
.Combine(stubEnvironment)
.Combine(stubOptions)
.Select(static (data, ct) => new
{
data.Left.Left.Syntax,
data.Left.Left.Symbol,
Environment = data.Left.Right,
Options = data.Right
})
.Select(
static (data, ct) => CalculateStubInformation(data.Syntax, data.Symbol, data.Environment, data.Options, ct)
)
.WithTrackingName(StepNames.CalculateStubInformation)
.Combine(stubOptions)
.Select(
static (data, ct) => GenerateSource(data.Left, data.Right)
)
.WithComparer(Comparers.GeneratedSyntax)
.WithTrackingName(StepNames.GenerateSingleStub);
context.RegisterDiagnostics(generateSingleStub.SelectMany((stubInfo, ct) => stubInfo.Item2));
context.RegisterConcatenatedSyntaxOutputs(generateSingleStub.Select((data, ct) => data.Item1), "LibraryImports.g.cs");
}
private static List<AttributeSyntax> GenerateSyntaxForForwardedAttributes(AttributeData? suppressGCTransitionAttribute, AttributeData? unmanagedCallConvAttribute, AttributeData? defaultDllImportSearchPathsAttribute)
{
const string CallConvsField = "CallConvs";
// Manually rehydrate the forwarded attributes with fully qualified types so we don't have to worry about any using directives.
List<AttributeSyntax> attributes = new();
if (suppressGCTransitionAttribute is not null)
{
attributes.Add(Attribute(ParseName(TypeNames.SuppressGCTransitionAttribute)));
}
if (unmanagedCallConvAttribute is not null)
{
AttributeSyntax unmanagedCallConvSyntax = Attribute(ParseName(TypeNames.UnmanagedCallConvAttribute));
foreach (KeyValuePair<string, TypedConstant> arg in unmanagedCallConvAttribute.NamedArguments)
{
if (arg.Key == CallConvsField)
{
InitializerExpressionSyntax callConvs = InitializerExpression(SyntaxKind.ArrayInitializerExpression);
foreach (TypedConstant callConv in arg.Value.Values)
{
callConvs = callConvs.AddExpressions(
TypeOfExpression(((ITypeSymbol)callConv.Value!).AsTypeSyntax()));
}
ArrayTypeSyntax arrayOfSystemType = ArrayType(ParseTypeName(TypeNames.System_Type), SingletonList(ArrayRankSpecifier()));
unmanagedCallConvSyntax = unmanagedCallConvSyntax.AddArgumentListArguments(
AttributeArgument(
ArrayCreationExpression(arrayOfSystemType)
.WithInitializer(callConvs))
.WithNameEquals(NameEquals(IdentifierName(CallConvsField))));
}
}
attributes.Add(unmanagedCallConvSyntax);
}
if (defaultDllImportSearchPathsAttribute is not null)
{
attributes.Add(
Attribute(ParseName(TypeNames.DefaultDllImportSearchPathsAttribute)).AddArgumentListArguments(
AttributeArgument(
CastExpression(ParseTypeName(TypeNames.DllImportSearchPath),
LiteralExpression(SyntaxKind.NumericLiteralExpression,
Literal((int)defaultDllImportSearchPathsAttribute.ConstructorArguments[0].Value!))))));
}
return attributes;
}
private 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);
}
private static MethodDeclarationSyntax PrintGeneratedSource(
ContainingSyntax userDeclaredMethod,
SignatureContext stub,
BlockSyntax stubCode)
{
// Create stub function
return MethodDeclaration(stub.StubReturnType, userDeclaredMethod.Identifier)
.AddAttributeLists(stub.AdditionalAttributes.ToArray())
.WithModifiers(StripTriviaFromModifiers(userDeclaredMethod.Modifiers))
.WithParameterList(ParameterList(SeparatedList(stub.StubParameters)))
.WithBody(stubCode);
}
private static LibraryImportCompilationData? ProcessLibraryImportAttribute(AttributeData attrData)
{
// Found the LibraryImport, 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;
}
if (attrData.ConstructorArguments.Length == 0)
{
return null;
}
ImmutableDictionary<string, TypedConstant> namedArguments = ImmutableDictionary.CreateRange(attrData.NamedArguments);
string? entryPoint = null;
if (namedArguments.TryGetValue(nameof(LibraryImportCompilationData.EntryPoint), out TypedConstant entryPointValue))
{
if (entryPointValue.Value is not string)
{
return null;
}
entryPoint = (string)entryPointValue.Value!;
}
return new LibraryImportCompilationData(attrData.ConstructorArguments[0].Value!.ToString())
{
EntryPoint = entryPoint,
}.WithValuesFromNamedArguments(namedArguments);
}
private static IncrementalStubGenerationContext CalculateStubInformation(
MethodDeclarationSyntax originalSyntax,
IMethodSymbol symbol,
StubEnvironment environment,
LibraryImportGeneratorOptions options,
CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
INamedTypeSymbol? lcidConversionAttrType = environment.LcidConversionAttrType;
INamedTypeSymbol? suppressGCTransitionAttrType = environment.SuppressGCTransitionAttrType;
INamedTypeSymbol? unmanagedCallConvAttrType = environment.UnmanagedCallConvAttrType;
INamedTypeSymbol? defaultDllImportSearchPathsAttrType = environment.DefaultDllImportSearchPathsAttrType;
// Get any attributes of interest on the method
AttributeData? generatedDllImportAttr = null;
AttributeData? lcidConversionAttr = null;
AttributeData? suppressGCTransitionAttribute = null;
AttributeData? unmanagedCallConvAttribute = null;
AttributeData? defaultDllImportSearchPathsAttribute = null;
foreach (AttributeData attr in symbol.GetAttributes())
{
if (attr.AttributeClass is not null
&& attr.AttributeClass.ToDisplayString() == TypeNames.LibraryImportAttribute)
{
generatedDllImportAttr = attr;
}
else if (lcidConversionAttrType is not null && SymbolEqualityComparer.Default.Equals(attr.AttributeClass, lcidConversionAttrType))
{
lcidConversionAttr = attr;
}
else if (suppressGCTransitionAttrType is not null && SymbolEqualityComparer.Default.Equals(attr.AttributeClass, suppressGCTransitionAttrType))
{
suppressGCTransitionAttribute = attr;
}
else if (unmanagedCallConvAttrType is not null && SymbolEqualityComparer.Default.Equals(attr.AttributeClass, unmanagedCallConvAttrType))
{
unmanagedCallConvAttribute = attr;
}
else if (defaultDllImportSearchPathsAttrType is not null && SymbolEqualityComparer.Default.Equals(attr.AttributeClass, defaultDllImportSearchPathsAttrType))
{
defaultDllImportSearchPathsAttribute = attr;
}
}
Debug.Assert(generatedDllImportAttr is not null);
var generatorDiagnostics = new GeneratorDiagnostics();
// Process the LibraryImport attribute
LibraryImportCompilationData libraryImportData =
ProcessLibraryImportAttribute(generatedDllImportAttr!) ??
new LibraryImportCompilationData("INVALID_CSHARP_SYNTAX");
if (libraryImportData.IsUserDefined.HasFlag(InteropAttributeMember.StringMarshalling))
{
// User specified StringMarshalling.Custom without specifying StringMarshallingCustomType
if (libraryImportData.StringMarshalling == StringMarshalling.Custom && libraryImportData.StringMarshallingCustomType is null)
{
generatorDiagnostics.ReportInvalidStringMarshallingConfiguration(
generatedDllImportAttr, symbol.Name, SR.InvalidStringMarshallingConfigurationMissingCustomType);
}
// User specified something other than StringMarshalling.Custom while specifying StringMarshallingCustomType
if (libraryImportData.StringMarshalling != StringMarshalling.Custom && libraryImportData.StringMarshallingCustomType is not null)
{
generatorDiagnostics.ReportInvalidStringMarshallingConfiguration(
generatedDllImportAttr, symbol.Name, SR.InvalidStringMarshallingConfigurationNotCustom);
}
}
if (lcidConversionAttr is not null)
{
// Using LCIDConversion with LibraryImport is not supported
generatorDiagnostics.ReportConfigurationNotSupported(lcidConversionAttr, nameof(TypeNames.LCIDConversionAttribute));
}
// Create the stub.
var signatureContext = SignatureContext.Create(symbol, DefaultMarshallingInfoParser.Create(environment, generatorDiagnostics, symbol, libraryImportData, generatedDllImportAttr), environment, typeof(LibraryImportGenerator).Assembly);
var containingTypeContext = new ContainingSyntaxContext(originalSyntax);
var methodSyntaxTemplate = new ContainingSyntax(originalSyntax.Modifiers.StripTriviaFromTokens(), SyntaxKind.MethodDeclaration, originalSyntax.Identifier, originalSyntax.TypeParameterList);
List<AttributeSyntax> additionalAttributes = GenerateSyntaxForForwardedAttributes(suppressGCTransitionAttribute, unmanagedCallConvAttribute, defaultDllImportSearchPathsAttribute);
return new IncrementalStubGenerationContext(
signatureContext,
containingTypeContext,
methodSyntaxTemplate,
new MethodSignatureDiagnosticLocations(originalSyntax),
new SequenceEqualImmutableArray<AttributeSyntax>(additionalAttributes.ToImmutableArray(), SyntaxEquivalentComparer.Instance),
LibraryImportData.From(libraryImportData),
LibraryImportGeneratorHelpers.CreateGeneratorFactory(environment, options),
new SequenceEqualImmutableArray<DiagnosticInfo>(generatorDiagnostics.Diagnostics.ToImmutableArray())
);
}
private static (MemberDeclarationSyntax, ImmutableArray<DiagnosticInfo>) GenerateSource(
IncrementalStubGenerationContext pinvokeStub,
LibraryImportGeneratorOptions options)
{
var diagnostics = new GeneratorDiagnostics();
if (options.GenerateForwarders)
{
return (PrintForwarderStub(pinvokeStub.StubMethodSyntaxTemplate, explicitForwarding: true, pinvokeStub, diagnostics), pinvokeStub.Diagnostics.Array.AddRange(diagnostics.Diagnostics));
}
// Generate stub code
var stubGenerator = new PInvokeStubCodeGenerator(
pinvokeStub.GeneratorFactoryKey.Key.TargetFramework,
pinvokeStub.GeneratorFactoryKey.Key.Version,
pinvokeStub.SignatureContext.ElementTypeInformation,
pinvokeStub.LibraryImportData.SetLastError && !options.GenerateForwarders,
(elementInfo, ex) =>
{
diagnostics.ReportMarshallingNotSupported(pinvokeStub.DiagnosticLocation, elementInfo, ex.NotSupportedDetails, ex.DiagnosticProperties ?? ImmutableDictionary<string, string>.Empty);
},
pinvokeStub.GeneratorFactoryKey.GeneratorFactory);
// Check if the generator should produce a forwarder stub - regular DllImport.
// This is done if the signature is blittable or the target framework is not supported.
if (stubGenerator.StubIsBasicForwarder
|| !stubGenerator.SupportsTargetFramework)
{
return (PrintForwarderStub(pinvokeStub.StubMethodSyntaxTemplate, !stubGenerator.SupportsTargetFramework, pinvokeStub, diagnostics), pinvokeStub.Diagnostics.Array.AddRange(diagnostics.Diagnostics));
}
ImmutableArray<AttributeSyntax> forwardedAttributes = pinvokeStub.ForwardedAttributes.Array;
const string innerPInvokeName = "__PInvoke";
BlockSyntax code = stubGenerator.GeneratePInvokeBody(innerPInvokeName);
LocalFunctionStatementSyntax dllImport = CreateTargetDllImportAsLocalStatement(
stubGenerator,
options,
pinvokeStub.LibraryImportData,
innerPInvokeName,
pinvokeStub.StubMethodSyntaxTemplate.Identifier.Text);
if (!forwardedAttributes.IsEmpty)
{
dllImport = dllImport.AddAttributeLists(AttributeList(SeparatedList(forwardedAttributes)));
}
dllImport = dllImport.WithLeadingTrivia(Comment("// Local P/Invoke"));
code = code.AddStatements(dllImport);
return (pinvokeStub.ContainingSyntaxContext.WrapMemberInContainingSyntaxWithUnsafeModifier(PrintGeneratedSource(pinvokeStub.StubMethodSyntaxTemplate, pinvokeStub.SignatureContext, code)), pinvokeStub.Diagnostics.Array.AddRange(diagnostics.Diagnostics));
}
private static MemberDeclarationSyntax PrintForwarderStub(ContainingSyntax userDeclaredMethod, bool explicitForwarding, IncrementalStubGenerationContext stub, GeneratorDiagnostics diagnostics)
{
LibraryImportData pinvokeData = stub.LibraryImportData with { EntryPoint = stub.LibraryImportData.EntryPoint ?? userDeclaredMethod.Identifier.ValueText };
if (pinvokeData.IsUserDefined.HasFlag(InteropAttributeMember.StringMarshalling)
&& pinvokeData.StringMarshalling != StringMarshalling.Utf16)
{
// Report a diagnostic when forwarding explicitly due to generator options or down-level support. Otherwise, StringMarshalling can just be omitted
if (explicitForwarding)
{
diagnostics.ReportCannotForwardToDllImport(
stub.DiagnosticLocation,
$"{nameof(TypeNames.LibraryImportAttribute)}{Type.Delimiter}{nameof(StringMarshalling)}",
$"{nameof(StringMarshalling)}{Type.Delimiter}{pinvokeData.StringMarshalling}");
}
pinvokeData = pinvokeData with { IsUserDefined = pinvokeData.IsUserDefined & ~InteropAttributeMember.StringMarshalling };
}
if (pinvokeData.IsUserDefined.HasFlag(InteropAttributeMember.StringMarshallingCustomType))
{
// Report a diagnostic when forwarding explicitly due to generator options or down-level support. Otherwise, StringMarshallingCustomType can just be omitted
if (explicitForwarding)
{
diagnostics.ReportCannotForwardToDllImport(
stub.DiagnosticLocation,
$"{nameof(TypeNames.LibraryImportAttribute)}{Type.Delimiter}{nameof(InteropAttributeMember.StringMarshallingCustomType)}");
}
pinvokeData = pinvokeData with { IsUserDefined = pinvokeData.IsUserDefined & ~InteropAttributeMember.StringMarshallingCustomType };
}
SyntaxTokenList modifiers = StripTriviaFromModifiers(userDeclaredMethod.Modifiers);
modifiers = modifiers.AddToModifiers(SyntaxKind.ExternKeyword);
// Create stub function
MethodDeclarationSyntax stubMethod = MethodDeclaration(stub.SignatureContext.StubReturnType, userDeclaredMethod.Identifier)
.WithModifiers(modifiers)
.WithParameterList(ParameterList(SeparatedList(stub.SignatureContext.StubParameters)))
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
.AddModifiers()
.AddAttributeLists(
AttributeList(
SingletonSeparatedList(
CreateForwarderDllImport(pinvokeData))));
MemberDeclarationSyntax toPrint = stub.ContainingSyntaxContext.WrapMemberInContainingSyntaxWithUnsafeModifier(stubMethod);
return toPrint;
}
private static LocalFunctionStatementSyntax CreateTargetDllImportAsLocalStatement(
PInvokeStubCodeGenerator stubGenerator,
LibraryImportGeneratorOptions options,
LibraryImportData libraryImportData,
string stubTargetName,
string stubMethodName)
{
Debug.Assert(!options.GenerateForwarders, "GenerateForwarders should have already been handled to use a forwarder stub");
(ParameterListSyntax parameterList, TypeSyntax returnType, AttributeListSyntax returnTypeAttributes) = stubGenerator.GenerateTargetMethodSignatureData();
LocalFunctionStatementSyntax localDllImport = LocalFunctionStatement(returnType, stubTargetName)
.AddModifiers(
Token(SyntaxKind.StaticKeyword),
Token(SyntaxKind.ExternKeyword),
Token(SyntaxKind.UnsafeKeyword))
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
.WithAttributeLists(
SingletonList(AttributeList(
SingletonSeparatedList(
Attribute(
ParseName(typeof(DllImportAttribute).FullName),
AttributeArgumentList(
SeparatedList(
new[]
{
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal(libraryImportData.ModuleName))),
AttributeArgument(
NameEquals(nameof(DllImportAttribute.EntryPoint)),
null,
LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal(libraryImportData.EntryPoint ?? stubMethodName))),
AttributeArgument(
NameEquals(nameof(DllImportAttribute.ExactSpelling)),
null,
LiteralExpression(SyntaxKind.TrueLiteralExpression))
}
)))))))
.WithParameterList(parameterList);
if (returnTypeAttributes is not null)
{
localDllImport = localDllImport.AddAttributeLists(returnTypeAttributes.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.ReturnKeyword))));
}
return localDllImport;
}
private static AttributeSyntax CreateForwarderDllImport(LibraryImportData target)
{
var newAttributeArgs = new List<AttributeArgumentSyntax>
{
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal(target.ModuleName))),
AttributeArgument(
NameEquals(nameof(DllImportAttribute.EntryPoint)),
null,
CreateStringExpressionSyntax(target.EntryPoint)),
AttributeArgument(
NameEquals(nameof(DllImportAttribute.ExactSpelling)),
null,
LiteralExpression(SyntaxKind.TrueLiteralExpression))
};
if (target.IsUserDefined.HasFlag(InteropAttributeMember.StringMarshalling))
{
Debug.Assert(target.StringMarshalling == StringMarshalling.Utf16);
NameEqualsSyntax name = NameEquals(nameof(DllImportAttribute.CharSet));
ExpressionSyntax value = CreateEnumExpressionSyntax(CharSet.Unicode);
newAttributeArgs.Add(AttributeArgument(name, null, value));
}
if (target.IsUserDefined.HasFlag(InteropAttributeMember.SetLastError))
{
NameEqualsSyntax name = NameEquals(nameof(DllImportAttribute.SetLastError));
ExpressionSyntax value = CreateBoolExpressionSyntax(target.SetLastError);
newAttributeArgs.Add(AttributeArgument(name, null, value));
}
// Create new attribute
return Attribute(
ParseName(typeof(DllImportAttribute).FullName),
AttributeArgumentList(SeparatedList(newAttributeArgs)));
static ExpressionSyntax CreateBoolExpressionSyntax(bool trueOrFalse)
{
return LiteralExpression(
trueOrFalse
? SyntaxKind.TrueLiteralExpression
: SyntaxKind.FalseLiteralExpression);
}
static ExpressionSyntax CreateStringExpressionSyntax(string str)
{
return LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal(str));
}
static ExpressionSyntax CreateEnumExpressionSyntax<T>(T value) where T : Enum
{
return MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(typeof(T).FullName),
IdentifierName(value.ToString()));
}
}
private static DiagnosticInfo? GetDiagnosticIfInvalidMethodForGeneration(MethodDeclarationSyntax methodSyntax, IMethodSymbol method)
{
// Verify the method has no generic types or defined implementation
// and is marked static and partial.
if (methodSyntax.TypeParameterList is not null
|| methodSyntax.Body is not null
|| !methodSyntax.Modifiers.Any(SyntaxKind.StaticKeyword)
|| !methodSyntax.Modifiers.Any(SyntaxKind.PartialKeyword))
{
return DiagnosticInfo.Create(GeneratorDiagnostics.InvalidAttributedMethodSignature, methodSyntax.Identifier.GetLocation(), method.Name);
}
// Verify that the types the method is declared in are marked partial.
if (methodSyntax.Parent is TypeDeclarationSyntax typeDecl && !typeDecl.IsInPartialContext(out var nonPartialIdentifier))
{
return DiagnosticInfo.Create(GeneratorDiagnostics.InvalidAttributedMethodContainingTypeMissingModifiers, methodSyntax.Identifier.GetLocation(), method.Name, nonPartialIdentifier);
}
// Verify the method does not have a ref return
if (method.ReturnsByRef || method.ReturnsByRefReadonly)
{
return DiagnosticInfo.Create(GeneratorDiagnostics.ReturnConfigurationNotSupported, methodSyntax.Identifier.GetLocation(), "ref return", method.ToDisplayString());
}
return null;
}
}
}