Browse Source

Code cleanup

pull/1904/head
duckdoom5 5 months ago
parent
commit
5fe36c080a
  1. 4
      src/AST/Function.cs
  2. 2
      src/AST/FunctionExtensions.cs
  3. 25
      src/AST/Method.cs
  4. 4
      src/AST/Property.cs
  5. 2
      src/CppParser/Helpers.h
  6. 4
      src/Generator/AST/Utils.cs
  7. 4
      src/Generator/Generators/CSharp/CSharpSources.cs
  8. 2
      src/Generator/Passes/CheckIgnoredDecls.cs
  9. 8
      src/Generator/Passes/FieldToPropertyPass.cs
  10. 2
      src/Generator/Passes/FixDefaultParamValuesOfOverridesPass.cs
  11. 2
      src/Generator/Passes/GetterSetterToPropertyPass.cs
  12. 25
      src/Generator/Types/Std/Stdlib.CSharp.cs
  13. 7
      src/Generator/Types/TypeMapDatabase.cs
  14. 2
      src/Parser/ASTConverter.cs

4
src/AST/Function.cs

@ -144,7 +144,7 @@ namespace CppSharp.AST
DefaultValueOverload, DefaultValueOverload,
InterfaceInstance, InterfaceInstance,
InterfaceDispose, InterfaceDispose,
FieldAcessor FieldAccessor
} }
public enum FriendKind public enum FriendKind
@ -260,7 +260,7 @@ namespace CppSharp.AST
} }
public FunctionSynthKind SynthKind { get; set; } public FunctionSynthKind SynthKind { get; set; }
public bool IsSynthetized => SynthKind != FunctionSynthKind.None; public bool IsSynthesized => SynthKind != FunctionSynthKind.None;
public bool IsNonMemberOperator { get; set; } public bool IsNonMemberOperator { get; set; }
public Function OriginalFunction { get; set; } public Function OriginalFunction { get; set; }

2
src/AST/FunctionExtensions.cs

@ -98,7 +98,7 @@ namespace CppSharp.AST
Class @class = (Class)(method.OriginalFunction ?? method).Namespace; Class @class = (Class)(method.OriginalFunction ?? method).Namespace;
// virtual functions cannot really be inlined and // virtual functions cannot really be inlined and
// we don't need their symbols anyway as we call them through the v-table // we don't need their symbols anyway as we call them through the v-table
return (!method.IsVirtual && !method.IsSynthetized && return (!method.IsVirtual && !method.IsSynthesized &&
!method.IsDefaultConstructor && !method.IsCopyConstructor && !method.IsDestructor) || !method.IsDefaultConstructor && !method.IsCopyConstructor && !method.IsDestructor) ||
(method.IsDefaultConstructor && @class.HasNonTrivialDefaultConstructor) || (method.IsDefaultConstructor && @class.HasNonTrivialDefaultConstructor) ||
(method.IsCopyConstructor && @class.HasNonTrivialCopyConstructor) || (method.IsCopyConstructor && @class.HasNonTrivialCopyConstructor) ||

25
src/AST/Method.cs

@ -123,10 +123,11 @@ namespace CppSharp.AST
public bool IsExplicit { get; set; } public bool IsExplicit { get; set; }
public bool IsVolatile { get; set; } public bool IsVolatile { get; set; }
private bool? isOverride;
public bool IsOverride public bool IsOverride
{ {
get { return isOverride ?? OverriddenMethods.Any(); } get => isOverride ?? OverriddenMethods.Any();
set { isOverride = value; } set => isOverride = value;
} }
public Method BaseMethod => OverriddenMethods.FirstOrDefault(); public Method BaseMethod => OverriddenMethods.FirstOrDefault();
@ -141,7 +142,7 @@ namespace CppSharp.AST
private CXXMethodKind kind; private CXXMethodKind kind;
public CXXMethodKind Kind public CXXMethodKind Kind
{ {
get { return kind; } get => kind;
set set
{ {
if (kind != value) if (kind != value)
@ -153,15 +154,9 @@ namespace CppSharp.AST
} }
} }
public bool IsConstructor public bool IsConstructor => Kind == CXXMethodKind.Constructor;
{
get { return Kind == CXXMethodKind.Constructor; }
}
public bool IsDestructor public bool IsDestructor => Kind == CXXMethodKind.Destructor;
{
get { return Kind == CXXMethodKind.Destructor; }
}
public bool IsDefaultConstructor; public bool IsDefaultConstructor;
public bool IsCopyConstructor; public bool IsCopyConstructor;
@ -175,13 +170,13 @@ namespace CppSharp.AST
public int AdjustedOffset { get; set; } public int AdjustedOffset { get; set; }
public List<Method> OverriddenMethods { get; } = new List<Method>(); public List<Method> OverriddenMethods { get; } = new();
public bool ConvertToProperty { get; set; } public bool ConvertToProperty { get; set; }
public Method GetRootBaseMethod() public Method GetRootBaseMethod()
{ {
return BaseMethod == null || BaseMethod.BaseMethod == null ? return BaseMethod?.BaseMethod == null ?
BaseMethod : BaseMethod.GetRootBaseMethod(); BaseMethod : BaseMethod.GetRootBaseMethod();
} }
@ -189,9 +184,7 @@ namespace CppSharp.AST
{ {
return visitor.VisitMethodDecl(this); return visitor.VisitMethodDecl(this);
} }
private bool? isOverride;
public bool HasSameSignature(Method other) public bool HasSameSignature(Method other)
{ {
return Parameters.SequenceEqual(other.Parameters, ParameterTypeComparer.Instance); return Parameters.SequenceEqual(other.Parameters, ParameterTypeComparer.Instance);

4
src/AST/Property.cs

@ -76,8 +76,8 @@ namespace CppSharp.AST
GetMethod is {OperatorKind: CXXOperatorKind.Subscript}; GetMethod is {OperatorKind: CXXOperatorKind.Subscript};
public bool IsSynthetized => public bool IsSynthetized =>
(GetMethod != null && GetMethod.IsSynthetized) || (GetMethod != null && GetMethod.IsSynthesized) ||
(SetMethod != null && SetMethod.IsSynthetized); (SetMethod != null && SetMethod.IsSynthesized);
public override T Visit<T>(IDeclVisitor<T> visitor) public override T Visit<T>(IDeclVisitor<T> visitor)
{ {

2
src/CppParser/Helpers.h

@ -50,6 +50,6 @@
#define DEF_VECTOR_STRING(klass, name) \ #define DEF_VECTOR_STRING(klass, name) \
const char* klass::get##name (unsigned i) { return name[i].c_str(); } \ const char* klass::get##name (unsigned i) { return name[i].c_str(); } \
void klass::add##name (const char* s) { return name.push_back(std::string(s)); } \ void klass::add##name (const char* s) { name.push_back(std::string(s)); } \
unsigned klass::get##name##Count () { return name.size(); } \ unsigned klass::get##name##Count () { return name.size(); } \
void klass::clear##name() { name.clear(); } void klass::clear##name() { name.clear(); }

4
src/Generator/AST/Utils.cs

@ -42,7 +42,7 @@ namespace CppSharp.AST
if (method.Access == AccessSpecifier.Private && !method.IsOverride && !method.IsExplicitlyGenerated) if (method.Access == AccessSpecifier.Private && !method.IsOverride && !method.IsExplicitlyGenerated)
return true; return true;
// Ignore copy constructor if a base class don't has or has a private copy constructor // Ignore copy constructor if a base class don't have a copy constructor (or it's private)
if (method.IsCopyConstructor) if (method.IsCopyConstructor)
{ {
var baseClass = @class; var baseClass = @class;
@ -329,7 +329,7 @@ namespace CppSharp.AST
case CXXOperatorKind.Array_New: case CXXOperatorKind.Array_New:
case CXXOperatorKind.Array_Delete: case CXXOperatorKind.Array_Delete:
isBuiltin = false; isBuiltin = false;
return "Operator" + kind.ToString(); return "Operator" + kind;
case CXXOperatorKind.Conversion: case CXXOperatorKind.Conversion:
return "implicit operator"; return "implicit operator";

4
src/Generator/Generators/CSharp/CSharpSources.cs

@ -263,7 +263,7 @@ namespace CppSharp.Generators.CSharp
// Generate all the internal function declarations. // Generate all the internal function declarations.
foreach (var function in context.Functions) foreach (var function in context.Functions)
{ {
if ((!function.IsGenerated && !function.IsInternal) || function.IsSynthetized) if ((!function.IsGenerated && !function.IsInternal) || function.IsSynthesized)
continue; continue;
GenerateInternalFunction(function); GenerateInternalFunction(function);
@ -631,7 +631,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
{ {
Action<Method> tryAddOverload = method => Action<Method> tryAddOverload = method =>
{ {
if (method.IsSynthetized) if (method.IsSynthesized)
return; return;
if (method.IsProxy || if (method.IsProxy ||

2
src/Generator/Passes/CheckIgnoredDecls.cs

@ -161,7 +161,7 @@ namespace CppSharp.Passes
public override bool VisitFunctionDecl(Function function) public override bool VisitFunctionDecl(Function function)
{ {
if (!base.VisitFunctionDecl(function) || function.IsSynthetized if (!base.VisitFunctionDecl(function) || function.IsSynthesized
|| function.IsExplicitlyGenerated) || function.IsExplicitlyGenerated)
return false; return false;

8
src/Generator/Passes/FieldToPropertyPass.cs

@ -56,7 +56,7 @@ namespace CppSharp.Passes
if (Options.GeneratorKind == GeneratorKind.C || if (Options.GeneratorKind == GeneratorKind.C ||
Options.GeneratorKind == GeneratorKind.CPlusPlus) Options.GeneratorKind == GeneratorKind.CPlusPlus)
GenerateAcessorMethods(field, prop); GenerateAccessorMethods(field, prop);
// do not rename value-class fields because they would be // do not rename value-class fields because they would be
// generated as fields later on even though they are wrapped by properties; // generated as fields later on even though they are wrapped by properties;
@ -72,7 +72,7 @@ namespace CppSharp.Passes
return false; return false;
} }
private void GenerateAcessorMethods(Field field, Property property) private void GenerateAccessorMethods(Field field, Property property)
{ {
var @class = field.Namespace as Class; var @class = field.Namespace as Class;
@ -84,7 +84,7 @@ namespace CppSharp.Passes
Access = field.Access, Access = field.Access,
AssociatedDeclaration = property, AssociatedDeclaration = property,
IsStatic = field.IsStatic, IsStatic = field.IsStatic,
SynthKind = FunctionSynthKind.FieldAcessor SynthKind = FunctionSynthKind.FieldAccessor
}; };
property.GetMethod = getter; property.GetMethod = getter;
@ -101,7 +101,7 @@ namespace CppSharp.Passes
Access = field.Access, Access = field.Access,
AssociatedDeclaration = property, AssociatedDeclaration = property,
IsStatic = field.IsStatic, IsStatic = field.IsStatic,
SynthKind = FunctionSynthKind.FieldAcessor SynthKind = FunctionSynthKind.FieldAccessor
}; };
var param = new Parameter var param = new Parameter

2
src/Generator/Passes/FixDefaultParamValuesOfOverridesPass.cs

@ -7,7 +7,7 @@ namespace CppSharp.Passes
{ {
public override bool VisitMethodDecl(Method method) public override bool VisitMethodDecl(Method method)
{ {
if (!method.IsOverride || method.IsSynthetized) if (!method.IsOverride || method.IsSynthesized)
return true; return true;
Method rootBaseMethod = method.GetRootBaseMethod(); Method rootBaseMethod = method.GetRootBaseMethod();

2
src/Generator/Passes/GetterSetterToPropertyPass.cs

@ -92,7 +92,7 @@ namespace CppSharp.Passes
m.OriginalFunction != null) && m.OriginalFunction != null) &&
m.SynthKind != FunctionSynthKind.DefaultValueOverload && m.SynthKind != FunctionSynthKind.DefaultValueOverload &&
m.SynthKind != FunctionSynthKind.ComplementOperator && m.SynthKind != FunctionSynthKind.ComplementOperator &&
m.SynthKind != FunctionSynthKind.FieldAcessor && m.SynthKind != FunctionSynthKind.FieldAccessor &&
!m.ExcludeFromPasses.Contains(typeof(GetterSetterToPropertyPass)))) !m.ExcludeFromPasses.Contains(typeof(GetterSetterToPropertyPass))))
{ {
if (IsGetter(method)) if (IsGetter(method))

25
src/Generator/Types/Std/Stdlib.CSharp.cs

@ -166,10 +166,10 @@ namespace CppSharp.Types.Std.CSharp
switch (encodingName) switch (encodingName)
{ {
case nameof(Encoding.Unicode): case nameof(Encoding.Unicode):
ctx.Before.WriteLine($@"var {bytePtr} = Marshal.StringToHGlobalUni({param});"); ctx.Before.WriteLine($"var {bytePtr} = Marshal.StringToHGlobalUni({param});");
break; break;
case nameof(Encoding.Default): case nameof(Encoding.Default):
ctx.Before.WriteLine($@"var {bytePtr} = Marshal.StringToHGlobalAnsi({param});"); ctx.Before.WriteLine($"var {bytePtr} = Marshal.StringToHGlobalAnsi({param});");
break; break;
default: default:
{ {
@ -183,8 +183,8 @@ namespace CppSharp.Types.Std.CSharp
$"Encoding bytes per char: {encodingBytesPerChar} is not implemented.") $"Encoding bytes per char: {encodingBytesPerChar} is not implemented.")
}; };
ctx.Before.WriteLine($@"var {bytes} = global::System.Text.Encoding.{encodingName}.GetBytes({param});"); ctx.Before.WriteLine($"var {bytes} = global::System.Text.Encoding.{encodingName}.GetBytes({param});");
ctx.Before.WriteLine($@"var {bytePtr} = Marshal.AllocHGlobal({bytes}.Length + {encodingBytesPerChar});"); ctx.Before.WriteLine($"var {bytePtr} = Marshal.AllocHGlobal({bytes}.Length + {encodingBytesPerChar});");
ctx.Before.WriteLine($"Marshal.Copy({bytes}, 0, {bytePtr}, {bytes}.Length);"); ctx.Before.WriteLine($"Marshal.Copy({bytes}, 0, {bytePtr}, {bytes}.Length);");
ctx.Before.WriteLine($"Marshal.{writeNulMethod}({bytePtr} + {bytes}.Length, 0);"); ctx.Before.WriteLine($"Marshal.{writeNulMethod}({bytePtr} + {bytes}.Length, 0);");
} }
@ -196,8 +196,7 @@ namespace CppSharp.Types.Std.CSharp
public override void MarshalToManaged(MarshalContext ctx) public override void MarshalToManaged(MarshalContext ctx)
{ {
if (ctx.Parameter != null && !ctx.Parameter.IsOut && if (ctx.Parameter is { IsOut: false, IsInOut: false })
!ctx.Parameter.IsInOut)
{ {
ctx.Return.Write(ctx.Parameter.Name); ctx.Return.Write(ctx.Parameter.Name);
return; return;
@ -215,7 +214,7 @@ namespace CppSharp.Types.Std.CSharp
} }
var encoding = $"global::System.Text.Encoding.{GetEncoding().Name}"; var encoding = $"global::System.Text.Encoding.{GetEncoding().Name}";
ctx.Return.Write($@"CppSharp.Runtime.MarshalUtil.GetString({encoding}, {returnVarName})"); ctx.Return.Write($"CppSharp.Runtime.MarshalUtil.GetString({encoding}, {returnVarName})");
} }
private (Encoding Encoding, string Name) GetEncoding() private (Encoding Encoding, string Name) GetEncoding()
@ -340,7 +339,7 @@ namespace CppSharp.Types.Std.CSharp
{ {
var = $"&{ctx.ReturnVarName}"; var = $"&{ctx.ReturnVarName}";
} }
ctx.Return.Write($@"{qualifiedBasicString}Extensions.{Helpers.InternalStruct}.{assign.Name}(new {typePrinter.IntPtrType}({var}), "); ctx.Return.Write($"{qualifiedBasicString}Extensions.{Helpers.InternalStruct}.{assign.Name}(new {typePrinter.IntPtrType}({var}), ");
if (ctx.Parameter.Type.IsTemplateParameterType()) if (ctx.Parameter.Type.IsTemplateParameterType())
ctx.Return.Write("(string) (object) "); ctx.Return.Write("(string) (object) ");
ctx.Return.Write($"{ctx.Parameter.Name})"); ctx.Return.Write($"{ctx.Parameter.Name})");
@ -349,15 +348,15 @@ namespace CppSharp.Types.Std.CSharp
else else
{ {
var varBasicString = $"__basicString{ctx.ParameterIndex}"; var varBasicString = $"__basicString{ctx.ParameterIndex}";
ctx.Before.WriteLine($@"var {varBasicString} = new {basicString.Visit(typePrinter)}();"); ctx.Before.WriteLine($"var {varBasicString} = new {basicString.Visit(typePrinter)}();");
ctx.Before.Write($@"{qualifiedBasicString}Extensions.{assign.Name}({varBasicString}, "); ctx.Before.Write($"{qualifiedBasicString}Extensions.{assign.Name}({varBasicString}, ");
if (ctx.Parameter.Type.IsTemplateParameterType()) if (ctx.Parameter.Type.IsTemplateParameterType())
ctx.Before.Write("(string) (object) "); ctx.Before.Write("(string) (object) ");
ctx.Before.WriteLine($"{ctx.Parameter.Name});"); ctx.Before.WriteLine($"{ctx.Parameter.Name});");
ctx.Return.Write($"{varBasicString}.{Helpers.InstanceIdentifier}"); ctx.Return.Write($"{varBasicString}.{Helpers.InstanceIdentifier}");
ctx.Cleanup.WriteLine($@"{varBasicString}.Dispose({(!Type.IsAddress() || ctx.Parameter?.IsIndirect == true ? "disposing: true, callNativeDtor:false" : string.Empty)});"); ctx.Cleanup.WriteLine($"{varBasicString}.Dispose({(!Type.IsAddress() || ctx.Parameter?.IsIndirect == true ? "disposing: true, callNativeDtor:false" : string.Empty)});");
} }
} }
@ -371,7 +370,7 @@ namespace CppSharp.Types.Std.CSharp
string varBasicString = $"__basicStringRet{ctx.ParameterIndex}"; string varBasicString = $"__basicStringRet{ctx.ParameterIndex}";
bool usePointer = type.IsAddress() || ctx.MarshalKind == MarshalKind.NativeField || bool usePointer = type.IsAddress() || ctx.MarshalKind == MarshalKind.NativeField ||
ctx.MarshalKind == MarshalKind.ReturnVariableArray; ctx.MarshalKind == MarshalKind.ReturnVariableArray;
ctx.Before.WriteLine($@"var {varBasicString} = {basicString.Visit(typePrinter)}.{Helpers.CreateInstanceIdentifier}({(usePointer ? string.Empty : $"new {typePrinter.IntPtrType}(&")}{ctx.ReturnVarName}{(usePointer ? string.Empty : ")")});"); ctx.Before.WriteLine($"var {varBasicString} = {basicString.Visit(typePrinter)}.{Helpers.CreateInstanceIdentifier}({(usePointer ? string.Empty : $"new {typePrinter.IntPtrType}(&")}{ctx.ReturnVarName}{(usePointer ? string.Empty : ")")});");
string @string = $"{qualifiedBasicString}Extensions.{data.Name}({varBasicString})"; string @string = $"{qualifiedBasicString}Extensions.{data.Name}({varBasicString})";
if (usePointer) if (usePointer)
{ {
@ -392,7 +391,7 @@ namespace CppSharp.Types.Std.CSharp
var names = new Stack<string>(); var names = new Stack<string>();
while (!(declContext is TranslationUnit)) while (!(declContext is TranslationUnit))
{ {
var isInlineNamespace = declContext is Namespace && ((Namespace)declContext).IsInline; var isInlineNamespace = declContext is Namespace { IsInline: true };
if (!isInlineNamespace) if (!isInlineNamespace)
names.Push(declContext.Name); names.Push(declContext.Name);
declContext = declContext.Namespace; declContext = declContext.Namespace;

7
src/Generator/Types/TypeMapDatabase.cs

@ -52,15 +52,14 @@ namespace CppSharp.Types
{ {
var typeMaps = TypeMapsByKind(typeMapsCache, kind); var typeMaps = TypeMapsByKind(typeMapsCache, kind);
// Looks up the type in the cache map. // Looks up the type in the cache map.
if (typeMaps.ContainsKey(type)) if (typeMaps.TryGetValue(type, out TypeMap map))
{ {
typeMap = typeMaps[type]; typeMap = map;
typeMap.Type = type; typeMap.Type = type;
return typeMap.IsEnabled; return typeMap.IsEnabled;
} }
var template = type as TemplateSpecializationType; if (type is TemplateSpecializationType template)
if (template != null)
{ {
var specialization = template.GetClassTemplateSpecialization(); var specialization = template.GetClassTemplateSpecialization();
if (specialization != null && if (specialization != null &&

2
src/Parser/ASTConverter.cs

@ -1457,7 +1457,7 @@ namespace CppSharp
case CXXOperatorKind.Coawait: case CXXOperatorKind.Coawait:
return AST.CXXOperatorKind.Coawait; return AST.CXXOperatorKind.Coawait;
default: default:
throw new ArgumentOutOfRangeException("operatorKind"); throw new ArgumentOutOfRangeException(nameof(operatorKind));
} }
} }

Loading…
Cancel
Save