From 8a2760301f0033d763c17359224513d7710fad08 Mon Sep 17 00:00:00 2001 From: smaillet <25911635+smaillet@users.noreply.github.com> Date: Sun, 4 May 2025 12:28:12 -0700 Subject: [PATCH 01/18] Removed legacy bindings generator not longer part of this repo --- .../Configuration/IGeneratorConfig.cs | 23 - .../Configuration/Yaml/IHandleInfo.cs | 14 - .../Configuration/Yaml/IncludeRef.cs | 18 - .../Configuration/Yaml/ReadOnlyConfig.cs | 32 -- .../Configuration/Yaml/YamlConfiguration.cs | 110 ---- .../Configuration/Yaml/YamlContextHandle.cs | 26 - .../Configuration/Yaml/YamlGlobalHandle.cs | 32 -- .../Yaml/YamlLocationNodeDeserializer.cs | 62 --- .../ASTContextExtensions.cs | 156 ------ .../CppSharpExtensions/Driver.cs | 341 ------------- .../ErrorTrackingDiagnostics.cs | 68 --- .../CppSharpExtensions/FieldExtensions.cs | 18 - .../CppSharpExtensions/ICodeGenTemplate.cs | 25 - .../CppSharpExtensions/ICodeGenerator.cs | 21 - .../ICodeGeneratorTemplateFactory.cs | 18 - .../CppSharpExtensions/IDriver.cs | 33 -- .../CppSharpExtensions/ILibrary.cs | 25 - .../CppSharpExtensions/ITypePrinter2.cs | 22 - .../CppSharpExtensions/NativeTypePrinter.cs | 188 ------- .../CppSharpExtensions/TargetedAttribute.cs | 58 --- .../GlobalSuppressions.cs | 14 - .../LibLLVMTypePrinter.cs | 95 ---- .../LibLlvmGeneratorLibrary.cs | 107 ---- .../LibLlvmTemplateFactory.cs | 80 --- .../LlvmBindingsGenerator.csproj | 71 --- .../LlvmBindingsGenerator.sln | 42 -- src/Interop/LlvmBindingsGenerator/Options.cs | 40 -- .../Passes/IgnoreDuplicateNamesPass.cs | 47 -- .../Passes/IgnoreSystemHeadersPass.cs | 59 --- .../Passes/MarkFunctionsInternalPass.cs | 36 -- .../Passes/ValidateExtensionNamingPass.cs | 77 --- src/Interop/LlvmBindingsGenerator/Program.cs | 81 --- .../Properties/AssemblyInfo.cs | 40 -- .../TemplateCodeGenerator.cs | 44 -- .../Templates/AssemblyExtensions.cs | 20 - .../Templates/ContextHandleTemplate.cs | 27 - .../Templates/ExportsTemplate.cs | 55 -- .../Templates/GlobalHandleTemplate.cs | 33 -- .../Templates/T4/ContextHandleTemplate.cs | 422 ---------------- .../Templates/T4/ContextHandleTemplate.tt | 63 --- .../Templates/T4/ExportsTemplate.cs | 400 --------------- .../Templates/T4/ExportsTemplate.tt | 33 -- .../Templates/T4/GlobalHandleTemplate.cs | 474 ------------------ .../Templates/T4/GlobalHandleTemplate.tt | 73 --- .../LlvmBindingsGenerator/Templates/readme.md | 150 ------ .../LlvmBindingsGenerator/bindingsConfig.yml | 81 --- 46 files changed, 3954 deletions(-) delete mode 100644 src/Interop/LlvmBindingsGenerator/Configuration/IGeneratorConfig.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/Configuration/Yaml/IHandleInfo.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/Configuration/Yaml/IncludeRef.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/Configuration/Yaml/ReadOnlyConfig.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/Configuration/Yaml/YamlConfiguration.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/Configuration/Yaml/YamlContextHandle.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/Configuration/Yaml/YamlGlobalHandle.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/Configuration/Yaml/YamlLocationNodeDeserializer.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ASTContextExtensions.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/CppSharpExtensions/Driver.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ErrorTrackingDiagnostics.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/CppSharpExtensions/FieldExtensions.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ICodeGenTemplate.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ICodeGenerator.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ICodeGeneratorTemplateFactory.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/CppSharpExtensions/IDriver.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ILibrary.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ITypePrinter2.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/CppSharpExtensions/NativeTypePrinter.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/CppSharpExtensions/TargetedAttribute.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/GlobalSuppressions.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/LibLLVMTypePrinter.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/LibLlvmGeneratorLibrary.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/LibLlvmTemplateFactory.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/LlvmBindingsGenerator.csproj delete mode 100644 src/Interop/LlvmBindingsGenerator/LlvmBindingsGenerator.sln delete mode 100644 src/Interop/LlvmBindingsGenerator/Options.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/Passes/IgnoreDuplicateNamesPass.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/Passes/IgnoreSystemHeadersPass.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/Passes/MarkFunctionsInternalPass.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/Passes/ValidateExtensionNamingPass.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/Program.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/Properties/AssemblyInfo.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/TemplateCodeGenerator.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/Templates/AssemblyExtensions.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/Templates/ContextHandleTemplate.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/Templates/ExportsTemplate.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/Templates/GlobalHandleTemplate.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/Templates/T4/ContextHandleTemplate.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/Templates/T4/ContextHandleTemplate.tt delete mode 100644 src/Interop/LlvmBindingsGenerator/Templates/T4/ExportsTemplate.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/Templates/T4/ExportsTemplate.tt delete mode 100644 src/Interop/LlvmBindingsGenerator/Templates/T4/GlobalHandleTemplate.cs delete mode 100644 src/Interop/LlvmBindingsGenerator/Templates/T4/GlobalHandleTemplate.tt delete mode 100644 src/Interop/LlvmBindingsGenerator/Templates/readme.md delete mode 100644 src/Interop/LlvmBindingsGenerator/bindingsConfig.yml diff --git a/src/Interop/LlvmBindingsGenerator/Configuration/IGeneratorConfig.cs b/src/Interop/LlvmBindingsGenerator/Configuration/IGeneratorConfig.cs deleted file mode 100644 index 9b206eace4..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Configuration/IGeneratorConfig.cs +++ /dev/null @@ -1,23 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Linq; - -using LlvmBindingsGenerator.Templates; - -namespace LlvmBindingsGenerator.Configuration -{ - internal interface IGeneratorConfig - { - ImmutableArray IgnoredHeaders { get; } - - IEnumerable HandleMap { get; } - - ILookup BuildTemplateMap( ); - } -} diff --git a/src/Interop/LlvmBindingsGenerator/Configuration/Yaml/IHandleInfo.cs b/src/Interop/LlvmBindingsGenerator/Configuration/Yaml/IHandleInfo.cs deleted file mode 100644 index 68e6a7459e..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Configuration/Yaml/IHandleInfo.cs +++ /dev/null @@ -1,14 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -namespace LlvmBindingsGenerator.Configuration -{ - internal interface IHandleInfo - : IYamlNodeLocation - { - string HandleName { get; } - } -} diff --git a/src/Interop/LlvmBindingsGenerator/Configuration/Yaml/IncludeRef.cs b/src/Interop/LlvmBindingsGenerator/Configuration/Yaml/IncludeRef.cs deleted file mode 100644 index cc6a12be25..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Configuration/Yaml/IncludeRef.cs +++ /dev/null @@ -1,18 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using YamlDotNet.Core; - -namespace LlvmBindingsGenerator.Configuration -{ - internal class IncludeRef - : IYamlNodeLocation - { - public string Path { get; set; } = string.Empty; - - public Mark Start { get; set; } - } -} diff --git a/src/Interop/LlvmBindingsGenerator/Configuration/Yaml/ReadOnlyConfig.cs b/src/Interop/LlvmBindingsGenerator/Configuration/Yaml/ReadOnlyConfig.cs deleted file mode 100644 index aeee8fcd80..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Configuration/Yaml/ReadOnlyConfig.cs +++ /dev/null @@ -1,32 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Linq; - -using LlvmBindingsGenerator.Templates; - -namespace LlvmBindingsGenerator.Configuration.Yaml -{ - internal class ReadOnlyConfig - : IGeneratorConfig - { - public ReadOnlyConfig( YamlConfiguration config ) - { - YamlConfig = config; - } - - public ImmutableArray IgnoredHeaders - => [ .. YamlConfig.IgnoredHeaders ]; - - public IEnumerable HandleMap => YamlConfig.HandleMap; - - public ILookup BuildTemplateMap( ) => YamlConfig.BuildTemplateMap( ); - - private readonly YamlConfiguration YamlConfig; - } -} diff --git a/src/Interop/LlvmBindingsGenerator/Configuration/Yaml/YamlConfiguration.cs b/src/Interop/LlvmBindingsGenerator/Configuration/Yaml/YamlConfiguration.cs deleted file mode 100644 index 2240ef054e..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Configuration/Yaml/YamlConfiguration.cs +++ /dev/null @@ -1,110 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.IO; -using System.Linq; - -using LlvmBindingsGenerator.Templates; - -using YamlDotNet.Core; -using YamlDotNet.Core.Events; -using YamlDotNet.Serialization; -using YamlDotNet.Serialization.NamingConventions; -using YamlDotNet.Serialization.NodeDeserializers; - -namespace LlvmBindingsGenerator.Configuration -{ - [SuppressMessage( "Performance", "CA1812:Avoid uninstantiated internal classes", Justification = "Instantiated via de-serialization" )] - [SuppressMessage( "CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "It is necessary, tooling can't agree on the point. (removing it generates a warning)" )] - internal class YamlConfiguration - { - public List IgnoredHeaders { get; set; } = new List(); - - public List HandleMap { get; set; } = new List(); - - public static YamlConfiguration ParseFrom( string path ) - { - using var input = File.OpenText( path ); - var deserializer = new DeserializerBuilder( ) - .WithNodeDeserializer( inner => new YamlLocationNodeDeserializer(inner) - , s => s.InsteadOf() - ) - .WithTypeConverter( new IncludeRefConverter()) - .WithNamingConvention( PascalCaseNamingConvention.Instance ) - .WithTagMapping("!ContextHandle", typeof(YamlContextHandle)) - .WithTagMapping("!GlobalHandle", typeof(YamlGlobalHandle)) - .Build( ); - - return deserializer.Deserialize( input ); - } - - public ILookup BuildTemplateMap() - { - // get all the templates to use for generating the output code - var handleTemplates = from h in HandleMap - from template in Transforms( h ) - select (h.HandleName, template); - return handleTemplates.ToLookup((p)=>p.HandleName, (p)=>p.template); - } - - private static IEnumerable Transforms( IHandleInfo h ) - { - switch(h) - { - case YamlGlobalHandle ygh: - yield return new GlobalHandleTemplate( ygh.HandleName, ygh.Disposer, ygh.Alias ); - - // for aliases treat them like a context handle as they are - // not owned by the managed code and only reference the native - // handle via a simple nint. Context Handle template creates - // a type safe wrapper around the raw 'nint' (as a value type) that - // does NOT implement IDisposable. (Unlike a SafeHandle) - if(ygh.Alias) - { - yield return new ContextHandleTemplate( $"{ygh.HandleName}Alias" ); - } - - break; - - case YamlContextHandle ych: - yield return new ContextHandleTemplate( ych.HandleName ); - break; - - default: - throw new InvalidOperationException( "Unknown handle info kind encountered" ); - } - } - - // special converter to ensure runtime platform normalized paths for any include paths in the file - private class IncludeRefConverter - : IYamlTypeConverter - { - public bool Accepts( Type type ) - { - return type == typeof( IncludeRef ); - } - - public object ReadYaml( IParser parser, Type type, ObjectDeserializer rootDeserializer) - { - var scalarEvent = parser.Consume(); - return new IncludeRef() { Path = NormalizePathSep( scalarEvent.Value ), Start = scalarEvent.Start }; - } - - public void WriteYaml( IEmitter emitter, object? value, Type type, ObjectSerializer serializer ) - { - throw new NotSupportedException(); - } - - internal static string NormalizePathSep( string path ) - { - return path.Replace( Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar ); - } - } - } -} diff --git a/src/Interop/LlvmBindingsGenerator/Configuration/Yaml/YamlContextHandle.cs b/src/Interop/LlvmBindingsGenerator/Configuration/Yaml/YamlContextHandle.cs deleted file mode 100644 index 548dc9f76d..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Configuration/Yaml/YamlContextHandle.cs +++ /dev/null @@ -1,26 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; - -using YamlDotNet.Core; -using YamlDotNet.Serialization; - -namespace LlvmBindingsGenerator.Configuration -{ - [SuppressMessage( "Performance", "CA1812:Avoid uninstantiated internal classes", Justification = "Instantiated via de-serialization" )] - [DebuggerDisplay( "ContextHandle({HandleName})" )] - internal class YamlContextHandle - : IYamlNodeLocation - , IHandleInfo - { - public string HandleName { get; set; } = string.Empty; - - [YamlIgnore] - public Mark Start { get; set; } - } -} diff --git a/src/Interop/LlvmBindingsGenerator/Configuration/Yaml/YamlGlobalHandle.cs b/src/Interop/LlvmBindingsGenerator/Configuration/Yaml/YamlGlobalHandle.cs deleted file mode 100644 index 9b0a7db09c..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Configuration/Yaml/YamlGlobalHandle.cs +++ /dev/null @@ -1,32 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; - -using YamlDotNet.Core; -using YamlDotNet.Serialization; - -#pragma warning disable IDE0130 // Namespace does not match folder structure -namespace LlvmBindingsGenerator.Configuration -{ - [SuppressMessage( "Performance", "CA1812:Avoid uninstantiated internal classes", Justification = "Instantiated via de-serialization" )] - [SuppressMessage( "CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "Tooling is not acapable of seeing the need for this" )] - [DebuggerDisplay( "GlobalHandle({HandleName},{Disposer}, Alias:{Alias})" )] - internal class YamlGlobalHandle - : IYamlNodeLocation - , IHandleInfo - { - public string HandleName { get; set; } = string.Empty; - - public string Disposer { get; set; } = string.Empty; - - public bool Alias { get; set; } - - [YamlIgnore] - public Mark Start { get; set; } - } -} diff --git a/src/Interop/LlvmBindingsGenerator/Configuration/Yaml/YamlLocationNodeDeserializer.cs b/src/Interop/LlvmBindingsGenerator/Configuration/Yaml/YamlLocationNodeDeserializer.cs deleted file mode 100644 index ef6feb8f7c..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Configuration/Yaml/YamlLocationNodeDeserializer.cs +++ /dev/null @@ -1,62 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System; -using System.Diagnostics.CodeAnalysis; - -using YamlDotNet.Core; -using YamlDotNet.Serialization; - -namespace LlvmBindingsGenerator.Configuration -{ - [SuppressMessage( "StyleCop.CSharp.DocumentationRules", "SA1649:File name should match first type name", Justification = "Interface and class to detect it are a matched pair" )] - [SuppressMessage( "CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "IDE/Tooling is confused, it is needed" )] - internal interface IYamlNodeLocation - { - Mark Start { get; set; } - } - - // Wrapper for standard object deserializer that tests for IYamlConfigLocation to add location inforamtion - // to the deserialized nodes. This allows far better error reporting etc.. when performing a semantic pass - // on the data. Unfortunately, the owner of YamlDotNet is presently unwilling to consider such a thing in - // a general manner as part of the library (see: https://github.com/aaubry/YamlDotNet/issues/494). - internal class YamlLocationNodeDeserializer - : INodeDeserializer - { - public YamlLocationNodeDeserializer(INodeDeserializer inner) - { - Inner = inner; - } - - public bool Deserialize( - IParser reader, - Type expectedType, - Func nestedObjectDeserializer, - out object? value, - ObjectDeserializer rootDeserializer - ) - { - value = null; - if (reader.Current is not null) - { - var start = reader.Current.Start; - if(Inner.Deserialize( reader, expectedType, nestedObjectDeserializer, out value, rootDeserializer )) - { - if(value is IYamlNodeLocation node) - { - node.Start = start; - } - - return true; - } - } - - return false; - } - - private readonly INodeDeserializer Inner; - } -} diff --git a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ASTContextExtensions.cs b/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ASTContextExtensions.cs deleted file mode 100644 index e16cb4d269..0000000000 --- a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ASTContextExtensions.cs +++ /dev/null @@ -1,156 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Text; - -using CppSharp.AST; - -namespace LlvmBindingsGenerator -{ - internal static class ASTContextExtensions - { - public static IEnumerable GeneratedUnits( this ASTContext ctx ) - { - return from tu in ctx.TranslationUnits - where tu.IsGenerated - select tu; - } - - public static IEnumerable ValidUnits( this ASTContext ctx ) - { - return from tu in ctx.TranslationUnits - where tu.IsValid - select tu; - } - - public static bool IsCoreHeader( this TranslationUnit tu ) - { - return tu.IsValid && tu.IncludePath != null && tu.FileRelativeDirectory.StartsWith( "llvm-c", StringComparison.Ordinal ); - } - - public static bool IsExtensionHeader( this TranslationUnit tu ) - { - return !tu.IsCoreHeader() - && tu.IsValid - && !tu.IsSystemHeader - && tu.FileNameWithoutExtension.EndsWith( "Bindings", StringComparison.Ordinal ); - } - - public static IEnumerable GetHandleTypeDefs( this ASTContext ctx ) - { - return from tu in ctx.GeneratedUnits() - from td in tu.Typedefs - where td.IsHandleTypeDef() - select td; - } - - public static bool TryGetHandleDecl( this CppSharp.AST.Type astType, [MaybeNullWhen(false)] out TypedefNameDecl? decl ) - { - switch( astType ) - { - case TypedefType tdt when( tdt.Declaration.IsHandleTypeDef() ): - decl = tdt.Declaration; - return true; - - case PointerType pt when( pt.Pointee is TypedefType tdt && tdt.Declaration.IsHandleTypeDef() ): - decl = tdt.Declaration; - return true; - - default: - decl = null; - return false; - } - } - - public static bool IsOpaqueStruct( this TagType tt ) - { - return tt.Declaration is Class c && c.IsOpaque; - } - - public static bool IsHandleTypeDef( this TypedefNameDecl td ) - { - return IsCannonicalHandleTypeDef( td ) || IsOpaquHandleTypeDef( td ); - } - - public static bool IsOpaquHandleTypeDef( this TypedefNameDecl td ) - { - // bad form, declaration is the opaque struct, not a pointer to the struct - return td.Type is TagType tt2 && tt2.IsOpaqueStruct(); - } - - [SuppressMessage( "Style", "IDE0046:Convert to conditional expression", Justification = "Result is anything but simplified!" )] - public static bool IsCannonicalHandleTypeDef( this TypedefNameDecl td ) - { - // Canonical form, declaration is a pointer to an opaque struct - if( td.Type is not PointerType pt ) - { - return false; - } - - return ( pt.Pointee is TagType tt && tt.IsOpaqueStruct() ) - || ( pt.Pointee is BuiltinType bt && bt.Type == PrimitiveType.Void ); - } - - [SuppressMessage( "Globalization", "CA1308:Normalize strings to uppercase", Justification = "It's supposed to be all lowercase" )] - [SuppressMessage( "CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "It is needed, tooling is too stupid to see that..." )] - public static string AsString( this CppSharp.AST.Attribute attr, bool useFullNamespace = false ) - { - var bldr = new StringBuilder( "[" ); - if( attr is TargetedAttribute ta && ta.Target != AttributeTarget.Default ) - { - bldr.Append( ta.Target.ToString().ToLowerInvariant() ); - bldr.Append( ": " ); - } - - bldr.Append( useFullNamespace ? attr.Type.FullName : attr.Type.Name[ 0..^9 ] ); - if( !string.IsNullOrWhiteSpace( attr.Value ) ) - { - bldr.Append( "( " ); - bldr.Append( attr.Value ); - bldr.Append( " )" ); - } - - bldr.Append( ']' ); - return bldr.ToString(); - } - - public static bool IsDelegateTypeDef( this TypedefNameDecl td ) - { - return td.TryGetFunctionSignature( out _ ); - } - - public static bool TryGetFunctionSignature( this TypedefNameDecl td, [MaybeNullWhen(false)] out FunctionType? signature ) - { - signature = null; - if( td.Type is PointerType pt && pt.Pointee is FunctionType sig ) - { - signature = sig; - return true; - } - - return false; - } - - public static FunctionType? GetFunctionPointerType( this TypedefNameDecl td ) - { - return ( td.Type is PointerType pt && pt.Pointee is FunctionType ft ) ? ft : null; - } - - public static IReadOnlyDictionary GetFunctionPointers( this ASTContext context ) - { - return ( from tu in context.TranslationUnits - from td in tu.Typedefs - let ft = td.GetFunctionPointerType() - where ft != null - select (td.Name, Signature: ft) - ).ToDictionary( item => item.Name, item => item.Signature ); - } - } -} diff --git a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/Driver.cs b/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/Driver.cs deleted file mode 100644 index ea6b533777..0000000000 --- a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/Driver.cs +++ /dev/null @@ -1,341 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; - -using CppSharp; -using CppSharp.AST; -using CppSharp.Generators; -using CppSharp.Parser; -using CppSharp.Passes; -using CppSharp.Types; -using CppSharp.Utils; - -using ClangParser = CppSharp.ClangParser; - -namespace LlvmBindingsGenerator -{ - /// Provides a more flexible implementation of the general "driver" concept in CppSharp - /// - /// Notable differences: - /// 1. The driver does not setup ANY passes, it is entirely up to the library to do that - /// 2. There is no intermediate "Generator" needed - /// 3. Deals in interfaces rather than concrete types so it is more extensible - /// 4. The code generation types are interfaces with names that more accurately reflect what they do - /// - internal sealed class Driver - : IDriver - , IDisposable - { - public Driver() - : this( new DriverOptions() ) - { - } - - public Driver( DriverOptions options ) - { - Options = options; - ParserOptions = new CppSharp.Parser.ParserOptions(); - Context = new BindingContext( Options, ParserOptions ); - } - - public DriverOptions Options { get; } - - public CppSharp.Parser.ParserOptions ParserOptions { get; } - - public BindingContext Context { get; private set; } - - public void SetupTypeMaps() => - Context.TypeMaps = new TypeMapDatabase( Context ); - - public void Setup() - { - ValidateOptions(); - ParserOptions.Setup(TargetPlatform.Windows); - } - - public bool ParseCode() - { - ClangParser.SourcesParsed += OnSourceFileParsed; - - var files = Options.Modules.SelectMany( m => m.Headers ); - ParserOptions.BuildForSourceFile( Options.Modules ); - - using( CppSharp.Parser.ParserResult result = ClangParser.ParseSourceFiles( files, ParserOptions ) ) - { - Context.TargetInfo = result.TargetInfo; - } - - Context.ASTContext = ClangParser.ConvertASTContext( ParserOptions.ASTContext ); - ClangParser.SourcesParsed -= OnSourceFileParsed; - return !HasParsingErrors; - } - - public void SortModulesByDependencies() - { - var sortedModules = Options.Modules.TopologicalSort( GetAndAddDependencies ); - Options.Modules.Clear(); - Options.Modules.AddRange( sortedModules ); - } - - public bool ParseLibraries() - { - ClangParser.LibraryParsed += OnFileParsed; - foreach( Module module in Options.Modules ) - { - using var linkerOptions = new LinkerOptions(Context.LinkerOptions); - foreach( string libraryDir in module.LibraryDirs ) - { - linkerOptions.AddLibraryDirs( libraryDir ); - } - - foreach( string library in module.Libraries ) - { - if( !Context.Symbols.Libraries.Any( ( NativeLibrary l ) => l.FileName == library ) ) - { - linkerOptions.AddLibraries( library ); - } - } - - using ParserResult parserResult = ClangParser.ParseLibrary(linkerOptions); - if( parserResult.Kind == ParserResultKind.Success ) - { - for( uint num = 0u; num < parserResult.LibrariesCount; num++ ) - { -#pragma warning disable IDISP004 // Don't ignore created IDisposable - // This is "cloned" from CppSharp code and it is assumed to transfer ownership - // documentation is sadly lacking on most of this library - Context.Symbols.Libraries.Add( ClangParser.ConvertLibrary( parserResult.GetLibraries( num ) ) ); -#pragma warning restore IDISP004 // Don't ignore created IDisposable - } - } - } - - ClangParser.LibraryParsed -= OnFileParsed; - Context.Symbols.IndexSymbols(); - SortModulesByDependencies(); - return true; - } - - public void ProcessCode() - { - Context.RunPasses(); - } - - public void GenerateCode( IEnumerable generators ) - { - string outputPath = Path.GetFullPath( Options.OutputDir ); - - if( !Directory.Exists( outputPath ) ) - { - Directory.CreateDirectory( outputPath ); - } - - foreach( ICodeGenerator generator in generators.Where( o => o.IsValid ) ) - { - string generatorOutputPath = outputPath; - - if( Options.UseHeaderDirectories ) - { - generatorOutputPath = Path.Combine( generatorOutputPath, generator.FileRelativeDirectory ); - Directory.CreateDirectory( generatorOutputPath ); - } - - try - { - string templateOutputPath = generatorOutputPath; - if( !string.IsNullOrWhiteSpace( generator.Template.SubFolder ) ) - { - templateOutputPath = Path.Combine( templateOutputPath, generator.Template.SubFolder ); - Directory.CreateDirectory( templateOutputPath ); - } - - string fileName = $"{generator.FileNameWithoutExtension}.{generator.Template.FileExtension}"; - - string fullFilePath = Path.Combine( templateOutputPath, fileName ); - File.WriteAllText( fullFilePath, generator.Template.Generate() ); - - Diagnostics.Debug( "Generated '{0}'", fileName ); - } - catch( System.IO.IOException ex ) - { - Diagnostics.Error( ex.Message ); - } - } - } - - public void Dispose() - { - Context?.TargetInfo.Dispose(); - - ParserOptions.Dispose(); - CppSharp.AST.Type.TypePrinterDelegate = null; - } - - public static void Run( ILibrary library ) - { - using var driver = new Driver(); - var options = driver.Options; - library.Setup( driver ); - driver.Setup(); - - Diagnostics.Message( "Parsing libraries..." ); - if( !driver.ParseLibraries() ) - { - return; - } - - Diagnostics.Message( "Parsing code..." ); - if( !driver.ParseCode() ) - { - Diagnostics.Error( "Encountered one or more errors while parsing source code - no code generation performed." ); - return; - } - - new CleanUnitPass { Context = driver.Context }.VisitASTContext( driver.Context.ASTContext ); - options.Modules.RemoveAll( m => m != options.SystemModule && !m.Units.GetGenerated().Any() ); - - Diagnostics.Message( "Processing code..." ); - - library.SetupPasses(); - driver.SetupTypeMaps(); - - library.Preprocess( driver.Context.ASTContext ); - - if( CppSharp.AST.Type.TypePrinterDelegate is null) - { - throw new InvalidOperationException("Type.TypePrinterDelegate is null; Library must configure it to a non-null value to prevent null reference crashes"); - } - - driver.ProcessCode(); - library.Postprocess( driver.Context.ASTContext ); - - if( !options.DryRun ) - { - bool hasErrors = Diagnostics.Implementation is ErrorTrackingDiagnostics etd && etd.ErrorCount > 0; - - if( hasErrors ) - { - Diagnostics.Error( "Errors in previous stages, skipping code generation" ); - } - else - { - Diagnostics.Message( "Generating code..." ); - - var generators = library.CreateGenerators( ); - driver.GenerateCode( generators ); - } - } - } - - private IEnumerable GetAndAddDependencies( Module m ) - { - var dependencies = ( from library in Context.Symbols.Libraries - where m.Libraries.Contains( library.FileName ) - from module in Options.Modules - where library.Dependencies.Intersect( module.Libraries ).Any( ) - select module ).ToList( ); - if( m != Options.SystemModule ) - { - m.Dependencies.Add( Options.SystemModule ); - } - - m.Dependencies.AddRange( dependencies ); - return m.Dependencies; - } - - private void ValidateOptions() - { - if( !Options.Compilation.Platform.HasValue ) - { - Options.Compilation.Platform = Platform.Host; - } - - foreach( var module in Options.Modules ) - { - if( string.IsNullOrWhiteSpace( module.LibraryName ) ) - { - throw new InvalidOptionException( "One of your modules has no library name." ); - } - - module.OutputNamespace ??= module.LibraryName; - } - - if( Options.NoGenIncludeDirs != null ) - { - foreach( string incDir in Options.NoGenIncludeDirs ) - { - ParserOptions.AddIncludeDirs( incDir ); - } - } - } - - private void OnSourceFileParsed( IEnumerable files, CppSharp.Parser.ParserResult result ) - { - OnFileParsed( files, result ); - } - - private void OnFileParsed( string file, CppSharp.Parser.ParserResult result ) - { - OnFileParsed( [file], result ); - } - - private void OnFileParsed( IEnumerable files, CppSharp.Parser.ParserResult result ) - { - switch( result.Kind ) - { - case ParserResultKind.Success: - if( !Options.Quiet ) - { - Diagnostics.Debug( "Parsed '{0}'", string.Join( ", ", files ) ); - } - - break; - - case ParserResultKind.Error: - Diagnostics.Error( "Error parsing '{0}'", string.Join( ", ", files ) ); - HasParsingErrors = true; - break; - - case ParserResultKind.FileNotFound: - Diagnostics.Error( "File{0} not found: '{1}'" - , ( files.Count() > 1 ) ? "s" : string.Empty - , string.Join( ",", files ) - ); - HasParsingErrors = true; - break; - } - - for( uint i = 0; i < result.DiagnosticsCount; ++i ) - { - using ParserDiagnostic diag = result.GetDiagnostics( i ); - - if( diag.Level == ParserDiagnosticLevel.Warning && !Options.Verbose ) - { - continue; - } - - if( diag.Level == ParserDiagnosticLevel.Note ) - { - continue; - } - - Diagnostics.Message( "{0}({1},{2}): {3}: {4}" - , diag.FileName - , diag.LineNumber - , diag.ColumnNumber - , diag.Level.ToString().ToUpperInvariant() - , diag.Message - ); - } - } - - private bool HasParsingErrors; - } -} diff --git a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ErrorTrackingDiagnostics.cs b/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ErrorTrackingDiagnostics.cs deleted file mode 100644 index ef52928bf7..0000000000 --- a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ErrorTrackingDiagnostics.cs +++ /dev/null @@ -1,68 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System; - -using CppSharp; - -namespace LlvmBindingsGenerator -{ - internal class ErrorTrackingDiagnostics - : IDiagnostics - { - public int ErrorCount { get; private set; } - - public DiagnosticKind Level - { - get => InnerDiagnostics.Level; - set => InnerDiagnostics.Level = value; - } - - public void Emit( DiagnosticInfo info ) - { - try - { - switch( info.Kind ) - { - case DiagnosticKind.Debug: - Console.ForegroundColor = ConsoleColor.Cyan; - break; - - case DiagnosticKind.Message: - Console.ForegroundColor = ConsoleColor.White; - break; - - case DiagnosticKind.Warning: - Console.ForegroundColor = ConsoleColor.Yellow; - break; - - case DiagnosticKind.Error: - Console.ForegroundColor = ConsoleColor.Red; - ++ErrorCount; - break; - } - - InnerDiagnostics.Emit( info ); - } - finally - { - Console.ResetColor( ); - } - } - - public void PopIndent( ) - { - InnerDiagnostics.PopIndent( ); - } - - public void PushIndent( int level = 4 ) - { - InnerDiagnostics.PushIndent( level ); - } - - private readonly IDiagnostics InnerDiagnostics = new ConsoleDiagnostics(); - } -} diff --git a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/FieldExtensions.cs b/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/FieldExtensions.cs deleted file mode 100644 index 5954005405..0000000000 --- a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/FieldExtensions.cs +++ /dev/null @@ -1,18 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using CppSharp.AST; - -namespace LlvmBindingsGenerator -{ - internal static class FieldExtensions - { - public static bool IsInlinedArray(this Field f) - { - return f.Type is ArrayType at && at.SizeType == ArrayType.ArraySize.Constant; - } - } -} diff --git a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ICodeGenTemplate.cs b/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ICodeGenTemplate.cs deleted file mode 100644 index da530e4c5a..0000000000 --- a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ICodeGenTemplate.cs +++ /dev/null @@ -1,25 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -namespace LlvmBindingsGenerator.Templates -{ - internal interface ICodeGenTemplate - { - string ToolVersion { get; } - - string FileExtension { get; } - - string SubFolder { get; } - - string Generate( ); - } - - internal interface IHandleCodeTemplate - : ICodeGenTemplate - { - string HandleName { get; } - } -} diff --git a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ICodeGenerator.cs b/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ICodeGenerator.cs deleted file mode 100644 index 9f3f44a9d1..0000000000 --- a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ICodeGenerator.cs +++ /dev/null @@ -1,21 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using LlvmBindingsGenerator.Templates; - -namespace LlvmBindingsGenerator -{ - internal interface ICodeGenerator - { - bool IsValid { get; } - - string FileNameWithoutExtension { get; } - - string FileRelativeDirectory { get; } - - ICodeGenTemplate Template { get; } - } -} diff --git a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ICodeGeneratorTemplateFactory.cs b/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ICodeGeneratorTemplateFactory.cs deleted file mode 100644 index b73eed56fe..0000000000 --- a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ICodeGeneratorTemplateFactory.cs +++ /dev/null @@ -1,18 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System.Collections.Generic; -using CppSharp.Generators; - -namespace LlvmBindingsGenerator -{ - internal interface ICodeGeneratorTemplateFactory - { - IEnumerable CreateTemplates( BindingContext bindingContext ); - - void SetupPasses( BindingContext bindingContext ); - } -} diff --git a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/IDriver.cs b/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/IDriver.cs deleted file mode 100644 index 81570f8833..0000000000 --- a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/IDriver.cs +++ /dev/null @@ -1,33 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System; - -using CppSharp; -using CppSharp.Generators; -using CppSharp.Parser; -using CppSharp.Passes; - -namespace LlvmBindingsGenerator -{ - internal interface IDriver - : IDisposable - { - DriverOptions Options { get; } - - ParserOptions ParserOptions { get; } - - BindingContext Context { get; } - } - - internal static class DriverExtensions - { - public static void AddTranslationUnitPass( this IDriver driver, TranslationUnitPass pass ) - { - driver.Context.TranslationUnitPasses.AddPass( pass ); - } - } -} diff --git a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ILibrary.cs b/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ILibrary.cs deleted file mode 100644 index 74a391fc02..0000000000 --- a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ILibrary.cs +++ /dev/null @@ -1,25 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System.Collections.Generic; - -using CppSharp.AST; - -namespace LlvmBindingsGenerator -{ - internal interface ILibrary - { - void Preprocess( ASTContext ctx ); - - void Postprocess( ASTContext ctx ); - - void Setup( IDriver driver ); - - void SetupPasses( ); - - IEnumerable CreateGenerators( ); - } -} diff --git a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ITypePrinter2.cs b/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ITypePrinter2.cs deleted file mode 100644 index 890fb115dc..0000000000 --- a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/ITypePrinter2.cs +++ /dev/null @@ -1,22 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using CppSharp.AST; - -namespace LlvmBindingsGenerator -{ - internal enum TypeNameKind - { - Native, - Managed, - } - - internal interface ITypePrinter2 - : ITypePrinter - { - string GetName( CppSharp.AST.Type t, TypeNameKind kind = TypeNameKind.Native ); - } -} diff --git a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/NativeTypePrinter.cs b/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/NativeTypePrinter.cs deleted file mode 100644 index 0f89d92b16..0000000000 --- a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/NativeTypePrinter.cs +++ /dev/null @@ -1,188 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text; - -using CppSharp.AST; - -namespace LlvmBindingsGenerator -{ - internal class NativeTypePrinter - : ITypePrinter - , ITypeVisitor - { - public string ToString( CppSharp.AST.Type type ) - { - return type.Visit( this ); - } - - [SuppressMessage( "Style", "IDE0046:Convert to conditional expression", Justification = "More complicated that way" )] - public string VisitArrayType( ArrayType array, TypeQualifiers quals ) - { - if( array.SizeType is ArrayType.ArraySize.Constant or ArrayType.ArraySize.Incomplete ) - { - return array.Size == 0 ? $"{array.Type}*" : $"{array.QualifiedType}[{array.Size}]"; - } - - throw new NotSupportedException( ); - } - - public string VisitAttributedType( AttributedType attributed, TypeQualifiers quals ) - { - throw new NotSupportedException( ); - } - - public string VisitBuiltinType( BuiltinType builtin, TypeQualifiers quals ) - { - return VisitPrimitiveType(builtin.Type, quals); - } - - public string VisitCILType( CILType type, TypeQualifiers quals ) - { - return type.Type.ToString(); - } - - public string VisitDecayedType( DecayedType decayed, TypeQualifiers quals ) - { - return decayed.Decayed.Visit(this); - } - - public string VisitDeclaration( Declaration decl, TypeQualifiers quals ) - { - return decl.QualifiedOriginalName; - } - - public string VisitDependentNameType( DependentNameType dependent, TypeQualifiers quals ) - { - throw new NotSupportedException( ); - } - - public string VisitDependentTemplateSpecializationType( DependentTemplateSpecializationType template, TypeQualifiers quals ) - { - throw new NotSupportedException( ); - } - - public string VisitFunctionType( FunctionType function, TypeQualifiers quals ) - { - throw new NotSupportedException( ); - } - - public string VisitInjectedClassNameType( InjectedClassNameType injected, TypeQualifiers quals ) - { - throw new NotSupportedException( ); - } - - public string VisitMemberPointerType( MemberPointerType member, TypeQualifiers quals ) - { - throw new NotSupportedException( ); - } - - public string VisitPackExpansionType( PackExpansionType packExpansionType, TypeQualifiers quals ) - { - throw new NotSupportedException( ); - } - - public string VisitPointerType( PointerType pointer, TypeQualifiers quals ) - { - return $"{pointer.QualifiedPointee.Visit(this)}*"; - } - - public string VisitPrimitiveType( PrimitiveType type, TypeQualifiers quals ) - { - return type switch - { - PrimitiveType.Bool => "bool", - PrimitiveType.Char => "char", - PrimitiveType.Double => "double", - PrimitiveType.Float => "float", - PrimitiveType.Int => "int", - PrimitiveType.IntPtr => "intptr_t", - PrimitiveType.Long => "long", - PrimitiveType.LongLong => "long long", - PrimitiveType.Short => "short", - PrimitiveType.UChar => "unsigned char", - PrimitiveType.UInt => "unsigned int", - PrimitiveType.UIntPtr => "uintptr_t", - PrimitiveType.ULong => "unsigned long", - PrimitiveType.ULongLong => "unsigned long long", - PrimitiveType.UShort => "unsigned short", - PrimitiveType.Void => "void", - PrimitiveType.WideChar => "wchar_t", - _ => throw new NotSupportedException( ), - }; - } - - public string VisitQualifiedType( QualifiedType type ) - { - StringBuilder bldr = new(); - bldr.Append(type.Type.Visit(this)); - if( type.Qualifiers.IsConst ) - { - bldr.Append("const "); - } - - if( type.Qualifiers.IsRestrict ) - { - throw new NotSupportedException("restricted types not allowed; only defined for C99, at best a non-standard extension in C++"); - } - - if(type.Qualifiers.IsVolatile) - { - bldr.Append( "volatile " ); - } - - // TODO: figure out what "mode is supposed to be and how to deal with it... - return bldr.ToString(); - } - - public string VisitTagType( TagType tag, TypeQualifiers quals ) - { - return VisitDeclaration(tag.Declaration, quals); - } - - public string VisitTemplateParameterSubstitutionType( TemplateParameterSubstitutionType param, TypeQualifiers quals ) - { - throw new NotSupportedException( ); - } - - public string VisitTemplateParameterType( TemplateParameterType param, TypeQualifiers quals ) - { - throw new NotSupportedException( ); - } - - public string VisitTemplateSpecializationType( TemplateSpecializationType template, TypeQualifiers quals ) - { - throw new NotSupportedException( ); - } - - public string VisitTypedefType( TypedefType typedef, TypeQualifiers quals ) - { - return typedef.Declaration.OriginalName; - } - - public string VisitUnaryTransformType( UnaryTransformType unaryTransformType, TypeQualifiers quals ) - { - throw new NotSupportedException( ); - } - - public string VisitUnresolvedUsingType( UnresolvedUsingType unresolvedUsingType, TypeQualifiers quals ) - { - throw new NotSupportedException( ); - } - - public string VisitUnsupportedType( UnsupportedType type, TypeQualifiers quals ) - { - throw new NotSupportedException( ); - } - - public string VisitVectorType( VectorType vectorType, TypeQualifiers quals ) - { - throw new NotSupportedException( ); - } - } -} diff --git a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/TargetedAttribute.cs b/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/TargetedAttribute.cs deleted file mode 100644 index 2dacf3b627..0000000000 --- a/src/Interop/LlvmBindingsGenerator/CppSharpExtensions/TargetedAttribute.cs +++ /dev/null @@ -1,58 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; - -namespace LlvmBindingsGenerator -{ - internal enum AttributeTarget - { - Default, - Assembly, - Module, - Field, - Event, - Method, - Param, - Property, - Return, - Type - } - - internal class TargetedAttribute - : CppSharp.AST.Attribute - { - public TargetedAttribute( Type type, params string[ ] args ) - : this( AttributeTarget.Default, type, ( IEnumerable )args ) - { - } - - public TargetedAttribute( AttributeTarget target, Type type, params string[ ] args ) - : this( target, type, ( IEnumerable )args ) - { - } - - public TargetedAttribute( AttributeTarget target, Type type, IEnumerable args ) - { - if( !typeof( Attribute ).IsAssignableFrom( type ) ) - { - throw new ArgumentException( "Attribute type required", nameof( type ) ); - } - - Type = type; - Target = target; - Value = string.Join( ", ", args ); - } - - public void AddParameter( string param ) - { - Value = $"{Value}, {param}"; - } - - public AttributeTarget Target { get; } - } -} diff --git a/src/Interop/LlvmBindingsGenerator/GlobalSuppressions.cs b/src/Interop/LlvmBindingsGenerator/GlobalSuppressions.cs deleted file mode 100644 index 5ff5b9180c..0000000000 --- a/src/Interop/LlvmBindingsGenerator/GlobalSuppressions.cs +++ /dev/null @@ -1,14 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -/* attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. -*/ - -using System.Diagnostics.CodeAnalysis; - -[assembly: SuppressMessage( "Performance", "CA1812:Avoid uninstantiated internal classes", Justification = "Use is Controlled by preprocessor define 'GENERATE_CS_INTEROP'" )] diff --git a/src/Interop/LlvmBindingsGenerator/LibLLVMTypePrinter.cs b/src/Interop/LlvmBindingsGenerator/LibLLVMTypePrinter.cs deleted file mode 100644 index a0a2b24c8f..0000000000 --- a/src/Interop/LlvmBindingsGenerator/LibLLVMTypePrinter.cs +++ /dev/null @@ -1,95 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System; - -using CppSharp.AST; -using CppSharp.Generators.CSharp; - -namespace LlvmBindingsGenerator -{ - // CONSIDER: Make this type printer provide the source language name - // so that Type.TosString() just works as is generally expected. - // (May be simpler to get the debug signature if available) - // Then add an extension method to type (i.e. ToTargetLanguageString()) - // that implements the functionality currently in this class - - /// Specialized type printer for Ubiquity.NET.Llvm.Interop - /// - /// Unfortunately will fail with a null - /// reference if there isn't a type printer delegate assigned. E.g. it has no - /// internal ability to convert the type to a string. Instead, it assumes that the - /// original source type is irrelevant and that the application is going to generate - /// code. Furthermore it assumes that the code generation will use ToString() to - /// get the final output generated code type name. Generally speaking that's a bad - /// design. It means that display of the type in a debugger doesn't work and you can't - /// see what you are dealing with easily. With the very surprising consequence of calls - /// to the ToString() method in code generating a null reference exception if the - /// delegate isn't set up. - /// This type serves as an extension to the default - /// that handles the specific needs of the Ubiquity.NET.Llvm.Interop code generation. The - /// role of the type printer is to get a string for the type in the syntax of the target - /// language. (As mentioned this is unfortunately tied into the type.ToString() method, - /// which means the debugger only shows the target language type names and NOT the original - /// AST names from the source) - /// - internal class LibLLVMTypePrinter - : CSharpTypePrinter - , ITypePrinter2 - { - public override string ToString( CppSharp.AST.Type type ) - { - throw new NotSupportedException("Direct calls to ToString are not supported, instead call GetName with the appropriate kind"); - } - - public string GetName( CppSharp.AST.Type type, TypeNameKind kind = TypeNameKind.Native) - { - if(kind == TypeNameKind.Native) - { - return type.Visit(NativePrinter); - } - - string retVal = type switch - { - TypedefType tdt when tdt.Declaration.Name == "LLVMBool" => "bool", - PointerType pt when pt.Pointee is BuiltinType => $"{base.ToString( pt.Pointee )}*", // shouldn't see this... Should be caught as an error... - TypedefType tdt when tdt.Declaration.Name == "intptr_t" => "nint", - TypedefType tdt when tdt.Declaration.Name == "uintptr_t" => "nuint", - TypedefType tdt when tdt.Declaration.Name == "uint8_t" => "byte", - TypedefType tdt when( ShouldBeUInt32(tdt) ) => "UInt32", - TypedefType tdt when( ShouldBeUInt64(tdt) ) => "UInt64", - TypedefType tdt when tdt.Declaration.Name == "int8_t" => "sbyte", - TypedefType tdt when tdt.Declaration.Name == "uint16_t" => "UInt16", - TypedefType tdt when tdt.Declaration.Name == "int16_t" => "Int16", - TypedefType tdt when tdt.Declaration.Name == "int32_t" => "Int32", - TypedefType tdt when tdt.Declaration.Name == "int64_t" => "Int64", - TypedefType tdt => tdt.Declaration.Name, - BuiltinType bit when bit.Type == PrimitiveType.IntPtr => "nint", - CppSharp.AST.Type t when t.TryGetHandleDecl( out TypedefNameDecl? decl ) => decl!.Name, - ArrayType at => $"{GetName( at.Type, kind )}[]", - _ => base.ToString( type ), - }; - return retVal; - } - - private static bool ShouldBeUInt32(TypedefType tdt) - { - return tdt.Declaration.Name == "uint32_t" - || tdt.Declaration.Name == "LLVMDWARFTypeEncoding"; // TODO: This should be mapped as a record struct (Closest equivalent to a typedef uint32_t foo;) - } - - private static bool ShouldBeUInt64(TypedefType tdt) - { - return tdt.Declaration.Name == "uint64_t" - || tdt.Declaration.Name == "LLVMOrcModuleHandle" // TODO: This should be mapped as a record struct - || tdt.Declaration.Name == "LLVMOrcTargetAddress" // TODO: This should be mapped as a record struct - || tdt.Declaration.Name == "LLVMOrcJITTargetAddress" // TODO: This should be mapped as a record struct - || tdt.Declaration.Name == "LLVMOrcExecutorAddress"; // TODO: This should be mapped as a record struct - } - - private readonly NativeTypePrinter NativePrinter = new(); - } -} diff --git a/src/Interop/LlvmBindingsGenerator/LibLlvmGeneratorLibrary.cs b/src/Interop/LlvmBindingsGenerator/LibLlvmGeneratorLibrary.cs deleted file mode 100644 index ff3eaf35bf..0000000000 --- a/src/Interop/LlvmBindingsGenerator/LibLlvmGeneratorLibrary.cs +++ /dev/null @@ -1,107 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System.Collections.Generic; -using System.IO; - -using CppSharp.AST; - -using LlvmBindingsGenerator.Configuration; -using LlvmBindingsGenerator.Passes; -using LlvmBindingsGenerator.Templates; - -namespace LlvmBindingsGenerator -{ - /// ILibrary implementation for the Ubiquity.NET.Llvm Interop - /// - /// This class provides the library specific bridging from the generalized - /// CppSharp infrastructure for the specific needs of the Ubiquity.NET.Llvm.Interop library - /// - internal class LibLlvmGeneratorLibrary - : ILibrary - { - /// Initializes a new instance of the class. - /// Root path to standard LLVM source - /// Output path of the generated code files - /// - /// The only needs to have the files required to parse the LLVM-C API - /// - public LibLlvmGeneratorLibrary( IGeneratorConfig configuration, string llvmRoot, string extensionsRoot, string outputPath ) - { - Configuration = configuration; - CommonInclude = Path.Combine( llvmRoot, "include" ); - ArchInclude = Path.Combine( llvmRoot, "x64-Release", "include" ); - ExtensionsInclude = Path.Combine( extensionsRoot, "include" ); - OutputPath = Path.GetFullPath( outputPath ); - InternalTypePrinter = new LibLLVMTypePrinter(); - - // Hook in the custom type printer via static delegate - Type.TypePrinterDelegate = t => InternalTypePrinter.GetName( t, TypeNameKind.Native ); - } - - public void Setup( IDriver driver ) - { - Driver = driver; - driver.Options.UseHeaderDirectories = true; - driver.Options.GenerationOutputMode = CppSharp.GenerationOutputMode.FilePerUnit; - - driver.Options.OutputDir = OutputPath; - - driver.ParserOptions.SetupMSVC(); - driver.ParserOptions.AddIncludeDirs( CommonInclude ); - driver.ParserOptions.AddIncludeDirs( ArchInclude ); - driver.ParserOptions.AddIncludeDirs( ExtensionsInclude ); - - var coreHeaders = Directory.EnumerateFiles( Path.Combine( CommonInclude, "llvm-c" ), "*.h", SearchOption.AllDirectories ); - var extHeaders = Directory.EnumerateFiles( Path.Combine( ExtensionsInclude, "libllvm-c" ), "*.h", SearchOption.AllDirectories ); - var module = driver.Options.AddModule( "Ubiquity.NET.Llvm.Interop" ); - module.Headers.AddRange( coreHeaders ); - module.Headers.AddRange( extHeaders ); - } - - public void SetupPasses( ) - { - // Analysis passes that markup, but don't otherwise modify the AST run first - // always start the passes with the IgnoreSystemHeaders pass to ensure that - // transformation only occurs for the desired headers. Other passes depend on - // TranslationUnit.IsGenerated to ignore headers. - Driver!.AddTranslationUnitPass( new IgnoreSystemHeadersPass( Configuration.IgnoredHeaders ) ); - Driver!.AddTranslationUnitPass( new IgnoreDuplicateNamesPass( ) ); - - // modifying pass(es) - Driver!.AddTranslationUnitPass( new MarkFunctionsInternalPass( ) ); - - // Verification/sanity checking passes - Driver!.AddTranslationUnitPass( new ValidateExtensionNamingPass( ) ); - } - - public void Preprocess( ASTContext ctx ) - { - // purge all the CppSharp type mapping to prevent any conversions/mapping - // Only the raw source should be in the AST until later stages adjust it. - Driver!.Context.TypeMaps.TypeMaps.Clear(); - InternalTypePrinter.Context = Driver.Context; - } - - public void Postprocess( ASTContext ctx ) - { - } - - public IEnumerable CreateGenerators( ) - { - var templateFactory = new LibLlvmTemplateFactory( Configuration ); - return templateFactory.CreateTemplates( Driver!.Context ); - } - - private IDriver? Driver; - private readonly LibLLVMTypePrinter InternalTypePrinter; - private readonly IGeneratorConfig Configuration; - private readonly string CommonInclude; - private readonly string ArchInclude; - private readonly string ExtensionsInclude; - private readonly string OutputPath; - } -} diff --git a/src/Interop/LlvmBindingsGenerator/LibLlvmTemplateFactory.cs b/src/Interop/LlvmBindingsGenerator/LibLlvmTemplateFactory.cs deleted file mode 100644 index 00f0417fca..0000000000 --- a/src/Interop/LlvmBindingsGenerator/LibLlvmTemplateFactory.cs +++ /dev/null @@ -1,80 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System.Collections.Generic; -using System.IO; -using System.Linq; - -using CppSharp; -using CppSharp.Generators; -using CppSharp.Passes; - -using LlvmBindingsGenerator.Configuration; -using LlvmBindingsGenerator.Templates; - -namespace LlvmBindingsGenerator -{ - // Factory class for the templates needed in code generation - // This is essentially a more flexible form of the CppSharp.CodeGenerator, - // which, despite the name, doesn't generate code, but instead creates - // templates in the form of GeneratorOutput. Therefore, ICodeGenerator - // here is the functional equivalent to CppSharp's GeneratorOutput. - internal class LibLlvmTemplateFactory - : ICodeGeneratorTemplateFactory - { - public LibLlvmTemplateFactory( IGeneratorConfig config) - { - HandleToTemplateMap = config.BuildTemplateMap( ); - } - - public void SetupPasses( BindingContext bindingContext ) - { - bindingContext.TranslationUnitPasses.AddPass( new CheckAbiParameters( ) ); - } - - public IEnumerable CreateTemplates( BindingContext bindingContext ) - { - return CreateHandleTypeTemplates( bindingContext ) - .Concat( CreateMiscTemplates( bindingContext ) ); - } - - private static IEnumerable CreateMiscTemplates( BindingContext bindingContext ) - { - yield return new TemplateCodeGenerator( "EXPORTS", Path.Combine( "..", "LibLLVM" ), new ExportsTemplate( bindingContext.ASTContext ) ); - } - - private IEnumerable CreateHandleTypeTemplates( BindingContext ctx ) - { - // filter out known handle types with non-templated implementations - // LLVMErrorRef is rather unique with disposal and requires a distinct - // implementation. (If the message is retrieved, the handle is destroyed, - // and it is destroyed if "consumed" without getting the message.) - var handles = from handle in ctx.ASTContext.GetHandleTypeDefs( ) - where handle.Name != "LLVMErrorRef" - select handle; - - foreach( var handle in handles ) - { - bool templatesFound = false; - foreach(IHandleCodeTemplate template in HandleToTemplateMap[handle.Name]) - { - yield return new TemplateCodeGenerator( template.HandleName, GeneratedCodePath, template ); - templatesFound = true; - } - - if(!templatesFound) - { - // Generate an error for any handle types parsed from native headers not accounted for in the YAML configuration. - Diagnostics.Error( "No Mapping for handle type {0} - {1}@{2}", handle.Name, handle.TranslationUnit.FileRelativePath, handle.LineNumberStart ); - } - } - } - - private readonly ILookup HandleToTemplateMap; - - private const string GeneratedCodePath = "GeneratedCode"; - } -} diff --git a/src/Interop/LlvmBindingsGenerator/LlvmBindingsGenerator.csproj b/src/Interop/LlvmBindingsGenerator/LlvmBindingsGenerator.csproj deleted file mode 100644 index c477437967..0000000000 --- a/src/Interop/LlvmBindingsGenerator/LlvmBindingsGenerator.csproj +++ /dev/null @@ -1,71 +0,0 @@ - - - - - Exe - false - portable - true - False - x64 - False - net8.0 - enable - - - - - - - - - - - - - - - - - Always - - - TextTemplatingFilePreprocessor - ContextHandleTemplate.cs - LlvmBindingsGenerator.Templates - - - TextTemplatingFilePreprocessor - ExportsTemplate.cs - LlvmBindingsGenerator.Templates - - - TextTemplatingFilePreprocessor - GlobalHandleTemplate.cs - LlvmBindingsGenerator.Templates - - - - - - True - True - ContextHandleTemplate.tt - - - True - True - ExportsTemplate.tt - - - True - True - GlobalHandleTemplate.tt - - - - - - - - diff --git a/src/Interop/LlvmBindingsGenerator/LlvmBindingsGenerator.sln b/src/Interop/LlvmBindingsGenerator/LlvmBindingsGenerator.sln deleted file mode 100644 index 9411f0762d..0000000000 --- a/src/Interop/LlvmBindingsGenerator/LlvmBindingsGenerator.sln +++ /dev/null @@ -1,42 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.12.35707.178 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LlvmBindingsGenerator", "LlvmBindingsGenerator.csproj", "{9A14EF74-BDF8-4D00-803A-A48A14828526}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{05813380-541B-47E8-95CB-B426127C2CEE}" - ProjectSection(SolutionItems) = preProject - ..\..\..\Build-All.ps1 = ..\..\..\Build-All.ps1 - ..\..\..\Build-Docs.ps1 = ..\..\..\Build-Docs.ps1 - ..\..\..\Build-Interop.ps1 = ..\..\..\Build-Interop.ps1 - ..\..\..\Build-Source.ps1 = ..\..\..\Build-Source.ps1 - ..\..\..\BuildVersion.xml = ..\..\..\BuildVersion.xml - ..\..\..\Directory.Build.props = ..\..\..\Directory.Build.props - ..\..\..\Directory.Build.targets = ..\..\..\Directory.Build.targets - ..\..\..\global.json = ..\..\..\global.json - ..\..\..\Invoke-UnitTests.ps1 = ..\..\..\Invoke-UnitTests.ps1 - ..\..\..\LICENSE.md = ..\..\..\LICENSE.md - ..\..\..\Make-DevBuildLLvmLink.ps1 = ..\..\..\Make-DevBuildLLvmLink.ps1 - ..\..\..\NuGet.Config = ..\..\..\NuGet.Config - ..\..\..\Packages.props = ..\..\..\Packages.props - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {9A14EF74-BDF8-4D00-803A-A48A14828526}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9A14EF74-BDF8-4D00-803A-A48A14828526}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9A14EF74-BDF8-4D00-803A-A48A14828526}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9A14EF74-BDF8-4D00-803A-A48A14828526}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {3C6B306B-6805-4AAA-A735-D285C826A434} - EndGlobalSection -EndGlobal diff --git a/src/Interop/LlvmBindingsGenerator/Options.cs b/src/Interop/LlvmBindingsGenerator/Options.cs deleted file mode 100644 index b7d117f767..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Options.cs +++ /dev/null @@ -1,40 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System; -using System.Diagnostics.CodeAnalysis; - -using CommandLine; - -using CppSharp; - -namespace LlvmBindingsGenerator -{ - [SuppressMessage("Build", "CA1812", Justification = "Instantiated via reflection from commandline parser" )] - [SuppressMessage( "CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "It is necessary, tooling can't agree on the point. (removing it generates a warning)" )] - internal class Options - { - public Options( string llvmRoot, string extensionsRoot, string outputPath, DiagnosticKind diagnostics ) - { - LlvmRoot = llvmRoot; - ExtensionsRoot = extensionsRoot; - OutputPath = outputPath; - Diagnostics = diagnostics; - } - - [Value( 0, MetaName = "LLVM Root", HelpText = "Root of source with the LLVM headers to parse", Required = true )] - public string LlvmRoot { get; } - - [Value( 1, MetaName = "Extensions Root", HelpText = "Root of source with the LibLLVM extension headers to parse", Required = true )] - public string ExtensionsRoot { get; } - - [Value( 2, MetaName = "Output Path", HelpText = "Root of the output to place the generated code", Required = true )] - public string OutputPath { get; } = Environment.CurrentDirectory; - - [Option( HelpText = "Diagnostics output level", Required = false, Default = DiagnosticKind.Message )] - public DiagnosticKind Diagnostics { get; } - } -} diff --git a/src/Interop/LlvmBindingsGenerator/Passes/IgnoreDuplicateNamesPass.cs b/src/Interop/LlvmBindingsGenerator/Passes/IgnoreDuplicateNamesPass.cs deleted file mode 100644 index 45cd49662e..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Passes/IgnoreDuplicateNamesPass.cs +++ /dev/null @@ -1,47 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System.Collections.Generic; - -using CppSharp.AST; -using CppSharp.Passes; - -namespace LlvmBindingsGenerator.Passes -{ - /// Translation unit pass to mark duplicate function names as ignored - internal class IgnoreDuplicateNamesPass - : TranslationUnitPass - { - public override bool VisitASTContext( ASTContext context ) - { - VisitedNames.Clear( ); - - foreach( TranslationUnit unit in context.GeneratedUnits( ) ) - { - VisitTranslationUnit( unit ); - } - - return true; - } - - public override bool VisitFunctionDecl( Function function ) - { - if( !base.VisitFunctionDecl( function ) ) - { - return false; - } - - if( !VisitedNames.Add( function.Name ) ) - { - function.Ignore = true; - } - - return true; - } - - private readonly HashSet VisitedNames = new HashSet(); - } -} diff --git a/src/Interop/LlvmBindingsGenerator/Passes/IgnoreSystemHeadersPass.cs b/src/Interop/LlvmBindingsGenerator/Passes/IgnoreSystemHeadersPass.cs deleted file mode 100644 index 7c0dc605c2..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Passes/IgnoreSystemHeadersPass.cs +++ /dev/null @@ -1,59 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System.Collections.Generic; -using System.Linq; - -using CppSharp; -using CppSharp.AST; -using CppSharp.Passes; - -using LlvmBindingsGenerator.Configuration; - -namespace LlvmBindingsGenerator.Passes -{ - /// Translation unit pass to mark system headers as ignored - /// - /// should always be the first pass so that other passes can rely on IsGenerated - /// properly to correctly ignore the header. - /// - internal class IgnoreSystemHeadersPass - : TranslationUnitPass - { - public IgnoreSystemHeadersPass( IReadOnlyCollection ignoredHeaders ) - { - IgnoredHeaders = from entry in ignoredHeaders - select entry.Path; - } - - public override bool VisitTranslationUnit( TranslationUnit unit ) - { - if( unit.IncludePath == null || !unit.IsValid || unit.IsInvalid ) - { - Diagnostics.Debug("Translation Unit '{0}' is invalid - marked to ignore.", unit); - unit.GenerationKind = GenerationKind.None; - return true; - } - - bool isExplicitlyIgnored = IgnoredHeaders.Contains( unit.FileRelativePath ); - if( isExplicitlyIgnored ) - { - unit.Ignore = true; - unit.GenerationKind = GenerationKind.None; - Diagnostics.Debug("Translation unit '{0}' is explicitly ignored", unit); - } - else - { - unit.GenerationKind = ( unit.IsCoreHeader() || unit.IsExtensionHeader() ) ? GenerationKind.Generate : GenerationKind.None; - Diagnostics.Debug("Translation unit '{0}' GenerationKind == {1}", unit, unit.GenerationKind); - } - - return true; - } - - private readonly IEnumerable IgnoredHeaders; - } -} diff --git a/src/Interop/LlvmBindingsGenerator/Passes/MarkFunctionsInternalPass.cs b/src/Interop/LlvmBindingsGenerator/Passes/MarkFunctionsInternalPass.cs deleted file mode 100644 index 93eba6004b..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Passes/MarkFunctionsInternalPass.cs +++ /dev/null @@ -1,36 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using CppSharp.AST; -using CppSharp.Passes; - -namespace LlvmBindingsGenerator.Passes -{ - /// Mark functions as internal or ignored - /// - /// This pass will mark all Implicit functions from the headers ignored (e.g. an - /// implicit constructor/destructor for a struct). - /// - internal class MarkFunctionsInternalPass - : TranslationUnitPass - { - public override bool VisitFunctionDecl( Function function ) - { - if( function.Ignore ) - { - return true; - } - - if( function.IsImplicit ) - { - function.Ignore = true; - return true; - } - - return false; - } - } -} diff --git a/src/Interop/LlvmBindingsGenerator/Passes/ValidateExtensionNamingPass.cs b/src/Interop/LlvmBindingsGenerator/Passes/ValidateExtensionNamingPass.cs deleted file mode 100644 index 07d3412581..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Passes/ValidateExtensionNamingPass.cs +++ /dev/null @@ -1,77 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System.Linq; - -using CppSharp; -using CppSharp.AST; -using CppSharp.Passes; - -namespace LlvmBindingsGenerator.Passes -{ - /// Translation unit pass to validate names of all functions in the extension headers have correct prefix - /// - /// All extended C APIs should have the 'LibLLVM' prefix so that they are clearly marked as an extension and there isn't - /// any conflict with the official LLVM-C API. - /// - internal class ValidateExtensionNamingPass - : TranslationUnitPass - { - public override bool VisitASTContext( ASTContext context ) - { - var extensionHeaders = from tu in context.TranslationUnits - where tu.IsExtensionHeader( ) - select tu; - - foreach( TranslationUnit translationUnit in extensionHeaders ) - { - VisitTranslationUnit( translationUnit ); - } - - return true; - } - - public override bool VisitFunctionDecl( Function function ) - { - if( !function.Ignore && !function.Name.StartsWith( "LibLLVM", System.StringComparison.Ordinal ) ) - { - Diagnostics.Error( "Extension function {0} in {1}, does not use correct prefix", function.Name, function.TranslationUnit.FileName ); - } - - return true; - } - - public override bool VisitTypedefDecl( TypedefDecl typedef ) - { - if( !typedef.Name.StartsWith( "LibLLVM", System.StringComparison.Ordinal ) ) - { - Diagnostics.Error( "Extension typeDef {0} in {1}, does not use correct prefix", typedef.Name, typedef.TranslationUnit.FileName ); - } - - return true; - } - - public override bool VisitEnumDecl( Enumeration @enum ) - { - if( !@enum.Name.StartsWith( "LibLLVM", System.StringComparison.Ordinal ) ) - { - Diagnostics.Error( "Extension enum {0} in {1}, does not use correct prefix", @enum.Name, @enum.TranslationUnit.FileName ); - } - - return true; - } - - public override bool VisitEnumItemDecl( Enumeration.Item item ) - { - if( !item.Name.StartsWith( "LibLLVM", System.StringComparison.Ordinal ) ) - { - Diagnostics.Error( "Extension enum item {0} in {1}, does not use correct prefix", item.Name, item.TranslationUnit.FileName ); - } - - return true; - } - } -} diff --git a/src/Interop/LlvmBindingsGenerator/Program.cs b/src/Interop/LlvmBindingsGenerator/Program.cs deleted file mode 100644 index 9d1f425710..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Program.cs +++ /dev/null @@ -1,81 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System; -using System.Collections.Immutable; -using System.IO; -using System.Reflection; -using System.Text.RegularExpressions; - -using CommandLine; - -using CppSharp; - -using LlvmBindingsGenerator.Configuration; -using LlvmBindingsGenerator.Configuration.Yaml; - -namespace LlvmBindingsGenerator -{ - internal static partial class Program - { - public static int Main( string[ ] args ) - { - return Parser.Default - .ParseArguments( args ) - .MapResult( Run, _ => -1 ); - } - - private static int Run( Options options ) - { - var diagnostics = new ErrorTrackingDiagnostics( ) - { - Level = options.Diagnostics - }; - - Diagnostics.Implementation = diagnostics; - string configPath = Path.Combine( Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location ) ?? string.Empty, "BindingsConfig.yml"); - - try - { - // read in the binding configuration from the YAML file - var config = new ReadOnlyConfig( YamlConfiguration.ParseFrom( configPath ) ); - var library = new LibLlvmGeneratorLibrary( config, options.LlvmRoot, options.ExtensionsRoot, options.OutputPath ); - Driver.Run( library ); - } - catch(IOException ioex) - { - Diagnostics.Error( ioex.Message ); - } - catch(YamlDotNet.Core.SyntaxErrorException yamlex) - { - // Sadly, the yaml exception message includes the location info in a format that doesn't match any standard tooling - // for parsing error messages, so unpack it to get just the message of interest and re-format - var matcher = YamlErrorMessageRegex(); - var result = matcher.Match( yamlex.Message ); - if( result.Success ) - { - Diagnostics.Error( "{0}({1},{2},{3},{4}): error CFG001: {5}" - , configPath - , yamlex.Start.Line - , yamlex.Start.Column - , yamlex.End.Line - , yamlex.End.Column - , result.Groups[ 1 ] ); - } - else - { - // message didn't match expectations, best effort at this point... - Diagnostics.Error( yamlex.Message ); - } - } - - return diagnostics.ErrorCount; - } - - [GeneratedRegex( @"\(Line\: \d+, Col\: \d+, Idx\: \d+\) - \(Line\: \d+, Col\: \d+, Idx\: \d+\)\: (.*)\Z" )] - private static partial Regex YamlErrorMessageRegex(); - } -} diff --git a/src/Interop/LlvmBindingsGenerator/Properties/AssemblyInfo.cs b/src/Interop/LlvmBindingsGenerator/Properties/AssemblyInfo.cs deleted file mode 100644 index 5432886087..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,40 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System; -using System.Reflection; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyDescription( "CLR Interop bindings generator for LibLLVM" )] -[assembly: AssemblyCopyright( "Copyright © 2019" )] -[assembly: AssemblyTrademark( "" )] -[assembly: AssemblyCulture( "" )] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible( false )] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid( "19930cea-c236-409f-b30e-88788af700e0" )] - -[assembly: CLSCompliant( false )] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -// [assembly: AssemblyVersion( "0.1.0.0" )] -// [assembly: AssemblyFileVersion( "0.1.0.0" )] diff --git a/src/Interop/LlvmBindingsGenerator/TemplateCodeGenerator.cs b/src/Interop/LlvmBindingsGenerator/TemplateCodeGenerator.cs deleted file mode 100644 index fab9b340a9..0000000000 --- a/src/Interop/LlvmBindingsGenerator/TemplateCodeGenerator.cs +++ /dev/null @@ -1,44 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using LlvmBindingsGenerator.Templates; - -namespace LlvmBindingsGenerator -{ - internal class TemplateCodeGenerator - : ICodeGenerator - { - public TemplateCodeGenerator( - string fileNameWithoutExtension, - string fileRelativeDirectory, - ICodeGenTemplate template - ) - : this( isValid: true, fileNameWithoutExtension, fileRelativeDirectory, template ) - { - } - - public TemplateCodeGenerator( - bool isValid, - string fileNameWithoutExtension, - string fileRelativeDirectory, - ICodeGenTemplate template - ) - { - IsValid = isValid; - FileNameWithoutExtension = fileNameWithoutExtension; - FileRelativeDirectory = fileRelativeDirectory; - Template = template; - } - - public bool IsValid { get; } - - public string FileNameWithoutExtension { get; } - - public string FileRelativeDirectory { get; } - - public ICodeGenTemplate Template { get; } - } -} diff --git a/src/Interop/LlvmBindingsGenerator/Templates/AssemblyExtensions.cs b/src/Interop/LlvmBindingsGenerator/Templates/AssemblyExtensions.cs deleted file mode 100644 index 9a8ba82081..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Templates/AssemblyExtensions.cs +++ /dev/null @@ -1,20 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System; -using System.Reflection; - -namespace LlvmBindingsGenerator.Templates -{ - internal static class AssemblyExtensions - { - public static string GetAssemblyInformationalVersion( this Assembly asm ) - { - var attr = asm.GetCustomAttribute(); - return attr?.InformationalVersion ?? throw new InvalidOperationException("Assembly does not have in information version"); - } - } -} diff --git a/src/Interop/LlvmBindingsGenerator/Templates/ContextHandleTemplate.cs b/src/Interop/LlvmBindingsGenerator/Templates/ContextHandleTemplate.cs deleted file mode 100644 index b2c09ade04..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Templates/ContextHandleTemplate.cs +++ /dev/null @@ -1,27 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -namespace LlvmBindingsGenerator.Templates -{ - internal partial class ContextHandleTemplate - : IHandleCodeTemplate - { - public ContextHandleTemplate( string name ) - { - HandleName = name; - } - - public string ToolVersion => GetType( ).Assembly.GetAssemblyInformationalVersion( ); - - public string HandleName { get; } - - public string FileExtension => "g.cs"; - - public string SubFolder => string.Empty; - - public string Generate( ) => TransformText( ); - } -} diff --git a/src/Interop/LlvmBindingsGenerator/Templates/ExportsTemplate.cs b/src/Interop/LlvmBindingsGenerator/Templates/ExportsTemplate.cs deleted file mode 100644 index 2d0ef7361e..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Templates/ExportsTemplate.cs +++ /dev/null @@ -1,55 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -using System.Collections.Generic; -using System.Linq; - -using CppSharp.AST; - -namespace LlvmBindingsGenerator.Templates -{ - internal partial class ExportsTemplate - : ICodeGenTemplate - { - public ExportsTemplate( ASTContext ast ) - { - Ast = ast; - } - - public string ToolVersion => GetType( ).Assembly.GetAssemblyInformationalVersion( ); - - public string FileExtension => "g.DEF"; - - public string SubFolder => string.Empty; - - public string Generate( ) - { - return TransformText( ); - } - - public IEnumerable InlinedFunctions - => from tu in Ast.GeneratedUnits( ) - from func in tu.Functions - where func.IsInline && !func.Ignore - select func; - - public IEnumerable ExtensionFunctions - => from tu in Ast.GeneratedUnits( ) - where tu.IsExtensionHeader( ) - from func in tu.Functions - where !func.IsInline && !func.Ignore - select func; - - public IEnumerable LlvmFunctions - => from tu in Ast.GeneratedUnits( ) - where tu.IsCoreHeader( ) - from func in tu.Functions - where !func.IsInline && !func.Ignore - select func; - - private readonly ASTContext Ast; - } -} diff --git a/src/Interop/LlvmBindingsGenerator/Templates/GlobalHandleTemplate.cs b/src/Interop/LlvmBindingsGenerator/Templates/GlobalHandleTemplate.cs deleted file mode 100644 index 7e4384700d..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Templates/GlobalHandleTemplate.cs +++ /dev/null @@ -1,33 +0,0 @@ -// ----------------------------------------------------------------------- -// -// Copyright (c) Ubiquity.NET Contributors. All rights reserved. -// -// ----------------------------------------------------------------------- - -namespace LlvmBindingsGenerator.Templates -{ - internal partial class GlobalHandleTemplate - : IHandleCodeTemplate - { - public GlobalHandleTemplate( string name, string disposerFunctionName, bool needsAlias = false ) - { - HandleName = name; - HandleDisposeFunction = disposerFunctionName; - NeedsAlias = needsAlias; - } - - public string ToolVersion => GetType( ).Assembly.GetAssemblyInformationalVersion( ); - - public string HandleName { get; } - - public string HandleDisposeFunction { get; } - - public string FileExtension => "g.cs"; - - public string SubFolder => string.Empty; - - public bool NeedsAlias { get; } - - public string Generate( ) => TransformText( ); - } -} diff --git a/src/Interop/LlvmBindingsGenerator/Templates/T4/ContextHandleTemplate.cs b/src/Interop/LlvmBindingsGenerator/Templates/T4/ContextHandleTemplate.cs deleted file mode 100644 index ef172c572c..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Templates/T4/ContextHandleTemplate.cs +++ /dev/null @@ -1,422 +0,0 @@ -// ------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version: 17.0.0.0 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -// ------------------------------------------------------------------------------ -namespace LlvmBindingsGenerator.Templates -{ - using System.Linq; - using System.Text; - using System.Collections.Generic; - using System; - - /// - /// Class to produce the template output - /// - - #line 1 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\ContextHandleTemplate.tt" - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")] - internal partial class ContextHandleTemplate : ContextHandleTemplateBase - { -#line hidden - /// - /// Create the template output - /// - public virtual string TransformText() - { - this.Write("// ------------------------------------------------------------------------------" + - "\r\n// \r\n// This code was generated by a tool. [LlvmBindingsGe" + - "nerator]\r\n// Tool Version: "); - - #line 9 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\ContextHandleTemplate.tt" - this.Write(this.ToStringHelper.ToStringWithCulture(ToolVersion)); - - #line default - #line hidden - this.Write(@" -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -// ------------------------------------------------------------------------------ - -using System.CodeDom.Compiler; - -namespace Ubiquity.NET.Llvm.Interop -{ - /// Simple type safe handle to wrap an opaque pointer for interop with ""C"" API exported from LibLLVM - /// - /// This handle is owned by it's container and therefore isn't disposed by the - /// calling App. - /// - /// Since the object this handle refers to is not owned by the App, the object is - /// destroyed whenever it's container is destroyed, which will invalidate this handle. - /// Use of this handle after the container is destroyed will produce undefined - /// behavior, including, and most likely, memory access violations. - /// - /// - [GeneratedCode(""LlvmBindingsGenerator"","""); - - #line 31 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\ContextHandleTemplate.tt" - this.Write(this.ToStringHelper.ToStringWithCulture(ToolVersion)); - - #line default - #line hidden - this.Write("\")]\r\n [NativeMarshalling(typeof(ContextHandleMarshaller<"); - - #line 32 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\ContextHandleTemplate.tt" - this.Write(this.ToStringHelper.ToStringWithCulture(HandleName)); - - #line default - #line hidden - this.Write(">))]\r\n public readonly record struct "); - - #line 33 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\ContextHandleTemplate.tt" - this.Write(this.ToStringHelper.ToStringWithCulture(HandleName)); - - #line default - #line hidden - this.Write("\r\n : IContextHandle<"); - - #line 34 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\ContextHandleTemplate.tt" - this.Write(this.ToStringHelper.ToStringWithCulture(HandleName)); - - #line default - #line hidden - this.Write(@"> - { - /// Gets a value indicating if this handle is a value - public bool IsNull => Handle == nint.Zero; - - /// Gets the handle as an suitable for passing to native code - /// The handle as an - public nint DangerousGetHandle() => Handle; - - /// Interface defined factory for an instance of \r\n /// Native ABI value of the handle<" + - "/param>\r\n /// Type specific wrapper around the native ABI handle" + - "\r\n public static "); - - #line 46 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\ContextHandleTemplate.tt" - this.Write(this.ToStringHelper.ToStringWithCulture(HandleName)); - - #line default - #line hidden - this.Write(" FromABI(nint abiValue) => new(abiValue);\r\n\r\n /// Gets a zero () value handle\r\n public static "); - - #line 49 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\ContextHandleTemplate.tt" - this.Write(this.ToStringHelper.ToStringWithCulture(HandleName)); - - #line default - #line hidden - this.Write(@" Zero => FromABI(nint.Zero); - - /// Gets the handle as an suitable for passing to native code - /// Handle to convert - /// The handle as an - public static implicit operator nint("); - - #line 54 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\ContextHandleTemplate.tt" - this.Write(this.ToStringHelper.ToStringWithCulture(HandleName)); - - #line default - #line hidden - this.Write(" value) => value.Handle;\r\n\r\n private "); - - #line 56 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\ContextHandleTemplate.tt" - this.Write(this.ToStringHelper.ToStringWithCulture(HandleName)); - - #line default - #line hidden - this.Write("( nint p )\r\n {\r\n Handle = p;\r\n }\r\n\r\n private read" + - "only nint Handle;\r\n }\r\n}\r\n"); - return this.GenerationEnvironment.ToString(); - } - } - - #line default - #line hidden - #region Base class - /// - /// Base class for this transformation - /// - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")] - internal class ContextHandleTemplateBase - { - #region Fields - private global::System.Text.StringBuilder generationEnvironmentField; - private global::System.CodeDom.Compiler.CompilerErrorCollection errorsField; - private global::System.Collections.Generic.List indentLengthsField; - private string currentIndentField = ""; - private bool endsWithNewline; - private global::System.Collections.Generic.IDictionary sessionField; - #endregion - #region Properties - /// - /// The string builder that generation-time code is using to assemble generated output - /// - public System.Text.StringBuilder GenerationEnvironment - { - get - { - if ((this.generationEnvironmentField == null)) - { - this.generationEnvironmentField = new global::System.Text.StringBuilder(); - } - return this.generationEnvironmentField; - } - set - { - this.generationEnvironmentField = value; - } - } - /// - /// The error collection for the generation process - /// - public System.CodeDom.Compiler.CompilerErrorCollection Errors - { - get - { - if ((this.errorsField == null)) - { - this.errorsField = new global::System.CodeDom.Compiler.CompilerErrorCollection(); - } - return this.errorsField; - } - } - /// - /// A list of the lengths of each indent that was added with PushIndent - /// - private System.Collections.Generic.List indentLengths - { - get - { - if ((this.indentLengthsField == null)) - { - this.indentLengthsField = new global::System.Collections.Generic.List(); - } - return this.indentLengthsField; - } - } - /// - /// Gets the current indent we use when adding lines to the output - /// - public string CurrentIndent - { - get - { - return this.currentIndentField; - } - } - /// - /// Current transformation session - /// - public virtual global::System.Collections.Generic.IDictionary Session - { - get - { - return this.sessionField; - } - set - { - this.sessionField = value; - } - } - #endregion - #region Transform-time helpers - /// - /// Write text directly into the generated output - /// - public void Write(string textToAppend) - { - if (string.IsNullOrEmpty(textToAppend)) - { - return; - } - // If we're starting off, or if the previous text ended with a newline, - // we have to append the current indent first. - if (((this.GenerationEnvironment.Length == 0) - || this.endsWithNewline)) - { - this.GenerationEnvironment.Append(this.currentIndentField); - this.endsWithNewline = false; - } - // Check if the current text ends with a newline - if (textToAppend.EndsWith(global::System.Environment.NewLine, global::System.StringComparison.CurrentCulture)) - { - this.endsWithNewline = true; - } - // This is an optimization. If the current indent is "", then we don't have to do any - // of the more complex stuff further down. - if ((this.currentIndentField.Length == 0)) - { - this.GenerationEnvironment.Append(textToAppend); - return; - } - // Everywhere there is a newline in the text, add an indent after it - textToAppend = textToAppend.Replace(global::System.Environment.NewLine, (global::System.Environment.NewLine + this.currentIndentField)); - // If the text ends with a newline, then we should strip off the indent added at the very end - // because the appropriate indent will be added when the next time Write() is called - if (this.endsWithNewline) - { - this.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - this.currentIndentField.Length)); - } - else - { - this.GenerationEnvironment.Append(textToAppend); - } - } - /// - /// Write text directly into the generated output - /// - public void WriteLine(string textToAppend) - { - this.Write(textToAppend); - this.GenerationEnvironment.AppendLine(); - this.endsWithNewline = true; - } - /// - /// Write formatted text directly into the generated output - /// - public void Write(string format, params object[] args) - { - this.Write(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args)); - } - /// - /// Write formatted text directly into the generated output - /// - public void WriteLine(string format, params object[] args) - { - this.WriteLine(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args)); - } - /// - /// Raise an error - /// - public void Error(string message) - { - System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError(); - error.ErrorText = message; - this.Errors.Add(error); - } - /// - /// Raise a warning - /// - public void Warning(string message) - { - System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError(); - error.ErrorText = message; - error.IsWarning = true; - this.Errors.Add(error); - } - /// - /// Increase the indent - /// - public void PushIndent(string indent) - { - if ((indent == null)) - { - throw new global::System.ArgumentNullException("indent"); - } - this.currentIndentField = (this.currentIndentField + indent); - this.indentLengths.Add(indent.Length); - } - /// - /// Remove the last indent that was added with PushIndent - /// - public string PopIndent() - { - string returnValue = ""; - if ((this.indentLengths.Count > 0)) - { - int indentLength = this.indentLengths[(this.indentLengths.Count - 1)]; - this.indentLengths.RemoveAt((this.indentLengths.Count - 1)); - if ((indentLength > 0)) - { - returnValue = this.currentIndentField.Substring((this.currentIndentField.Length - indentLength)); - this.currentIndentField = this.currentIndentField.Remove((this.currentIndentField.Length - indentLength)); - } - } - return returnValue; - } - /// - /// Remove any indentation - /// - public void ClearIndent() - { - this.indentLengths.Clear(); - this.currentIndentField = ""; - } - #endregion - #region ToString Helpers - /// - /// Utility class to produce culture-oriented representation of an object as a string. - /// - public class ToStringInstanceHelper - { - private System.IFormatProvider formatProviderField = global::System.Globalization.CultureInfo.InvariantCulture; - /// - /// Gets or sets format provider to be used by ToStringWithCulture method. - /// - public System.IFormatProvider FormatProvider - { - get - { - return this.formatProviderField ; - } - set - { - if ((value != null)) - { - this.formatProviderField = value; - } - } - } - /// - /// This is called from the compile/run appdomain to convert objects within an expression block to a string - /// - public string ToStringWithCulture(object objectToConvert) - { - if ((objectToConvert == null)) - { - throw new global::System.ArgumentNullException("objectToConvert"); - } - System.Type t = objectToConvert.GetType(); - System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] { - typeof(System.IFormatProvider)}); - if ((method == null)) - { - return objectToConvert.ToString(); - } - else - { - return ((string)(method.Invoke(objectToConvert, new object[] { - this.formatProviderField }))); - } - } - } - private ToStringInstanceHelper toStringHelperField = new ToStringInstanceHelper(); - /// - /// Helper to produce culture-oriented representation of an object as a string - /// - public ToStringInstanceHelper ToStringHelper - { - get - { - return this.toStringHelperField; - } - } - #endregion - } - #endregion -} diff --git a/src/Interop/LlvmBindingsGenerator/Templates/T4/ContextHandleTemplate.tt b/src/Interop/LlvmBindingsGenerator/Templates/T4/ContextHandleTemplate.tt deleted file mode 100644 index 99d29d8105..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Templates/T4/ContextHandleTemplate.tt +++ /dev/null @@ -1,63 +0,0 @@ -<#@ template language="C#" visibility="internal" #> -<#@ assembly name="System.Core" #> -<#@ import namespace="System.Linq" #> -<#@ import namespace="System.Text" #> -<#@ import namespace="System.Collections.Generic" #> -// ------------------------------------------------------------------------------ -// -// This code was generated by a tool. [LlvmBindingsGenerator] -// Tool Version: <#=ToolVersion#> -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -// ------------------------------------------------------------------------------ - -using System.CodeDom.Compiler; - -namespace Ubiquity.NET.Llvm.Interop -{ - /// Simple type safe handle to wrap an opaque pointer for interop with "C" API exported from LibLLVM - /// - /// This handle is owned by it's container and therefore isn't disposed by the - /// calling App. - /// - /// Since the object this handle refers to is not owned by the App, the object is - /// destroyed whenever it's container is destroyed, which will invalidate this handle. - /// Use of this handle after the container is destroyed will produce undefined - /// behavior, including, and most likely, memory access violations. - /// - /// - [GeneratedCode("LlvmBindingsGenerator","<#=ToolVersion#>")] - [NativeMarshalling(typeof(ContextHandleMarshaller<<#=HandleName#>>))] - public readonly record struct <#=HandleName#> - : IContextHandle<<#=HandleName#>> - { - /// Gets a value indicating if this handle is a value - public bool IsNull => Handle == nint.Zero; - - /// Gets the handle as an suitable for passing to native code - /// The handle as an - public nint DangerousGetHandle() => Handle; - - /// Interface defined factory for an instance of - /// Native ABI value of the handle - /// Type specific wrapper around the native ABI handle - public static <#=HandleName#> FromABI(nint abiValue) => new(abiValue); - - /// Gets a zero () value handle - public static <#=HandleName#> Zero => FromABI(nint.Zero); - - /// Gets the handle as an suitable for passing to native code - /// Handle to convert - /// The handle as an - public static implicit operator nint(<#=HandleName#> value) => value.Handle; - - private <#=HandleName#>( nint p ) - { - Handle = p; - } - - private readonly nint Handle; - } -} diff --git a/src/Interop/LlvmBindingsGenerator/Templates/T4/ExportsTemplate.cs b/src/Interop/LlvmBindingsGenerator/Templates/T4/ExportsTemplate.cs deleted file mode 100644 index ca9a73229a..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Templates/T4/ExportsTemplate.cs +++ /dev/null @@ -1,400 +0,0 @@ -// ------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version: 17.0.0.0 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -// ------------------------------------------------------------------------------ -namespace LlvmBindingsGenerator.Templates -{ - using System.Linq; - using System.Text; - using System.Collections.Generic; - using System; - - /// - /// Class to produce the template output - /// - - #line 1 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\ExportsTemplate.tt" - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")] - internal partial class ExportsTemplate : ExportsTemplateBase - { -#line hidden - /// - /// Create the template output - /// - public virtual string TransformText() - { - this.Write(";; ------------------------------------------------------------------------------" + - "\r\n;; \r\n;; This file was generated by a tool.\r\n;; Runtime" + - " Version: "); - - #line 9 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\ExportsTemplate.tt" - this.Write(this.ToStringHelper.ToStringWithCulture(ToolVersion)); - - #line default - #line hidden - this.Write(@" -;; -;; Changes to this file may cause incorrect behavior and will be lost if -;; the code is regenerated. -;; -;; ------------------------------------------------------------------------------ -EXPORTS -; Custom Extension APIs for Ubiquity.NET.Llvm -"); - - #line 17 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\ExportsTemplate.tt" -foreach(var func in ExtensionFunctions) { - - #line default - #line hidden - - #line 18 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\ExportsTemplate.tt" - this.Write(this.ToStringHelper.ToStringWithCulture(func.Name)); - - #line default - #line hidden - this.Write("\r\n"); - - #line 19 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\ExportsTemplate.tt" -} - - #line default - #line hidden - this.Write("\r\n; Inlined Functions in LLVM Headers wrapped as non-inlined *Export functions in" + - " LibLLVM\r\n"); - - #line 22 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\ExportsTemplate.tt" -foreach(var inlineFunc in InlinedFunctions) { - - #line default - #line hidden - - #line 23 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\ExportsTemplate.tt" - this.Write(this.ToStringHelper.ToStringWithCulture(inlineFunc.Name)); - - #line default - #line hidden - this.Write(" = "); - - #line 23 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\ExportsTemplate.tt" - this.Write(this.ToStringHelper.ToStringWithCulture(inlineFunc.Name)); - - #line default - #line hidden - this.Write("Export\r\n"); - - #line 24 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\ExportsTemplate.tt" -} - - #line default - #line hidden - this.Write(@" -; Standard Official LLVM-C APIs -; If LibLLCVM-C.lib is available, these could be generated to forward to that -; or left out completely and use it directly from managed interop code -; A Major problem with that is that it loses ALL access to the C++ as that is -; NOT exported (and should never be as it isn't ABI stable) -"); - - #line 31 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\ExportsTemplate.tt" -foreach(var func in LlvmFunctions) { - - #line default - #line hidden - - #line 32 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\ExportsTemplate.tt" - this.Write(this.ToStringHelper.ToStringWithCulture(func.Name)); - - #line default - #line hidden - this.Write("\r\n"); - - #line 33 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\ExportsTemplate.tt" -} - - #line default - #line hidden - return this.GenerationEnvironment.ToString(); - } - } - - #line default - #line hidden - #region Base class - /// - /// Base class for this transformation - /// - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")] - internal class ExportsTemplateBase - { - #region Fields - private global::System.Text.StringBuilder generationEnvironmentField; - private global::System.CodeDom.Compiler.CompilerErrorCollection errorsField; - private global::System.Collections.Generic.List indentLengthsField; - private string currentIndentField = ""; - private bool endsWithNewline; - private global::System.Collections.Generic.IDictionary sessionField; - #endregion - #region Properties - /// - /// The string builder that generation-time code is using to assemble generated output - /// - public System.Text.StringBuilder GenerationEnvironment - { - get - { - if ((this.generationEnvironmentField == null)) - { - this.generationEnvironmentField = new global::System.Text.StringBuilder(); - } - return this.generationEnvironmentField; - } - set - { - this.generationEnvironmentField = value; - } - } - /// - /// The error collection for the generation process - /// - public System.CodeDom.Compiler.CompilerErrorCollection Errors - { - get - { - if ((this.errorsField == null)) - { - this.errorsField = new global::System.CodeDom.Compiler.CompilerErrorCollection(); - } - return this.errorsField; - } - } - /// - /// A list of the lengths of each indent that was added with PushIndent - /// - private System.Collections.Generic.List indentLengths - { - get - { - if ((this.indentLengthsField == null)) - { - this.indentLengthsField = new global::System.Collections.Generic.List(); - } - return this.indentLengthsField; - } - } - /// - /// Gets the current indent we use when adding lines to the output - /// - public string CurrentIndent - { - get - { - return this.currentIndentField; - } - } - /// - /// Current transformation session - /// - public virtual global::System.Collections.Generic.IDictionary Session - { - get - { - return this.sessionField; - } - set - { - this.sessionField = value; - } - } - #endregion - #region Transform-time helpers - /// - /// Write text directly into the generated output - /// - public void Write(string textToAppend) - { - if (string.IsNullOrEmpty(textToAppend)) - { - return; - } - // If we're starting off, or if the previous text ended with a newline, - // we have to append the current indent first. - if (((this.GenerationEnvironment.Length == 0) - || this.endsWithNewline)) - { - this.GenerationEnvironment.Append(this.currentIndentField); - this.endsWithNewline = false; - } - // Check if the current text ends with a newline - if (textToAppend.EndsWith(global::System.Environment.NewLine, global::System.StringComparison.CurrentCulture)) - { - this.endsWithNewline = true; - } - // This is an optimization. If the current indent is "", then we don't have to do any - // of the more complex stuff further down. - if ((this.currentIndentField.Length == 0)) - { - this.GenerationEnvironment.Append(textToAppend); - return; - } - // Everywhere there is a newline in the text, add an indent after it - textToAppend = textToAppend.Replace(global::System.Environment.NewLine, (global::System.Environment.NewLine + this.currentIndentField)); - // If the text ends with a newline, then we should strip off the indent added at the very end - // because the appropriate indent will be added when the next time Write() is called - if (this.endsWithNewline) - { - this.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - this.currentIndentField.Length)); - } - else - { - this.GenerationEnvironment.Append(textToAppend); - } - } - /// - /// Write text directly into the generated output - /// - public void WriteLine(string textToAppend) - { - this.Write(textToAppend); - this.GenerationEnvironment.AppendLine(); - this.endsWithNewline = true; - } - /// - /// Write formatted text directly into the generated output - /// - public void Write(string format, params object[] args) - { - this.Write(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args)); - } - /// - /// Write formatted text directly into the generated output - /// - public void WriteLine(string format, params object[] args) - { - this.WriteLine(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args)); - } - /// - /// Raise an error - /// - public void Error(string message) - { - System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError(); - error.ErrorText = message; - this.Errors.Add(error); - } - /// - /// Raise a warning - /// - public void Warning(string message) - { - System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError(); - error.ErrorText = message; - error.IsWarning = true; - this.Errors.Add(error); - } - /// - /// Increase the indent - /// - public void PushIndent(string indent) - { - if ((indent == null)) - { - throw new global::System.ArgumentNullException("indent"); - } - this.currentIndentField = (this.currentIndentField + indent); - this.indentLengths.Add(indent.Length); - } - /// - /// Remove the last indent that was added with PushIndent - /// - public string PopIndent() - { - string returnValue = ""; - if ((this.indentLengths.Count > 0)) - { - int indentLength = this.indentLengths[(this.indentLengths.Count - 1)]; - this.indentLengths.RemoveAt((this.indentLengths.Count - 1)); - if ((indentLength > 0)) - { - returnValue = this.currentIndentField.Substring((this.currentIndentField.Length - indentLength)); - this.currentIndentField = this.currentIndentField.Remove((this.currentIndentField.Length - indentLength)); - } - } - return returnValue; - } - /// - /// Remove any indentation - /// - public void ClearIndent() - { - this.indentLengths.Clear(); - this.currentIndentField = ""; - } - #endregion - #region ToString Helpers - /// - /// Utility class to produce culture-oriented representation of an object as a string. - /// - public class ToStringInstanceHelper - { - private System.IFormatProvider formatProviderField = global::System.Globalization.CultureInfo.InvariantCulture; - /// - /// Gets or sets format provider to be used by ToStringWithCulture method. - /// - public System.IFormatProvider FormatProvider - { - get - { - return this.formatProviderField ; - } - set - { - if ((value != null)) - { - this.formatProviderField = value; - } - } - } - /// - /// This is called from the compile/run appdomain to convert objects within an expression block to a string - /// - public string ToStringWithCulture(object objectToConvert) - { - if ((objectToConvert == null)) - { - throw new global::System.ArgumentNullException("objectToConvert"); - } - System.Type t = objectToConvert.GetType(); - System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] { - typeof(System.IFormatProvider)}); - if ((method == null)) - { - return objectToConvert.ToString(); - } - else - { - return ((string)(method.Invoke(objectToConvert, new object[] { - this.formatProviderField }))); - } - } - } - private ToStringInstanceHelper toStringHelperField = new ToStringInstanceHelper(); - /// - /// Helper to produce culture-oriented representation of an object as a string - /// - public ToStringInstanceHelper ToStringHelper - { - get - { - return this.toStringHelperField; - } - } - #endregion - } - #endregion -} diff --git a/src/Interop/LlvmBindingsGenerator/Templates/T4/ExportsTemplate.tt b/src/Interop/LlvmBindingsGenerator/Templates/T4/ExportsTemplate.tt deleted file mode 100644 index 0c2ef3df4a..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Templates/T4/ExportsTemplate.tt +++ /dev/null @@ -1,33 +0,0 @@ -<#@ template language="C#" visibility="internal" #> -<#@ assembly name="System.Core" #> -<#@ import namespace="System.Linq" #> -<#@ import namespace="System.Text" #> -<#@ import namespace="System.Collections.Generic" #> -;; ------------------------------------------------------------------------------ -;; -;; This file was generated by a tool. -;; Runtime Version: <#=ToolVersion#> -;; -;; Changes to this file may cause incorrect behavior and will be lost if -;; the code is regenerated. -;; -;; ------------------------------------------------------------------------------ -EXPORTS -; Custom Extension APIs for Ubiquity.NET.Llvm -<#foreach(var func in ExtensionFunctions) {#> -<#=func.Name#> -<#}#> - -; Inlined Functions in LLVM Headers wrapped as non-inlined *Export functions in LibLLVM -<#foreach(var inlineFunc in InlinedFunctions) {#> -<#=inlineFunc.Name#> = <#=inlineFunc.Name#>Export -<#}#> - -; Standard Official LLVM-C APIs -; If LibLLCVM-C.lib is available, these could be generated to forward to that -; or left out completely and use it directly from managed interop code -; A Major problem with that is that it loses ALL access to the C++ as that is -; NOT exported (and should never be as it isn't ABI stable) -<#foreach(var func in LlvmFunctions) {#> -<#=func.Name#> -<#}#> diff --git a/src/Interop/LlvmBindingsGenerator/Templates/T4/GlobalHandleTemplate.cs b/src/Interop/LlvmBindingsGenerator/Templates/T4/GlobalHandleTemplate.cs deleted file mode 100644 index 590b4b4150..0000000000 --- a/src/Interop/LlvmBindingsGenerator/Templates/T4/GlobalHandleTemplate.cs +++ /dev/null @@ -1,474 +0,0 @@ -// ------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version: 17.0.0.0 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -// ------------------------------------------------------------------------------ -namespace LlvmBindingsGenerator.Templates -{ - using System.Linq; - using System.Text; - using System.Collections.Generic; - using System; - - /// - /// Class to produce the template output - /// - - #line 1 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\GlobalHandleTemplate.tt" - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")] - internal partial class GlobalHandleTemplate : GlobalHandleTemplateBase - { -#line hidden - /// - /// Create the template output - /// - public virtual string TransformText() - { - this.Write("// ------------------------------------------------------------------------------" + - "\r\n// \r\n// This code was generated by a tool. [LlvmBindingsGe" + - "nerator]\r\n// Tool Version: "); - - #line 9 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\GlobalHandleTemplate.tt" - this.Write(this.ToStringHelper.ToStringWithCulture(ToolVersion)); - - #line default - #line hidden - this.Write(@" -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -// ------------------------------------------------------------------------------ -#nullable enable - -using System.CodeDom.Compiler; - -namespace Ubiquity.NET.Llvm.Interop -{ - /// Global LLVM object handle - [GeneratedCode(""LlvmBindingsGenerator"","""); - - #line 22 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\GlobalHandleTemplate.tt" - this.Write(this.ToStringHelper.ToStringWithCulture(ToolVersion)); - - #line default - #line hidden - this.Write("\")]\r\n public class "); - - #line 23 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\GlobalHandleTemplate.tt" - this.Write(this.ToStringHelper.ToStringWithCulture(HandleName)); - - #line default - #line hidden - this.Write("\r\n : GlobalHandleBase\r\n , IEquatable<"); - - #line 25 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\GlobalHandleTemplate.tt" - this.Write(this.ToStringHelper.ToStringWithCulture(HandleName)); - - #line default - #line hidden - this.Write(">\r\n {\r\n /// Initializes an instance of \r\n public "); - - #line 28 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\GlobalHandleTemplate.tt" - this.Write(this.ToStringHelper.ToStringWithCulture(HandleName)); - - #line default - #line hidden - this.Write("()\r\n : base(ownsHandle: true)\r\n {\r\n }\r\n\r\n /// Initializes an instance of