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

Greatly improve the understanding of the log-potential-typedef-remappings feature #281

Merged
merged 1 commit into from
Oct 16, 2021
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
67 changes: 33 additions & 34 deletions sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitDecl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ private void VisitDecl(Decl decl)
{
if (IsExcluded(decl))
{
if (decl.Kind == CX_DeclKind.CX_DeclKind_Typedef)
{
VisitTypedefDecl((TypedefDecl)decl, onlyHandleRemappings: true);
}
return;
}

Expand Down Expand Up @@ -133,7 +137,7 @@ private void VisitDecl(Decl decl)

case CX_DeclKind.CX_DeclKind_Typedef:
{
VisitTypedefDecl((TypedefDecl)decl);
VisitTypedefDecl((TypedefDecl)decl, onlyHandleRemappings: false);
break;
}

Expand Down Expand Up @@ -268,7 +272,7 @@ private void VisitEnumConstantDecl(EnumConstantDecl enumConstantDecl)
var kind = isAnonymousEnum ? ValueKind.Primitive : ValueKind.Enumerator;
var flags = ValueFlags.Constant;

if (enumConstantDecl.InitExpr is not null)
if ((enumConstantDecl.InitExpr is not null) || isAnonymousEnum)
{
flags |= ValueFlags.Initializer;
}
Expand Down Expand Up @@ -2411,13 +2415,13 @@ private void VisitTypeAliasDecl(TypeAliasDecl typeAliasDecl)
// Nothing to generate for type alias declarations
}

private void VisitTypedefDecl(TypedefDecl typedefDecl)
private void VisitTypedefDecl(TypedefDecl typedefDecl, bool onlyHandleRemappings)
{
ForUnderlyingType(typedefDecl, typedefDecl.UnderlyingType);
ForUnderlyingType(typedefDecl, typedefDecl.UnderlyingType, onlyHandleRemappings);

void ForFunctionProtoType(TypedefDecl typedefDecl, FunctionProtoType functionProtoType, Type parentType)
void ForFunctionProtoType(TypedefDecl typedefDecl, FunctionProtoType functionProtoType, Type parentType, bool onlyHandleRemappings)
{
if (!_config.ExcludeFnptrCodegen)
if (!_config.ExcludeFnptrCodegen || onlyHandleRemappings)
{
return;
}
Expand Down Expand Up @@ -2457,43 +2461,43 @@ void ForFunctionProtoType(TypedefDecl typedefDecl, FunctionProtoType functionPro
StopUsingOutputBuilder();
}

void ForPointeeType(TypedefDecl typedefDecl, Type parentType, Type pointeeType)
void ForPointeeType(TypedefDecl typedefDecl, Type parentType, Type pointeeType, bool onlyHandleRemappings)
{
if (pointeeType is AttributedType attributedType)
{
ForPointeeType(typedefDecl, attributedType, attributedType.ModifiedType);
ForPointeeType(typedefDecl, attributedType, attributedType.ModifiedType, onlyHandleRemappings);
}
else if (pointeeType is ElaboratedType elaboratedType)
{
ForPointeeType(typedefDecl, elaboratedType, elaboratedType.NamedType);
ForPointeeType(typedefDecl, elaboratedType, elaboratedType.NamedType, onlyHandleRemappings);
}
else if (pointeeType is FunctionProtoType functionProtoType)
{
ForFunctionProtoType(typedefDecl, functionProtoType, parentType);
ForFunctionProtoType(typedefDecl, functionProtoType, parentType, onlyHandleRemappings);
}
else if (pointeeType is PointerType pointerType)
{
ForPointeeType(typedefDecl, pointerType, pointerType.PointeeType);
ForPointeeType(typedefDecl, pointerType, pointerType.PointeeType, onlyHandleRemappings);
}
else if (pointeeType is TypedefType typedefType)
{
ForPointeeType(typedefDecl, typedefType, typedefType.Decl.UnderlyingType);
ForPointeeType(typedefDecl, typedefType, typedefType.Decl.UnderlyingType, onlyHandleRemappings);
}
else if (pointeeType is not ConstantArrayType and not BuiltinType and not TagType and not TemplateTypeParmType)
{
AddDiagnostic(DiagnosticLevel.Error, $"Unsupported pointee type: '{pointeeType.TypeClassSpelling}'. Generating bindings may be incomplete.", typedefDecl);
}
}

void ForUnderlyingType(TypedefDecl typedefDecl, Type underlyingType)
void ForUnderlyingType(TypedefDecl typedefDecl, Type underlyingType, bool onlyHandleRemappings)
{
if (underlyingType is ArrayType arrayType)
{
// Nothing to do for array types
}
else if (underlyingType is AttributedType attributedType)
{
ForUnderlyingType(typedefDecl, attributedType.ModifiedType);
ForUnderlyingType(typedefDecl, attributedType.ModifiedType, onlyHandleRemappings);
}
else if (underlyingType is BuiltinType builtinType)
{
Expand All @@ -2505,46 +2509,41 @@ void ForUnderlyingType(TypedefDecl typedefDecl, Type underlyingType)
}
else if (underlyingType is ElaboratedType elaboratedType)
{
ForUnderlyingType(typedefDecl, elaboratedType.NamedType);
ForUnderlyingType(typedefDecl, elaboratedType.NamedType, onlyHandleRemappings);
}
else if (underlyingType is FunctionProtoType functionProtoType)
{
ForFunctionProtoType(typedefDecl, functionProtoType, parentType: null);
ForFunctionProtoType(typedefDecl, functionProtoType, parentType: null, onlyHandleRemappings);
}
else if (underlyingType is PointerType pointerType)
{
ForPointeeType(typedefDecl, parentType: null, pointerType.PointeeType);
ForPointeeType(typedefDecl, parentType: null, pointerType.PointeeType, onlyHandleRemappings);
}
else if (underlyingType is ReferenceType referenceType)
{
ForPointeeType(typedefDecl, parentType: null, referenceType.PointeeType);
ForPointeeType(typedefDecl, parentType: null, referenceType.PointeeType, onlyHandleRemappings);
}
else if (underlyingType is TagType underlyingTagType)
{
// See if there's a potential typedef remapping we want to log
if (_config.LogPotentialTypedefRemappings)
{
var typedefName = typedefDecl.UnderlyingDecl.Name;
var possibleNamesToRemap = new string[] {"_" + typedefName, "_tag" + typedefName, "tag" + typedefName, typedefName + "_tag" };
var underlyingName = underlyingTagType.AsString;
var underlyingName = GetCursorName(underlyingTagType.AsTagDecl);
var typedefName = GetCursorName(typedefDecl);

foreach (var possibleNameToRemap in possibleNamesToRemap)
if (underlyingName != typedefName)
{
if (!_validNameRemappings.TryGetValue(underlyingName, out var remappings))
{
if (!_config.RemappedNames.ContainsKey(possibleNameToRemap) && !_config.RemappedNames.ContainsKey(possibleNameToRemap + "*"))
{
if (possibleNameToRemap == underlyingName)
{
AddDiagnostic(DiagnosticLevel.Info, $"Potential remap: {possibleNameToRemap}={typedefName}");
}
}
remappings = new HashSet<string>();
_validNameRemappings[underlyingName] = remappings;
}

_ = remappings.Add(typedefName);
}
}
else if (underlyingType is TemplateSpecializationType templateSpecializationType)
{
if (templateSpecializationType.IsTypeAlias)
{
ForUnderlyingType(typedefDecl, templateSpecializationType.AliasedType);
ForUnderlyingType(typedefDecl, templateSpecializationType.AliasedType, onlyHandleRemappings);
}
else
{
Expand All @@ -2557,7 +2556,7 @@ void ForUnderlyingType(TypedefDecl typedefDecl, Type underlyingType)
}
else if (underlyingType is TypedefType typedefType)
{
ForUnderlyingType(typedefDecl, typedefType.Decl.UnderlyingType);
ForUnderlyingType(typedefDecl, typedefType.Decl.UnderlyingType, onlyHandleRemappings);
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2440,7 +2440,7 @@ private void VisitOffsetOfExpr(OffsetOfExpr offsetOfExpr)
outputBuilder.Write("Marshal.OffsetOf<");
outputBuilder.Write(GetRemappedTypeName(offsetOfExpr, context: null, offsetOfExpr.TypeSourceInfoType, out var _, skipUsing: false));
outputBuilder.Write(">(\"");
Visit(offsetOfExpr.Referenced);
Visit(offsetOfExpr.Referenced ?? offsetOfExpr.CursorChildren[1]);
outputBuilder.Write("\")");

StopCSharpCode();
Expand Down
153 changes: 149 additions & 4 deletions sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ public sealed partial class PInvokeGenerator : IDisposable
private readonly Dictionary<NamedDecl, string> _cursorNames;
private readonly Dictionary<(NamedDecl namedDecl, bool truncateForFunctionParameters), string> _cursorQualifiedNames;
private readonly Dictionary<(Cursor cursor, Cursor context, Type type), (string typeName, string nativeTypeName)> _typeNames;
private readonly Dictionary<string, HashSet<string>> _validNameRemappings;
private readonly HashSet<string> _usedRemappings;

private string _filePath;
private string[] _clangCommandLineArgs;
Expand Down Expand Up @@ -90,6 +92,14 @@ public PInvokeGenerator(PInvokeGeneratorConfiguration config, Func<string, Strea
_cursorNames = new Dictionary<NamedDecl, string>();
_cursorQualifiedNames = new Dictionary<(NamedDecl, bool), string>();
_typeNames = new Dictionary<(Cursor, Cursor, Type), (string, string)>();
_validNameRemappings = new Dictionary<string, HashSet<string>>() {
["intptr_t"] = new HashSet<string>() { "IntPtr", "nint" },
["ptrdiff_t"] = new HashSet<string>() { "IntPtr", "nint" },
["size_t"] = new HashSet<string>() { "UIntPtr", "nuint" },
["uintptr_t"] = new HashSet<string>() { "UIntPtr", "nuint" },
["_GUID"] = new HashSet<string>() { "Guid" },
};
_usedRemappings = new HashSet<string>();
}

~PInvokeGenerator()
Expand Down Expand Up @@ -121,7 +131,7 @@ public void Close()
{
var iidName = foundUuid.Key;

if (_generatedUuids.Contains(iidName))
if (_generatedUuids.Contains(iidName) || _config.ExcludedNames.Contains(iidName))
{
continue;
}
Expand Down Expand Up @@ -355,6 +365,121 @@ public void GenerateBindings(TranslationUnit translationUnit, string filePath, s
{
Visit(translationUnit.TranslationUnitDecl);
}

if (_config.LogPotentialTypedefRemappings)
{
foreach (var kvp in _validNameRemappings)
{
var name = kvp.Key;
var remappings = kvp.Value;

if (!_config.RemappedNames.TryGetValue(name, out var remappedName))
{
AddDiagnostic(DiagnosticLevel.Info, $"Potential missing remapping '{name}'. {GetFoundRemappingString(name, remappings)}");
}
else if (!remappings.Contains(remappedName) && (name != remappedName) && !_config.ForceRemappedNames.Contains(name))
{
AddDiagnostic(DiagnosticLevel.Info, $"Potential invalid remapping '{name}={remappedName}'. {GetFoundRemappingString(name, remappings)}");
}
}

foreach (var name in _usedRemappings)
{
var remappedName = _config.RemappedNames[name];

if (!_validNameRemappings.ContainsKey(name) && (name != remappedName) && !_config.ForceRemappedNames.Contains(name))
{
AddDiagnostic(DiagnosticLevel.Info, $"Potential invalid remapping '{name}={remappedName}'. No remappings were found.");
}
}

static string GetFoundRemappingString(string name, HashSet<string> remappings)
{
var recommendedRemapping = "";

if (remappings.Count == 1)
{
recommendedRemapping = remappings.Single();
}

if ((recommendedRemapping == "") && name.StartsWith("_"))
{
var remapping = name[1..];

if (remappings.Contains(remapping))
{
recommendedRemapping = remapping;
}
}

if ((recommendedRemapping == "") && name.StartsWith("tag"))
{
var remapping = name[3..];

if (remappings.Contains(remapping))
{
recommendedRemapping = remapping;
}
}

if ((recommendedRemapping == "") && name.EndsWith("_"))
{
var remapping = name[0..^1];

if (remappings.Contains(remapping))
{
recommendedRemapping = remapping;
}
}

if ((recommendedRemapping == "") && name.EndsWith("tag"))
{
var remapping = name[0..^3];

if (remappings.Contains(remapping))
{
recommendedRemapping = remapping;
}
}

if (recommendedRemapping == "")
{
var remapping = name.ToUpperInvariant();

if (remappings.Contains(remapping))
{
recommendedRemapping = remapping;
}
}

var result = "";
var remainingRemappings = (IEnumerable<string>)remappings;
var remainingString = "Found";

if (recommendedRemapping != "")
{
result += $"Recommended remapping: '{name}={recommendedRemapping}'.";

if (remappings.Count == 1)
{
remainingRemappings = Array.Empty<string>();
}
else
{
result += ' ';
remainingRemappings = remappings.Except(new string[] { recommendedRemapping });
remainingString = "Other";
}
}

if (remainingRemappings.Any())
{
result += $"{remainingString} typedefs: {string.Join("; ", remainingRemappings)}";
}

return result;
}
}
}
catch (Exception e)
{
Expand Down Expand Up @@ -1336,20 +1461,29 @@ private string GetRemappedName(string name, Cursor cursor, bool tryRemapOperator
if (_config.RemappedNames.TryGetValue(name, out var remappedName))
{
wasRemapped = true;
_ = _usedRemappings.Add(name);
return AddUsingDirectiveIfNeeded(_outputBuilder, remappedName, skipUsing);
}

if (name.StartsWith("const ") && _config.RemappedNames.TryGetValue(name[6..], out remappedName))
if (name.StartsWith("const "))
{
wasRemapped = true;
return AddUsingDirectiveIfNeeded(_outputBuilder, remappedName, skipUsing);
var tmpName = name[6..];

if (_config.RemappedNames.TryGetValue(tmpName, out remappedName))
{

wasRemapped = true;
_ = _usedRemappings.Add(tmpName);
return AddUsingDirectiveIfNeeded(_outputBuilder, remappedName, skipUsing);
}
}

remappedName = name;

if ((cursor is FunctionDecl functionDecl) && tryRemapOperatorName && TryRemapOperatorName(ref remappedName, functionDecl))
{
wasRemapped = true;
// We don't track remapped operators in _usedRemappings
return AddUsingDirectiveIfNeeded(_outputBuilder, remappedName, skipUsing);
}

Expand Down Expand Up @@ -2607,6 +2741,17 @@ bool IsExcludedByName(Cursor cursor, out bool isExcludedByConflictingDefinition)
{
return false;
}

if (qualifiedName.Contains("ClangSharpMacro_"))
{
qualifiedName = qualifiedName.Replace("ClangSharpMacro_", "");
}

if (name.Contains("ClangSharpMacro_"))
{
name = name.Replace("ClangSharpMacro_", "");
}

if (cursor is RecordDecl recordDecl)
{
if (_config.ExcludeEmptyRecords && IsEmptyRecord(recordDecl))
Expand Down
Loading