Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
10 changes: 9 additions & 1 deletion src/bgen/AttributeManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,15 @@
using PlatformName = ObjCRuntime.PlatformName;
#endif

public class AttributeManager {
public interface IAttributeManager {
Comment thread
rolfbjarne marked this conversation as resolved.
Outdated
T [] GetCustomAttributes<T> (ICustomAttributeProvider provider) where T : Attribute;
bool HasAttribute<T> (ICustomAttributeProvider provider) where T : Attribute;
bool HasAttribute<T> (ICustomAttributeProvider i, Attribute [] attributes) where T : Attribute;
T GetCustomAttribute<T> (ICustomAttributeProvider provider) where T : Attribute;
bool HasNativeAttribute (ICustomAttributeProvider provider);
}

public class AttributeManager : IAttributeManager {
public BindingTouch BindingTouch;
TypeManager TypeManager { get { return BindingTouch.TypeManager; } }

Expand Down
112 changes: 19 additions & 93 deletions src/bgen/Generator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,14 @@ public partial class Generator : IMemberGatherer {
Frameworks Frameworks { get { return BindingTouch.Frameworks; } }
public TypeManager TypeManager { get { return BindingTouch.TypeManager; } }
public AttributeManager AttributeManager { get { return BindingTouch.AttributeManager; } }

Nomenclator nomenclator;
Nomenclator Nomenclator {
get {
nomenclator ??= new (AttributeManager);
return nomenclator;
}
}
public GeneratedTypes GeneratedTypes;
List<Exception> exceptions = new List<Exception> ();

Expand All @@ -73,7 +81,6 @@ public partial class Generator : IMemberGatherer {
Dictionary<string, string> send_methods = new Dictionary<string, string> ();
readonly MarshalTypeList marshalTypes = new ();
Dictionary<Type, TrampolineInfo> trampolines = new Dictionary<Type, TrampolineInfo> ();
Dictionary<Type, int> trampolines_generic_versions = new Dictionary<Type, int> ();
Dictionary<Type, Type> notification_event_arg_types = new Dictionary<Type, Type> ();
Dictionary<string, string> libraries = new Dictionary<string, string> (); // <LibraryName, libraryPath>

Expand Down Expand Up @@ -665,20 +672,6 @@ public bool HasForcedAttribute (ICustomAttributeProvider cu, out string owns)
return true;
}

public string MakeTrampolineName (Type t)
{
var trampoline_name = t.Name.Replace ("`", "Arity");
if (t.IsGenericType) {
var gdef = t.GetGenericTypeDefinition ();

if (!trampolines_generic_versions.ContainsKey (gdef))
trampolines_generic_versions.Add (gdef, 0);

trampoline_name = trampoline_name + "V" + trampolines_generic_versions [gdef]++;
}
return trampoline_name;
}

//
// MakeTrampoline: processes a delegate type and registers a TrampolineInfo with all the information
// necessary to create trampolines that allow Objective-C blocks to call C# code, and C# code to call
Expand Down Expand Up @@ -849,7 +842,7 @@ public TrampolineInfo MakeTrampoline (Type t)
}
if (AttributeManager.HasAttribute<BlockCallbackAttribute> (pi)) {
pars.AppendFormat ("{1} {0}", safe_name, NativeHandleType);
invoke.AppendFormat ("NID{0}.Create ({1})!", MakeTrampolineName (pi.ParameterType), safe_name);
invoke.AppendFormat ("NID{0}.Create ({1})!", Nomenclator.GetTrampolineName (pi.ParameterType), safe_name);
// The trampoline will eventually be generated in the final loop
} else {
if (!AttributeManager.HasAttribute<CCallbackAttribute> (pi)) {
Expand All @@ -870,7 +863,7 @@ public TrampolineInfo MakeTrampoline (Type t)

var rt = mi.ReturnType;
var rts = IsNativeEnum (rt) ? "var" : RenderType (rt);
var trampoline_name = MakeTrampolineName (t);
var trampoline_name = Nomenclator.GetTrampolineName (t);
var ti = new TrampolineInfo (userDelegate: FormatType (null, t),
delegateName: "D" + trampoline_name,
trampolineName: "T" + trampoline_name,
Expand Down Expand Up @@ -6658,9 +6651,9 @@ public void Generate (Type type)
if (bta.Singleton || mi.GetParameters ().Length == 1)
print ("internal EventHandler? {0};", miname);
else
print ("internal EventHandler<{0}>? {1};", GetEventArgName (mi), miname);
print ("internal EventHandler<{0}>? {1};", Nomenclator.GetEventArgName (mi), miname);
} else
print ("internal {0}? {1};", GetDelegateName (mi), miname);
print ("internal {0}? {1};", Nomenclator.GetDelegateName (mi), miname);

print ("[Preserve (Conditional = true)]");
if (isProtocolizedEventBacked)
Expand All @@ -6678,7 +6671,7 @@ public void Generate (Type type)
if (debug)
print ("Console.WriteLine (\"Method {0}.{1} invoked\");", dtype.Name, mi.Name);
if (pars.Length != minPars) {
eaname = GetEventArgName (mi);
eaname = Nomenclator.GetEventArgName (mi);
if (!generatedEvents.ContainsKey (eaname) && !eventArgTypes.ContainsKey (eaname)) {
eventArgTypes.Add (eaname, pars);
generatedEvents.Add (eaname, pars);
Expand Down Expand Up @@ -6714,7 +6707,7 @@ public void Generate (Type type)
indent--;
print ("}");
} else {
var delname = GetDelegateName (mi);
var delname = Nomenclator.GetDelegateName (mi);

if (!generatedDelegates.ContainsKey (delname) && !delegate_types.ContainsKey (delname)) {
generatedDelegates.Add (delname, null);
Expand Down Expand Up @@ -6811,7 +6804,7 @@ public void Generate (Type type)

string prev_miname = null;
int minameCount = 0;
repeatedDelegateApiNames.Clear ();
Nomenclator.ForgetDelegateApiNames ();
// Now add the instance vars and event handlers
foreach (var dtype in bta.Events.OrderBy (d => d.Name, StringComparer.Ordinal)) {
foreach (var mi in dtype.GatherMethods (this).OrderBy (m => m.Name, StringComparer.Ordinal)) {
Expand All @@ -6832,14 +6825,14 @@ public void Generate (Type type)
PrintObsoleteAttributes (mi);

if (bta.Singleton && mi.GetParameters ().Length == 0 || mi.GetParameters ().Length == 1)
print ("public event EventHandler {0} {{", GetEventName (mi).CamelCase ());
print ("public event EventHandler {0} {{", nomenclator.GetEventName (mi).CamelCase ());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The other examples reference Nomenclator, so I believe it should be the same here?

Suggested change
print ("public event EventHandler {0} {{", nomenclator.GetEventName (mi).CamelCase ());
print ("public event EventHandler {0} {{", Nomenclator.GetEventName (mi).CamelCase ());

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

hmm good catch, they should all use the property!

else
print ("public event EventHandler<{0}> {1} {{", GetEventArgName (mi), GetEventName (mi).CamelCase ());
print ("public event EventHandler<{0}> {1} {{", Nomenclator.GetEventArgName (mi), Nomenclator.GetEventName (mi).CamelCase ());
print ("\tadd {{ Ensure{0} ({1})!.{2} += value; }}", dtype.Name, ensureArg, miname);
print ("\tremove {{ Ensure{0} ({1})!.{2} -= value; }}", dtype.Name, ensureArg, miname);
print ("}\n");
} else {
print ("public {0}? {1} {{", GetDelegateName (mi), GetDelegateApiName (mi).CamelCase ());
print ("public {0}? {1} {{", Nomenclator.GetDelegateName (mi), Nomenclator.GetDelegateApiName (mi).CamelCase ());
print ("\tget {{ return Ensure{0} ({1})!.{2}; }}", dtype.Name, ensureArg, miname);
print ("\tset {{ Ensure{0} ({1})!.{2} = value; }}", dtype.Name, ensureArg, miname);
print ("}\n");
Expand Down Expand Up @@ -7017,7 +7010,7 @@ public void Generate (Type type)
}
// Now add the EventArgs classes
foreach (var eaclass in eventArgTypes.Keys.OrderBy (e => e, StringComparer.Ordinal)) {
if (skipGeneration.ContainsKey (eaclass)) {
if (Nomenclator.WasEventArgGenerated (eaclass)) {
continue;
}
int minPars = bta.Singleton ? 0 : 1;
Expand Down Expand Up @@ -7322,73 +7315,6 @@ bool MustPullValuesBack (IEnumerable<ParameterInfo> parameters)
return parameters.Any (pi => pi.ParameterType.IsByRef);
}

Dictionary<string, bool> skipGeneration = new Dictionary<string, bool> ();
string GetEventName (MethodInfo mi)
{
var a = AttributeManager.GetCustomAttribute<EventNameAttribute> (mi);
if (a == null)
return mi.Name;
var ea = (EventNameAttribute) a;

return ea.EvtName;
}

HashSet<string> repeatedDelegateApiNames = new HashSet<string> ();
string GetDelegateApiName (MethodInfo mi)
{
var a = AttributeManager.GetCustomAttribute<DelegateApiNameAttribute> (mi);

if (repeatedDelegateApiNames.Contains (mi.Name) && a == null)
throw new BindingException (1043, true, mi.Name);
if (a == null) {
repeatedDelegateApiNames.Add (mi.Name);
return mi.Name;
}

var apiName = (DelegateApiNameAttribute) a;
if (repeatedDelegateApiNames.Contains (apiName.Name))
throw new BindingException (1044, true, apiName.Name);

return apiName.Name;
}

string GetEventArgName (MethodInfo mi)
{
if (mi.GetParameters ().Length == 1)
return "EventArgs";

var a = AttributeManager.GetCustomAttribute<EventArgsAttribute> (mi);
if (a == null)
throw new BindingException (1004, true, mi.DeclaringType.FullName, mi.Name, mi.GetParameters ().Length);

var ea = (EventArgsAttribute) a;
if (ea.ArgName.EndsWith ("EventArgs", StringComparison.Ordinal))
throw new BindingException (1005, true, mi.DeclaringType.FullName, mi.Name);

if (ea.SkipGeneration) {
skipGeneration [ea.FullName ? ea.ArgName : ea.ArgName + "EventArgs"] = true;
}

if (ea.FullName)
return ea.ArgName;

return ea.ArgName + "EventArgs";
}

string GetDelegateName (MethodInfo mi)
{
Attribute a = AttributeManager.GetCustomAttribute<DelegateNameAttribute> (mi);
if (a != null)
return ((DelegateNameAttribute) a).Name;

a = AttributeManager.GetCustomAttribute<EventArgsAttribute> (mi);
if (a == null)
throw new BindingException (1006, true, mi.DeclaringType.FullName, mi.Name);

ErrorHelper.Warning (1102, mi.DeclaringType.FullName, mi.Name);
return ((EventArgsAttribute) a).ArgName;
}

object GetDefaultValue (MethodInfo mi)
{
Attribute a = AttributeManager.GetCustomAttribute<DefaultValueAttribute> (mi);
Expand Down
100 changes: 100 additions & 0 deletions src/bgen/Nomenclator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
using System;
using System.Collections.Generic;
using System.Reflection;

#nullable enable

// Noun. nomenclator (plural nomenclators) An assistant who specializes in providing timely and spatially relevant
// reminders of the names of persons and other socially important information
public class Nomenclator {
readonly Dictionary<string, bool> skipGeneration = new ();
readonly HashSet<string> repeatedDelegateApiNames = new ();
readonly Dictionary<Type, int> trampolinesGenericVersions = new ();

readonly IAttributeManager attributeManager;

public Nomenclator (IAttributeManager attributeManager)
{
this.attributeManager = attributeManager;
}

public string GetDelegateName (MethodInfo mi)
{
Attribute a = attributeManager.GetCustomAttribute<DelegateNameAttribute> (mi);
if (a is not null)
return ((DelegateNameAttribute) a).Name;

a = attributeManager.GetCustomAttribute<EventArgsAttribute> (mi);
if (a is null)
throw new BindingException (1006, true, mi.DeclaringType!.FullName, mi.Name);

ErrorHelper.Warning (1102, mi.DeclaringType!.FullName, mi.Name);
return ((EventArgsAttribute) a).ArgName;
}

public string GetEventName (MethodInfo mi)
{
var a = attributeManager.GetCustomAttribute<EventNameAttribute> (mi);
return a is null ? mi.Name : a.EvtName;
}

public string GetDelegateApiName (MethodInfo mi)
{
var apiName = attributeManager.GetCustomAttribute<DelegateApiNameAttribute> (mi);

if (repeatedDelegateApiNames.Contains (mi.Name) && apiName is null)
throw new BindingException (1043, true, mi.Name);
if (apiName is null) {
repeatedDelegateApiNames.Add (mi.Name);
return mi.Name;
}

if (repeatedDelegateApiNames.Contains (apiName.Name))
throw new BindingException (1044, true, apiName.Name);

return apiName.Name;
}

public string GetEventArgName (MethodInfo mi)
{
if (mi.GetParameters ().Length == 1)
return "EventArgs";

var a = attributeManager.GetCustomAttribute<EventArgsAttribute> (mi);
if (a is null)
throw new BindingException (1004, true, mi.DeclaringType!.FullName, mi.Name, mi.GetParameters ().Length);

var ea = (EventArgsAttribute) a;
if (ea.ArgName.EndsWith ("EventArgs", StringComparison.Ordinal))
throw new BindingException (1005, true, mi.DeclaringType!.FullName, mi.Name);

if (ea.SkipGeneration) {
skipGeneration [ea.FullName ? ea.ArgName : ea.ArgName + "EventArgs"] = true;
}

if (ea.FullName)
return ea.ArgName;

return ea.ArgName + "EventArgs";
}

public bool WasEventArgGenerated (string eaclass)
=> skipGeneration.ContainsKey (eaclass);

public string GetTrampolineName (Type t)
{
var trampolineName = t.Name.Replace ("`", "Arity");
if (t.IsGenericType) {
var gdef = t.GetGenericTypeDefinition ();

if (!trampolinesGenericVersions.ContainsKey (gdef))
trampolinesGenericVersions.Add (gdef, 0);

trampolineName = trampolineName + "V" + trampolinesGenericVersions [gdef]++;
}
return trampolineName;
}

public void ForgetDelegateApiNames ()
=> repeatedDelegateApiNames.Clear ();
}
1 change: 1 addition & 0 deletions src/generator.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@
<Compile Include="..\src\bgen\IMemberGatherer.cs" />
<Compile Include="..\src\bgen\MemberInformation.cs" />
<Compile Include="..\src\bgen\NamespaceManager.cs" />
<Compile Include="..\src\bgen\Nomenclator.cs" />
<Compile Include="..\src\bgen\NullabilityInfoContext.cs" />
<Compile Include="..\src\bgen\PlatformNameExtensions.cs" />
<Compile Include="..\src\bgen\StringExtensions.cs" />
Expand Down
13 changes: 13 additions & 0 deletions tests/bgen/bgen-tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<PackageReference Include="NUnit3TestAdapter" Version="3.15.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.1" />
<PackageReference Include="Mono.Cecil" Version="0.11.4" />
<PackageReference Include="Moq" Version="4.18.4" />
<PackageReference Include="MSBuild.StructuredLogger" Version="2.1.758" />
</ItemGroup>

Expand All @@ -28,6 +29,9 @@
<Compile Include="..\generator\BGenTool.cs">
<Link>BGenTool.cs</Link>
</Compile>
<Compile Include="..\generator\CollectionsExtensionsTests.cs">
<Link>CollectionsExtensionsTests.cs</Link>
</Compile>
<Compile Include="..\generator\ErrorTests.cs">
<Link>ErrorTests.cs</Link>
</Compile>
Expand All @@ -43,12 +47,21 @@
<Compile Include="..\common\Profile.cs">
<Link>Profile.cs</Link>
</Compile>
<Compile Include="..\generator\NomenclatorTests.cs">
<Link>NomenclatorTests.cs</Link>
</Compile>
<Compile Include="..\generator\NullabilityContextTests.cs">
<Link>NullabilityContextTests.cs</Link>
</Compile>
<Compile Include="..\generator\StringExtensionTests.cs">
<Link>StringExtensionTests.cs</Link>
</Compile>
<Compile Include="..\generator\PlatformNameExtensionsTests.cs">
<Link>PlatformNameExtensionsTests.cs</Link>
</Compile>
<Compile Include="..\generator\ReflectionTest.cs">
<Link>ReflectionTest.cs</Link>
</Compile>
<Compile Include="..\mtouch\Cache.cs">
<Link>Cache.cs</Link>
</Compile>
Expand Down
Loading