Skip to content
Merged
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
3 changes: 2 additions & 1 deletion global.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"allowPrerelease": false
},
"msbuild-sdks": {
"Microsoft.Build.NoTargets": "3.7.56"
"Microsoft.Build.NoTargets": "3.7.56",
"Microsoft.Windows.WinmdGenerator": "0.63.31-preview"
}
}
2 changes: 1 addition & 1 deletion src/Microsoft.Windows.CsWin32/ArrayTypeHandleInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ internal record ArrayTypeHandleInfo(TypeHandleInfo ElementType, ArrayShape Shape
{
public override string ToString() => this.ToTypeSyntaxForDisplay().ToString();

internal override TypeSyntaxAndMarshaling ToTypeSyntax(TypeSyntaxSettings inputs, Generator.GeneratingElement forElement, CustomAttributeHandleCollection? customAttributes, ParameterAttributes parameterAttributes)
internal override TypeSyntaxAndMarshaling ToTypeSyntax(TypeSyntaxSettings inputs, Generator.GeneratingElement forElement, QualifiedCustomAttributeHandleCollection? customAttributes, ParameterAttributes parameterAttributes)
{
TypeSyntaxAndMarshaling element = this.ElementType.ToTypeSyntax(inputs, forElement, customAttributes);
if (inputs.AllowMarshaling || inputs.IsField)
Expand Down
93 changes: 48 additions & 45 deletions src/Microsoft.Windows.CsWin32/Generator.Com.cs

Large diffs are not rendered by default.

10 changes: 5 additions & 5 deletions src/Microsoft.Windows.CsWin32/Generator.Constant.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ internal void RequestConstant(FieldDefinitionHandle fieldDefHandle)
FieldDefinition fieldDef = this.Reader.GetFieldDefinition(fieldDefHandle);
FieldDeclarationSyntax constantDeclaration = this.DeclareConstant(fieldDef);

TypeHandleInfo fieldTypeInfo = fieldDef.DecodeSignature<TypeHandleInfo, SignatureHandleProvider.IGenericContext?>(SignatureHandleProvider.Instance, null) with { IsConstantField = true };
TypeHandleInfo fieldTypeInfo = fieldDef.DecodeSignature<TypeHandleInfo, SignatureHandleProvider.IGenericContext?>(this.SignatureHandleProvider, null) with { IsConstantField = true };
TypeDefinitionHandle? fieldType = null;
if (fieldTypeInfo is HandleTypeHandleInfo handleInfo && this.IsTypeDefStruct(handleInfo) && handleInfo.Handle.Kind == HandleKind.TypeReference)
{
Expand Down Expand Up @@ -213,7 +213,7 @@ ReadOnlyMemory<char> TrimCurlyBraces(ReadOnlyMemory<char> arg)
MethodDefinition methodDef = this.Reader.GetMethodDefinition(methodDefHandle);
if (this.Reader.StringComparer.Equals(methodDef.Name, ".ctor") && methodDef.GetParameters().Count == args.Count)
{
MethodSignature<TypeHandleInfo> ctorSignature = methodDef.DecodeSignature(SignatureHandleProvider.Instance, null);
MethodSignature<TypeHandleInfo> ctorSignature = methodDef.DecodeSignature(this.SignatureHandleProvider, null);
var argExpressions = new ArgumentSyntax[args.Count];

for (int i = 0; i < args.Count; i++)
Expand Down Expand Up @@ -245,7 +245,7 @@ ReadOnlyMemory<char> TrimCurlyBraces(ReadOnlyMemory<char> arg)
{
FieldDefinition fieldDef = this.Reader.GetFieldDefinition(fieldDefHandle);
string fieldName = this.Reader.GetString(fieldDef.Name);
TypeHandleInfo fieldTypeInfo = fieldDef.DecodeSignature(SignatureHandleProvider.Instance, null) with { IsConstantField = true };
TypeHandleInfo fieldTypeInfo = fieldDef.DecodeSignature(this.SignatureHandleProvider, null) with { IsConstantField = true };
fieldAssignmentExpressions[i] = AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName(fieldName),
Expand Down Expand Up @@ -354,9 +354,9 @@ private FieldDeclarationSyntax DeclareConstant(FieldDefinition fieldDef)
string name = this.Reader.GetString(fieldDef.Name);
try
{
TypeHandleInfo fieldTypeInfo = fieldDef.DecodeSignature(SignatureHandleProvider.Instance, null) with { IsConstantField = true };
TypeHandleInfo fieldTypeInfo = fieldDef.DecodeSignature(this.SignatureHandleProvider, null) with { IsConstantField = true };
CustomAttributeHandleCollection customAttributes = fieldDef.GetCustomAttributes();
TypeSyntaxAndMarshaling fieldType = fieldTypeInfo.ToTypeSyntax(this.fieldTypeSettings, GeneratingElement.Constant, customAttributes);
TypeSyntaxAndMarshaling fieldType = fieldTypeInfo.ToTypeSyntax(this.fieldTypeSettings, GeneratingElement.Constant, customAttributes.QualifyWith(this));
bool requiresUnsafe = false;
ExpressionSyntax value =
fieldDef.GetDefaultValue() is { IsNil: false } constantHandle ? ToExpressionSyntax(this.Reader, constantHandle) :
Expand Down
6 changes: 3 additions & 3 deletions src/Microsoft.Windows.CsWin32/Generator.Delegate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ private DelegateDeclarationSyntax DeclareDelegate(TypeDefinition typeDef)
}

this.GetSignatureForDelegate(typeDef, out MethodDefinition invokeMethodDef, out MethodSignature<TypeHandleInfo> signature, out CustomAttributeHandleCollection? returnTypeAttributes);
TypeSyntaxAndMarshaling returnValue = signature.ReturnType.ToTypeSyntax(typeSettings, GeneratingElement.Delegate, returnTypeAttributes);
TypeSyntaxAndMarshaling returnValue = signature.ReturnType.ToTypeSyntax(typeSettings, GeneratingElement.Delegate, returnTypeAttributes?.QualifyWith(this));

DelegateDeclarationSyntax result = DelegateDeclaration(returnValue.Type, Identifier(name))
.WithParameterList(FixTrivia(this.CreateParameterList(invokeMethodDef, signature, typeSettings, GeneratingElement.Delegate)))
Expand Down Expand Up @@ -113,7 +113,7 @@ private MemberDeclarationSyntax DeclareUntypedDelegate(TypeDefinition typeDef)
private void GetSignatureForDelegate(TypeDefinition typeDef, out MethodDefinition invokeMethodDef, out MethodSignature<TypeHandleInfo> signature, out CustomAttributeHandleCollection? returnTypeAttributes)
{
invokeMethodDef = typeDef.GetMethods().Select(this.Reader.GetMethodDefinition).Single(def => this.Reader.StringComparer.Equals(def.Name, "Invoke"));
signature = invokeMethodDef.DecodeSignature(SignatureHandleProvider.Instance, null);
signature = invokeMethodDef.DecodeSignature(this.SignatureHandleProvider, null);
returnTypeAttributes = this.GetReturnTypeCustomAttributes(invokeMethodDef);
}

Expand Down Expand Up @@ -149,6 +149,6 @@ private FunctionPointerParameterSyntax TranslateDelegateToFunctionPointer(TypeHa
return FunctionPointerParameter(delegateTypeDef.Generator.FunctionPointer(delegateTypeDef.Definition));
}

return FunctionPointerParameter(parameterTypeInfo.ToTypeSyntax(this.functionPointerTypeSettings, GeneratingElement.FunctionPointer, customAttributeHandles).GetUnmarshaledType());
return FunctionPointerParameter(parameterTypeInfo.ToTypeSyntax(this.functionPointerTypeSettings, GeneratingElement.FunctionPointer, customAttributeHandles?.QualifyWith(this)).GetUnmarshaledType());
}
}
2 changes: 1 addition & 1 deletion src/Microsoft.Windows.CsWin32/Generator.Enum.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ void AddEnumValue(FieldDefinitionHandle fieldDefHandle)
ConstantHandle valueHandle = fieldDef.GetDefaultValue();
if (valueHandle.IsNil)
{
enumBaseType = fieldDef.DecodeSignature(SignatureHandleProvider.Instance, null).ToTypeSyntax(this.enumTypeSettings, GeneratingElement.EnumValue, null).Type;
enumBaseType = fieldDef.DecodeSignature(this.SignatureHandleProvider, null).ToTypeSyntax(this.enumTypeSettings, GeneratingElement.EnumValue, null).Type;
return;
}

Expand Down
6 changes: 3 additions & 3 deletions src/Microsoft.Windows.CsWin32/Generator.Extern.cs
Original file line number Diff line number Diff line change
Expand Up @@ -184,11 +184,11 @@ private void DeclareExternMethod(MethodDefinitionHandle methodDefinitionHandle)

// If this method releases a handle, recreate the method signature such that we take the struct rather than the SafeHandle as a parameter.
TypeSyntaxSettings typeSettings = this.MetadataIndex.ReleaseMethods.Contains(entrypoint ?? methodName) ? this.externReleaseSignatureTypeSettings : this.externSignatureTypeSettings;
MethodSignature<TypeHandleInfo> signature = methodDefinition.DecodeSignature(SignatureHandleProvider.Instance, null);
MethodSignature<TypeHandleInfo> signature = methodDefinition.DecodeSignature(this.SignatureHandleProvider, null);
bool requiresUnicodeCharSet = signature.ParameterTypes.Any(p => p is PrimitiveTypeHandleInfo { PrimitiveTypeCode: PrimitiveTypeCode.Char });

CustomAttributeHandleCollection? returnTypeAttributes = this.GetReturnTypeCustomAttributes(methodDefinition);
TypeSyntaxAndMarshaling returnType = signature.ReturnType.ToTypeSyntax(typeSettings, GeneratingElement.ExternMethod, returnTypeAttributes, ParameterAttributes.Out);
TypeSyntaxAndMarshaling returnType = signature.ReturnType.ToTypeSyntax(typeSettings, GeneratingElement.ExternMethod, returnTypeAttributes?.QualifyWith(this), ParameterAttributes.Out);

// Search for any enum substitutions.
TypeSyntax? returnTypeEnumName = this.FindAssociatedEnum(returnTypeAttributes);
Expand Down Expand Up @@ -355,7 +355,7 @@ static SyntaxToken RefInOutKeyword(ParameterSyntax p) =>
// Add documentation if we can find it.
exposedMethod = this.AddApiDocumentation(entrypoint ?? methodName, exposedMethod);

this.volatileCode.AddMemberToModule(moduleName, this.DeclareFriendlyOverloads(methodDefinition, exposedMethod, this.methodsAndConstantsClassName, FriendlyOverloadOf.ExternMethod, this.injectedPInvokeHelperMethods));
this.volatileCode.AddMemberToModule(moduleName, this.DeclareFriendlyOverloads(methodDefinition, exposedMethod, this.methodsAndConstantsClassName, FriendlyOverloadOf.ExternMethod, this.injectedPInvokeHelperMethods, avoidWinmdRootAlias: false));
this.volatileCode.AddMemberToModule(moduleName, exposedMethod);
}
catch (Exception ex)
Expand Down
17 changes: 11 additions & 6 deletions src/Microsoft.Windows.CsWin32/Generator.FriendlyOverloads.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ private enum FriendlyOverloadOf
InterfaceMethod,
}

private IEnumerable<MethodDeclarationSyntax> DeclareFriendlyOverloads(MethodDefinition methodDefinition, MethodDeclarationSyntax externMethodDeclaration, NameSyntax declaringTypeName, FriendlyOverloadOf overloadOf, HashSet<string> helperMethodsAdded)
private IEnumerable<MethodDeclarationSyntax> DeclareFriendlyOverloads(MethodDefinition methodDefinition, MethodDeclarationSyntax externMethodDeclaration, NameSyntax declaringTypeName, FriendlyOverloadOf overloadOf, HashSet<string> helperMethodsAdded, bool avoidWinmdRootAlias)
{
if (!this.options.FriendlyOverloads.Enabled)
{
Expand Down Expand Up @@ -59,7 +59,12 @@ private IEnumerable<MethodDeclarationSyntax> DeclareFriendlyOverloads(MethodDefi
_ => throw new NotSupportedException(overloadOf.ToString()),
};

MethodSignature<TypeHandleInfo> originalSignature = methodDefinition.DecodeSignature(SignatureHandleProvider.Instance, null);
if (avoidWinmdRootAlias)
{
parameterTypeSyntaxSettings = parameterTypeSyntaxSettings with { AvoidWinmdRootAlias = true };
}

MethodSignature<TypeHandleInfo> originalSignature = methodDefinition.DecodeSignature(this.SignatureHandleProvider, null);
CustomAttributeHandleCollection? returnTypeAttributes = null;
var parameters = externMethodDeclaration.ParameterList.Parameters.Select(StripAttributes).ToList();
var lengthParamUsedBy = new Dictionary<int, int>();
Expand Down Expand Up @@ -105,7 +110,7 @@ private IEnumerable<MethodDeclarationSyntax> DeclareFriendlyOverloads(MethodDefi

TypeHandleInfo parameterTypeInfo = originalSignature.ParameterTypes[param.SequenceNumber - 1];
bool isManagedParameterType = this.IsManagedType(parameterTypeInfo);
bool mustRemainAsPointer = parameterTypeInfo is PointerTypeHandleInfo { ElementType: HandleTypeHandleInfo pointedElement } && this.IsStructWithFlexibleArray(pointedElement);
bool mustRemainAsPointer = parameterTypeInfo is PointerTypeHandleInfo { ElementType: HandleTypeHandleInfo pointedElement } && pointedElement.Generator.IsStructWithFlexibleArray(pointedElement);

IdentifierNameSyntax origName = IdentifierName(externParam.Identifier.ValueText);

Expand Down Expand Up @@ -146,7 +151,7 @@ private IEnumerable<MethodDeclarationSyntax> DeclareFriendlyOverloads(MethodDefi
bool hasOut = externParam.Modifiers.Any(SyntaxKind.OutKeyword);
arguments[param.SequenceNumber - 1] = arguments[param.SequenceNumber - 1].WithRefKindKeyword(TokenWithSpace(hasOut ? SyntaxKind.OutKeyword : SyntaxKind.RefKeyword));
}
else if (isOut && !isIn && !isReleaseMethod && parameterTypeInfo is PointerTypeHandleInfo { ElementType: HandleTypeHandleInfo pointedElementInfo } && this.TryGetHandleReleaseMethod(pointedElementInfo.Handle, paramAttributes, out string? outReleaseMethod) && !this.Reader.StringComparer.Equals(methodDefinition.Name, outReleaseMethod))
else if (isOut && !isIn && !isReleaseMethod && parameterTypeInfo is PointerTypeHandleInfo { ElementType: HandleTypeHandleInfo pointedElementInfo } && pointedElementInfo.Generator.TryGetHandleReleaseMethod(pointedElementInfo.Handle, paramAttributes, out string? outReleaseMethod) && !this.Reader.StringComparer.Equals(methodDefinition.Name, outReleaseMethod))
{
if (this.RequestSafeHandle(outReleaseMethod) is TypeSyntax safeHandleType)
{
Expand Down Expand Up @@ -668,7 +673,7 @@ bool TryHandleCountParam(TypeSyntax elementType, bool nullableSource)
}

TypeSyntax? returnSafeHandleType = originalSignature.ReturnType is HandleTypeHandleInfo returnTypeHandleInfo
&& this.TryGetHandleReleaseMethod(returnTypeHandleInfo.Handle, returnTypeAttributes, out string? returnReleaseMethod)
&& returnTypeHandleInfo.Generator.TryGetHandleReleaseMethod(returnTypeHandleInfo.Handle, returnTypeAttributes, out string? returnReleaseMethod)
? this.RequestSafeHandle(returnReleaseMethod) : null;
SyntaxToken friendlyMethodName = externMethodDeclaration.Identifier;

Expand Down Expand Up @@ -794,7 +799,7 @@ bool TryHandleCountParam(TypeSyntax elementType, bool nullableSource)
// If we're using C# 13 or later, consider adding the overload resolution attribute if it would likely resolve ambiguities.
if (this.LanguageVersion >= (LanguageVersion)1300 && parameters.Count == externMethodDeclaration.ParameterList.Parameters.Count)
{
this.DeclareOverloadResolutionPriorityAttributeIfNecessary();
this.volatileCode.GenerationTransaction(() => this.DeclareOverloadResolutionPriorityAttributeIfNecessary());
friendlyDeclaration = friendlyDeclaration.AddAttributeLists(AttributeList().AddAttributes(OverloadResolutionPriorityAttribute(1)));
}

Expand Down
22 changes: 16 additions & 6 deletions src/Microsoft.Windows.CsWin32/Generator.Handle.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ public partial class Generator
string releaseMethodModule = this.GetNormalizedModuleName(releaseMethodDef.GetImport());

IdentifierNameSyntax? safeHandleTypeIdentifier = IdentifierName(safeHandleClassName);
safeHandleType = safeHandleTypeIdentifier;
safeHandleType = QualifiedName(ParseName($"global::{this.Namespace}"), safeHandleTypeIdentifier);

MethodSignature<TypeHandleInfo> releaseMethodSignature = releaseMethodDef.DecodeSignature(SignatureHandleProvider.Instance, null);
MethodSignature<TypeHandleInfo> releaseMethodSignature = releaseMethodDef.DecodeSignature(this.SignatureHandleProvider, null);
TypeHandleInfo releaseMethodParameterTypeHandleInfo = releaseMethodSignature.ParameterTypes[0];
TypeSyntaxAndMarshaling releaseMethodParameterType = releaseMethodParameterTypeHandleInfo.ToTypeSyntax(this.externSignatureTypeSettings, GeneratingElement.HelperClassMember, default);

Expand All @@ -60,7 +60,10 @@ public partial class Generator
safeHandleType = null;
}

this.volatileCode.AddSafeHandleNameForReleaseMethod(releaseMethod, safeHandleType);
this.volatileCode.GenerationTransaction(delegate
{
this.volatileCode.AddSafeHandleNameForReleaseMethod(releaseMethod, safeHandleType);
});

if (safeHandleType is null)
{
Expand All @@ -72,15 +75,18 @@ public partial class Generator
return safeHandleType;
}

this.RequestExternMethod(releaseMethodHandle.Value);
this.volatileCode.GenerationTransaction(delegate
{
this.RequestExternMethod(releaseMethodHandle.Value);
});

// Collect all the known invalid values for this handle.
// If no invalid values are given (e.g. BSTR), we'll just assume 0 is invalid.
HashSet<IntPtr> invalidHandleValues = this.GetInvalidHandleValues(((HandleTypeHandleInfo)releaseMethodParameterTypeHandleInfo).Handle);
IntPtr preferredInvalidValue = GetPreferredInvalidHandleValue(invalidHandleValues, new IntPtr(-1));

CustomAttributeHandleCollection? atts = this.GetReturnTypeCustomAttributes(releaseMethodDef);
TypeSyntaxAndMarshaling releaseMethodReturnType = releaseMethodSignature.ReturnType.ToTypeSyntax(this.externSignatureTypeSettings, GeneratingElement.HelperClassMember, atts);
TypeSyntaxAndMarshaling releaseMethodReturnType = releaseMethodSignature.ReturnType.ToTypeSyntax(this.externSignatureTypeSettings, GeneratingElement.HelperClassMember, atts?.QualifyWith(this));

this.TryGetRenamedMethod(releaseMethod, out string? renamedReleaseMethod);

Expand Down Expand Up @@ -257,7 +263,11 @@ public partial class Generator
/// </summary>
"));

this.volatileCode.AddSafeHandleType(safeHandleDeclaration);
this.volatileCode.GenerationTransaction(delegate
{
this.volatileCode.AddSafeHandleType(safeHandleDeclaration);
});

return safeHandleType;
}
catch (Exception ex)
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.Windows.CsWin32/Generator.InlineArrays.cs
Original file line number Diff line number Diff line change
Expand Up @@ -731,7 +731,7 @@ StatementSyntax ClearSlice(ExpressionSyntax span) =>
}
else
{
qualifiedElementType = fieldTypeHandleInfo.ToTypeSyntax(this.extensionMethodSignatureTypeSettings, GeneratingElement.Other, customAttributes).Type switch
qualifiedElementType = fieldTypeHandleInfo.ToTypeSyntax(this.extensionMethodSignatureTypeSettings, GeneratingElement.Other, customAttributes.QualifyWith(this)).Type switch
{
ArrayTypeSyntax at => at.ElementType,
PointerTypeSyntax ptrType => ptrType.ElementType,
Expand Down
14 changes: 12 additions & 2 deletions src/Microsoft.Windows.CsWin32/Generator.Invariants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -312,8 +312,6 @@ public partial class Generator
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(ThisAssembly.AssemblyName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(ThisAssembly.AssemblyInformationalVersion)))));

private static readonly TypeSyntax HresultTypeSyntax = QualifiedName(QualifiedName(IdentifierName(GlobalWinmdRootNamespaceAlias), IdentifierName("Foundation")), IdentifierName("HRESULT"));

/// <summary>
/// Gets the set of macros that can be generated.
/// </summary>
Expand All @@ -340,4 +338,16 @@ public partial class Generator
.Add("IUnknown", "This COM interface is implicit in the runtime. Interfaces that derive from it should apply the [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] attribute instead.")
.Add("IDispatch", "This COM interface is implicit in the runtime. Interfaces that derive from it should apply the [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] attribute instead.")
.Add("VARIANT", "Use `object` instead of VARIANT when in COM interface mode. VARIANT can only be emitted when emitting COM interfaces as structs.");

private string Win32NamespacePrefixString => this.IsWin32Sdk ? GlobalWinmdRootNamespaceAlias : "global::Windows.Win32";

private IdentifierNameSyntax Win32NamespacePrefix => IdentifierName(this.Win32NamespacePrefixString);

private TypeSyntax HresultTypeSyntax
{
get
{
return QualifiedName(QualifiedName(this.Win32NamespacePrefix, IdentifierName("Foundation")), IdentifierName("HRESULT"));
}
}
}
Loading
Loading