Skip to content

Fix generate-macro-bindings generation #440

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

Merged
merged 6 commits into from
Apr 10, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ private unsafe void VisitMacroDefinitionRecord(MacroDefinitionRecord macroDefini
var macroName = $"ClangSharpMacro_{macroDefinitionRecord.Spelling}";

_ = _fileContentsBuilder.Append('\n');
_ = _fileContentsBuilder.Append($"const auto {macroName} = ");
_ = _fileContentsBuilder.Append($"const {_placeholderMacroType} {macroName} = ");

var sourceRangeEnd = tokens[^1].GetExtent(translationUnitHandle).End;
var sourceRangeStart = tokens[1].GetLocation(translationUnitHandle);
Expand Down
57 changes: 54 additions & 3 deletions sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,13 @@ public sealed partial class PInvokeGenerator : IDisposable
private readonly Dictionary<string, List<string>> _topLevelClassAttributes;
private readonly HashSet<string> _topLevelClassNames;
private readonly HashSet<string> _usedRemappings;
private readonly string _placeholderMacroType;

private string _filePath;
private string[] _clangCommandLineArgs;
private CXTranslationUnit_Flags _translationFlags;
private string? _currentClass;
private string? _currentNamespace;

private IOutputBuilder? _outputBuilder;
private CSharpOutputBuilder? _testOutputBuilder;
private CSharpOutputBuilder? _stmtOutputBuilder;
Expand Down Expand Up @@ -135,6 +135,7 @@ public PInvokeGenerator(PInvokeGeneratorConfiguration config, Func<string, Strea
_usedRemappings = new HashSet<string>();
_filePath = "";
_clangCommandLineArgs = Array.Empty<string>();
_placeholderMacroType = GetPlaceholderMacroType();
}

~PInvokeGenerator()
Expand Down Expand Up @@ -6095,7 +6096,7 @@ private void WithAttributes(NamedDecl namedDecl, bool onlySupportedOSPlatform =
if (IsType<TypedefType>(fieldDecl, out var typedefType))
{
declAttrs = declAttrs.Concat(typedefType.Decl.Attrs);
}
}
}
else if (namedDecl is RecordDecl recordDecl)
{
Expand Down Expand Up @@ -6532,4 +6533,54 @@ private void StopCSharpCode()
}
}
}
}

private string GetPlaceholderMacroType()
{
const string Cxx11AutoType = "auto";
const string GnuAutoType = "__auto_type";

if (_config.Language is "c++")
{
if (string.IsNullOrEmpty(_config.LanguageStandard))
{
return Cxx11AutoType; // Nowadays, the default standard within clang will always be above c++11
}

var cxxStandard = ParseCxxStandard(_config.LanguageStandard);
return (cxxStandard is not -1 and not 98 and >= 11) ? Cxx11AutoType : GnuAutoType;
}
else
{
return GnuAutoType;
}
}

private static int ParseCxxStandard(string standard)
{
const string CxxStandard = "c++";
const string GnuxxStandard = "gnu++";

if (standard.StartsWith(CxxStandard))
{
return ParseCxxStandardVersion(standard.AsSpan()[CxxStandard.Length..]);
}

if (standard.StartsWith(GnuxxStandard))
{
return ParseCxxStandardVersion(standard.AsSpan()[GnuxxStandard.Length..]);
}

return -1;
}

private static int ParseCxxStandardVersion(ReadOnlySpan<char> version)
{
// Maybe in the future we'll need to check for more c++ standard drafts, but atm this should work
if(version.EndsWith("a") || version.EndsWith("b"))
{
return int.TryParse(version[..^1], out var draftStd) ? draftStd * 10 : -1;
}

return int.TryParse(version, out var std) ? std : -1;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ public sealed class PInvokeGeneratorConfiguration
private const string DefaultMethodPrefixToStripValue = "";
private const string DefaultTestOutputLocationValue = "";

private readonly string _language;
private readonly string _languageStandard;

private readonly string _defaultNamespace;
private readonly string _headerText;
private readonly string _libraryPath;
Expand Down Expand Up @@ -49,8 +52,11 @@ public sealed class PInvokeGeneratorConfiguration

private PInvokeGeneratorConfigurationOptions _options;

public PInvokeGeneratorConfiguration(string defaultNamespace, string outputLocation, string? headerFile, PInvokeGeneratorOutputMode outputMode, PInvokeGeneratorConfigurationOptions options)
public PInvokeGeneratorConfiguration(string language, string languageStandard, string defaultNamespace, string outputLocation, string? headerFile, PInvokeGeneratorOutputMode outputMode, PInvokeGeneratorConfigurationOptions options)
{
_language = language;
_languageStandard = languageStandard;

if (string.IsNullOrWhiteSpace(defaultNamespace))
{
throw new ArgumentNullException(nameof(defaultNamespace));
Expand Down Expand Up @@ -321,6 +327,10 @@ public IReadOnlyCollection<string> NativeTypeNamesToStrip

public string OutputLocation => _outputLocation;

public string Language => _language;

public string LanguageStandard => _languageStandard;

[AllowNull]
public IReadOnlyDictionary<string, string> RemappedNames
{
Expand Down
4 changes: 2 additions & 2 deletions sources/ClangSharpPInvokeGenerator/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -691,7 +691,7 @@ public static void Run(InvocationContext context)
translationFlags |= CXTranslationUnit_IncludeAttributedTypes; // Include attributed types in CXType
translationFlags |= CXTranslationUnit_VisitImplicitAttributes; // Implicit attributes should be visited

var config = new PInvokeGeneratorConfiguration(namespaceName, outputLocation, headerFile, outputMode, configOptions) {
var config = new PInvokeGeneratorConfiguration(language, std, namespaceName, outputLocation, headerFile, outputMode, configOptions) {
DefaultClass = methodClassName,
ExcludedNames = excludedNames,
IncludedNames = includedNames,
Expand Down Expand Up @@ -1062,7 +1062,7 @@ private static Option<string> GetLanguageOption()
aliases: new string[] { "--language", "-x" },
description: "Treat subsequent input files as having type <language>.",
getDefaultValue: () => "c++"
);
).FromAmong("c", "c++");
}

private static Option<string> GetLibraryOption()
Expand Down
28 changes: 25 additions & 3 deletions tests/ClangSharp.PInvokeGenerator.UnitTests/CTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public partial struct MyStruct
";
}

return ValidateGeneratedCSharpLatestWindowsBindingsAsync(inputContents, expectedOutputContents, commandlineArgs: DefaultCClangCommandLineArgs);
return ValidateGeneratedCSharpLatestWindowsBindingsAsync(inputContents, expectedOutputContents, commandlineArgs: DefaultCClangCommandLineArgs, language: "c", languageStandard: DefaultCStandard);
}

[Test]
Expand Down Expand Up @@ -97,7 +97,7 @@ public unsafe partial struct _MyOtherStruct
}
}
";
return ValidateGeneratedCSharpLatestWindowsBindingsAsync(inputContents, expectedOutputContents, commandlineArgs: DefaultCClangCommandLineArgs);
return ValidateGeneratedCSharpLatestWindowsBindingsAsync(inputContents, expectedOutputContents, commandlineArgs: DefaultCClangCommandLineArgs, language: "c", languageStandard: DefaultCStandard);
}

[Test]
Expand Down Expand Up @@ -138,6 +138,28 @@ public unsafe partial struct _MyOtherUnion
}
}
";
return ValidateGeneratedCSharpLatestWindowsBindingsAsync(inputContents, expectedOutputContents, commandlineArgs: DefaultCClangCommandLineArgs);
return ValidateGeneratedCSharpLatestWindowsBindingsAsync(inputContents, expectedOutputContents, commandlineArgs: DefaultCClangCommandLineArgs, language: "c", languageStandard: DefaultCStandard);
}

[Test]
public Task MacroTest()
{
var inputContents = @"#define MyMacro1 5
#define MyMacro2 MyMacro1";

var expectedOutputContents = @"namespace ClangSharp.Test
{
public static partial class Methods
{
[NativeTypeName(""#define MyMacro1 5"")]
public const int MyMacro1 = 5;

[NativeTypeName(""#define MyMacro2 MyMacro1"")]
public const int MyMacro2 = 5;
}
}
";

return ValidateGeneratedCSharpLatestWindowsBindingsAsync(inputContents, expectedOutputContents, commandlineArgs: DefaultCClangCommandLineArgs, language: "c", languageStandard: DefaultCStandard);
}
}
Loading