Skip to content
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

[Rgen] Add the method data model missing pieces for the transformer. #22092

Merged
merged 2 commits into from
Feb 1, 2025
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
2 changes: 1 addition & 1 deletion src/rgen/Microsoft.Macios.Generator/DataModel/Method.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ namespace Microsoft.Macios.Generator.DataModel;
/// <summary>
/// Modifiers list.
/// </summary>
public ImmutableArray<SyntaxToken> Modifiers { get; } = [];
public ImmutableArray<SyntaxToken> Modifiers { get; init; } = [];

/// <summary>
/// Parameters list.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ symbol is IArrayTypeSymbol arrayTypeSymbol
IsArray = true;
ArrayElementTypeIsWrapped = arraySymbol.ElementType.IsWrapped ();
}
IsArray = symbol is IArrayTypeSymbol;

// try to get the named type symbol to have more educated decisions
var namedTypeSymbol = symbol as INamedTypeSymbol;
Expand Down
2 changes: 1 addition & 1 deletion src/rgen/Microsoft.Macios.Transformer/AttributesNames.cs
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ static class AttributesNames {
/// When this attribute is applied to a class it will just generate a static class, one that does not derive
/// from NSObject.
/// </summary>
[BindingFlag (AttributeTargets.Class)]
[BindingFlag (AttributeTargets.Class | AttributeTargets.Method)]
public const string StaticAttribute = "StaticAttribute";

/// <summary>
Expand Down
120 changes: 111 additions & 9 deletions src/rgen/Microsoft.Macios.Transformer/DataModel/Method.Transformer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,30 @@
// Licensed under the MIT License.

using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.Macios.Generator.Availability;
using Microsoft.Macios.Generator.Extensions;
using Microsoft.Macios.Transformer.Attributes;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;

namespace Microsoft.Macios.Generator.DataModel;

readonly partial struct Method {

readonly ExportData? overrideExportData;

/// <summary>
/// The data of the export attribute used to mark the value as a property binding.
/// </summary>
public ExportData ExportMethodData { get; }
public ExportData? ExportMethodData {
get {
return overrideExportData ?? ExportAttribute;
}
init => overrideExportData = value;
}

/// <summary>
/// Returns the bind from data if present in the binding.
Expand All @@ -23,22 +35,112 @@ readonly partial struct Method {
/// <summary>
/// True if the method was exported with the MarshalNativeExceptions flag allowing it to support native exceptions.
/// </summary>
public bool MarshalNativeExceptions => throw new NotImplementedException ();
public bool MarshalNativeExceptions => HasMarshalNativeExceptionsFlag;

public Method (string type, string name, TypeInfo returnType,
public Method (string type,
string name,
TypeInfo returnType,
SymbolAvailability symbolAvailability,
ExportData exportMethodData,
ImmutableArray<AttributeCodeChange> attributes,
ImmutableArray<SyntaxToken> modifiers,
Dictionary<string, List<AttributeData>> attributes,
ImmutableArray<Parameter> parameters)
{
Type = type;
Name = name;
AttributesDictionary = attributes;
ReturnType = returnType;
SymbolAvailability = symbolAvailability;
ExportMethodData = exportMethodData;
Attributes = attributes;
Modifiers = modifiers;
Parameters = parameters;

#pragma warning disable format
// Modifiers are special because we might be dealing with several flags that the user has set in the method.
// We have to add the partial keyword so that we can have the partial implementation of the method later generated
// by the roslyn code generator
Modifiers = this switch {
// internal static partial
{ HasNewFlag: false, HasStaticFlag: true, HasInternalFlag: true }
=> [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.StaticKeyword), Token (SyntaxKind.PartialKeyword)],

// public static partial
{ HasNewFlag: false, HasStaticFlag: true, HasInternalFlag: false }
=> [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.StaticKeyword), Token (SyntaxKind.PartialKeyword)],

// internal new static partial
{ HasNewFlag: true, HasStaticFlag: true, HasInternalFlag: true}
=> [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.NewKeyword), Token (SyntaxKind.StaticKeyword), Token (SyntaxKind.PartialKeyword)],

// public new static partial
{ HasNewFlag: true, HasStaticFlag: true, HasInternalFlag: false }
=> [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.NewKeyword), Token (SyntaxKind.StaticKeyword), Token (SyntaxKind.PartialKeyword)],

// public new virtual partial
{ HasNewFlag: true, HasStaticFlag: false, HasAbstractFlag: false, HasInternalFlag: false }
=> [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.NewKeyword), Token (SyntaxKind.VirtualKeyword), Token (SyntaxKind.PartialKeyword)],

// internal new virtual partial
{ HasNewFlag: true, HasStaticFlag: false, HasAbstractFlag: false, HasInternalFlag: true }
=> [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.NewKeyword), Token (SyntaxKind.VirtualKeyword), Token (SyntaxKind.PartialKeyword)],

// public new abstract
{ HasNewFlag: true, HasAbstractFlag: true, HasInternalFlag: false}
=> [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.NewKeyword), Token (SyntaxKind.AbstractKeyword)],

// internal new abstract
{ HasNewFlag: true, HasAbstractFlag: true, HasInternalFlag: true}
=> [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.NewKeyword), Token (SyntaxKind.AbstractKeyword)],

// public override partial
{ HasNewFlag: false, HasOverrideFlag: true, HasInternalFlag: false}
=> [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.OverrideKeyword), Token (SyntaxKind.PartialKeyword)],

// internal override partial
{ HasNewFlag: false, HasOverrideFlag: true, HasInternalFlag: true}
=> [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.OverrideKeyword), Token (SyntaxKind.PartialKeyword)],

// public abstract
{ HasAbstractFlag: true, HasInternalFlag: false}
=> [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.AbstractKeyword)],

// internal abstract
{ HasAbstractFlag: true, HasInternalFlag: true}
=> [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.AbstractKeyword)],

// general case, but internal
{ HasInternalFlag: true} =>
[Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.VirtualKeyword), Token (SyntaxKind.VirtualKeyword)],

// general case
_ => [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.VirtualKeyword), Token (SyntaxKind.PartialKeyword)]
};
#pragma warning restore format

}

public static bool TryCreate (MethodDeclarationSyntax declaration, SemanticModel semanticModel,
[NotNullWhen (true)] out Method? change)
{
if (semanticModel.GetDeclaredSymbol (declaration) is not IMethodSymbol method) {
change = null;
return false;
}
var parametersBucket = ImmutableArray.CreateBuilder<Parameter> ();
// loop over the parameters of the construct since changes on those implies a change in the generated code
foreach (var parameter in method.Parameters) {
var parameterDeclaration = declaration.ParameterList.Parameters [parameter.Ordinal];
if (!Parameter.TryCreate (parameter, parameterDeclaration, semanticModel, out var parameterChange))
continue;
parametersBucket.Add (parameterChange.Value);
}
// get the attributes of the method, this are used for two reasons:
// 1. The attributes might have flags such as [Internal] or [Abstract] that we need to set in the modifiers
// 2. The attributes might have return attributes that we need to set in the return type
var attributes = method.GetAttributeData ();
change = new (
type: method.ContainingSymbol.ToDisplayString ().Trim (), // we want the full name
name: method.Name,
returnType: new TypeInfo (method.ReturnType, attributes),
symbolAvailability: method.GetAvailabilityForSymbol (), // special case, in the transformer we only translate, we do not merge
attributes: attributes,
parameters: parametersBucket.ToImmutableArray ());
return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
// Licensed under the MIT License.

using Microsoft.Macios.Transformer.Attributes;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.Macios.Generator.Extensions;

namespace Microsoft.Macios.Generator.DataModel;

Expand All @@ -11,4 +15,29 @@ readonly partial struct Parameter {
/// Returns the bind from data if present in the binding.
/// </summary>
public BindAsData? BindAs => BindAsAttribute;

public static bool TryCreate (IParameterSymbol symbol, ParameterSyntax declaration, SemanticModel semanticModel,
[NotNullWhen (true)] out Parameter? parameter)
{
DelegateInfo? delegateInfo = null;
if (symbol.Type is INamedTypeSymbol namedTypeSymbol
&& namedTypeSymbol.DelegateInvokeMethod is not null) {
DelegateInfo.TryCreate (namedTypeSymbol.DelegateInvokeMethod, out delegateInfo);
}

// retrieve the parameter attributes because those might affect the parameter type, for example, the
// NullAllowed attribute can change the parameter type to be nullable.
var parameterAttrs = symbol.GetAttributeData ();
parameter = new (symbol.Ordinal, new (symbol.Type, parameterAttrs), symbol.Name) {
IsOptional = symbol.IsOptional,
IsParams = symbol.IsParams,
IsThis = symbol.IsThis,
DefaultValue = (symbol.HasExplicitDefaultValue) ? symbol.ExplicitDefaultValue?.ToString () : null,
ReferenceKind = symbol.RefKind.ToReferenceKind (),
Delegate = delegateInfo,
Attributes = declaration.GetAttributeCodeChanges (semanticModel),
AttributesDictionary = parameterAttrs,
};
return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,46 @@
// Licensed under the MIT License.

using Microsoft.CodeAnalysis;
using Microsoft.Macios.Generator.Extensions;
using Microsoft.Macios.Transformer;
using Microsoft.Macios.Transformer.Extensions;

namespace Microsoft.Macios.Generator.DataModel;

readonly partial struct TypeInfo {

internal TypeInfo (ITypeSymbol symbol) :
internal TypeInfo (ITypeSymbol symbol, Dictionary<string, List<AttributeData>> attributes) :
this (
symbol is IArrayTypeSymbol arrayTypeSymbol
? arrayTypeSymbol.ElementType.ToDisplayString ()
: symbol.ToDisplayString ().Trim ('?', '[', ']'),
symbol.SpecialType)
{
throw new NotImplementedException ();
IsNullable = attributes.HasNullAllowedFlag ();
// special case, the old bindings might not have the ? operator but will have the attr
IsBlittable = symbol.IsBlittable () && !IsNullable;
IsSmartEnum = symbol.IsSmartEnum ();
IsReferenceType = symbol.IsReferenceType;
IsStruct = symbol.TypeKind == TypeKind.Struct;
IsInterface = symbol.TypeKind == TypeKind.Interface;
IsNativeIntegerType = symbol.IsNativeIntegerType;
IsNativeEnum = symbol.HasAttribute (AttributesNames.NativeAttribute);

// data that we can get from the symbol without being INamedType
symbol.GetInheritance (
isNSObject: out isNSObject,
isNativeObject: out isINativeObject,
isDictionaryContainer: out isDictionaryContainer,
parents: out parents,
interfaces: out interfaces);
IsArray = symbol is IArrayTypeSymbol;

// try to get the named type symbol to have more educated decisions
var namedTypeSymbol = symbol as INamedTypeSymbol;

// store the enum special type, useful when generate code that needs to cast
EnumUnderlyingType = namedTypeSymbol?.EnumUnderlyingType?.SpecialType;
MetadataName = SpecialType is SpecialType.None or SpecialType.System_Void
? null : symbol.MetadataName;
}
}
33 changes: 20 additions & 13 deletions tests/rgen/Microsoft.Macios.Generator.Tests/TestDataFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public static TypeInfo ReturnTypeForString (bool isNullable = false)
IsINativeObject = false,
};

public static TypeInfo ReturnTypeForInt (bool isNullable = false)
public static TypeInfo ReturnTypeForInt (bool isNullable = false, bool keepInterfaces = false)
=> new (
name: "int",
specialType: SpecialType.System_Int32,
Expand All @@ -44,7 +44,7 @@ public static TypeInfo ReturnTypeForInt (bool isNullable = false)
isStruct: true
) {
Parents = ["System.ValueType", "object"],
Interfaces = isNullable
Interfaces = isNullable && !keepInterfaces
? []
: [
"System.IComparable",
Expand Down Expand Up @@ -175,17 +175,19 @@ public static TypeInfo ReturnTypeForInterface (string interfaceName)
IsInterface = true,
};

public static TypeInfo ReturnTypeForStruct (string structName)
public static TypeInfo ReturnTypeForStruct (string structName, bool isBlittable = false)
=> new (
name: structName,
isBlittable: isBlittable,
isStruct: true
) { Parents = ["System.ValueType", "object"] };

public static TypeInfo ReturnTypeForEnum (string enumName, bool isSmartEnum = false, bool isNativeEnum = false,
SpecialType underlyingType = SpecialType.System_Int32)
bool isNullable = false, bool isBlittable = true, SpecialType underlyingType = SpecialType.System_Int32)
=> new (
name: enumName,
isBlittable: true,
isNullable: isNullable,
isBlittable: isBlittable,
isSmartEnum: isSmartEnum
) {
Parents = [
Expand Down Expand Up @@ -300,7 +302,7 @@ public static TypeInfo ReturnTypeForDelegate (string delegateName)
]
};

public static TypeInfo ReturnTypeForNSObject (string? nsObjectName = null, bool isNullable = false)
public static TypeInfo ReturnTypeForNSObject (string? nsObjectName = null, bool isNullable = false, bool isApiDefinition = false)
=> new (
name: nsObjectName ?? "Foundation.NSObject",
isNullable: isNullable,
Expand All @@ -310,13 +312,18 @@ public static TypeInfo ReturnTypeForNSObject (string? nsObjectName = null, bool
IsNSObject = true,
IsINativeObject = true,
Parents = nsObjectName is null ? ["object"] : ["Foundation.NSObject", "object"],
Interfaces = [
"ObjCRuntime.INativeObject",
$"System.IEquatable<{nsObjectName ?? "Foundation.NSObject"}>",
"System.IDisposable",
"Foundation.INSObjectFactory",
"Foundation.INSObjectProtocol"
]
Interfaces = isApiDefinition
? [
"ObjCRuntime.INativeObject",
"Foundation.INSObjectFactory",
]
: [
"ObjCRuntime.INativeObject",
$"System.IEquatable<{nsObjectName ?? "Foundation.NSObject"}>",
"System.IDisposable",
"Foundation.INSObjectFactory",
"Foundation.INSObjectProtocol"
]
};

public static TypeInfo ReturnTypeForINativeObject (string nativeObjectName, bool isNullable = false)
Expand Down
Loading