Browse Source

Format files

295227ce-f4a3-466b-a694-65c571873871
josetr 3 years ago
parent
commit
eb5031bf4c
  1. 2
      src/AST/ASTContext.cs
  2. 10
      src/AST/ASTVisitor.cs
  3. 2
      src/AST/ClassExtensions.cs
  4. 2
      src/AST/ClassLayout.cs
  5. 76
      src/AST/Comment.cs
  6. 8
      src/AST/Declaration.cs
  7. 4
      src/AST/DeclarationsList.cs
  8. 2
      src/AST/Field.cs
  9. 48
      src/AST/FunctionExtensions.cs
  10. 2
      src/AST/Method.cs
  11. 16
      src/AST/Namespace.cs
  12. 6
      src/AST/Property.cs
  13. 2
      src/AST/PropertyExtensions.cs
  14. 16
      src/AST/Template.cs
  15. 78
      src/AST/Type.cs
  16. 26
      src/AST/TypeExtensions.cs
  17. 60
      src/CLI/CLI.cs
  18. 8
      src/CLI/Generator.cs
  19. 2
      src/CLI/Options.cs
  20. 2
      src/Core/Compilation.cs
  21. 4
      src/Core/Diagnostics.cs
  22. 6
      src/Core/Platform.cs
  23. 4
      src/Core/Toolchains/MSVCToolchain.cs
  24. 8
      src/Core/Toolchains/ManagedToolchain.cs
  25. 19
      src/Core/Toolchains/XcodeToolchain.cs
  26. 2
      src/CppParser/Bootstrap/Bootstrap.cs
  27. 16
      src/Generator.Tests/AST/TestAST.cs
  28. 2
      src/Generator.Tests/ASTTestFixture.cs
  29. 2
      src/Generator.Tests/Passes/TestPasses.cs
  30. 2
      src/Generator.Tests/ReadNativeSymbolsTest.cs
  31. 12
      src/Generator/AST/ASTRecord.cs
  32. 4
      src/Generator/AST/Utils.cs
  33. 12
      src/Generator/AST/VTables.cs
  34. 2
      src/Generator/Extensions/FunctionExtensions.cs
  35. 4
      src/Generator/Generator.cs
  36. 8
      src/Generator/Generators/C/CCodeGenerator.cs
  37. 12
      src/Generator/Generators/C/CppHeaders.cs
  38. 108
      src/Generator/Generators/C/CppMarshal.cs
  39. 14
      src/Generator/Generators/C/CppSources.cs
  40. 162
      src/Generator/Generators/C/CppTypePrinter.cs
  41. 12
      src/Generator/Generators/CLI/CLIHeaders.cs
  42. 34
      src/Generator/Generators/CLI/CLIMarshal.cs
  43. 90
      src/Generator/Generators/CLI/CLISources.cs
  44. 2
      src/Generator/Generators/CLI/CLITemplate.cs
  45. 8
      src/Generator/Generators/CLI/CLITypePrinter.cs
  46. 6
      src/Generator/Generators/CLI/CLITypeReferences.cs
  47. 12
      src/Generator/Generators/CSharp/CSharpCommentPrinter.cs
  48. 8
      src/Generator/Generators/CSharp/CSharpExpressionPrinter.cs
  49. 4
      src/Generator/Generators/CSharp/CSharpMarshal.cs
  50. 117
      src/Generator/Generators/CSharp/CSharpSources.cs
  51. 28
      src/Generator/Generators/CSharp/CSharpTypePrinter.cs
  52. 8
      src/Generator/Generators/CodeGenerator.cs
  53. 8
      src/Generator/Generators/ITypePrinter.cs
  54. 476
      src/Generator/Generators/NAPI/NAPIMarshal.cs
  55. 8
      src/Generator/Generators/NAPI/NAPISources.cs
  56. 88
      src/Generator/Generators/NAPI/NAPITypeCheckGen.cs
  57. 26
      src/Generator/Generators/NAPI/NAPITypeCheckPass.cs
  58. 2
      src/Generator/Generators/QuickJS/QuickJSHeaders.cs
  59. 272
      src/Generator/Generators/QuickJS/QuickJSMarshal.cs
  60. 24
      src/Generator/Generators/QuickJS/QuickJSSources.cs
  61. 116
      src/Generator/Generators/QuickJS/QuickJSTypeCheckGen.cs
  62. 6
      src/Generator/Generators/TS/TSSources.cs
  63. 38
      src/Generator/Generators/TS/TSTypePrinter.cs
  64. 10
      src/Generator/Library.cs
  65. 20
      src/Generator/Passes/CheckAbiParameters.cs
  66. 4
      src/Generator/Passes/CheckAmbiguousFunctions.cs
  67. 8
      src/Generator/Passes/CheckIgnoredDecls.cs
  68. 2
      src/Generator/Passes/CheckMacrosPass.cs
  69. 34
      src/Generator/Passes/CheckOperatorsOverloads.cs
  70. 4
      src/Generator/Passes/CheckStaticClass.cs
  71. 4
      src/Generator/Passes/CleanCommentsPass.cs
  72. 12
      src/Generator/Passes/ConstructorToConversionOperatorPass.cs
  73. 36
      src/Generator/Passes/DelegatesPass.cs
  74. 2
      src/Generator/Passes/ExpressionHelper.cs
  75. 16
      src/Generator/Passes/FlattenAnonymousTypesToFields.cs
  76. 30
      src/Generator/Passes/FunctionToInstanceMethodPass.cs
  77. 26
      src/Generator/Passes/GenerateAbstractImplementationsPass.cs
  78. 4
      src/Generator/Passes/GenerateSymbolsPass.cs
  79. 10
      src/Generator/Passes/GetterSetterToPropertyPass.cs
  80. 2
      src/Generator/Passes/HandleDefaultParamValuesPass.cs
  81. 2
      src/Generator/Passes/MakeProtectedNestedTypesPublicPass.cs
  82. 4
      src/Generator/Passes/MultipleInheritancePass.cs
  83. 2
      src/Generator/Passes/ParamTypeToInterfacePass.cs
  84. 38
      src/Generator/Passes/Pass.cs
  85. 32
      src/Generator/Passes/RenamePass.cs
  86. 4
      src/Generator/Passes/SpecializationMethodsWithDependentPointersPass.cs
  87. 10
      src/Generator/Passes/SymbolsCodeGenerator.cs
  88. 2
      src/Generator/Passes/ValidateOperatorsPass.cs
  89. 2
      src/Generator/Types/DeclMapDatabase.cs
  90. 26
      src/Generator/Types/Std/Stdlib.CLI.cs
  91. 8
      src/Generator/Types/Std/Stdlib.CSharp.cs
  92. 68
      src/Generator/Types/TypeMap.cs
  93. 2
      src/Generator/Types/TypeMapDatabase.cs
  94. 8
      src/Generator/Utils/BlockGenerator.cs
  95. 14
      src/Generator/Utils/ExpressionEvaluator.cs
  96. 35
      src/Generator/Utils/FSM/ConsoleWriter.cs
  97. 262
      src/Generator/Utils/FSM/DFSM.cs
  98. 128
      src/Generator/Utils/FSM/Minimize.cs
  99. 146
      src/Generator/Utils/FSM/NDFSM.cs
  100. 27
      src/Generator/Utils/FSM/Program.cs
  101. Some files were not shown because too many files have changed in this diff Show More

2
src/AST/ASTContext.cs

@ -144,7 +144,7 @@ namespace CppSharp.AST @@ -144,7 +144,7 @@ namespace CppSharp.AST
public void SetEnumAsFlags(string name)
{
var enums = FindEnum(name);
foreach(var @enum in enums)
foreach (var @enum in enums)
@enum.SetFlags();
}

10
src/AST/ASTVisitor.cs

@ -438,7 +438,7 @@ namespace CppSharp.AST @@ -438,7 +438,7 @@ namespace CppSharp.AST
{
if (property.GetMethod != null)
property.GetMethod.Visit(this);
if (property.SetMethod != null)
property.SetMethod.Visit(this);
}
@ -478,8 +478,8 @@ namespace CppSharp.AST @@ -478,8 +478,8 @@ namespace CppSharp.AST
public virtual bool VisitParameterDecl(Parameter parameter)
{
if (!VisitDeclaration(parameter))
return false;
return false;
return parameter.Type.Visit(this, parameter.QualifiedType.Qualifiers);
}
@ -600,7 +600,7 @@ namespace CppSharp.AST @@ -600,7 +600,7 @@ namespace CppSharp.AST
template.TemplatedVariable.Visit(this);
return true;
return true;
}
public virtual bool VisitVarTemplateSpecializationDecl(VarTemplateSpecialization specialization)
@ -631,7 +631,7 @@ namespace CppSharp.AST @@ -631,7 +631,7 @@ namespace CppSharp.AST
if (VisitOptions.VisitNamespaceEnums)
foreach (var decl in context.Enums)
decl.Visit(this);
decl.Visit(this);
if (VisitOptions.VisitNamespaceTemplates)
foreach (var decl in context.Templates)

2
src/AST/ClassExtensions.cs

@ -39,7 +39,7 @@ namespace CppSharp.AST @@ -39,7 +39,7 @@ namespace CppSharp.AST
foreach (var @base in @class.Bases)
{
if (!@base.IsClass) continue;
foreach(var elem in @base.Class.FindHierarchy(func))
foreach (var elem in @base.Class.FindHierarchy(func))
yield return elem;
}
}

2
src/AST/ClassLayout.cs

@ -99,7 +99,7 @@ namespace CppSharp.AST @@ -99,7 +99,7 @@ namespace CppSharp.AST
/// Provides native argument ABI information.
public RecordArgABI ArgABI { get; set; }
/// Virtual function tables in Microsoft mode.
public List<VFTableInfo> VFTables { get; set; }

76
src/AST/Comment.cs

@ -131,17 +131,17 @@ namespace CppSharp.AST @@ -131,17 +131,17 @@ namespace CppSharp.AST
{
switch (kind)
{
case CommentKind.BCPL:
case CommentKind.BCPLExcl:
return "//";
case CommentKind.C:
case CommentKind.JavaDoc:
case CommentKind.Qt:
return " *";
case CommentKind.BCPLSlash:
return "///";
default:
throw new ArgumentOutOfRangeException();
case CommentKind.BCPL:
case CommentKind.BCPLExcl:
return "//";
case CommentKind.C:
case CommentKind.JavaDoc:
case CommentKind.Qt:
return " *";
case CommentKind.BCPLSlash:
return "///";
default:
throw new ArgumentOutOfRangeException();
}
}
@ -149,19 +149,19 @@ namespace CppSharp.AST @@ -149,19 +149,19 @@ namespace CppSharp.AST
{
switch (kind)
{
case CommentKind.BCPL:
case CommentKind.BCPLSlash:
return string.Empty;
case CommentKind.C:
return "/*";
case CommentKind.BCPLExcl:
return "//!";
case CommentKind.JavaDoc:
return "/**";
case CommentKind.Qt:
return "/*!";
default:
throw new ArgumentOutOfRangeException();
case CommentKind.BCPL:
case CommentKind.BCPLSlash:
return string.Empty;
case CommentKind.C:
return "/*";
case CommentKind.BCPLExcl:
return "//!";
case CommentKind.JavaDoc:
return "/**";
case CommentKind.Qt:
return "/*!";
default:
throw new ArgumentOutOfRangeException();
}
}
@ -169,16 +169,16 @@ namespace CppSharp.AST @@ -169,16 +169,16 @@ namespace CppSharp.AST
{
switch (kind)
{
case CommentKind.BCPL:
case CommentKind.BCPLSlash:
case CommentKind.BCPLExcl:
return string.Empty;
case CommentKind.C:
case CommentKind.JavaDoc:
case CommentKind.Qt:
return " */";
default:
throw new ArgumentOutOfRangeException();
case CommentKind.BCPL:
case CommentKind.BCPLSlash:
case CommentKind.BCPLExcl:
return string.Empty;
case CommentKind.C:
case CommentKind.JavaDoc:
case CommentKind.Qt:
return " */";
default:
throw new ArgumentOutOfRangeException();
}
}
}
@ -227,7 +227,7 @@ namespace CppSharp.AST @@ -227,7 +227,7 @@ namespace CppSharp.AST
public CommentCommandKind CommandKind
{
get { return (CommentCommandKind) CommandId; }
get { return (CommentCommandKind)CommandId; }
}
public ParagraphComment ParagraphComment { get; set; }
@ -310,7 +310,7 @@ namespace CppSharp.AST @@ -310,7 +310,7 @@ namespace CppSharp.AST
Kind = DocumentationCommentKind.TParamCommandComment;
Position = new List<uint>();
}
public override void Visit<T>(ICommentVisitor<T> visitor)
{
visitor.VisitTParamCommand(this);
@ -364,7 +364,7 @@ namespace CppSharp.AST @@ -364,7 +364,7 @@ namespace CppSharp.AST
public class ParagraphComment : BlockContentComment
{
public List<InlineContentComment> Content;
public bool IsWhitespace;
public ParagraphComment()
@ -489,7 +489,7 @@ namespace CppSharp.AST @@ -489,7 +489,7 @@ namespace CppSharp.AST
public CommentCommandKind CommandKind
{
get { return (CommentCommandKind) CommandId; }
get { return (CommentCommandKind)CommandId; }
}
public RenderKind CommentRenderKind;

8
src/AST/Declaration.cs

@ -115,7 +115,7 @@ namespace CppSharp.AST @@ -115,7 +115,7 @@ namespace CppSharp.AST
public int LineNumberEnd { get; set; }
public bool IsImplicit { get; set; }
public int AlignAs { get; set; }
public int MaxFieldAlignment { get; set; }
public int MaxFieldAlignment { get; set; }
private DeclarationContext @namespace;
public DeclarationContext OriginalNamespace;
@ -213,7 +213,7 @@ namespace CppSharp.AST @@ -213,7 +213,7 @@ namespace CppSharp.AST
var currentNamespace = @namespace;
while (currentNamespace != null)
{
var isInlineNamespace = currentNamespace is Namespace {IsInline: true};
var isInlineNamespace = currentNamespace is Namespace { IsInline: true };
if (!isInlineNamespace)
namespaces.Push(currentNamespace);
currentNamespace = currentNamespace.Namespace;
@ -242,7 +242,7 @@ namespace CppSharp.AST @@ -242,7 +242,7 @@ namespace CppSharp.AST
public string QualifiedLogicalName
{
get
{
{
return GetQualifiedName(
decl => GetDeclName(decl, decl.LogicalName), decl => decl.Namespace);
}
@ -295,7 +295,7 @@ namespace CppSharp.AST @@ -295,7 +295,7 @@ namespace CppSharp.AST
public ISet<System.Type> ExcludeFromPasses;
// List of preprocessed entities attached to this declaration.
public IList<PreprocessedEntity> PreprocessedEntities;
public IList<PreprocessedEntity> PreprocessedEntities;
// Pointer to the original declaration from Clang.
public IntPtr OriginalPtr;

4
src/AST/DeclarationsList.cs

@ -82,7 +82,7 @@ namespace CppSharp.AST @@ -82,7 +82,7 @@ namespace CppSharp.AST
var offset = offsets[kind];
for (var i = GetStart(kind); i < offset; i++)
{
yield return (T) this[i];
yield return (T)this[i];
}
}
@ -99,7 +99,7 @@ namespace CppSharp.AST @@ -99,7 +99,7 @@ namespace CppSharp.AST
Variable _ => Kind.Variable,
Friend _ => Kind.Friend,
Event _ => Kind.Event,
_ => throw new System.ArgumentOutOfRangeException(nameof(item), "Unsupported type of declaration.")
_ => throw new System.ArgumentOutOfRangeException(nameof(item), "Unsupported type of declaration.")
};
}

2
src/AST/Field.cs

@ -28,7 +28,7 @@ namespace CppSharp.AST @@ -28,7 +28,7 @@ namespace CppSharp.AST
Access = access;
}
public Field(Field field): base(field)
public Field(Field field) : base(field)
{
QualifiedType = field.QualifiedType;
Class = field.Class;

48
src/AST/FunctionExtensions.cs

@ -20,11 +20,11 @@ namespace CppSharp.AST @@ -20,11 +20,11 @@ namespace CppSharp.AST
(!isItaniumLikeAbi || !function.HasIndirectReturnTypeParameter))
{
@params.Add(new Parameter
{
QualifiedType = pointer,
Name = "__instance",
Namespace = function
});
{
QualifiedType = pointer,
Name = "__instance",
Namespace = function
});
}
var i = 0;
@ -32,40 +32,40 @@ namespace CppSharp.AST @@ -32,40 +32,40 @@ namespace CppSharp.AST
p => p.Kind != ParameterKind.OperatorParameter && p.Kind != ParameterKind.Extension))
{
@params.Add(new Parameter
{
QualifiedType = universalDelegate &&
{
QualifiedType = universalDelegate &&
(param.Kind == ParameterKind.IndirectReturnType ||
param.Type.Desugar().IsPointerTo(out FunctionType functionType)) ?
pointer : param.QualifiedType,
Kind = param.Kind,
Usage = param.Usage,
Name = universalDelegate ? $"arg{++i}": param.Name,
Namespace = param.Namespace
});
Kind = param.Kind,
Usage = param.Usage,
Name = universalDelegate ? $"arg{++i}" : param.Name,
Namespace = param.Namespace
});
if (param.Kind == ParameterKind.IndirectReturnType &&
isInstanceMethod && isItaniumLikeAbi)
{
@params.Add(new Parameter
{
QualifiedType = pointer,
Name = "__instance",
Namespace = function
});
{
QualifiedType = pointer,
Name = "__instance",
Namespace = function
});
}
}
if (method != null && method.IsConstructor)
{
var @class = (Class) method.Namespace;
var @class = (Class)method.Namespace;
if (!isItaniumLikeAbi && @class.Layout.HasVirtualBases)
{
@params.Add(new Parameter
{
QualifiedType = new QualifiedType(new BuiltinType(PrimitiveType.Int)),
Name = "__forBases",
Namespace = function
});
{
QualifiedType = new QualifiedType(new BuiltinType(PrimitiveType.Int)),
Name = "__forBases",
Namespace = function
});
}
}
@ -95,7 +95,7 @@ namespace CppSharp.AST @@ -95,7 +95,7 @@ namespace CppSharp.AST
public static bool NeedsSymbol(this Method method)
{
Class @class = (Class) (method.OriginalFunction ?? method).Namespace;
Class @class = (Class)(method.OriginalFunction ?? method).Namespace;
// virtual functions cannot really be inlined and
// we don't need their symbols anyway as we call them through the v-table
return (!method.IsVirtual && !method.IsSynthetized &&

2
src/AST/Method.cs

@ -112,7 +112,7 @@ namespace CppSharp.AST @@ -112,7 +112,7 @@ namespace CppSharp.AST
public Method(Function function)
: base(function)
{
}
public bool IsVirtual { get; set; }

16
src/AST/Namespace.cs

@ -31,7 +31,7 @@ namespace CppSharp.AST @@ -31,7 +31,7 @@ namespace CppSharp.AST
public IEnumerable<Event> Events => Declarations.Events;
// Used to keep track of anonymous declarations.
public Dictionary<ulong, Declaration> Anonymous;
public Dictionary<ulong, Declaration> Anonymous;
// True if the context is inside an extern "C" context.
public bool IsExternCContext;
@ -116,10 +116,10 @@ namespace CppSharp.AST @@ -116,10 +116,10 @@ namespace CppSharp.AST
if (@namespace == null)
{
@namespace = new Namespace
{
Name = name,
Namespace = this,
};
{
Name = name,
Namespace = this,
};
Declarations.Add(@namespace);
}
@ -162,7 +162,7 @@ namespace CppSharp.AST @@ -162,7 +162,7 @@ namespace CppSharp.AST
public IEnumerable<Function> FindFunction(string name, bool createDecl = false)
{
if (string.IsNullOrEmpty(name))
if (string.IsNullOrEmpty(name))
return Enumerable.Empty<Function>();
var entries = name.Split(new string[] { "::" },
@ -177,7 +177,7 @@ namespace CppSharp.AST @@ -177,7 +177,7 @@ namespace CppSharp.AST
var function = new Function() { Name = name, Namespace = this };
Declarations.Add(function);
}
return functions;
}
@ -218,7 +218,7 @@ namespace CppSharp.AST @@ -218,7 +218,7 @@ namespace CppSharp.AST
Namespaces.Select(n => n.FindClass(name, stringComparison)).FirstOrDefault(c => c != null);
if (@class != null)
return @class.CompleteDeclaration == null ?
@class : (Class) @class.CompleteDeclaration;
@class : (Class)@class.CompleteDeclaration;
return null;
}

6
src/AST/Property.cs

@ -84,9 +84,9 @@ namespace CppSharp.AST @@ -84,9 +84,9 @@ namespace CppSharp.AST
{
get
{
return (SetMethod != null &&
return (SetMethod != null &&
SetMethod.GenerationKind != GenerationKind.None) ||
(Field != null &&
(Field != null &&
(!Field.QualifiedType.IsConst() ||
Field.Type.IsConstCharString()) &&
Field.GenerationKind != GenerationKind.None);
@ -99,7 +99,7 @@ namespace CppSharp.AST @@ -99,7 +99,7 @@ namespace CppSharp.AST
public Class ExplicitInterfaceImpl { get; set; }
private readonly List<Parameter> parameters = new List<Parameter>();
/// <summary>
/// Only applicable to index ([]) properties.
/// </summary>

2
src/AST/PropertyExtensions.cs

@ -6,7 +6,7 @@ namespace CppSharp.AST @@ -6,7 +6,7 @@ namespace CppSharp.AST
{
public static bool IsInRefTypeAndBackedByValueClassField(this Property p)
{
if (p.Field == null || ((Class) p.Namespace).IsRefType)
if (p.Field == null || ((Class)p.Namespace).IsRefType)
return false;
Type type;

16
src/AST/Template.cs

@ -140,8 +140,8 @@ namespace CppSharp.AST @@ -140,8 +140,8 @@ namespace CppSharp.AST
public override string Name
{
get => TemplatedDecl != null ? TemplatedDecl.Name : base.Name;
set
{
set
{
base.Name = value;
if (TemplatedDecl != null)
TemplatedDecl.Name = value;
@ -208,9 +208,9 @@ namespace CppSharp.AST @@ -208,9 +208,9 @@ namespace CppSharp.AST
public override string Name
{
get => TemplatedDecl != null ? TemplatedClass.Name : base.Name;
set
{
if(TemplatedDecl != null)
set
{
if (TemplatedDecl != null)
TemplatedClass.Name = value;
else
base.Name = value;
@ -220,9 +220,9 @@ namespace CppSharp.AST @@ -220,9 +220,9 @@ namespace CppSharp.AST
public override string OriginalName
{
get => TemplatedDecl != null ? TemplatedClass.OriginalName : base.OriginalName;
set
{
if(TemplatedDecl != null)
set
{
if (TemplatedDecl != null)
TemplatedClass.OriginalName = value;
else
base.OriginalName = value;

78
src/AST/Type.cs

@ -92,7 +92,7 @@ namespace CppSharp.AST @@ -92,7 +92,7 @@ namespace CppSharp.AST
{
if (!(obj is QualifiedType)) return false;
var type = (QualifiedType) obj;
var type = (QualifiedType)obj;
return Type.Equals(type.Type) && Qualifiers.Equals(type.Qualifiers);
}
@ -190,7 +190,7 @@ namespace CppSharp.AST @@ -190,7 +190,7 @@ namespace CppSharp.AST
public ArrayType(ArrayType type)
: base(type)
{
QualifiedType = new QualifiedType((Type) type.QualifiedType.Type.Clone(),
QualifiedType = new QualifiedType((Type)type.QualifiedType.Type.Clone(),
type.QualifiedType.Qualifiers);
SizeType = type.SizeType;
Size = type.Size;
@ -264,7 +264,7 @@ namespace CppSharp.AST @@ -264,7 +264,7 @@ namespace CppSharp.AST
public FunctionType(FunctionType type)
: base(type)
{
ReturnType = new QualifiedType((Type) type.ReturnType.Type.Clone(), type.ReturnType.Qualifiers);
ReturnType = new QualifiedType((Type)type.ReturnType.Type.Clone(), type.ReturnType.Qualifiers);
Parameters.AddRange(type.Parameters.Select(p => new Parameter(p)));
CallingConvention = type.CallingConvention;
IsDependent = type.IsDependent;
@ -326,7 +326,7 @@ namespace CppSharp.AST @@ -326,7 +326,7 @@ namespace CppSharp.AST
public PointerType(PointerType type)
: base(type)
{
QualifiedPointee = new QualifiedType((Type) type.QualifiedPointee.Type.Clone(),
QualifiedPointee = new QualifiedType((Type)type.QualifiedPointee.Type.Clone(),
type.QualifiedPointee.Qualifiers);
Modifier = type.Modifier;
}
@ -341,7 +341,7 @@ namespace CppSharp.AST @@ -341,7 +341,7 @@ namespace CppSharp.AST
}
public QualifiedType QualifiedPointee;
public Type Pointee { get { return QualifiedPointee.Type; } }
public Type Pointee { get { return QualifiedPointee.Type; } }
public TypeModifier Modifier;
@ -382,7 +382,7 @@ namespace CppSharp.AST @@ -382,7 +382,7 @@ namespace CppSharp.AST
public MemberPointerType(MemberPointerType type)
: base(type)
{
QualifiedPointee = new QualifiedType((Type) type.QualifiedPointee.Type.Clone(),
QualifiedPointee = new QualifiedType((Type)type.QualifiedPointee.Type.Clone(),
type.QualifiedPointee.Qualifiers);
}
@ -481,8 +481,8 @@ namespace CppSharp.AST @@ -481,8 +481,8 @@ namespace CppSharp.AST
public AttributedType(AttributedType type)
: base(type)
{
Modified = new QualifiedType((Type) type.Modified.Type.Clone(), type.Modified.Qualifiers);
Equivalent = new QualifiedType((Type) type.Equivalent.Type.Clone(), type.Equivalent.Qualifiers);
Modified = new QualifiedType((Type)type.Modified.Type.Clone(), type.Modified.Qualifiers);
Equivalent = new QualifiedType((Type)type.Equivalent.Type.Clone(), type.Equivalent.Qualifiers);
}
public override T Visit<T>(ITypeVisitor<T> visitor, TypeQualifiers quals = new TypeQualifiers())
@ -495,8 +495,8 @@ namespace CppSharp.AST @@ -495,8 +495,8 @@ namespace CppSharp.AST
return new AttributedType
{
IsDependent = IsDependent,
Modified = new QualifiedType((Type) Modified.Type.Clone(), Modified.Qualifiers),
Equivalent = new QualifiedType((Type) Equivalent.Type.Clone(), Equivalent.Qualifiers)
Modified = new QualifiedType((Type)Modified.Type.Clone(), Modified.Qualifiers),
Equivalent = new QualifiedType((Type)Equivalent.Type.Clone(), Equivalent.Qualifiers)
};
}
@ -529,11 +529,11 @@ namespace CppSharp.AST @@ -529,11 +529,11 @@ namespace CppSharp.AST
public DecayedType(DecayedType type)
: base(type)
{
Decayed = new QualifiedType((Type) type.Decayed.Type.Clone(),
Decayed = new QualifiedType((Type)type.Decayed.Type.Clone(),
type.Decayed.Qualifiers);
Original = new QualifiedType((Type) type.Original.Type.Clone(),
Original = new QualifiedType((Type)type.Original.Type.Clone(),
type.Original.Qualifiers);
Pointee = new QualifiedType((Type) type.Pointee.Type.Clone(),
Pointee = new QualifiedType((Type)type.Pointee.Type.Clone(),
type.Pointee.Qualifiers);
}
@ -608,22 +608,22 @@ namespace CppSharp.AST @@ -608,22 +608,22 @@ namespace CppSharp.AST
public override bool Equals(object obj)
{
if (!(obj is TemplateArgument)) return false;
var arg = (TemplateArgument) obj;
var arg = (TemplateArgument)obj;
if (Kind != arg.Kind) return false;
switch (Kind)
{
case ArgumentKind.Type:
return Type.Equals(arg.Type);
case ArgumentKind.Declaration:
return Declaration.Equals(arg.Declaration);
case ArgumentKind.Integral:
return Integral.Equals(arg.Integral);
case ArgumentKind.Expression:
return true;
default:
throw new Exception("Unknown TemplateArgument Kind");
case ArgumentKind.Type:
return Type.Equals(arg.Type);
case ArgumentKind.Declaration:
return Declaration.Equals(arg.Declaration);
case ArgumentKind.Integral:
return Integral.Equals(arg.Integral);
case ArgumentKind.Expression:
return true;
default:
throw new Exception("Unknown TemplateArgument Kind");
}
}
@ -669,11 +669,11 @@ namespace CppSharp.AST @@ -669,11 +669,11 @@ namespace CppSharp.AST
Declaration = t.Declaration,
Integral = t.Integral,
Kind = t.Kind,
Type = new QualifiedType((Type) t.Type.Type.Clone(), t.Type.Qualifiers)
Type = new QualifiedType((Type)t.Type.Type.Clone(), t.Type.Qualifiers)
}).ToList();
Template = type.Template;
if (type.Desugared.Type != null)
Desugared = new QualifiedType((Type) type.Desugared.Type.Clone(),
Desugared = new QualifiedType((Type)type.Desugared.Type.Clone(),
type.Desugared.Qualifiers);
}
@ -749,9 +749,9 @@ namespace CppSharp.AST @@ -749,9 +749,9 @@ namespace CppSharp.AST
Declaration = t.Declaration,
Integral = t.Integral,
Kind = t.Kind,
Type = new QualifiedType((Type) t.Type.Type.Clone(), t.Type.Qualifiers)
Type = new QualifiedType((Type)t.Type.Type.Clone(), t.Type.Qualifiers)
}).ToList();
Desugared = new QualifiedType((Type) type.Desugared.Type.Clone(), type.Desugared.Qualifiers);
Desugared = new QualifiedType((Type)type.Desugared.Type.Clone(), type.Desugared.Qualifiers);
}
public List<TemplateArgument> Arguments;
@ -860,8 +860,8 @@ namespace CppSharp.AST @@ -860,8 +860,8 @@ namespace CppSharp.AST
public TemplateParameterSubstitutionType(TemplateParameterSubstitutionType type)
: base(type)
{
Replacement = new QualifiedType((Type) type.Replacement.Type.Clone(), type.Replacement.Qualifiers);
ReplacedParameter = (TemplateParameterType) type.ReplacedParameter.Clone();
Replacement = new QualifiedType((Type)type.Replacement.Type.Clone(), type.Replacement.Qualifiers);
ReplacedParameter = (TemplateParameterType)type.ReplacedParameter.Clone();
}
public override T Visit<T>(ITypeVisitor<T> visitor,
@ -905,9 +905,9 @@ namespace CppSharp.AST @@ -905,9 +905,9 @@ namespace CppSharp.AST
: base(type)
{
if (type.TemplateSpecialization != null)
TemplateSpecialization = (TemplateSpecializationType) type.TemplateSpecialization.Clone();
TemplateSpecialization = (TemplateSpecializationType)type.TemplateSpecialization.Clone();
InjectedSpecializationType = new QualifiedType(
(Type) type.InjectedSpecializationType.Type.Clone(),
(Type)type.InjectedSpecializationType.Type.Clone(),
type.InjectedSpecializationType.Qualifiers);
Class = type.Class;
}
@ -1227,13 +1227,13 @@ namespace CppSharp.AST @@ -1227,13 +1227,13 @@ namespace CppSharp.AST
{
switch (Type)
{
case PrimitiveType.Bool:
case PrimitiveType.UChar:
case PrimitiveType.UShort:
case PrimitiveType.UInt:
case PrimitiveType.ULong:
case PrimitiveType.ULongLong:
return true;
case PrimitiveType.Bool:
case PrimitiveType.UChar:
case PrimitiveType.UShort:
case PrimitiveType.UInt:
case PrimitiveType.ULong:
case PrimitiveType.ULongLong:
return true;
}
return false;

26
src/AST/TypeExtensions.cs

@ -33,7 +33,7 @@ @@ -33,7 +33,7 @@
public static bool IsEnumType(this Type t)
{
var tag = t.Desugar() as TagType;
if (tag == null)
return false;
@ -131,20 +131,20 @@ @@ -131,20 +131,20 @@
type.Desugared.Type.TryGetDeclaration(out decl, value);
return decl != null;
case ClassTemplate classTemplate:
{
var templatedClass = classTemplate.TemplatedClass;
decl = templatedClass.CompleteDeclaration == null
? templatedClass as T
: (T) templatedClass.CompleteDeclaration;
{
var templatedClass = classTemplate.TemplatedClass;
decl = templatedClass.CompleteDeclaration == null
? templatedClass as T
: (T)templatedClass.CompleteDeclaration;
if (decl == null)
return false;
if (decl == null)
return false;
if (value != null)
type.Template = new ClassTemplate { TemplatedDecl = value };
if (value != null)
type.Template = new ClassTemplate { TemplatedDecl = value };
return true;
}
return true;
}
case TemplateTemplateParameter templateTemplateParameter:
return (decl = templateTemplateParameter.TemplatedDecl as T) != null;
}
@ -316,7 +316,7 @@ @@ -316,7 +316,7 @@
if (type == null)
return null;
var pointee = type.Desugar().GetPointee();
if (pointee.IsPointer())

60
src/CLI/CLI.cs

@ -10,36 +10,36 @@ namespace CppSharp @@ -10,36 +10,36 @@ namespace CppSharp
{
private static OptionSet optionSet = new OptionSet();
private static Options options = new Options();
static bool ParseCommandLineArgs(string[] args, List<string> errorMessages, ref bool helpShown)
{
var showHelp = false;
optionSet.Add("I=", "the {PATH} of a folder to search for include files", (i) => { AddIncludeDirs(i, errorMessages); });
optionSet.Add("l=", "{LIBRARY} that that contains the symbols of the generated code", l => options.Libraries.Add(l) );
optionSet.Add("L=", "the {PATH} of a folder to search for additional libraries", l => options.LibraryDirs.Add(l) );
optionSet.Add("D:", "additional define with (optional) value to add to be used while parsing the given header files", (n, v) => AddDefine(n, v, errorMessages) );
optionSet.Add("A=", "additional Clang arguments to pass to the compiler while parsing the given header files", (v) => AddArgument(v, errorMessages) );
optionSet.Add("l=", "{LIBRARY} that that contains the symbols of the generated code", l => options.Libraries.Add(l));
optionSet.Add("L=", "the {PATH} of a folder to search for additional libraries", l => options.LibraryDirs.Add(l));
optionSet.Add("D:", "additional define with (optional) value to add to be used while parsing the given header files", (n, v) => AddDefine(n, v, errorMessages));
optionSet.Add("A=", "additional Clang arguments to pass to the compiler while parsing the given header files", (v) => AddArgument(v, errorMessages));
optionSet.Add("o=|output=", "the {PATH} for the generated bindings file (doesn't need the extension since it will depend on the generator)", v => HandleOutputArg(v, errorMessages) );
optionSet.Add("on=|outputnamespace=", "the {NAMESPACE} that will be used for the generated code", on => options.OutputNamespace = on );
optionSet.Add("o=|output=", "the {PATH} for the generated bindings file (doesn't need the extension since it will depend on the generator)", v => HandleOutputArg(v, errorMessages));
optionSet.Add("on=|outputnamespace=", "the {NAMESPACE} that will be used for the generated code", on => options.OutputNamespace = on);
optionSet.Add("m=|module=", "the name for the generated {MODULE}", a => { options.OutputFileName = a; });
optionSet.Add("iln=|inputlibraryname=|inputlib=", "the {NAME} of the shared library that contains the symbols of the generated code", iln => options.InputLibraryName = iln );
optionSet.Add("iln=|inputlibraryname=|inputlib=", "the {NAME} of the shared library that contains the symbols of the generated code", iln => options.InputLibraryName = iln);
optionSet.Add("d|debug", "enables debug mode which generates more verbose code to aid debugging", v => options.Debug = true);
optionSet.Add("c|compile", "enables automatic compilation of the generated code", v => options.Compile = true);
optionSet.Add("g=|gen=|generator=", "the {TYPE} of generated code: 'csharp' or 'cli' ('cli' supported only for Windows)", g => { GetGeneratorKind(g, errorMessages); } );
optionSet.Add("p=|platform=", "the {PLATFORM} that the generated code will target: 'win', 'osx' or 'linux'", p => { GetDestinationPlatform(p, errorMessages); } );
optionSet.Add("a=|arch=", "the {ARCHITECTURE} that the generated code will target: 'x86' or 'x64'", a => { GetDestinationArchitecture(a, errorMessages); } );
optionSet.Add("g=|gen=|generator=", "the {TYPE} of generated code: 'csharp' or 'cli' ('cli' supported only for Windows)", g => { GetGeneratorKind(g, errorMessages); });
optionSet.Add("p=|platform=", "the {PLATFORM} that the generated code will target: 'win', 'osx' or 'linux'", p => { GetDestinationPlatform(p, errorMessages); });
optionSet.Add("a=|arch=", "the {ARCHITECTURE} that the generated code will target: 'x86' or 'x64'", a => { GetDestinationArchitecture(a, errorMessages); });
optionSet.Add("prefix=", "sets a string prefix to the names of generated files", a => { options.Prefix = a; });
optionSet.Add("exceptions", "enables support for C++ exceptions in the parser", v => { options.EnableExceptions = true; });
optionSet.Add("rtti", "enables support for C++ RTTI in the parser", v => { options.EnableRTTI = true; });
optionSet.Add("c++11", "enables GCC C++ 11 compilation (valid only for Linux platform)", cpp11 => { options.Cpp11ABI = (cpp11 != null); } );
optionSet.Add("cs|checksymbols", "enable the symbol check for the generated code", cs => { options.CheckSymbols = (cs != null); } );
optionSet.Add("ub|unitybuild|unity", "enable unity build", ub => { options.UnityBuild = (ub != null); } );
optionSet.Add("c++11", "enables GCC C++ 11 compilation (valid only for Linux platform)", cpp11 => { options.Cpp11ABI = (cpp11 != null); });
optionSet.Add("cs|checksymbols", "enable the symbol check for the generated code", cs => { options.CheckSymbols = (cs != null); });
optionSet.Add("ub|unitybuild|unity", "enable unity build", ub => { options.UnityBuild = (ub != null); });
optionSet.Add("v|verbose", "enables verbose mode", v => { options.Verbose = true; });
optionSet.Add("h|help", "shows the help", hl => { showHelp = (hl != null); });
@ -55,7 +55,7 @@ namespace CppSharp @@ -55,7 +55,7 @@ namespace CppSharp
Console.WriteLine(e.Message);
return false;
}
if (showHelp || additionalArguments != null && additionalArguments.Count == 0)
{
helpShown = true;
@ -63,7 +63,7 @@ namespace CppSharp @@ -63,7 +63,7 @@ namespace CppSharp
return false;
}
foreach(string s in additionalArguments)
foreach (string s in additionalArguments)
HandleAdditionalArgument(s, errorMessages);
return true;
@ -117,7 +117,7 @@ namespace CppSharp @@ -117,7 +117,7 @@ namespace CppSharp
var dir = Path.HasExtension(arg) ? Path.GetDirectoryName(arg) : Path.GetFullPath(arg);
options.OutputDir = dir;
}
catch(Exception e)
catch (Exception e)
{
errorMessages.Add(e.Message);
@ -159,7 +159,7 @@ namespace CppSharp @@ -159,7 +159,7 @@ namespace CppSharp
errorMessages.Add($"File '{args}' could not be found.");
}
}
catch(Exception)
catch (Exception)
{
errorMessages.Add($"Error while looking for files inside path '{args}'. Ignoring.");
}
@ -278,23 +278,23 @@ namespace CppSharp @@ -278,23 +278,23 @@ namespace CppSharp
List<string> errorMessages = new List<string>();
bool helpShown = false;
if (!ParseCommandLineArgs(args, errorMessages, ref helpShown))
{
PrintErrorMessages(errorMessages);
if (!ParseCommandLineArgs(args, errorMessages, ref helpShown))
{
PrintErrorMessages(errorMessages);
// Don't need to show the help since if ParseCommandLineArgs returns false the help has already been shown
return;
}
// Don't need to show the help since if ParseCommandLineArgs returns false the help has already been shown
return;
}
Generator gen = new Generator(options);
Generator gen = new Generator(options);
bool validOptions = gen.ValidateOptions(errorMessages);
PrintErrorMessages(errorMessages);
bool validOptions = gen.ValidateOptions(errorMessages);
PrintErrorMessages(errorMessages);
if (errorMessages.Any() || !validOptions)
Environment.Exit(1);
if (errorMessages.Any() || !validOptions)
Environment.Exit(1);
gen.Run();
gen.Run();
}
}
}

8
src/CLI/Generator.cs

@ -45,7 +45,7 @@ namespace CppSharp @@ -45,7 +45,7 @@ namespace CppSharp
if (options.Architecture == TargetArchitecture.x64)
tripleBuilder.Append("x86_64-");
else if(options.Architecture == TargetArchitecture.x86)
else if (options.Architecture == TargetArchitecture.x86)
tripleBuilder.Append("i686-");
if (options.Platform == TargetPlatform.Windows)
@ -63,7 +63,7 @@ namespace CppSharp @@ -63,7 +63,7 @@ namespace CppSharp
tripleBuilder.Append("linux-gnu");
abi = CppAbi.Itanium;
if(options.Cpp11ABI)
if (options.Cpp11ABI)
tripleBuilder.Append("-cxx11abi");
}
@ -118,7 +118,7 @@ namespace CppSharp @@ -118,7 +118,7 @@ namespace CppSharp
driverOptions.GeneratorKind = options.Kind;
var module = driverOptions.AddModule(options.OutputFileName);
if(!string.IsNullOrEmpty(options.InputLibraryName))
if (!string.IsNullOrEmpty(options.InputLibraryName))
module.SharedLibraryName = options.InputLibraryName;
module.Headers.AddRange(options.HeaderFiles);
@ -143,7 +143,7 @@ namespace CppSharp @@ -143,7 +143,7 @@ namespace CppSharp
foreach (KeyValuePair<string, string> d in options.Defines)
{
if(string.IsNullOrEmpty(d.Value))
if (string.IsNullOrEmpty(d.Value))
parserOptions.AddDefines(d.Key);
else
parserOptions.AddDefines(d.Key + "=" + d.Value);

2
src/CLI/Options.cs

@ -32,7 +32,7 @@ namespace CppSharp @@ -32,7 +32,7 @@ namespace CppSharp
public string InputLibraryName { get; set; }
public string Prefix { get; set; }
public TargetPlatform? Platform { get; set; }
public TargetArchitecture Architecture { get; set; } = TargetArchitecture.x86;

2
src/Core/Compilation.cs

@ -29,5 +29,5 @@ namespace CppSharp @@ -29,5 +29,5 @@ namespace CppSharp
// If true, will force the generation of debug metadata for the native
// and managed code.
public bool DebugMode;
}
}
}

4
src/Core/Diagnostics.cs

@ -120,11 +120,11 @@ namespace CppSharp @@ -120,11 +120,11 @@ namespace CppSharp
var currentIndentation = Indents.Sum();
var message = new string(' ', currentIndentation) + info.Message;
if(info.Kind == DiagnosticKind.Error)
if (info.Kind == DiagnosticKind.Error)
{
Console.Error.WriteLine(message);
}
else
else
{
Console.WriteLine(message);
}

6
src/Core/Platform.cs

@ -84,13 +84,13 @@ namespace CppSharp @@ -84,13 +84,13 @@ namespace CppSharp
{
if (IsWindows)
return TargetPlatform.Windows;
if (IsMacOS)
return TargetPlatform.MacOS;
if (IsLinux)
return TargetPlatform.Linux;
throw new NotImplementedException();
}
}

4
src/Core/Toolchains/MSVCToolchain.cs

@ -55,7 +55,7 @@ namespace CppSharp @@ -55,7 +55,7 @@ namespace CppSharp
switch (vsVersion)
{
case VisualStudioVersion.VS2012:
clVersion = new Version { Major = 17, Minor = 0};
clVersion = new Version { Major = 17, Minor = 0 };
break;
case VisualStudioVersion.VS2013:
clVersion = new Version { Major = 18, Minor = 0 };
@ -108,7 +108,7 @@ namespace CppSharp @@ -108,7 +108,7 @@ namespace CppSharp
int windowsSdkMajorVer, List<ToolchainVersion> windowsSdks)
{
var majorWindowsSdk = windowsSdks.Find(
version => (int) Math.Floor(version.Version) == windowsSdkMajorVer);
version => (int)Math.Floor(version.Version) == windowsSdkMajorVer);
var windowsSdkDirs = majorWindowsSdk.Directory != null ?
new[] { majorWindowsSdk.Directory } :
windowsSdks.Select(w => w.Directory).Reverse();

8
src/Core/Toolchains/ManagedToolchain.cs

@ -10,18 +10,18 @@ namespace CppSharp @@ -10,18 +10,18 @@ namespace CppSharp
{
public static string ReadMonoPathFromWindowsRegistry(bool prefer64bits = false)
{
using (var baseKey = RegistryKey.OpenBaseKey (RegistryHive.LocalMachine,
using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,
prefer64bits ? RegistryView.Registry64 : RegistryView.Registry32))
{
if (baseKey == null)
return null;
using (var subKey = baseKey.OpenSubKey (@"SOFTWARE\Mono"))
using (var subKey = baseKey.OpenSubKey(@"SOFTWARE\Mono"))
{
if (subKey == null)
return null;
return (string)subKey.GetValue ("SdkInstallRoot", "");
return (string)subKey.GetValue("SdkInstallRoot", "");
}
}
}
@ -33,7 +33,7 @@ namespace CppSharp @@ -33,7 +33,7 @@ namespace CppSharp
// Try to lookup the Mono SDK path from registry.
string path = ReadMonoPathFromWindowsRegistry(prefer64bits);
if (!string.IsNullOrEmpty(path))
return path;
return path;
// If that fails, then lets try a default location.
return @"C:\Program Files (x86)\Mono";

19
src/Core/Toolchains/XcodeToolchain.cs

@ -25,7 +25,7 @@ namespace CppSharp @@ -25,7 +25,7 @@ namespace CppSharp
throw new Exception("Could not find a valid Xcode toolchain");
return toolchainPath;
}
}
public static string GetXcodeCppIncludesFolder()
{
@ -68,30 +68,33 @@ namespace CppSharp @@ -68,30 +68,33 @@ namespace CppSharp
return Path.Combine(sdkPath, "usr/include");
}
private static string GetXcodePathFromXcodeSelect()
private static string GetXcodePathFromXcodeSelect()
{
try
try
{
var xcodeSelect = Process.Start(new ProcessStartInfo("xcode-select", "--print-path") {
var xcodeSelect = Process.Start(new ProcessStartInfo("xcode-select", "--print-path")
{
RedirectStandardOutput = true,
UseShellExecute = false
});
var result = xcodeSelect.StandardOutput.ReadToEnd();
if(!string.IsNullOrEmpty(result))
if (!string.IsNullOrEmpty(result))
{
var extraStuffIndex = result.LastIndexOf("/Contents/Developer");
if(extraStuffIndex >= 0)
if (extraStuffIndex >= 0)
return result.Remove(extraStuffIndex);
}
} catch {
}
catch
{
// TODO: Log exception?
}
return null;
}
private static string GetXcodePathFromFileSystem()
private static string GetXcodePathFromFileSystem()
{
var toolchains = Directory.EnumerateDirectories("/Applications", "Xcode*")
.ToList();

2
src/CppParser/Bootstrap/Bootstrap.cs

@ -803,7 +803,7 @@ namespace CppSharp @@ -803,7 +803,7 @@ namespace CppSharp
UnindentAndWriteCloseBrace();
}
WriteLine($"default:");
WriteLineIndent($"throw new System.NotImplementedException(" +
$"{ParamName}.StmtClass.ToString());");

16
src/Generator.Tests/AST/TestAST.cs

@ -251,11 +251,11 @@ namespace CppSharp.Generator.Tests.AST @@ -251,11 +251,11 @@ namespace CppSharp.Generator.Tests.AST
Assert.IsInstanceOf<TemplateParameterType>(twoParamMethod.Parameters[0].Type);
Assert.IsInstanceOf<TemplateParameterType>(twoParamMethod.Parameters[1].Type);
Assert.AreEqual(twoParamMethodTemplate.Parameters[0],
((TemplateParameterType) twoParamMethod.Parameters[0].Type).Parameter);
((TemplateParameterType)twoParamMethod.Parameters[0].Type).Parameter);
Assert.AreEqual(twoParamMethodTemplate.Parameters[1],
((TemplateParameterType) twoParamMethod.Parameters[1].Type).Parameter);
Assert.AreEqual(0, ((TemplateParameterType) twoParamMethod.Parameters[0].Type).Index);
Assert.AreEqual(1, ((TemplateParameterType) twoParamMethod.Parameters[1].Type).Index);
((TemplateParameterType)twoParamMethod.Parameters[1].Type).Parameter);
Assert.AreEqual(0, ((TemplateParameterType)twoParamMethod.Parameters[0].Type).Index);
Assert.AreEqual(1, ((TemplateParameterType)twoParamMethod.Parameters[1].Type).Index);
}
[Test]
@ -436,20 +436,20 @@ namespace CppSharp.Generator.Tests.AST @@ -436,20 +436,20 @@ namespace CppSharp.Generator.Tests.AST
Assert.IsTrue(constExpr.IsConstExpr);
var noExcept = AstContext.FindFunction("noExcept").First();
Assert.That(((FunctionType) noExcept.FunctionType.Type).ExceptionSpecType,
Assert.That(((FunctionType)noExcept.FunctionType.Type).ExceptionSpecType,
Is.EqualTo(ExceptionSpecType.BasicNoexcept));
var noExceptTrue = AstContext.FindFunction("noExceptTrue").First();
Assert.That(((FunctionType) noExceptTrue.FunctionType.Type).ExceptionSpecType,
Assert.That(((FunctionType)noExceptTrue.FunctionType.Type).ExceptionSpecType,
Is.EqualTo(ExceptionSpecType.NoexceptTrue));
var noExceptFalse = AstContext.FindFunction("noExceptFalse").First();
Assert.That(((FunctionType) noExceptFalse.FunctionType.Type).ExceptionSpecType,
Assert.That(((FunctionType)noExceptFalse.FunctionType.Type).ExceptionSpecType,
Is.EqualTo(ExceptionSpecType.NoexceptFalse));
var regular = AstContext.FindFunction("testSignature").First();
Assert.IsFalse(regular.IsConstExpr);
var regularFunctionType = (FunctionType) regular.FunctionType.Type;
var regularFunctionType = (FunctionType)regular.FunctionType.Type;
Assert.That(regularFunctionType.ExceptionSpecType,
Is.EqualTo(ExceptionSpecType.None));
}

2
src/Generator.Tests/ASTTestFixture.cs

@ -14,7 +14,7 @@ namespace CppSharp.Generator.Tests @@ -14,7 +14,7 @@ namespace CppSharp.Generator.Tests
protected Driver Driver;
protected ASTContext AstContext;
protected BindingContext Context;
public ASTTestFixture(params string[] files)
{
this.files = files;

2
src/Generator.Tests/Passes/TestPasses.cs

@ -273,7 +273,7 @@ namespace CppSharp.Generator.Tests.Passes @@ -273,7 +273,7 @@ namespace CppSharp.Generator.Tests.Passes
static IEnumerable GetExpressionEvaluatorTestCases()
{
var testNumber = 100;
var testNumber = 100;
foreach (var tc in TestExpressionEvaluatorTestCases)
{
// "testNumber" is just used to cause the test runner to show the tests in the order

2
src/Generator.Tests/ReadNativeSymbolsTest.cs

@ -106,7 +106,7 @@ namespace CppSharp.Generator.Tests @@ -106,7 +106,7 @@ namespace CppSharp.Generator.Tests
{
var symbols = GetSymbols("linux", "libexpat");
Assert.That(symbols, Is.EquivalentTo(
new []
new[]
{
".init",
"free",

12
src/Generator/AST/ASTRecord.cs

@ -21,7 +21,7 @@ namespace CppSharp.Generators.AST @@ -21,7 +21,7 @@ namespace CppSharp.Generators.AST
if (!(v is T))
return false;
@out = (T) v;
@out = (T)v;
return true;
}
@ -48,14 +48,14 @@ namespace CppSharp.Generators.AST @@ -48,14 +48,14 @@ namespace CppSharp.Generators.AST
return true;
}
return Parent != null
return Parent != null
&& Parent.GetAncestors<T>(ref ancestors);
}
}
public class ASTRecord<T> : ASTRecord
{
public T Value => (T) Object;
public T Value => (T)Object;
public override string ToString()
{
@ -132,7 +132,7 @@ namespace CppSharp.Generators.AST @@ -132,7 +132,7 @@ namespace CppSharp.Generators.AST
public static bool IsFieldValueType(this ASTRecord record)
{
var ancestors = new Stack<object>();
if(!record.GetAncestors<Field>(ref ancestors))
if (!record.GetAncestors<Field>(ref ancestors))
return false;
var field = (Field)ancestors.Pop();
@ -154,7 +154,7 @@ namespace CppSharp.Generators.AST @@ -154,7 +154,7 @@ namespace CppSharp.Generators.AST
public static bool FunctionReturnsClassByValue(this ASTRecord record)
{
var ancestors = new Stack<object>();
if(!record.GetAncestors<Function>(ref ancestors))
if (!record.GetAncestors<Function>(ref ancestors))
return false;
var function = (Function)ancestors.Pop();
@ -231,5 +231,5 @@ namespace CppSharp.Generators.AST @@ -231,5 +231,5 @@ namespace CppSharp.Generators.AST
// translation unit is encountered.
return decl.Namespace.TranslationUnit == translationUnit;
}
}
}
}

4
src/Generator/AST/Utils.cs

@ -132,7 +132,7 @@ namespace CppSharp.AST @@ -132,7 +132,7 @@ namespace CppSharp.AST
template = specialization.TemplatedDecl.TemplatedClass;
else
{
template = (Class) method.Namespace;
template = (Class)method.Namespace;
if (!template.IsDependent)
return false;
}
@ -219,7 +219,7 @@ namespace CppSharp.AST @@ -219,7 +219,7 @@ namespace CppSharp.AST
{
public static CXXOperatorArity ClassifyOperator(Function function)
{
switch(function.Parameters.Count)
switch (function.Parameters.Count)
{
case 0: return CXXOperatorArity.Zero;
case 1: return CXXOperatorArity.Unary;

12
src/Generator/AST/VTables.cs

@ -12,10 +12,10 @@ namespace CppSharp.AST @@ -12,10 +12,10 @@ namespace CppSharp.AST
{
switch (@class.Layout.ABI)
{
case CppAbi.Microsoft:
return GatherVTableMethodsMS(@class);
case CppAbi.Itanium:
return GatherVTableMethodsItanium(@class);
case CppAbi.Microsoft:
return GatherVTableMethodsMS(@class);
case CppAbi.Itanium:
return GatherVTableMethodsItanium(@class);
}
throw new NotSupportedException(
@ -57,7 +57,7 @@ namespace CppSharp.AST @@ -57,7 +57,7 @@ namespace CppSharp.AST
public static int GetVTableIndex(Function function)
{
var @class = (Class) function.Namespace;
var @class = (Class)function.Namespace;
switch (@class.Layout.ABI)
{
case CppAbi.Microsoft:
@ -77,7 +77,7 @@ namespace CppSharp.AST @@ -77,7 +77,7 @@ namespace CppSharp.AST
return entry.Method != null &&
(entry.Method.IsOperator ||
(!entry.Method.IsDeclared &&
((Class) entry.Method.Namespace).GetPropertyByConstituentMethod(entry.Method) == null));
((Class)entry.Method.Namespace).GetPropertyByConstituentMethod(entry.Method) == null));
}
}
}

2
src/Generator/Extensions/FunctionExtensions.cs

@ -7,7 +7,7 @@ namespace CppSharp.Extensions @@ -7,7 +7,7 @@ namespace CppSharp.Extensions
public static bool IsNativeMethod(this Function function)
{
var method = function as Method;
if (method == null)
if (method == null)
return false;
return method.Conversion == MethodConversionKind.None;

4
src/Generator/Generator.cs

@ -85,7 +85,7 @@ namespace CppSharp.Generators @@ -85,7 +85,7 @@ namespace CppSharp.Generators
// TODO: Remove this once file per module works for C++ backend
if (!Context.Options.IsCSharpGenerator)
outputMode = GenerationOutputMode.FilePerUnit;
var outputs = new List<GeneratorOutput>();
if (outputMode == GenerationOutputMode.FilePerModule)
@ -115,7 +115,7 @@ namespace CppSharp.Generators @@ -115,7 +115,7 @@ namespace CppSharp.Generators
}
}
var generateSystemModule = Context.Options.SystemModule != null &&
var generateSystemModule = Context.Options.SystemModule != null &&
Context.Options.GeneratorKind == GeneratorKind.CSharp;
if (generateSystemModule)
{

8
src/Generator/Generators/C/CCodeGenerator.cs

@ -402,15 +402,15 @@ namespace CppSharp.Generators.C @@ -402,15 +402,15 @@ namespace CppSharp.Generators.C
if (isDeclaration)
{
if (method.IsPure)
Write(" = 0");
Write(" = 0");
else if (method.IsOverride)
Write(" override");
Write(" override");
}
}
public virtual void GenerateMethodParameters(Function function)
{
Write(CTypePrinter.VisitParameters(function.Parameters));
Write(CTypePrinter.VisitParameters(function.Parameters));
}
public override bool VisitMethodDecl(Method method)
@ -440,7 +440,7 @@ namespace CppSharp.Generators.C @@ -440,7 +440,7 @@ namespace CppSharp.Generators.C
GeneratePropertySetter(property.SetMethod);
//if (Options.GenerateMSDeclspecProperties)
//GenerateMSDeclspecProperty(property);
//GenerateMSDeclspecProperty(property);
return true;
}

12
src/Generator/Generators/C/CppHeaders.cs

@ -302,7 +302,7 @@ namespace CppSharp.Generators.Cpp @@ -302,7 +302,7 @@ namespace CppSharp.Generators.Cpp
return false;
//if (@class.IsOpaque)
// return false;
// return false;
PushBlock(BlockKind.Class, @class);
@ -392,8 +392,8 @@ namespace CppSharp.Generators.Cpp @@ -392,8 +392,8 @@ namespace CppSharp.Generators.Cpp
Name = Generator.GeneratedIdentifier("ExternalData"),
QualifiedType = new QualifiedType(new ArrayType
{
QualifiedType = new QualifiedType(voidPtrType),
SizeType = ArrayType.ArraySize.Constant,
QualifiedType = new QualifiedType(voidPtrType),
SizeType = ArrayType.ArraySize.Constant,
Size = 2
}),
Namespace = @class
@ -567,7 +567,7 @@ namespace CppSharp.Generators.Cpp @@ -567,7 +567,7 @@ namespace CppSharp.Generators.Cpp
Indent();
var @class = (Class) methods[0].Namespace;
var @class = (Class)methods[0].Namespace;
if (@class.IsValueType)
foreach (var @base in @class.Bases.Where(b => b.IsClass && !b.Class.Ignore))
@ -591,7 +591,7 @@ namespace CppSharp.Generators.Cpp @@ -591,7 +591,7 @@ namespace CppSharp.Generators.Cpp
method.Visit(this);
}
foreach(var method in staticMethods)
foreach (var method in staticMethods)
method.Visit(this);
Unindent();
@ -686,7 +686,7 @@ namespace CppSharp.Generators.Cpp @@ -686,7 +686,7 @@ namespace CppSharp.Generators.Cpp
var @delegate = string.Format(CTypePrinter.VisitDelegate(functionType), typedef.Name);
WriteLine($"{@delegate};");
PopBlock(NewLineKind.BeforeNextBlock);
return true;

108
src/Generator/Generators/C/CppMarshal.cs

@ -36,13 +36,13 @@ namespace CppSharp.Generators.Cpp @@ -36,13 +36,13 @@ namespace CppSharp.Generators.Cpp
{
switch (array.SizeType)
{
case ArrayType.ArraySize.Constant:
case ArrayType.ArraySize.Incomplete:
case ArrayType.ArraySize.Variable:
Context.Return.Write("nullptr");
break;
default:
throw new System.NotImplementedException();
case ArrayType.ArraySize.Constant:
case ArrayType.ArraySize.Incomplete:
case ArrayType.ArraySize.Variable:
Context.Return.Write("nullptr");
break;
default:
throw new System.NotImplementedException();
}
return true;
@ -76,7 +76,7 @@ namespace CppSharp.Generators.Cpp @@ -76,7 +76,7 @@ namespace CppSharp.Generators.Cpp
Context.ReturnType.Qualifiers.IsConst)
{
var nativeTypePrinter = new CppTypePrinter(Context.Context)
{ PrintTypeQualifiers = false };
{ PrintTypeQualifiers = false };
var returnType = Context.ReturnType.Type.Desugar();
var constlessPointer = new PointerType()
{
@ -137,28 +137,28 @@ namespace CppSharp.Generators.Cpp @@ -137,28 +137,28 @@ namespace CppSharp.Generators.Cpp
{
switch (primitive)
{
case PrimitiveType.Void:
return true;
case PrimitiveType.Bool:
case PrimitiveType.Char:
case PrimitiveType.Char16:
case PrimitiveType.WideChar:
case PrimitiveType.SChar:
case PrimitiveType.UChar:
case PrimitiveType.Short:
case PrimitiveType.UShort:
case PrimitiveType.Int:
case PrimitiveType.UInt:
case PrimitiveType.Long:
case PrimitiveType.ULong:
case PrimitiveType.LongLong:
case PrimitiveType.ULongLong:
case PrimitiveType.Float:
case PrimitiveType.Double:
case PrimitiveType.LongDouble:
case PrimitiveType.Null:
Context.Return.Write(Context.ReturnVarName);
return true;
case PrimitiveType.Void:
return true;
case PrimitiveType.Bool:
case PrimitiveType.Char:
case PrimitiveType.Char16:
case PrimitiveType.WideChar:
case PrimitiveType.SChar:
case PrimitiveType.UChar:
case PrimitiveType.Short:
case PrimitiveType.UShort:
case PrimitiveType.Int:
case PrimitiveType.UInt:
case PrimitiveType.Long:
case PrimitiveType.ULong:
case PrimitiveType.LongLong:
case PrimitiveType.ULongLong:
case PrimitiveType.Float:
case PrimitiveType.Double:
case PrimitiveType.LongDouble:
case PrimitiveType.Null:
Context.Return.Write(Context.ReturnVarName);
return true;
}
throw new NotSupportedException();
@ -330,7 +330,7 @@ namespace CppSharp.Generators.Cpp @@ -330,7 +330,7 @@ namespace CppSharp.Generators.Cpp
public class CppMarshalManagedToNativePrinter : MarshalPrinter<MarshalContext, CppTypePrinter>
{
public CppMarshalManagedToNativePrinter(MarshalContext ctx)
public CppMarshalManagedToNativePrinter(MarshalContext ctx)
: base(ctx)
{
Context.MarshalToNative = this;
@ -363,9 +363,9 @@ namespace CppSharp.Generators.Cpp @@ -363,9 +363,9 @@ namespace CppSharp.Generators.Cpp
switch (array.SizeType)
{
default:
Context.Return.Write("nullptr");
break;
default:
Context.Return.Write("nullptr");
break;
}
return true;
@ -447,26 +447,26 @@ namespace CppSharp.Generators.Cpp @@ -447,26 +447,26 @@ namespace CppSharp.Generators.Cpp
{
switch (primitive)
{
case PrimitiveType.Void:
return true;
case PrimitiveType.Bool:
case PrimitiveType.Char:
case PrimitiveType.UChar:
case PrimitiveType.Short:
case PrimitiveType.UShort:
case PrimitiveType.Int:
case PrimitiveType.UInt:
case PrimitiveType.Long:
case PrimitiveType.ULong:
case PrimitiveType.LongLong:
case PrimitiveType.ULongLong:
case PrimitiveType.Float:
case PrimitiveType.Double:
case PrimitiveType.WideChar:
Context.Return.Write(Context.Parameter.Name);
return true;
default:
throw new NotImplementedException();
case PrimitiveType.Void:
return true;
case PrimitiveType.Bool:
case PrimitiveType.Char:
case PrimitiveType.UChar:
case PrimitiveType.Short:
case PrimitiveType.UShort:
case PrimitiveType.Int:
case PrimitiveType.UInt:
case PrimitiveType.Long:
case PrimitiveType.ULong:
case PrimitiveType.LongLong:
case PrimitiveType.ULongLong:
case PrimitiveType.Float:
case PrimitiveType.Double:
case PrimitiveType.WideChar:
Context.Return.Write(Context.Parameter.Name);
return true;
default:
throw new NotImplementedException();
}
}

14
src/Generator/Generators/C/CppSources.cs

@ -114,7 +114,7 @@ namespace CppSharp.Generators.Cpp @@ -114,7 +114,7 @@ namespace CppSharp.Generators.Cpp
}
}
foreach(var childNamespace in context.Namespaces)
foreach (var childNamespace in context.Namespaces)
VisitDeclContext(childNamespace);
PopBlock();
@ -521,10 +521,10 @@ namespace CppSharp.Generators.Cpp @@ -521,10 +521,10 @@ namespace CppSharp.Generators.Cpp
WriteLine(");");
}
foreach(var paramInfo in @params)
foreach (var paramInfo in @params)
{
var param = paramInfo.Param;
if(param.Usage != ParameterUsage.Out && param.Usage != ParameterUsage.InOut)
if (param.Usage != ParameterUsage.Out && param.Usage != ParameterUsage.InOut)
continue;
if (param.Type.IsPointer() && !param.Type.GetFinalPointee().IsPrimitiveType())
@ -541,7 +541,7 @@ namespace CppSharp.Generators.Cpp @@ -541,7 +541,7 @@ namespace CppSharp.Generators.Cpp
var marshal = new CppMarshalNativeToManagedPrinter(ctx);
param.Visit(marshal);
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Write(marshal.Context.Before);
@ -575,7 +575,7 @@ namespace CppSharp.Generators.Cpp @@ -575,7 +575,7 @@ namespace CppSharp.Generators.Cpp
public static bool IsNativeMethod(Function function)
{
var method = function as Method;
if (method == null)
if (method == null)
return false;
return method.Conversion == MethodConversionKind.None;
@ -584,7 +584,7 @@ namespace CppSharp.Generators.Cpp @@ -584,7 +584,7 @@ namespace CppSharp.Generators.Cpp
public bool IsNativeFunctionOrStaticMethod(Function function)
{
var method = function as Method;
if (method == null)
if (method == null)
return true;
if (!IsCLIGenerator && method.IsOperator)
@ -602,7 +602,7 @@ namespace CppSharp.Generators.Cpp @@ -602,7 +602,7 @@ namespace CppSharp.Generators.Cpp
public string Prefix;
public Parameter Param;
}
}
public List<ParamMarshal> GenerateFunctionParamsMarshal(IEnumerable<Parameter> @params,
Function function = null)

162
src/Generator/Generators/C/CppTypePrinter.cs

@ -94,16 +94,16 @@ namespace CppSharp.Generators.C @@ -94,16 +94,16 @@ namespace CppSharp.Generators.C
string arraySuffix;
switch (array.SizeType)
{
case ArrayType.ArraySize.Constant:
arraySuffix = $"[{array.Size}]";
break;
case ArrayType.ArraySize.Variable:
case ArrayType.ArraySize.Dependent:
case ArrayType.ArraySize.Incomplete:
arraySuffix = $"{(PrintVariableArrayAsPointers ? "*" : "[]")}";
break;
default:
throw new NotImplementedException();
case ArrayType.ArraySize.Constant:
arraySuffix = $"[{array.Size}]";
break;
case ArrayType.ArraySize.Variable:
case ArrayType.ArraySize.Dependent:
case ArrayType.ArraySize.Incomplete:
arraySuffix = $"{(PrintVariableArrayAsPointers ? "*" : "[]")}";
break;
default:
throw new NotImplementedException();
}
return new TypePrinterResult
@ -199,32 +199,32 @@ namespace CppSharp.Generators.C @@ -199,32 +199,32 @@ namespace CppSharp.Generators.C
return PrintFlavorKind == CppTypePrintFlavorKind.Cpp ?
"std::nullptr_t" : "NULL";
case PrimitiveType.String:
{
switch (PrintFlavorKind)
{
case CppTypePrintFlavorKind.C:
return "const char*";
case CppTypePrintFlavorKind.Cpp:
return "std::string";
case CppTypePrintFlavorKind.ObjC:
return "NSString";
default:
throw new ArgumentOutOfRangeException();
switch (PrintFlavorKind)
{
case CppTypePrintFlavorKind.C:
return "const char*";
case CppTypePrintFlavorKind.Cpp:
return "std::string";
case CppTypePrintFlavorKind.ObjC:
return "NSString";
default:
throw new ArgumentOutOfRangeException();
}
}
}
case PrimitiveType.Decimal:
{
switch (PrintFlavorKind)
{
case CppTypePrintFlavorKind.C:
case CppTypePrintFlavorKind.Cpp:
return "_Decimal32";
case CppTypePrintFlavorKind.ObjC:
return "NSDecimalNumber";
default:
throw new ArgumentOutOfRangeException();
switch (PrintFlavorKind)
{
case CppTypePrintFlavorKind.C:
case CppTypePrintFlavorKind.Cpp:
return "_Decimal32";
case CppTypePrintFlavorKind.ObjC:
return "NSDecimalNumber";
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
throw new NotSupportedException();
@ -237,8 +237,12 @@ namespace CppSharp.Generators.C @@ -237,8 +237,12 @@ namespace CppSharp.Generators.C
if (ResolveTypedefs && !typedef.Declaration.Type.IsPointerTo(out FunctionType _))
{
TypePrinterResult type = typedef.Declaration.QualifiedType.Visit(this);
return new TypePrinterResult { Type = $"{qual}{type.Type}",
NamePrefix = type.NamePrefix, NameSuffix = type.NameSuffix };
return new TypePrinterResult
{
Type = $"{qual}{type.Type}",
NamePrefix = type.NamePrefix,
NameSuffix = type.NameSuffix
};
}
var result = typedef.Declaration.Visit(this);
@ -469,59 +473,59 @@ namespace CppSharp.Generators.C @@ -469,59 +473,59 @@ namespace CppSharp.Generators.C
{
switch (scope)
{
case TypePrintScopeKind.Local:
{
if (ContextKind == TypePrinterContextKind.Managed)
{
return PrintLogicalNames ? declaration.LogicalName : declaration.Name;
}
case TypePrintScopeKind.Local:
{
if (ContextKind == TypePrinterContextKind.Managed)
{
return PrintLogicalNames ? declaration.LogicalName : declaration.Name;
}
if (PrefixSpecialFunctions)
{
if (declaration is Function {IsOperator: true} function)
return $"operator_{function.OperatorKind}";
}
if (PrefixSpecialFunctions)
{
if (declaration is Function { IsOperator: true } function)
return $"operator_{function.OperatorKind}";
}
return PrintLogicalNames ? declaration.LogicalOriginalName
: declaration.OriginalName;
}
case TypePrintScopeKind.Qualified:
{
if (ContextKind == TypePrinterContextKind.Managed)
{
var outputNamespace = GlobalNamespace(declaration);
if (!string.IsNullOrEmpty(outputNamespace))
{
return $"{outputNamespace}{NamespaceSeparator}{declaration.QualifiedName}";
return PrintLogicalNames ? declaration.LogicalOriginalName
: declaration.OriginalName;
}
case TypePrintScopeKind.Qualified:
{
if (ContextKind == TypePrinterContextKind.Managed)
{
var outputNamespace = GlobalNamespace(declaration);
if (!string.IsNullOrEmpty(outputNamespace))
{
return $"{outputNamespace}{NamespaceSeparator}{declaration.QualifiedName}";
}
return declaration.QualifiedName;
}
return declaration.QualifiedName;
}
if (declaration.Namespace is Class)
{
var declName = GetDeclName(declaration, TypePrintScopeKind.Local);
bool printTags = PrintTags;
PrintTags = false;
TypePrinterResult declContext = declaration.Namespace.Visit(this);
PrintTags = printTags;
return $"{declContext}{NamespaceSeparator}{declName}";
}
if (declaration.Namespace is Class)
{
var declName = GetDeclName(declaration, TypePrintScopeKind.Local);
bool printTags = PrintTags;
PrintTags = false;
TypePrinterResult declContext = declaration.Namespace.Visit(this);
PrintTags = printTags;
return $"{declContext}{NamespaceSeparator}{declName}";
}
return PrintLogicalNames ? declaration.QualifiedLogicalOriginalName
: declaration.QualifiedOriginalName;
}
case TypePrintScopeKind.GlobalQualified:
{
var name = (ContextKind == TypePrinterContextKind.Managed) ?
declaration.Name : declaration.OriginalName;
return PrintLogicalNames ? declaration.QualifiedLogicalOriginalName
: declaration.QualifiedOriginalName;
}
case TypePrintScopeKind.GlobalQualified:
{
var name = (ContextKind == TypePrinterContextKind.Managed) ?
declaration.Name : declaration.OriginalName;
if (declaration.Namespace is Class)
return $"{declaration.Namespace.Visit(this)}{NamespaceSeparator}{name}";
if (declaration.Namespace is Class)
return $"{declaration.Namespace.Visit(this)}{NamespaceSeparator}{name}";
var qualifier = HasGlobalNamespacePrefix ? NamespaceSeparator : string.Empty;
return qualifier + GetDeclName(declaration, TypePrintScopeKind.Qualified);
}
var qualifier = HasGlobalNamespacePrefix ? NamespaceSeparator : string.Empty;
return qualifier + GetDeclName(declaration, TypePrintScopeKind.Qualified);
}
}
throw new NotSupportedException();
@ -619,7 +623,7 @@ namespace CppSharp.Generators.C @@ -619,7 +623,7 @@ namespace CppSharp.Generators.C
FunctionType functionType;
CppSharp.AST.Type desugared = function.FunctionType.Type.Desugar();
if (!desugared.IsPointerTo(out functionType))
functionType = (FunctionType) desugared;
functionType = (FunctionType)desugared;
string exceptionType = Print(functionType.ExceptionSpecType);
var @return = function.OriginalReturnType.Visit(this);

12
src/Generator/Generators/CLI/CLIHeaders.cs

@ -70,7 +70,7 @@ namespace CppSharp.Generators.CLI @@ -70,7 +70,7 @@ namespace CppSharp.Generators.CLI
if (unit != null && !unit.IsDeclared)
continue;
if(!string.IsNullOrEmpty(include.File) && include.InHeader)
if (!string.IsNullOrEmpty(include.File) && include.InHeader)
includes.Add(include.ToString());
}
@ -507,7 +507,7 @@ namespace CppSharp.Generators.CLI @@ -507,7 +507,7 @@ namespace CppSharp.Generators.CLI
Indent();
var @class = (Class) methods[0].Namespace;
var @class = (Class)methods[0].Namespace;
if (@class.IsValueType)
foreach (var @base in @class.Bases.Where(b => b.IsClass && !b.Class.Ignore))
@ -531,7 +531,7 @@ namespace CppSharp.Generators.CLI @@ -531,7 +531,7 @@ namespace CppSharp.Generators.CLI
GenerateMethod(method);
}
foreach(var method in staticMethods)
foreach (var method in staticMethods)
GenerateMethod(method);
Unindent();
@ -541,7 +541,7 @@ namespace CppSharp.Generators.CLI @@ -541,7 +541,7 @@ namespace CppSharp.Generators.CLI
{
Indent();
foreach(var variable in @class.Variables)
foreach (var variable in @class.Variables)
{
if (!variable.IsGenerated) continue;
@ -720,7 +720,7 @@ namespace CppSharp.Generators.CLI @@ -720,7 +720,7 @@ namespace CppSharp.Generators.CLI
if (method.OperatorKind == CXXOperatorKind.EqualEqual)
{
GenerateEquals(method, (Class) method.Namespace);
GenerateEquals(method, (Class)method.Namespace);
}
PopBlock(NewLineKind.BeforeNextBlock);
@ -759,7 +759,7 @@ namespace CppSharp.Generators.CLI @@ -759,7 +759,7 @@ namespace CppSharp.Generators.CLI
: ((FunctionType)attributedType).CallingConvention;
var interopCallConv = callingConvention.ToInteropCallConv();
if (interopCallConv != System.Runtime.InteropServices.CallingConvention.Winapi)
WriteLine("[::System::Runtime::InteropServices::UnmanagedFunctionPointer" +
WriteLine("[::System::Runtime::InteropServices::UnmanagedFunctionPointer" +
"(::System::Runtime::InteropServices::CallingConvention::{0})] ",
interopCallConv);

34
src/Generator/Generators/CLI/CLIMarshal.cs

@ -391,7 +391,7 @@ namespace CppSharp.Generators.CLI @@ -391,7 +391,7 @@ namespace CppSharp.Generators.CLI
public readonly TextGenerator VarPrefix;
public readonly TextGenerator ArgumentPrefix;
public CLIMarshalManagedToNativePrinter(MarshalContext ctx)
public CLIMarshalManagedToNativePrinter(MarshalContext ctx)
: base(ctx)
{
VarPrefix = new TextGenerator();
@ -466,7 +466,7 @@ namespace CppSharp.Generators.CLI @@ -466,7 +466,7 @@ namespace CppSharp.Generators.CLI
isPointerToPrimitive || isPrimitive ? string.Empty : "*",
Context.Parameter.Name,
nativeVal);
supportBefore.UnindentAndWriteCloseBrace();
supportBefore.UnindentAndWriteCloseBrace();
break;
default:
Context.Return.Write("null");
@ -521,7 +521,7 @@ namespace CppSharp.Generators.CLI @@ -521,7 +521,7 @@ namespace CppSharp.Generators.CLI
Context.Parameter.Usage == ParameterUsage.Out ||
Context.Parameter.Usage == ParameterUsage.InOut;
if(!isRef)
if (!isRef)
{
ArgumentPrefix.Write("&");
}
@ -759,7 +759,7 @@ namespace CppSharp.Generators.CLI @@ -759,7 +759,7 @@ namespace CppSharp.Generators.CLI
MarshalValueClassProperties(@base.Class, marshalVar);
}
foreach (var property in @class.Properties.Where( p => !ASTUtils.CheckIgnoreProperty(p)))
foreach (var property in @class.Properties.Where(p => !ASTUtils.CheckIgnoreProperty(p)))
{
if (property.Field == null)
continue;
@ -773,11 +773,11 @@ namespace CppSharp.Generators.CLI @@ -773,11 +773,11 @@ namespace CppSharp.Generators.CLI
var fieldRef = $"{Context.Parameter.Name}.{property.Name}";
var marshalCtx = new MarshalContext(Context.Context, Context.Indentation)
{
ArgName = fieldRef,
ParameterIndex = Context.ParameterIndex++,
ReturnVarName = $"{marshalVar}.{property.Field.OriginalName}"
};
{
ArgName = fieldRef,
ParameterIndex = Context.ParameterIndex++,
ReturnVarName = $"{marshalVar}.{property.Field.OriginalName}"
};
var marshal = new CLIMarshalManagedToNativePrinter(marshalCtx);
property.Visit(marshal);
@ -812,10 +812,10 @@ namespace CppSharp.Generators.CLI @@ -812,10 +812,10 @@ namespace CppSharp.Generators.CLI
public override bool VisitFieldDecl(Field field)
{
Context.Parameter = new Parameter
{
Name = Context.ArgName,
QualifiedType = field.QualifiedType
};
{
Name = Context.ArgName,
QualifiedType = field.QualifiedType
};
return field.Type.Visit(this);
}
@ -823,10 +823,10 @@ namespace CppSharp.Generators.CLI @@ -823,10 +823,10 @@ namespace CppSharp.Generators.CLI
public override bool VisitProperty(Property property)
{
Context.Parameter = new Parameter
{
Name = Context.ArgName,
QualifiedType = property.QualifiedType
};
{
Name = Context.ArgName,
QualifiedType = property.QualifiedType
};
return base.VisitProperty(property);
}

90
src/Generator/Generators/CLI/CLISources.cs

@ -64,7 +64,7 @@ namespace CppSharp.Generators.CLI @@ -64,7 +64,7 @@ namespace CppSharp.Generators.CLI
continue;
var include = typeRef.Include;
if(!string.IsNullOrEmpty(include.File) && !include.InHeader)
if (!string.IsNullOrEmpty(include.File) && !include.InHeader)
includes.Add(include.ToString());
}
@ -113,7 +113,7 @@ namespace CppSharp.Generators.CLI @@ -113,7 +113,7 @@ namespace CppSharp.Generators.CLI
}
}
foreach(var childNamespace in @namespace.Namespaces)
foreach (var childNamespace in @namespace.Namespaces)
GenerateDeclContext(childNamespace);
PopBlock();
@ -305,7 +305,7 @@ namespace CppSharp.Generators.CLI @@ -305,7 +305,7 @@ namespace CppSharp.Generators.CLI
typeNames = "typename " + string.Join(", typename ", paramNames);
WriteLine("generic<{0}>", typeNames);
WriteLine("{0} {1}::{2}({3})", retType,
WriteLine("{0} {1}::{2}({3})", retType,
QualifiedIdentifier(function.Namespace), function.Name,
GenerateParametersList(function.Parameters));
@ -348,7 +348,7 @@ namespace CppSharp.Generators.CLI @@ -348,7 +348,7 @@ namespace CppSharp.Generators.CLI
GeneratePropertySetter(property.SetMethod, realOwner, property.Name,
property.Type);
}
PopBlock();
PopBlock();
}
private void GeneratePropertySetter<T>(T decl, Class @class, string name, Type type, Parameter indexParameter = null)
@ -502,7 +502,7 @@ namespace CppSharp.Generators.CLI @@ -502,7 +502,7 @@ namespace CppSharp.Generators.CLI
WriteLine($"return {marshal.Context.Return};");
}
UnindentAndWriteCloseBrace();
NewLine();
@ -593,10 +593,10 @@ namespace CppSharp.Generators.CLI @@ -593,10 +593,10 @@ namespace CppSharp.Generators.CLI
foreach (var param in @event.Parameters)
{
var ctx = new MarshalContext(Context, CurrentIndentation)
{
ReturnVarName = param.Name,
ReturnType = param.QualifiedType
};
{
ReturnVarName = param.Name,
ReturnType = param.QualifiedType
};
var marshal = new CLIMarshalNativeToManagedPrinter(ctx);
param.Visit(marshal);
@ -685,7 +685,7 @@ namespace CppSharp.Generators.CLI @@ -685,7 +685,7 @@ namespace CppSharp.Generators.CLI
}
int paramIndex = 0;
foreach (var property in @class.Properties.Where(
foreach (var property in @class.Properties.Where(
p => !ASTUtils.CheckIgnoreProperty(p) && !CLIHeaders.TypeIgnored(p.Type)))
{
if (property.Field == null)
@ -849,12 +849,12 @@ namespace CppSharp.Generators.CLI @@ -849,12 +849,12 @@ namespace CppSharp.Generators.CLI
foreach (var param in method.Parameters)
{
var ctx = new MarshalContext(Context, CurrentIndentation)
{
Function = method,
Parameter = param,
ArgName = param.Name,
ParameterIndex = paramIndex++
};
{
Function = method,
Parameter = param,
ArgName = param.Name,
ParameterIndex = paramIndex++
};
var marshal = new CLIMarshalManagedToNativePrinter(ctx);
param.Visit(marshal);
@ -885,10 +885,10 @@ namespace CppSharp.Generators.CLI @@ -885,10 +885,10 @@ namespace CppSharp.Generators.CLI
var varName = $"_native.{property.Field.OriginalName}";
var ctx = new MarshalContext(Context, CurrentIndentation)
{
ReturnVarName = varName,
ReturnType = property.QualifiedType
};
{
ReturnVarName = varName,
ReturnType = property.QualifiedType
};
var marshal = new CLIMarshalNativeToManagedPrinter(ctx);
property.Visit(marshal);
@ -959,11 +959,11 @@ namespace CppSharp.Generators.CLI @@ -959,11 +959,11 @@ namespace CppSharp.Generators.CLI
{
WriteLine($"auto {valueMarshalName} = {typePrinter.PrintTag(@class)}::{@class.QualifiedOriginalName}();");
var param = new Parameter { Name = "(*this)" , Namespace = function.Namespace };
var param = new Parameter { Name = "(*this)", Namespace = function.Namespace };
var ctx = new MarshalContext(Context, CurrentIndentation)
{
Parameter = param
};
{
Parameter = param
};
ctx.VarPrefix.Write(valueMarshalName);
var marshal = new CLIMarshalManagedToNativePrinter(ctx);
@ -982,7 +982,7 @@ namespace CppSharp.Generators.CLI @@ -982,7 +982,7 @@ namespace CppSharp.Generators.CLI
else
Write("auto {0} = ", returnIdentifier);
if (function.OperatorKind == CXXOperatorKind.Conversion ||
if (function.OperatorKind == CXXOperatorKind.Conversion ||
function.OperatorKind == CXXOperatorKind.ExplicitConversion)
{
var method = function as Method;
@ -996,12 +996,12 @@ namespace CppSharp.Generators.CLI @@ -996,12 +996,12 @@ namespace CppSharp.Generators.CLI
switch (Operators.ClassifyOperator(function))
{
case CXXOperatorArity.Unary:
WriteLine("{0} {1};", opName, @params[0].Name);
break;
case CXXOperatorArity.Binary:
WriteLine("{0} {1} {2};", @params[0].Name, opName, @params[1].Name);
break;
case CXXOperatorArity.Unary:
WriteLine("{0} {1};", opName, @params[0].Name);
break;
case CXXOperatorArity.Binary:
WriteLine("{0} {1} {2};", @params[0].Name, opName, @params[1].Name);
break;
}
}
else
@ -1023,10 +1023,10 @@ namespace CppSharp.Generators.CLI @@ -1023,10 +1023,10 @@ namespace CppSharp.Generators.CLI
WriteLine(");");
}
foreach(var paramInfo in @params)
foreach (var paramInfo in @params)
{
var param = paramInfo.Param;
if(param.Usage != ParameterUsage.Out && param.Usage != ParameterUsage.InOut)
if (param.Usage != ParameterUsage.Out && param.Usage != ParameterUsage.InOut)
continue;
if (param.Type.IsPointer() && !param.Type.GetFinalPointee().IsPrimitiveType())
@ -1035,19 +1035,19 @@ namespace CppSharp.Generators.CLI @@ -1035,19 +1035,19 @@ namespace CppSharp.Generators.CLI
var nativeVarName = paramInfo.Name;
var ctx = new MarshalContext(Context, CurrentIndentation)
{
ArgName = nativeVarName,
ReturnVarName = nativeVarName,
ReturnType = param.QualifiedType
};
{
ArgName = nativeVarName,
ReturnVarName = nativeVarName,
ReturnType = param.QualifiedType
};
var marshal = new CLIMarshalNativeToManagedPrinter(ctx);
param.Visit(marshal);
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Write(marshal.Context.Before);
WriteLine("{0} = {1};",param.Name,marshal.Context.Return);
WriteLine("{0} = {1};", param.Name, marshal.Context.Return);
}
if (isValueType && !IsNativeFunctionOrStaticMethod(function))
@ -1082,7 +1082,7 @@ namespace CppSharp.Generators.CLI @@ -1082,7 +1082,7 @@ namespace CppSharp.Generators.CLI
// Special case for indexer - needs to dereference if the internal
// function is a pointer type and the property is not.
if (retType.Type.IsPointer() &&
if (retType.Type.IsPointer() &&
retType.Type.GetPointee().Equals(publicRetType) &&
publicRetType.IsPrimitiveType())
WriteLine("return *({0});", marshal.Context.Return);
@ -1104,7 +1104,7 @@ namespace CppSharp.Generators.CLI @@ -1104,7 +1104,7 @@ namespace CppSharp.Generators.CLI
// C++/CLI can actually handle char -> sbyte in all case, this is for compatibility with the C# generator
WriteLineIndent(
"throw gcnew ::System::OverflowException(\"{0} must be in the range {1} - {2}.\");",
param.Name, (int) char.MinValue, sbyte.MaxValue);
param.Name, (int)char.MinValue, sbyte.MaxValue);
}
}
}
@ -1112,7 +1112,7 @@ namespace CppSharp.Generators.CLI @@ -1112,7 +1112,7 @@ namespace CppSharp.Generators.CLI
private static bool IsNativeMethod(Function function)
{
var method = function as Method;
if (method == null)
if (method == null)
return false;
return method.Conversion == MethodConversionKind.None;
@ -1121,7 +1121,7 @@ namespace CppSharp.Generators.CLI @@ -1121,7 +1121,7 @@ namespace CppSharp.Generators.CLI
private static bool IsNativeFunctionOrStaticMethod(Function function)
{
var method = function as Method;
if (method == null)
if (method == null)
return true;
if (method.IsOperator && Operators.IsBuiltinOperator(method.OperatorKind))
@ -1136,7 +1136,7 @@ namespace CppSharp.Generators.CLI @@ -1136,7 +1136,7 @@ namespace CppSharp.Generators.CLI
public string Prefix;
public Parameter Param;
}
}
public List<ParamMarshal> GenerateFunctionParamsMarshal(IEnumerable<Parameter> @params,
Function function = null)

2
src/Generator/Generators/CLI/CLITemplate.cs

@ -28,7 +28,7 @@ namespace CppSharp.Generators.CLI @@ -28,7 +28,7 @@ namespace CppSharp.Generators.CLI
if (method.IsConstructor || method.IsDestructor)
{
var @class = (Class) method.Namespace;
var @class = (Class)method.Namespace;
return @class.Name;
}

8
src/Generator/Generators/CLI/CLITypePrinter.cs

@ -74,14 +74,14 @@ namespace CppSharp.Generators.CLI @@ -74,14 +74,14 @@ namespace CppSharp.Generators.CLI
Parameter = null;
var str = string.Empty;
if(param.Usage == ParameterUsage.Out)
if (param.Usage == ParameterUsage.Out)
str += "[::System::Runtime::InteropServices::Out] ";
else if (param.Usage == ParameterUsage.InOut)
str += "[::System::Runtime::InteropServices::In, ::System::Runtime::InteropServices::Out] ";
str += type;
if(param.Usage == ParameterUsage.Out ||
if (param.Usage == ParameterUsage.Out ||
param.Usage == ParameterUsage.InOut)
str += "%";
@ -110,7 +110,7 @@ namespace CppSharp.Generators.CLI @@ -110,7 +110,7 @@ namespace CppSharp.Generators.CLI
MarshalKind = MarshalKind,
Type = pointer
};
return typeMap.CLISignatureType(typePrinterContext).Visit(this);
}
@ -150,7 +150,7 @@ namespace CppSharp.Generators.CLI @@ -150,7 +150,7 @@ namespace CppSharp.Generators.CLI
var typeName = VisitDeclaration(@enum, quals);
// Skip one indirection if passed by reference
if (Parameter != null && (Parameter.Type.IsReference()
if (Parameter != null && (Parameter.Type.IsReference()
|| ((Parameter.IsOut || Parameter.IsInOut)
&& pointee == finalPointee)))
return typeName;

6
src/Generator/Generators/CLI/CLITypeReferences.cs

@ -123,7 +123,7 @@ namespace CppSharp.Generators.CLI @@ -123,7 +123,7 @@ namespace CppSharp.Generators.CLI
// Find a type map for the declaration and use it if it exists.
TypeMap typeMap;
if (TypeMapDatabase.FindTypeMap(record.Value, out typeMap)
if (TypeMapDatabase.FindTypeMap(record.Value, out typeMap)
|| (typedefType != null && TypeMapDatabase.FindTypeMap(typedefType.Type.Desugar(), out typeMap)))
{
typeMap.CLITypeReference(this, record);
@ -131,7 +131,7 @@ namespace CppSharp.Generators.CLI @@ -131,7 +131,7 @@ namespace CppSharp.Generators.CLI
}
var typeRef = GetTypeReference(decl);
if(typeRef != null)
if (typeRef != null)
{
typeRef.Include.InHeader |= IsIncludeInHeader(record);
}
@ -176,7 +176,7 @@ namespace CppSharp.Generators.CLI @@ -176,7 +176,7 @@ namespace CppSharp.Generators.CLI
return false;
if (@class.IsIncomplete && @class.CompleteDeclaration != null)
@class = (Class) @class.CompleteDeclaration;
@class = (Class)@class.CompleteDeclaration;
if (@class.TranslationUnit == TranslationUnit)
GeneratedDeclarations.Add(@class);

12
src/Generator/Generators/CSharp/CSharpCommentPrinter.cs

@ -23,12 +23,12 @@ namespace CppSharp.Generators.CSharp @@ -23,12 +23,12 @@ namespace CppSharp.Generators.CSharp
switch (comment.Kind)
{
case DocumentationCommentKind.FullComment:
var fullComment = (FullComment) comment;
var fullComment = (FullComment)comment;
foreach (var block in fullComment.Blocks)
block.GetCommentSections(sections);
break;
case DocumentationCommentKind.BlockCommandComment:
var blockCommandComment = (BlockCommandComment) comment;
var blockCommandComment = (BlockCommandComment)comment;
if (blockCommandComment.ParagraphComment == null)
break;
switch (blockCommandComment.CommandKind)
@ -58,7 +58,7 @@ namespace CppSharp.Generators.CSharp @@ -58,7 +58,7 @@ namespace CppSharp.Generators.CSharp
break;
case DocumentationCommentKind.ParamCommandComment:
var paramCommandComment = (ParamCommandComment) comment;
var paramCommandComment = (ParamCommandComment)comment;
var param = new Section(CommentElement.Param);
sections.Add(param);
if (paramCommandComment.Arguments.Count > 0)
@ -82,7 +82,7 @@ namespace CppSharp.Generators.CSharp @@ -82,7 +82,7 @@ namespace CppSharp.Generators.CSharp
break;
case DocumentationCommentKind.ParagraphComment:
var summaryParagraph = sections.Count == 1;
var paragraphComment = (ParagraphComment) comment;
var paragraphComment = (ParagraphComment)comment;
var lastParagraphSection = sections.Last();
foreach (var inlineContentComment in paragraphComment.Content)
{
@ -117,7 +117,7 @@ namespace CppSharp.Generators.CSharp @@ -117,7 +117,7 @@ namespace CppSharp.Generators.CSharp
break;
case DocumentationCommentKind.InlineCommandComment:
var lastInlineSection = sections.Last();
var inlineCommand = (InlineCommandComment) comment;
var inlineCommand = (InlineCommandComment)comment;
if (inlineCommand.CommandKind == CommentCommandKind.B)
{
@ -132,7 +132,7 @@ namespace CppSharp.Generators.CSharp @@ -132,7 +132,7 @@ namespace CppSharp.Generators.CSharp
private static string GetText(Comment comment, bool trim = false)
{
var textComment = ((TextComment) comment);
var textComment = ((TextComment)comment);
var text = textComment.Text;
if (trim)
text = text.Trim();

8
src/Generator/Generators/CSharp/CSharpExpressionPrinter.cs

@ -40,7 +40,7 @@ namespace CppSharp.Generators.CSharp @@ -40,7 +40,7 @@ namespace CppSharp.Generators.CSharp
switch (expr.Class)
{
case StatementClass.Call:
var callExpr = (CallExprObsolete) expr;
var callExpr = (CallExprObsolete)expr;
switch (callExpr.Declaration.GenerationKind)
{
case GenerationKind.Generate:
@ -48,7 +48,7 @@ namespace CppSharp.Generators.CSharp @@ -48,7 +48,7 @@ namespace CppSharp.Generators.CSharp
return $"{typePrinter.VisitDeclaration(callExpr.Declaration.Namespace)}.{callExpr.Declaration.Name}({args})";
case GenerationKind.Internal:
// a non-ctor can only be internal if it's been converted to a property
var property = ((Class) callExpr.Declaration.Namespace).Properties.First(
var property = ((Class)callExpr.Declaration.Namespace).Properties.First(
p => p.GetMethod == callExpr.Declaration);
return $"{typePrinter.VisitDeclaration(callExpr.Declaration.Namespace)}.{property.Name}";
default:
@ -59,7 +59,7 @@ namespace CppSharp.Generators.CSharp @@ -59,7 +59,7 @@ namespace CppSharp.Generators.CSharp
return expr.Declaration.Visit(typePrinter).Type;
goto default;
case StatementClass.BinaryOperator:
var binaryOperator = (BinaryOperatorObsolete) expr;
var binaryOperator = (BinaryOperatorObsolete)expr;
var lhsResult = binaryOperator.LHS.String;
if (binaryOperator.LHS.Declaration is Enumeration.Item)
@ -71,7 +71,7 @@ namespace CppSharp.Generators.CSharp @@ -71,7 +71,7 @@ namespace CppSharp.Generators.CSharp
return $"{lhsResult} {binaryOperator.OpcodeStr} {rhsResult}";
case StatementClass.ConstructorReference:
var constructorExpr = (CXXConstructExprObsolete) expr;
var constructorExpr = (CXXConstructExprObsolete)expr;
if (constructorExpr.Arguments.Count == 1 &&
constructorExpr.Arguments[0].Declaration is Enumeration.Item)
return constructorExpr.Arguments[0].Declaration.Visit(typePrinter).Type;

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

@ -74,7 +74,7 @@ namespace CppSharp.Generators.CSharp @@ -74,7 +74,7 @@ namespace CppSharp.Generators.CSharp
Context.Return.Write($"new Span<{arrayType}>({Context.ReturnVarName}, {array.Size})");
else
Context.Return.Write($"CppSharp.Runtime.MarshalUtil.GetArray<{arrayType}>({Context.ReturnVarName}, {array.Size})");
}
}
else if (array.Type.IsPrimitiveType(PrimitiveType.Char) && Context.Context.Options.MarshalCharAsManagedChar)
Context.Return.Write($"CppSharp.Runtime.MarshalUtil.GetCharArray({Context.ReturnVarName}, {array.Size})");
else if (array.Type.IsPointerToPrimitiveType(PrimitiveType.Void))
@ -386,7 +386,7 @@ namespace CppSharp.Generators.CSharp @@ -386,7 +386,7 @@ namespace CppSharp.Generators.CSharp
{
var originalClass = @class.OriginalClass ?? @class;
var ret = Generator.GeneratedIdentifier("result") + Context.ParameterIndex;
if (originalClass.IsRefType)
{
var dtor = originalClass.Destructors.FirstOrDefault();

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

@ -228,7 +228,7 @@ namespace CppSharp.Generators.CSharp @@ -228,7 +228,7 @@ namespace CppSharp.Generators.CSharp
GenerateNamespaceFunctionsAndVariables(context);
foreach(var childNamespace in context.Namespaces)
foreach (var childNamespace in context.Namespaces)
childNamespace.Visit(this);
return true;
@ -411,7 +411,7 @@ namespace CppSharp.Generators.CSharp @@ -411,7 +411,7 @@ namespace CppSharp.Generators.CSharp
if (@class.IsDependent && !@class.IsGenerated)
return true;
// disable the type maps, if any, for this class because of copy ctors, operators and others
this.DisableTypeMap(@class);
@ -480,7 +480,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -480,7 +480,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
managed = default;
return NativeToManagedMap.TryGetValue(native, out var wr) && wr.TryGetTarget(out managed);
}}");
}
}
else
{
WriteLines($@"
@ -512,7 +512,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -512,7 +512,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
if (@class.IsDynamic)
GenerateVTable(@class);
exit:
exit:
UnindentAndWriteCloseBrace();
PopBlock(NewLineKind.BeforeNextBlock);
@ -542,7 +542,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -542,7 +542,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
foreach (var method in @class.Methods.Where(m =>
(m.OriginalFunction == null ||
!ASTUtils.CheckIgnoreFunction(m.OriginalFunction)) &&
m.Access == AccessSpecifier.Public &&
m.Access == AccessSpecifier.Public &&
(!shouldInheritFromIDisposable || !IsDisposeMethod(m))))
{
PushBlock(BlockKind.Method);
@ -568,7 +568,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -568,7 +568,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
PushBlock(BlockKind.Property);
var type = prop.Type;
if (prop.Parameters.Count > 0 && prop.Type.IsPointerToPrimitiveType())
type = ((PointerType) prop.Type).Pointee;
type = ((PointerType)prop.Type).Pointee;
GenerateDeclarationCommon(prop);
Write($"{type} {GetPropertyName(prop)} {{ ");
if (prop.HasGetter)
@ -596,7 +596,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -596,7 +596,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
PushBlock(BlockKind.InternalsClass);
if (@class.Layout.Size > 0)
{
{
var layout = sequentialLayout ? "Sequential" : "Explicit";
var pack = @class.MaxFieldAlignment > 0 ? $", Pack = {@class.MaxFieldAlignment}" : string.Empty;
WriteLine($"[StructLayout(LayoutKind.{layout}, Size = {@class.Layout.Size}{pack})]");
@ -847,7 +847,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -847,7 +847,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
var fields = @class.Layout.Fields;
if (fields.Count > 1)
{
{
for (var i = 1; i < fields.Count; ++i)
{
if (fields[i].Offset == fields[i - 1].Offset)
@ -916,7 +916,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -916,7 +916,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
PopBlock(NewLineKind.BeforeNextBlock);
}
#endregion
#endregion
private void GeneratePropertySetter<T>(T decl,
Class @class, bool isAbstract = false, Property property = null)
@ -1063,11 +1063,12 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -1063,11 +1063,12 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
}
else
{
var name = ((Class) field.Namespace).Layout.Fields.First(
var name = ((Class)field.Namespace).Layout.Fields.First(
f => f.FieldPtr == field.OriginalPtr).Name;
if (@class.IsValueType)
returnVar = $"{Helpers.InstanceField}.{name}";
else {
else
{
var typeName = TypePrinter.PrintNative(@class);
if (IsInternalClassNested(field.Class))
typeName.RemoveNamespace();
@ -1141,7 +1142,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -1141,7 +1142,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
else
type = originalType.ToString();
var name = ((Class) field.Namespace).Layout.Fields.First(
var name = ((Class)field.Namespace).Layout.Fields.First(
f => f.FieldPtr == field.OriginalPtr).Name;
WriteLine(string.Format("fixed ({0} {1} = {2}.{3})",
type, arrPtr, Helpers.InstanceField, name));
@ -1276,7 +1277,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -1276,7 +1277,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
{
NewLine();
WriteOpenBraceAndIndent();
var to = ((Class) property.OriginalNamespace).OriginalClass;
var to = ((Class)property.OriginalNamespace).OriginalClass;
var baseOffset = GetOffsetToBase(@class, to);
WriteLine("return {0} + {1};", Helpers.InstanceIdentifier, baseOffset);
UnindentAndWriteCloseBrace();
@ -1379,7 +1380,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -1379,7 +1380,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
QualifiedType type = default;
if (actualProperty != property ||
// indexers
(property.QualifiedType.Type.IsPrimitiveType() &&
(property.QualifiedType.Type.IsPrimitiveType() &&
actualProperty.GetMethod.ReturnType.Type.IsPointerToPrimitiveType()))
{
type = property.QualifiedType;
@ -1415,7 +1416,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -1415,7 +1416,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
private void GenerateFieldGetter(Field field, Class @class, QualifiedType returnType)
{
var name = ((Class) field.Namespace).Layout.Fields.First(
var name = ((Class)field.Namespace).Layout.Fields.First(
f => f.FieldPtr == field.OriginalPtr).Name;
string returnVar;
Type fieldType = field.Type.Desugar();
@ -1473,11 +1474,11 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -1473,11 +1474,11 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
!final.IsPrimitiveType(PrimitiveType.Char16) &&
!final.IsPrimitiveType(PrimitiveType.Char32)) ||
(!Context.Options.MarshalCharAsManagedChar &&
!((PointerType) fieldType).QualifiedPointee.Qualifiers.IsConst)) &&
!((PointerType)fieldType).QualifiedPointee.Qualifiers.IsConst)) &&
templateSubstitution == null) ||
(!((PointerType) fieldType).QualifiedPointee.Qualifiers.IsConst &&
(final.IsPrimitiveType(PrimitiveType.WideChar) ||
final.IsPrimitiveType(PrimitiveType.Char16) ||
(!((PointerType)fieldType).QualifiedPointee.Qualifiers.IsConst &&
(final.IsPrimitiveType(PrimitiveType.WideChar) ||
final.IsPrimitiveType(PrimitiveType.Char16) ||
final.IsPrimitiveType(PrimitiveType.Char32))))
Write($"({fieldType.GetPointee().Desugar()}*) ");
}
@ -1512,7 +1513,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -1512,7 +1513,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
if (methods.Count == 0)
return;
var @class = (Class) methods[0].Namespace;
var @class = (Class)methods[0].Namespace;
if (@class.IsValueType)
foreach (var @base in @class.Bases.Where(b => b.IsClass && !b.Class.Ignore))
@ -1649,7 +1650,8 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -1649,7 +1650,8 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
if (!isIndexer)
return prop.Name;
var @params = prop.Parameters.Select(param => {
var @params = prop.Parameters.Select(param =>
{
var p = new Parameter(param);
p.Usage = ParameterUsage.In;
return p;
@ -1671,7 +1673,8 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -1671,7 +1673,8 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
if (variable.Initializer != null && !string.IsNullOrWhiteSpace(variable.Initializer.String))
GeneratePropertyGetterForVariableWithInitializer(variable, signature);
else {
else
{
WriteLine(signature);
WriteOpenBraceAndIndent();
@ -1687,7 +1690,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -1687,7 +1690,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
PopBlock(NewLineKind.BeforeNextBlock);
}
#region Virtual Tables
#region Virtual Tables
public List<VTableComponent> GetUniqueVTableMethodEntries(Class @class)
{
@ -1718,7 +1721,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -1718,7 +1721,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
// Generate a delegate type for each method.
foreach (var method in wrappedEntries.Select(e => e.Method).Where(m => !m.Ignore))
GenerateVTableMethodDelegates(containingClass, method.Namespace.IsDependent ?
(Method) method.InstantiatedFrom : method);
(Method)method.InstantiatedFrom : method);
var hasVirtualDtor = wrappedEntries.Any(e => e.Method.IsDestructor);
bool hasDynamicBase = @class.NeedsBase && @class.BaseClass.IsDynamic;
@ -1839,7 +1842,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -1839,7 +1842,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
{{
if (__VTables.IsTransient)
__VTables = VTableLoader.SetupVTables(__Instance, destructorOnly);
}}", trimIndentation : true);
}}", trimIndentation: true);
WriteLine("#endregion");
PopBlock(NewLineKind.BeforeNextBlock);
@ -1865,7 +1868,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -1865,7 +1868,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
private void AllocateNewVTablesMS(Class @class, IList<VTableComponent> wrappedEntries,
bool destructorOnly, string table)
{
{
for (int i = 0; i < @class.Layout.VFTables.Count; i++)
{
VFTableInfo vftable = @class.Layout.VFTables[i];
@ -1892,9 +1895,9 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -1892,9 +1895,9 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
{
string suffix = (destructorOnly ? "_dtor" : string.Empty) +
(tableIndex == 0 ? string.Empty : tableIndex.ToString(CultureInfo.InvariantCulture));
WriteLine($"{table}[{tableIndex}] = CppSharp.Runtime.VTables.CloneTable(SafeHandles, instance, {vptrOffset}, {entries.Count});");
// fill the newly allocated v-table
for (var i = 0; i < entries.Count; i++)
{
@ -1908,7 +1911,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -1908,7 +1911,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
// patch with pointers to managed code where needed
WriteLine("{0}[{1}][{2}] = Thunks[{3}];", table, tableIndex, i - offsetRTTI, wrappedEntries.IndexOf(entry));
}
if (!destructorOnly)
WriteLine($"VTables.Methods[{tableIndex}] = new Delegate[{entries.Count}];");
}
@ -1974,7 +1977,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -1974,7 +1977,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
Type returnType = method.OriginalReturnType.Type.Desugar();
bool isPrimitive = returnType.IsPrimitiveType();
bool isVoid = returnType.IsPrimitiveType(PrimitiveType.Void);
var property = ((Class) method.Namespace).Properties.Find(
var property = ((Class)method.Namespace).Properties.Find(
p => p.GetMethod == method || p.SetMethod == method);
bool isSetter = property != null && property.SetMethod == method;
var hasReturn = !isVoid && !isSetter;
@ -2097,9 +2100,9 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -2097,9 +2100,9 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
return @class.IsGenerated && @class.IsDynamic && GetUniqueVTableMethodEntries(@class).Count > 0;
}
#endregion
#endregion
#region Events
#region Events
public override bool VisitEvent(Event @event)
{
@ -2207,9 +2210,9 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -2207,9 +2210,9 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
UnindentAndWriteCloseBrace();
}
#endregion
#endregion
#region Constructors
#region Constructors
public void GenerateClassConstructors(Class @class)
{
@ -2394,7 +2397,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat @@ -2394,7 +2397,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat
private bool GenerateDestructorCall(Method dtor)
{
var @class = (Class) dtor.Namespace;
var @class = (Class)dtor.Namespace;
GenerateVirtualFunctionCall(dtor, true);
if (@class.IsAbstract)
{
@ -2518,7 +2521,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty @@ -2518,7 +2521,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty
public void GenerateNativeConstructorByValue(Class @class, TypePrinterResult returnType)
{
var @internal = TypePrinter.PrintNative(@class.IsAbstractImpl ? @class.BaseClass : @class);
if (IsInternalClassNested(@class))
@internal.RemoveNamespace();
@ -2605,9 +2608,9 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty @@ -2605,9 +2608,9 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty
WriteLineIndent(": this()");
}
#endregion
#endregion
#region Methods / Functions
#region Methods / Functions
public void GenerateFunction(Function function, string parentName)
{
@ -2732,7 +2735,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty @@ -2732,7 +2735,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty
c, method, method.OriginalReturnType));
}
SkipImpl:
SkipImpl:
UnindentAndWriteCloseBrace();
@ -2829,7 +2832,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty @@ -2829,7 +2832,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty
{
if (function.OriginalFunction.GenerationKind == GenerationKind.Internal)
{
var property = ((Class) function.Namespace).Properties.First(
var property = ((Class)function.Namespace).Properties.First(
p => p.SetMethod == function.OriginalFunction);
WriteLine($@"{property.Name} = {ExpressionPrinter.VisitParameter(
function.Parameters.First(p => p.Kind == ParameterKind.Regular))};");
@ -2844,7 +2847,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty @@ -2844,7 +2847,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty
parameter.Type.IsPointerToPrimitiveType(out primitiveType) &&
parameter.Usage == ParameterUsage.InOut && parameter.HasDefaultValue)
{
var pointeeType = ((PointerType) parameter.Type).Pointee.ToString();
var pointeeType = ((PointerType)parameter.Type).Pointee.ToString();
WriteLine($@"{pointeeType} param{j++} = {
(primitiveType == PrimitiveType.Bool ? "false" : "0")};");
}
@ -2927,16 +2930,16 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty @@ -2927,16 +2930,16 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty
{
Function @virtual = method;
if (method.OriginalFunction != null &&
!((Class) method.OriginalFunction.Namespace).IsInterface)
!((Class)method.OriginalFunction.Namespace).IsInterface)
@virtual = method.OriginalFunction;
var i = VTables.GetVTableIndex(@virtual);
int vtableIndex = 0;
var @class = (Class) method.Namespace;
var @class = (Class)method.Namespace;
var thisParam = method.Parameters.Find(
p => p.Kind == ParameterKind.Extension);
if (thisParam != null)
@class = (Class) method.OriginalFunction.Namespace;
@class = (Class)method.OriginalFunction.Namespace;
if (Context.ParserOptions.IsMicrosoftAbi)
vtableIndex = @class.Layout.VFTables.IndexOf(@class.Layout.VFTables.First(
@ -3094,7 +3097,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty @@ -3094,7 +3097,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty
Parameter operatorParam = null;
if (method != null)
{
var @class = (Class) method.Namespace;
var @class = (Class)method.Namespace;
isValueType = @class.IsValueType;
operatorParam = method.Parameters.FirstOrDefault(
@ -3186,7 +3189,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty @@ -3186,7 +3189,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty
if (operatorParam == null)
{
WriteLine($@"fixed ({Helpers.InternalStruct}{
Helpers.GetSuffixForInternal((Class) originalFunction.Namespace)}* __instancePtr = &{
Helpers.GetSuffixForInternal((Class)originalFunction.Namespace)}* __instancePtr = &{
Helpers.InstanceField})");
WriteOpenBraceAndIndent();
}
@ -3200,10 +3203,10 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty @@ -3200,10 +3203,10 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty
Write("var {0} = ", Helpers.ReturnIdentifier);
if (method != null && !method.IsConstructor && method.OriginalFunction != null &&
((Method) method.OriginalFunction).IsConstructor)
((Method)method.OriginalFunction).IsConstructor)
{
WriteLine($@"Marshal.AllocHGlobal({
((Class) method.OriginalNamespace).Layout.Size});");
((Class)method.OriginalNamespace).Layout.Size});");
names.Insert(0, Helpers.ReturnIdentifier);
}
WriteLine("{0}({1});", functionName, string.Join(", ", names));
@ -3241,19 +3244,19 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty @@ -3241,19 +3244,19 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty
UnindentAndWriteCloseBrace();
var numFixedBlocks = @params.Count(param => param.HasUsingBlock);
for(var i = 0; i < numFixedBlocks; ++i)
for (var i = 0; i < numFixedBlocks; ++i)
UnindentAndWriteCloseBrace();
}
private string GetInstanceParam(Function function)
{
var from = (Class) function.Namespace;
var from = (Class)function.Namespace;
var to = (function.OriginalFunction == null ||
// we don't need to offset the instance with Itanium if there's an existing interface impl
(Context.ParserOptions.IsItaniumLikeAbi &&
!((Class) function.OriginalNamespace).IsInterface)) &&
!((Class)function.OriginalNamespace).IsInterface)) &&
function.SynthKind != FunctionSynthKind.AbstractImplCall ?
@from.BaseClass : (Class) function.OriginalFunction.Namespace;
@from.BaseClass : (Class)function.OriginalFunction.Namespace;
var baseOffset = 0u;
if (to != null)
@ -3320,7 +3323,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty @@ -3320,7 +3323,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty
{
// Do not delete instance in MS ABI.
var name = param.Name;
var function = (Function) param.Namespace;
var function = (Function)param.Namespace;
param.Name = param.Kind == ParameterKind.ImplicitDestructorParameter ? "0" :
ActiveBlock.Parent.Kind != BlockKind.Property ||
function.OperatorKind == CXXOperatorKind.Subscript ? name : "value";
@ -3377,7 +3380,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty @@ -3377,7 +3380,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty
return TypePrinter.VisitParameters(@params, true).Type;
}
#endregion
#endregion
public override bool VisitTypedefNameDecl(TypedefNameDecl typedef)
{
@ -3394,7 +3397,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty @@ -3394,7 +3397,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty
var attributedType = typedef.Type.GetPointee() as AttributedType;
var callingConvention = attributedType == null
? functionType.CallingConvention
: ((FunctionType) attributedType.Equivalent.Type).CallingConvention;
: ((FunctionType)attributedType.Equivalent.Type).CallingConvention;
TypePrinter.PushContext(TypePrinterContextKind.Native);
var interopCallConv = callingConvention.ToInteropCallConv();
if (interopCallConv == System.Runtime.InteropServices.CallingConvention.Winapi)
@ -3530,7 +3533,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty @@ -3530,7 +3533,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty
PushBlock(BlockKind.InternalsClassMethod);
var callConv = function.CallingConvention.ToInteropCallConv();
WriteLine("[SuppressUnmanagedCodeSecurity, DllImport(\"{0}\", EntryPoint = \"{1}\", CallingConvention = __CallingConvention.{2})]",
WriteLine("[SuppressUnmanagedCodeSecurity, DllImport(\"{0}\", EntryPoint = \"{1}\", CallingConvention = __CallingConvention.{2})]",
GetLibraryOf(function),
function.Mangled,
callConv);
@ -3555,7 +3558,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty @@ -3555,7 +3558,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty
string libName = declaration.TranslationUnit.Module.SharedLibraryName;
NativeLibrary library;
Context.Symbols.FindLibraryBySymbol(((IMangledDecl) declaration).Mangled, out library);
Context.Symbols.FindLibraryBySymbol(((IMangledDecl)declaration).Mangled, out library);
if (library != null)
libName = Path.GetFileNameWithoutExtension(library.FileName);

28
src/Generator/Generators/CSharp/CSharpTypePrinter.cs

@ -136,7 +136,7 @@ namespace CppSharp.Generators.CSharp @@ -136,7 +136,7 @@ namespace CppSharp.Generators.CSharp
}
}
var arraySuffix = array.SizeType != ArrayType.ArraySize.Constant &&
MarshalKind == MarshalKind.ReturnVariableArray ?
(ContextKind == TypePrinterContextKind.Managed &&
@ -303,7 +303,7 @@ namespace CppSharp.Generators.CSharp @@ -303,7 +303,7 @@ namespace CppSharp.Generators.CSharp
template.Arguments.All(IsValid))
{
List<TemplateArgument> args = template.Arguments;
var @class = (Class) template.Template.TemplatedDecl;
var @class = (Class)template.Template.TemplatedDecl;
TemplateArgument lastArg = args.Last();
TypePrinterResult typePrinterResult = VisitDeclaration(decl);
typePrinterResult.NameSuffix.Append($@"<{string.Join(", ",
@ -467,16 +467,20 @@ namespace CppSharp.Generators.CSharp @@ -467,16 +467,20 @@ namespace CppSharp.Generators.CSharp
case PrimitiveType.LongLong:
case PrimitiveType.ULongLong:
return GetIntString(primitive, Context.TargetInfo);
case PrimitiveType.Int128: return new TypePrinterResult("fixed byte",
"[16]"); // The type is always 128 bits wide
case PrimitiveType.UInt128: return new TypePrinterResult("fixed byte",
"[16]"); // The type is always 128 bits wide
case PrimitiveType.Half: return new TypePrinterResult("fixed byte",
$"[{Context.TargetInfo.HalfWidth}]");
case PrimitiveType.Int128:
return new TypePrinterResult("fixed byte",
"[16]"); // The type is always 128 bits wide
case PrimitiveType.UInt128:
return new TypePrinterResult("fixed byte",
"[16]"); // The type is always 128 bits wide
case PrimitiveType.Half:
return new TypePrinterResult("fixed byte",
$"[{Context.TargetInfo.HalfWidth}]");
case PrimitiveType.Float: return "float";
case PrimitiveType.Double: return "double";
case PrimitiveType.LongDouble: return new TypePrinterResult("fixed byte",
$"[{Context.TargetInfo.LongDoubleWidth}]");
case PrimitiveType.LongDouble:
return new TypePrinterResult("fixed byte",
$"[{Context.TargetInfo.LongDoubleWidth}]");
case PrimitiveType.IntPtr: return IntPtrType;
case PrimitiveType.UIntPtr: return QualifiedType("System.UIntPtr");
case PrimitiveType.Null: return "void*";
@ -692,7 +696,7 @@ namespace CppSharp.Generators.CSharp @@ -692,7 +696,7 @@ namespace CppSharp.Generators.CSharp
var returnTypePrinter = new TypePrinterResult();
returnTypePrinter.NameSuffix.Append(fieldTypePrinted.NameSuffix);
returnTypePrinter.Type = $"{fieldTypePrinted.Type} {field.Name}";
returnTypePrinter.Type = $"{fieldTypePrinted.Type} {field.Name}";
return returnTypePrinter;
}
@ -766,7 +770,7 @@ namespace CppSharp.Generators.CSharp @@ -766,7 +770,7 @@ namespace CppSharp.Generators.CSharp
private void AddContextName(Stack<string> names, Declaration ctx)
{
var isInlineNamespace = ctx is Namespace && ((Namespace) ctx).IsInline;
var isInlineNamespace = ctx is Namespace && ((Namespace)ctx).IsInline;
if (string.IsNullOrWhiteSpace(ctx.Name) || isInlineNamespace)
return;

8
src/Generator/Generators/CodeGenerator.cs

@ -34,10 +34,10 @@ namespace CppSharp.Generators @@ -34,10 +34,10 @@ namespace CppSharp.Generators
{
if (!Options.CommentKind.HasValue)
return CommentKind.BCPL;
return Options.CommentKind.Value;
}
}
}
/// <summary>
/// Gets the comment style kind for documentation comments.
@ -164,7 +164,7 @@ namespace CppSharp.Generators @@ -164,7 +164,7 @@ namespace CppSharp.Generators
public virtual void GenerateMultiLineComment(List<string> lines, CommentKind kind)
{
PushBlock(BlockKind.BlockComment);
var lineCommentPrologue = Comment.GetLineCommentPrologue(kind);
if (!string.IsNullOrWhiteSpace(lineCommentPrologue))
WriteLine("{0}", lineCommentPrologue);
@ -410,7 +410,7 @@ namespace CppSharp.Generators @@ -410,7 +410,7 @@ namespace CppSharp.Generators
{
if (property.GetMethod != null)
property.GetMethod.Visit(this);
if (property.SetMethod != null)
property.SetMethod.Visit(this);
}

8
src/Generator/Generators/ITypePrinter.cs

@ -52,7 +52,7 @@ namespace CppSharp.AST @@ -52,7 +52,7 @@ namespace CppSharp.AST
{
if (Kind == TypePrinterContextKind.Template)
{
var template = (Template) Declaration;
var template = (Template)Declaration;
return string.Join(", ", template.Parameters.Select(p => p.Name));
}
@ -63,12 +63,12 @@ namespace CppSharp.AST @@ -63,12 +63,12 @@ namespace CppSharp.AST
templateArgs = templateSpecializationType.Arguments;
else
{
var declaration = ((TagType) type).Declaration;
var declaration = ((TagType)type).Declaration;
var specialization = declaration as ClassTemplateSpecialization;
if (specialization == null)
return string.Join(", ",
((Class) declaration).TemplateParameters.Select(t => t.Name));
templateArgs = ((ClassTemplateSpecialization) declaration).Arguments;
((Class)declaration).TemplateParameters.Select(t => t.Name));
templateArgs = ((ClassTemplateSpecialization)declaration).Arguments;
}
var paramsList = new List<string>();

476
src/Generator/Generators/NAPI/NAPIMarshal.cs

@ -37,13 +37,13 @@ namespace CppSharp.Generators.NAPI @@ -37,13 +37,13 @@ namespace CppSharp.Generators.NAPI
{
switch (array.SizeType)
{
case ArrayType.ArraySize.Constant:
case ArrayType.ArraySize.Incomplete:
case ArrayType.ArraySize.Variable:
Context.Return.Write("nullptr");
break;
default:
throw new System.NotImplementedException();
case ArrayType.ArraySize.Constant:
case ArrayType.ArraySize.Incomplete:
case ArrayType.ArraySize.Variable:
Context.Return.Write("nullptr");
break;
default:
throw new System.NotImplementedException();
}
return true;
@ -81,48 +81,48 @@ namespace CppSharp.Generators.NAPI @@ -81,48 +81,48 @@ namespace CppSharp.Generators.NAPI
public static (string type, string func) GetNAPIPrimitiveType(PrimitiveType type)
{
switch(type)
switch (type)
{
case PrimitiveType.Bool:
return ("napi_boolean", "napi_get_boolean");
case PrimitiveType.WideChar:
case PrimitiveType.Char:
case PrimitiveType.SChar:
case PrimitiveType.Char16:
case PrimitiveType.Char32:
case PrimitiveType.Short:
case PrimitiveType.Int:
case PrimitiveType.Long:
return ("napi_number", "napi_create_int32");
case PrimitiveType.UChar:
case PrimitiveType.UShort:
case PrimitiveType.UInt:
case PrimitiveType.ULong:
return ("napi_number", "napi_create_uint32");
case PrimitiveType.LongLong:
return ("napi_number", "napi_create_bigint_int64");
case PrimitiveType.ULongLong:
return ("napi_number", "napi_create_bigint_uint64");
case PrimitiveType.Half:
case PrimitiveType.Float:
case PrimitiveType.Double:
case PrimitiveType.LongDouble:
return ("napi_number", "napi_create_double");
case PrimitiveType.Int128:
case PrimitiveType.UInt128:
case PrimitiveType.Float128:
return ("napi_bigint", "napi_create_bigint_words");
case PrimitiveType.String:
return ("napi_string", "napi_create_string_latin1");
case PrimitiveType.Null:
return ("napi_null", "napi_get_null");
case PrimitiveType.Void:
return ("napi_undefined", "napi_get_undefined");
case PrimitiveType.IntPtr:
case PrimitiveType.UIntPtr:
case PrimitiveType.Decimal:
default:
throw new ArgumentOutOfRangeException(nameof(type), type, null);
case PrimitiveType.Bool:
return ("napi_boolean", "napi_get_boolean");
case PrimitiveType.WideChar:
case PrimitiveType.Char:
case PrimitiveType.SChar:
case PrimitiveType.Char16:
case PrimitiveType.Char32:
case PrimitiveType.Short:
case PrimitiveType.Int:
case PrimitiveType.Long:
return ("napi_number", "napi_create_int32");
case PrimitiveType.UChar:
case PrimitiveType.UShort:
case PrimitiveType.UInt:
case PrimitiveType.ULong:
return ("napi_number", "napi_create_uint32");
case PrimitiveType.LongLong:
return ("napi_number", "napi_create_bigint_int64");
case PrimitiveType.ULongLong:
return ("napi_number", "napi_create_bigint_uint64");
case PrimitiveType.Half:
case PrimitiveType.Float:
case PrimitiveType.Double:
case PrimitiveType.LongDouble:
return ("napi_number", "napi_create_double");
case PrimitiveType.Int128:
case PrimitiveType.UInt128:
case PrimitiveType.Float128:
return ("napi_bigint", "napi_create_bigint_words");
case PrimitiveType.String:
return ("napi_string", "napi_create_string_latin1");
case PrimitiveType.Null:
return ("napi_null", "napi_get_null");
case PrimitiveType.Void:
return ("napi_undefined", "napi_get_undefined");
case PrimitiveType.IntPtr:
case PrimitiveType.UIntPtr:
case PrimitiveType.Decimal:
default:
throw new ArgumentOutOfRangeException(nameof(type), type, null);
}
}
@ -133,55 +133,55 @@ namespace CppSharp.Generators.NAPI @@ -133,55 +133,55 @@ namespace CppSharp.Generators.NAPI
switch (primitive)
{
case PrimitiveType.Bool:
case PrimitiveType.WideChar:
case PrimitiveType.Char:
case PrimitiveType.SChar:
case PrimitiveType.Char16:
case PrimitiveType.Char32:
case PrimitiveType.Short:
case PrimitiveType.Int:
case PrimitiveType.Long:
case PrimitiveType.UChar:
case PrimitiveType.UShort:
case PrimitiveType.UInt:
case PrimitiveType.ULong:
case PrimitiveType.LongLong:
case PrimitiveType.ULongLong:
case PrimitiveType.Half:
case PrimitiveType.Float:
case PrimitiveType.Double:
case PrimitiveType.LongDouble:
Context.Before.WriteLine($"napi_value {result};");
Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}, &{result});");
Context.Before.WriteLine("assert(status == napi_ok);");
Context.Return.Write(result);
return true;
case PrimitiveType.Int128:
case PrimitiveType.UInt128:
case PrimitiveType.Float128:
return true;
case PrimitiveType.String:
Context.Before.WriteLine($"napi_value {result};");
Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}, NAPI_AUTO_LENGTH, &{result});");
Context.Before.WriteLine("assert(status == napi_ok);");
Context.Return.Write(result);
return true;
case PrimitiveType.Null:
Context.Before.WriteLine($"napi_value {result};");
Context.Before.WriteLine($"status = {func}(env, &{result});");
Context.Before.WriteLine("assert(status == napi_ok);");
Context.Return.Write(result);
return true;
case PrimitiveType.IntPtr:
case PrimitiveType.UIntPtr:
case PrimitiveType.Decimal:
default:
throw new NotImplementedException();
case PrimitiveType.Bool:
case PrimitiveType.WideChar:
case PrimitiveType.Char:
case PrimitiveType.SChar:
case PrimitiveType.Char16:
case PrimitiveType.Char32:
case PrimitiveType.Short:
case PrimitiveType.Int:
case PrimitiveType.Long:
case PrimitiveType.UChar:
case PrimitiveType.UShort:
case PrimitiveType.UInt:
case PrimitiveType.ULong:
case PrimitiveType.LongLong:
case PrimitiveType.ULongLong:
case PrimitiveType.Half:
case PrimitiveType.Float:
case PrimitiveType.Double:
case PrimitiveType.LongDouble:
Context.Before.WriteLine($"napi_value {result};");
Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}, &{result});");
Context.Before.WriteLine("assert(status == napi_ok);");
Context.Return.Write(result);
return true;
case PrimitiveType.Int128:
case PrimitiveType.UInt128:
case PrimitiveType.Float128:
return true;
case PrimitiveType.String:
Context.Before.WriteLine($"napi_value {result};");
Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}, NAPI_AUTO_LENGTH, &{result});");
Context.Before.WriteLine("assert(status == napi_ok);");
Context.Return.Write(result);
return true;
case PrimitiveType.Null:
Context.Before.WriteLine($"napi_value {result};");
Context.Before.WriteLine($"status = {func}(env, &{result});");
Context.Before.WriteLine("assert(status == napi_ok);");
Context.Return.Write(result);
return true;
case PrimitiveType.IntPtr:
case PrimitiveType.UIntPtr:
case PrimitiveType.Decimal:
default:
throw new NotImplementedException();
}
}
@ -255,15 +255,15 @@ namespace CppSharp.Generators.NAPI @@ -255,15 +255,15 @@ namespace CppSharp.Generators.NAPI
Context.Before.WriteLine("assert(status == napi_ok);");
Context.Before.NewLine();
/*
var refId = $"__{Context.ReturnVarName}_ref";
Context.Before.WriteLine($"napi_ref {refId};");
/*
var refId = $"__{Context.ReturnVarName}_ref";
Context.Before.WriteLine($"napi_ref {refId};");
var dtorId = $"dtor_{NAPISources.GetCIdentifier(Context.Context, ctor)}";
Context.Before.WriteLine($"status = napi_wrap(env, _this, {instanceId}, {dtorId}" +
$", nullptr, &{refId});");
Context.Before.WriteLine("assert(status == napi_ok);");
*/
var dtorId = $"dtor_{NAPISources.GetCIdentifier(Context.Context, ctor)}";
Context.Before.WriteLine($"status = napi_wrap(env, _this, {instanceId}, {dtorId}" +
$", nullptr, &{refId});");
Context.Before.WriteLine("assert(status == napi_ok);");
*/
Context.Return.Write($"{instanceId}");
return true;
@ -332,7 +332,7 @@ namespace CppSharp.Generators.NAPI @@ -332,7 +332,7 @@ namespace CppSharp.Generators.NAPI
public class NAPIMarshalManagedToNativePrinter : MarshalPrinter<MarshalContext, CppTypePrinter>
{
public NAPIMarshalManagedToNativePrinter(MarshalContext ctx)
public NAPIMarshalManagedToNativePrinter(MarshalContext ctx)
: base(ctx)
{
Context.MarshalToNative = this;
@ -365,9 +365,9 @@ namespace CppSharp.Generators.NAPI @@ -365,9 +365,9 @@ namespace CppSharp.Generators.NAPI
switch (array.SizeType)
{
default:
Context.Return.Write("nullptr");
break;
default:
Context.Return.Write("nullptr");
break;
}
return true;
@ -450,54 +450,54 @@ namespace CppSharp.Generators.NAPI @@ -450,54 +450,54 @@ namespace CppSharp.Generators.NAPI
public static (string func, string type, string cast) GetNAPIPrimitiveGetter(PrimitiveType type)
{
switch(type)
switch (type)
{
case PrimitiveType.Bool:
return ("napi_get_value_bool", "bool", "bool");
case PrimitiveType.WideChar:
return ("napi_get_value_int32", "int32_t", "wchar_t");
case PrimitiveType.Char:
case PrimitiveType.SChar:
return ("napi_get_value_int32", "int32_t", "char");
case PrimitiveType.Char16:
return ("napi_get_value_int32", "int32_t", "char16_t");
case PrimitiveType.Char32:
return ("napi_get_value_int32", "int32_t", "char32_t");
case PrimitiveType.Short:
case PrimitiveType.Int:
case PrimitiveType.Long:
return ("napi_get_value_int32", "int32_t", null);
case PrimitiveType.UChar:
case PrimitiveType.UShort:
case PrimitiveType.UInt:
case PrimitiveType.ULong:
return ("napi_get_value_uint32", "uint32_t", null);
case PrimitiveType.LongLong:
return ("napi_get_value_bigint_int64", "int64_t", null);
case PrimitiveType.ULongLong:
return ("napi_get_value_bigint_uint64", "uint64_t", null);
case PrimitiveType.Half:
case PrimitiveType.Float:
return ("napi_get_value_double", "double", "float");
case PrimitiveType.Double:
case PrimitiveType.LongDouble:
return ("napi_get_value_double", "double", null);
case PrimitiveType.Int128:
case PrimitiveType.UInt128:
case PrimitiveType.Float128:
return (null, null, null);
case PrimitiveType.String:
return ("napi_get_value_string_utf8", "char*", null);
case PrimitiveType.Null:
return ("napi_get_null", null, null);
case PrimitiveType.Void:
return (null, null, null);
case PrimitiveType.IntPtr:
case PrimitiveType.UIntPtr:
return (null, null, null);
case PrimitiveType.Decimal:
default:
throw new NotImplementedException();
case PrimitiveType.Bool:
return ("napi_get_value_bool", "bool", "bool");
case PrimitiveType.WideChar:
return ("napi_get_value_int32", "int32_t", "wchar_t");
case PrimitiveType.Char:
case PrimitiveType.SChar:
return ("napi_get_value_int32", "int32_t", "char");
case PrimitiveType.Char16:
return ("napi_get_value_int32", "int32_t", "char16_t");
case PrimitiveType.Char32:
return ("napi_get_value_int32", "int32_t", "char32_t");
case PrimitiveType.Short:
case PrimitiveType.Int:
case PrimitiveType.Long:
return ("napi_get_value_int32", "int32_t", null);
case PrimitiveType.UChar:
case PrimitiveType.UShort:
case PrimitiveType.UInt:
case PrimitiveType.ULong:
return ("napi_get_value_uint32", "uint32_t", null);
case PrimitiveType.LongLong:
return ("napi_get_value_bigint_int64", "int64_t", null);
case PrimitiveType.ULongLong:
return ("napi_get_value_bigint_uint64", "uint64_t", null);
case PrimitiveType.Half:
case PrimitiveType.Float:
return ("napi_get_value_double", "double", "float");
case PrimitiveType.Double:
case PrimitiveType.LongDouble:
return ("napi_get_value_double", "double", null);
case PrimitiveType.Int128:
case PrimitiveType.UInt128:
case PrimitiveType.Float128:
return (null, null, null);
case PrimitiveType.String:
return ("napi_get_value_string_utf8", "char*", null);
case PrimitiveType.Null:
return ("napi_get_null", null, null);
case PrimitiveType.Void:
return (null, null, null);
case PrimitiveType.IntPtr:
case PrimitiveType.UIntPtr:
return (null, null, null);
case PrimitiveType.Decimal:
default:
throw new NotImplementedException();
}
}
@ -507,79 +507,79 @@ namespace CppSharp.Generators.NAPI @@ -507,79 +507,79 @@ namespace CppSharp.Generators.NAPI
switch (primitive)
{
case PrimitiveType.Bool:
case PrimitiveType.WideChar:
case PrimitiveType.Char:
case PrimitiveType.SChar:
case PrimitiveType.Char16:
case PrimitiveType.Char32:
case PrimitiveType.Short:
case PrimitiveType.Int:
case PrimitiveType.Long:
case PrimitiveType.UChar:
case PrimitiveType.UShort:
case PrimitiveType.UInt:
case PrimitiveType.ULong:
case PrimitiveType.Half:
case PrimitiveType.Float:
case PrimitiveType.Double:
case PrimitiveType.LongDouble:
Context.Before.WriteLine($"{type} {Context.Parameter.Name};");
Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}," +
$" &{Context.Parameter.Name});");
if (!string.IsNullOrEmpty(cast))
Context.Return.Write($"({cast})");
Context.Return.Write($"{Context.Parameter.Name}");
return true;
case PrimitiveType.LongLong:
case PrimitiveType.ULongLong:
case PrimitiveType.Int128:
case PrimitiveType.UInt128:
case PrimitiveType.Float128:
Context.Before.WriteLine($"{type} {Context.Parameter.Name};");
Context.Before.WriteLine("bool lossless;");
Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}," +
$" &{Context.Parameter.Name}, &lossless);");
if (!string.IsNullOrEmpty(cast))
Context.Return.Write($"({cast})");
Context.Return.Write($"{Context.Parameter.Name}");
return true;
case PrimitiveType.String:
var size = $"_{Context.Parameter.Name}_size";
Context.Before.WriteLine($"size_t {size};");
Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}, " +
$"nullptr, 0, &{size});");
Context.Before.NewLine();
var buf = $"{Context.Parameter.Name}";
Context.Before.WriteLine($"char* {buf} = (char*) malloc({size});");
Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}, " +
$"nullptr, 0, &{size});");
Context.Before.WriteLine("assert(status == napi_ok);");
Context.Cleanup.WriteLine($"free({buf});");
Context.Return.Write($"{buf}");
return true;
case PrimitiveType.Null:
return true;
case PrimitiveType.Void:
return true;
case PrimitiveType.IntPtr:
case PrimitiveType.UIntPtr:
return true;
case PrimitiveType.Decimal:
default:
throw new NotImplementedException();
case PrimitiveType.Bool:
case PrimitiveType.WideChar:
case PrimitiveType.Char:
case PrimitiveType.SChar:
case PrimitiveType.Char16:
case PrimitiveType.Char32:
case PrimitiveType.Short:
case PrimitiveType.Int:
case PrimitiveType.Long:
case PrimitiveType.UChar:
case PrimitiveType.UShort:
case PrimitiveType.UInt:
case PrimitiveType.ULong:
case PrimitiveType.Half:
case PrimitiveType.Float:
case PrimitiveType.Double:
case PrimitiveType.LongDouble:
Context.Before.WriteLine($"{type} {Context.Parameter.Name};");
Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}," +
$" &{Context.Parameter.Name});");
if (!string.IsNullOrEmpty(cast))
Context.Return.Write($"({cast})");
Context.Return.Write($"{Context.Parameter.Name}");
return true;
case PrimitiveType.LongLong:
case PrimitiveType.ULongLong:
case PrimitiveType.Int128:
case PrimitiveType.UInt128:
case PrimitiveType.Float128:
Context.Before.WriteLine($"{type} {Context.Parameter.Name};");
Context.Before.WriteLine("bool lossless;");
Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}," +
$" &{Context.Parameter.Name}, &lossless);");
if (!string.IsNullOrEmpty(cast))
Context.Return.Write($"({cast})");
Context.Return.Write($"{Context.Parameter.Name}");
return true;
case PrimitiveType.String:
var size = $"_{Context.Parameter.Name}_size";
Context.Before.WriteLine($"size_t {size};");
Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}, " +
$"nullptr, 0, &{size});");
Context.Before.NewLine();
var buf = $"{Context.Parameter.Name}";
Context.Before.WriteLine($"char* {buf} = (char*) malloc({size});");
Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}, " +
$"nullptr, 0, &{size});");
Context.Before.WriteLine("assert(status == napi_ok);");
Context.Cleanup.WriteLine($"free({buf});");
Context.Return.Write($"{buf}");
return true;
case PrimitiveType.Null:
return true;
case PrimitiveType.Void:
return true;
case PrimitiveType.IntPtr:
case PrimitiveType.UIntPtr:
return true;
case PrimitiveType.Decimal:
default:
throw new NotImplementedException();
}
}
@ -672,15 +672,15 @@ namespace CppSharp.Generators.NAPI @@ -672,15 +672,15 @@ namespace CppSharp.Generators.NAPI
{
var type = Context.Parameter.Type.Desugar();
/*
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) &&
typeMap.DoesMarshalling)
{
typeMap.NAPIMarshalToNative(Context);
return;
}
*/
/*
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) &&
typeMap.DoesMarshalling)
{
typeMap.NAPIMarshalToNative(Context);
return;
}
*/
var instance = $"{Context.Parameter.Name}_instance";
Context.Before.WriteLine($"{@class.QualifiedOriginalName}* {instance};");
Context.Before.WriteLine($"status = napi_unwrap(env, _this, (void**) &{instance});");

8
src/Generator/Generators/NAPI/NAPISources.cs

@ -804,9 +804,9 @@ namespace CppSharp.Generators.Cpp @@ -804,9 +804,9 @@ namespace CppSharp.Generators.Cpp
.Select(p => p.Type).Distinct().ToList();
// Consider the alphabet as sequential ordered numbers, one per type.
var Sigma = Enumerable.Range(0, uniqueTypes.Count).Select(i => (char) i).ToArray();
var Sigma = Enumerable.Range(0, uniqueTypes.Count).Select(i => (char)i).ToArray();
var Q = new List<string> {"S"};
var Q = new List<string> { "S" };
var overloadStates = Enumerable.Range(0, functionGroup.Count).Select(i => $"F{i}")
.ToArray();
@ -831,12 +831,12 @@ namespace CppSharp.Generators.Cpp @@ -831,12 +831,12 @@ namespace CppSharp.Generators.Cpp
if (!isLastTransition)
Q.Add(nextState);
Delta.Add(new Transition(curState, (char) typeIndex, nextState));
Delta.Add(new Transition(curState, (char)typeIndex, nextState));
curState = nextState;
}
}
var Q0 = new List<string> {"S"};
var Q0 = new List<string> { "S" };
var F = overloadStates;
var NDFSM = new NDFSM(Q, Sigma, Delta, Q0, F);

88
src/Generator/Generators/NAPI/NAPITypeCheckGen.cs

@ -25,50 +25,50 @@ namespace CppSharp.Generators.Cpp @@ -25,50 +25,50 @@ namespace CppSharp.Generators.Cpp
var condition = string.Empty;
switch (primitive)
{
case PrimitiveType.Bool:
condition = $"NAPI_IS_BOOL(types[{ParameterIndex}])";
break;
case PrimitiveType.Char:
case PrimitiveType.SChar:
case PrimitiveType.UChar:
case PrimitiveType.WideChar:
case PrimitiveType.Short:
case PrimitiveType.UShort:
case PrimitiveType.Int:
case PrimitiveType.Long:
case PrimitiveType.ULong:
condition = $"NAPI_IS_INT32(types[{ParameterIndex}], args[{ParameterIndex}])";
break;
case PrimitiveType.UInt:
condition = $"NAPI_IS_UINT32(types[{ParameterIndex}], args[{ParameterIndex}])";
break;
case PrimitiveType.LongLong:
condition = $"NAPI_IS_INT64(types[{ParameterIndex}], args[{ParameterIndex}])";
break;
case PrimitiveType.ULongLong:
condition = $"NAPI_IS_UINT64(types[{ParameterIndex}], args[{ParameterIndex}])";
break;
case PrimitiveType.Null:
condition = $"NAPI_IS_NULL(types[{ParameterIndex}])";
break;
case PrimitiveType.Half:
case PrimitiveType.Float:
case PrimitiveType.Double:
case PrimitiveType.LongDouble:
condition = $"NAPI_IS_NUMBER(types[{ParameterIndex}])";
break;
case PrimitiveType.Void:
case PrimitiveType.Char16:
case PrimitiveType.Char32:
case PrimitiveType.Int128:
case PrimitiveType.UInt128:
case PrimitiveType.Float128:
case PrimitiveType.IntPtr:
case PrimitiveType.UIntPtr:
case PrimitiveType.String:
case PrimitiveType.Decimal:
default:
throw new NotImplementedException();
case PrimitiveType.Bool:
condition = $"NAPI_IS_BOOL(types[{ParameterIndex}])";
break;
case PrimitiveType.Char:
case PrimitiveType.SChar:
case PrimitiveType.UChar:
case PrimitiveType.WideChar:
case PrimitiveType.Short:
case PrimitiveType.UShort:
case PrimitiveType.Int:
case PrimitiveType.Long:
case PrimitiveType.ULong:
condition = $"NAPI_IS_INT32(types[{ParameterIndex}], args[{ParameterIndex}])";
break;
case PrimitiveType.UInt:
condition = $"NAPI_IS_UINT32(types[{ParameterIndex}], args[{ParameterIndex}])";
break;
case PrimitiveType.LongLong:
condition = $"NAPI_IS_INT64(types[{ParameterIndex}], args[{ParameterIndex}])";
break;
case PrimitiveType.ULongLong:
condition = $"NAPI_IS_UINT64(types[{ParameterIndex}], args[{ParameterIndex}])";
break;
case PrimitiveType.Null:
condition = $"NAPI_IS_NULL(types[{ParameterIndex}])";
break;
case PrimitiveType.Half:
case PrimitiveType.Float:
case PrimitiveType.Double:
case PrimitiveType.LongDouble:
condition = $"NAPI_IS_NUMBER(types[{ParameterIndex}])";
break;
case PrimitiveType.Void:
case PrimitiveType.Char16:
case PrimitiveType.Char32:
case PrimitiveType.Int128:
case PrimitiveType.UInt128:
case PrimitiveType.Float128:
case PrimitiveType.IntPtr:
case PrimitiveType.UIntPtr:
case PrimitiveType.String:
case PrimitiveType.Decimal:
default:
throw new NotImplementedException();
}
Write(condition);

26
src/Generator/Generators/NAPI/NAPITypeCheckPass.cs

@ -32,19 +32,19 @@ namespace CppSharp.Generators.C @@ -32,19 +32,19 @@ namespace CppSharp.Generators.C
{
switch (primitive)
{
case PrimitiveType.LongDouble:
case PrimitiveType.Char16:
case PrimitiveType.Char32:
case PrimitiveType.Int128:
case PrimitiveType.UInt128:
case PrimitiveType.Float128:
case PrimitiveType.IntPtr:
case PrimitiveType.UIntPtr:
case PrimitiveType.Decimal:
Diagnostics.Warning($"Unsupported decl: {decl.QualifiedName}");
return false;
default:
return true;
case PrimitiveType.LongDouble:
case PrimitiveType.Char16:
case PrimitiveType.Char32:
case PrimitiveType.Int128:
case PrimitiveType.UInt128:
case PrimitiveType.Float128:
case PrimitiveType.IntPtr:
case PrimitiveType.UIntPtr:
case PrimitiveType.Decimal:
Diagnostics.Warning($"Unsupported decl: {decl.QualifiedName}");
return false;
default:
return true;
}
}

2
src/Generator/Generators/QuickJS/QuickJSHeaders.cs

@ -16,7 +16,7 @@ namespace CppSharp.Generators.Cpp @@ -16,7 +16,7 @@ namespace CppSharp.Generators.Cpp
CTypePrinter.PushContext(TypePrinterContextKind.Managed);
}
public override bool ShouldGenerateNamespaces => false;
public override bool ShouldGenerateNamespaces => false;
public override void Process()
{

272
src/Generator/Generators/QuickJS/QuickJSMarshal.cs

@ -36,13 +36,13 @@ namespace CppSharp.Generators.Cpp @@ -36,13 +36,13 @@ namespace CppSharp.Generators.Cpp
{
switch (array.SizeType)
{
case ArrayType.ArraySize.Constant:
case ArrayType.ArraySize.Incomplete:
case ArrayType.ArraySize.Variable:
Context.Return.Write("nullptr");
break;
default:
throw new System.NotImplementedException();
case ArrayType.ArraySize.Constant:
case ArrayType.ArraySize.Incomplete:
case ArrayType.ArraySize.Variable:
Context.Return.Write("nullptr");
break;
default:
throw new System.NotImplementedException();
}
return true;
@ -78,7 +78,7 @@ namespace CppSharp.Generators.Cpp @@ -78,7 +78,7 @@ namespace CppSharp.Generators.Cpp
Context.ReturnType.Qualifiers.IsConst)
{
var nativeTypePrinter = new CppTypePrinter(Context.Context)
{ PrintTypeQualifiers = false };
{ PrintTypeQualifiers = false };
var returnType = Context.ReturnType.Type.Desugar();
var constlessPointer = new PointerType()
{
@ -148,53 +148,53 @@ namespace CppSharp.Generators.Cpp @@ -148,53 +148,53 @@ namespace CppSharp.Generators.Cpp
switch (primitive)
{
case PrimitiveType.Void:
return true;
case PrimitiveType.Bool:
Context.Before.WriteLine($"JS_NewBool(ctx, {Context.ArgName});");
break;
case PrimitiveType.Char:
case PrimitiveType.Char16:
case PrimitiveType.Char32:
case PrimitiveType.WideChar:
case PrimitiveType.SChar:
case PrimitiveType.UChar:
case PrimitiveType.Short:
case PrimitiveType.UShort:
case PrimitiveType.Int:
case PrimitiveType.Long:
Context.Before.WriteLine($"JS_NewInt32(ctx, {Context.ArgName});");
break;
case PrimitiveType.UInt:
case PrimitiveType.ULong:
Context.Before.WriteLine($"JS_NewUint32(ctx, {Context.ArgName});");
break;
case PrimitiveType.LongLong:
Context.Before.WriteLine($"JS_NewBigInt64(ctx, {Context.ArgName});");
break;
case PrimitiveType.ULongLong:
Context.Before.WriteLine($"JS_NewBigUint64(ctx, {Context.ArgName});");
break;
case PrimitiveType.Float:
case PrimitiveType.Double:
Context.Before.WriteLine($"JS_NewFloat64(ctx, {Context.ArgName});");
break;
case PrimitiveType.LongDouble:
throw new NotImplementedException();
case PrimitiveType.Null:
Context.Before.WriteLine($"JS_NULL;");
break;
default:
throw new NotImplementedException();
case PrimitiveType.Void:
return true;
case PrimitiveType.Bool:
Context.Before.WriteLine($"JS_NewBool(ctx, {Context.ArgName});");
break;
case PrimitiveType.Char:
case PrimitiveType.Char16:
case PrimitiveType.Char32:
case PrimitiveType.WideChar:
case PrimitiveType.SChar:
case PrimitiveType.UChar:
case PrimitiveType.Short:
case PrimitiveType.UShort:
case PrimitiveType.Int:
case PrimitiveType.Long:
Context.Before.WriteLine($"JS_NewInt32(ctx, {Context.ArgName});");
break;
case PrimitiveType.UInt:
case PrimitiveType.ULong:
Context.Before.WriteLine($"JS_NewUint32(ctx, {Context.ArgName});");
break;
case PrimitiveType.LongLong:
Context.Before.WriteLine($"JS_NewBigInt64(ctx, {Context.ArgName});");
break;
case PrimitiveType.ULongLong:
Context.Before.WriteLine($"JS_NewBigUint64(ctx, {Context.ArgName});");
break;
case PrimitiveType.Float:
case PrimitiveType.Double:
Context.Before.WriteLine($"JS_NewFloat64(ctx, {Context.ArgName});");
break;
case PrimitiveType.LongDouble:
throw new NotImplementedException();
case PrimitiveType.Null:
Context.Before.WriteLine($"JS_NULL;");
break;
default:
throw new NotImplementedException();
}
Context.Return.Write(retName);
@ -296,7 +296,7 @@ namespace CppSharp.Generators.Cpp @@ -296,7 +296,7 @@ namespace CppSharp.Generators.Cpp
{
WriteClassInstance(@class.CompleteDeclaration as Class, instance);
return;
}
}
if (!Context.ReturnType.Type.Desugar().IsPointer())
{
@ -371,7 +371,7 @@ namespace CppSharp.Generators.Cpp @@ -371,7 +371,7 @@ namespace CppSharp.Generators.Cpp
public readonly TextGenerator VarPrefix;
public readonly TextGenerator ArgumentPrefix;
public QuickJSMarshalManagedToNativePrinter(MarshalContext ctx)
public QuickJSMarshalManagedToNativePrinter(MarshalContext ctx)
: base(ctx)
{
VarPrefix = new TextGenerator();
@ -407,9 +407,9 @@ namespace CppSharp.Generators.Cpp @@ -407,9 +407,9 @@ namespace CppSharp.Generators.Cpp
switch (array.SizeType)
{
default:
Context.Return.Write("nullptr");
break;
default:
Context.Return.Write("nullptr");
break;
}
return true;
@ -496,82 +496,82 @@ namespace CppSharp.Generators.Cpp @@ -496,82 +496,82 @@ namespace CppSharp.Generators.Cpp
switch (primitive)
{
case PrimitiveType.Void:
return true;
case PrimitiveType.Bool:
Context.Before.WriteLine($"{argName} = JS_ToBool(ctx, argv[{Context.ParameterIndex}]);");
Context.Before.WriteLine($"if ({argName} == -1)");
Context.Before.WriteLineIndent("return JS_EXCEPTION;");
Context.Return.Write($"{argName}");
return true;
case PrimitiveType.Char:
case PrimitiveType.SChar:
case PrimitiveType.UChar:
Context.Before.WriteLine($"int32_t _{argName};");
Context.Before.WriteLine($"if (JS_ToInt32(ctx, &_{argName}, argv[{Context.ParameterIndex}]))");
Context.Before.WriteLineIndent("return JS_EXCEPTION;");
Context.Before.WriteLine($"{argName} = ({type})_{argName};");
Context.Return.Write($"{argName}");
return true;
case PrimitiveType.Short:
case PrimitiveType.UShort:
Context.Before.WriteLine($"int32_t _{argName};");
Context.Before.WriteLine($"if (JS_ToInt32(ctx, &_{argName}, argv[{Context.ParameterIndex}]))");
Context.Before.WriteLineIndent("return JS_EXCEPTION;");
Context.Before.WriteLine($"{argName} = ({type})_{argName};");
Context.Return.Write($"{argName}");
return true;
case PrimitiveType.Int:
case PrimitiveType.Long:
Context.Before.WriteLine($"if (JS_ToInt32(ctx, &{argName}, argv[{Context.ParameterIndex}]))");
Context.Before.WriteLineIndent("return JS_EXCEPTION;");
Context.Return.Write($"{argName}");
return true;
case PrimitiveType.UInt:
case PrimitiveType.ULong:
Context.Before.WriteLine($"if (JS_ToUint32(ctx, &{argName}, argv[{Context.ParameterIndex}]))");
Context.Before.WriteLineIndent("return JS_EXCEPTION;");
Context.Return.Write($"{argName}");
return true;
case PrimitiveType.LongLong:
Context.Before.WriteLine($"int64_t _{argName};");
Context.Before.WriteLine($"if (JS_ToInt64Ext(ctx, &_{argName}, argv[{Context.ParameterIndex}]))");
Context.Before.WriteLineIndent("return JS_EXCEPTION;");
Context.Before.WriteLine($"{argName} = ({type})_{argName};");
Context.Return.Write($"{argName}");
return true;
case PrimitiveType.ULongLong:
Context.Before.WriteLine($"int64_t _{argName};");
Context.Before.WriteLine($"if (JS_ToInt64Ext(ctx, &_{argName}, argv[{Context.ParameterIndex}]))");
Context.Before.WriteLineIndent("return JS_EXCEPTION;");
Context.Before.WriteLine($"{argName} = ({type})_{argName};");
Context.Return.Write($"{argName}");
return true;
case PrimitiveType.Float:
Context.Before.WriteLine($"double _{argName};");
Context.Before.WriteLine($"if (JS_ToFloat64(ctx, &_{argName}, argv[{Context.ParameterIndex}]))");
Context.Before.WriteLineIndent("return JS_EXCEPTION;");
Context.Before.WriteLine($"{argName} = ({type})_{argName};");
Context.Return.Write($"{argName}");
return true;
case PrimitiveType.Double:
Context.Before.WriteLine($"if (JS_ToFloat64(ctx, &{argName}, argv[{Context.ParameterIndex}]))");
Context.Before.WriteLineIndent("return JS_EXCEPTION;");
Context.Return.Write($"{argName}");
return true;
case PrimitiveType.WideChar:
default:
throw new NotImplementedException();
case PrimitiveType.Void:
return true;
case PrimitiveType.Bool:
Context.Before.WriteLine($"{argName} = JS_ToBool(ctx, argv[{Context.ParameterIndex}]);");
Context.Before.WriteLine($"if ({argName} == -1)");
Context.Before.WriteLineIndent("return JS_EXCEPTION;");
Context.Return.Write($"{argName}");
return true;
case PrimitiveType.Char:
case PrimitiveType.SChar:
case PrimitiveType.UChar:
Context.Before.WriteLine($"int32_t _{argName};");
Context.Before.WriteLine($"if (JS_ToInt32(ctx, &_{argName}, argv[{Context.ParameterIndex}]))");
Context.Before.WriteLineIndent("return JS_EXCEPTION;");
Context.Before.WriteLine($"{argName} = ({type})_{argName};");
Context.Return.Write($"{argName}");
return true;
case PrimitiveType.Short:
case PrimitiveType.UShort:
Context.Before.WriteLine($"int32_t _{argName};");
Context.Before.WriteLine($"if (JS_ToInt32(ctx, &_{argName}, argv[{Context.ParameterIndex}]))");
Context.Before.WriteLineIndent("return JS_EXCEPTION;");
Context.Before.WriteLine($"{argName} = ({type})_{argName};");
Context.Return.Write($"{argName}");
return true;
case PrimitiveType.Int:
case PrimitiveType.Long:
Context.Before.WriteLine($"if (JS_ToInt32(ctx, &{argName}, argv[{Context.ParameterIndex}]))");
Context.Before.WriteLineIndent("return JS_EXCEPTION;");
Context.Return.Write($"{argName}");
return true;
case PrimitiveType.UInt:
case PrimitiveType.ULong:
Context.Before.WriteLine($"if (JS_ToUint32(ctx, &{argName}, argv[{Context.ParameterIndex}]))");
Context.Before.WriteLineIndent("return JS_EXCEPTION;");
Context.Return.Write($"{argName}");
return true;
case PrimitiveType.LongLong:
Context.Before.WriteLine($"int64_t _{argName};");
Context.Before.WriteLine($"if (JS_ToInt64Ext(ctx, &_{argName}, argv[{Context.ParameterIndex}]))");
Context.Before.WriteLineIndent("return JS_EXCEPTION;");
Context.Before.WriteLine($"{argName} = ({type})_{argName};");
Context.Return.Write($"{argName}");
return true;
case PrimitiveType.ULongLong:
Context.Before.WriteLine($"int64_t _{argName};");
Context.Before.WriteLine($"if (JS_ToInt64Ext(ctx, &_{argName}, argv[{Context.ParameterIndex}]))");
Context.Before.WriteLineIndent("return JS_EXCEPTION;");
Context.Before.WriteLine($"{argName} = ({type})_{argName};");
Context.Return.Write($"{argName}");
return true;
case PrimitiveType.Float:
Context.Before.WriteLine($"double _{argName};");
Context.Before.WriteLine($"if (JS_ToFloat64(ctx, &_{argName}, argv[{Context.ParameterIndex}]))");
Context.Before.WriteLineIndent("return JS_EXCEPTION;");
Context.Before.WriteLine($"{argName} = ({type})_{argName};");
Context.Return.Write($"{argName}");
return true;
case PrimitiveType.Double:
Context.Before.WriteLine($"if (JS_ToFloat64(ctx, &{argName}, argv[{Context.ParameterIndex}]))");
Context.Before.WriteLineIndent("return JS_EXCEPTION;");
Context.Return.Write($"{argName}");
return true;
case PrimitiveType.WideChar:
default:
throw new NotImplementedException();
}
}

24
src/Generator/Generators/QuickJS/QuickJSSources.cs

@ -289,7 +289,7 @@ namespace CppSharp.Generators.Cpp @@ -289,7 +289,7 @@ namespace CppSharp.Generators.Cpp
//WriteLine($"printf(\"Calling finalizer for {@class.QualifiedOriginalName}\\n\");");
if(ClassNeedsExtraData(@class))
if (ClassNeedsExtraData(@class))
{
// Remove the event connection from the delegate.
// var invokeId = $"event_invoke_{@event.OriginalName}";
@ -456,19 +456,19 @@ namespace CppSharp.Generators.Cpp @@ -456,19 +456,19 @@ namespace CppSharp.Generators.Cpp
//WriteLine($"{@class.QualifiedOriginalName}* instance = data->instance;");
/*
/*
if (!isVoidReturn)
{
CTypePrinter.PushContext(TypePrinterContextKind.Native);
var returnType = function.ReturnType.Visit(CTypePrinter);
CTypePrinter.PopContext();
if (!isVoidReturn)
{
CTypePrinter.PushContext(TypePrinterContextKind.Native);
var returnType = function.ReturnType.Visit(CTypePrinter);
CTypePrinter.PopContext();
Write($"{returnType} {Helpers.ReturnIdentifier} = ");
}
Write($"{returnType} {Helpers.ReturnIdentifier} = ");
}
var @class = function.Namespace as Class;
*/
var @class = function.Namespace as Class;
*/
UnindentAndWriteCloseBrace();
}
@ -783,7 +783,7 @@ namespace CppSharp.Generators.Cpp @@ -783,7 +783,7 @@ namespace CppSharp.Generators.Cpp
{
WriteLine($"{@class.QualifiedOriginalName}* instance;");
}
else if(QuickJSRegister.ClassNeedsExtraData(@class))
else if (QuickJSRegister.ClassNeedsExtraData(@class))
{
var classDataId = $"data_{GetCIdentifier(Context, @class)}";
WriteLine($"auto data = ({classDataId}*) JS_GetOpaque(this_val, 0);");

116
src/Generator/Generators/QuickJS/QuickJSTypeCheckGen.cs

@ -29,64 +29,64 @@ namespace CppSharp.Generators.Cpp @@ -29,64 +29,64 @@ namespace CppSharp.Generators.Cpp
var arg = $"argv[{ParameterIndex}]";
switch (primitive)
{
case PrimitiveType.Bool:
condition = $"JS_IsBool({arg})";
break;
case PrimitiveType.Char:
case PrimitiveType.SChar:
condition = $"JS_IsInt8({arg})";
break;
case PrimitiveType.UChar:
condition = $"JS_IsUInt8({arg})";
break;
case PrimitiveType.WideChar:
condition = $"JS_IsUInt16({arg})";
break;
case PrimitiveType.Short:
condition = $"JS_IsInt16({arg})";
break;
case PrimitiveType.UShort:
condition = $"JS_IsUInt16({arg})";
break;
case PrimitiveType.Int:
case PrimitiveType.Long:
condition = $"JS_IsInt32({arg})";
break;
case PrimitiveType.ULong:
case PrimitiveType.UInt:
condition = $"JS_IsUInt32({arg})";
break;
case PrimitiveType.LongLong:
case PrimitiveType.ULongLong:
case PrimitiveType.Int128:
case PrimitiveType.UInt128:
condition = $"JS_IsBigInt(ctx, {arg})";
break;
case PrimitiveType.Half:
case PrimitiveType.Float:
case PrimitiveType.Double:
condition = $"JS_IsFloat({arg})";
break;
case PrimitiveType.LongDouble:
case PrimitiveType.Float128:
condition = $"JS_IsBigFloat({arg})";
break;
case PrimitiveType.String:
condition = $"JS_IsString({arg}) || JS_IsNull({arg})";
break;
case PrimitiveType.Decimal:
condition = $"JS_IsBigDecimal({arg})";
break;
case PrimitiveType.Null:
condition = $"JS_IsNull({arg})";
break;
case PrimitiveType.Void:
case PrimitiveType.Char16:
case PrimitiveType.Char32:
case PrimitiveType.IntPtr:
case PrimitiveType.UIntPtr:
default:
throw new NotImplementedException();
case PrimitiveType.Bool:
condition = $"JS_IsBool({arg})";
break;
case PrimitiveType.Char:
case PrimitiveType.SChar:
condition = $"JS_IsInt8({arg})";
break;
case PrimitiveType.UChar:
condition = $"JS_IsUInt8({arg})";
break;
case PrimitiveType.WideChar:
condition = $"JS_IsUInt16({arg})";
break;
case PrimitiveType.Short:
condition = $"JS_IsInt16({arg})";
break;
case PrimitiveType.UShort:
condition = $"JS_IsUInt16({arg})";
break;
case PrimitiveType.Int:
case PrimitiveType.Long:
condition = $"JS_IsInt32({arg})";
break;
case PrimitiveType.ULong:
case PrimitiveType.UInt:
condition = $"JS_IsUInt32({arg})";
break;
case PrimitiveType.LongLong:
case PrimitiveType.ULongLong:
case PrimitiveType.Int128:
case PrimitiveType.UInt128:
condition = $"JS_IsBigInt(ctx, {arg})";
break;
case PrimitiveType.Half:
case PrimitiveType.Float:
case PrimitiveType.Double:
condition = $"JS_IsFloat({arg})";
break;
case PrimitiveType.LongDouble:
case PrimitiveType.Float128:
condition = $"JS_IsBigFloat({arg})";
break;
case PrimitiveType.String:
condition = $"JS_IsString({arg}) || JS_IsNull({arg})";
break;
case PrimitiveType.Decimal:
condition = $"JS_IsBigDecimal({arg})";
break;
case PrimitiveType.Null:
condition = $"JS_IsNull({arg})";
break;
case PrimitiveType.Void:
case PrimitiveType.Char16:
case PrimitiveType.Char32:
case PrimitiveType.IntPtr:
case PrimitiveType.UIntPtr:
default:
throw new NotImplementedException();
}
Write(condition);

6
src/Generator/Generators/TS/TSSources.cs

@ -146,7 +146,7 @@ namespace CppSharp.Generators.TS @@ -146,7 +146,7 @@ namespace CppSharp.Generators.TS
return false;
//if (@class.IsOpaque)
// return false;
// return false;
PushBlock(BlockKind.Class, @class);
@ -240,7 +240,7 @@ namespace CppSharp.Generators.TS @@ -240,7 +240,7 @@ namespace CppSharp.Generators.TS
Indent();
var @class = (Class) methods[0].Namespace;
var @class = (Class)methods[0].Namespace;
if (@class.IsValueType)
foreach (var @base in @class.Bases.Where(b => b.IsClass && !b.Class.Ignore))
@ -267,7 +267,7 @@ namespace CppSharp.Generators.TS @@ -267,7 +267,7 @@ namespace CppSharp.Generators.TS
method.Visit(this);
}
foreach(var method in staticMethods)
foreach (var method in staticMethods)
method.Visit(this);
Unindent();

38
src/Generator/Generators/TS/TSTypePrinter.cs

@ -24,7 +24,7 @@ namespace CppSharp.Generators.TS @@ -24,7 +24,7 @@ namespace CppSharp.Generators.TS
return declaration.TranslationUnit?.Module?.LibraryName;
}
public override TypePrinterResult GetDeclName(Declaration declaration, TypePrintScopeKind scope)
public override TypePrinterResult GetDeclName(Declaration declaration, TypePrintScopeKind scope)
{
var result = base.GetDeclName(declaration, scope);
result.Type = result.Type.Replace("::", NamespaceSeparator);
@ -41,7 +41,7 @@ namespace CppSharp.Generators.TS @@ -41,7 +41,7 @@ namespace CppSharp.Generators.TS
return VisitPrimitiveType(builtin.Type);
}
public override TypePrinterResult VisitPrimitiveType(PrimitiveType primitive, TypeQualifiers quals)
public override TypePrinterResult VisitPrimitiveType(PrimitiveType primitive, TypeQualifiers quals)
{
return VisitPrimitiveType(primitive);
}
@ -142,23 +142,23 @@ namespace CppSharp.Generators.TS @@ -142,23 +142,23 @@ namespace CppSharp.Generators.TS
result.Name = param.Name;
/*
if (param.DefaultArgument != null && Options.GenerateDefaultValuesForArguments)
{
try
{
var expressionPrinter = new CSharpExpressionPrinter(this);
var defaultValue = expressionPrinter.VisitParameter(param);
return $"{result} = {defaultValue}";
}
catch (Exception)
{
var function = param.Namespace as Function;
Diagnostics.Warning($"Error printing default argument expression: " +
$"{function.QualifiedOriginalName}({param.OriginalName})");
}
}
*/
/*
if (param.DefaultArgument != null && Options.GenerateDefaultValuesForArguments)
{
try
{
var expressionPrinter = new CSharpExpressionPrinter(this);
var defaultValue = expressionPrinter.VisitParameter(param);
return $"{result} = {defaultValue}";
}
catch (Exception)
{
var function = param.Namespace as Function;
Diagnostics.Warning($"Error printing default argument expression: " +
$"{function.QualifiedOriginalName}({param.OriginalName})");
}
}
*/
return $"{result}";
}

10
src/Generator/Library.cs

@ -286,7 +286,7 @@ namespace CppSharp @@ -286,7 +286,7 @@ namespace CppSharp
{
var units = list.Select(item => item.TranslationUnit)
.GroupBy(x => x)
.Select(y => new {Element = y.Key, Counter = y.Count()});
.Select(y => new { Element = y.Key, Counter = y.Count() });
var translationUnit = units.OrderByDescending(u => u.Counter)
.FirstOrDefault()?.Element ?? null;
@ -341,7 +341,7 @@ namespace CppSharp @@ -341,7 +341,7 @@ namespace CppSharp
maxValue = (ulong)@enum.Items.Max(i => Math.Max(0, unchecked((long)i.Value)));
minValue = @enum.Items.Min(i => unchecked((long)i.Value));
}
@enum.BuiltinType = new BuiltinType(GetUnderlyingTypeForEnumValue(maxValue, minValue));
@enum.Type = @enum.BuiltinType;
@ -493,8 +493,8 @@ namespace CppSharp @@ -493,8 +493,8 @@ namespace CppSharp
string className, string methodName, int parameterCount, int parameterIndex,
ParameterUsage usage)
{
if (parameterIndex <= 0 )
throw new ArgumentException("parameterIndex");
if (parameterIndex <= 0)
throw new ArgumentException("parameterIndex");
var @class = context.FindCompleteClass(className);
@ -635,7 +635,7 @@ namespace CppSharp @@ -635,7 +635,7 @@ namespace CppSharp
public static void IgnoreHeadersWithName(this ASTContext context, IEnumerable<string> patterns)
{
foreach(var pattern in patterns)
foreach (var pattern in patterns)
context.IgnoreHeadersWithName(pattern);
}

20
src/Generator/Passes/CheckAbiParameters.cs

@ -33,20 +33,20 @@ namespace CppSharp.Passes @@ -33,20 +33,20 @@ namespace CppSharp.Passes
var isReturnIndirect = function.IsReturnIndirect || (
Context.ParserOptions.IsMicrosoftAbi &&
function is Method &&
!function.ReturnType.Type.Desugar().IsAddress() &&
function.ReturnType.Type.Desugar().TryGetDeclaration(out Class returnTypeDecl) &&
returnTypeDecl.IsPOD &&
!function.ReturnType.Type.Desugar().IsAddress() &&
function.ReturnType.Type.Desugar().TryGetDeclaration(out Class returnTypeDecl) &&
returnTypeDecl.IsPOD &&
returnTypeDecl.Layout.Size <= 8);
if (isReturnIndirect)
{
var indirectParam = new Parameter()
{
Kind = ParameterKind.IndirectReturnType,
QualifiedType = function.ReturnType,
Name = "return",
Namespace = function
};
{
Kind = ParameterKind.IndirectReturnType,
QualifiedType = function.ReturnType,
Name = "return",
Namespace = function
};
function.Parameters.Insert(0, indirectParam);
function.ReturnType = new QualifiedType(new BuiltinType(
@ -59,7 +59,7 @@ namespace CppSharp.Passes @@ -59,7 +59,7 @@ namespace CppSharp.Passes
{
// This flag should only be true on methods.
var classType = new QualifiedType(new TagType(method.Namespace),
new TypeQualifiers {IsConst = true});
new TypeQualifiers { IsConst = true });
function.ReturnType = new QualifiedType(new PointerType(classType));
}

4
src/Generator/Passes/CheckAmbiguousFunctions.cs

@ -46,7 +46,7 @@ namespace CppSharp.Passes @@ -46,7 +46,7 @@ namespace CppSharp.Passes
if (!overload.IsGenerated) continue;
var ambiguous =
var ambiguous =
function.OperatorKind == CXXOperatorKind.Conversion ||
function.OperatorKind == CXXOperatorKind.ExplicitConversion
? CheckConversionAmbiguity(function, overload)
@ -185,7 +185,7 @@ namespace CppSharp.Passes @@ -185,7 +185,7 @@ namespace CppSharp.Passes
var type1 = method1.ReturnType.Type.Desugar();
var type2 = method2.ReturnType.Type.Desugar();
if (type1 is PointerType pointerType1 &&
if (type1 is PointerType pointerType1 &&
type2 is PointerType pointerType2)
{
type1 = pointerType1.GetPointee();

8
src/Generator/Passes/CheckIgnoredDecls.cs

@ -145,8 +145,8 @@ namespace CppSharp.Passes @@ -145,8 +145,8 @@ namespace CppSharp.Passes
public override bool VisitFunctionTemplateDecl(FunctionTemplate decl)
{
if (!base.VisitFunctionTemplateDecl(decl))
return false;
if (!base.VisitFunctionTemplateDecl(decl))
return false;
if (decl.TemplatedFunction.IsDependent && !decl.IsExplicitlyGenerated)
{
@ -454,7 +454,7 @@ namespace CppSharp.Passes @@ -454,7 +454,7 @@ namespace CppSharp.Passes
/// </summary>
private bool HasInvalidType(ITypedDecl decl, out string msg)
{
return HasInvalidType(decl.Type, (Declaration) decl, out msg);
return HasInvalidType(decl.Type, (Declaration)decl, out msg);
}
private bool HasInvalidType(Type type, Declaration decl, out string msg)
@ -506,7 +506,7 @@ namespace CppSharp.Passes @@ -506,7 +506,7 @@ namespace CppSharp.Passes
}
var @class = decl as Class;
if (@class != null && @class.IsOpaque && !@class.IsDependent &&
if (@class != null && @class.IsOpaque && !@class.IsDependent &&
!(@class is ClassTemplateSpecialization))
{
msg = null;

2
src/Generator/Passes/CheckMacrosPass.cs

@ -177,7 +177,7 @@ namespace CppSharp.Passes @@ -177,7 +177,7 @@ namespace CppSharp.Passes
var quals = field.QualifiedType.Qualifiers;
quals.IsConst = true;
var qualType = field.QualifiedType;
var qualType = field.QualifiedType;
qualType.Qualifiers = quals;
field.QualifiedType = qualType;

34
src/Generator/Passes/CheckOperatorsOverloads.cs

@ -81,24 +81,24 @@ namespace CppSharp.Passes @@ -81,24 +81,24 @@ namespace CppSharp.Passes
private void CreateIndexer(Class @class, Method @operator)
{
var property = new Property
{
Name = "Item",
QualifiedType = @operator.ReturnType,
Access = @operator.Access,
Namespace = @class,
GetMethod = @operator
};
{
Name = "Item",
QualifiedType = @operator.ReturnType,
Access = @operator.Access,
Namespace = @class,
GetMethod = @operator
};
var returnType = @operator.Type;
if (returnType.IsAddress() &&
!returnType.GetQualifiedPointee().Type.Desugar().IsPrimitiveType(PrimitiveType.Void))
{
var pointer = (PointerType) returnType;
var pointer = (PointerType)returnType;
var qualifiedPointee = pointer.QualifiedPointee;
if (!qualifiedPointee.Qualifiers.IsConst)
property.SetMethod = @operator;
}
// If we've a setter use the pointee as the type of the property.
var pointerType = property.Type as PointerType;
if (pointerType != null && property.HasSetter)
@ -130,14 +130,14 @@ namespace CppSharp.Passes @@ -130,14 +130,14 @@ namespace CppSharp.Passes
continue;
var method = new Method()
{
Name = Operators.GetOperatorIdentifier(missingKind),
Namespace = @class,
SynthKind = FunctionSynthKind.ComplementOperator,
Kind = CXXMethodKind.Operator,
OperatorKind = missingKind,
ReturnType = op.ReturnType
};
{
Name = Operators.GetOperatorIdentifier(missingKind),
Namespace = @class,
SynthKind = FunctionSynthKind.ComplementOperator,
Kind = CXXMethodKind.Operator,
OperatorKind = missingKind,
ReturnType = op.ReturnType
};
method.Parameters.AddRange(op.Parameters.Select(
p => new Parameter(p) { Namespace = method }));

4
src/Generator/Passes/CheckStaticClass.cs

@ -31,7 +31,7 @@ namespace CppSharp.Passes @@ -31,7 +31,7 @@ namespace CppSharp.Passes
{
if (decl.Access != AccessSpecifier.Protected)
return false;
var @class = decl.Namespace as Class;
return @class != null && @class.IsStatic;
}
@ -58,7 +58,7 @@ namespace CppSharp.Passes @@ -58,7 +58,7 @@ namespace CppSharp.Passes
if (tag == null)
return false;
var @class = (Class) function.Namespace;
var @class = (Class)function.Namespace;
var decl = tag.Declaration;
if (!(decl is Class))

4
src/Generator/Passes/CleanCommentsPass.cs

@ -52,14 +52,14 @@ namespace CppSharp.Passes @@ -52,14 +52,14 @@ namespace CppSharp.Passes
i + 1 < comment.Content.Count &&
comment.Content[i + 1].Kind == DocumentationCommentKind.TextComment)
{
var textComment = (TextComment) comment.Content[i + 1];
var textComment = (TextComment)comment.Content[i + 1];
textComment.Text = Helpers.RegexCommentCommandLeftover.Replace(
textComment.Text, string.Empty);
}
}
foreach (var item in comment.Content.Where(c => c.Kind == DocumentationCommentKind.TextComment))
{
var textComment = (TextComment) item;
var textComment = (TextComment)item;
if (textComment.Text.StartsWith("<", StringComparison.Ordinal))
textComment.Text = $"{textComment.Text}>";

12
src/Generator/Passes/ConstructorToConversionOperatorPass.cs

@ -82,12 +82,12 @@ namespace CppSharp.Passes @@ -82,12 +82,12 @@ namespace CppSharp.Passes
FunctionType = method.FunctionType
};
conversionOperator.Parameters.Add(new Parameter(parameter)
{
Namespace = conversionOperator,
DefaultArgument = null,
OriginalDefaultArgument = null
});
((Class) method.Namespace).Methods.Add(conversionOperator);
{
Namespace = conversionOperator,
DefaultArgument = null,
OriginalDefaultArgument = null
});
((Class)method.Namespace).Methods.Add(conversionOperator);
return true;
}

36
src/Generator/Passes/DelegatesPass.cs

@ -63,11 +63,11 @@ namespace CppSharp.Passes @@ -63,11 +63,11 @@ namespace CppSharp.Passes
return false;
var functionType = new FunctionType
{
CallingConvention = method.CallingConvention,
IsDependent = method.IsDependent,
ReturnType = method.ReturnType
};
{
CallingConvention = method.CallingConvention,
IsDependent = method.IsDependent,
ReturnType = method.ReturnType
};
TypePrinter.PushMarshalKind(MarshalKind.VTableReturnValue);
functionType.Parameters.AddRange(
@ -92,7 +92,7 @@ namespace CppSharp.Passes @@ -92,7 +92,7 @@ namespace CppSharp.Passes
public override bool VisitParameterDecl(Parameter parameter)
{
if(parameter.Namespace?.TranslationUnit?.Module == null && namespaces.Count > 0)
if (parameter.Namespace?.TranslationUnit?.Module == null && namespaces.Count > 0)
parameter.Namespace = namespaces.Peek();
if (!base.VisitDeclaration(parameter) || parameter.Namespace == null ||
@ -170,7 +170,7 @@ namespace CppSharp.Passes @@ -170,7 +170,7 @@ namespace CppSharp.Passes
existingDelegate.Access = access;
// Check if there is an existing delegate with a different calling convention
if (((FunctionType) existingDelegate.Type.GetPointee()).CallingConvention ==
if (((FunctionType)existingDelegate.Type.GetPointee()).CallingConvention ==
functionType.CallingConvention)
return existingDelegate;
@ -184,13 +184,13 @@ namespace CppSharp.Passes @@ -184,13 +184,13 @@ namespace CppSharp.Passes
var namespaceDelegates = GetDeclContextForDelegates(declarationContext);
var delegateType = new QualifiedType(new PointerType(new QualifiedType(functionType)));
existingDelegate = new TypedefDecl
{
Access = access,
Name = delegateName,
Namespace = namespaceDelegates,
QualifiedType = delegateType,
IsSynthetized = true
};
{
Access = access,
Name = delegateName,
Namespace = namespaceDelegates,
QualifiedType = delegateType,
IsSynthetized = true
};
delegates.Add(existingDelegate);
return existingDelegate;
@ -235,10 +235,10 @@ namespace CppSharp.Passes @@ -235,10 +235,10 @@ namespace CppSharp.Passes
parent = module.Units.Last(u => u.IsGenerated);
var namespaceDelegates = new Namespace
{
Name = "Delegates",
Namespace = parent
};
{
Name = "Delegates",
Namespace = parent
};
namespacesDelegates.Add(module, namespaceDelegates);
return namespaceDelegates;

2
src/Generator/Passes/ExpressionHelper.cs

@ -433,7 +433,7 @@ namespace CppSharp.Internal @@ -433,7 +433,7 @@ namespace CppSharp.Internal
// ArgumentOutOfRangeException.
var initialQuoteIndex = result.IndexOf("\"");
if (initialQuoteIndex >= 0)
{
{
result = result[initialQuoteIndex..];
return true;
}

16
src/Generator/Passes/FlattenAnonymousTypesToFields.cs

@ -44,7 +44,7 @@ namespace CppSharp.Passes @@ -44,7 +44,7 @@ namespace CppSharp.Passes
!field.QualifiedType.Type.Desugar().TryGetClass(out fieldType) ||
!string.IsNullOrEmpty(fieldType.OriginalName))
continue;
ReplaceLayoutField(@class, i, fieldType);
fieldType.Fields.Clear();
fieldType.ExplicitlyIgnore();
@ -77,13 +77,13 @@ namespace CppSharp.Passes @@ -77,13 +77,13 @@ namespace CppSharp.Passes
{
LayoutField nestedLayoutField = fieldType.Layout.Fields[j];
var layoutField = new LayoutField
{
Expression = nestedLayoutField.Expression,
FieldPtr = nestedLayoutField.FieldPtr,
Name = nestedLayoutField.Name,
Offset = nestedLayoutField.Offset + offset,
QualifiedType = nestedLayoutField.QualifiedType
};
{
Expression = nestedLayoutField.Expression,
FieldPtr = nestedLayoutField.FieldPtr,
Name = nestedLayoutField.Name,
Offset = nestedLayoutField.Offset + offset,
QualifiedType = nestedLayoutField.QualifiedType
};
@class.Layout.Fields.Insert(i + j, layoutField);
}
}

30
src/Generator/Passes/FunctionToInstanceMethodPass.cs

@ -46,21 +46,21 @@ namespace CppSharp.Passes @@ -46,21 +46,21 @@ namespace CppSharp.Passes
// Create a new fake method so it acts as an instance method.
var method = new Method
{
Namespace = @class,
OriginalNamespace = function.Namespace,
Name = function.Name,
OriginalName = function.OriginalName,
Mangled = function.Mangled,
Access = AccessSpecifier.Public,
Kind = CXXMethodKind.Normal,
ReturnType = function.ReturnType,
CallingConvention = function.CallingConvention,
IsVariadic = function.IsVariadic,
IsInline = function.IsInline,
Conversion = MethodConversionKind.FunctionToInstanceMethod,
FunctionType = function.FunctionType
};
{
Namespace = @class,
OriginalNamespace = function.Namespace,
Name = function.Name,
OriginalName = function.OriginalName,
Mangled = function.Mangled,
Access = AccessSpecifier.Public,
Kind = CXXMethodKind.Normal,
ReturnType = function.ReturnType,
CallingConvention = function.CallingConvention,
IsVariadic = function.IsVariadic,
IsInline = function.IsInline,
Conversion = MethodConversionKind.FunctionToInstanceMethod,
FunctionType = function.FunctionType
};
method.Parameters.AddRange(function.Parameters.Select(
p => new Parameter(p) { Namespace = method }));

26
src/Generator/Passes/GenerateAbstractImplementationsPass.cs

@ -64,13 +64,13 @@ namespace CppSharp.Passes @@ -64,13 +64,13 @@ namespace CppSharp.Passes
foreach (var abstractMethod in abstractMethods)
{
var impl = new Method(abstractMethod)
{
Namespace = internalImpl,
OriginalFunction = abstractMethod,
IsPure = false,
SynthKind = abstractMethod.SynthKind == FunctionSynthKind.DefaultValueOverload ?
{
Namespace = internalImpl,
OriginalFunction = abstractMethod,
IsPure = false,
SynthKind = abstractMethod.SynthKind == FunctionSynthKind.DefaultValueOverload ?
FunctionSynthKind.DefaultValueOverload : FunctionSynthKind.AbstractImplCall
};
};
impl.OverriddenMethods.Clear();
impl.OverriddenMethods.Add(abstractMethod);
if (abstractMethod.OriginalReturnType.Type.IsDependentPointer() ||
@ -90,11 +90,11 @@ namespace CppSharp.Passes @@ -90,11 +90,11 @@ namespace CppSharp.Passes
private static T GetInternalImpl<T>(T @class) where T : Class, new()
{
var internalImpl = new T
{
Name = @class.Name + "Internal",
Access = AccessSpecifier.Private,
Namespace = @class.Namespace
};
{
Name = @class.Name + "Internal",
Access = AccessSpecifier.Private,
Namespace = @class.Namespace
};
if (@class.IsDependent)
{
internalImpl.IsDependent = true;
@ -122,8 +122,8 @@ namespace CppSharp.Passes @@ -122,8 +122,8 @@ namespace CppSharp.Passes
for (var i = abstractMethods.Count - 1; i >= 0; i--)
{
var @abstract = abstractMethods[i];
var @override = overriddenMethods.Find(m => m.Name == @abstract.Name &&
m.ReturnType == @abstract.ReturnType &&
var @override = overriddenMethods.Find(m => m.Name == @abstract.Name &&
m.ReturnType == @abstract.ReturnType &&
m.Parameters.SequenceEqual(@abstract.Parameters, ParameterTypeComparer.Instance));
if (@override != null)
{

4
src/Generator/Passes/GenerateSymbolsPass.cs

@ -181,7 +181,7 @@ namespace CppSharp.Passes @@ -181,7 +181,7 @@ namespace CppSharp.Passes
{
if (symbolsCodeGenerators.ContainsKey(module))
return symbolsCodeGenerators[module];
var symbolsCodeGenerator = new SymbolsCodeGenerator(Context, module.Units);
symbolsCodeGenerators[module] = symbolsCodeGenerator;
symbolsCodeGenerator.Process();
@ -237,7 +237,7 @@ namespace CppSharp.Passes @@ -237,7 +237,7 @@ namespace CppSharp.Passes
Diagnostics.Error(errorMessage);
else
compiledLibraries[module] = new CompiledLibrary
{ OutputDir = outputDir, Library = module.SymbolsLibraryName };
{ OutputDir = outputDir, Library = module.SymbolsLibraryName };
RemainingCompilationTasks--;
}).Start();
}

10
src/Generator/Passes/GetterSetterToPropertyPass.cs

@ -119,7 +119,7 @@ namespace CppSharp.Passes @@ -119,7 +119,7 @@ namespace CppSharp.Passes
string name, QualifiedType type, bool isSetter = false)
{
Type underlyingType = GetUnderlyingType(type);
Class @class = (Class) method.Namespace;
Class @class = (Class)method.Namespace;
Property property = properties.Find(
p => p.Field == null &&
@ -144,10 +144,10 @@ namespace CppSharp.Passes @@ -144,10 +144,10 @@ namespace CppSharp.Passes
property.QualifiedType = method.OriginalReturnType;
}
property.Access = (AccessSpecifier) Math.Max(
(int) (property.GetMethod ?? property.SetMethod).Access,
(int) method.Access);
property.Access = (AccessSpecifier)Math.Max(
(int)(property.GetMethod ?? property.SetMethod).Access,
(int)method.Access);
if (method.ExplicitInterfaceImpl != null)
property.ExplicitInterfaceImpl = method.ExplicitInterfaceImpl;
}

2
src/Generator/Passes/HandleDefaultParamValuesPass.cs

@ -80,7 +80,7 @@ namespace CppSharp.Passes @@ -80,7 +80,7 @@ namespace CppSharp.Passes
overload.Parameters[i].DefaultArgument = null;
if (method != null)
((Class) function.Namespace).Methods.Add((Method) overload);
((Class)function.Namespace).Methods.Add((Method)overload);
else
{
List<Function> functions;

2
src/Generator/Passes/MakeProtectedNestedTypesPublicPass.cs

@ -14,7 +14,7 @@ namespace CppSharp.Passes @@ -14,7 +14,7 @@ namespace CppSharp.Passes
if (!base.VisitClassDecl(@class))
return false;
(from d in ((IEnumerable<Declaration>) @class.Classes).Concat(@class.Enums)
(from d in ((IEnumerable<Declaration>)@class.Classes).Concat(@class.Enums)
where d.Access == AccessSpecifier.Protected
select d).All(d => { d.Access = AccessSpecifier.Public; return true; });

4
src/Generator/Passes/MultipleInheritancePass.cs

@ -72,7 +72,7 @@ namespace CppSharp.Passes @@ -72,7 +72,7 @@ namespace CppSharp.Passes
protected Class GetInterface(Class @base)
{
if (@base.CompleteDeclaration != null)
@base = (Class) @base.CompleteDeclaration;
@base = (Class)@base.CompleteDeclaration;
return interfaces.FirstOrDefault(i => i.OriginalClass == @base) ??
GetNewInterface("I" + @base.Name, @base);
@ -189,7 +189,7 @@ namespace CppSharp.Passes @@ -189,7 +189,7 @@ namespace CppSharp.Passes
templatedInterfaces[@base] = @interface;
foreach (var spec in @base.Specializations)
@interface.Specializations.Add(
(ClassTemplateSpecialization) GetNewInterface(name, spec));
(ClassTemplateSpecialization)GetNewInterface(name, spec));
}
return @interface;
}

2
src/Generator/Passes/ParamTypeToInterfacePass.cs

@ -127,7 +127,7 @@ namespace CppSharp.Passes @@ -127,7 +127,7 @@ namespace CppSharp.Passes
if (@interface == null)
return;
type.Type = (Type) type.Type.Clone();
type.Type = (Type)type.Type.Clone();
finalType = (type.Type.GetFinalPointee() ?? type.Type).Desugar();
finalType.TryGetClass(out @class, @interface);
}

38
src/Generator/Passes/Pass.cs

@ -60,26 +60,26 @@ namespace CppSharp.Passes @@ -60,26 +60,26 @@ namespace CppSharp.Passes
public virtual void HandleBlock(Block block)
{
switch(block.Kind)
switch (block.Kind)
{
case BlockKind.Class:
VisitClass(block);
break;
case BlockKind.Method:
VisitMethod(block);
break;
case BlockKind.Constructor:
VisitConstructor(block);
break;
case BlockKind.ConstructorBody:
VisitConstructorBody(block);
break;
case BlockKind.Namespace:
VisitNamespace(block);
break;
case BlockKind.Includes:
VisitIncludes(block);
break;
case BlockKind.Class:
VisitClass(block);
break;
case BlockKind.Method:
VisitMethod(block);
break;
case BlockKind.Constructor:
VisitConstructor(block);
break;
case BlockKind.ConstructorBody:
VisitConstructorBody(block);
break;
case BlockKind.Namespace:
VisitNamespace(block);
break;
case BlockKind.Includes:
VisitIncludes(block);
break;
}
foreach (var childBlock in block.Blocks)

32
src/Generator/Passes/RenamePass.cs

@ -47,7 +47,7 @@ namespace CppSharp.Passes @@ -47,7 +47,7 @@ namespace CppSharp.Passes
{
Method rootBaseMethod;
if (method.OriginalNamespace is Class @class && @class.IsInterface)
rootBaseMethod = (Method) method.OriginalFunction;
rootBaseMethod = (Method)method.OriginalFunction;
else
rootBaseMethod = method.GetRootBaseMethod();
if (rootBaseMethod != null && rootBaseMethod != method)
@ -59,7 +59,7 @@ namespace CppSharp.Passes @@ -59,7 +59,7 @@ namespace CppSharp.Passes
if (decl is Property property && !property.IsStatic)
{
var rootBaseProperty = ((Class) property.Namespace).GetBasePropertyByName(property);
var rootBaseProperty = ((Class)property.Namespace).GetBasePropertyByName(property);
if (rootBaseProperty != null && rootBaseProperty != property)
{
newName = rootBaseProperty.Name;
@ -121,7 +121,7 @@ namespace CppSharp.Passes @@ -121,7 +121,7 @@ namespace CppSharp.Passes
{
if (!Targets.HasFlag(RenameTargets.Field))
return false;
var fieldProperty = ((Class) field.Namespace).Properties.FirstOrDefault(
var fieldProperty = ((Class)field.Namespace).Properties.FirstOrDefault(
p => p.Field == field);
return (fieldProperty != null &&
fieldProperty.IsInRefTypeAndBackedByValueClassField());
@ -217,7 +217,7 @@ namespace CppSharp.Passes @@ -217,7 +217,7 @@ namespace CppSharp.Passes
var enumItem = decl as Enumeration.Item;
if (enumItem != null)
return ((Enumeration) enumItem.Namespace).Items.Any(
return ((Enumeration)enumItem.Namespace).Items.Any(
i => i != decl && i.Name == newName);
return false;
@ -228,7 +228,7 @@ namespace CppSharp.Passes @@ -228,7 +228,7 @@ namespace CppSharp.Passes
var method = function as Method;
if (method != null)
{
return ((Class) method.Namespace).Methods.Where(
return ((Class)method.Namespace).Methods.Where(
m => !m.Ignore && m.Parameters.SequenceEqual(function.Parameters, new ParameterComparer()));
}
return function.Namespace.Functions.Where(
@ -295,17 +295,17 @@ namespace CppSharp.Passes @@ -295,17 +295,17 @@ namespace CppSharp.Passes
[Flags]
public enum RenameTargets
{
Class = 1 << 0,
Field = 1 << 1,
Method = 1 << 2,
Function = 1 << 3,
Class = 1 << 0,
Field = 1 << 1,
Method = 1 << 2,
Function = 1 << 3,
Parameter = 1 << 4,
Enum = 1 << 5,
EnumItem = 1 << 6,
Event = 1 << 7,
Property = 1 << 8,
Delegate = 1 << 9,
Variable = 1 << 10,
Enum = 1 << 5,
EnumItem = 1 << 6,
Event = 1 << 7,
Property = 1 << 8,
Delegate = 1 << 9,
Variable = 1 << 10,
Any = Function | Method | Parameter | Class | Field | Enum | EnumItem | Event | Property | Delegate | Variable
}
@ -466,7 +466,7 @@ namespace CppSharp.Passes @@ -466,7 +466,7 @@ namespace CppSharp.Passes
decl.Visit(pass);
}
public static void RenameDeclsCase(this PassBuilder<TranslationUnitPass> builder,
public static void RenameDeclsCase(this PassBuilder<TranslationUnitPass> builder,
RenameTargets targets, RenameCasePattern pattern)
{
builder.AddPass(new CaseRenamePass(targets, pattern));

4
src/Generator/Passes/SpecializationMethodsWithDependentPointersPass.cs

@ -141,7 +141,7 @@ namespace CppSharp.Passes @@ -141,7 +141,7 @@ namespace CppSharp.Passes
var type = qualType.Type.Desugar();
while (type.IsAddress())
{
var pointee = ((PointerType) type).Pointee.Desugar(
var pointee = ((PointerType)type).Pointee.Desugar(
resolveTemplateSubstitution: false);
if (pointee.IsAddress())
type = pointee;
@ -149,7 +149,7 @@ namespace CppSharp.Passes @@ -149,7 +149,7 @@ namespace CppSharp.Passes
{
substitution = pointee as TemplateParameterSubstitutionType;
if (substitution != null)
((PointerType) type).QualifiedPointee.Type = substitution.Replacement.Type;
((PointerType)type).QualifiedPointee.Type = substitution.Replacement.Type;
break;
}
}

10
src/Generator/Passes/SymbolsCodeGenerator.cs

@ -45,7 +45,7 @@ namespace CppSharp.Passes @@ -45,7 +45,7 @@ namespace CppSharp.Passes
public override bool VisitMethodDecl(Method method)
{
if (method.IsDestructor &&
(!((Class) method.Namespace).HasNonTrivialDestructor ||
(!((Class)method.Namespace).HasNonTrivialDestructor ||
method.Access == AccessSpecifier.Private))
return false;
@ -58,7 +58,7 @@ namespace CppSharp.Passes @@ -58,7 +58,7 @@ namespace CppSharp.Passes
return true;
}
Class @class = (Class) method.Namespace;
Class @class = (Class)method.Namespace;
bool needSubclass = (method.Access == AccessSpecifier.Protected ||
@class.IsAbstract) && (method.IsConstructor || method.IsDestructor);
string wrapper = GetWrapper(method);
@ -159,7 +159,7 @@ namespace CppSharp.Passes @@ -159,7 +159,7 @@ namespace CppSharp.Passes
Write("extern \"C\" ");
Write($"{GetExporting()}void {wrapper}({signature}) ");
bool isAbstract = ((Class) method.Namespace).IsAbstract;
bool isAbstract = ((Class)method.Namespace).IsAbstract;
if (method.Access == AccessSpecifier.Protected || isAbstract)
{
Write($@"{{ ::new ({Helpers.InstanceField}) {
@ -197,7 +197,7 @@ namespace CppSharp.Passes @@ -197,7 +197,7 @@ namespace CppSharp.Passes
}
bool needSubclass = method.Access == AccessSpecifier.Protected ||
((Class) method.Namespace).IsAbstract;
((Class)method.Namespace).IsAbstract;
string @namespace = method.Namespace.Visit(cppTypePrinter);
if (!needSubclass)
Write("extern \"C\" ");
@ -318,7 +318,7 @@ namespace CppSharp.Passes @@ -318,7 +318,7 @@ namespace CppSharp.Passes
string paramTypes, string functionName)
{
Stack<string> parentsOpen = GenerateNamespace(function);
var functionType = (FunctionType) function.FunctionType.Type;
var functionType = (FunctionType)function.FunctionType.Type;
Write($"{string.Concat(parentsOpen)}");
if (function.IsConstExpr)
Write("constexpr ");

2
src/Generator/Passes/ValidateOperatorsPass.cs

@ -74,7 +74,7 @@ namespace CppSharp.Passes @@ -74,7 +74,7 @@ namespace CppSharp.Passes
returnType = (returnType.GetFinalPointee() ?? returnType).Desugar();
return returnType.TryGetClass(out @class) &&
@class.GetNonIgnoredRootBase() ==
((Class) @operator.Namespace).GetNonIgnoredRootBase() &&
((Class)@operator.Namespace).GetNonIgnoredRootBase() &&
@operator.Parameters.Count == 0;
// Bitwise shift operators can only be overloaded if the second parameter is int

2
src/Generator/Types/DeclMapDatabase.cs

@ -44,7 +44,7 @@ namespace CppSharp.Types @@ -44,7 +44,7 @@ namespace CppSharp.Types
if (attr.GeneratorKind == 0 ||
attr.GeneratorKind == bindingContext.Options.GeneratorKind)
{
var declMap = (DeclMap) Activator.CreateInstance(type);
var declMap = (DeclMap)Activator.CreateInstance(type);
declMap.Context = bindingContext;
declMap.DeclMapDatabase = this;

26
src/Generator/Types/Std/Stdlib.CLI.cs

@ -135,8 +135,8 @@ namespace CppSharp.Types.Std @@ -135,8 +135,8 @@ namespace CppSharp.Types.Std
var type = finalType as TemplateSpecializationType;
if (type == null)
{
var injectedClassNameType = (InjectedClassNameType) finalType;
type = (TemplateSpecializationType) injectedClassNameType.InjectedSpecializationType.Type;
var injectedClassNameType = (InjectedClassNameType)finalType;
type = (TemplateSpecializationType)injectedClassNameType.InjectedSpecializationType.Type;
}
var checker = new TypeIgnoreChecker(TypeMapDatabase);
type.Arguments[0].Type.Visit(checker);
@ -182,10 +182,10 @@ namespace CppSharp.Types.Std @@ -182,10 +182,10 @@ namespace CppSharp.Types.Std
};
var elementCtx = new MarshalContext(ctx.Context, ctx.Indentation)
{
Parameter = param,
ArgName = param.Name,
};
{
Parameter = param,
ArgName = param.Name,
};
var marshal = new CLIMarshalManagedToNativePrinter(elementCtx);
type.Type.Visit(marshal);
@ -203,7 +203,7 @@ namespace CppSharp.Types.Std @@ -203,7 +203,7 @@ namespace CppSharp.Types.Std
ctx.Before.WriteLine("{0}.push_back(_marshalElement);",
tmpVarName);
}
ctx.Before.UnindentAndWriteCloseBrace();
ctx.Return.Write(tmpVarName);
@ -219,7 +219,7 @@ namespace CppSharp.Types.Std @@ -219,7 +219,7 @@ namespace CppSharp.Types.Std
? new CILType(typeof(System.IntPtr))
: type.Type;
var tmpVarName = "_tmp" + ctx.ArgName;
ctx.Before.WriteLine(
"auto {0} = gcnew ::System::Collections::Generic::List<{1}>();",
tmpVarName, managedType);
@ -231,10 +231,10 @@ namespace CppSharp.Types.Std @@ -231,10 +231,10 @@ namespace CppSharp.Types.Std
ctx.Before.WriteOpenBraceAndIndent();
{
var elementCtx = new MarshalContext(ctx.Context, ctx.Indentation)
{
ReturnVarName = "_element",
ReturnType = type
};
{
ReturnVarName = "_element",
ReturnType = type
};
var marshal = new CLIMarshalNativeToManagedPrinter(elementCtx);
type.Type.Visit(marshal);
@ -315,7 +315,7 @@ namespace CppSharp.Types.Std @@ -315,7 +315,7 @@ namespace CppSharp.Types.Std
public override void CLIMarshalToNative(MarshalContext ctx)
{
var marshal = (CLIMarshalManagedToNativePrinter) ctx.MarshalToNative;
var marshal = (CLIMarshalManagedToNativePrinter)ctx.MarshalToNative;
if (!ctx.Parameter.Type.Desugar().IsPointer())
marshal.ArgumentPrefix.Write("*");
var marshalCtxName = string.Format("ctx_{0}", ctx.Parameter.Name);

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

@ -145,8 +145,8 @@ namespace CppSharp.Types.Std @@ -145,8 +145,8 @@ namespace CppSharp.Types.Std
// would be really helpful to have ctx hold a Decl property representing the
// "appropriate" Decl when we get here. When MarshalKind == NativeField, Decl would
// be set to the Field we're operating on.
var fieldName = ctx.ReturnVarName.Substring(ctx.ReturnVarName.LastIndexOf("->") + 2);
var fieldName = ctx.ReturnVarName.Substring(ctx.ReturnVarName.LastIndexOf("->") + 2);
ctx.Before.WriteLine($"if (__{fieldName}_OwnsNativeMemory)");
ctx.Before.WriteLineIndent($"Marshal.FreeHGlobal({ctx.ReturnVarName});");
ctx.Before.WriteLine($"__{fieldName}_OwnsNativeMemory = true;");
@ -355,7 +355,7 @@ namespace CppSharp.Types.Std @@ -355,7 +355,7 @@ namespace CppSharp.Types.Std
var typePrinter = new CSharpTypePrinter(ctx.Context);
string qualifiedBasicString = GetQualifiedBasicString(basicString);
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.Before.WriteLine($@"var {varBasicString} = {
basicString.Visit(typePrinter)}.{Helpers.CreateInstanceIdentifier}({
@ -397,7 +397,7 @@ namespace CppSharp.Types.Std @@ -397,7 +397,7 @@ namespace CppSharp.Types.Std
var templateSpecializationType = template as TemplateSpecializationType;
if (templateSpecializationType != null)
return templateSpecializationType.GetClassTemplateSpecialization();
return (ClassTemplateSpecialization) ((TagType) template).Declaration;
return (ClassTemplateSpecialization)((TagType)template).Declaration;
}
}

68
src/Generator/Types/TypeMap.cs

@ -16,7 +16,7 @@ namespace CppSharp.Types @@ -16,7 +16,7 @@ namespace CppSharp.Types
{
public string Type { get; }
public GeneratorKind GeneratorKind { get; set; }
public TypeMapAttribute(string type) : this(type, 0)
{
Type = type;
@ -55,15 +55,15 @@ namespace CppSharp.Types @@ -55,15 +55,15 @@ namespace CppSharp.Types
{
switch (kind)
{
case GeneratorKind.C:
case GeneratorKind.CPlusPlus:
return CppSignatureType(ctx);
case GeneratorKind.CLI:
return CLISignatureType(ctx);
case GeneratorKind.CSharp:
return CSharpSignatureType(ctx);
default:
throw new System.NotImplementedException();
case GeneratorKind.C:
case GeneratorKind.CPlusPlus:
return CppSignatureType(ctx);
case GeneratorKind.CLI:
return CLISignatureType(ctx);
case GeneratorKind.CSharp:
return CSharpSignatureType(ctx);
default:
throw new System.NotImplementedException();
}
}
@ -71,18 +71,18 @@ namespace CppSharp.Types @@ -71,18 +71,18 @@ namespace CppSharp.Types
{
switch (kind)
{
case GeneratorKind.C:
case GeneratorKind.CPlusPlus:
CppMarshalToNative(ctx);
return;
case GeneratorKind.CLI:
CLIMarshalToNative(ctx);
return;
case GeneratorKind.CSharp:
CSharpMarshalToNative(ctx as CSharpMarshalContext);
return;
default:
throw new System.NotImplementedException();
case GeneratorKind.C:
case GeneratorKind.CPlusPlus:
CppMarshalToNative(ctx);
return;
case GeneratorKind.CLI:
CLIMarshalToNative(ctx);
return;
case GeneratorKind.CSharp:
CSharpMarshalToNative(ctx as CSharpMarshalContext);
return;
default:
throw new System.NotImplementedException();
}
}
@ -90,18 +90,18 @@ namespace CppSharp.Types @@ -90,18 +90,18 @@ namespace CppSharp.Types
{
switch (kind)
{
case GeneratorKind.C:
case GeneratorKind.CPlusPlus:
CppMarshalToManaged(ctx);
return;
case GeneratorKind.CLI:
CLIMarshalToManaged(ctx);
return;
case GeneratorKind.CSharp:
CSharpMarshalToManaged(ctx as CSharpMarshalContext);
return;
default:
throw new System.NotImplementedException();
case GeneratorKind.C:
case GeneratorKind.CPlusPlus:
CppMarshalToManaged(ctx);
return;
case GeneratorKind.CLI:
CLIMarshalToManaged(ctx);
return;
case GeneratorKind.CSharp:
CSharpMarshalToManaged(ctx as CSharpMarshalContext);
return;
default:
throw new System.NotImplementedException();
}
}

2
src/Generator/Types/TypeMapDatabase.cs

@ -43,7 +43,7 @@ namespace CppSharp.Types @@ -43,7 +43,7 @@ namespace CppSharp.Types
if (attr.GeneratorKind == 0 ||
attr.GeneratorKind == bindingContext.Options.GeneratorKind)
{
var typeMap = (TypeMap) Activator.CreateInstance(type);
var typeMap = (TypeMap)Activator.CreateInstance(type);
typeMap.Context = bindingContext;
typeMap.TypeMapDatabase = this;

8
src/Generator/Utils/BlockGenerator.cs

@ -319,15 +319,15 @@ namespace CppSharp @@ -319,15 +319,15 @@ namespace CppSharp
if (trimIndentation)
{
foreach(var line in lines)
{
foreach (var line in lines)
{
for (int i = 0; i < line.Length; ++i)
{
if (char.IsWhiteSpace(line[i]))
continue;
if (i < indentation)
{
{
indentation = i;
break;
}

14
src/Generator/Utils/ExpressionEvaluator.cs

@ -54,8 +54,8 @@ namespace CodingSeb.ExpressionEvaluator @@ -54,8 +54,8 @@ namespace CodingSeb.ExpressionEvaluator
protected static readonly Regex initInNewBeginningRegex = new Regex(@"^(?>\s*){", RegexOptions.Compiled);
// Depending on OptionInlineNamespacesEvaluationActive. Initialized in constructor
protected string InstanceCreationWithNewKeywordRegexPattern { get { return @"^new(?>\s*)((?<isAnonymous>[{{])|((?<name>[\p{L}_][\p{L}_0-9"+ (OptionInlineNamespacesEvaluationActive ? @"\." : string.Empty) + @"]*)(?>\s*)(?<isgeneric>[<](?>[^<>]+|(?<gentag>[<])|(?<-gentag>[>]))*(?(gentag)(?!))[>])?(?>\s*)((?<isfunction>[(])|(?<isArray>\[)|(?<isInit>[{{]))?))"; } }
protected string CastRegexPattern { get { return @"^\((?>\s*)(?<typeName>[\p{L}_][\p{L}_0-9"+ (OptionInlineNamespacesEvaluationActive ? @"\." : string.Empty) + @"\[\]<>]*[?]?)(?>\s*)\)"; } }
protected string InstanceCreationWithNewKeywordRegexPattern { get { return @"^new(?>\s*)((?<isAnonymous>[{{])|((?<name>[\p{L}_][\p{L}_0-9" + (OptionInlineNamespacesEvaluationActive ? @"\." : string.Empty) + @"]*)(?>\s*)(?<isgeneric>[<](?>[^<>]+|(?<gentag>[<])|(?<-gentag>[>]))*(?(gentag)(?!))[>])?(?>\s*)((?<isfunction>[(])|(?<isArray>\[)|(?<isInit>[{{]))?))"; } }
protected string CastRegexPattern { get { return @"^\((?>\s*)(?<typeName>[\p{L}_][\p{L}_0-9" + (OptionInlineNamespacesEvaluationActive ? @"\." : string.Empty) + @"\[\]<>]*[?]?)(?>\s*)\)"; } }
// To remove comments in scripts based on https://stackoverflow.com/questions/3524317/regex-to-strip-line-comments-from-c-sharp/3524689#3524689
protected const string blockComments = @"/\*(.*?)\*/";
@ -1578,7 +1578,7 @@ namespace CodingSeb.ExpressionEvaluator @@ -1578,7 +1578,7 @@ namespace CodingSeb.ExpressionEvaluator
{
string restOfExpression = expression.Substring(i);
// CPPSHARP
// CPPSHARP
if (restOfExpression.StartsWith("0x", StringComparison.CurrentCultureIgnoreCase))
{
// This is in case the literal contains suffix
@ -1586,7 +1586,7 @@ namespace CodingSeb.ExpressionEvaluator @@ -1586,7 +1586,7 @@ namespace CodingSeb.ExpressionEvaluator
i += restOfExpression.Length - cleanedUp.Length;
restOfExpression = cleanedUp;
}
//
//
Match numberMatch = Regex.Match(restOfExpression, numberRegexPattern, RegexOptions.IgnoreCase);
Match otherBaseMatch = otherBasesNumberRegex.Match(restOfExpression);
@ -1639,7 +1639,7 @@ namespace CodingSeb.ExpressionEvaluator @@ -1639,7 +1639,7 @@ namespace CodingSeb.ExpressionEvaluator
}
else
{
string numberNoSign = numberMatch.Groups[1].Value.Replace("_", "");
string numberNoSign = numberMatch.Groups[1].Value.Replace("_", "");
int sign = numberMatch.Groups["sign"].Success ? -1 : 1;
stack.Push(ParseInteger(numberNoSign, 10, sign));
}
@ -1652,7 +1652,7 @@ namespace CodingSeb.ExpressionEvaluator @@ -1652,7 +1652,7 @@ namespace CodingSeb.ExpressionEvaluator
}
}
// CPPSHARP
// CPPSHARP
/// <summary>
/// Heuristically convert <paramref name="numberToParse"/> to an int, uint, long, or ulong
@ -1688,7 +1688,7 @@ namespace CodingSeb.ExpressionEvaluator @@ -1688,7 +1688,7 @@ namespace CodingSeb.ExpressionEvaluator
if (number <= long.MaxValue) return (long)number;
return number;
}
//
//
protected virtual bool EvaluateInstanceCreationWithNewKeyword(string expression, Stack<object> stack, ref int i)
{

35
src/Generator/Utils/FSM/ConsoleWriter.cs

@ -1,20 +1,25 @@ @@ -1,20 +1,25 @@
using System;
namespace CppSharp.Utils.FSM{
public class ConsoleWriter{
public static void Failure(string message){
Console.ForegroundColor = ConsoleColor.DarkRed;
Write(message);
}
namespace CppSharp.Utils.FSM
{
public class ConsoleWriter
{
public static void Failure(string message)
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Write(message);
}
public static void Success(string message){
Console.ForegroundColor = ConsoleColor.DarkGreen;
Write(message);
}
public static void Success(string message)
{
Console.ForegroundColor = ConsoleColor.DarkGreen;
Write(message);
}
private static void Write(string message){
Console.WriteLine(message);
Console.ResetColor();
}
}
private static void Write(string message)
{
Console.WriteLine(message);
Console.ResetColor();
}
}
}

262
src/Generator/Utils/FSM/DFSM.cs

@ -4,136 +4,166 @@ using System.Text; @@ -4,136 +4,166 @@ using System.Text;
namespace CppSharp.Utils.FSM
{
public class DFSM{
public readonly List<string> Q = new List<string>();
public readonly List<char> Sigma = new List<char>();
public readonly List<Transition> Delta = new List<Transition>();
public List<string> Q0 = new List<string>();
public List<string> F = new List<string>();
public class DFSM
{
public readonly List<string> Q = new List<string>();
public readonly List<char> Sigma = new List<char>();
public readonly List<Transition> Delta = new List<Transition>();
public List<string> Q0 = new List<string>();
public List<string> F = new List<string>();
public DFSM(IEnumerable<string> q, IEnumerable<char> sigma, IEnumerable<Transition> delta,
IEnumerable<string> q0, IEnumerable<string> f){
Q = q.ToList();
Sigma = sigma.ToList();
AddTransitions(delta);
AddInitialStates(q0);
AddFinalStates(f);
}
public DFSM(IEnumerable<string> q, IEnumerable<char> sigma, IEnumerable<Transition> delta,
IEnumerable<string> q0, IEnumerable<string> f)
{
Q = q.ToList();
Sigma = sigma.ToList();
AddTransitions(delta);
AddInitialStates(q0);
AddFinalStates(f);
}
private void AddTransitions(IEnumerable<Transition> transitions){
foreach (var transition in transitions.Where(ValidTransition)){
Delta.Add(transition);
}
}
private void AddTransitions(IEnumerable<Transition> transitions)
{
foreach (var transition in transitions.Where(ValidTransition))
{
Delta.Add(transition);
}
}
private bool ValidTransition(Transition transition){
return Q.Contains(transition.StartState) &&
Q.Contains(transition.EndState) &&
Sigma.Contains(transition.Symbol) &&
!TransitionAlreadyDefined(transition);
}
private bool ValidTransition(Transition transition)
{
return Q.Contains(transition.StartState) &&
Q.Contains(transition.EndState) &&
Sigma.Contains(transition.Symbol) &&
!TransitionAlreadyDefined(transition);
}
private bool TransitionAlreadyDefined(Transition transition){
return Delta.Any(t => t.StartState == transition.StartState &&
t.Symbol == transition.Symbol);
}
private bool TransitionAlreadyDefined(Transition transition)
{
return Delta.Any(t => t.StartState == transition.StartState &&
t.Symbol == transition.Symbol);
}
private void AddInitialStates(IEnumerable<string> q0){
foreach (var startingState in q0.Where(q => q != null && Q.Contains(q))){
Q0.Add(startingState);
}
}
private void AddInitialStates(IEnumerable<string> q0)
{
foreach (var startingState in q0.Where(q => q != null && Q.Contains(q)))
{
Q0.Add(startingState);
}
}
private void AddFinalStates(IEnumerable<string> finalStates){
foreach (var finalState in finalStates.Where(finalState => Q.Contains(finalState))){
F.Add(finalState);
}
}
private void AddFinalStates(IEnumerable<string> finalStates)
{
foreach (var finalState in finalStates.Where(finalState => Q.Contains(finalState)))
{
F.Add(finalState);
}
}
public void Accepts(string input){
ConsoleWriter.Success("Trying to parse: " + input);
if (InvalidInputOrFSM(input)){
return;
}
foreach (var q0 in Q0){
var currentState = q0;
var steps = new StringBuilder();
foreach (var symbol in input.ToCharArray()){
var transition = Delta.Find(t => t.StartState == currentState &&
t.Symbol == symbol);
if (transition == null){
ConsoleWriter.Failure("No transitions for current state and symbol");
ConsoleWriter.Failure(steps.ToString());
continue;
}
currentState = transition.EndState;
steps.Append(transition + "\n");
public void Accepts(string input)
{
ConsoleWriter.Success("Trying to parse: " + input);
if (InvalidInputOrFSM(input))
{
return;
}
if (F.Contains(currentState)){
ConsoleWriter.Success("Accepted the input with steps:\n" + steps);
return;
foreach (var q0 in Q0)
{
var currentState = q0;
var steps = new StringBuilder();
foreach (var symbol in input.ToCharArray())
{
var transition = Delta.Find(t => t.StartState == currentState &&
t.Symbol == symbol);
if (transition == null)
{
ConsoleWriter.Failure("No transitions for current state and symbol");
ConsoleWriter.Failure(steps.ToString());
continue;
}
currentState = transition.EndState;
steps.Append(transition + "\n");
}
if (F.Contains(currentState))
{
ConsoleWriter.Success("Accepted the input with steps:\n" + steps);
return;
}
ConsoleWriter.Failure("Stopped in state " + currentState +
" which is not a final state.");
ConsoleWriter.Failure(steps.ToString());
}
ConsoleWriter.Failure("Stopped in state " + currentState +
" which is not a final state.");
ConsoleWriter.Failure(steps.ToString());
}
}
}
private bool InvalidInputOrFSM(string input){
if (InputContainsNotDefinedSymbols(input)){
return true;
}
if (InitialStateNotSet()){
ConsoleWriter.Failure("No initial state has been set");
return true;
}
if (NoFinalStates()){
ConsoleWriter.Failure("No final states have been set");
return true;
}
return false;
}
private bool InvalidInputOrFSM(string input)
{
if (InputContainsNotDefinedSymbols(input))
{
return true;
}
if (InitialStateNotSet())
{
ConsoleWriter.Failure("No initial state has been set");
return true;
}
if (NoFinalStates())
{
ConsoleWriter.Failure("No final states have been set");
return true;
}
return false;
}
private bool InputContainsNotDefinedSymbols(string input){
foreach (var symbol in input.ToCharArray().Where(symbol => !Sigma.Contains(symbol))){
ConsoleWriter.Failure("Could not accept the input since the symbol " + symbol + " is not part of the alphabet");
return true;
}
return false;
}
private bool InputContainsNotDefinedSymbols(string input)
{
foreach (var symbol in input.ToCharArray().Where(symbol => !Sigma.Contains(symbol)))
{
ConsoleWriter.Failure("Could not accept the input since the symbol " + symbol + " is not part of the alphabet");
return true;
}
return false;
}
private bool InitialStateNotSet(){
return Q0.Count == 0;
}
private bool InitialStateNotSet()
{
return Q0.Count == 0;
}
private bool NoFinalStates(){
return F.Count == 0;
}
private bool NoFinalStates()
{
return F.Count == 0;
}
public void RemoveUnreachableStates(){
var reachableStates = new HashSet<string>(Q0);
var newStates = new HashSet<string>(Q0);
do{
var temp = new HashSet<string>();
foreach (var q in newStates){
var reachableFromQ = Delta.FindAll(t => t.StartState == q).Select(t => t.EndState);
temp.UnionWith(reachableFromQ);
public void RemoveUnreachableStates()
{
var reachableStates = new HashSet<string>(Q0);
var newStates = new HashSet<string>(Q0);
do
{
var temp = new HashSet<string>();
foreach (var q in newStates)
{
var reachableFromQ = Delta.FindAll(t => t.StartState == q).Select(t => t.EndState);
temp.UnionWith(reachableFromQ);
}
temp.ExceptWith(reachableStates);
newStates = temp;
reachableStates.UnionWith(newStates);
} while (newStates.Count > 0);
var unreachableStates = Q.Where(q => !reachableStates.Contains(q));
for (int i = Delta.Count - 1; i > 0; i--)
{
var transition = Delta[i];
if (unreachableStates.Contains(transition.EndState) ||
unreachableStates.Contains(transition.StartState))
{
Delta.Remove(transition);
}
}
temp.ExceptWith(reachableStates);
newStates = temp;
reachableStates.UnionWith(newStates);
} while (newStates.Count > 0);
var unreachableStates = Q.Where(q => !reachableStates.Contains(q));
for (int i = Delta.Count - 1; i > 0; i--){
var transition = Delta[i];
if (unreachableStates.Contains(transition.EndState) ||
unreachableStates.Contains(transition.StartState)){
Delta.Remove(transition);
foreach (var unrechableState in unreachableStates)
{
Q.Remove(unrechableState);
}
}
foreach (var unrechableState in unreachableStates){
Q.Remove(unrechableState);
}
}
}
}
}
}

128
src/Generator/Utils/FSM/Minimize.cs

@ -1,71 +1,83 @@ @@ -1,71 +1,83 @@
using System.Collections.Generic;
using System.Linq;
namespace CppSharp.Utils.FSM{
internal class Minimize{
public static DFSM MinimizeDFSM(DFSM fsm){
var reversedNDFSM = Reverse(fsm);
var reversedDFSM = PowersetConstruction(reversedNDFSM);
var NDFSM = Reverse(reversedDFSM);
return PowersetConstruction(NDFSM);
}
namespace CppSharp.Utils.FSM
{
internal class Minimize
{
public static DFSM MinimizeDFSM(DFSM fsm)
{
var reversedNDFSM = Reverse(fsm);
var reversedDFSM = PowersetConstruction(reversedNDFSM);
var NDFSM = Reverse(reversedDFSM);
return PowersetConstruction(NDFSM);
}
private static NDFSM Reverse(DFSM d){
var delta = new List<Transition>();
foreach (var transition in d.Delta){
delta.Add(new Transition(transition.EndState, transition.Symbol, transition.StartState));
}
return new NDFSM(d.Q, d.Sigma, delta, d.F, d.Q0);
}
private static NDFSM Reverse(DFSM d)
{
var delta = new List<Transition>();
foreach (var transition in d.Delta)
{
delta.Add(new Transition(transition.EndState, transition.Symbol, transition.StartState));
}
return new NDFSM(d.Q, d.Sigma, delta, d.F, d.Q0);
}
public static DFSM PowersetConstruction(NDFSM ndfsm){
var Q = new List<string>();
var Sigma = ndfsm.Sigma.ToList();
var Delta = new List<Transition>();
var Q0 = new List<string> { string.Join(" ", ndfsm.Q0) };
var F = new List<string>();
public static DFSM PowersetConstruction(NDFSM ndfsm)
{
var Q = new List<string>();
var Sigma = ndfsm.Sigma.ToList();
var Delta = new List<Transition>();
var Q0 = new List<string> { string.Join(" ", ndfsm.Q0) };
var F = new List<string>();
var processed = new List<string>();
var queue = new Queue<string>();
queue.Enqueue(string.Join(",", ndfsm.Q0));
var processed = new List<string>();
var queue = new Queue<string>();
queue.Enqueue(string.Join(",", ndfsm.Q0));
while (queue.Count > 0){
var setState = queue.Dequeue();
processed.Add(setState);
Q.Add(CleanupState(setState));
while (queue.Count > 0)
{
var setState = queue.Dequeue();
processed.Add(setState);
Q.Add(CleanupState(setState));
var statesInCurrentSetState = setState.Split(',').ToList();
foreach (var state in statesInCurrentSetState){
if (ndfsm.F.Contains(state)){
F.Add(CleanupState(setState));
break;
}
}
var symbols = ndfsm.Delta
.Where(t => statesInCurrentSetState.Contains(t.StartState))
.Select(t => t.Symbol)
.Distinct();
foreach (var symbol in symbols){
var reachableStates =
ndfsm.Delta
.Where(t => t.Symbol == symbol &&
statesInCurrentSetState.Contains(t.StartState))
.OrderBy(t => t.EndState).
Select(t => t.EndState);
var reachableSetState = string.Join(",", reachableStates);
var statesInCurrentSetState = setState.Split(',').ToList();
foreach (var state in statesInCurrentSetState)
{
if (ndfsm.F.Contains(state))
{
F.Add(CleanupState(setState));
break;
}
}
var symbols = ndfsm.Delta
.Where(t => statesInCurrentSetState.Contains(t.StartState))
.Select(t => t.Symbol)
.Distinct();
foreach (var symbol in symbols)
{
var reachableStates =
ndfsm.Delta
.Where(t => t.Symbol == symbol &&
statesInCurrentSetState.Contains(t.StartState))
.OrderBy(t => t.EndState).
Select(t => t.EndState);
var reachableSetState = string.Join(",", reachableStates);
Delta.Add(new Transition(CleanupState(setState), symbol, CleanupState(reachableSetState)));
Delta.Add(new Transition(CleanupState(setState), symbol, CleanupState(reachableSetState)));
if (!processed.Contains(reachableSetState)){
queue.Enqueue(reachableSetState);
}
if (!processed.Contains(reachableSetState))
{
queue.Enqueue(reachableSetState);
}
}
}
}
return new DFSM(Q, Sigma, Delta, Q0, F);
}
return new DFSM(Q, Sigma, Delta, Q0, F);
}
private static string CleanupState(string state){
return state.Replace(",", " ");
}
}
private static string CleanupState(string state)
{
return state.Replace(",", " ");
}
}
}

146
src/Generator/Utils/FSM/NDFSM.cs

@ -2,78 +2,96 @@ @@ -2,78 +2,96 @@
using System.Linq;
using System.Text;
namespace CppSharp.Utils.FSM{
public class NDFSM{
private readonly List<string> Q = new List<string>();
public readonly List<char> Sigma = new List<char>();
public readonly List<Transition> Delta = new List<Transition>();
public List<string> Q0 = new List<string>();
public readonly List<string> F = new List<string>();
namespace CppSharp.Utils.FSM
{
public class NDFSM
{
private readonly List<string> Q = new List<string>();
public readonly List<char> Sigma = new List<char>();
public readonly List<Transition> Delta = new List<Transition>();
public List<string> Q0 = new List<string>();
public readonly List<string> F = new List<string>();
public NDFSM(IEnumerable<string> q, IEnumerable<char> sigma,
IEnumerable<Transition> delta, IEnumerable<string> q0, IEnumerable<string> f){
Q = q.ToList();
Sigma = sigma.ToList();
AddTransitions(delta);
AddInitialStates(q0);
AddFinalStates(f);
}
public NDFSM(IEnumerable<string> q, IEnumerable<char> sigma,
IEnumerable<Transition> delta, IEnumerable<string> q0, IEnumerable<string> f)
{
Q = q.ToList();
Sigma = sigma.ToList();
AddTransitions(delta);
AddInitialStates(q0);
AddFinalStates(f);
}
private void AddTransitions(IEnumerable<Transition> transitions){
foreach (var transition in transitions.Where(ValidTransition)){
Delta.Add(transition);
}
}
private void AddTransitions(IEnumerable<Transition> transitions)
{
foreach (var transition in transitions.Where(ValidTransition))
{
Delta.Add(transition);
}
}
private bool ValidTransition(Transition transition){
return Q.Contains(transition.StartState) &&
Q.Contains(transition.EndState) &&
Sigma.Contains(transition.Symbol);
}
private bool ValidTransition(Transition transition)
{
return Q.Contains(transition.StartState) &&
Q.Contains(transition.EndState) &&
Sigma.Contains(transition.Symbol);
}
private void AddInitialStates(IEnumerable<string> q0){
foreach (var startingState in q0.Where(q => q != null && Q.Contains(q))){
Q0.Add(startingState);
}
}
private void AddInitialStates(IEnumerable<string> q0)
{
foreach (var startingState in q0.Where(q => q != null && Q.Contains(q)))
{
Q0.Add(startingState);
}
}
private void AddFinalStates(IEnumerable<string> finalStates){
foreach (var finalState in finalStates.Where(finalState => Q.Contains(finalState))){
F.Add(finalState);
}
}
private void AddFinalStates(IEnumerable<string> finalStates)
{
foreach (var finalState in finalStates.Where(finalState => Q.Contains(finalState)))
{
F.Add(finalState);
}
}
public void Accepts(string input){
ConsoleWriter.Success("Trying to accept: " + input);
if (Q0.Any(q0 => Accepts(q0, input, new StringBuilder()))){
return;
}
ConsoleWriter.Failure("Could not accept the input: " + input);
}
public void Accepts(string input)
{
ConsoleWriter.Success("Trying to accept: " + input);
if (Q0.Any(q0 => Accepts(q0, input, new StringBuilder())))
{
return;
}
ConsoleWriter.Failure("Could not accept the input: " + input);
}
private bool Accepts(string currentState, string input, StringBuilder steps){
if (input.Length > 0){
var transitions = GetAllTransitions(currentState, input[0]);
foreach (var transition in transitions){
var currentSteps = new StringBuilder(steps.ToString() + transition);
if (Accepts(transition.EndState, input.Substring(1), currentSteps)){
return true;
}
private bool Accepts(string currentState, string input, StringBuilder steps)
{
if (input.Length > 0)
{
var transitions = GetAllTransitions(currentState, input[0]);
foreach (var transition in transitions)
{
var currentSteps = new StringBuilder(steps.ToString() + transition);
if (Accepts(transition.EndState, input.Substring(1), currentSteps))
{
return true;
}
}
return false;
}
if (F.Contains(currentState))
{
ConsoleWriter.Success("Successfully accepted the input " + input + " " +
"in the final state " + currentState +
" with steps:\n" + steps);
return true;
}
return false;
}
if (F.Contains(currentState)){
ConsoleWriter.Success("Successfully accepted the input " + input + " " +
"in the final state " + currentState +
" with steps:\n" + steps);
return true;
}
return false;
}
}
private IEnumerable<Transition> GetAllTransitions(string currentState, char symbol){
return Delta.FindAll(t => t.StartState == currentState &&
t.Symbol == symbol);
}
}
private IEnumerable<Transition> GetAllTransitions(string currentState, char symbol)
{
return Delta.FindAll(t => t.StartState == currentState &&
t.Symbol == symbol);
}
}
}

27
src/Generator/Utils/FSM/Program.cs

@ -1,21 +1,24 @@ @@ -1,21 +1,24 @@
using System.Collections.Generic;
namespace CppSharp.Utils.FSM{
internal class Program{
private static void Main(string[] args){
var Q = new List<string>{"q0", "q1"};
var Sigma = new List<char>{'0', '1'};
var Delta = new List<Transition>{
namespace CppSharp.Utils.FSM
{
internal class Program
{
private static void Main(string[] args)
{
var Q = new List<string> { "q0", "q1" };
var Sigma = new List<char> { '0', '1' };
var Delta = new List<Transition>{
new Transition("q0", '0', "q0"),
new Transition("q0", '1', "q1"),
new Transition("q1", '1', "q1"),
new Transition("q1", '0', "q0")
};
var Q0 = new List<string>{"q0"};
var F = new List<string>{"q0", "q1"};
var DFSM = new DFSM(Q, Sigma, Delta, Q0, F);
var Q0 = new List<string> { "q0" };
var F = new List<string> { "q0", "q1" };
var DFSM = new DFSM(Q, Sigma, Delta, Q0, F);
var minimizedDFSM = Minimize.MinimizeDFSM(DFSM);
}
}
var minimizedDFSM = Minimize.MinimizeDFSM(DFSM);
}
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save