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
public void SetEnumAsFlags(string name) public void SetEnumAsFlags(string name)
{ {
var enums = FindEnum(name); var enums = FindEnum(name);
foreach(var @enum in enums) foreach (var @enum in enums)
@enum.SetFlags(); @enum.SetFlags();
} }

10
src/AST/ASTVisitor.cs

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

2
src/AST/ClassExtensions.cs

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

2
src/AST/ClassLayout.cs

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

76
src/AST/Comment.cs

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

8
src/AST/Declaration.cs

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

4
src/AST/DeclarationsList.cs

@ -82,7 +82,7 @@ namespace CppSharp.AST
var offset = offsets[kind]; var offset = offsets[kind];
for (var i = GetStart(kind); i < offset; i++) 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
Variable _ => Kind.Variable, Variable _ => Kind.Variable,
Friend _ => Kind.Friend, Friend _ => Kind.Friend,
Event _ => Kind.Event, 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
Access = access; Access = access;
} }
public Field(Field field): base(field) public Field(Field field) : base(field)
{ {
QualifiedType = field.QualifiedType; QualifiedType = field.QualifiedType;
Class = field.Class; Class = field.Class;

48
src/AST/FunctionExtensions.cs

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

2
src/AST/Method.cs

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

16
src/AST/Namespace.cs

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

6
src/AST/Property.cs

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

2
src/AST/PropertyExtensions.cs

@ -6,7 +6,7 @@ namespace CppSharp.AST
{ {
public static bool IsInRefTypeAndBackedByValueClassField(this Property p) 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; return false;
Type type; Type type;

16
src/AST/Template.cs

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

78
src/AST/Type.cs

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

26
src/AST/TypeExtensions.cs

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

60
src/CLI/CLI.cs

@ -10,36 +10,36 @@ namespace CppSharp
{ {
private static OptionSet optionSet = new OptionSet(); private static OptionSet optionSet = new OptionSet();
private static Options options = new Options(); private static Options options = new Options();
static bool ParseCommandLineArgs(string[] args, List<string> errorMessages, ref bool helpShown) static bool ParseCommandLineArgs(string[] args, List<string> errorMessages, ref bool helpShown)
{ {
var showHelp = false; var showHelp = false;
optionSet.Add("I=", "the {PATH} of a folder to search for include files", (i) => { AddIncludeDirs(i, errorMessages); }); 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=", "{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("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("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("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("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("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("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("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("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("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("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("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("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("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("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("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("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("ub|unitybuild|unity", "enable unity build", ub => { options.UnityBuild = (ub != null); });
optionSet.Add("v|verbose", "enables verbose mode", v => { options.Verbose = true; }); optionSet.Add("v|verbose", "enables verbose mode", v => { options.Verbose = true; });
optionSet.Add("h|help", "shows the help", hl => { showHelp = (hl != null); }); optionSet.Add("h|help", "shows the help", hl => { showHelp = (hl != null); });
@ -55,7 +55,7 @@ namespace CppSharp
Console.WriteLine(e.Message); Console.WriteLine(e.Message);
return false; return false;
} }
if (showHelp || additionalArguments != null && additionalArguments.Count == 0) if (showHelp || additionalArguments != null && additionalArguments.Count == 0)
{ {
helpShown = true; helpShown = true;
@ -63,7 +63,7 @@ namespace CppSharp
return false; return false;
} }
foreach(string s in additionalArguments) foreach (string s in additionalArguments)
HandleAdditionalArgument(s, errorMessages); HandleAdditionalArgument(s, errorMessages);
return true; return true;
@ -117,7 +117,7 @@ namespace CppSharp
var dir = Path.HasExtension(arg) ? Path.GetDirectoryName(arg) : Path.GetFullPath(arg); var dir = Path.HasExtension(arg) ? Path.GetDirectoryName(arg) : Path.GetFullPath(arg);
options.OutputDir = dir; options.OutputDir = dir;
} }
catch(Exception e) catch (Exception e)
{ {
errorMessages.Add(e.Message); errorMessages.Add(e.Message);
@ -159,7 +159,7 @@ namespace CppSharp
errorMessages.Add($"File '{args}' could not be found."); errorMessages.Add($"File '{args}' could not be found.");
} }
} }
catch(Exception) catch (Exception)
{ {
errorMessages.Add($"Error while looking for files inside path '{args}'. Ignoring."); errorMessages.Add($"Error while looking for files inside path '{args}'. Ignoring.");
} }
@ -278,23 +278,23 @@ namespace CppSharp
List<string> errorMessages = new List<string>(); List<string> errorMessages = new List<string>();
bool helpShown = false; bool helpShown = false;
if (!ParseCommandLineArgs(args, errorMessages, ref helpShown)) if (!ParseCommandLineArgs(args, errorMessages, ref helpShown))
{ {
PrintErrorMessages(errorMessages); PrintErrorMessages(errorMessages);
// Don't need to show the help since if ParseCommandLineArgs returns false the help has already been shown // Don't need to show the help since if ParseCommandLineArgs returns false the help has already been shown
return; return;
} }
Generator gen = new Generator(options); Generator gen = new Generator(options);
bool validOptions = gen.ValidateOptions(errorMessages); bool validOptions = gen.ValidateOptions(errorMessages);
PrintErrorMessages(errorMessages); PrintErrorMessages(errorMessages);
if (errorMessages.Any() || !validOptions) if (errorMessages.Any() || !validOptions)
Environment.Exit(1); Environment.Exit(1);
gen.Run(); gen.Run();
} }
} }
} }

8
src/CLI/Generator.cs

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

2
src/CLI/Options.cs

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

2
src/Core/Compilation.cs

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

4
src/Core/Diagnostics.cs

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

6
src/Core/Platform.cs

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

4
src/Core/Toolchains/MSVCToolchain.cs

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

8
src/Core/Toolchains/ManagedToolchain.cs

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

19
src/Core/Toolchains/XcodeToolchain.cs

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

2
src/CppParser/Bootstrap/Bootstrap.cs

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

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

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

2
src/Generator.Tests/ASTTestFixture.cs

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

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

@ -273,7 +273,7 @@ namespace CppSharp.Generator.Tests.Passes
static IEnumerable GetExpressionEvaluatorTestCases() static IEnumerable GetExpressionEvaluatorTestCases()
{ {
var testNumber = 100; var testNumber = 100;
foreach (var tc in TestExpressionEvaluatorTestCases) foreach (var tc in TestExpressionEvaluatorTestCases)
{ {
// "testNumber" is just used to cause the test runner to show the tests in the order // "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
{ {
var symbols = GetSymbols("linux", "libexpat"); var symbols = GetSymbols("linux", "libexpat");
Assert.That(symbols, Is.EquivalentTo( Assert.That(symbols, Is.EquivalentTo(
new [] new[]
{ {
".init", ".init",
"free", "free",

12
src/Generator/AST/ASTRecord.cs

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

4
src/Generator/AST/Utils.cs

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

12
src/Generator/AST/VTables.cs

@ -12,10 +12,10 @@ namespace CppSharp.AST
{ {
switch (@class.Layout.ABI) switch (@class.Layout.ABI)
{ {
case CppAbi.Microsoft: case CppAbi.Microsoft:
return GatherVTableMethodsMS(@class); return GatherVTableMethodsMS(@class);
case CppAbi.Itanium: case CppAbi.Itanium:
return GatherVTableMethodsItanium(@class); return GatherVTableMethodsItanium(@class);
} }
throw new NotSupportedException( throw new NotSupportedException(
@ -57,7 +57,7 @@ namespace CppSharp.AST
public static int GetVTableIndex(Function function) public static int GetVTableIndex(Function function)
{ {
var @class = (Class) function.Namespace; var @class = (Class)function.Namespace;
switch (@class.Layout.ABI) switch (@class.Layout.ABI)
{ {
case CppAbi.Microsoft: case CppAbi.Microsoft:
@ -77,7 +77,7 @@ namespace CppSharp.AST
return entry.Method != null && return entry.Method != null &&
(entry.Method.IsOperator || (entry.Method.IsOperator ||
(!entry.Method.IsDeclared && (!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
public static bool IsNativeMethod(this Function function) public static bool IsNativeMethod(this Function function)
{ {
var method = function as Method; var method = function as Method;
if (method == null) if (method == null)
return false; return false;
return method.Conversion == MethodConversionKind.None; return method.Conversion == MethodConversionKind.None;

4
src/Generator/Generator.cs

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

8
src/Generator/Generators/CodeGenerator.cs

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

8
src/Generator/Generators/ITypePrinter.cs

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

10
src/Generator/Library.cs

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

20
src/Generator/Passes/CheckAbiParameters.cs

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

4
src/Generator/Passes/CheckAmbiguousFunctions.cs

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

8
src/Generator/Passes/CheckIgnoredDecls.cs

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

2
src/Generator/Passes/CheckMacrosPass.cs

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

34
src/Generator/Passes/CheckOperatorsOverloads.cs

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

4
src/Generator/Passes/CheckStaticClass.cs

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

4
src/Generator/Passes/CleanCommentsPass.cs

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

12
src/Generator/Passes/ConstructorToConversionOperatorPass.cs

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

36
src/Generator/Passes/DelegatesPass.cs

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

2
src/Generator/Passes/ExpressionHelper.cs

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

16
src/Generator/Passes/FlattenAnonymousTypesToFields.cs

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

30
src/Generator/Passes/FunctionToInstanceMethodPass.cs

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

26
src/Generator/Passes/GenerateAbstractImplementationsPass.cs

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

4
src/Generator/Passes/GenerateSymbolsPass.cs

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

10
src/Generator/Passes/GetterSetterToPropertyPass.cs

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

2
src/Generator/Passes/HandleDefaultParamValuesPass.cs

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

2
src/Generator/Passes/MakeProtectedNestedTypesPublicPass.cs

@ -14,7 +14,7 @@ namespace CppSharp.Passes
if (!base.VisitClassDecl(@class)) if (!base.VisitClassDecl(@class))
return false; 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 where d.Access == AccessSpecifier.Protected
select d).All(d => { d.Access = AccessSpecifier.Public; return true; }); select d).All(d => { d.Access = AccessSpecifier.Public; return true; });

4
src/Generator/Passes/MultipleInheritancePass.cs

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

2
src/Generator/Passes/ParamTypeToInterfacePass.cs

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

38
src/Generator/Passes/Pass.cs

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

32
src/Generator/Passes/RenamePass.cs

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

4
src/Generator/Passes/SpecializationMethodsWithDependentPointersPass.cs

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

10
src/Generator/Passes/SymbolsCodeGenerator.cs

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

2
src/Generator/Passes/ValidateOperatorsPass.cs

@ -74,7 +74,7 @@ namespace CppSharp.Passes
returnType = (returnType.GetFinalPointee() ?? returnType).Desugar(); returnType = (returnType.GetFinalPointee() ?? returnType).Desugar();
return returnType.TryGetClass(out @class) && return returnType.TryGetClass(out @class) &&
@class.GetNonIgnoredRootBase() == @class.GetNonIgnoredRootBase() ==
((Class) @operator.Namespace).GetNonIgnoredRootBase() && ((Class)@operator.Namespace).GetNonIgnoredRootBase() &&
@operator.Parameters.Count == 0; @operator.Parameters.Count == 0;
// Bitwise shift operators can only be overloaded if the second parameter is int // 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
if (attr.GeneratorKind == 0 || if (attr.GeneratorKind == 0 ||
attr.GeneratorKind == bindingContext.Options.GeneratorKind) attr.GeneratorKind == bindingContext.Options.GeneratorKind)
{ {
var declMap = (DeclMap) Activator.CreateInstance(type); var declMap = (DeclMap)Activator.CreateInstance(type);
declMap.Context = bindingContext; declMap.Context = bindingContext;
declMap.DeclMapDatabase = this; declMap.DeclMapDatabase = this;

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

@ -135,8 +135,8 @@ namespace CppSharp.Types.Std
var type = finalType as TemplateSpecializationType; var type = finalType as TemplateSpecializationType;
if (type == null) if (type == null)
{ {
var injectedClassNameType = (InjectedClassNameType) finalType; var injectedClassNameType = (InjectedClassNameType)finalType;
type = (TemplateSpecializationType) injectedClassNameType.InjectedSpecializationType.Type; type = (TemplateSpecializationType)injectedClassNameType.InjectedSpecializationType.Type;
} }
var checker = new TypeIgnoreChecker(TypeMapDatabase); var checker = new TypeIgnoreChecker(TypeMapDatabase);
type.Arguments[0].Type.Visit(checker); type.Arguments[0].Type.Visit(checker);
@ -182,10 +182,10 @@ namespace CppSharp.Types.Std
}; };
var elementCtx = new MarshalContext(ctx.Context, ctx.Indentation) var elementCtx = new MarshalContext(ctx.Context, ctx.Indentation)
{ {
Parameter = param, Parameter = param,
ArgName = param.Name, ArgName = param.Name,
}; };
var marshal = new CLIMarshalManagedToNativePrinter(elementCtx); var marshal = new CLIMarshalManagedToNativePrinter(elementCtx);
type.Type.Visit(marshal); type.Type.Visit(marshal);
@ -203,7 +203,7 @@ namespace CppSharp.Types.Std
ctx.Before.WriteLine("{0}.push_back(_marshalElement);", ctx.Before.WriteLine("{0}.push_back(_marshalElement);",
tmpVarName); tmpVarName);
} }
ctx.Before.UnindentAndWriteCloseBrace(); ctx.Before.UnindentAndWriteCloseBrace();
ctx.Return.Write(tmpVarName); ctx.Return.Write(tmpVarName);
@ -219,7 +219,7 @@ namespace CppSharp.Types.Std
? new CILType(typeof(System.IntPtr)) ? new CILType(typeof(System.IntPtr))
: type.Type; : type.Type;
var tmpVarName = "_tmp" + ctx.ArgName; var tmpVarName = "_tmp" + ctx.ArgName;
ctx.Before.WriteLine( ctx.Before.WriteLine(
"auto {0} = gcnew ::System::Collections::Generic::List<{1}>();", "auto {0} = gcnew ::System::Collections::Generic::List<{1}>();",
tmpVarName, managedType); tmpVarName, managedType);
@ -231,10 +231,10 @@ namespace CppSharp.Types.Std
ctx.Before.WriteOpenBraceAndIndent(); ctx.Before.WriteOpenBraceAndIndent();
{ {
var elementCtx = new MarshalContext(ctx.Context, ctx.Indentation) var elementCtx = new MarshalContext(ctx.Context, ctx.Indentation)
{ {
ReturnVarName = "_element", ReturnVarName = "_element",
ReturnType = type ReturnType = type
}; };
var marshal = new CLIMarshalNativeToManagedPrinter(elementCtx); var marshal = new CLIMarshalNativeToManagedPrinter(elementCtx);
type.Type.Visit(marshal); type.Type.Visit(marshal);
@ -315,7 +315,7 @@ namespace CppSharp.Types.Std
public override void CLIMarshalToNative(MarshalContext ctx) public override void CLIMarshalToNative(MarshalContext ctx)
{ {
var marshal = (CLIMarshalManagedToNativePrinter) ctx.MarshalToNative; var marshal = (CLIMarshalManagedToNativePrinter)ctx.MarshalToNative;
if (!ctx.Parameter.Type.Desugar().IsPointer()) if (!ctx.Parameter.Type.Desugar().IsPointer())
marshal.ArgumentPrefix.Write("*"); marshal.ArgumentPrefix.Write("*");
var marshalCtxName = string.Format("ctx_{0}", ctx.Parameter.Name); 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
// would be really helpful to have ctx hold a Decl property representing the // would be really helpful to have ctx hold a Decl property representing the
// "appropriate" Decl when we get here. When MarshalKind == NativeField, Decl would // "appropriate" Decl when we get here. When MarshalKind == NativeField, Decl would
// be set to the Field we're operating on. // 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.WriteLine($"if (__{fieldName}_OwnsNativeMemory)");
ctx.Before.WriteLineIndent($"Marshal.FreeHGlobal({ctx.ReturnVarName});"); ctx.Before.WriteLineIndent($"Marshal.FreeHGlobal({ctx.ReturnVarName});");
ctx.Before.WriteLine($"__{fieldName}_OwnsNativeMemory = true;"); ctx.Before.WriteLine($"__{fieldName}_OwnsNativeMemory = true;");
@ -355,7 +355,7 @@ namespace CppSharp.Types.Std
var typePrinter = new CSharpTypePrinter(ctx.Context); var typePrinter = new CSharpTypePrinter(ctx.Context);
string qualifiedBasicString = GetQualifiedBasicString(basicString); string qualifiedBasicString = GetQualifiedBasicString(basicString);
string varBasicString = $"__basicStringRet{ctx.ParameterIndex}"; string varBasicString = $"__basicStringRet{ctx.ParameterIndex}";
bool usePointer = type.IsAddress() || ctx.MarshalKind == MarshalKind.NativeField || bool usePointer = type.IsAddress() || ctx.MarshalKind == MarshalKind.NativeField ||
ctx.MarshalKind == MarshalKind.ReturnVariableArray; ctx.MarshalKind == MarshalKind.ReturnVariableArray;
ctx.Before.WriteLine($@"var {varBasicString} = { ctx.Before.WriteLine($@"var {varBasicString} = {
basicString.Visit(typePrinter)}.{Helpers.CreateInstanceIdentifier}({ basicString.Visit(typePrinter)}.{Helpers.CreateInstanceIdentifier}({
@ -397,7 +397,7 @@ namespace CppSharp.Types.Std
var templateSpecializationType = template as TemplateSpecializationType; var templateSpecializationType = template as TemplateSpecializationType;
if (templateSpecializationType != null) if (templateSpecializationType != null)
return templateSpecializationType.GetClassTemplateSpecialization(); 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
{ {
public string Type { get; } public string Type { get; }
public GeneratorKind GeneratorKind { get; set; } public GeneratorKind GeneratorKind { get; set; }
public TypeMapAttribute(string type) : this(type, 0) public TypeMapAttribute(string type) : this(type, 0)
{ {
Type = type; Type = type;
@ -55,15 +55,15 @@ namespace CppSharp.Types
{ {
switch (kind) switch (kind)
{ {
case GeneratorKind.C: case GeneratorKind.C:
case GeneratorKind.CPlusPlus: case GeneratorKind.CPlusPlus:
return CppSignatureType(ctx); return CppSignatureType(ctx);
case GeneratorKind.CLI: case GeneratorKind.CLI:
return CLISignatureType(ctx); return CLISignatureType(ctx);
case GeneratorKind.CSharp: case GeneratorKind.CSharp:
return CSharpSignatureType(ctx); return CSharpSignatureType(ctx);
default: default:
throw new System.NotImplementedException(); throw new System.NotImplementedException();
} }
} }
@ -71,18 +71,18 @@ namespace CppSharp.Types
{ {
switch (kind) switch (kind)
{ {
case GeneratorKind.C: case GeneratorKind.C:
case GeneratorKind.CPlusPlus: case GeneratorKind.CPlusPlus:
CppMarshalToNative(ctx); CppMarshalToNative(ctx);
return; return;
case GeneratorKind.CLI: case GeneratorKind.CLI:
CLIMarshalToNative(ctx); CLIMarshalToNative(ctx);
return; return;
case GeneratorKind.CSharp: case GeneratorKind.CSharp:
CSharpMarshalToNative(ctx as CSharpMarshalContext); CSharpMarshalToNative(ctx as CSharpMarshalContext);
return; return;
default: default:
throw new System.NotImplementedException(); throw new System.NotImplementedException();
} }
} }
@ -90,18 +90,18 @@ namespace CppSharp.Types
{ {
switch (kind) switch (kind)
{ {
case GeneratorKind.C: case GeneratorKind.C:
case GeneratorKind.CPlusPlus: case GeneratorKind.CPlusPlus:
CppMarshalToManaged(ctx); CppMarshalToManaged(ctx);
return; return;
case GeneratorKind.CLI: case GeneratorKind.CLI:
CLIMarshalToManaged(ctx); CLIMarshalToManaged(ctx);
return; return;
case GeneratorKind.CSharp: case GeneratorKind.CSharp:
CSharpMarshalToManaged(ctx as CSharpMarshalContext); CSharpMarshalToManaged(ctx as CSharpMarshalContext);
return; return;
default: default:
throw new System.NotImplementedException(); throw new System.NotImplementedException();
} }
} }

2
src/Generator/Types/TypeMapDatabase.cs

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

8
src/Generator/Utils/BlockGenerator.cs

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

14
src/Generator/Utils/ExpressionEvaluator.cs

@ -54,8 +54,8 @@ namespace CodingSeb.ExpressionEvaluator
protected static readonly Regex initInNewBeginningRegex = new Regex(@"^(?>\s*){", RegexOptions.Compiled); protected static readonly Regex initInNewBeginningRegex = new Regex(@"^(?>\s*){", RegexOptions.Compiled);
// Depending on OptionInlineNamespacesEvaluationActive. Initialized in constructor // 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 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 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 // 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 = @"/\*(.*?)\*/"; protected const string blockComments = @"/\*(.*?)\*/";
@ -1578,7 +1578,7 @@ namespace CodingSeb.ExpressionEvaluator
{ {
string restOfExpression = expression.Substring(i); string restOfExpression = expression.Substring(i);
// CPPSHARP // CPPSHARP
if (restOfExpression.StartsWith("0x", StringComparison.CurrentCultureIgnoreCase)) if (restOfExpression.StartsWith("0x", StringComparison.CurrentCultureIgnoreCase))
{ {
// This is in case the literal contains suffix // This is in case the literal contains suffix
@ -1586,7 +1586,7 @@ namespace CodingSeb.ExpressionEvaluator
i += restOfExpression.Length - cleanedUp.Length; i += restOfExpression.Length - cleanedUp.Length;
restOfExpression = cleanedUp; restOfExpression = cleanedUp;
} }
// //
Match numberMatch = Regex.Match(restOfExpression, numberRegexPattern, RegexOptions.IgnoreCase); Match numberMatch = Regex.Match(restOfExpression, numberRegexPattern, RegexOptions.IgnoreCase);
Match otherBaseMatch = otherBasesNumberRegex.Match(restOfExpression); Match otherBaseMatch = otherBasesNumberRegex.Match(restOfExpression);
@ -1639,7 +1639,7 @@ namespace CodingSeb.ExpressionEvaluator
} }
else else
{ {
string numberNoSign = numberMatch.Groups[1].Value.Replace("_", ""); string numberNoSign = numberMatch.Groups[1].Value.Replace("_", "");
int sign = numberMatch.Groups["sign"].Success ? -1 : 1; int sign = numberMatch.Groups["sign"].Success ? -1 : 1;
stack.Push(ParseInteger(numberNoSign, 10, sign)); stack.Push(ParseInteger(numberNoSign, 10, sign));
} }
@ -1652,7 +1652,7 @@ namespace CodingSeb.ExpressionEvaluator
} }
} }
// CPPSHARP // CPPSHARP
/// <summary> /// <summary>
/// Heuristically convert <paramref name="numberToParse"/> to an int, uint, long, or ulong /// Heuristically convert <paramref name="numberToParse"/> to an int, uint, long, or ulong
@ -1688,7 +1688,7 @@ namespace CodingSeb.ExpressionEvaluator
if (number <= long.MaxValue) return (long)number; if (number <= long.MaxValue) return (long)number;
return number; return number;
} }
// //
protected virtual bool EvaluateInstanceCreationWithNewKeyword(string expression, Stack<object> stack, ref int i) protected virtual bool EvaluateInstanceCreationWithNewKeyword(string expression, Stack<object> stack, ref int i)
{ {

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

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

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

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

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

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

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

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

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

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