Browse Source

Format files

295227ce-f4a3-466b-a694-65c571873871
josetr 3 years ago
parent
commit
eb5031bf4c
  1. 2
      src/AST/ASTContext.cs
  2. 2
      src/AST/ClassExtensions.cs
  3. 4
      src/AST/Comment.cs
  4. 2
      src/AST/Declaration.cs
  5. 2
      src/AST/DeclarationsList.cs
  6. 2
      src/AST/Field.cs
  7. 6
      src/AST/FunctionExtensions.cs
  8. 2
      src/AST/Namespace.cs
  9. 2
      src/AST/PropertyExtensions.cs
  10. 4
      src/AST/Template.cs
  11. 42
      src/AST/Type.cs
  12. 2
      src/AST/TypeExtensions.cs
  13. 32
      src/CLI/CLI.cs
  14. 8
      src/CLI/Generator.cs
  15. 2
      src/Core/Diagnostics.cs
  16. 4
      src/Core/Toolchains/MSVCToolchain.cs
  17. 6
      src/Core/Toolchains/ManagedToolchain.cs
  18. 11
      src/Core/Toolchains/XcodeToolchain.cs
  19. 16
      src/Generator.Tests/AST/TestAST.cs
  20. 2
      src/Generator.Tests/ReadNativeSymbolsTest.cs
  21. 8
      src/Generator/AST/ASTRecord.cs
  22. 4
      src/Generator/AST/Utils.cs
  23. 4
      src/Generator/AST/VTables.cs
  24. 4
      src/Generator/Generators/C/CppHeaders.cs
  25. 6
      src/Generator/Generators/C/CppSources.cs
  26. 12
      src/Generator/Generators/C/CppTypePrinter.cs
  27. 10
      src/Generator/Generators/CLI/CLIHeaders.cs
  28. 4
      src/Generator/Generators/CLI/CLIMarshal.cs
  29. 14
      src/Generator/Generators/CLI/CLISources.cs
  30. 2
      src/Generator/Generators/CLI/CLITemplate.cs
  31. 4
      src/Generator/Generators/CLI/CLITypePrinter.cs
  32. 4
      src/Generator/Generators/CLI/CLITypeReferences.cs
  33. 12
      src/Generator/Generators/CSharp/CSharpCommentPrinter.cs
  34. 8
      src/Generator/Generators/CSharp/CSharpExpressionPrinter.cs
  35. 85
      src/Generator/Generators/CSharp/CSharpSources.cs
  36. 24
      src/Generator/Generators/CSharp/CSharpTypePrinter.cs
  37. 8
      src/Generator/Generators/ITypePrinter.cs
  38. 12
      src/Generator/Generators/NAPI/NAPIMarshal.cs
  39. 8
      src/Generator/Generators/NAPI/NAPISources.cs
  40. 8
      src/Generator/Generators/QuickJS/QuickJSSources.cs
  41. 4
      src/Generator/Generators/TS/TSSources.cs
  42. 4
      src/Generator/Generators/TS/TSTypePrinter.cs
  43. 6
      src/Generator/Library.cs
  44. 2
      src/Generator/Passes/CheckAbiParameters.cs
  45. 2
      src/Generator/Passes/CheckIgnoredDecls.cs
  46. 2
      src/Generator/Passes/CheckOperatorsOverloads.cs
  47. 2
      src/Generator/Passes/CheckStaticClass.cs
  48. 4
      src/Generator/Passes/CleanCommentsPass.cs
  49. 2
      src/Generator/Passes/ConstructorToConversionOperatorPass.cs
  50. 4
      src/Generator/Passes/DelegatesPass.cs
  51. 8
      src/Generator/Passes/GetterSetterToPropertyPass.cs
  52. 2
      src/Generator/Passes/HandleDefaultParamValuesPass.cs
  53. 2
      src/Generator/Passes/MakeProtectedNestedTypesPublicPass.cs
  54. 4
      src/Generator/Passes/MultipleInheritancePass.cs
  55. 2
      src/Generator/Passes/ParamTypeToInterfacePass.cs
  56. 2
      src/Generator/Passes/Pass.cs
  57. 10
      src/Generator/Passes/RenamePass.cs
  58. 4
      src/Generator/Passes/SpecializationMethodsWithDependentPointersPass.cs
  59. 10
      src/Generator/Passes/SymbolsCodeGenerator.cs
  60. 2
      src/Generator/Passes/ValidateOperatorsPass.cs
  61. 2
      src/Generator/Types/DeclMapDatabase.cs
  62. 6
      src/Generator/Types/Std/Stdlib.CLI.cs
  63. 2
      src/Generator/Types/Std/Stdlib.CSharp.cs
  64. 2
      src/Generator/Types/TypeMapDatabase.cs
  65. 2
      src/Generator/Utils/BlockGenerator.cs
  66. 12
      src/Generator/Utils/ExpressionEvaluator.cs
  67. 15
      src/Generator/Utils/FSM/ConsoleWriter.cs
  68. 90
      src/Generator/Utils/FSM/DFSM.cs
  69. 36
      src/Generator/Utils/FSM/Minimize.cs
  70. 54
      src/Generator/Utils/FSM/NDFSM.cs
  71. 17
      src/Generator/Utils/FSM/Program.cs
  72. 12
      src/Generator/Utils/FSM/Transition.cs
  73. 727
      src/Generator/Utils/HtmlEncoder.cs
  74. 6
      src/Generator/Utils/Options.cs
  75. 2
      src/Generator/Utils/TextGenerator.cs
  76. 46
      src/Parser/ASTConverter.cs
  77. 8
      src/Parser/Parser.cs
  78. 32
      src/Runtime/SymbolResolver.cs
  79. 6
      src/Runtime/UTF8Marshaller.cs
  80. 12
      tests/CSharp/CSharp.Gen.cs
  81. 40
      tests/CSharp/CSharp.Tests.cs
  82. 24
      tests/Common/Common.Tests.cs
  83. 2
      tests/NamespacesDerived/NamespacesDerived.Tests.cs
  84. 1
      tests/StandardLib/StandardLib.Tests.cs

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();
} }

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;
} }
} }

4
src/AST/Comment.cs

@ -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; }
@ -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;

2
src/AST/Declaration.cs

@ -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;

2
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];
} }
} }

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;

6
src/AST/FunctionExtensions.cs

@ -39,7 +39,7 @@ namespace CppSharp.AST
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
}); });
@ -57,7 +57,7 @@ namespace CppSharp.AST
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
@ -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/Namespace.cs

@ -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;
} }

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;

4
src/AST/Template.cs

@ -210,7 +210,7 @@ namespace CppSharp.AST
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;
@ -222,7 +222,7 @@ namespace CppSharp.AST
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;

42
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;
} }
@ -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,7 +608,7 @@ 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;
@ -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;
} }

2
src/AST/TypeExtensions.cs

@ -135,7 +135,7 @@
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;

32
src/CLI/CLI.cs

@ -16,30 +16,30 @@ namespace CppSharp
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); });
@ -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.");
} }

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/Core/Diagnostics.cs

@ -120,7 +120,7 @@ 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);
} }

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();

6
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", "");
} }
} }
} }

11
src/Core/Toolchains/XcodeToolchain.cs

@ -72,20 +72,23 @@ namespace CppSharp
{ {
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;

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/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",

8
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;
} }
@ -55,7 +55,7 @@ namespace CppSharp.Generators.AST
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();

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;

4
src/Generator/AST/VTables.cs

@ -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));
} }
} }
} }

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

@ -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();

6
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())

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

@ -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);
@ -478,7 +482,7 @@ namespace CppSharp.Generators.C
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}";
} }
@ -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);

10
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);

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

@ -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;

14
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();
@ -959,7 +959,7 @@ 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
@ -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())
@ -1047,7 +1047,7 @@ namespace CppSharp.Generators.CLI
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))
@ -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);
} }
} }
} }

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;
} }

4
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 += "%";

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

@ -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;

85
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;
@ -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)
@ -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();
@ -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,9 +1474,9 @@ 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))))
@ -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);
@ -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)
{ {
@ -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)
{ {
@ -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)
@ -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);

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

@ -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*";
@ -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/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>();

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

@ -81,7 +81,7 @@ 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");
@ -255,7 +255,7 @@ 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};");
@ -263,7 +263,7 @@ namespace CppSharp.Generators.NAPI
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;
@ -450,7 +450,7 @@ 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");
@ -672,7 +672,7 @@ 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)
@ -680,7 +680,7 @@ namespace CppSharp.Generators.NAPI
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);

8
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,7 +456,7 @@ namespace CppSharp.Generators.Cpp
//WriteLine($"{@class.QualifiedOriginalName}* instance = data->instance;"); //WriteLine($"{@class.QualifiedOriginalName}* instance = data->instance;");
/* /*
if (!isVoidReturn) if (!isVoidReturn)
{ {
@ -468,7 +468,7 @@ namespace CppSharp.Generators.Cpp
} }
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);");

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

@ -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();

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

@ -142,7 +142,7 @@ 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
@ -158,7 +158,7 @@ namespace CppSharp.Generators.TS
$"{function.QualifiedOriginalName}({param.OriginalName})"); $"{function.QualifiedOriginalName}({param.OriginalName})");
} }
} }
*/ */
return $"{result}"; return $"{result}";
} }

6
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;
@ -493,7 +493,7 @@ 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);
} }

2
src/Generator/Passes/CheckAbiParameters.cs

@ -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));
} }

2
src/Generator/Passes/CheckIgnoredDecls.cs

@ -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)

2
src/Generator/Passes/CheckOperatorsOverloads.cs

@ -93,7 +93,7 @@ namespace CppSharp.Passes
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;

2
src/Generator/Passes/CheckStaticClass.cs

@ -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}>";

2
src/Generator/Passes/ConstructorToConversionOperatorPass.cs

@ -87,7 +87,7 @@ namespace CppSharp.Passes
DefaultArgument = null, DefaultArgument = null,
OriginalDefaultArgument = null OriginalDefaultArgument = null
}); });
((Class) method.Namespace).Methods.Add(conversionOperator); ((Class)method.Namespace).Methods.Add(conversionOperator);
return true; return true;
} }

4
src/Generator/Passes/DelegatesPass.cs

@ -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;

8
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,9 +144,9 @@ 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);
} }

2
src/Generator/Passes/Pass.cs

@ -60,7 +60,7 @@ 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);

10
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(

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;

6
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);
@ -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);

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

@ -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;
} }
} }

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;

2
src/Generator/Utils/BlockGenerator.cs

@ -319,7 +319,7 @@ 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)
{ {

12
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);
@ -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)
{ {

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

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

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

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

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

@ -1,24 +1,30 @@
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
{
public static DFSM MinimizeDFSM(DFSM fsm)
{
var reversedNDFSM = Reverse(fsm); var reversedNDFSM = Reverse(fsm);
var reversedDFSM = PowersetConstruction(reversedNDFSM); var reversedDFSM = PowersetConstruction(reversedNDFSM);
var NDFSM = Reverse(reversedDFSM); var NDFSM = Reverse(reversedDFSM);
return PowersetConstruction(NDFSM); return PowersetConstruction(NDFSM);
} }
private static NDFSM Reverse(DFSM d){ private static NDFSM Reverse(DFSM d)
{
var delta = new List<Transition>(); var delta = new List<Transition>();
foreach (var transition in d.Delta){ foreach (var transition in d.Delta)
{
delta.Add(new Transition(transition.EndState, transition.Symbol, transition.StartState)); delta.Add(new Transition(transition.EndState, transition.Symbol, transition.StartState));
} }
return new NDFSM(d.Q, d.Sigma, delta, d.F, d.Q0); 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 Q = new List<string>();
var Sigma = ndfsm.Sigma.ToList(); var Sigma = ndfsm.Sigma.ToList();
var Delta = new List<Transition>(); var Delta = new List<Transition>();
@ -29,14 +35,17 @@ namespace CppSharp.Utils.FSM{
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(); var setState = queue.Dequeue();
processed.Add(setState); processed.Add(setState);
Q.Add(CleanupState(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)){ {
if (ndfsm.F.Contains(state))
{
F.Add(CleanupState(setState)); F.Add(CleanupState(setState));
break; break;
} }
@ -45,7 +54,8 @@ namespace CppSharp.Utils.FSM{
.Where(t => statesInCurrentSetState.Contains(t.StartState)) .Where(t => statesInCurrentSetState.Contains(t.StartState))
.Select(t => t.Symbol) .Select(t => t.Symbol)
.Distinct(); .Distinct();
foreach (var symbol in symbols){ foreach (var symbol in symbols)
{
var reachableStates = var reachableStates =
ndfsm.Delta ndfsm.Delta
.Where(t => t.Symbol == symbol && .Where(t => t.Symbol == symbol &&
@ -56,7 +66,8 @@ namespace CppSharp.Utils.FSM{
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);
} }
} }
@ -64,7 +75,8 @@ namespace CppSharp.Utils.FSM{
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(",", " ");
} }
} }

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

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

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

@ -1,18 +1,21 @@
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 Q = new List<string> { "q0", "q1" };
var Sigma = new List<char> { '0', '1' };
var Delta = new List<Transition>{ 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);

12
src/Generator/Utils/FSM/Transition.cs

@ -1,16 +1,20 @@
namespace CppSharp.Utils.FSM{ namespace CppSharp.Utils.FSM
public class Transition{ {
public class Transition
{
public string StartState { get; private set; } public string StartState { get; private set; }
public char Symbol { get; private set; } public char Symbol { get; private set; }
public string EndState { get; private set; } public string EndState { get; private set; }
public Transition(string startState, char symbol, string endState){ public Transition(string startState, char symbol, string endState)
{
StartState = startState; StartState = startState;
Symbol = symbol; Symbol = symbol;
EndState = endState; EndState = endState;
} }
public override string ToString(){ public override string ToString()
{
return string.Format("({0}, {1}) -> {2}\n", StartState, Symbol, EndState); return string.Format("({0}, {1}) -> {2}\n", StartState, Symbol, EndState);
} }
} }

727
src/Generator/Utils/HtmlEncoder.cs

@ -40,14 +40,14 @@ namespace System.Web.Util
{ {
public class HtmlEncoder public class HtmlEncoder
{ {
static SortedDictionary <string, char> entities; static SortedDictionary<string, char> entities;
static HtmlEncoder () static HtmlEncoder()
{ {
InitEntities(); InitEntities();
} }
public static string HtmlEncode (string s) public static string HtmlEncode(string s)
{ {
if (s == null) if (s == null)
return null; return null;
@ -60,47 +60,51 @@ namespace System.Web.Util
if (!needEncode) if (!needEncode)
return s; return s;
StringBuilder output = new StringBuilder (); StringBuilder output = new StringBuilder();
int len = s.Length; int len = s.Length;
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++)
switch (s [i]) { {
case '&' : switch (s[i])
output.Append ("&amp;"); {
case '&':
output.Append("&amp;");
break; break;
case '>' : case '>':
output.Append ("&gt;"); output.Append("&gt;");
break; break;
case '<' : case '<':
output.Append ("&lt;"); output.Append("&lt;");
break; break;
case '"' : case '"':
output.Append ("&quot;"); output.Append("&quot;");
break; break;
case '\uff1c': case '\uff1c':
output.Append ("&#65308;"); output.Append("&#65308;");
break; break;
case '\uff1e': case '\uff1e':
output.Append ("&#65310;"); output.Append("&#65310;");
break; break;
default: default:
char ch = s [i]; char ch = s[i];
if (ch > 159 && ch < 256) { if (ch > 159 && ch < 256)
output.Append ("&#"); {
output.Append (((int) ch).ToString (CultureInfo.InvariantCulture)); output.Append("&#");
output.Append (";"); output.Append(((int)ch).ToString(CultureInfo.InvariantCulture));
} else output.Append(";");
output.Append (ch); }
else
output.Append(ch);
break; break;
} }
} }
return output.ToString (); return output.ToString();
} }
internal static string HtmlAttributeEncode (string s) internal static string HtmlAttributeEncode(string s)
{ {
if (s == null) if (s == null)
return null; return null;
@ -112,28 +116,29 @@ namespace System.Web.Util
if (!needEncode) if (!needEncode)
return s; return s;
StringBuilder output = new StringBuilder (); StringBuilder output = new StringBuilder();
int len = s.Length; int len = s.Length;
for (int i = 0; i < len; i++) for (int i = 0; i < len; i++)
switch (s [i]) { switch (s[i])
case '&' : {
output.Append ("&amp;"); case '&':
output.Append("&amp;");
break; break;
case '"' : case '"':
output.Append ("&quot;"); output.Append("&quot;");
break; break;
case '<': case '<':
output.Append ("&lt;"); output.Append("&lt;");
break; break;
default: default:
output.Append (s [i]); output.Append(s[i]);
break; break;
} }
return output.ToString(); return output.ToString();
} }
public static string HtmlDecode (string s) public static string HtmlDecode(string s)
{ {
if (s == null) if (s == null)
return null; return null;
@ -141,11 +146,11 @@ namespace System.Web.Util
if (s.Length == 0) if (s.Length == 0)
return String.Empty; return String.Empty;
if (s.IndexOf ('&') == -1) if (s.IndexOf('&') == -1)
return s; return s;
StringBuilder rawEntity = new StringBuilder (); StringBuilder rawEntity = new StringBuilder();
StringBuilder entity = new StringBuilder (); StringBuilder entity = new StringBuilder();
StringBuilder output = new StringBuilder (); StringBuilder output = new StringBuilder();
int len = s.Length; int len = s.Length;
// 0 -> nothing, // 0 -> nothing,
// 1 -> right after '&' // 1 -> right after '&'
@ -156,365 +161,397 @@ namespace System.Web.Util
bool is_hex_value = false; bool is_hex_value = false;
bool have_trailing_digits = false; bool have_trailing_digits = false;
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++)
char c = s [i]; {
if (state == 0) { char c = s[i];
if (c == '&') { if (state == 0)
entity.Append (c); {
rawEntity.Append (c); if (c == '&')
{
entity.Append(c);
rawEntity.Append(c);
state = 1; state = 1;
} else { }
output.Append (c); else
{
output.Append(c);
} }
continue; continue;
} }
if (c == '&') { if (c == '&')
{
state = 1; state = 1;
if (have_trailing_digits) { if (have_trailing_digits)
entity.Append (number.ToString (CultureInfo.InvariantCulture)); {
entity.Append(number.ToString(CultureInfo.InvariantCulture));
have_trailing_digits = false; have_trailing_digits = false;
} }
output.Append (entity); output.Append(entity);
entity.Length = 0; entity.Length = 0;
entity.Append ('&'); entity.Append('&');
continue; continue;
} }
if (state == 1) { if (state == 1)
if (c == ';') { {
if (c == ';')
{
state = 0; state = 0;
output.Append (entity); output.Append(entity);
output.Append (c); output.Append(c);
entity.Length = 0; entity.Length = 0;
} else { }
else
{
number = 0; number = 0;
is_hex_value = false; is_hex_value = false;
state = c != '#' ? 2 : 3; state = c != '#' ? 2 : 3;
entity.Append (c); entity.Append(c);
rawEntity.Append (c); rawEntity.Append(c);
} }
} else if (state == 2) { }
entity.Append (c); else if (state == 2)
if (c == ';') { {
string key = entity.ToString (); entity.Append(c);
if (key.Length > 1 && entities.ContainsKey (key.Substring (1, key.Length - 2))) if (c == ';')
key = entities [key.Substring (1, key.Length - 2)].ToString (); {
string key = entity.ToString();
if (key.Length > 1 && entities.ContainsKey(key.Substring(1, key.Length - 2)))
key = entities[key.Substring(1, key.Length - 2)].ToString();
output.Append (key); output.Append(key);
state = 0; state = 0;
entity.Length = 0; entity.Length = 0;
rawEntity.Length = 0; rawEntity.Length = 0;
} }
} else if (state == 3) { }
if (c == ';') { else if (state == 3)
{
if (c == ';')
{
if (number == 0) if (number == 0)
output.Append (rawEntity + ";"); output.Append(rawEntity + ";");
else if (number > 65535) { else if (number > 65535)
output.Append ("&#"); {
output.Append (number.ToString (CultureInfo.InvariantCulture)); output.Append("&#");
output.Append (";"); output.Append(number.ToString(CultureInfo.InvariantCulture));
} else { output.Append(";");
output.Append ((char) number); }
else
{
output.Append((char)number);
} }
state = 0; state = 0;
entity.Length = 0; entity.Length = 0;
rawEntity.Length = 0; rawEntity.Length = 0;
have_trailing_digits = false; have_trailing_digits = false;
} else if (is_hex_value && Uri.IsHexDigit(c)) { }
else if (is_hex_value && Uri.IsHexDigit(c))
{
number = number * 16 + Uri.FromHex(c); number = number * 16 + Uri.FromHex(c);
have_trailing_digits = true; have_trailing_digits = true;
rawEntity.Append (c); rawEntity.Append(c);
} else if (Char.IsDigit (c)) { }
else if (Char.IsDigit(c))
{
number = number * 10 + (c - '0'); number = number * 10 + (c - '0');
have_trailing_digits = true; have_trailing_digits = true;
rawEntity.Append (c); rawEntity.Append(c);
} else if (number == 0 && (c == 'x' || c == 'X')) { }
else if (number == 0 && (c == 'x' || c == 'X'))
{
is_hex_value = true; is_hex_value = true;
rawEntity.Append (c); rawEntity.Append(c);
} else { }
else
{
state = 2; state = 2;
if (have_trailing_digits) { if (have_trailing_digits)
entity.Append (number.ToString (CultureInfo.InvariantCulture)); {
entity.Append(number.ToString(CultureInfo.InvariantCulture));
have_trailing_digits = false; have_trailing_digits = false;
} }
entity.Append (c); entity.Append(c);
} }
} }
} }
if (entity.Length > 0) { if (entity.Length > 0)
output.Append (entity); {
} else if (have_trailing_digits) { output.Append(entity);
output.Append (number.ToString (CultureInfo.InvariantCulture));
} }
return output.ToString (); else if (have_trailing_digits)
{
output.Append(number.ToString(CultureInfo.InvariantCulture));
}
return output.ToString();
} }
internal static bool NotEncoded (char c) internal static bool NotEncoded(char c)
{ {
return (c == '!' || c == '(' || c == ')' || c == '*' || c == '-' || c == '.' || c == '_'); return (c == '!' || c == '(' || c == ')' || c == '*' || c == '-' || c == '.' || c == '_');
} }
static void InitEntities () static void InitEntities()
{ {
// Build the hash table of HTML entity references. This list comes // Build the hash table of HTML entity references. This list comes
// from the HTML 4.01 W3C recommendation. // from the HTML 4.01 W3C recommendation.
entities = new SortedDictionary <string, char> (StringComparer.Ordinal); entities = new SortedDictionary<string, char>(StringComparer.Ordinal);
entities.Add ("nbsp", '\u00A0'); entities.Add("nbsp", '\u00A0');
entities.Add ("iexcl", '\u00A1'); entities.Add("iexcl", '\u00A1');
entities.Add ("cent", '\u00A2'); entities.Add("cent", '\u00A2');
entities.Add ("pound", '\u00A3'); entities.Add("pound", '\u00A3');
entities.Add ("curren", '\u00A4'); entities.Add("curren", '\u00A4');
entities.Add ("yen", '\u00A5'); entities.Add("yen", '\u00A5');
entities.Add ("brvbar", '\u00A6'); entities.Add("brvbar", '\u00A6');
entities.Add ("sect", '\u00A7'); entities.Add("sect", '\u00A7');
entities.Add ("uml", '\u00A8'); entities.Add("uml", '\u00A8');
entities.Add ("copy", '\u00A9'); entities.Add("copy", '\u00A9');
entities.Add ("ordf", '\u00AA'); entities.Add("ordf", '\u00AA');
entities.Add ("laquo", '\u00AB'); entities.Add("laquo", '\u00AB');
entities.Add ("not", '\u00AC'); entities.Add("not", '\u00AC');
entities.Add ("shy", '\u00AD'); entities.Add("shy", '\u00AD');
entities.Add ("reg", '\u00AE'); entities.Add("reg", '\u00AE');
entities.Add ("macr", '\u00AF'); entities.Add("macr", '\u00AF');
entities.Add ("deg", '\u00B0'); entities.Add("deg", '\u00B0');
entities.Add ("plusmn", '\u00B1'); entities.Add("plusmn", '\u00B1');
entities.Add ("sup2", '\u00B2'); entities.Add("sup2", '\u00B2');
entities.Add ("sup3", '\u00B3'); entities.Add("sup3", '\u00B3');
entities.Add ("acute", '\u00B4'); entities.Add("acute", '\u00B4');
entities.Add ("micro", '\u00B5'); entities.Add("micro", '\u00B5');
entities.Add ("para", '\u00B6'); entities.Add("para", '\u00B6');
entities.Add ("middot", '\u00B7'); entities.Add("middot", '\u00B7');
entities.Add ("cedil", '\u00B8'); entities.Add("cedil", '\u00B8');
entities.Add ("sup1", '\u00B9'); entities.Add("sup1", '\u00B9');
entities.Add ("ordm", '\u00BA'); entities.Add("ordm", '\u00BA');
entities.Add ("raquo", '\u00BB'); entities.Add("raquo", '\u00BB');
entities.Add ("frac14", '\u00BC'); entities.Add("frac14", '\u00BC');
entities.Add ("frac12", '\u00BD'); entities.Add("frac12", '\u00BD');
entities.Add ("frac34", '\u00BE'); entities.Add("frac34", '\u00BE');
entities.Add ("iquest", '\u00BF'); entities.Add("iquest", '\u00BF');
entities.Add ("Agrave", '\u00C0'); entities.Add("Agrave", '\u00C0');
entities.Add ("Aacute", '\u00C1'); entities.Add("Aacute", '\u00C1');
entities.Add ("Acirc", '\u00C2'); entities.Add("Acirc", '\u00C2');
entities.Add ("Atilde", '\u00C3'); entities.Add("Atilde", '\u00C3');
entities.Add ("Auml", '\u00C4'); entities.Add("Auml", '\u00C4');
entities.Add ("Aring", '\u00C5'); entities.Add("Aring", '\u00C5');
entities.Add ("AElig", '\u00C6'); entities.Add("AElig", '\u00C6');
entities.Add ("Ccedil", '\u00C7'); entities.Add("Ccedil", '\u00C7');
entities.Add ("Egrave", '\u00C8'); entities.Add("Egrave", '\u00C8');
entities.Add ("Eacute", '\u00C9'); entities.Add("Eacute", '\u00C9');
entities.Add ("Ecirc", '\u00CA'); entities.Add("Ecirc", '\u00CA');
entities.Add ("Euml", '\u00CB'); entities.Add("Euml", '\u00CB');
entities.Add ("Igrave", '\u00CC'); entities.Add("Igrave", '\u00CC');
entities.Add ("Iacute", '\u00CD'); entities.Add("Iacute", '\u00CD');
entities.Add ("Icirc", '\u00CE'); entities.Add("Icirc", '\u00CE');
entities.Add ("Iuml", '\u00CF'); entities.Add("Iuml", '\u00CF');
entities.Add ("ETH", '\u00D0'); entities.Add("ETH", '\u00D0');
entities.Add ("Ntilde", '\u00D1'); entities.Add("Ntilde", '\u00D1');
entities.Add ("Ograve", '\u00D2'); entities.Add("Ograve", '\u00D2');
entities.Add ("Oacute", '\u00D3'); entities.Add("Oacute", '\u00D3');
entities.Add ("Ocirc", '\u00D4'); entities.Add("Ocirc", '\u00D4');
entities.Add ("Otilde", '\u00D5'); entities.Add("Otilde", '\u00D5');
entities.Add ("Ouml", '\u00D6'); entities.Add("Ouml", '\u00D6');
entities.Add ("times", '\u00D7'); entities.Add("times", '\u00D7');
entities.Add ("Oslash", '\u00D8'); entities.Add("Oslash", '\u00D8');
entities.Add ("Ugrave", '\u00D9'); entities.Add("Ugrave", '\u00D9');
entities.Add ("Uacute", '\u00DA'); entities.Add("Uacute", '\u00DA');
entities.Add ("Ucirc", '\u00DB'); entities.Add("Ucirc", '\u00DB');
entities.Add ("Uuml", '\u00DC'); entities.Add("Uuml", '\u00DC');
entities.Add ("Yacute", '\u00DD'); entities.Add("Yacute", '\u00DD');
entities.Add ("THORN", '\u00DE'); entities.Add("THORN", '\u00DE');
entities.Add ("szlig", '\u00DF'); entities.Add("szlig", '\u00DF');
entities.Add ("agrave", '\u00E0'); entities.Add("agrave", '\u00E0');
entities.Add ("aacute", '\u00E1'); entities.Add("aacute", '\u00E1');
entities.Add ("acirc", '\u00E2'); entities.Add("acirc", '\u00E2');
entities.Add ("atilde", '\u00E3'); entities.Add("atilde", '\u00E3');
entities.Add ("auml", '\u00E4'); entities.Add("auml", '\u00E4');
entities.Add ("aring", '\u00E5'); entities.Add("aring", '\u00E5');
entities.Add ("aelig", '\u00E6'); entities.Add("aelig", '\u00E6');
entities.Add ("ccedil", '\u00E7'); entities.Add("ccedil", '\u00E7');
entities.Add ("egrave", '\u00E8'); entities.Add("egrave", '\u00E8');
entities.Add ("eacute", '\u00E9'); entities.Add("eacute", '\u00E9');
entities.Add ("ecirc", '\u00EA'); entities.Add("ecirc", '\u00EA');
entities.Add ("euml", '\u00EB'); entities.Add("euml", '\u00EB');
entities.Add ("igrave", '\u00EC'); entities.Add("igrave", '\u00EC');
entities.Add ("iacute", '\u00ED'); entities.Add("iacute", '\u00ED');
entities.Add ("icirc", '\u00EE'); entities.Add("icirc", '\u00EE');
entities.Add ("iuml", '\u00EF'); entities.Add("iuml", '\u00EF');
entities.Add ("eth", '\u00F0'); entities.Add("eth", '\u00F0');
entities.Add ("ntilde", '\u00F1'); entities.Add("ntilde", '\u00F1');
entities.Add ("ograve", '\u00F2'); entities.Add("ograve", '\u00F2');
entities.Add ("oacute", '\u00F3'); entities.Add("oacute", '\u00F3');
entities.Add ("ocirc", '\u00F4'); entities.Add("ocirc", '\u00F4');
entities.Add ("otilde", '\u00F5'); entities.Add("otilde", '\u00F5');
entities.Add ("ouml", '\u00F6'); entities.Add("ouml", '\u00F6');
entities.Add ("divide", '\u00F7'); entities.Add("divide", '\u00F7');
entities.Add ("oslash", '\u00F8'); entities.Add("oslash", '\u00F8');
entities.Add ("ugrave", '\u00F9'); entities.Add("ugrave", '\u00F9');
entities.Add ("uacute", '\u00FA'); entities.Add("uacute", '\u00FA');
entities.Add ("ucirc", '\u00FB'); entities.Add("ucirc", '\u00FB');
entities.Add ("uuml", '\u00FC'); entities.Add("uuml", '\u00FC');
entities.Add ("yacute", '\u00FD'); entities.Add("yacute", '\u00FD');
entities.Add ("thorn", '\u00FE'); entities.Add("thorn", '\u00FE');
entities.Add ("yuml", '\u00FF'); entities.Add("yuml", '\u00FF');
entities.Add ("fnof", '\u0192'); entities.Add("fnof", '\u0192');
entities.Add ("Alpha", '\u0391'); entities.Add("Alpha", '\u0391');
entities.Add ("Beta", '\u0392'); entities.Add("Beta", '\u0392');
entities.Add ("Gamma", '\u0393'); entities.Add("Gamma", '\u0393');
entities.Add ("Delta", '\u0394'); entities.Add("Delta", '\u0394');
entities.Add ("Epsilon", '\u0395'); entities.Add("Epsilon", '\u0395');
entities.Add ("Zeta", '\u0396'); entities.Add("Zeta", '\u0396');
entities.Add ("Eta", '\u0397'); entities.Add("Eta", '\u0397');
entities.Add ("Theta", '\u0398'); entities.Add("Theta", '\u0398');
entities.Add ("Iota", '\u0399'); entities.Add("Iota", '\u0399');
entities.Add ("Kappa", '\u039A'); entities.Add("Kappa", '\u039A');
entities.Add ("Lambda", '\u039B'); entities.Add("Lambda", '\u039B');
entities.Add ("Mu", '\u039C'); entities.Add("Mu", '\u039C');
entities.Add ("Nu", '\u039D'); entities.Add("Nu", '\u039D');
entities.Add ("Xi", '\u039E'); entities.Add("Xi", '\u039E');
entities.Add ("Omicron", '\u039F'); entities.Add("Omicron", '\u039F');
entities.Add ("Pi", '\u03A0'); entities.Add("Pi", '\u03A0');
entities.Add ("Rho", '\u03A1'); entities.Add("Rho", '\u03A1');
entities.Add ("Sigma", '\u03A3'); entities.Add("Sigma", '\u03A3');
entities.Add ("Tau", '\u03A4'); entities.Add("Tau", '\u03A4');
entities.Add ("Upsilon", '\u03A5'); entities.Add("Upsilon", '\u03A5');
entities.Add ("Phi", '\u03A6'); entities.Add("Phi", '\u03A6');
entities.Add ("Chi", '\u03A7'); entities.Add("Chi", '\u03A7');
entities.Add ("Psi", '\u03A8'); entities.Add("Psi", '\u03A8');
entities.Add ("Omega", '\u03A9'); entities.Add("Omega", '\u03A9');
entities.Add ("alpha", '\u03B1'); entities.Add("alpha", '\u03B1');
entities.Add ("beta", '\u03B2'); entities.Add("beta", '\u03B2');
entities.Add ("gamma", '\u03B3'); entities.Add("gamma", '\u03B3');
entities.Add ("delta", '\u03B4'); entities.Add("delta", '\u03B4');
entities.Add ("epsilon", '\u03B5'); entities.Add("epsilon", '\u03B5');
entities.Add ("zeta", '\u03B6'); entities.Add("zeta", '\u03B6');
entities.Add ("eta", '\u03B7'); entities.Add("eta", '\u03B7');
entities.Add ("theta", '\u03B8'); entities.Add("theta", '\u03B8');
entities.Add ("iota", '\u03B9'); entities.Add("iota", '\u03B9');
entities.Add ("kappa", '\u03BA'); entities.Add("kappa", '\u03BA');
entities.Add ("lambda", '\u03BB'); entities.Add("lambda", '\u03BB');
entities.Add ("mu", '\u03BC'); entities.Add("mu", '\u03BC');
entities.Add ("nu", '\u03BD'); entities.Add("nu", '\u03BD');
entities.Add ("xi", '\u03BE'); entities.Add("xi", '\u03BE');
entities.Add ("omicron", '\u03BF'); entities.Add("omicron", '\u03BF');
entities.Add ("pi", '\u03C0'); entities.Add("pi", '\u03C0');
entities.Add ("rho", '\u03C1'); entities.Add("rho", '\u03C1');
entities.Add ("sigmaf", '\u03C2'); entities.Add("sigmaf", '\u03C2');
entities.Add ("sigma", '\u03C3'); entities.Add("sigma", '\u03C3');
entities.Add ("tau", '\u03C4'); entities.Add("tau", '\u03C4');
entities.Add ("upsilon", '\u03C5'); entities.Add("upsilon", '\u03C5');
entities.Add ("phi", '\u03C6'); entities.Add("phi", '\u03C6');
entities.Add ("chi", '\u03C7'); entities.Add("chi", '\u03C7');
entities.Add ("psi", '\u03C8'); entities.Add("psi", '\u03C8');
entities.Add ("omega", '\u03C9'); entities.Add("omega", '\u03C9');
entities.Add ("thetasym", '\u03D1'); entities.Add("thetasym", '\u03D1');
entities.Add ("upsih", '\u03D2'); entities.Add("upsih", '\u03D2');
entities.Add ("piv", '\u03D6'); entities.Add("piv", '\u03D6');
entities.Add ("bull", '\u2022'); entities.Add("bull", '\u2022');
entities.Add ("hellip", '\u2026'); entities.Add("hellip", '\u2026');
entities.Add ("prime", '\u2032'); entities.Add("prime", '\u2032');
entities.Add ("Prime", '\u2033'); entities.Add("Prime", '\u2033');
entities.Add ("oline", '\u203E'); entities.Add("oline", '\u203E');
entities.Add ("frasl", '\u2044'); entities.Add("frasl", '\u2044');
entities.Add ("weierp", '\u2118'); entities.Add("weierp", '\u2118');
entities.Add ("image", '\u2111'); entities.Add("image", '\u2111');
entities.Add ("real", '\u211C'); entities.Add("real", '\u211C');
entities.Add ("trade", '\u2122'); entities.Add("trade", '\u2122');
entities.Add ("alefsym", '\u2135'); entities.Add("alefsym", '\u2135');
entities.Add ("larr", '\u2190'); entities.Add("larr", '\u2190');
entities.Add ("uarr", '\u2191'); entities.Add("uarr", '\u2191');
entities.Add ("rarr", '\u2192'); entities.Add("rarr", '\u2192');
entities.Add ("darr", '\u2193'); entities.Add("darr", '\u2193');
entities.Add ("harr", '\u2194'); entities.Add("harr", '\u2194');
entities.Add ("crarr", '\u21B5'); entities.Add("crarr", '\u21B5');
entities.Add ("lArr", '\u21D0'); entities.Add("lArr", '\u21D0');
entities.Add ("uArr", '\u21D1'); entities.Add("uArr", '\u21D1');
entities.Add ("rArr", '\u21D2'); entities.Add("rArr", '\u21D2');
entities.Add ("dArr", '\u21D3'); entities.Add("dArr", '\u21D3');
entities.Add ("hArr", '\u21D4'); entities.Add("hArr", '\u21D4');
entities.Add ("forall", '\u2200'); entities.Add("forall", '\u2200');
entities.Add ("part", '\u2202'); entities.Add("part", '\u2202');
entities.Add ("exist", '\u2203'); entities.Add("exist", '\u2203');
entities.Add ("empty", '\u2205'); entities.Add("empty", '\u2205');
entities.Add ("nabla", '\u2207'); entities.Add("nabla", '\u2207');
entities.Add ("isin", '\u2208'); entities.Add("isin", '\u2208');
entities.Add ("notin", '\u2209'); entities.Add("notin", '\u2209');
entities.Add ("ni", '\u220B'); entities.Add("ni", '\u220B');
entities.Add ("prod", '\u220F'); entities.Add("prod", '\u220F');
entities.Add ("sum", '\u2211'); entities.Add("sum", '\u2211');
entities.Add ("minus", '\u2212'); entities.Add("minus", '\u2212');
entities.Add ("lowast", '\u2217'); entities.Add("lowast", '\u2217');
entities.Add ("radic", '\u221A'); entities.Add("radic", '\u221A');
entities.Add ("prop", '\u221D'); entities.Add("prop", '\u221D');
entities.Add ("infin", '\u221E'); entities.Add("infin", '\u221E');
entities.Add ("ang", '\u2220'); entities.Add("ang", '\u2220');
entities.Add ("and", '\u2227'); entities.Add("and", '\u2227');
entities.Add ("or", '\u2228'); entities.Add("or", '\u2228');
entities.Add ("cap", '\u2229'); entities.Add("cap", '\u2229');
entities.Add ("cup", '\u222A'); entities.Add("cup", '\u222A');
entities.Add ("int", '\u222B'); entities.Add("int", '\u222B');
entities.Add ("there4", '\u2234'); entities.Add("there4", '\u2234');
entities.Add ("sim", '\u223C'); entities.Add("sim", '\u223C');
entities.Add ("cong", '\u2245'); entities.Add("cong", '\u2245');
entities.Add ("asymp", '\u2248'); entities.Add("asymp", '\u2248');
entities.Add ("ne", '\u2260'); entities.Add("ne", '\u2260');
entities.Add ("equiv", '\u2261'); entities.Add("equiv", '\u2261');
entities.Add ("le", '\u2264'); entities.Add("le", '\u2264');
entities.Add ("ge", '\u2265'); entities.Add("ge", '\u2265');
entities.Add ("sub", '\u2282'); entities.Add("sub", '\u2282');
entities.Add ("sup", '\u2283'); entities.Add("sup", '\u2283');
entities.Add ("nsub", '\u2284'); entities.Add("nsub", '\u2284');
entities.Add ("sube", '\u2286'); entities.Add("sube", '\u2286');
entities.Add ("supe", '\u2287'); entities.Add("supe", '\u2287');
entities.Add ("oplus", '\u2295'); entities.Add("oplus", '\u2295');
entities.Add ("otimes", '\u2297'); entities.Add("otimes", '\u2297');
entities.Add ("perp", '\u22A5'); entities.Add("perp", '\u22A5');
entities.Add ("sdot", '\u22C5'); entities.Add("sdot", '\u22C5');
entities.Add ("lceil", '\u2308'); entities.Add("lceil", '\u2308');
entities.Add ("rceil", '\u2309'); entities.Add("rceil", '\u2309');
entities.Add ("lfloor", '\u230A'); entities.Add("lfloor", '\u230A');
entities.Add ("rfloor", '\u230B'); entities.Add("rfloor", '\u230B');
entities.Add ("lang", '\u2329'); entities.Add("lang", '\u2329');
entities.Add ("rang", '\u232A'); entities.Add("rang", '\u232A');
entities.Add ("loz", '\u25CA'); entities.Add("loz", '\u25CA');
entities.Add ("spades", '\u2660'); entities.Add("spades", '\u2660');
entities.Add ("clubs", '\u2663'); entities.Add("clubs", '\u2663');
entities.Add ("hearts", '\u2665'); entities.Add("hearts", '\u2665');
entities.Add ("diams", '\u2666'); entities.Add("diams", '\u2666');
entities.Add ("quot", '\u0022'); entities.Add("quot", '\u0022');
entities.Add ("amp", '\u0026'); entities.Add("amp", '\u0026');
entities.Add ("lt", '\u003C'); entities.Add("lt", '\u003C');
entities.Add ("gt", '\u003E'); entities.Add("gt", '\u003E');
entities.Add ("OElig", '\u0152'); entities.Add("OElig", '\u0152');
entities.Add ("oelig", '\u0153'); entities.Add("oelig", '\u0153');
entities.Add ("Scaron", '\u0160'); entities.Add("Scaron", '\u0160');
entities.Add ("scaron", '\u0161'); entities.Add("scaron", '\u0161');
entities.Add ("Yuml", '\u0178'); entities.Add("Yuml", '\u0178');
entities.Add ("circ", '\u02C6'); entities.Add("circ", '\u02C6');
entities.Add ("tilde", '\u02DC'); entities.Add("tilde", '\u02DC');
entities.Add ("ensp", '\u2002'); entities.Add("ensp", '\u2002');
entities.Add ("emsp", '\u2003'); entities.Add("emsp", '\u2003');
entities.Add ("thinsp", '\u2009'); entities.Add("thinsp", '\u2009');
entities.Add ("zwnj", '\u200C'); entities.Add("zwnj", '\u200C');
entities.Add ("zwj", '\u200D'); entities.Add("zwj", '\u200D');
entities.Add ("lrm", '\u200E'); entities.Add("lrm", '\u200E');
entities.Add ("rlm", '\u200F'); entities.Add("rlm", '\u200F');
entities.Add ("ndash", '\u2013'); entities.Add("ndash", '\u2013');
entities.Add ("mdash", '\u2014'); entities.Add("mdash", '\u2014');
entities.Add ("lsquo", '\u2018'); entities.Add("lsquo", '\u2018');
entities.Add ("rsquo", '\u2019'); entities.Add("rsquo", '\u2019');
entities.Add ("sbquo", '\u201A'); entities.Add("sbquo", '\u201A');
entities.Add ("ldquo", '\u201C'); entities.Add("ldquo", '\u201C');
entities.Add ("rdquo", '\u201D'); entities.Add("rdquo", '\u201D');
entities.Add ("bdquo", '\u201E'); entities.Add("bdquo", '\u201E');
entities.Add ("dagger", '\u2020'); entities.Add("dagger", '\u2020');
entities.Add ("Dagger", '\u2021'); entities.Add("Dagger", '\u2021');
entities.Add ("permil", '\u2030'); entities.Add("permil", '\u2030');
entities.Add ("lsaquo", '\u2039'); entities.Add("lsaquo", '\u2039');
entities.Add ("rsaquo", '\u203A'); entities.Add("rsaquo", '\u203A');
entities.Add ("euro", '\u20AC'); entities.Add("euro", '\u20AC');
} }
} }
} }

6
src/Generator/Utils/Options.cs

@ -723,7 +723,7 @@ namespace Mono.Options
public class OptionSet : KeyedCollection<string, Option> public class OptionSet : KeyedCollection<string, Option>
{ {
public OptionSet() public OptionSet()
: this(delegate(string f) { return f; }) : this(delegate (string f) { return f; })
{ {
} }
@ -880,7 +880,7 @@ namespace Mono.Options
if (action == null) if (action == null)
throw new ArgumentNullException("action"); throw new ArgumentNullException("action");
Option p = new ActionOption(prototype, description, 1, Option p = new ActionOption(prototype, description, 1,
delegate(OptionValueCollection v) { action(v[0]); }); delegate (OptionValueCollection v) { action(v[0]); });
base.Add(p); base.Add(p);
return this; return this;
} }
@ -895,7 +895,7 @@ namespace Mono.Options
if (action == null) if (action == null)
throw new ArgumentNullException("action"); throw new ArgumentNullException("action");
Option p = new ActionOption(prototype, description, 2, Option p = new ActionOption(prototype, description, 2,
delegate(OptionValueCollection v) { action(v[0], v[1]); }); delegate (OptionValueCollection v) { action(v[0], v[1]); });
base.Add(p); base.Add(p);
return this; return this;
} }

2
src/Generator/Utils/TextGenerator.cs

@ -55,7 +55,7 @@ namespace CppSharp
if (IsStartOfLine && !string.IsNullOrWhiteSpace(msg)) if (IsStartOfLine && !string.IsNullOrWhiteSpace(msg))
StringBuilder.Append(new string(' ', StringBuilder.Append(new string(' ',
(int) (CurrentIndentation * DefaultIndentation))); (int)(CurrentIndentation * DefaultIndentation)));
if (msg.Length > 0) if (msg.Length > 0)
IsStartOfLine = msg.EndsWith(Environment.NewLine); IsStartOfLine = msg.EndsWith(Environment.NewLine);

46
src/Parser/ASTConverter.cs

@ -421,14 +421,14 @@ namespace CppSharp
for (uint i = 0; i < Context.TranslationUnitsCount; ++i) for (uint i = 0; i < Context.TranslationUnitsCount; ++i)
{ {
var unit = Context.GetTranslationUnits(i); var unit = Context.GetTranslationUnits(i);
var _unit = (AST.TranslationUnit) declConverter.Visit(unit); var _unit = (AST.TranslationUnit)declConverter.Visit(unit);
_ctx.TranslationUnits.Add(_unit); _ctx.TranslationUnits.Add(_unit);
} }
for (uint i = 0; i < Context.TranslationUnitsCount; i++) for (uint i = 0; i < Context.TranslationUnitsCount; i++)
{ {
var unit = Context.GetTranslationUnits(i); var unit = Context.GetTranslationUnits(i);
var _unit = (AST.TranslationUnit) declConverter.Visit(unit); var _unit = (AST.TranslationUnit)declConverter.Visit(unit);
declConverter.VisitDeclContext(unit, _unit); declConverter.VisitDeclContext(unit, _unit);
} }
@ -604,7 +604,7 @@ namespace CppSharp
{ {
var _type = new AST.TypedefType(); var _type = new AST.TypedefType();
VisitType(type, _type); VisitType(type, _type);
_type.Declaration = (AST.TypedefNameDecl) declConverter.Visit(type.Declaration); _type.Declaration = (AST.TypedefNameDecl)declConverter.Visit(type.Declaration);
return _type; return _type;
} }
@ -705,7 +705,7 @@ namespace CppSharp
{ {
var _type = new AST.TemplateParameterType(); var _type = new AST.TemplateParameterType();
if (type.Parameter != null) if (type.Parameter != null)
_type.Parameter = (AST.TypeTemplateParameter) declConverter.Visit(type.Parameter); _type.Parameter = (AST.TypeTemplateParameter)declConverter.Visit(type.Parameter);
_type.Depth = type.Depth; _type.Depth = type.Depth;
_type.Index = type.Index; _type.Index = type.Index;
_type.IsParameterPack = type.IsParameterPack; _type.IsParameterPack = type.IsParameterPack;
@ -717,7 +717,7 @@ namespace CppSharp
{ {
var _type = new AST.TemplateParameterSubstitutionType(); var _type = new AST.TemplateParameterSubstitutionType();
_type.Replacement = VisitQualified(type.Replacement); _type.Replacement = VisitQualified(type.Replacement);
_type.ReplacedParameter = (AST.TemplateParameterType) Visit(type.ReplacedParameter); _type.ReplacedParameter = (AST.TemplateParameterType)Visit(type.ReplacedParameter);
VisitType(type, _type); VisitType(type, _type);
return _type; return _type;
} }
@ -976,7 +976,7 @@ namespace CppSharp
bool CheckForDuplicates(Declaration decl) bool CheckForDuplicates(Declaration decl)
{ {
return decl.OriginalPtr.ToPointer() != (void*) (0x1); return decl.OriginalPtr.ToPointer() != (void*)(0x1);
} }
void VisitDeclaration(Declaration decl, AST.Declaration _decl) void VisitDeclaration(Declaration decl, AST.Declaration _decl)
@ -1105,14 +1105,14 @@ namespace CppSharp
for (uint i = 0; i < ctx.NamespacesCount; ++i) for (uint i = 0; i < ctx.NamespacesCount; ++i)
{ {
var decl = ctx.GetNamespaces(i); var decl = ctx.GetNamespaces(i);
var _decl = (AST.Namespace) Visit(decl); var _decl = (AST.Namespace)Visit(decl);
VisitDeclContext(decl, _decl); VisitDeclContext(decl, _decl);
} }
for (uint i = 0; i < ctx.ClassesCount; ++i) for (uint i = 0; i < ctx.ClassesCount; ++i)
{ {
var decl = ctx.GetClasses(i); var decl = ctx.GetClasses(i);
var _decl = (AST.Class) Visit(decl); var _decl = (AST.Class)Visit(decl);
if (!_decl.IsIncomplete || _decl.IsOpaque) if (!_decl.IsIncomplete || _decl.IsOpaque)
VisitClass(decl, _decl); VisitClass(decl, _decl);
} }
@ -1161,7 +1161,7 @@ namespace CppSharp
VisitDeclaration(decl, _typeAlias); VisitDeclaration(decl, _typeAlias);
_typeAlias.QualifiedType = typeConverter.VisitQualified(decl.QualifiedType); _typeAlias.QualifiedType = typeConverter.VisitQualified(decl.QualifiedType);
if (decl.DescribedAliasTemplate != null) if (decl.DescribedAliasTemplate != null)
_typeAlias.DescribedAliasTemplate = (AST.TypeAliasTemplate) Visit(decl.DescribedAliasTemplate); _typeAlias.DescribedAliasTemplate = (AST.TypeAliasTemplate)Visit(decl.DescribedAliasTemplate);
return _typeAlias; return _typeAlias;
} }
@ -1267,7 +1267,7 @@ namespace CppSharp
_function.Body = function.Body; _function.Body = function.Body;
_function.CallingConvention = VisitCallingConvention(function.CallingConvention); _function.CallingConvention = VisitCallingConvention(function.CallingConvention);
if (function.InstantiatedFrom != null) if (function.InstantiatedFrom != null)
_function.InstantiatedFrom = (AST.Function) Visit(function.InstantiatedFrom); _function.InstantiatedFrom = (AST.Function)Visit(function.InstantiatedFrom);
for (uint i = 0; i < function.ParametersCount; ++i) for (uint i = 0; i < function.ParametersCount; ++i)
{ {
@ -1331,7 +1331,7 @@ namespace CppSharp
for (uint i = 0; i < decl.OverriddenMethodsCount; i++) for (uint i = 0; i < decl.OverriddenMethodsCount; i++)
{ {
var @override = decl.GetOverriddenMethods(i); var @override = decl.GetOverriddenMethods(i);
_method.OverriddenMethods.Add((AST.Method) Visit(@override)); _method.OverriddenMethods.Add((AST.Method)Visit(@override));
} }
return _method; return _method;
@ -1517,7 +1517,7 @@ namespace CppSharp
private AST.Enumeration.EnumModifiers VisitEnumModifiers( private AST.Enumeration.EnumModifiers VisitEnumModifiers(
Enumeration.EnumModifiers modifiers) Enumeration.EnumModifiers modifiers)
{ {
return (AST.Enumeration.EnumModifiers) modifiers; return (AST.Enumeration.EnumModifiers)modifiers;
} }
public override AST.Declaration VisitEnumerationItem(Enumeration.Item decl) public override AST.Declaration VisitEnumerationItem(Enumeration.Item decl)
@ -1698,7 +1698,7 @@ namespace CppSharp
var @base = layout.GetBases(i); var @base = layout.GetBases(i);
var _base = new AST.LayoutBase(); var _base = new AST.LayoutBase();
_base.Offset = @base.Offset; _base.Offset = @base.Offset;
_base.Class = (AST.Class) Visit(@base.Class); _base.Class = (AST.Class)Visit(@base.Class);
_layout.Bases.Add(_base); _layout.Bases.Add(_base);
} }
@ -1821,7 +1821,7 @@ namespace CppSharp
for (uint i = 0; i < decl.SpecializationsCount; ++i) for (uint i = 0; i < decl.SpecializationsCount; ++i)
{ {
var spec = decl.GetSpecializations(i); var spec = decl.GetSpecializations(i);
var _spec = (AST.ClassTemplateSpecialization) Visit(spec); var _spec = (AST.ClassTemplateSpecialization)Visit(spec);
_decl.Specializations.Add(_spec); _decl.Specializations.Add(_spec);
} }
return _decl; return _decl;
@ -1841,7 +1841,7 @@ namespace CppSharp
VisitDeclaration(decl, _decl); VisitDeclaration(decl, _decl);
VisitClass(decl, _decl); VisitClass(decl, _decl);
_decl.SpecializationKind = VisitSpecializationKind(decl.SpecializationKind); _decl.SpecializationKind = VisitSpecializationKind(decl.SpecializationKind);
_decl.TemplatedDecl = (AST.ClassTemplate) Visit(decl.TemplatedDecl); _decl.TemplatedDecl = (AST.ClassTemplate)Visit(decl.TemplatedDecl);
for (uint i = 0; i < decl.ArgumentsCount; ++i) for (uint i = 0; i < decl.ArgumentsCount; ++i)
{ {
var arg = decl.GetArguments(i); var arg = decl.GetArguments(i);
@ -1935,8 +1935,8 @@ namespace CppSharp
var _spec = new AST.FunctionTemplateSpecialization(); var _spec = new AST.FunctionTemplateSpecialization();
FunctionTemplateSpecializations.Add(spec.__Instance, _spec); FunctionTemplateSpecializations.Add(spec.__Instance, _spec);
_spec.Template = (AST.FunctionTemplate) Visit(spec.Template); _spec.Template = (AST.FunctionTemplate)Visit(spec.Template);
_spec.SpecializedFunction = (AST.Function) Visit(spec.SpecializedFunction); _spec.SpecializedFunction = (AST.Function)Visit(spec.SpecializedFunction);
_spec.SpecializationKind = VisitSpecializationKind(spec.SpecializationKind); _spec.SpecializationKind = VisitSpecializationKind(spec.SpecializationKind);
for (uint i = 0; i < spec.ArgumentsCount; ++i) for (uint i = 0; i < spec.ArgumentsCount; ++i)
{ {
@ -1954,7 +1954,7 @@ namespace CppSharp
for (uint i = 0; i < decl.SpecializationsCount; ++i) for (uint i = 0; i < decl.SpecializationsCount; ++i)
{ {
var spec = decl.GetSpecializations(i); var spec = decl.GetSpecializations(i);
var _spec = (AST.VarTemplateSpecialization) Visit(spec); var _spec = (AST.VarTemplateSpecialization)Visit(spec);
_decl.Specializations.Add(_spec); _decl.Specializations.Add(_spec);
} }
return _decl; return _decl;
@ -1973,7 +1973,7 @@ namespace CppSharp
{ {
VisitVariable(decl, _decl); VisitVariable(decl, _decl);
_decl.SpecializationKind = VisitSpecializationKind(decl.SpecializationKind); _decl.SpecializationKind = VisitSpecializationKind(decl.SpecializationKind);
_decl.TemplatedDecl = (AST.VarTemplate) Visit(decl.TemplatedDecl); _decl.TemplatedDecl = (AST.VarTemplate)Visit(decl.TemplatedDecl);
for (uint i = 0; i < decl.ArgumentsCount; ++i) for (uint i = 0; i < decl.ArgumentsCount; ++i)
{ {
var arg = decl.GetArguments(i); var arg = decl.GetArguments(i);
@ -2108,7 +2108,7 @@ namespace CppSharp
{ {
var fullComment = new AST.FullComment(); var fullComment = new AST.FullComment();
for (uint i = 0; i < comment.BlocksCount; i++) for (uint i = 0; i < comment.BlocksCount; i++)
fullComment.Blocks.Add((AST.BlockContentComment) Visit(comment.GetBlocks(i))); fullComment.Blocks.Add((AST.BlockContentComment)Visit(comment.GetBlocks(i)));
return fullComment; return fullComment;
} }
@ -2152,7 +2152,7 @@ namespace CppSharp
{ {
var verbatimBlockComment = new AST.VerbatimBlockComment(); var verbatimBlockComment = new AST.VerbatimBlockComment();
for (uint i = 0; i < comment.LinesCount; i++) for (uint i = 0; i < comment.LinesCount; i++)
verbatimBlockComment.Lines.Add((AST.VerbatimBlockLineComment) Visit(comment.GetLines(i))); verbatimBlockComment.Lines.Add((AST.VerbatimBlockLineComment)Visit(comment.GetLines(i)));
VisitBlockCommandComment(verbatimBlockComment, comment); VisitBlockCommandComment(verbatimBlockComment, comment);
return verbatimBlockComment; return verbatimBlockComment;
} }
@ -2168,7 +2168,7 @@ namespace CppSharp
{ {
var paragraphComment = new AST.ParagraphComment(); var paragraphComment = new AST.ParagraphComment();
for (uint i = 0; i < comment.ContentCount; i++) for (uint i = 0; i < comment.ContentCount; i++)
paragraphComment.Content.Add((AST.InlineContentComment) Visit(comment.GetContent(i))); paragraphComment.Content.Add((AST.InlineContentComment)Visit(comment.GetContent(i)));
paragraphComment.IsWhitespace = comment.IsWhitespace; paragraphComment.IsWhitespace = comment.IsWhitespace;
return paragraphComment; return paragraphComment;
} }
@ -2249,7 +2249,7 @@ namespace CppSharp
{ {
blockCommandComment.CommandId = comment.CommandId; blockCommandComment.CommandId = comment.CommandId;
if (comment.ParagraphComment != null) if (comment.ParagraphComment != null)
blockCommandComment.ParagraphComment = (AST.ParagraphComment) Visit(comment.ParagraphComment); blockCommandComment.ParagraphComment = (AST.ParagraphComment)Visit(comment.ParagraphComment);
for (uint i = 0; i < comment.ArgumentsCount; i++) for (uint i = 0; i < comment.ArgumentsCount; i++)
{ {
var argument = new AST.BlockCommandComment.Argument { Text = comment.GetArguments(i).Text }; var argument = new AST.BlockCommandComment.Argument { Text = comment.GetArguments(i).Text };

8
src/Parser/Parser.cs

@ -13,19 +13,19 @@ namespace CppSharp
/// <summary> /// <summary>
/// Fired when source files are parsed. /// Fired when source files are parsed.
/// </summary> /// </summary>
public static Action<IEnumerable<string>, ParserResult> SourcesParsed = delegate {}; public static Action<IEnumerable<string>, ParserResult> SourcesParsed = delegate { };
/// <summary> /// <summary>
/// Fired when library files are parsed. /// Fired when library files are parsed.
/// </summary> /// </summary>
public static Action<string, ParserResult> LibraryParsed = delegate {}; public static Action<string, ParserResult> LibraryParsed = delegate { };
/// <summary> /// <summary>
/// Parses a C++ source file as a translation unit. /// Parses a C++ source file as a translation unit.
/// </summary> /// </summary>
public static ParserResult ParseSourceFile(string file, ParserOptions options) public static ParserResult ParseSourceFile(string file, ParserOptions options)
{ {
return ParseSourceFiles(new [] { file }, options); return ParseSourceFiles(new[] { file }, options);
} }
/// <summary> /// <summary>
@ -70,7 +70,7 @@ namespace CppSharp
var newLibrary = new AST.NativeLibrary var newLibrary = new AST.NativeLibrary
{ {
FileName = library.FileName, FileName = library.FileName,
ArchType = (ArchType) library.ArchType ArchType = (ArchType)library.ArchType
}; };
for (uint i = 0; i < library.SymbolsCount; ++i) for (uint i = 0; i < library.SymbolsCount; ++i)

32
src/Runtime/SymbolResolver.cs

@ -33,7 +33,7 @@ namespace CppSharp
static readonly Func<string, IntPtr> loadImage; static readonly Func<string, IntPtr> loadImage;
static readonly Func<IntPtr, string, IntPtr> resolveSymbol; static readonly Func<IntPtr, string, IntPtr> resolveSymbol;
static SymbolResolver () static SymbolResolver()
{ {
switch (Environment.OSVersion.Platform) switch (Environment.OSVersion.Platform)
{ {
@ -58,7 +58,7 @@ namespace CppSharp
} }
} }
public static IntPtr LoadImage (ref string name) public static IntPtr LoadImage(ref string name)
{ {
var pathValues = Environment.GetEnvironmentVariable("PATH"); var pathValues = Environment.GetEnvironmentVariable("PATH");
var paths = new List<string>(pathValues == null ? new string[0] : var paths = new List<string>(pathValues == null ? new string[0] :
@ -83,7 +83,7 @@ namespace CppSharp
if (!File.Exists(attempted)) if (!File.Exists(attempted))
continue; continue;
var ptr = loadImage (attempted); var ptr = loadImage(attempted);
if (ptr == IntPtr.Zero) if (ptr == IntPtr.Zero)
continue; continue;
@ -95,16 +95,16 @@ namespace CppSharp
return IntPtr.Zero; return IntPtr.Zero;
} }
public static IntPtr ResolveSymbol (string name, string symbol) public static IntPtr ResolveSymbol(string name, string symbol)
{ {
var image = LoadImage(ref name); var image = LoadImage(ref name);
return ResolveSymbol(image, symbol); return ResolveSymbol(image, symbol);
} }
public static IntPtr ResolveSymbol (IntPtr image, string symbol) public static IntPtr ResolveSymbol(IntPtr image, string symbol)
{ {
if (image != IntPtr.Zero) if (image != IntPtr.Zero)
return resolveSymbol (image, symbol); return resolveSymbol(image, symbol);
return IntPtr.Zero; return IntPtr.Zero;
} }
@ -113,26 +113,26 @@ namespace CppSharp
private const int RTLD_LAZY = 0x1; private const int RTLD_LAZY = 0x1;
static IntPtr dlopen (string path) static IntPtr dlopen(string path)
{ {
return dlopen (path, RTLD_LAZY); return dlopen(path, RTLD_LAZY);
} }
[DllImport ("dl", CharSet=CharSet.Ansi)] [DllImport("dl", CharSet = CharSet.Ansi)]
static extern IntPtr dlopen (string path, int flags); static extern IntPtr dlopen(string path, int flags);
[DllImport ("dl", CharSet=CharSet.Ansi)] [DllImport("dl", CharSet = CharSet.Ansi)]
static extern IntPtr dlsym (IntPtr handle, string symbol); static extern IntPtr dlsym(IntPtr handle, string symbol);
#endregion #endregion
#region Win32 #region Win32
[DllImport("kernel32", SetLastError=true)] [DllImport("kernel32", SetLastError = true)]
static extern IntPtr LoadLibrary (string lpFileName); static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)] [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
static extern IntPtr GetProcAddress (IntPtr hModule, string procName); static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
#endregion #endregion

6
src/Runtime/UTF8Marshaller.cs

@ -25,7 +25,7 @@ namespace CppSharp.Runtime
"UTF8Marshaler must be used on a string."); "UTF8Marshaler must be used on a string.");
// not null terminated // not null terminated
byte[] strbuf = Encoding.UTF8.GetBytes((string) managedObj); byte[] strbuf = Encoding.UTF8.GetBytes((string)managedObj);
IntPtr buffer = Marshal.AllocHGlobal(strbuf.Length + 1); IntPtr buffer = Marshal.AllocHGlobal(strbuf.Length + 1);
Marshal.Copy(strbuf, 0, buffer, strbuf.Length); Marshal.Copy(strbuf, 0, buffer, strbuf.Length);
@ -40,10 +40,10 @@ namespace CppSharp.Runtime
return null; return null;
int byteCount = 0; int byteCount = 0;
var str8 = (byte*) str; var str8 = (byte*)str;
while (*(str8++) != 0) byteCount += sizeof(byte); while (*(str8++) != 0) byteCount += sizeof(byte);
return Encoding.UTF8.GetString((byte*) str, byteCount); return Encoding.UTF8.GetString((byte*)str, byteCount);
} }
public static ICustomMarshaler GetInstance(string pstrCookie) public static ICustomMarshaler GetInstance(string pstrCookie)

12
tests/CSharp/CSharp.Gen.cs

@ -167,10 +167,10 @@ namespace CppSharp.Tests
var templateSpecializationType = type as TemplateSpecializationType; var templateSpecializationType = type as TemplateSpecializationType;
if (templateSpecializationType != null) if (templateSpecializationType != null)
return templateSpecializationType.Arguments[0].Type.Type; return templateSpecializationType.Arguments[0].Type.Type;
var declaration = ((TagType) type).Declaration; var declaration = ((TagType)type).Declaration;
if (declaration.IsDependent) if (declaration.IsDependent)
return new TagType(((Class) declaration).TemplateParameters[0]); return new TagType(((Class)declaration).TemplateParameters[0]);
classTemplateSpecialization = (ClassTemplateSpecialization) declaration; classTemplateSpecialization = (ClassTemplateSpecialization)declaration;
return classTemplateSpecialization.Arguments[0].Type.Type; return classTemplateSpecialization.Arguments[0].Type.Type;
} }
} }
@ -208,7 +208,7 @@ namespace CppSharp.Tests
{ {
get get
{ {
var type = (TemplateSpecializationType) Type; var type = (TemplateSpecializationType)Type;
var pointeeType = type.Arguments[0].Type; var pointeeType = type.Arguments[0].Type;
var checker = new TypeIgnoreChecker(TypeMapDatabase); var checker = new TypeIgnoreChecker(TypeMapDatabase);
pointeeType.Visit(checker); pointeeType.Visit(checker);
@ -220,7 +220,7 @@ namespace CppSharp.Tests
{ {
if (ctx.Kind == TypePrinterContextKind.Native) if (ctx.Kind == TypePrinterContextKind.Native)
{ {
var type = (TemplateSpecializationType) ctx.Type.Desugar(); var type = (TemplateSpecializationType)ctx.Type.Desugar();
var specialization = type.GetClassTemplateSpecialization(); var specialization = type.GetClassTemplateSpecialization();
var typePrinter = new CSharpTypePrinter(null); var typePrinter = new CSharpTypePrinter(null);
typePrinter.PushContext(TypePrinterContextKind.Native); typePrinter.PushContext(TypePrinterContextKind.Native);
@ -239,7 +239,7 @@ namespace CppSharp.Tests
public override void CSharpMarshalToNative(CSharpMarshalContext ctx) public override void CSharpMarshalToNative(CSharpMarshalContext ctx)
{ {
// pointless, put just so that the generated code compiles // pointless, put just so that the generated code compiles
var type = (TemplateSpecializationType) ctx.Parameter.Type.Desugar(); var type = (TemplateSpecializationType)ctx.Parameter.Type.Desugar();
var specialization = type.GetClassTemplateSpecialization(); var specialization = type.GetClassTemplateSpecialization();
var typePrinter = new CSharpTypePrinter(null); var typePrinter = new CSharpTypePrinter(null);
typePrinter.PushContext(TypePrinterContextKind.Native); typePrinter.PushContext(TypePrinterContextKind.Native);

40
tests/CSharp/CSharp.Tests.cs

@ -149,7 +149,7 @@ public unsafe class CSharpTests
foo[0] = 250; foo[0] = 250;
Assert.That(foo[0], Is.EqualTo(250)); Assert.That(foo[0], Is.EqualTo(250));
Assert.That(foo[(uint) 0], Is.EqualTo(15)); Assert.That(foo[(uint)0], Is.EqualTo(15));
} }
using (var bar = new Bar()) using (var bar = new Bar())
@ -168,7 +168,7 @@ public unsafe class CSharpTests
{ {
using (var f = new Foo()) using (var f = new Foo())
{ {
foreach(var pod in new[] { f.SmallPodCdecl, f.SmallPodStdcall, f.SmallPodThiscall }) foreach (var pod in new[] { f.SmallPodCdecl, f.SmallPodStdcall, f.SmallPodThiscall })
{ {
Assert.That(pod.A, Is.EqualTo(10000)); Assert.That(pod.A, Is.EqualTo(10000));
Assert.That(pod.B, Is.EqualTo(40000)); Assert.That(pod.B, Is.EqualTo(40000));
@ -189,7 +189,7 @@ public unsafe class CSharpTests
using (var baz = new Baz()) using (var baz = new Baz())
{ {
Assert.That(baz.Method, Is.EqualTo(1)); Assert.That(baz.Method, Is.EqualTo(1));
var bar = (IBar) baz; var bar = (IBar)baz;
Assert.That(bar.Method, Is.EqualTo(2)); Assert.That(bar.Method, Is.EqualTo(2));
Assert.That(baz[0], Is.EqualTo(50)); Assert.That(baz[0], Is.EqualTo(50));
using (Foo foo = new Foo { A = 1000 }) using (Foo foo = new Foo { A = 1000 })
@ -222,7 +222,7 @@ public unsafe class CSharpTests
} }
using (var qux = new Qux()) using (var qux = new Qux())
{ {
using (var p = new P((IQux) qux) { Value = 20 }) using (var p = new P((IQux)qux) { Value = 20 })
{ {
Assert.That(p.Value, Is.EqualTo(30)); Assert.That(p.Value, Is.EqualTo(30));
p.Prop = 50; p.Prop = 50;
@ -271,7 +271,7 @@ public unsafe class CSharpTests
int i = 5; int i = 5;
array[0] = new IntPtr(&i); array[0] = new IntPtr(&i);
bar.ArrayOfPrimitivePointers = array; bar.ArrayOfPrimitivePointers = array;
Assert.That(i, Is.EqualTo(*(int*) bar.ArrayOfPrimitivePointers[0])); Assert.That(i, Is.EqualTo(*(int*)bar.ArrayOfPrimitivePointers[0]));
} }
} }
@ -287,7 +287,7 @@ public unsafe class CSharpTests
[Test] [Test]
public void TestPropertiesConflictingWithMethod() public void TestPropertiesConflictingWithMethod()
{ {
using (var p = new P((IQux) new Qux()) { Test = true }) using (var p = new P((IQux)new Qux()) { Test = true })
{ {
Assert.That(p.Test, Is.True); Assert.That(p.Test, Is.True);
p.GetTest(); p.GetTest();
@ -463,10 +463,10 @@ public unsafe class CSharpTests
{ {
IntPtr native1; IntPtr native1;
IntPtr native2; IntPtr native2;
var hasVirtualDtor1Map = (IDictionary<IntPtr, HasVirtualDtor1>) typeof( var hasVirtualDtor1Map = (IDictionary<IntPtr, HasVirtualDtor1>)typeof(
HasVirtualDtor1).GetField("NativeToManagedMap", HasVirtualDtor1).GetField("NativeToManagedMap",
BindingFlags.Static | BindingFlags.NonPublic).GetValue(null); BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
var hasVirtualDtor2Map = (IDictionary<IntPtr, HasVirtualDtor2>) typeof( var hasVirtualDtor2Map = (IDictionary<IntPtr, HasVirtualDtor2>)typeof(
HasVirtualDtor2).GetField("NativeToManagedMap", HasVirtualDtor2).GetField("NativeToManagedMap",
BindingFlags.Static | BindingFlags.NonPublic).GetValue(null); BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
using (var testNativeToManagedMap = new TestNativeToManagedMap()) using (var testNativeToManagedMap = new TestNativeToManagedMap())
@ -487,7 +487,7 @@ public unsafe class CSharpTests
{ {
using (var testNativeToManagedMap = new TestNativeToManagedMap()) using (var testNativeToManagedMap = new TestNativeToManagedMap())
{ {
var quxMap = (IDictionary<IntPtr, IQux>) typeof( var quxMap = (IDictionary<IntPtr, IQux>)typeof(
Qux).GetField("NativeToManagedMap", Qux).GetField("NativeToManagedMap",
BindingFlags.Static | BindingFlags.NonPublic).GetValue(null); BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
var bar = new Bar(); var bar = new Bar();
@ -811,7 +811,7 @@ public unsafe class CSharpTests
}) })
{ {
var independentFields = internalType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic); var independentFields = internalType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
var fieldOffset = (FieldOffsetAttribute) independentFields[0].GetCustomAttribute(typeof(FieldOffsetAttribute)); var fieldOffset = (FieldOffsetAttribute)independentFields[0].GetCustomAttribute(typeof(FieldOffsetAttribute));
if (fieldOffset != null) if (fieldOffset != null)
Assert.That(fieldOffset.Value, Is.EqualTo(0)); Assert.That(fieldOffset.Value, Is.EqualTo(0));
Assert.That((int)Marshal.OffsetOf(internalType, independentFields[0].Name), Is.EqualTo(0)); Assert.That((int)Marshal.OffsetOf(internalType, independentFields[0].Name), Is.EqualTo(0));
@ -827,11 +827,11 @@ public unsafe class CSharpTests
{ {
var independentFields = internalType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic); var independentFields = internalType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
Assert.That(independentFields.Length, Is.EqualTo(2)); Assert.That(independentFields.Length, Is.EqualTo(2));
var fieldOffsetKey = (FieldOffsetAttribute) independentFields[0].GetCustomAttribute(typeof(FieldOffsetAttribute)); var fieldOffsetKey = (FieldOffsetAttribute)independentFields[0].GetCustomAttribute(typeof(FieldOffsetAttribute));
if (fieldOffsetKey != null) if (fieldOffsetKey != null)
Assert.That(fieldOffsetKey.Value, Is.EqualTo(0)); Assert.That(fieldOffsetKey.Value, Is.EqualTo(0));
Assert.That((int)Marshal.OffsetOf(internalType, independentFields[0].Name), Is.EqualTo(0)); Assert.That((int)Marshal.OffsetOf(internalType, independentFields[0].Name), Is.EqualTo(0));
var fieldOffsetValue = (FieldOffsetAttribute) independentFields[1].GetCustomAttribute(typeof(FieldOffsetAttribute)); var fieldOffsetValue = (FieldOffsetAttribute)independentFields[1].GetCustomAttribute(typeof(FieldOffsetAttribute));
if (fieldOffsetValue != null) if (fieldOffsetValue != null)
Assert.That(fieldOffsetValue.Value, Is.EqualTo(Marshal.SizeOf(IntPtr.Zero))); Assert.That(fieldOffsetValue.Value, Is.EqualTo(Marshal.SizeOf(IntPtr.Zero)));
Assert.That((int)Marshal.OffsetOf(internalType, independentFields[1].Name), Is.EqualTo(Marshal.SizeOf(IntPtr.Zero))); Assert.That((int)Marshal.OffsetOf(internalType, independentFields[1].Name), Is.EqualTo(Marshal.SizeOf(IntPtr.Zero)));
@ -896,8 +896,8 @@ public unsafe class CSharpTests
Assert.That(StaticVariables.Int, Is.EqualTo(1020304050)); Assert.That(StaticVariables.Int, Is.EqualTo(1020304050));
Assert.That(StaticVariables.Float, Is.EqualTo(0.5020f)); Assert.That(StaticVariables.Float, Is.EqualTo(0.5020f));
Assert.That(StaticVariables.String, Is.EqualTo("Str")); Assert.That(StaticVariables.String, Is.EqualTo("Str"));
Assert.That(StaticVariables.ChrArray, Is.EqualTo(new[] { 'A', 'B'})); Assert.That(StaticVariables.ChrArray, Is.EqualTo(new[] { 'A', 'B' }));
Assert.That(StaticVariables.IntArray, Is.EqualTo(new[] { 1020304050 , 1526374850 })); Assert.That(StaticVariables.IntArray, Is.EqualTo(new[] { 1020304050, 1526374850 }));
Assert.That(StaticVariables.FloatArray, Is.EqualTo(new[] { 0.5020f, 0.6020f })); Assert.That(StaticVariables.FloatArray, Is.EqualTo(new[] { 0.5020f, 0.6020f }));
Assert.That(StaticVariables.BoolArray, Is.EqualTo(new[] { false, true })); Assert.That(StaticVariables.BoolArray, Is.EqualTo(new[] { false, true }));
Assert.That(StaticVariables.VoidPtrArray, Is.EqualTo(new IntPtr[] { new IntPtr(0x10203040), new IntPtr(0x40302010) })); Assert.That(StaticVariables.VoidPtrArray, Is.EqualTo(new IntPtr[] { new IntPtr(0x10203040), new IntPtr(0x40302010) }));
@ -1036,7 +1036,7 @@ public unsafe class CSharpTests
Assert.That(ts.ThirtyTwoBitConst, Is.EqualTo(str)); Assert.That(ts.ThirtyTwoBitConst, Is.EqualTo(str));
Assert.That(OwnsNativeMemory(ts, "__thirtyTwoBitConst_OwnsNativeMemory"), Is.EqualTo(false)); Assert.That(OwnsNativeMemory(ts, "__thirtyTwoBitConst_OwnsNativeMemory"), Is.EqualTo(false));
var x = (uint *)ts.ThirtyTwoBitNonConst; var x = (uint*)ts.ThirtyTwoBitNonConst;
for (int i = 0; i < otherStr.Length; i++) for (int i = 0; i < otherStr.Length; i++)
{ {
Assert.That(*x++, Is.EqualTo(otherStr[i])); Assert.That(*x++, Is.EqualTo(otherStr[i]));
@ -1333,8 +1333,8 @@ public unsafe class CSharpTests
using (var dependentValueFields = new DependentValueFields<IntPtr>()) using (var dependentValueFields = new DependentValueFields<IntPtr>())
{ {
int i = 10; int i = 10;
dependentValueFields.DependentValue = (IntPtr) (&i); dependentValueFields.DependentValue = (IntPtr)(&i);
Assert.That(*(int*) dependentValueFields.DependentValue, Is.EqualTo(10)); Assert.That(*(int*)dependentValueFields.DependentValue, Is.EqualTo(10));
} }
} }
@ -1673,7 +1673,7 @@ public unsafe class CSharpTests
using (var indexproperty = new TestIndexedProperties()) using (var indexproperty = new TestIndexedProperties())
{ {
uint n = 21; uint n = 21;
Assert.That(*((int*) indexproperty[n]), Is.EqualTo(21)); Assert.That(*((int*)indexproperty[n]), Is.EqualTo(21));
} }
} }
@ -1773,8 +1773,8 @@ public unsafe class CSharpTests
public void TestRValueReferenceToPointer() public void TestRValueReferenceToPointer()
{ {
int value = 5; int value = 5;
IntPtr intPtr = CSharp.CSharp.RValueReferenceToPointer((IntPtr*) &value); IntPtr intPtr = CSharp.CSharp.RValueReferenceToPointer((IntPtr*)&value);
Assert.That((int) intPtr, Is.EqualTo(value)); Assert.That((int)intPtr, Is.EqualTo(value));
} }
[Test] [Test]

24
tests/Common/Common.Tests.cs

@ -66,7 +66,7 @@ public class CommonTests
new AmbiguousParamNames(0, 0).Dispose(); new AmbiguousParamNames(0, 0).Dispose();
Common.SMallFollowedByCapital(); Common.SMallFollowedByCapital();
Common.IntegerOverload(0); Common.IntegerOverload(0);
Common.IntegerOverload((uint) 0); Common.IntegerOverload((uint)0);
Common.TakeVoidStarStar(null); Common.TakeVoidStarStar(null);
Common.OverloadPointer(IntPtr.Zero, 1); Common.OverloadPointer(IntPtr.Zero, 1);
using (new DerivedFromSecondaryBaseWithIgnoredVirtualMethod()) { } using (new DerivedFromSecondaryBaseWithIgnoredVirtualMethod()) { }
@ -198,7 +198,7 @@ public class CommonTests
{ {
using (var hello = new Hello()) using (var hello = new Hello())
{ {
hello.EnumOut((int) Enum.C, out Enum e); hello.EnumOut((int)Enum.C, out Enum e);
Assert.That(e, Is.EqualTo(Enum.C)); Assert.That(e, Is.EqualTo(Enum.C));
} }
} }
@ -208,7 +208,7 @@ public class CommonTests
{ {
using (var hello = new Hello()) using (var hello = new Hello())
{ {
hello.EnumOutRef((int) Enum.C, out Enum e); hello.EnumOutRef((int)Enum.C, out Enum e);
Assert.That(e, Is.EqualTo(Enum.C)); Assert.That(e, Is.EqualTo(Enum.C));
} }
} }
@ -485,16 +485,16 @@ public class CommonTests
Assert.AreEqual(2, indexedProperties[0]); Assert.AreEqual(2, indexedProperties[0]);
indexedProperties[0f] = 3; indexedProperties[0f] = 3;
Assert.AreEqual(3, indexedProperties[0f]); Assert.AreEqual(3, indexedProperties[0f]);
var properties = indexedProperties[(byte) 0]; var properties = indexedProperties[(byte)0];
Assert.AreEqual(0, properties.Field); Assert.AreEqual(0, properties.Field);
var newProperties = new TestProperties(); var newProperties = new TestProperties();
newProperties.Field = 4; newProperties.Field = 4;
indexedProperties[(byte) 0] = newProperties; indexedProperties[(byte)0] = newProperties;
Assert.AreEqual(4, indexedProperties[(byte) 0].Field); Assert.AreEqual(4, indexedProperties[(byte)0].Field);
newProperties = indexedProperties[(short) 0]; newProperties = indexedProperties[(short)0];
Assert.AreEqual(4, newProperties.Field); Assert.AreEqual(4, newProperties.Field);
newProperties.Field = 5; newProperties.Field = 5;
Assert.AreEqual(5, indexedProperties[(byte) 0].Field); Assert.AreEqual(5, indexedProperties[(byte)0].Field);
newProperties.get(); newProperties.get();
newProperties.set(0); newProperties.set(0);
newProperties.Get(); newProperties.Get();
@ -503,8 +503,8 @@ public class CommonTests
var bar = new Bar { A = 5 }; var bar = new Bar { A = 5 };
indexedProperties[0u] = bar; indexedProperties[0u] = bar;
Assert.That(bar.A, Is.EqualTo(indexedProperties[0u].A)); Assert.That(bar.A, Is.EqualTo(indexedProperties[0u].A));
indexedProperties[(ushort) 0] = bar; indexedProperties[(ushort)0] = bar;
Assert.That(bar.A, Is.EqualTo(indexedProperties[(ushort) 0].A)); Assert.That(bar.A, Is.EqualTo(indexedProperties[(ushort)0].A));
using (var foo = new Foo()) using (var foo = new Foo())
{ {
@ -649,7 +649,7 @@ public class CommonTests
{ {
ClassB classB = classA; ClassB classB = classA;
Assert.AreEqual(classA.Value, classB.Value); Assert.AreEqual(classA.Value, classB.Value);
ClassC classC = (ClassC) classB; ClassC classC = (ClassC)classB;
Assert.AreEqual(classB.Value, classC.Value); Assert.AreEqual(classB.Value, classC.Value);
} }
} }
@ -889,7 +889,7 @@ public class CommonTests
[Test] [Test]
public void TestPassingNullToValue() public void TestPassingNullToValue()
{ {
Assert.Catch<ArgumentNullException>(() => new Bar((Foo) null)); Assert.Catch<ArgumentNullException>(() => new Bar((Foo)null));
} }
[Test] [Test]

2
tests/NamespacesDerived/NamespacesDerived.Tests.cs

@ -129,7 +129,7 @@ public class NamespaceDerivedTests
Is.EqualTo(@params[0].Name)); Is.EqualTo(@params[0].Name));
Assert.That(path.Value, Is.EqualTo("A full or partial name for the process to attach to.")); Assert.That(path.Value, Is.EqualTo("A full or partial name for the process to attach to."));
XElement wait_for = (XElement) path.NextNode; XElement wait_for = (XElement)path.NextNode;
Assert.That(wait_for.Attribute("name").Value, Is.EqualTo(@params[1].Name)); Assert.That(wait_for.Attribute("name").Value, Is.EqualTo(@params[1].Name));
Assert.That(wait_for.Elements("para").Select(p => string.Concat(p.Nodes())), Assert.That(wait_for.Elements("para").Select(p => string.Concat(p.Nodes())),
Is.EquivalentTo( Is.EquivalentTo(

1
tests/StandardLib/StandardLib.Tests.cs

@ -57,4 +57,3 @@ public class StandardLibTests
Assert.AreEqual(testString, stringWriter.ToString()); Assert.AreEqual(testString, stringWriter.ToString());
} }
} }
Loading…
Cancel
Save