Browse Source

Merge pull request #249 from tomba/normalize

Normalize line-endings
pull/250/head
João Matos 12 years ago
parent
commit
cd37e10e5f
  1. 10
      .gitattributes
  2. 42
      src/AST/Class.cs
  3. 16
      src/AST/Field.cs
  4. 36
      src/AST/TranslationUnit.cs
  5. 5688
      src/CppParser/Bindings/CLI/AST.cpp
  6. 3750
      src/CppParser/Bindings/CLI/AST.h
  7. 878
      src/CppParser/Bindings/CLI/CppParser.cpp
  8. 566
      src/CppParser/Bindings/CLI/CppParser.h
  9. 54
      src/Generator/AST/Utils.cs
  10. 72
      src/Generator/Driver.cs
  11. 34
      src/Generator/Generator.lua
  12. 88
      src/Generator/Generators/CLI/CLIMarshal.cs
  13. 6
      src/Generator/Generators/CLI/CLISourcesTemplate.cs
  14. 796
      src/Generator/Generators/CLI/CLITypePrinter.cs
  15. 60
      src/Generator/Generators/CLI/CLITypeReferences.cs
  16. 404
      src/Generator/Generators/CSharp/CSharpTextTemplate.cs
  17. 1172
      src/Generator/Generators/CSharp/CSharpTypePrinter.cs
  18. 54
      src/Generator/Generators/ExtensionMethods.cs
  19. 42
      src/Generator/Generators/Template.cs
  20. 72
      src/Generator/Options.cs
  21. 448
      src/Generator/Passes/CheckOperatorsOverloads.cs
  22. 116
      src/Generator/Passes/ConstructorToConversionOperatorPass.cs
  23. 12
      src/Generator/Passes/GenerateAbstractImplementationsPass.cs
  24. 18
      src/Generator/Passes/GetterSetterToPropertyPass.cs
  25. 10
      src/Generator/Passes/MultipleInheritancePass.cs
  26. 660
      src/Generator/Types/CppTypePrinter.cs
  27. 48
      src/Generator/Types/Types.cs
  28. 30
      src/Generator/Utils/Utils.cs
  29. 104
      tests/Basic/Basic.Tests.cs
  30. 2
      tests/Basic/Basic.cs
  31. 214
      tests/Basic/Basic.h
  32. 6
      tests/CSharpTemp/CSharpTemp.cs

10
.gitattributes vendored

@ -0,0 +1,10 @@
# Explicitly declare text files you want to always be normalized and converted
# to native line endings on checkout.
*.c text
*.h text
*.cpp text
*.cs text diff=csharp
*.lua text
# Declare files that will always have CRLF line endings on checkout.
*.sln text eol=crlf

42
src/AST/Class.cs

@ -33,7 +33,7 @@ namespace CppSharp.AST
{ {
get get
{ {
Class @class; Class @class;
Type.TryGetClass(out @class); Type.TryGetClass(out @class);
return @class; return @class;
} }
@ -115,26 +115,26 @@ namespace CppSharp.AST
Layout = new ClassLayout(); Layout = new ClassLayout();
} }
public Class(Class @class) public Class(Class @class)
: base(@class) : base(@class)
{ {
Bases = new List<BaseClassSpecifier>(@class.Bases); Bases = new List<BaseClassSpecifier>(@class.Bases);
Fields = new List<Field>(@class.Fields); Fields = new List<Field>(@class.Fields);
Properties = new List<Property>(@class.Properties); Properties = new List<Property>(@class.Properties);
Methods = new List<Method>(@class.Methods); Methods = new List<Method>(@class.Methods);
Specifiers = new List<AccessSpecifierDecl>(@class.Specifiers); Specifiers = new List<AccessSpecifierDecl>(@class.Specifiers);
IsPOD = @class.IsPOD; IsPOD = @class.IsPOD;
Type = @class.Type; Type = @class.Type;
Layout = new ClassLayout(@class.Layout); Layout = new ClassLayout(@class.Layout);
IsAbstract = @class.IsAbstract; IsAbstract = @class.IsAbstract;
IsUnion = @class.IsUnion; IsUnion = @class.IsUnion;
IsOpaque = @class.IsOpaque; IsOpaque = @class.IsOpaque;
IsDynamic = @class.IsDynamic; IsDynamic = @class.IsDynamic;
IsPolymorphic = @class.IsPolymorphic; IsPolymorphic = @class.IsPolymorphic;
HasNonTrivialDefaultConstructor = @class.HasNonTrivialDefaultConstructor; HasNonTrivialDefaultConstructor = @class.HasNonTrivialDefaultConstructor;
HasNonTrivialCopyConstructor = @class.HasNonTrivialCopyConstructor; HasNonTrivialCopyConstructor = @class.HasNonTrivialCopyConstructor;
HasNonTrivialDestructor = @class.HasNonTrivialDestructor; HasNonTrivialDestructor = @class.HasNonTrivialDestructor;
IsStatic = @class.IsStatic; IsStatic = @class.IsStatic;
} }
public bool HasBase public bool HasBase

16
src/AST/Field.cs

@ -29,14 +29,14 @@ namespace CppSharp.AST
QualifiedType = type; QualifiedType = type;
Access = access; Access = access;
Offset = 0; Offset = 0;
} }
public Field(Field field): base(field) public Field(Field field): base(field)
{ {
QualifiedType = field.QualifiedType; QualifiedType = field.QualifiedType;
Offset = field.Offset; Offset = field.Offset;
Class = field.Class; Class = field.Class;
Expression = field.Expression; Expression = field.Expression;
} }
public override T Visit<T>(IDeclVisitor<T> visitor) public override T Visit<T>(IDeclVisitor<T> visitor)

36
src/AST/TranslationUnit.cs

@ -45,23 +45,23 @@ namespace CppSharp.AST
/// Contains the include path. /// Contains the include path.
public string IncludePath; public string IncludePath;
public string FileRelativeDirectory public string FileRelativeDirectory
{ {
get get
{ {
var path = IncludePath.Replace('\\', '/'); var path = IncludePath.Replace('\\', '/');
var index = path.LastIndexOf('/'); var index = path.LastIndexOf('/');
return path.Substring(0, index); return path.Substring(0, index);
} }
} }
public string FileRelativePath public string FileRelativePath
{ {
get get
{ {
return Path.Combine(FileRelativeDirectory, FileName); return Path.Combine(FileRelativeDirectory, FileName);
} }
} }
} }
} }

5688
src/CppParser/Bindings/CLI/AST.cpp

File diff suppressed because it is too large Load Diff

3750
src/CppParser/Bindings/CLI/AST.h

File diff suppressed because it is too large Load Diff

878
src/CppParser/Bindings/CLI/CppParser.cpp

@ -1,439 +1,439 @@
#include "CppParser.h" #include "CppParser.h"
#include "AST.h" #include "AST.h"
#include "Target.h" #include "Target.h"
using namespace System; using namespace System;
using namespace System::Runtime::InteropServices; using namespace System::Runtime::InteropServices;
CppSharp::Parser::ParserOptions::ParserOptions(::CppSharp::CppParser::ParserOptions* native) CppSharp::Parser::ParserOptions::ParserOptions(::CppSharp::CppParser::ParserOptions* native)
{ {
NativePtr = native; NativePtr = native;
} }
CppSharp::Parser::ParserOptions::ParserOptions(System::IntPtr native) CppSharp::Parser::ParserOptions::ParserOptions(System::IntPtr native)
{ {
auto __native = (::CppSharp::CppParser::ParserOptions*)native.ToPointer(); auto __native = (::CppSharp::CppParser::ParserOptions*)native.ToPointer();
NativePtr = __native; NativePtr = __native;
} }
CppSharp::Parser::ParserOptions::ParserOptions() CppSharp::Parser::ParserOptions::ParserOptions()
{ {
NativePtr = new ::CppSharp::CppParser::ParserOptions(); NativePtr = new ::CppSharp::CppParser::ParserOptions();
} }
System::String^ CppSharp::Parser::ParserOptions::getArguments(unsigned int i) System::String^ CppSharp::Parser::ParserOptions::getArguments(unsigned int i)
{ {
auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getArguments(i); auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getArguments(i);
if (__ret == nullptr) return nullptr; if (__ret == nullptr) return nullptr;
return clix::marshalString<clix::E_UTF8>(__ret); return clix::marshalString<clix::E_UTF8>(__ret);
} }
void CppSharp::Parser::ParserOptions::addArguments(System::String^ s) void CppSharp::Parser::ParserOptions::addArguments(System::String^ s)
{ {
auto _arg0 = clix::marshalString<clix::E_UTF8>(s); auto _arg0 = clix::marshalString<clix::E_UTF8>(s);
auto arg0 = _arg0.c_str(); auto arg0 = _arg0.c_str();
((::CppSharp::CppParser::ParserOptions*)NativePtr)->addArguments(arg0); ((::CppSharp::CppParser::ParserOptions*)NativePtr)->addArguments(arg0);
} }
System::String^ CppSharp::Parser::ParserOptions::getIncludeDirs(unsigned int i) System::String^ CppSharp::Parser::ParserOptions::getIncludeDirs(unsigned int i)
{ {
auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getIncludeDirs(i); auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getIncludeDirs(i);
if (__ret == nullptr) return nullptr; if (__ret == nullptr) return nullptr;
return clix::marshalString<clix::E_UTF8>(__ret); return clix::marshalString<clix::E_UTF8>(__ret);
} }
void CppSharp::Parser::ParserOptions::addIncludeDirs(System::String^ s) void CppSharp::Parser::ParserOptions::addIncludeDirs(System::String^ s)
{ {
auto _arg0 = clix::marshalString<clix::E_UTF8>(s); auto _arg0 = clix::marshalString<clix::E_UTF8>(s);
auto arg0 = _arg0.c_str(); auto arg0 = _arg0.c_str();
((::CppSharp::CppParser::ParserOptions*)NativePtr)->addIncludeDirs(arg0); ((::CppSharp::CppParser::ParserOptions*)NativePtr)->addIncludeDirs(arg0);
} }
System::String^ CppSharp::Parser::ParserOptions::getSystemIncludeDirs(unsigned int i) System::String^ CppSharp::Parser::ParserOptions::getSystemIncludeDirs(unsigned int i)
{ {
auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getSystemIncludeDirs(i); auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getSystemIncludeDirs(i);
if (__ret == nullptr) return nullptr; if (__ret == nullptr) return nullptr;
return clix::marshalString<clix::E_UTF8>(__ret); return clix::marshalString<clix::E_UTF8>(__ret);
} }
void CppSharp::Parser::ParserOptions::addSystemIncludeDirs(System::String^ s) void CppSharp::Parser::ParserOptions::addSystemIncludeDirs(System::String^ s)
{ {
auto _arg0 = clix::marshalString<clix::E_UTF8>(s); auto _arg0 = clix::marshalString<clix::E_UTF8>(s);
auto arg0 = _arg0.c_str(); auto arg0 = _arg0.c_str();
((::CppSharp::CppParser::ParserOptions*)NativePtr)->addSystemIncludeDirs(arg0); ((::CppSharp::CppParser::ParserOptions*)NativePtr)->addSystemIncludeDirs(arg0);
} }
System::String^ CppSharp::Parser::ParserOptions::getDefines(unsigned int i) System::String^ CppSharp::Parser::ParserOptions::getDefines(unsigned int i)
{ {
auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getDefines(i); auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getDefines(i);
if (__ret == nullptr) return nullptr; if (__ret == nullptr) return nullptr;
return clix::marshalString<clix::E_UTF8>(__ret); return clix::marshalString<clix::E_UTF8>(__ret);
} }
void CppSharp::Parser::ParserOptions::addDefines(System::String^ s) void CppSharp::Parser::ParserOptions::addDefines(System::String^ s)
{ {
auto _arg0 = clix::marshalString<clix::E_UTF8>(s); auto _arg0 = clix::marshalString<clix::E_UTF8>(s);
auto arg0 = _arg0.c_str(); auto arg0 = _arg0.c_str();
((::CppSharp::CppParser::ParserOptions*)NativePtr)->addDefines(arg0); ((::CppSharp::CppParser::ParserOptions*)NativePtr)->addDefines(arg0);
} }
System::String^ CppSharp::Parser::ParserOptions::getLibraryDirs(unsigned int i) System::String^ CppSharp::Parser::ParserOptions::getLibraryDirs(unsigned int i)
{ {
auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getLibraryDirs(i); auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getLibraryDirs(i);
if (__ret == nullptr) return nullptr; if (__ret == nullptr) return nullptr;
return clix::marshalString<clix::E_UTF8>(__ret); return clix::marshalString<clix::E_UTF8>(__ret);
} }
void CppSharp::Parser::ParserOptions::addLibraryDirs(System::String^ s) void CppSharp::Parser::ParserOptions::addLibraryDirs(System::String^ s)
{ {
auto _arg0 = clix::marshalString<clix::E_UTF8>(s); auto _arg0 = clix::marshalString<clix::E_UTF8>(s);
auto arg0 = _arg0.c_str(); auto arg0 = _arg0.c_str();
((::CppSharp::CppParser::ParserOptions*)NativePtr)->addLibraryDirs(arg0); ((::CppSharp::CppParser::ParserOptions*)NativePtr)->addLibraryDirs(arg0);
} }
System::IntPtr CppSharp::Parser::ParserOptions::__Instance::get() System::IntPtr CppSharp::Parser::ParserOptions::__Instance::get()
{ {
return System::IntPtr(NativePtr); return System::IntPtr(NativePtr);
} }
void CppSharp::Parser::ParserOptions::__Instance::set(System::IntPtr object) void CppSharp::Parser::ParserOptions::__Instance::set(System::IntPtr object)
{ {
NativePtr = (::CppSharp::CppParser::ParserOptions*)object.ToPointer(); NativePtr = (::CppSharp::CppParser::ParserOptions*)object.ToPointer();
} }
unsigned int CppSharp::Parser::ParserOptions::ArgumentsCount::get() unsigned int CppSharp::Parser::ParserOptions::ArgumentsCount::get()
{ {
auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getArgumentsCount(); auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getArgumentsCount();
return __ret; return __ret;
} }
System::String^ CppSharp::Parser::ParserOptions::FileName::get() System::String^ CppSharp::Parser::ParserOptions::FileName::get()
{ {
auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getFileName(); auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getFileName();
if (__ret == nullptr) return nullptr; if (__ret == nullptr) return nullptr;
return clix::marshalString<clix::E_UTF8>(__ret); return clix::marshalString<clix::E_UTF8>(__ret);
} }
void CppSharp::Parser::ParserOptions::FileName::set(System::String^ s) void CppSharp::Parser::ParserOptions::FileName::set(System::String^ s)
{ {
auto _arg0 = clix::marshalString<clix::E_UTF8>(s); auto _arg0 = clix::marshalString<clix::E_UTF8>(s);
auto arg0 = _arg0.c_str(); auto arg0 = _arg0.c_str();
((::CppSharp::CppParser::ParserOptions*)NativePtr)->setFileName(arg0); ((::CppSharp::CppParser::ParserOptions*)NativePtr)->setFileName(arg0);
} }
unsigned int CppSharp::Parser::ParserOptions::IncludeDirsCount::get() unsigned int CppSharp::Parser::ParserOptions::IncludeDirsCount::get()
{ {
auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getIncludeDirsCount(); auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getIncludeDirsCount();
return __ret; return __ret;
} }
unsigned int CppSharp::Parser::ParserOptions::SystemIncludeDirsCount::get() unsigned int CppSharp::Parser::ParserOptions::SystemIncludeDirsCount::get()
{ {
auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getSystemIncludeDirsCount(); auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getSystemIncludeDirsCount();
return __ret; return __ret;
} }
unsigned int CppSharp::Parser::ParserOptions::DefinesCount::get() unsigned int CppSharp::Parser::ParserOptions::DefinesCount::get()
{ {
auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getDefinesCount(); auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getDefinesCount();
return __ret; return __ret;
} }
unsigned int CppSharp::Parser::ParserOptions::LibraryDirsCount::get() unsigned int CppSharp::Parser::ParserOptions::LibraryDirsCount::get()
{ {
auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getLibraryDirsCount(); auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getLibraryDirsCount();
return __ret; return __ret;
} }
System::String^ CppSharp::Parser::ParserOptions::TargetTriple::get() System::String^ CppSharp::Parser::ParserOptions::TargetTriple::get()
{ {
auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getTargetTriple(); auto __ret = ((::CppSharp::CppParser::ParserOptions*)NativePtr)->getTargetTriple();
if (__ret == nullptr) return nullptr; if (__ret == nullptr) return nullptr;
return clix::marshalString<clix::E_UTF8>(__ret); return clix::marshalString<clix::E_UTF8>(__ret);
} }
void CppSharp::Parser::ParserOptions::TargetTriple::set(System::String^ s) void CppSharp::Parser::ParserOptions::TargetTriple::set(System::String^ s)
{ {
auto _arg0 = clix::marshalString<clix::E_UTF8>(s); auto _arg0 = clix::marshalString<clix::E_UTF8>(s);
auto arg0 = _arg0.c_str(); auto arg0 = _arg0.c_str();
((::CppSharp::CppParser::ParserOptions*)NativePtr)->setTargetTriple(arg0); ((::CppSharp::CppParser::ParserOptions*)NativePtr)->setTargetTriple(arg0);
} }
CppSharp::Parser::AST::ASTContext^ CppSharp::Parser::ParserOptions::ASTContext::get() CppSharp::Parser::AST::ASTContext^ CppSharp::Parser::ParserOptions::ASTContext::get()
{ {
return (((::CppSharp::CppParser::ParserOptions*)NativePtr)->ASTContext == nullptr) ? nullptr : gcnew CppSharp::Parser::AST::ASTContext((::CppSharp::CppParser::AST::ASTContext*)((::CppSharp::CppParser::ParserOptions*)NativePtr)->ASTContext); return (((::CppSharp::CppParser::ParserOptions*)NativePtr)->ASTContext == nullptr) ? nullptr : gcnew CppSharp::Parser::AST::ASTContext((::CppSharp::CppParser::AST::ASTContext*)((::CppSharp::CppParser::ParserOptions*)NativePtr)->ASTContext);
} }
void CppSharp::Parser::ParserOptions::ASTContext::set(CppSharp::Parser::AST::ASTContext^ value) void CppSharp::Parser::ParserOptions::ASTContext::set(CppSharp::Parser::AST::ASTContext^ value)
{ {
((::CppSharp::CppParser::ParserOptions*)NativePtr)->ASTContext = (::CppSharp::CppParser::AST::ASTContext*)value->NativePtr; ((::CppSharp::CppParser::ParserOptions*)NativePtr)->ASTContext = (::CppSharp::CppParser::AST::ASTContext*)value->NativePtr;
} }
int CppSharp::Parser::ParserOptions::ToolSetToUse::get() int CppSharp::Parser::ParserOptions::ToolSetToUse::get()
{ {
return ((::CppSharp::CppParser::ParserOptions*)NativePtr)->ToolSetToUse; return ((::CppSharp::CppParser::ParserOptions*)NativePtr)->ToolSetToUse;
} }
void CppSharp::Parser::ParserOptions::ToolSetToUse::set(int value) void CppSharp::Parser::ParserOptions::ToolSetToUse::set(int value)
{ {
((::CppSharp::CppParser::ParserOptions*)NativePtr)->ToolSetToUse = value; ((::CppSharp::CppParser::ParserOptions*)NativePtr)->ToolSetToUse = value;
} }
CppSharp::Parser::AST::CppAbi CppSharp::Parser::ParserOptions::Abi::get() CppSharp::Parser::AST::CppAbi CppSharp::Parser::ParserOptions::Abi::get()
{ {
return (CppSharp::Parser::AST::CppAbi)((::CppSharp::CppParser::ParserOptions*)NativePtr)->Abi; return (CppSharp::Parser::AST::CppAbi)((::CppSharp::CppParser::ParserOptions*)NativePtr)->Abi;
} }
void CppSharp::Parser::ParserOptions::Abi::set(CppSharp::Parser::AST::CppAbi value) void CppSharp::Parser::ParserOptions::Abi::set(CppSharp::Parser::AST::CppAbi value)
{ {
((::CppSharp::CppParser::ParserOptions*)NativePtr)->Abi = (::CppSharp::CppParser::AST::CppAbi)value; ((::CppSharp::CppParser::ParserOptions*)NativePtr)->Abi = (::CppSharp::CppParser::AST::CppAbi)value;
} }
bool CppSharp::Parser::ParserOptions::NoStandardIncludes::get() bool CppSharp::Parser::ParserOptions::NoStandardIncludes::get()
{ {
return ((::CppSharp::CppParser::ParserOptions*)NativePtr)->NoStandardIncludes; return ((::CppSharp::CppParser::ParserOptions*)NativePtr)->NoStandardIncludes;
} }
void CppSharp::Parser::ParserOptions::NoStandardIncludes::set(bool value) void CppSharp::Parser::ParserOptions::NoStandardIncludes::set(bool value)
{ {
((::CppSharp::CppParser::ParserOptions*)NativePtr)->NoStandardIncludes = value; ((::CppSharp::CppParser::ParserOptions*)NativePtr)->NoStandardIncludes = value;
} }
bool CppSharp::Parser::ParserOptions::NoBuiltinIncludes::get() bool CppSharp::Parser::ParserOptions::NoBuiltinIncludes::get()
{ {
return ((::CppSharp::CppParser::ParserOptions*)NativePtr)->NoBuiltinIncludes; return ((::CppSharp::CppParser::ParserOptions*)NativePtr)->NoBuiltinIncludes;
} }
void CppSharp::Parser::ParserOptions::NoBuiltinIncludes::set(bool value) void CppSharp::Parser::ParserOptions::NoBuiltinIncludes::set(bool value)
{ {
((::CppSharp::CppParser::ParserOptions*)NativePtr)->NoBuiltinIncludes = value; ((::CppSharp::CppParser::ParserOptions*)NativePtr)->NoBuiltinIncludes = value;
} }
bool CppSharp::Parser::ParserOptions::MicrosoftMode::get() bool CppSharp::Parser::ParserOptions::MicrosoftMode::get()
{ {
return ((::CppSharp::CppParser::ParserOptions*)NativePtr)->MicrosoftMode; return ((::CppSharp::CppParser::ParserOptions*)NativePtr)->MicrosoftMode;
} }
void CppSharp::Parser::ParserOptions::MicrosoftMode::set(bool value) void CppSharp::Parser::ParserOptions::MicrosoftMode::set(bool value)
{ {
((::CppSharp::CppParser::ParserOptions*)NativePtr)->MicrosoftMode = value; ((::CppSharp::CppParser::ParserOptions*)NativePtr)->MicrosoftMode = value;
} }
bool CppSharp::Parser::ParserOptions::Verbose::get() bool CppSharp::Parser::ParserOptions::Verbose::get()
{ {
return ((::CppSharp::CppParser::ParserOptions*)NativePtr)->Verbose; return ((::CppSharp::CppParser::ParserOptions*)NativePtr)->Verbose;
} }
void CppSharp::Parser::ParserOptions::Verbose::set(bool value) void CppSharp::Parser::ParserOptions::Verbose::set(bool value)
{ {
((::CppSharp::CppParser::ParserOptions*)NativePtr)->Verbose = value; ((::CppSharp::CppParser::ParserOptions*)NativePtr)->Verbose = value;
} }
CppSharp::Parser::ParserDiagnostic::ParserDiagnostic(::CppSharp::CppParser::ParserDiagnostic* native) CppSharp::Parser::ParserDiagnostic::ParserDiagnostic(::CppSharp::CppParser::ParserDiagnostic* native)
{ {
NativePtr = native; NativePtr = native;
} }
CppSharp::Parser::ParserDiagnostic::ParserDiagnostic(System::IntPtr native) CppSharp::Parser::ParserDiagnostic::ParserDiagnostic(System::IntPtr native)
{ {
auto __native = (::CppSharp::CppParser::ParserDiagnostic*)native.ToPointer(); auto __native = (::CppSharp::CppParser::ParserDiagnostic*)native.ToPointer();
NativePtr = __native; NativePtr = __native;
} }
CppSharp::Parser::ParserDiagnostic::ParserDiagnostic() CppSharp::Parser::ParserDiagnostic::ParserDiagnostic()
{ {
NativePtr = new ::CppSharp::CppParser::ParserDiagnostic(); NativePtr = new ::CppSharp::CppParser::ParserDiagnostic();
} }
System::IntPtr CppSharp::Parser::ParserDiagnostic::__Instance::get() System::IntPtr CppSharp::Parser::ParserDiagnostic::__Instance::get()
{ {
return System::IntPtr(NativePtr); return System::IntPtr(NativePtr);
} }
void CppSharp::Parser::ParserDiagnostic::__Instance::set(System::IntPtr object) void CppSharp::Parser::ParserDiagnostic::__Instance::set(System::IntPtr object)
{ {
NativePtr = (::CppSharp::CppParser::ParserDiagnostic*)object.ToPointer(); NativePtr = (::CppSharp::CppParser::ParserDiagnostic*)object.ToPointer();
} }
System::String^ CppSharp::Parser::ParserDiagnostic::FileName::get() System::String^ CppSharp::Parser::ParserDiagnostic::FileName::get()
{ {
auto __ret = ((::CppSharp::CppParser::ParserDiagnostic*)NativePtr)->getFileName(); auto __ret = ((::CppSharp::CppParser::ParserDiagnostic*)NativePtr)->getFileName();
if (__ret == nullptr) return nullptr; if (__ret == nullptr) return nullptr;
return clix::marshalString<clix::E_UTF8>(__ret); return clix::marshalString<clix::E_UTF8>(__ret);
} }
void CppSharp::Parser::ParserDiagnostic::FileName::set(System::String^ s) void CppSharp::Parser::ParserDiagnostic::FileName::set(System::String^ s)
{ {
auto _arg0 = clix::marshalString<clix::E_UTF8>(s); auto _arg0 = clix::marshalString<clix::E_UTF8>(s);
auto arg0 = _arg0.c_str(); auto arg0 = _arg0.c_str();
((::CppSharp::CppParser::ParserDiagnostic*)NativePtr)->setFileName(arg0); ((::CppSharp::CppParser::ParserDiagnostic*)NativePtr)->setFileName(arg0);
} }
System::String^ CppSharp::Parser::ParserDiagnostic::Message::get() System::String^ CppSharp::Parser::ParserDiagnostic::Message::get()
{ {
auto __ret = ((::CppSharp::CppParser::ParserDiagnostic*)NativePtr)->getMessage(); auto __ret = ((::CppSharp::CppParser::ParserDiagnostic*)NativePtr)->getMessage();
if (__ret == nullptr) return nullptr; if (__ret == nullptr) return nullptr;
return clix::marshalString<clix::E_UTF8>(__ret); return clix::marshalString<clix::E_UTF8>(__ret);
} }
void CppSharp::Parser::ParserDiagnostic::Message::set(System::String^ s) void CppSharp::Parser::ParserDiagnostic::Message::set(System::String^ s)
{ {
auto _arg0 = clix::marshalString<clix::E_UTF8>(s); auto _arg0 = clix::marshalString<clix::E_UTF8>(s);
auto arg0 = _arg0.c_str(); auto arg0 = _arg0.c_str();
((::CppSharp::CppParser::ParserDiagnostic*)NativePtr)->setMessage(arg0); ((::CppSharp::CppParser::ParserDiagnostic*)NativePtr)->setMessage(arg0);
} }
CppSharp::Parser::ParserDiagnosticLevel CppSharp::Parser::ParserDiagnostic::Level::get() CppSharp::Parser::ParserDiagnosticLevel CppSharp::Parser::ParserDiagnostic::Level::get()
{ {
return (CppSharp::Parser::ParserDiagnosticLevel)((::CppSharp::CppParser::ParserDiagnostic*)NativePtr)->Level; return (CppSharp::Parser::ParserDiagnosticLevel)((::CppSharp::CppParser::ParserDiagnostic*)NativePtr)->Level;
} }
void CppSharp::Parser::ParserDiagnostic::Level::set(CppSharp::Parser::ParserDiagnosticLevel value) void CppSharp::Parser::ParserDiagnostic::Level::set(CppSharp::Parser::ParserDiagnosticLevel value)
{ {
((::CppSharp::CppParser::ParserDiagnostic*)NativePtr)->Level = (::CppSharp::CppParser::ParserDiagnosticLevel)value; ((::CppSharp::CppParser::ParserDiagnostic*)NativePtr)->Level = (::CppSharp::CppParser::ParserDiagnosticLevel)value;
} }
int CppSharp::Parser::ParserDiagnostic::LineNumber::get() int CppSharp::Parser::ParserDiagnostic::LineNumber::get()
{ {
return ((::CppSharp::CppParser::ParserDiagnostic*)NativePtr)->LineNumber; return ((::CppSharp::CppParser::ParserDiagnostic*)NativePtr)->LineNumber;
} }
void CppSharp::Parser::ParserDiagnostic::LineNumber::set(int value) void CppSharp::Parser::ParserDiagnostic::LineNumber::set(int value)
{ {
((::CppSharp::CppParser::ParserDiagnostic*)NativePtr)->LineNumber = value; ((::CppSharp::CppParser::ParserDiagnostic*)NativePtr)->LineNumber = value;
} }
int CppSharp::Parser::ParserDiagnostic::ColumnNumber::get() int CppSharp::Parser::ParserDiagnostic::ColumnNumber::get()
{ {
return ((::CppSharp::CppParser::ParserDiagnostic*)NativePtr)->ColumnNumber; return ((::CppSharp::CppParser::ParserDiagnostic*)NativePtr)->ColumnNumber;
} }
void CppSharp::Parser::ParserDiagnostic::ColumnNumber::set(int value) void CppSharp::Parser::ParserDiagnostic::ColumnNumber::set(int value)
{ {
((::CppSharp::CppParser::ParserDiagnostic*)NativePtr)->ColumnNumber = value; ((::CppSharp::CppParser::ParserDiagnostic*)NativePtr)->ColumnNumber = value;
} }
CppSharp::Parser::ParserResult::ParserResult(::CppSharp::CppParser::ParserResult* native) CppSharp::Parser::ParserResult::ParserResult(::CppSharp::CppParser::ParserResult* native)
{ {
NativePtr = native; NativePtr = native;
} }
CppSharp::Parser::ParserResult::ParserResult(System::IntPtr native) CppSharp::Parser::ParserResult::ParserResult(System::IntPtr native)
{ {
auto __native = (::CppSharp::CppParser::ParserResult*)native.ToPointer(); auto __native = (::CppSharp::CppParser::ParserResult*)native.ToPointer();
NativePtr = __native; NativePtr = __native;
} }
CppSharp::Parser::ParserResult::ParserResult() CppSharp::Parser::ParserResult::ParserResult()
{ {
NativePtr = new ::CppSharp::CppParser::ParserResult(); NativePtr = new ::CppSharp::CppParser::ParserResult();
} }
CppSharp::Parser::ParserDiagnostic^ CppSharp::Parser::ParserResult::getDiagnostics(unsigned int i) CppSharp::Parser::ParserDiagnostic^ CppSharp::Parser::ParserResult::getDiagnostics(unsigned int i)
{ {
auto __ret = ((::CppSharp::CppParser::ParserResult*)NativePtr)->getDiagnostics(i); auto __ret = ((::CppSharp::CppParser::ParserResult*)NativePtr)->getDiagnostics(i);
auto ____ret = new ::CppSharp::CppParser::ParserDiagnostic(__ret); auto ____ret = new ::CppSharp::CppParser::ParserDiagnostic(__ret);
return (____ret == nullptr) ? nullptr : gcnew CppSharp::Parser::ParserDiagnostic((::CppSharp::CppParser::ParserDiagnostic*)____ret); return (____ret == nullptr) ? nullptr : gcnew CppSharp::Parser::ParserDiagnostic((::CppSharp::CppParser::ParserDiagnostic*)____ret);
} }
void CppSharp::Parser::ParserResult::addDiagnostics(CppSharp::Parser::ParserDiagnostic^ s) void CppSharp::Parser::ParserResult::addDiagnostics(CppSharp::Parser::ParserDiagnostic^ s)
{ {
auto &arg0 = *(::CppSharp::CppParser::ParserDiagnostic*)s->NativePtr; auto &arg0 = *(::CppSharp::CppParser::ParserDiagnostic*)s->NativePtr;
((::CppSharp::CppParser::ParserResult*)NativePtr)->addDiagnostics(arg0); ((::CppSharp::CppParser::ParserResult*)NativePtr)->addDiagnostics(arg0);
} }
System::IntPtr CppSharp::Parser::ParserResult::__Instance::get() System::IntPtr CppSharp::Parser::ParserResult::__Instance::get()
{ {
return System::IntPtr(NativePtr); return System::IntPtr(NativePtr);
} }
void CppSharp::Parser::ParserResult::__Instance::set(System::IntPtr object) void CppSharp::Parser::ParserResult::__Instance::set(System::IntPtr object)
{ {
NativePtr = (::CppSharp::CppParser::ParserResult*)object.ToPointer(); NativePtr = (::CppSharp::CppParser::ParserResult*)object.ToPointer();
} }
unsigned int CppSharp::Parser::ParserResult::DiagnosticsCount::get() unsigned int CppSharp::Parser::ParserResult::DiagnosticsCount::get()
{ {
auto __ret = ((::CppSharp::CppParser::ParserResult*)NativePtr)->getDiagnosticsCount(); auto __ret = ((::CppSharp::CppParser::ParserResult*)NativePtr)->getDiagnosticsCount();
return __ret; return __ret;
} }
CppSharp::Parser::ParserResultKind CppSharp::Parser::ParserResult::Kind::get() CppSharp::Parser::ParserResultKind CppSharp::Parser::ParserResult::Kind::get()
{ {
return (CppSharp::Parser::ParserResultKind)((::CppSharp::CppParser::ParserResult*)NativePtr)->Kind; return (CppSharp::Parser::ParserResultKind)((::CppSharp::CppParser::ParserResult*)NativePtr)->Kind;
} }
void CppSharp::Parser::ParserResult::Kind::set(CppSharp::Parser::ParserResultKind value) void CppSharp::Parser::ParserResult::Kind::set(CppSharp::Parser::ParserResultKind value)
{ {
((::CppSharp::CppParser::ParserResult*)NativePtr)->Kind = (::CppSharp::CppParser::ParserResultKind)value; ((::CppSharp::CppParser::ParserResult*)NativePtr)->Kind = (::CppSharp::CppParser::ParserResultKind)value;
} }
CppSharp::Parser::AST::ASTContext^ CppSharp::Parser::ParserResult::ASTContext::get() CppSharp::Parser::AST::ASTContext^ CppSharp::Parser::ParserResult::ASTContext::get()
{ {
return (((::CppSharp::CppParser::ParserResult*)NativePtr)->ASTContext == nullptr) ? nullptr : gcnew CppSharp::Parser::AST::ASTContext((::CppSharp::CppParser::AST::ASTContext*)((::CppSharp::CppParser::ParserResult*)NativePtr)->ASTContext); return (((::CppSharp::CppParser::ParserResult*)NativePtr)->ASTContext == nullptr) ? nullptr : gcnew CppSharp::Parser::AST::ASTContext((::CppSharp::CppParser::AST::ASTContext*)((::CppSharp::CppParser::ParserResult*)NativePtr)->ASTContext);
} }
void CppSharp::Parser::ParserResult::ASTContext::set(CppSharp::Parser::AST::ASTContext^ value) void CppSharp::Parser::ParserResult::ASTContext::set(CppSharp::Parser::AST::ASTContext^ value)
{ {
((::CppSharp::CppParser::ParserResult*)NativePtr)->ASTContext = (::CppSharp::CppParser::AST::ASTContext*)value->NativePtr; ((::CppSharp::CppParser::ParserResult*)NativePtr)->ASTContext = (::CppSharp::CppParser::AST::ASTContext*)value->NativePtr;
} }
CppSharp::Parser::AST::NativeLibrary^ CppSharp::Parser::ParserResult::Library::get() CppSharp::Parser::AST::NativeLibrary^ CppSharp::Parser::ParserResult::Library::get()
{ {
return (((::CppSharp::CppParser::ParserResult*)NativePtr)->Library == nullptr) ? nullptr : gcnew CppSharp::Parser::AST::NativeLibrary((::CppSharp::CppParser::AST::NativeLibrary*)((::CppSharp::CppParser::ParserResult*)NativePtr)->Library); return (((::CppSharp::CppParser::ParserResult*)NativePtr)->Library == nullptr) ? nullptr : gcnew CppSharp::Parser::AST::NativeLibrary((::CppSharp::CppParser::AST::NativeLibrary*)((::CppSharp::CppParser::ParserResult*)NativePtr)->Library);
} }
void CppSharp::Parser::ParserResult::Library::set(CppSharp::Parser::AST::NativeLibrary^ value) void CppSharp::Parser::ParserResult::Library::set(CppSharp::Parser::AST::NativeLibrary^ value)
{ {
((::CppSharp::CppParser::ParserResult*)NativePtr)->Library = (::CppSharp::CppParser::AST::NativeLibrary*)value->NativePtr; ((::CppSharp::CppParser::ParserResult*)NativePtr)->Library = (::CppSharp::CppParser::AST::NativeLibrary*)value->NativePtr;
} }
CppSharp::Parser::ClangParser::ClangParser(::CppSharp::CppParser::ClangParser* native) CppSharp::Parser::ClangParser::ClangParser(::CppSharp::CppParser::ClangParser* native)
{ {
NativePtr = native; NativePtr = native;
} }
CppSharp::Parser::ClangParser::ClangParser(System::IntPtr native) CppSharp::Parser::ClangParser::ClangParser(System::IntPtr native)
{ {
auto __native = (::CppSharp::CppParser::ClangParser*)native.ToPointer(); auto __native = (::CppSharp::CppParser::ClangParser*)native.ToPointer();
NativePtr = __native; NativePtr = __native;
} }
CppSharp::Parser::ParserResult^ CppSharp::Parser::ClangParser::ParseHeader(CppSharp::Parser::ParserOptions^ Opts) CppSharp::Parser::ParserResult^ CppSharp::Parser::ClangParser::ParseHeader(CppSharp::Parser::ParserOptions^ Opts)
{ {
auto arg0 = (::CppSharp::CppParser::ParserOptions*)Opts->NativePtr; auto arg0 = (::CppSharp::CppParser::ParserOptions*)Opts->NativePtr;
auto __ret = ::CppSharp::CppParser::ClangParser::ParseHeader(arg0); auto __ret = ::CppSharp::CppParser::ClangParser::ParseHeader(arg0);
if (__ret == nullptr) return nullptr; if (__ret == nullptr) return nullptr;
return (__ret == nullptr) ? nullptr : gcnew CppSharp::Parser::ParserResult((::CppSharp::CppParser::ParserResult*)__ret); return (__ret == nullptr) ? nullptr : gcnew CppSharp::Parser::ParserResult((::CppSharp::CppParser::ParserResult*)__ret);
} }
CppSharp::Parser::ParserResult^ CppSharp::Parser::ClangParser::ParseLibrary(CppSharp::Parser::ParserOptions^ Opts) CppSharp::Parser::ParserResult^ CppSharp::Parser::ClangParser::ParseLibrary(CppSharp::Parser::ParserOptions^ Opts)
{ {
auto arg0 = (::CppSharp::CppParser::ParserOptions*)Opts->NativePtr; auto arg0 = (::CppSharp::CppParser::ParserOptions*)Opts->NativePtr;
auto __ret = ::CppSharp::CppParser::ClangParser::ParseLibrary(arg0); auto __ret = ::CppSharp::CppParser::ClangParser::ParseLibrary(arg0);
if (__ret == nullptr) return nullptr; if (__ret == nullptr) return nullptr;
return (__ret == nullptr) ? nullptr : gcnew CppSharp::Parser::ParserResult((::CppSharp::CppParser::ParserResult*)__ret); return (__ret == nullptr) ? nullptr : gcnew CppSharp::Parser::ParserResult((::CppSharp::CppParser::ParserResult*)__ret);
} }
CppSharp::Parser::ParserTargetInfo^ CppSharp::Parser::ClangParser::GetTargetInfo(CppSharp::Parser::ParserOptions^ Opts) CppSharp::Parser::ParserTargetInfo^ CppSharp::Parser::ClangParser::GetTargetInfo(CppSharp::Parser::ParserOptions^ Opts)
{ {
auto arg0 = (::CppSharp::CppParser::ParserOptions*)Opts->NativePtr; auto arg0 = (::CppSharp::CppParser::ParserOptions*)Opts->NativePtr;
auto __ret = ::CppSharp::CppParser::ClangParser::GetTargetInfo(arg0); auto __ret = ::CppSharp::CppParser::ClangParser::GetTargetInfo(arg0);
if (__ret == nullptr) return nullptr; if (__ret == nullptr) return nullptr;
return (__ret == nullptr) ? nullptr : gcnew CppSharp::Parser::ParserTargetInfo((::CppSharp::CppParser::ParserTargetInfo*)__ret); return (__ret == nullptr) ? nullptr : gcnew CppSharp::Parser::ParserTargetInfo((::CppSharp::CppParser::ParserTargetInfo*)__ret);
} }
CppSharp::Parser::ClangParser::ClangParser() CppSharp::Parser::ClangParser::ClangParser()
{ {
NativePtr = new ::CppSharp::CppParser::ClangParser(); NativePtr = new ::CppSharp::CppParser::ClangParser();
} }
System::IntPtr CppSharp::Parser::ClangParser::__Instance::get() System::IntPtr CppSharp::Parser::ClangParser::__Instance::get()
{ {
return System::IntPtr(NativePtr); return System::IntPtr(NativePtr);
} }
void CppSharp::Parser::ClangParser::__Instance::set(System::IntPtr object) void CppSharp::Parser::ClangParser::__Instance::set(System::IntPtr object)
{ {
NativePtr = (::CppSharp::CppParser::ClangParser*)object.ToPointer(); NativePtr = (::CppSharp::CppParser::ClangParser*)object.ToPointer();
} }

566
src/CppParser/Bindings/CLI/CppParser.h

@ -1,283 +1,283 @@
#pragma once #pragma once
#include "CppSharp.h" #include "CppSharp.h"
#include <CppParser.h> #include <CppParser.h>
namespace CppSharp namespace CppSharp
{ {
namespace Parser namespace Parser
{ {
enum struct ParserDiagnosticLevel; enum struct ParserDiagnosticLevel;
enum struct ParserResultKind; enum struct ParserResultKind;
enum struct SourceLocationKind; enum struct SourceLocationKind;
ref class ClangParser; ref class ClangParser;
ref class Parser; ref class Parser;
ref class ParserDiagnostic; ref class ParserDiagnostic;
ref class ParserOptions; ref class ParserOptions;
ref class ParserResult; ref class ParserResult;
ref class ParserTargetInfo; ref class ParserTargetInfo;
namespace AST namespace AST
{ {
enum struct CppAbi; enum struct CppAbi;
ref class ASTContext; ref class ASTContext;
ref class NativeLibrary; ref class NativeLibrary;
} }
} }
} }
namespace CppSharp namespace CppSharp
{ {
namespace Parser namespace Parser
{ {
public enum struct ParserDiagnosticLevel public enum struct ParserDiagnosticLevel
{ {
Ignored = 0, Ignored = 0,
Note = 1, Note = 1,
Warning = 2, Warning = 2,
Error = 3, Error = 3,
Fatal = 4 Fatal = 4
}; };
public enum struct ParserResultKind public enum struct ParserResultKind
{ {
Success = 0, Success = 0,
Error = 1, Error = 1,
FileNotFound = 2 FileNotFound = 2
}; };
public enum struct SourceLocationKind public enum struct SourceLocationKind
{ {
Invalid = 0, Invalid = 0,
Builtin = 1, Builtin = 1,
CommandLine = 2, CommandLine = 2,
System = 3, System = 3,
User = 4 User = 4
}; };
public ref class ParserOptions : ICppInstance public ref class ParserOptions : ICppInstance
{ {
public: public:
property ::CppSharp::CppParser::ParserOptions* NativePtr; property ::CppSharp::CppParser::ParserOptions* NativePtr;
property System::IntPtr __Instance property System::IntPtr __Instance
{ {
virtual System::IntPtr get(); virtual System::IntPtr get();
virtual void set(System::IntPtr instance); virtual void set(System::IntPtr instance);
} }
ParserOptions(::CppSharp::CppParser::ParserOptions* native); ParserOptions(::CppSharp::CppParser::ParserOptions* native);
ParserOptions(System::IntPtr native); ParserOptions(System::IntPtr native);
ParserOptions(); ParserOptions();
property unsigned int ArgumentsCount property unsigned int ArgumentsCount
{ {
unsigned int get(); unsigned int get();
} }
property System::String^ FileName property System::String^ FileName
{ {
System::String^ get(); System::String^ get();
void set(System::String^); void set(System::String^);
} }
property unsigned int IncludeDirsCount property unsigned int IncludeDirsCount
{ {
unsigned int get(); unsigned int get();
} }
property unsigned int SystemIncludeDirsCount property unsigned int SystemIncludeDirsCount
{ {
unsigned int get(); unsigned int get();
} }
property unsigned int DefinesCount property unsigned int DefinesCount
{ {
unsigned int get(); unsigned int get();
} }
property unsigned int LibraryDirsCount property unsigned int LibraryDirsCount
{ {
unsigned int get(); unsigned int get();
} }
property System::String^ TargetTriple property System::String^ TargetTriple
{ {
System::String^ get(); System::String^ get();
void set(System::String^); void set(System::String^);
} }
property CppSharp::Parser::AST::ASTContext^ ASTContext property CppSharp::Parser::AST::ASTContext^ ASTContext
{ {
CppSharp::Parser::AST::ASTContext^ get(); CppSharp::Parser::AST::ASTContext^ get();
void set(CppSharp::Parser::AST::ASTContext^); void set(CppSharp::Parser::AST::ASTContext^);
} }
property int ToolSetToUse property int ToolSetToUse
{ {
int get(); int get();
void set(int); void set(int);
} }
property CppSharp::Parser::AST::CppAbi Abi property CppSharp::Parser::AST::CppAbi Abi
{ {
CppSharp::Parser::AST::CppAbi get(); CppSharp::Parser::AST::CppAbi get();
void set(CppSharp::Parser::AST::CppAbi); void set(CppSharp::Parser::AST::CppAbi);
} }
property bool NoStandardIncludes property bool NoStandardIncludes
{ {
bool get(); bool get();
void set(bool); void set(bool);
} }
property bool NoBuiltinIncludes property bool NoBuiltinIncludes
{ {
bool get(); bool get();
void set(bool); void set(bool);
} }
property bool MicrosoftMode property bool MicrosoftMode
{ {
bool get(); bool get();
void set(bool); void set(bool);
} }
property bool Verbose property bool Verbose
{ {
bool get(); bool get();
void set(bool); void set(bool);
} }
System::String^ getArguments(unsigned int i); System::String^ getArguments(unsigned int i);
void addArguments(System::String^ s); void addArguments(System::String^ s);
System::String^ getIncludeDirs(unsigned int i); System::String^ getIncludeDirs(unsigned int i);
void addIncludeDirs(System::String^ s); void addIncludeDirs(System::String^ s);
System::String^ getSystemIncludeDirs(unsigned int i); System::String^ getSystemIncludeDirs(unsigned int i);
void addSystemIncludeDirs(System::String^ s); void addSystemIncludeDirs(System::String^ s);
System::String^ getDefines(unsigned int i); System::String^ getDefines(unsigned int i);
void addDefines(System::String^ s); void addDefines(System::String^ s);
System::String^ getLibraryDirs(unsigned int i); System::String^ getLibraryDirs(unsigned int i);
void addLibraryDirs(System::String^ s); void addLibraryDirs(System::String^ s);
}; };
public ref class ParserDiagnostic : ICppInstance public ref class ParserDiagnostic : ICppInstance
{ {
public: public:
property ::CppSharp::CppParser::ParserDiagnostic* NativePtr; property ::CppSharp::CppParser::ParserDiagnostic* NativePtr;
property System::IntPtr __Instance property System::IntPtr __Instance
{ {
virtual System::IntPtr get(); virtual System::IntPtr get();
virtual void set(System::IntPtr instance); virtual void set(System::IntPtr instance);
} }
ParserDiagnostic(::CppSharp::CppParser::ParserDiagnostic* native); ParserDiagnostic(::CppSharp::CppParser::ParserDiagnostic* native);
ParserDiagnostic(System::IntPtr native); ParserDiagnostic(System::IntPtr native);
ParserDiagnostic(); ParserDiagnostic();
property System::String^ FileName property System::String^ FileName
{ {
System::String^ get(); System::String^ get();
void set(System::String^); void set(System::String^);
} }
property System::String^ Message property System::String^ Message
{ {
System::String^ get(); System::String^ get();
void set(System::String^); void set(System::String^);
} }
property CppSharp::Parser::ParserDiagnosticLevel Level property CppSharp::Parser::ParserDiagnosticLevel Level
{ {
CppSharp::Parser::ParserDiagnosticLevel get(); CppSharp::Parser::ParserDiagnosticLevel get();
void set(CppSharp::Parser::ParserDiagnosticLevel); void set(CppSharp::Parser::ParserDiagnosticLevel);
} }
property int LineNumber property int LineNumber
{ {
int get(); int get();
void set(int); void set(int);
} }
property int ColumnNumber property int ColumnNumber
{ {
int get(); int get();
void set(int); void set(int);
} }
}; };
public ref class ParserResult : ICppInstance public ref class ParserResult : ICppInstance
{ {
public: public:
property ::CppSharp::CppParser::ParserResult* NativePtr; property ::CppSharp::CppParser::ParserResult* NativePtr;
property System::IntPtr __Instance property System::IntPtr __Instance
{ {
virtual System::IntPtr get(); virtual System::IntPtr get();
virtual void set(System::IntPtr instance); virtual void set(System::IntPtr instance);
} }
ParserResult(::CppSharp::CppParser::ParserResult* native); ParserResult(::CppSharp::CppParser::ParserResult* native);
ParserResult(System::IntPtr native); ParserResult(System::IntPtr native);
ParserResult(); ParserResult();
property unsigned int DiagnosticsCount property unsigned int DiagnosticsCount
{ {
unsigned int get(); unsigned int get();
} }
property CppSharp::Parser::ParserResultKind Kind property CppSharp::Parser::ParserResultKind Kind
{ {
CppSharp::Parser::ParserResultKind get(); CppSharp::Parser::ParserResultKind get();
void set(CppSharp::Parser::ParserResultKind); void set(CppSharp::Parser::ParserResultKind);
} }
property CppSharp::Parser::AST::ASTContext^ ASTContext property CppSharp::Parser::AST::ASTContext^ ASTContext
{ {
CppSharp::Parser::AST::ASTContext^ get(); CppSharp::Parser::AST::ASTContext^ get();
void set(CppSharp::Parser::AST::ASTContext^); void set(CppSharp::Parser::AST::ASTContext^);
} }
property CppSharp::Parser::AST::NativeLibrary^ Library property CppSharp::Parser::AST::NativeLibrary^ Library
{ {
CppSharp::Parser::AST::NativeLibrary^ get(); CppSharp::Parser::AST::NativeLibrary^ get();
void set(CppSharp::Parser::AST::NativeLibrary^); void set(CppSharp::Parser::AST::NativeLibrary^);
} }
CppSharp::Parser::ParserDiagnostic^ getDiagnostics(unsigned int i); CppSharp::Parser::ParserDiagnostic^ getDiagnostics(unsigned int i);
void addDiagnostics(CppSharp::Parser::ParserDiagnostic^ s); void addDiagnostics(CppSharp::Parser::ParserDiagnostic^ s);
}; };
public ref class ClangParser : ICppInstance public ref class ClangParser : ICppInstance
{ {
public: public:
property ::CppSharp::CppParser::ClangParser* NativePtr; property ::CppSharp::CppParser::ClangParser* NativePtr;
property System::IntPtr __Instance property System::IntPtr __Instance
{ {
virtual System::IntPtr get(); virtual System::IntPtr get();
virtual void set(System::IntPtr instance); virtual void set(System::IntPtr instance);
} }
ClangParser(::CppSharp::CppParser::ClangParser* native); ClangParser(::CppSharp::CppParser::ClangParser* native);
ClangParser(System::IntPtr native); ClangParser(System::IntPtr native);
ClangParser(); ClangParser();
static CppSharp::Parser::ParserResult^ ParseHeader(CppSharp::Parser::ParserOptions^ Opts); static CppSharp::Parser::ParserResult^ ParseHeader(CppSharp::Parser::ParserOptions^ Opts);
static CppSharp::Parser::ParserResult^ ParseLibrary(CppSharp::Parser::ParserOptions^ Opts); static CppSharp::Parser::ParserResult^ ParseLibrary(CppSharp::Parser::ParserOptions^ Opts);
static CppSharp::Parser::ParserTargetInfo^ GetTargetInfo(CppSharp::Parser::ParserOptions^ Opts); static CppSharp::Parser::ParserTargetInfo^ GetTargetInfo(CppSharp::Parser::ParserOptions^ Opts);
}; };
} }
} }

54
src/Generator/AST/Utils.cs

@ -1,15 +1,15 @@
 
using System; using System;
using System.Linq; using System.Linq;
using Mono.Options; using Mono.Options;
namespace CppSharp.AST namespace CppSharp.AST
{ {
public static class ASTUtils public static class ASTUtils
{ {
public static bool CheckIgnoreFunction(Function function, DriverOptions options) public static bool CheckIgnoreFunction(Function function, DriverOptions options)
{ {
if (!function.IsGenerated) return true; if (!function.IsGenerated) return true;
if (function is Method) if (function is Method)
return CheckIgnoreMethod(function as Method, options); return CheckIgnoreMethod(function as Method, options);
@ -19,7 +19,7 @@ namespace CppSharp.AST
public static bool CheckIgnoreMethod(Method method, DriverOptions options) public static bool CheckIgnoreMethod(Method method, DriverOptions options)
{ {
if (!method.IsGenerated) return true; if (!method.IsGenerated) return true;
var isEmptyCtor = method.IsConstructor && method.Parameters.Count == 0; var isEmptyCtor = method.IsConstructor && method.Parameters.Count == 0;
@ -39,24 +39,24 @@ namespace CppSharp.AST
if (method.Access == AccessSpecifier.Private && !method.IsOverride) if (method.Access == AccessSpecifier.Private && !method.IsOverride)
return true; return true;
//Ignore copy constructor if a base class don't has or has a private copy constructor //Ignore copy constructor if a base class don't has or has a private copy constructor
if (method.IsCopyConstructor) if (method.IsCopyConstructor)
{ {
if (!options.GenerateCopyConstructors) if (!options.GenerateCopyConstructors)
return true; return true;
var baseClass = @class; var baseClass = @class;
while (baseClass != null && baseClass.HasBaseClass) while (baseClass != null && baseClass.HasBaseClass)
{ {
baseClass = baseClass.BaseClass; baseClass = baseClass.BaseClass;
var copyConstructor = baseClass.Methods.FirstOrDefault(m => m.IsCopyConstructor); var copyConstructor = baseClass.Methods.FirstOrDefault(m => m.IsCopyConstructor);
if (copyConstructor == null if (copyConstructor == null
|| copyConstructor.Access == AccessSpecifier.Private || copyConstructor.Access == AccessSpecifier.Private
|| !copyConstructor.IsDeclared) || !copyConstructor.IsDeclared)
return true; return true;
} }
} }
return false; return false;
} }
@ -66,8 +66,8 @@ namespace CppSharp.AST
return true; return true;
if (field.Class.IsValueType && field.IsDeclared) if (field.Class.IsValueType && field.IsDeclared)
return false; return false;
return !field.IsGenerated && (!useInternals || !field.IsInternal); return !field.IsGenerated && (!useInternals || !field.IsInternal);
} }
@ -200,7 +200,7 @@ namespace CppSharp.AST
case CXXOperatorKind.Conversion: case CXXOperatorKind.Conversion:
return "implicit operator"; return "implicit operator";
case CXXOperatorKind.ExplicitConversion: case CXXOperatorKind.ExplicitConversion:
return "explicit operator"; return "explicit operator";
} }

72
src/Generator/Driver.cs

@ -71,27 +71,27 @@ namespace CppSharp
for (var i = 0; i < options.LibraryDirs.Count; i++) for (var i = 0; i < options.LibraryDirs.Count; i++)
options.LibraryDirs[i] = Path.GetFullPath(options.LibraryDirs[i]); options.LibraryDirs[i] = Path.GetFullPath(options.LibraryDirs[i]);
if (options.NoGenIncludeDirs != null) if (options.NoGenIncludeDirs != null)
for (var i = 0; i < options.NoGenIncludeDirs.Count; i++) for (var i = 0; i < options.NoGenIncludeDirs.Count; i++)
options.NoGenIncludeDirs[i] = Path.GetFullPath(options.NoGenIncludeDirs[i]); options.NoGenIncludeDirs[i] = Path.GetFullPath(options.NoGenIncludeDirs[i]);
#endif #endif
if (options.NoGenIncludeDirs != null) if (options.NoGenIncludeDirs != null)
foreach (var incDir in options.NoGenIncludeDirs) foreach (var incDir in options.NoGenIncludeDirs)
#if OLD_PARSER #if OLD_PARSER
options.IncludeDirs.Add(incDir); options.IncludeDirs.Add(incDir);
#else #else
options.addIncludeDirs(incDir); options.addIncludeDirs(incDir);
#endif #endif
if (string.IsNullOrWhiteSpace(options.OutputNamespace)) if (string.IsNullOrWhiteSpace(options.OutputNamespace))
options.OutputNamespace = options.LibraryName; options.OutputNamespace = options.LibraryName;
} }
public void Setup() public void Setup()
{ {
ValidateOptions(Options); ValidateOptions(Options);
TypeDatabase.SetupTypeMaps(); TypeDatabase.SetupTypeMaps();
Generator = CreateGeneratorFromKind(Options.GeneratorKind); Generator = CreateGeneratorFromKind(Options.GeneratorKind);
} }
@ -276,9 +276,9 @@ namespace CppSharp
TranslationUnitPasses.AddPass(new FindSymbolsPass()); TranslationUnitPasses.AddPass(new FindSymbolsPass());
TranslationUnitPasses.AddPass(new CheckStaticClass()); TranslationUnitPasses.AddPass(new CheckStaticClass());
TranslationUnitPasses.AddPass(new MoveOperatorToClassPass()); TranslationUnitPasses.AddPass(new MoveOperatorToClassPass());
TranslationUnitPasses.AddPass(new MoveFunctionToClassPass()); TranslationUnitPasses.AddPass(new MoveFunctionToClassPass());
if (Options.GenerateConversionOperators) if (Options.GenerateConversionOperators)
TranslationUnitPasses.AddPass(new ConstructorToConversionOperatorPass()); TranslationUnitPasses.AddPass(new ConstructorToConversionOperatorPass());
TranslationUnitPasses.AddPass(new CheckAmbiguousFunctions()); TranslationUnitPasses.AddPass(new CheckAmbiguousFunctions());
@ -303,12 +303,12 @@ namespace CppSharp
} }
if (Options.GenerateVirtualTables) if (Options.GenerateVirtualTables)
TranslationUnitPasses.AddPass(new CheckVTableComponentsPass()); TranslationUnitPasses.AddPass(new CheckVTableComponentsPass());
if (Options.GenerateProperties) if (Options.GenerateProperties)
TranslationUnitPasses.AddPass(new GetterSetterToPropertyPass()); TranslationUnitPasses.AddPass(new GetterSetterToPropertyPass());
if (Options.GeneratePropertiesAdvanced) if (Options.GeneratePropertiesAdvanced)
TranslationUnitPasses.AddPass(new GetterSetterToPropertyAdvancedPass()); TranslationUnitPasses.AddPass(new GetterSetterToPropertyAdvancedPass());
} }
@ -332,7 +332,7 @@ namespace CppSharp
public void WriteCode(List<GeneratorOutput> outputs) public void WriteCode(List<GeneratorOutput> outputs)
{ {
var outputPath = Path.GetFullPath(Options.OutputDir); var outputPath = Path.GetFullPath(Options.OutputDir);
if (!Directory.Exists(outputPath)) if (!Directory.Exists(outputPath))
Directory.CreateDirectory(outputPath); Directory.CreateDirectory(outputPath);
@ -341,31 +341,31 @@ namespace CppSharp
{ {
var fileBase = output.TranslationUnit.FileNameWithoutExtension; var fileBase = output.TranslationUnit.FileNameWithoutExtension;
if (Options.UseHeaderDirectories) if (Options.UseHeaderDirectories)
{ {
var dir = Path.Combine(outputPath, output.TranslationUnit.FileRelativeDirectory); var dir = Path.Combine(outputPath, output.TranslationUnit.FileRelativeDirectory);
Directory.CreateDirectory(dir); Directory.CreateDirectory(dir);
fileBase = Path.Combine(output.TranslationUnit.FileRelativeDirectory, fileBase); fileBase = Path.Combine(output.TranslationUnit.FileRelativeDirectory, fileBase);
} }
if (Options.GenerateName != null) if (Options.GenerateName != null)
fileBase = Options.GenerateName(output.TranslationUnit); fileBase = Options.GenerateName(output.TranslationUnit);
foreach (var template in output.Templates) foreach (var template in output.Templates)
{ {
var fileRelativePath = string.Format("{0}.{1}", fileBase, template.FileExtension); var fileRelativePath = string.Format("{0}.{1}", fileBase, template.FileExtension);
Diagnostics.EmitMessage("Generated '{0}'", fileRelativePath); Diagnostics.EmitMessage("Generated '{0}'", fileRelativePath);
var file = Path.Combine(outputPath, fileRelativePath); var file = Path.Combine(outputPath, fileRelativePath);
File.WriteAllText(file, template.Generate()); File.WriteAllText(file, template.Generate());
Options.CodeFiles.Add(file); Options.CodeFiles.Add(file);
} }
} }
} }
public void CompileCode() public void CompileCode()
{ {
if (!Options.CompileCode) if (!Options.CompileCode)
return; return;
var assemblyFile = string.IsNullOrEmpty(Options.LibraryName) ? var assemblyFile = string.IsNullOrEmpty(Options.LibraryName) ?

34
src/Generator/Generator.lua

@ -1,17 +1,17 @@
project "CppSharp.Generator" project "CppSharp.Generator"
kind "SharedLib" kind "SharedLib"
language "C#" language "C#"
location "." location "."
SetupManagedProject() SetupManagedProject()
files { "**.cs", "**verbs.txt" } files { "**.cs", "**verbs.txt" }
excludes { "Filter.cs" } excludes { "Filter.cs" }
links { "System", "System.Core", "CppSharp", "CppSharp.AST" } links { "System", "System.Core", "CppSharp", "CppSharp.AST" }
SetupParser() SetupParser()
configuration '**verbs.txt' configuration '**verbs.txt'
buildaction "Embed" buildaction "Embed"

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

@ -1,5 +1,5 @@
using System; using System;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using CppSharp.AST; using CppSharp.AST;
using CppSharp.AST.Extensions; using CppSharp.AST.Extensions;
@ -90,35 +90,35 @@ namespace CppSharp.Generators.CLI
} }
if (pointee.IsPrimitiveType(out primitive)) if (pointee.IsPrimitiveType(out primitive))
{ {
var returnVarName = Context.ReturnVarName; var returnVarName = Context.ReturnVarName;
if (quals.IsConst != Context.ReturnType.Qualifiers.IsConst) if (quals.IsConst != Context.ReturnType.Qualifiers.IsConst)
{ {
var nativeTypePrinter = new CppTypePrinter(Context.Driver.TypeDatabase, false); var nativeTypePrinter = new CppTypePrinter(Context.Driver.TypeDatabase, false);
var constlessPointer = new PointerType() var constlessPointer = new PointerType()
{ {
IsDependent = pointer.IsDependent, IsDependent = pointer.IsDependent,
Modifier = pointer.Modifier, Modifier = pointer.Modifier,
QualifiedPointee = new QualifiedType(Context.ReturnType.Type.GetPointee()) QualifiedPointee = new QualifiedType(Context.ReturnType.Type.GetPointee())
}; };
var nativeConstlessTypeName = constlessPointer.Visit(nativeTypePrinter, new TypeQualifiers()); var nativeConstlessTypeName = constlessPointer.Visit(nativeTypePrinter, new TypeQualifiers());
returnVarName = string.Format("const_cast<{0}>({1})", returnVarName = string.Format("const_cast<{0}>({1})",
nativeConstlessTypeName, Context.ReturnVarName); nativeConstlessTypeName, Context.ReturnVarName);
} }
if (pointer.Pointee is TypedefType) if (pointer.Pointee is TypedefType)
{ {
var desugaredPointer = new PointerType() var desugaredPointer = new PointerType()
{ {
IsDependent = pointer.IsDependent, IsDependent = pointer.IsDependent,
Modifier = pointer.Modifier, Modifier = pointer.Modifier,
QualifiedPointee = new QualifiedType(pointee) QualifiedPointee = new QualifiedType(pointee)
}; };
var nativeTypePrinter = new CppTypePrinter(Context.Driver.TypeDatabase); var nativeTypePrinter = new CppTypePrinter(Context.Driver.TypeDatabase);
var nativeTypeName = desugaredPointer.Visit(nativeTypePrinter, quals); var nativeTypeName = desugaredPointer.Visit(nativeTypePrinter, quals);
Context.Return.Write("reinterpret_cast<{0}>({1})", nativeTypeName, Context.Return.Write("reinterpret_cast<{0}>({1})", nativeTypeName,
returnVarName); returnVarName);
} }
else else
Context.Return.Write(returnVarName); Context.Return.Write(returnVarName);
return true; return true;
} }
@ -165,7 +165,7 @@ namespace CppSharp.Generators.CLI
case PrimitiveType.Int64: case PrimitiveType.Int64:
case PrimitiveType.UInt64: case PrimitiveType.UInt64:
case PrimitiveType.Float: case PrimitiveType.Float:
case PrimitiveType.Double: case PrimitiveType.Double:
case PrimitiveType.Null: case PrimitiveType.Null:
Context.Return.Write(Context.ReturnVarName); Context.Return.Write(Context.ReturnVarName);
return true; return true;
@ -444,15 +444,15 @@ namespace CppSharp.Generators.CLI
var cppTypeName = pointer.Visit(cppTypePrinter, quals); var cppTypeName = pointer.Visit(cppTypePrinter, quals);
return VisitDelegateType(function, cppTypeName); return VisitDelegateType(function, cppTypeName);
} }
Enumeration @enum; Enumeration @enum;
if (pointee.TryGetEnum(out @enum)) if (pointee.TryGetEnum(out @enum))
{ {
ArgumentPrefix.Write("&"); ArgumentPrefix.Write("&");
Context.Return.Write("(::{0})*{1}", @enum.QualifiedOriginalName, Context.Return.Write("(::{0})*{1}", @enum.QualifiedOriginalName,
Context.Parameter.Name); Context.Parameter.Name);
return true; return true;
} }
Class @class; Class @class;
@ -461,9 +461,9 @@ namespace CppSharp.Generators.CLI
if (Context.Function == null) if (Context.Function == null)
Context.Return.Write("&"); Context.Return.Write("&");
return pointee.Visit(this, quals); return pointee.Visit(this, quals);
} }
var finalPointee = pointer.GetFinalPointee(); var finalPointee = pointer.GetFinalPointee();
if (finalPointee.IsPrimitiveType()) if (finalPointee.IsPrimitiveType())
{ {
var cppTypePrinter = new CppTypePrinter(Context.Driver.TypeDatabase); var cppTypePrinter = new CppTypePrinter(Context.Driver.TypeDatabase);
@ -641,7 +641,7 @@ namespace CppSharp.Generators.CLI
{ {
foreach (var @base in @class.Bases.Where(b => b.IsClass && b.Class.IsDeclared)) foreach (var @base in @class.Bases.Where(b => b.IsClass && b.Class.IsDeclared))
{ {
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)))

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

@ -843,7 +843,7 @@ namespace CppSharp.Generators.CLI
CheckArgumentRange(function); CheckArgumentRange(function);
var retType = function.ReturnType; var retType = function.ReturnType;
if (publicRetType == null) if (publicRetType == null)
publicRetType = retType.Type; publicRetType = retType.Type;
var needsReturn = !retType.Type.IsPrimitiveType(PrimitiveType.Void); var needsReturn = !retType.Type.IsPrimitiveType(PrimitiveType.Void);
@ -977,8 +977,8 @@ namespace CppSharp.Generators.CLI
if (retType.Type.IsPointer() && if (retType.Type.IsPointer() &&
retType.Type.GetPointee().Equals(publicRetType) && retType.Type.GetPointee().Equals(publicRetType) &&
publicRetType.IsPrimitiveType()) publicRetType.IsPrimitiveType())
WriteLine("return *({0});", marshal.Context.Return); WriteLine("return *({0});", marshal.Context.Return);
else if (retType.Type.IsReference() && publicRetType.IsReference()) else if (retType.Type.IsReference() && publicRetType.IsReference())
WriteLine("return ({0})({1});", publicRetType, marshal.Context.Return); WriteLine("return ({0})({1});", publicRetType, marshal.Context.Return);
else else
WriteLine("return {0};", marshal.Context.Return); WriteLine("return {0};", marshal.Context.Return);

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

@ -1,398 +1,398 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using CppSharp.AST; using CppSharp.AST;
using CppSharp.AST.Extensions; using CppSharp.AST.Extensions;
using CppSharp.Types; using CppSharp.Types;
using Type = CppSharp.AST.Type; using Type = CppSharp.AST.Type;
namespace CppSharp.Generators.CLI namespace CppSharp.Generators.CLI
{ {
public class CLITypePrinterContext : TypePrinterContext public class CLITypePrinterContext : TypePrinterContext
{ {
public CLITypePrinterContext() public CLITypePrinterContext()
{ {
} }
public CLITypePrinterContext(TypePrinterContextKind kind) public CLITypePrinterContext(TypePrinterContextKind kind)
: base(kind) : base(kind)
{ {
} }
} }
public class CLITypePrinter : ITypePrinter<string>, IDeclVisitor<string> public class CLITypePrinter : ITypePrinter<string>, IDeclVisitor<string>
{ {
public Driver Driver { get; set; } public Driver Driver { get; set; }
public CLITypePrinterContext Context { get; set; } public CLITypePrinterContext Context { get; set; }
readonly ITypeMapDatabase TypeMapDatabase; readonly ITypeMapDatabase TypeMapDatabase;
readonly DriverOptions Options; readonly DriverOptions Options;
public CLITypePrinter(Driver driver) public CLITypePrinter(Driver driver)
{ {
Driver = driver; Driver = driver;
TypeMapDatabase = driver.TypeDatabase; TypeMapDatabase = driver.TypeDatabase;
Options = driver.Options; Options = driver.Options;
Context = new CLITypePrinterContext(); Context = new CLITypePrinterContext();
} }
public CLITypePrinter(Driver driver, CLITypePrinterContext context) public CLITypePrinter(Driver driver, CLITypePrinterContext context)
: this(driver) : this(driver)
{ {
Context = context; Context = context;
} }
public string VisitTagType(TagType tag, TypeQualifiers quals) public string VisitTagType(TagType tag, TypeQualifiers quals)
{ {
TypeMap typeMap = null; TypeMap typeMap = null;
if (TypeMapDatabase.FindTypeMap(tag, out typeMap)) if (TypeMapDatabase.FindTypeMap(tag, out typeMap))
{ {
typeMap.Type = tag; typeMap.Type = tag;
Context.Type = tag; Context.Type = tag;
return typeMap.CLISignature(Context); return typeMap.CLISignature(Context);
} }
Declaration decl = tag.Declaration; Declaration decl = tag.Declaration;
if (decl == null) if (decl == null)
return string.Empty; return string.Empty;
return VisitDeclaration(decl, quals); return VisitDeclaration(decl, quals);
} }
public string VisitArrayType(ArrayType array, TypeQualifiers quals) public string VisitArrayType(ArrayType array, TypeQualifiers quals)
{ {
return string.Format("cli::array<{0}>^", array.Type.Visit(this)); return string.Format("cli::array<{0}>^", array.Type.Visit(this));
} }
public string VisitFunctionType(FunctionType function, TypeQualifiers quals) public string VisitFunctionType(FunctionType function, TypeQualifiers quals)
{ {
var arguments = function.Parameters; var arguments = function.Parameters;
var returnType = function.ReturnType; var returnType = function.ReturnType;
var args = string.Empty; var args = string.Empty;
if (arguments.Count > 0) if (arguments.Count > 0)
args = VisitParameters(function.Parameters, hasNames: false); args = VisitParameters(function.Parameters, hasNames: false);
if (returnType.Type.IsPrimitiveType(PrimitiveType.Void)) if (returnType.Type.IsPrimitiveType(PrimitiveType.Void))
{ {
if (!string.IsNullOrEmpty(args)) if (!string.IsNullOrEmpty(args))
args = string.Format("<{0}>", args); args = string.Format("<{0}>", args);
return string.Format("System::Action{0}", args); return string.Format("System::Action{0}", args);
} }
if (!string.IsNullOrEmpty(args)) if (!string.IsNullOrEmpty(args))
args = string.Format(", {0}", args); args = string.Format(", {0}", args);
return string.Format("System::Func<{0}{1}>", returnType.Visit(this), args); return string.Format("System::Func<{0}{1}>", returnType.Visit(this), args);
} }
public string VisitParameters(IEnumerable<Parameter> @params, public string VisitParameters(IEnumerable<Parameter> @params,
bool hasNames) bool hasNames)
{ {
var args = new List<string>(); var args = new List<string>();
foreach (var param in @params) foreach (var param in @params)
args.Add(VisitParameter(param, hasNames)); args.Add(VisitParameter(param, hasNames));
return string.Join(", ", args); return string.Join(", ", args);
} }
public string VisitParameter(Parameter param, bool hasName = true) public string VisitParameter(Parameter param, bool hasName = true)
{ {
Context.Parameter = param; Context.Parameter = param;
var type = param.Type.Visit(this, param.QualifiedType.Qualifiers); var type = param.Type.Visit(this, param.QualifiedType.Qualifiers);
Context.Parameter = null; Context.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] ";
str += type; str += type;
if(param.Usage == ParameterUsage.Out || if(param.Usage == ParameterUsage.Out ||
param.Usage == ParameterUsage.InOut) param.Usage == ParameterUsage.InOut)
str += "%"; str += "%";
if (hasName && !string.IsNullOrEmpty(param.Name)) if (hasName && !string.IsNullOrEmpty(param.Name))
str += " " + param.Name; str += " " + param.Name;
return str; return str;
} }
public string VisitDelegate(FunctionType function) public string VisitDelegate(FunctionType function)
{ {
return string.Format("delegate {0} {{0}}({1})", return string.Format("delegate {0} {{0}}({1})",
function.ReturnType.Visit(this), function.ReturnType.Visit(this),
VisitParameters(function.Parameters, hasNames: true)); VisitParameters(function.Parameters, hasNames: true));
} }
public string VisitPointerType(PointerType pointer, TypeQualifiers quals) public string VisitPointerType(PointerType pointer, TypeQualifiers quals)
{ {
var pointee = pointer.Pointee.Desugar(); var pointee = pointer.Pointee.Desugar();
if (pointee is FunctionType) if (pointee is FunctionType)
{ {
var function = pointee as FunctionType; var function = pointee as FunctionType;
return string.Format("{0}^", function.Visit(this, quals)); return string.Format("{0}^", function.Visit(this, quals));
} }
if (pointee.IsPrimitiveType(PrimitiveType.Char) && quals.IsConst) if (pointee.IsPrimitiveType(PrimitiveType.Char) && quals.IsConst)
{ {
return "System::String^"; return "System::String^";
} }
// From http://msdn.microsoft.com/en-us/library/y31yhkeb.aspx // From http://msdn.microsoft.com/en-us/library/y31yhkeb.aspx
// Any of the following types may be a pointer type: // Any of the following types may be a pointer type:
// * sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool. // * sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool.
// * Any enum type. // * Any enum type.
// * Any pointer type. // * Any pointer type.
// * Any user-defined struct type that contains fields of unmanaged types only. // * Any user-defined struct type that contains fields of unmanaged types only.
var finalPointee = pointer.GetFinalPointee(); var finalPointee = pointer.GetFinalPointee();
if (finalPointee.IsPrimitiveType()) if (finalPointee.IsPrimitiveType())
{ {
// Skip one indirection if passed by reference // Skip one indirection if passed by reference
var param = Context.Parameter; var param = Context.Parameter;
if (param != null && (param.IsOut || param.IsInOut) if (param != null && (param.IsOut || param.IsInOut)
&& pointee == finalPointee) && pointee == finalPointee)
return pointee.Visit(this, quals); return pointee.Visit(this, quals);
return pointee.Visit(this, quals) + "*"; return pointee.Visit(this, quals) + "*";
} }
Enumeration @enum; Enumeration @enum;
if (pointee.TryGetEnum(out @enum)) if (pointee.TryGetEnum(out @enum))
{ {
var typeName = @enum.Visit(this); var typeName = @enum.Visit(this);
return string.Format("{0}*", typeName); return string.Format("{0}*", typeName);
} }
return pointer.Pointee.Visit(this, quals); return pointer.Pointee.Visit(this, quals);
} }
public string VisitMemberPointerType(MemberPointerType member, public string VisitMemberPointerType(MemberPointerType member,
TypeQualifiers quals) TypeQualifiers quals)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public string VisitBuiltinType(BuiltinType builtin, TypeQualifiers quals) public string VisitBuiltinType(BuiltinType builtin, TypeQualifiers quals)
{ {
return VisitPrimitiveType(builtin.Type); return VisitPrimitiveType(builtin.Type);
} }
public string VisitPrimitiveType(PrimitiveType primitive) public string VisitPrimitiveType(PrimitiveType primitive)
{ {
switch (primitive) switch (primitive)
{ {
case PrimitiveType.Bool: return "bool"; case PrimitiveType.Bool: return "bool";
case PrimitiveType.Void: return "void"; case PrimitiveType.Void: return "void";
case PrimitiveType.Char16: case PrimitiveType.Char16:
case PrimitiveType.WideChar: return "System::Char"; case PrimitiveType.WideChar: return "System::Char";
case PrimitiveType.Int8: return Options.MarshalCharAsManagedChar ? "System::Char" : "char"; case PrimitiveType.Int8: return Options.MarshalCharAsManagedChar ? "System::Char" : "char";
case PrimitiveType.UInt8: return "unsigned char"; case PrimitiveType.UInt8: return "unsigned char";
case PrimitiveType.Int16: return "short"; case PrimitiveType.Int16: return "short";
case PrimitiveType.UInt16: return "unsigned short"; case PrimitiveType.UInt16: return "unsigned short";
case PrimitiveType.Int32: return "int"; case PrimitiveType.Int32: return "int";
case PrimitiveType.UInt32: return "unsigned int"; case PrimitiveType.UInt32: return "unsigned int";
case PrimitiveType.Int64: return "long long"; case PrimitiveType.Int64: return "long long";
case PrimitiveType.UInt64: return "unsigned long long"; case PrimitiveType.UInt64: return "unsigned long long";
case PrimitiveType.Float: return "float"; case PrimitiveType.Float: return "float";
case PrimitiveType.Double: return "double"; case PrimitiveType.Double: return "double";
case PrimitiveType.IntPtr: return "IntPtr"; case PrimitiveType.IntPtr: return "IntPtr";
case PrimitiveType.UIntPtr: return "UIntPtr"; case PrimitiveType.UIntPtr: return "UIntPtr";
case PrimitiveType.Null: return "void*"; case PrimitiveType.Null: return "void*";
} }
throw new NotSupportedException(); throw new NotSupportedException();
} }
public string VisitTypedefType(TypedefType typedef, TypeQualifiers quals) public string VisitTypedefType(TypedefType typedef, TypeQualifiers quals)
{ {
var decl = typedef.Declaration; var decl = typedef.Declaration;
TypeMap typeMap = null; TypeMap typeMap = null;
if (TypeMapDatabase.FindTypeMap(decl, out typeMap)) if (TypeMapDatabase.FindTypeMap(decl, out typeMap))
{ {
typeMap.Type = typedef; typeMap.Type = typedef;
Context.Type = typedef; Context.Type = typedef;
return typeMap.CLISignature(Context); return typeMap.CLISignature(Context);
} }
FunctionType func; FunctionType func;
if (decl.Type.IsPointerTo<FunctionType>(out func)) if (decl.Type.IsPointerTo<FunctionType>(out func))
{ {
// TODO: Use SafeIdentifier() // TODO: Use SafeIdentifier()
return string.Format("{0}^", VisitDeclaration(decl)); return string.Format("{0}^", VisitDeclaration(decl));
} }
return decl.Type.Visit(this); return decl.Type.Visit(this);
} }
public string VisitAttributedType(AttributedType attributed, TypeQualifiers quals) public string VisitAttributedType(AttributedType attributed, TypeQualifiers quals)
{ {
return attributed.Modified.Visit(this); return attributed.Modified.Visit(this);
} }
public string VisitDecayedType(DecayedType decayed, TypeQualifiers quals) public string VisitDecayedType(DecayedType decayed, TypeQualifiers quals)
{ {
return decayed.Decayed.Visit(this); return decayed.Decayed.Visit(this);
} }
public string VisitTemplateSpecializationType(TemplateSpecializationType template, public string VisitTemplateSpecializationType(TemplateSpecializationType template,
TypeQualifiers quals) TypeQualifiers quals)
{ {
var decl = template.Template.TemplatedDecl; var decl = template.Template.TemplatedDecl;
TypeMap typeMap = null; TypeMap typeMap = null;
if (TypeMapDatabase.FindTypeMap(template, out typeMap)) if (TypeMapDatabase.FindTypeMap(template, out typeMap))
{ {
typeMap.Declaration = decl; typeMap.Declaration = decl;
typeMap.Type = template; typeMap.Type = template;
Context.Type = template; Context.Type = template;
return typeMap.CLISignature(Context); return typeMap.CLISignature(Context);
} }
return decl.Name; return decl.Name;
} }
public string VisitTemplateParameterType(TemplateParameterType param, public string VisitTemplateParameterType(TemplateParameterType param,
TypeQualifiers quals) TypeQualifiers quals)
{ {
return param.Parameter.Name; return param.Parameter.Name;
} }
public string VisitTemplateParameterSubstitutionType( public string VisitTemplateParameterSubstitutionType(
TemplateParameterSubstitutionType param, TypeQualifiers quals) TemplateParameterSubstitutionType param, TypeQualifiers quals)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public string VisitInjectedClassNameType(InjectedClassNameType injected, TypeQualifiers quals) public string VisitInjectedClassNameType(InjectedClassNameType injected, TypeQualifiers quals)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public string VisitDependentNameType(DependentNameType dependent, TypeQualifiers quals) public string VisitDependentNameType(DependentNameType dependent, TypeQualifiers quals)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public string VisitPackExpansionType(PackExpansionType packExpansionType, TypeQualifiers quals) public string VisitPackExpansionType(PackExpansionType packExpansionType, TypeQualifiers quals)
{ {
return string.Empty; return string.Empty;
} }
public string VisitCILType(CILType type, TypeQualifiers quals) public string VisitCILType(CILType type, TypeQualifiers quals)
{ {
var result = type.Type.FullName.Replace(".", "::"); var result = type.Type.FullName.Replace(".", "::");
if (!type.Type.IsValueType) if (!type.Type.IsValueType)
result += "^"; result += "^";
return result; return result;
} }
public string VisitPrimitiveType(PrimitiveType type, TypeQualifiers quals) public string VisitPrimitiveType(PrimitiveType type, TypeQualifiers quals)
{ {
return VisitPrimitiveType(type); return VisitPrimitiveType(type);
} }
public string VisitDeclaration(Declaration decl, TypeQualifiers quals) public string VisitDeclaration(Declaration decl, TypeQualifiers quals)
{ {
return VisitDeclaration(decl); return VisitDeclaration(decl);
} }
public string VisitDeclaration(Declaration decl) public string VisitDeclaration(Declaration decl)
{ {
var names = new List<string>(); var names = new List<string>();
if (Options.GenerateLibraryNamespace) if (Options.GenerateLibraryNamespace)
names.Add(Driver.Options.OutputNamespace); names.Add(Driver.Options.OutputNamespace);
if (!string.IsNullOrEmpty(decl.Namespace.QualifiedName)) if (!string.IsNullOrEmpty(decl.Namespace.QualifiedName))
names.Add(decl.Namespace.QualifiedName); names.Add(decl.Namespace.QualifiedName);
names.Add(decl.Visit(this)); names.Add(decl.Visit(this));
return string.Join("::", names); return string.Join("::", names);
} }
public string VisitClassDecl(Class @class) public string VisitClassDecl(Class @class)
{ {
if (@class.CompleteDeclaration != null) if (@class.CompleteDeclaration != null)
return VisitClassDecl(@class.CompleteDeclaration as Class); return VisitClassDecl(@class.CompleteDeclaration as Class);
return string.Format("{0}{1}", @class.Name, @class.IsRefType ? "^" return string.Format("{0}{1}", @class.Name, @class.IsRefType ? "^"
: string.Empty); : string.Empty);
} }
public string VisitFieldDecl(Field field) public string VisitFieldDecl(Field field)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public string VisitFunctionDecl(Function function) public string VisitFunctionDecl(Function function)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public string VisitMethodDecl(Method method) public string VisitMethodDecl(Method method)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public string VisitParameterDecl(Parameter parameter) public string VisitParameterDecl(Parameter parameter)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public string VisitTypedefDecl(TypedefDecl typedef) public string VisitTypedefDecl(TypedefDecl typedef)
{ {
return typedef.Name; return typedef.Name;
} }
public string VisitEnumDecl(Enumeration @enum) public string VisitEnumDecl(Enumeration @enum)
{ {
return @enum.Name; return @enum.Name;
} }
public string VisitVariableDecl(Variable variable) public string VisitVariableDecl(Variable variable)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public string VisitClassTemplateDecl(ClassTemplate template) public string VisitClassTemplateDecl(ClassTemplate template)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public string VisitFunctionTemplateDecl(FunctionTemplate template) public string VisitFunctionTemplateDecl(FunctionTemplate template)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public string VisitMacroDefinition(MacroDefinition macro) public string VisitMacroDefinition(MacroDefinition macro)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public string VisitNamespace(Namespace @namespace) public string VisitNamespace(Namespace @namespace)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public string VisitEvent(Event @event) public string VisitEvent(Event @event)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public string VisitProperty(Property property) public string VisitProperty(Property property)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public string ToString(Type type) public string ToString(Type type)
{ {
return type.Visit(this); return type.Visit(this);
} }
} }
} }

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

@ -1,6 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using CppSharp.AST; using CppSharp.AST;
using CppSharp.AST.Extensions; using CppSharp.AST.Extensions;
using CppSharp.Generators.AST; using CppSharp.Generators.AST;
@ -27,7 +27,7 @@ namespace CppSharp.Generators.CLI
public class CLITypeReferenceCollector : AstVisitor public class CLITypeReferenceCollector : AstVisitor
{ {
private readonly ITypeMapDatabase TypeMapDatabase; private readonly ITypeMapDatabase TypeMapDatabase;
private readonly DriverOptions DriverOptions; private readonly DriverOptions DriverOptions;
private TranslationUnit TranslationUnit; private TranslationUnit TranslationUnit;
private Dictionary<Declaration, CLITypeReference> typeReferences; private Dictionary<Declaration, CLITypeReference> typeReferences;
@ -36,10 +36,10 @@ namespace CppSharp.Generators.CLI
get { return typeReferences.Values; } get { return typeReferences.Values; }
} }
public CLITypeReferenceCollector(ITypeMapDatabase typeMapDatabase, DriverOptions driverOptions) public CLITypeReferenceCollector(ITypeMapDatabase typeMapDatabase, DriverOptions driverOptions)
{ {
TypeMapDatabase = typeMapDatabase; TypeMapDatabase = typeMapDatabase;
DriverOptions = driverOptions; DriverOptions = driverOptions;
typeReferences = new Dictionary<Declaration,CLITypeReference>(); typeReferences = new Dictionary<Declaration,CLITypeReference>();
} }
@ -110,11 +110,11 @@ namespace CppSharp.Generators.CLI
return; return;
} }
var translationUnit = decl.Namespace.TranslationUnit; var translationUnit = decl.Namespace.TranslationUnit;
if (translationUnit.IsSystemHeader)
return;
if (translationUnit.IsSystemHeader)
return;
if (!decl.IsGenerated) if (!decl.IsGenerated)
return; return;
@ -126,32 +126,32 @@ namespace CppSharp.Generators.CLI
{ {
typeRef.Include = new Include typeRef.Include = new Include
{ {
File = GetIncludePath(translationUnit), File = GetIncludePath(translationUnit),
TranslationUnit = translationUnit, TranslationUnit = translationUnit,
Kind = translationUnit.IsGenerated Kind = translationUnit.IsGenerated
? Include.IncludeKind.Quoted ? Include.IncludeKind.Quoted
: Include.IncludeKind.Angled, : Include.IncludeKind.Angled,
}; };
} }
typeRef.Include.InHeader |= IsIncludeInHeader(record); typeRef.Include.InHeader |= IsIncludeInHeader(record);
} }
private string GetIncludePath(TranslationUnit translationUnit) private string GetIncludePath(TranslationUnit translationUnit)
{ {
if (!DriverOptions.UseHeaderDirectories) if (!DriverOptions.UseHeaderDirectories)
return translationUnit.FileName; return translationUnit.FileName;
var rel = PathHelpers.GetRelativePath( var rel = PathHelpers.GetRelativePath(
TranslationUnit.FileRelativeDirectory, TranslationUnit.FileRelativeDirectory,
translationUnit.FileRelativeDirectory); translationUnit.FileRelativeDirectory);
if (string.IsNullOrEmpty(rel)) if (string.IsNullOrEmpty(rel))
return translationUnit.FileName; return translationUnit.FileName;
return Path.Combine(rel, translationUnit.FileName); return Path.Combine(rel, translationUnit.FileName);
} }
private bool IsBuiltinTypedef(Declaration decl) private bool IsBuiltinTypedef(Declaration decl)
{ {
var typedefDecl = decl as TypedefDecl; var typedefDecl = decl as TypedefDecl;

404
src/Generator/Generators/CSharp/CSharpTextTemplate.cs

@ -6,8 +6,8 @@ using System.Linq;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Web.Util; using System.Web.Util;
using CppSharp.AST; using CppSharp.AST;
using CppSharp.AST.Extensions; using CppSharp.AST.Extensions;
using CppSharp.Types; using CppSharp.Types;
using CppSharp.Utils; using CppSharp.Utils;
using Attribute = CppSharp.AST.Attribute; using Attribute = CppSharp.AST.Attribute;
@ -184,7 +184,7 @@ namespace CppSharp.Generators.CSharp
// Generate all the enum declarations. // Generate all the enum declarations.
foreach (var @enum in context.Enums) foreach (var @enum in context.Enums)
{ {
if (!@enum.IsGenerated || @enum.IsIncomplete) if (!@enum.IsGenerated || @enum.IsIncomplete)
continue; continue;
@ -200,7 +200,7 @@ namespace CppSharp.Generators.CSharp
// Generate all the struct/class declarations. // Generate all the struct/class declarations.
foreach (var @class in context.Classes) foreach (var @class in context.Classes)
{ {
if (@class.IsIncomplete) if (@class.IsIncomplete)
continue; continue;
if (@class.IsInterface) if (@class.IsInterface)
@ -222,7 +222,7 @@ namespace CppSharp.Generators.CSharp
// Generate all the internal function declarations. // Generate all the internal function declarations.
foreach (var function in context.Functions) foreach (var function in context.Functions)
{ {
if (!function.IsGenerated && !function.IsInternal ) continue; if (!function.IsGenerated && !function.IsInternal ) continue;
GenerateInternalFunction(function); GenerateInternalFunction(function);
@ -232,7 +232,7 @@ namespace CppSharp.Generators.CSharp
PopBlock(NewLineKind.BeforeNextBlock); PopBlock(NewLineKind.BeforeNextBlock);
foreach (var function in context.Functions) foreach (var function in context.Functions)
{ {
if (!function.IsGenerated) continue; if (!function.IsGenerated) continue;
GenerateFunction(function); GenerateFunction(function);
@ -243,7 +243,7 @@ namespace CppSharp.Generators.CSharp
} }
foreach (var @event in context.Events) foreach (var @event in context.Events)
{ {
if (!@event.IsGenerated) continue; if (!@event.IsGenerated) continue;
GenerateEvent(@event); GenerateEvent(@event);
@ -359,7 +359,7 @@ namespace CppSharp.Generators.CSharp
if (Options.GenerateVirtualTables && @class.IsDynamic) if (Options.GenerateVirtualTables && @class.IsDynamic)
GenerateVTable(@class); GenerateVTable(@class);
} }
exit: exit:
WriteCloseBraceIndent(); WriteCloseBraceIndent();
PopBlock(NewLineKind.BeforeNextBlock); PopBlock(NewLineKind.BeforeNextBlock);
} }
@ -384,7 +384,7 @@ namespace CppSharp.Generators.CSharp
} }
private void GenerateInterface(Class @class) private void GenerateInterface(Class @class)
{ {
if (!@class.IsGenerated || @class.IsIncomplete) if (!@class.IsGenerated || @class.IsIncomplete)
return; return;
@ -413,7 +413,7 @@ namespace CppSharp.Generators.CSharp
WriteLine(");"); WriteLine(");");
PopBlock(NewLineKind.BeforeNextBlock); PopBlock(NewLineKind.BeforeNextBlock);
} }
foreach (var prop in @class.Properties.Where(p => p.IsGenerated)) foreach (var prop in @class.Properties.Where(p => p.IsGenerated))
{ {
PushBlock(CSharpBlockKind.Property); PushBlock(CSharpBlockKind.Property);
@ -454,9 +454,9 @@ namespace CppSharp.Generators.CSharp
var typePrinter = TypePrinter; var typePrinter = TypePrinter;
typePrinter.PushContext(CSharpTypePrinterContextKind.Native); typePrinter.PushContext(CSharpTypePrinterContextKind.Native);
GenerateClassFields(@class, GenerateClassInternalsField, true); GenerateClassFields(@class, GenerateClassInternalsField, true);
if (Options.GenerateVirtualTables && @class.IsDynamic) if (Options.GenerateVirtualTables && @class.IsDynamic)
GenerateVTablePointers(@class); GenerateVTablePointers(@class);
var functions = GatherClassInternalFunctions(@class); var functions = GatherClassInternalFunctions(@class);
@ -486,9 +486,9 @@ namespace CppSharp.Generators.CSharp
functions.Add(method); functions.Add(method);
}; };
foreach (var ctor in @class.Constructors) foreach (var ctor in @class.Constructors)
{ {
if (@class.IsStatic) if (@class.IsStatic)
continue; continue;
if (ctor.IsMoveConstructor) if (ctor.IsMoveConstructor)
@ -579,7 +579,7 @@ namespace CppSharp.Generators.CSharp
private void GenerateStructMarshalingProperties(Class @class) private void GenerateStructMarshalingProperties(Class @class)
{ {
foreach (var @base in @class.Bases) foreach (var @base in @class.Bases)
{ {
if (!@base.IsClass || !@base.Class.IsDeclared) if (!@base.IsClass || !@base.Class.IsDeclared)
continue; continue;
@ -588,7 +588,7 @@ namespace CppSharp.Generators.CSharp
for (int i = 0; i < @class.Properties.Count; i++) for (int i = 0; i < @class.Properties.Count; i++)
{ {
var property = @class.Properties[i]; var property = @class.Properties[i];
if (!property.IsGenerated || property.Field == null) continue; if (!property.IsGenerated || property.Field == null) continue;
var nativeField = string.Format("{0}->{1}", var nativeField = string.Format("{0}->{1}",
@ -630,7 +630,7 @@ namespace CppSharp.Generators.CSharp
private void GenerateStructInternalMarshalingProperties(Class @class, string marshalVar) private void GenerateStructInternalMarshalingProperties(Class @class, string marshalVar)
{ {
foreach (var @base in @class.Bases) foreach (var @base in @class.Bases)
{ {
if (!@base.IsClass || !@base.Class.IsDeclared) if (!@base.IsClass || !@base.Class.IsDeclared)
continue; continue;
@ -639,7 +639,7 @@ namespace CppSharp.Generators.CSharp
} }
foreach (var property in @class.Properties) foreach (var property in @class.Properties)
{ {
if (!property.IsGenerated || property.Field == null) if (!property.IsGenerated || property.Field == null)
continue; continue;
@ -701,8 +701,8 @@ namespace CppSharp.Generators.CSharp
public static bool ShouldGenerateClassNativeField(Class @class) public static bool ShouldGenerateClassNativeField(Class @class)
{ {
if (@class.IsStatic) if (@class.IsStatic)
return false; return false;
return @class.IsRefType && (!@class.HasBase || !HasRefBase(@class)); return @class.IsRefType && (!@class.HasBase || !HasRefBase(@class));
} }
@ -711,26 +711,26 @@ namespace CppSharp.Generators.CSharp
if (@class.IsUnion) if (@class.IsUnion)
WriteLine("[StructLayout(LayoutKind.Explicit)]"); WriteLine("[StructLayout(LayoutKind.Explicit)]");
Write(@class.IsInternal ? "internal " : Helpers.GetAccess(@class.Access)); Write(@class.IsInternal ? "internal " : Helpers.GetAccess(@class.Access));
Write("unsafe "); Write("unsafe ");
if (Driver.Options.GenerateAbstractImpls && @class.IsAbstract) if (Driver.Options.GenerateAbstractImpls && @class.IsAbstract)
Write("abstract "); Write("abstract ");
if (@class.IsStatic) if (@class.IsStatic)
Write("static "); Write("static ");
// This token needs to directly precede the "class" token. // This token needs to directly precede the "class" token.
if (Options.GeneratePartialClasses) if (Options.GeneratePartialClasses)
Write("partial "); Write("partial ");
Write(@class.IsInterface ? "interface " : (@class.IsValueType ? "struct " : "class ")); Write(@class.IsInterface ? "interface " : (@class.IsValueType ? "struct " : "class "));
Write("{0}", @class.Name); Write("{0}", @class.Name);
var bases = new List<string>(); var bases = new List<string>();
var needsBase = @class.HasBaseClass && !@class.IsValueType && @class.IsGenerated var needsBase = @class.HasBaseClass && !@class.IsValueType && @class.IsGenerated
&& !@class.Bases[0].Class.IsValueType && !@class.Bases[0].Class.IsValueType
&& @class.Bases[0].Class.IsGenerated; && @class.Bases[0].Class.IsGenerated;
if (needsBase) if (needsBase)
@ -739,12 +739,12 @@ namespace CppSharp.Generators.CSharp
from @base in @class.Bases from @base in @class.Bases
where @base.IsClass where @base.IsClass
select QualifiedIdentifier(@base.Class)); select QualifiedIdentifier(@base.Class));
} }
if (@class.IsGenerated) if (@class.IsGenerated)
{ {
if (@class.IsRefType) if (@class.IsRefType)
bases.Add("IDisposable"); bases.Add("IDisposable");
if (Options.GenerateClassMarshals) if (Options.GenerateClassMarshals)
{ {
@ -752,37 +752,37 @@ namespace CppSharp.Generators.CSharp
} }
} }
if (bases.Count > 0 && !@class.IsStatic) if (bases.Count > 0 && !@class.IsStatic)
Write(" : {0}", string.Join(", ", bases)); Write(" : {0}", string.Join(", ", bases));
} }
public void GenerateClassFields(Class @class, Action<Field> action, bool nativeFields = false) public void GenerateClassFields(Class @class, Action<Field> action, bool nativeFields = false)
{ {
foreach (var @base in @class.Bases.Where(b => !(b.Type is DependentNameType))) foreach (var @base in @class.Bases.Where(b => !(b.Type is DependentNameType)))
{ {
TypeMap typeMap; TypeMap typeMap;
if ((!Driver.TypeDatabase.FindTypeMap(@base.Type, out typeMap) && !@base.Class.IsDeclared) || if ((!Driver.TypeDatabase.FindTypeMap(@base.Type, out typeMap) && !@base.Class.IsDeclared) ||
@base.Class.OriginalClass == @class) @base.Class.OriginalClass == @class)
continue; continue;
GenerateClassFields(@base.Class, action, nativeFields); GenerateClassFields(@base.Class, action, nativeFields);
} }
foreach (var field in @class.Fields) foreach (var field in @class.Fields)
{ {
if (ASTUtils.CheckIgnoreField(field, nativeFields)) continue; if (ASTUtils.CheckIgnoreField(field, nativeFields)) continue;
action(field); action(field);
} }
} }
private void GenerateClassInternalsField(Field field) private void GenerateClassInternalsField(Field field)
{ {
// we do not support dependent fields yet, see https://github.com/mono/CppSharp/issues/197 // we do not support dependent fields yet, see https://github.com/mono/CppSharp/issues/197
Class @class; Class @class;
if (field.Type.IsDependent && !field.Type.IsPointer() && if (field.Type.IsDependent && !field.Type.IsPointer() &&
!(field.Type.TryGetClass(out @class) && @class.IsUnion)) !(field.Type.TryGetClass(out @class) && @class.IsUnion))
return; return;
var safeIdentifier = Helpers.SafeIdentifier(field.OriginalName); var safeIdentifier = Helpers.SafeIdentifier(field.OriginalName);
PushBlock(CSharpBlockKind.Field); PushBlock(CSharpBlockKind.Field);
@ -797,11 +797,11 @@ namespace CppSharp.Generators.CSharp
if (field.Expression != null) if (field.Expression != null)
{ {
var fieldValuePrinted = field.Expression.CSharpValue(ExpressionPrinter); var fieldValuePrinted = field.Expression.CSharpValue(ExpressionPrinter);
Write("public {0} {1} = {2};", fieldTypePrinted.Type, safeIdentifier, fieldValuePrinted); Write("public {0} {1} = {2};", fieldTypePrinted.Type, safeIdentifier, fieldValuePrinted);
} }
else else
{ {
Write("public {0} {1};", fieldTypePrinted.Type, safeIdentifier); Write("public {0} {1};", fieldTypePrinted.Type, safeIdentifier);
} }
PopBlock(NewLineKind.BeforeNextBlock); PopBlock(NewLineKind.BeforeNextBlock);
@ -974,7 +974,7 @@ namespace CppSharp.Generators.CSharp
private void GenerateIndexerSetter(QualifiedType returnType, Function function) private void GenerateIndexerSetter(QualifiedType returnType, Function function)
{ {
Type type; Type type;
function.Type.IsPointerTo(out type); function.Type.IsPointerTo(out type);
PrimitiveType primitiveType; PrimitiveType primitiveType;
string internalFunction = GetFunctionNativeIdentifier(function); string internalFunction = GetFunctionNativeIdentifier(function);
@ -1120,7 +1120,7 @@ namespace CppSharp.Generators.CSharp
{ {
var staticMethods = new List<Method>(); var staticMethods = new List<Method>();
foreach (var method in @class.Methods) foreach (var method in @class.Methods)
{ {
if (ASTUtils.CheckIgnoreMethod(method, Options)) if (ASTUtils.CheckIgnoreMethod(method, Options))
continue; continue;
@ -1145,7 +1145,7 @@ namespace CppSharp.Generators.CSharp
public void GenerateClassVariables(Class @class) public void GenerateClassVariables(Class @class)
{ {
foreach (var variable in @class.Variables) foreach (var variable in @class.Variables)
{ {
if (!variable.IsGenerated) continue; if (!variable.IsGenerated) continue;
if (variable.Access != AccessSpecifier.Public) if (variable.Access != AccessSpecifier.Public)
@ -1160,7 +1160,7 @@ namespace CppSharp.Generators.CSharp
private void GenerateClassProperties(Class @class) private void GenerateClassProperties(Class @class)
{ {
if (@class.IsValueType) if (@class.IsValueType)
{ {
foreach (var @base in @class.Bases.Where(b => b.IsClass && b.Class.IsDeclared)) foreach (var @base in @class.Bases.Where(b => b.IsClass && b.Class.IsDeclared))
{ {
GenerateClassProperties(@base.Class); GenerateClassProperties(@base.Class);
@ -1171,7 +1171,7 @@ namespace CppSharp.Generators.CSharp
} }
private void GenerateProperties(Class @class) private void GenerateProperties(Class @class)
{ {
foreach (var prop in @class.Properties.Where(p => p.IsGenerated)) foreach (var prop in @class.Properties.Where(p => p.IsGenerated))
{ {
if (prop.IsInRefTypeAndBackedByValueClassField()) if (prop.IsInRefTypeAndBackedByValueClassField())
@ -1225,7 +1225,7 @@ namespace CppSharp.Generators.CSharp
} }
else else
{ {
if (prop.HasGetter) if (prop.HasGetter)
GeneratePropertyGetter(prop.QualifiedType, prop.GetMethod, @class); GeneratePropertyGetter(prop.QualifiedType, prop.GetMethod, @class);
if (prop.HasSetter) if (prop.HasSetter)
@ -1289,8 +1289,8 @@ namespace CppSharp.Generators.CSharp
const string dictionary = "System.Collections.Generic.Dictionary"; const string dictionary = "System.Collections.Generic.Dictionary";
WriteLine("private static void*[] _OldVTables;"); WriteLine("private static void*[] _OldVTables;");
WriteLine("private static void*[] _NewVTables;"); WriteLine("private static void*[] _NewVTables;");
WriteLine("private static void*[] _Thunks;"); WriteLine("private static void*[] _Thunks;");
WriteLine("private static {0}<IntPtr, WeakReference> _References;", dictionary); WriteLine("private static {0}<IntPtr, WeakReference> _References;", dictionary);
NewLine(); NewLine();
@ -1340,7 +1340,7 @@ namespace CppSharp.Generators.CSharp
// Get the _Thunks // Get the _Thunks
WriteLine("if (_Thunks == null)"); WriteLine("if (_Thunks == null)");
WriteStartBraceIndent(); WriteStartBraceIndent();
WriteLine("_Thunks = new void*[{0}];", wrappedEntries.Count); WriteLine("_Thunks = new void*[{0}];", wrappedEntries.Count);
var uniqueEntries = new HashSet<VTableComponent>(); var uniqueEntries = new HashSet<VTableComponent>();
@ -1379,24 +1379,24 @@ namespace CppSharp.Generators.CSharp
} }
private void SaveOriginalVTablePointersMS(Class @class) private void SaveOriginalVTablePointersMS(Class @class)
{ {
WriteLine("_OldVTables = new void*[{0}];", @class.Layout.VFTables.Count); WriteLine("_OldVTables = new void*[{0}];", @class.Layout.VFTables.Count);
for (int i = 0; i < @class.Layout.VFTables.Count; i++) for (int i = 0; i < @class.Layout.VFTables.Count; i++)
{ {
WriteLine("_OldVTables[{0}] = native->vfptr{0}.ToPointer();", i); WriteLine("_OldVTables[{0}] = native->vfptr{0}.ToPointer();", i);
} }
} }
private void SaveOriginalVTablePointersItanium() private void SaveOriginalVTablePointersItanium()
{ {
WriteLine("_OldVTables = new void*[1];"); WriteLine("_OldVTables = new void*[1];");
WriteLine("_OldVTables[0] = native->vfptr0.ToPointer();"); WriteLine("_OldVTables[0] = native->vfptr0.ToPointer();");
} }
private void AllocateNewVTablesMS(Class @class) private void AllocateNewVTablesMS(Class @class)
{ {
WriteLine("_NewVTables = new void*[{0}];", @class.Layout.VFTables.Count); WriteLine("_NewVTables = new void*[{0}];", @class.Layout.VFTables.Count);
for (int tableIndex = 0; tableIndex < @class.Layout.VFTables.Count; tableIndex++) for (int tableIndex = 0; tableIndex < @class.Layout.VFTables.Count; tableIndex++)
@ -1412,10 +1412,10 @@ namespace CppSharp.Generators.CSharp
var entry = vfptr.Layout.Components[entryIndex]; var entry = vfptr.Layout.Components[entryIndex];
var offsetInBytes = VTables.GetVTableComponentIndex(@class, entry) var offsetInBytes = VTables.GetVTableComponentIndex(@class, entry)
* (Driver.Options.Is32Bit ? 4 : 8); * (Driver.Options.Is32Bit ? 4 : 8);
if (entry.Ignore) if (entry.Ignore)
WriteLine("*(void**)(vfptr{0} + {1}) = *(void**)(native->vfptr{0} + {1});", WriteLine("*(void**)(vfptr{0} + {1}) = *(void**)(native->vfptr{0} + {1});",
tableIndex, offsetInBytes); tableIndex, offsetInBytes);
else else
WriteLine("*(void**)(vfptr{0} + {1}) = _Thunks[{2}];", tableIndex, WriteLine("*(void**)(vfptr{0} + {1}) = _Thunks[{2}];", tableIndex,
offsetInBytes, entryIndex); offsetInBytes, entryIndex);
} }
@ -1424,7 +1424,7 @@ namespace CppSharp.Generators.CSharp
WriteCloseBraceIndent(); WriteCloseBraceIndent();
NewLine(); NewLine();
for (var i = 0; i < @class.Layout.VFTables.Count; i++) for (var i = 0; i < @class.Layout.VFTables.Count; i++)
WriteLine("native->vfptr{0} = new IntPtr(_NewVTables[{0}]);", i); WriteLine("native->vfptr{0} = new IntPtr(_NewVTables[{0}]);", i);
} }
@ -1434,7 +1434,7 @@ namespace CppSharp.Generators.CSharp
// reserve space for the offset-to-top and RTTI pointers as well // reserve space for the offset-to-top and RTTI pointers as well
var size = entries.Count; var size = entries.Count;
WriteLine("var vfptr{0} = Marshal.AllocHGlobal({1} * {2});", 0, size, Driver.Options.Is32Bit ? 4 : 8); WriteLine("var vfptr{0} = Marshal.AllocHGlobal({1} * {2});", 0, size, Driver.Options.Is32Bit ? 4 : 8);
WriteLine("_NewVTables[0] = vfptr0.ToPointer();"); WriteLine("_NewVTables[0] = vfptr0.ToPointer();");
for (int i = 0; i < entries.Count; i++) for (int i = 0; i < entries.Count; i++)
@ -1442,15 +1442,15 @@ namespace CppSharp.Generators.CSharp
var entry = entries[i]; var entry = entries[i];
var offsetInBytes = VTables.GetVTableComponentIndex(@class, entry) var offsetInBytes = VTables.GetVTableComponentIndex(@class, entry)
* (Driver.Options.Is32Bit ? 4 : 8); * (Driver.Options.Is32Bit ? 4 : 8);
if (entry.Ignore) if (entry.Ignore)
WriteLine("*(void**)(vfptr0 + {0}) = *(void**)(native->vfptr0 + {0});", offsetInBytes); WriteLine("*(void**)(vfptr0 + {0}) = *(void**)(native->vfptr0 + {0});", offsetInBytes);
else else
WriteLine("*(void**)(vfptr0 + {0}) = _Thunks[{1}];", offsetInBytes, i); WriteLine("*(void**)(vfptr0 + {0}) = _Thunks[{1}];", offsetInBytes, i);
} }
WriteCloseBraceIndent(); WriteCloseBraceIndent();
NewLine(); NewLine();
WriteLine("native->vfptr0 = new IntPtr(_NewVTables[0]);"); WriteLine("native->vfptr0 = new IntPtr(_NewVTables[0]);");
} }
@ -1483,7 +1483,7 @@ namespace CppSharp.Generators.CSharp
var marshals = new List<string>(); var marshals = new List<string>();
for (int i = 0; i < method.Parameters.Count; i++) for (int i = 0; i < method.Parameters.Count; i++)
{ {
var param = method.Parameters[i]; var param = method.Parameters[i];
if (!param.IsGenerated) if (!param.IsGenerated)
continue; continue;
@ -1566,16 +1566,16 @@ namespace CppSharp.Generators.CSharp
private void GenerateVTableMethodDelegates(Class @class, Method method) private void GenerateVTableMethodDelegates(Class @class, Method method)
{ {
PushBlock(CSharpBlockKind.VTableDelegate); PushBlock(CSharpBlockKind.VTableDelegate);
// This works around a parser bug, see https://github.com/mono/CppSharp/issues/202 // This works around a parser bug, see https://github.com/mono/CppSharp/issues/202
if (method.Signature != null) if (method.Signature != null)
{ {
var cleanSig = method.Signature.ReplaceLineBreaks(""); var cleanSig = method.Signature.ReplaceLineBreaks("");
cleanSig = Regex.Replace(cleanSig, @"\s+", " "); cleanSig = Regex.Replace(cleanSig, @"\s+", " ");
WriteLine("// {0}", cleanSig); WriteLine("// {0}", cleanSig);
} }
WriteLine("[SuppressUnmanagedCodeSecurity]"); WriteLine("[SuppressUnmanagedCodeSecurity]");
WriteLine("[UnmanagedFunctionPointerAttribute(global::System.Runtime.InteropServices.CallingConvention.{0})]", WriteLine("[UnmanagedFunctionPointerAttribute(global::System.Runtime.InteropServices.CallingConvention.{0})]",
method.CallingConvention.ToInteropCallConv()); method.CallingConvention.ToInteropCallConv());
@ -1759,14 +1759,14 @@ namespace CppSharp.Generators.CSharp
public void GenerateClassConstructors(Class @class) public void GenerateClassConstructors(Class @class)
{ {
if (@class.IsStatic) if (@class.IsStatic)
return; return;
// Output a default constructor that takes the native pointer. // Output a default constructor that takes the native pointer.
GenerateNativeConstructor(@class); GenerateNativeConstructor(@class);
foreach (var ctor in @class.Constructors) foreach (var ctor in @class.Constructors)
{ {
if (ASTUtils.CheckIgnoreMethod(ctor, Options)) if (ASTUtils.CheckIgnoreMethod(ctor, Options))
continue; continue;
@ -1929,8 +1929,8 @@ namespace CppSharp.Generators.CSharp
} }
private bool GenerateClassConstructorBase(Class @class, Method method) private bool GenerateClassConstructorBase(Class @class, Method method)
{ {
var hasBase = @class.HasBaseClass; var hasBase = @class.HasBaseClass;
if (hasBase && !@class.IsValueType) if (hasBase && !@class.IsValueType)
{ {
@ -2072,23 +2072,23 @@ namespace CppSharp.Generators.CSharp
WriteCloseBraceIndent(); WriteCloseBraceIndent();
PopBlock(NewLineKind.BeforeNextBlock); PopBlock(NewLineKind.BeforeNextBlock);
} }
private void CheckArgumentRange(Function method) private void CheckArgumentRange(Function method)
{ {
if (Driver.Options.MarshalCharAsManagedChar) if (Driver.Options.MarshalCharAsManagedChar)
{ {
foreach (var param in method.Parameters.Where( foreach (var param in method.Parameters.Where(
p => p.Type.IsPrimitiveType(PrimitiveType.Int8))) p => p.Type.IsPrimitiveType(PrimitiveType.Int8)))
{ {
WriteLine("if ({0} < char.MinValue || {0} > sbyte.MaxValue)", param.Name); WriteLine("if ({0} < char.MinValue || {0} > sbyte.MaxValue)", param.Name);
WriteLineIndent( WriteLineIndent(
"throw new global::System.ArgumentException(\"{0} must be in the range {1} - {2}.\");", "throw new global::System.ArgumentException(\"{0} must be in the range {1} - {2}.\");",
param.Name, (int) char.MinValue, sbyte.MaxValue); param.Name, (int) char.MinValue, sbyte.MaxValue);
} }
} }
} }
private static AccessSpecifier GetValidMethodAccess(Method method) private static AccessSpecifier GetValidMethodAccess(Method method)
{ {
switch (method.Access) switch (method.Access)
@ -2130,24 +2130,24 @@ namespace CppSharp.Generators.CSharp
private void GenerateOperator(Method method, Class @class) private void GenerateOperator(Method method, Class @class)
{ {
if (method.IsSynthetized) if (method.IsSynthetized)
{ {
if (method.Kind == CXXMethodKind.Conversion) if (method.Kind == CXXMethodKind.Conversion)
{ {
// To avoid ambiguity when having the multiple inheritance pass enabled // To avoid ambiguity when having the multiple inheritance pass enabled
var @interface = @class.Namespace.Classes.Find(c => c.OriginalClass == @class); var @interface = @class.Namespace.Classes.Find(c => c.OriginalClass == @class);
if (@interface != null) if (@interface != null)
WriteLine("return new {0}(({2}){1});", method.ConversionType, WriteLine("return new {0}(({2}){1});", method.ConversionType,
method.Parameters[0].Name, @interface.Name); method.Parameters[0].Name, @interface.Name);
else else
WriteLine("return new {0}({1});", method.ConversionType, WriteLine("return new {0}({1});", method.ConversionType,
method.Parameters[0].Name); method.Parameters[0].Name);
} }
else else
{ {
var @operator = Operators.GetOperatorOverloadPair(method.OperatorKind); var @operator = Operators.GetOperatorOverloadPair(method.OperatorKind);
WriteLine("return !({0} {1} {2});", method.Parameters[0].Name, WriteLine("return !({0} {1} {2});", method.Parameters[0].Name,
@operator, method.Parameters[1].Name); @operator, method.Parameters[1].Name);
} }
return; return;
} }
@ -2177,7 +2177,7 @@ namespace CppSharp.Generators.CSharp
GenerateVTableClassSetupCall(@class); GenerateVTableClassSetupCall(@class);
} }
public void GenerateInternalFunctionCall(Function function, public void GenerateInternalFunctionCall(Function function,
List<Parameter> parameters = null, Type returnType = null) List<Parameter> parameters = null, Type returnType = null)
{ {
if (parameters == null) if (parameters == null)
@ -2189,7 +2189,7 @@ namespace CppSharp.Generators.CSharp
GenerateFunctionCall(functionName, parameters, function, returnType); GenerateFunctionCall(functionName, parameters, function, returnType);
} }
public void GenerateFunctionCall(string functionName, List<Parameter> parameters, public void GenerateFunctionCall(string functionName, List<Parameter> parameters,
Function function, Type returnType = null) Function function, Type returnType = null)
{ {
if (function.IsPure) if (function.IsPure)
@ -2198,8 +2198,8 @@ namespace CppSharp.Generators.CSharp
return; return;
} }
var retType = function.OriginalReturnType; var retType = function.OriginalReturnType;
if (returnType == null) if (returnType == null)
returnType = retType.Type; returnType = retType.Type;
var needsReturn = !retType.Type.IsPrimitiveType(PrimitiveType.Void); var needsReturn = !retType.Type.IsPrimitiveType(PrimitiveType.Void);
@ -2220,12 +2220,12 @@ namespace CppSharp.Generators.CSharp
var @params = GenerateFunctionParamsMarshal(parameters, function); var @params = GenerateFunctionParamsMarshal(parameters, function);
var originalFunction = function.OriginalFunction ?? function; var originalFunction = function.OriginalFunction ?? function;
if (originalFunction.HasIndirectReturnTypeParameter) if (originalFunction.HasIndirectReturnTypeParameter)
{ {
var indirectRetType = originalFunction.Parameters.First( var indirectRetType = originalFunction.Parameters.First(
parameter => parameter.Kind == ParameterKind.IndirectReturnType); parameter => parameter.Kind == ParameterKind.IndirectReturnType);
Class retClass; Class retClass;
indirectRetType.Type.Desugar().TryGetClass(out retClass); indirectRetType.Type.Desugar().TryGetClass(out retClass);
@ -2247,37 +2247,37 @@ namespace CppSharp.Generators.CSharp
name += param.Name; name += param.Name;
names.Add(name); names.Add(name);
} }
var needsFixedThis = needsInstance && isValueType; var needsFixedThis = needsInstance && isValueType;
if (originalFunction.HasIndirectReturnTypeParameter) if (originalFunction.HasIndirectReturnTypeParameter)
{ {
var name = string.Format("new IntPtr(&{0})", GeneratedIdentifier("ret")); var name = string.Format("new IntPtr(&{0})", GeneratedIdentifier("ret"));
names.Insert(0, name); names.Insert(0, name);
} }
if (needsInstance) if (needsInstance)
{ {
var instanceIndex = GetInstanceParamIndex(function); var instanceIndex = GetInstanceParamIndex(function);
if (needsFixedThis) if (needsFixedThis)
{ {
names.Insert(instanceIndex, string.Format("new global::System.IntPtr(&{0})", names.Insert(instanceIndex, string.Format("new global::System.IntPtr(&{0})",
GeneratedIdentifier("fixedInstance"))); GeneratedIdentifier("fixedInstance")));
} }
else else
{ {
if (operatorParam != null) if (operatorParam != null)
{ {
names.Insert(instanceIndex, operatorParam.Name + "." + Helpers.InstanceIdentifier); names.Insert(instanceIndex, operatorParam.Name + "." + Helpers.InstanceIdentifier);
} }
else else
{ {
names.Insert(instanceIndex, Helpers.InstanceIdentifier); names.Insert(instanceIndex, Helpers.InstanceIdentifier);
} }
} }
} }
if (needsFixedThis) if (needsFixedThis)
{ {
@ -2359,31 +2359,31 @@ namespace CppSharp.Generators.CSharp
if (!string.IsNullOrWhiteSpace(marshal.Context.SupportBefore)) if (!string.IsNullOrWhiteSpace(marshal.Context.SupportBefore))
Write(marshal.Context.SupportBefore); Write(marshal.Context.SupportBefore);
// Special case for indexer - needs to dereference if the internal // Special case for indexer - needs to dereference if the internal
// function is a pointer type and the property is not. // function is a pointer type and the property is not.
if (retType.Type.IsAddress() && if (retType.Type.IsAddress() &&
retType.Type.GetPointee().Equals(returnType) && retType.Type.GetPointee().Equals(returnType) &&
returnType.IsPrimitiveType()) returnType.IsPrimitiveType())
WriteLine("return *{0};", marshal.Context.Return); WriteLine("return *{0};", marshal.Context.Return);
else else
WriteLine("return {0};", marshal.Context.Return); WriteLine("return {0};", marshal.Context.Return);
} }
} }
private int GetInstanceParamIndex(Function function) private int GetInstanceParamIndex(Function function)
{ {
var method = function as Method; var method = function as Method;
if (Options.IsMicrosoftAbi) if (Options.IsMicrosoftAbi)
return 0; return 0;
var indirectReturnType = method.Parameters.FirstOrDefault( var indirectReturnType = method.Parameters.FirstOrDefault(
parameter => parameter.Kind == ParameterKind.IndirectReturnType); parameter => parameter.Kind == ParameterKind.IndirectReturnType);
var indirectReturnTypeIndex = method.Parameters.IndexOf(indirectReturnType); var indirectReturnTypeIndex = method.Parameters.IndexOf(indirectReturnType);
return indirectReturnTypeIndex >= 0 ? ++indirectReturnTypeIndex : 0; return indirectReturnTypeIndex >= 0 ? ++indirectReturnTypeIndex : 0;
} }
private void GenerateFunctionCallOutParams(IEnumerable<ParamMarshal> @params, private void GenerateFunctionCallOutParams(IEnumerable<ParamMarshal> @params,
ICollection<TextGenerator> cleanups) ICollection<TextGenerator> cleanups)
{ {
@ -2522,7 +2522,7 @@ namespace CppSharp.Generators.CSharp
#endregion #endregion
public bool GenerateTypedef(TypedefDecl typedef) public bool GenerateTypedef(TypedefDecl typedef)
{ {
if (!typedef.IsGenerated) if (!typedef.IsGenerated)
return false; return false;
@ -2540,17 +2540,17 @@ namespace CppSharp.Generators.CSharp
} }
else if (typedef.Type.IsPointerTo(out functionType)) else if (typedef.Type.IsPointerTo(out functionType))
{ {
PushBlock(CSharpBlockKind.Typedef); PushBlock(CSharpBlockKind.Typedef);
var attributedType = typedef.Type.GetPointee() as AttributedType; var attributedType = typedef.Type.GetPointee() as AttributedType;
if (attributedType != null) if (attributedType != null)
{ {
var equivalentFunctionType = attributedType.Equivalent.Type as FunctionType; var equivalentFunctionType = attributedType.Equivalent.Type as FunctionType;
var callingConvention = equivalentFunctionType.CallingConvention.ToInteropCallConv(); var callingConvention = equivalentFunctionType.CallingConvention.ToInteropCallConv();
if (callingConvention != System.Runtime.InteropServices.CallingConvention.Winapi) if (callingConvention != System.Runtime.InteropServices.CallingConvention.Winapi)
{ {
WriteLine("[UnmanagedFunctionPointerAttribute(global::System.Runtime.InteropServices.CallingConvention.{0})]", WriteLine("[UnmanagedFunctionPointerAttribute(global::System.Runtime.InteropServices.CallingConvention.{0})]",
callingConvention); callingConvention);
} }
} }
TypePrinter.PushContext(CSharpTypePrinterContextKind.Native); TypePrinter.PushContext(CSharpTypePrinterContextKind.Native);
WriteLine("{0}unsafe {1};", WriteLine("{0}unsafe {1};",
@ -2565,7 +2565,7 @@ namespace CppSharp.Generators.CSharp
} }
public void GenerateEnum(Enumeration @enum) public void GenerateEnum(Enumeration @enum)
{ {
if (!@enum.IsGenerated) return; if (!@enum.IsGenerated) return;
PushBlock(CSharpBlockKind.Enum); PushBlock(CSharpBlockKind.Enum);
@ -2631,7 +2631,7 @@ namespace CppSharp.Generators.CSharp
if (method.IsConstructor && !method.IsCopyConstructor) if (method.IsConstructor && !method.IsCopyConstructor)
functionName = "ctor"; functionName = "ctor";
else if (method.IsCopyConstructor) else if (method.IsCopyConstructor)
functionName = "cctor"; functionName = "cctor";
else if (method.IsDestructor) else if (method.IsDestructor)
functionName = "dtor"; functionName = "dtor";
else else
@ -2649,7 +2649,7 @@ namespace CppSharp.Generators.CSharp
if (index >= 0) if (index >= 0)
identifier += "_" + index.ToString(CultureInfo.InvariantCulture); identifier += "_" + index.ToString(CultureInfo.InvariantCulture);
else if (function.Index.HasValue) else if (function.Index.HasValue)
identifier += "_" + function.Index.Value; identifier += "_" + function.Index.Value;
return identifier; return identifier;
@ -2685,8 +2685,8 @@ namespace CppSharp.Generators.CSharp
if (Options.GenerateInternalImports) if (Options.GenerateInternalImports)
libName = "__Internal"; libName = "__Internal";
Write("[DllImport(\"{0}\", ", libName); Write("[DllImport(\"{0}\", ", libName);
var callConv = function.CallingConvention.ToInteropCallConv(); var callConv = function.CallingConvention.ToInteropCallConv();
WriteLine("CallingConvention = global::System.Runtime.InteropServices.CallingConvention.{0},", WriteLine("CallingConvention = global::System.Runtime.InteropServices.CallingConvention.{0},",
callConv); callConv);
@ -2705,20 +2705,20 @@ namespace CppSharp.Generators.CSharp
var retType = retParam.CSharpType(typePrinter); var retType = retParam.CSharpType(typePrinter);
var method = function as Method; var method = function as Method;
var isInstanceMethod = method != null && !method.IsStatic; var isInstanceMethod = method != null && !method.IsStatic;
if (isInstanceMethod && Options.IsMicrosoftAbi) if (isInstanceMethod && Options.IsMicrosoftAbi)
{ {
@params.Add("global::System.IntPtr instance"); @params.Add("global::System.IntPtr instance");
if (method.IsConstructor) if (method.IsConstructor)
retType = "global::System.IntPtr"; retType = "global::System.IntPtr";
} }
if (!function.HasIndirectReturnTypeParameter && if (!function.HasIndirectReturnTypeParameter &&
isInstanceMethod && Options.IsItaniumAbi) isInstanceMethod && Options.IsItaniumAbi)
@params.Add("global::System.IntPtr instance"); @params.Add("global::System.IntPtr instance");
foreach (var param in function.Parameters) foreach (var param in function.Parameters)
{ {
if (param.Kind == ParameterKind.OperatorParameter) if (param.Kind == ParameterKind.OperatorParameter)
@ -2727,12 +2727,12 @@ namespace CppSharp.Generators.CSharp
var typeName = param.CSharpType(typePrinter); var typeName = param.CSharpType(typePrinter);
@params.Add(string.Format("{0} {1}", typeName, param.Name)); @params.Add(string.Format("{0} {1}", typeName, param.Name));
if (param.Kind == ParameterKind.IndirectReturnType && if (param.Kind == ParameterKind.IndirectReturnType &&
isInstanceMethod && Options.IsItaniumAbi) isInstanceMethod && Options.IsItaniumAbi)
@params.Add("global::System.IntPtr instance"); @params.Add("global::System.IntPtr instance");
} }
if (method != null && method.IsConstructor) if (method != null && method.IsConstructor)
{ {
var @class = method.Namespace as Class; var @class = method.Namespace as Class;

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

File diff suppressed because it is too large Load Diff

54
src/Generator/Generators/ExtensionMethods.cs

@ -1,27 +1,27 @@
using CppSharp.AST; using CppSharp.AST;
using Interop = System.Runtime.InteropServices; using Interop = System.Runtime.InteropServices;
namespace CppSharp.Generators namespace CppSharp.Generators
{ {
public static class ExtensionMethods public static class ExtensionMethods
{ {
public static Interop.CallingConvention ToInteropCallConv(this CallingConvention convention) public static Interop.CallingConvention ToInteropCallConv(this CallingConvention convention)
{ {
switch (convention) switch (convention)
{ {
case CallingConvention.Default: case CallingConvention.Default:
return Interop.CallingConvention.Winapi; return Interop.CallingConvention.Winapi;
case CallingConvention.C: case CallingConvention.C:
return Interop.CallingConvention.Cdecl; return Interop.CallingConvention.Cdecl;
case CallingConvention.StdCall: case CallingConvention.StdCall:
return Interop.CallingConvention.StdCall; return Interop.CallingConvention.StdCall;
case CallingConvention.ThisCall: case CallingConvention.ThisCall:
return Interop.CallingConvention.ThisCall; return Interop.CallingConvention.ThisCall;
case CallingConvention.FastCall: case CallingConvention.FastCall:
return Interop.CallingConvention.FastCall; return Interop.CallingConvention.FastCall;
} }
return Interop.CallingConvention.Winapi; return Interop.CallingConvention.Winapi;
} }
} }
} }

42
src/Generator/Generators/Template.cs

@ -38,8 +38,8 @@ namespace CppSharp.Generators
private bool hasIndentChanged; private bool hasIndentChanged;
private bool isSubBlock; private bool isSubBlock;
public Func<bool> CheckGenerate; public Func<bool> CheckGenerate;
public Block() : this(BlockKind.Unknown) public Block() : this(BlockKind.Unknown)
{ {
@ -83,9 +83,9 @@ namespace CppSharp.Generators
public virtual string Generate(DriverOptions options) public virtual string Generate(DriverOptions options)
{ {
if (CheckGenerate != null && !CheckGenerate()) if (CheckGenerate != null && !CheckGenerate())
return ""; return "";
if (Blocks.Count == 0) if (Blocks.Count == 0)
return Text.ToString(); return Text.ToString();
@ -170,17 +170,17 @@ namespace CppSharp.Generators
return builder.ToString(); return builder.ToString();
} }
public bool IsEmpty public bool IsEmpty
{ {
get get
{ {
if (Blocks.Any(block => !block.IsEmpty)) if (Blocks.Any(block => !block.IsEmpty))
return false; return false;
return string.IsNullOrEmpty(Text.ToString()); return string.IsNullOrEmpty(Text.ToString());
} }
} }
#region ITextGenerator implementation #region ITextGenerator implementation
public uint Indent { get { return Text.Indent; } } public uint Indent { get { return Text.Indent; } }
@ -296,14 +296,14 @@ namespace CppSharp.Generators
ActiveBlock = block; ActiveBlock = block;
} }
public Block PopBlock(NewLineKind newLineKind = NewLineKind.Never) public Block PopBlock(NewLineKind newLineKind = NewLineKind.Never)
{ {
var block = ActiveBlock; var block = ActiveBlock;
ActiveBlock.NewLineKind = newLineKind; ActiveBlock.NewLineKind = newLineKind;
ActiveBlock = ActiveBlock.Parent; ActiveBlock = ActiveBlock.Parent;
return block; return block;
} }
public IEnumerable<Block> FindBlocks(int kind) public IEnumerable<Block> FindBlocks(int kind)

72
src/Generator/Options.cs

@ -54,14 +54,14 @@ namespace CppSharp
// General options // General options
public bool Quiet; public bool Quiet;
public bool ShowHelpText; public bool ShowHelpText;
public bool OutputDebug; public bool OutputDebug;
/// <summary> /// <summary>
/// Set to true to simulate generating without actually writing /// Set to true to simulate generating without actually writing
/// any output to disk. This can be useful to activate while /// any output to disk. This can be useful to activate while
/// debugging the parser generator so generator bugs do not get /// debugging the parser generator so generator bugs do not get
/// in the way while iterating. /// in the way while iterating.
/// </summary> /// </summary>
public bool DryRun; public bool DryRun;
// Parser options // Parser options
@ -101,39 +101,39 @@ namespace CppSharp
public bool GenerateAbstractImpls; public bool GenerateAbstractImpls;
public bool GenerateInterfacesForMultipleInheritance; public bool GenerateInterfacesForMultipleInheritance;
public bool GenerateInternalImports; public bool GenerateInternalImports;
public bool GenerateClassMarshals; public bool GenerateClassMarshals;
public bool GenerateInlines; public bool GenerateInlines;
public bool GenerateCopyConstructors; public bool GenerateCopyConstructors;
public bool UseHeaderDirectories; public bool UseHeaderDirectories;
/// <summary> /// <summary>
/// If set to true the generator will use GetterSetterToPropertyPass to /// If set to true the generator will use GetterSetterToPropertyPass to
/// convert matching getter/setter pairs to properties. /// convert matching getter/setter pairs to properties.
/// </summary> /// </summary>
public bool GenerateProperties; public bool GenerateProperties;
/// <summary> /// <summary>
/// If set to true the generator will use GetterSetterToPropertyAdvancedPass to /// If set to true the generator will use GetterSetterToPropertyAdvancedPass to
/// convert matching getter/setter pairs to properties. This pass has slightly /// convert matching getter/setter pairs to properties. This pass has slightly
/// different semantics from GetterSetterToPropertyPass, it will more agressively /// different semantics from GetterSetterToPropertyPass, it will more agressively
/// try to match for matching properties. /// try to match for matching properties.
/// </summary> /// </summary>
public bool GeneratePropertiesAdvanced; public bool GeneratePropertiesAdvanced;
/// <summary> /// <summary>
/// If set to true the generator will use ConstructorToConversionOperatorPass to /// If set to true the generator will use ConstructorToConversionOperatorPass to
/// create implicit and explicit conversion operators out of single argument /// create implicit and explicit conversion operators out of single argument
/// constructors. /// constructors.
/// </summary> /// </summary>
public bool GenerateConversionOperators; public bool GenerateConversionOperators;
//List of include directories that are used but not generated //List of include directories that are used but not generated
public List<string> NoGenIncludeDirs; public List<string> NoGenIncludeDirs;
/// <summary> /// <summary>
/// Wether the generated C# code should be automatically compiled. /// Wether the generated C# code should be automatically compiled.
/// </summary> /// </summary>
public bool CompileCode; public bool CompileCode;
/// <summary> /// <summary>
/// Enable this option to enable generation of finalizers. /// Enable this option to enable generation of finalizers.

448
src/Generator/Passes/CheckOperatorsOverloads.cs

@ -1,109 +1,109 @@
using System.Linq; using System.Linq;
using CppSharp.AST; using CppSharp.AST;
using CppSharp.AST.Extensions; using CppSharp.AST.Extensions;
using CppSharp.Generators; using CppSharp.Generators;
namespace CppSharp.Passes namespace CppSharp.Passes
{ {
/// <summary> /// <summary>
/// Checks for missing operator overloads required by C#. /// Checks for missing operator overloads required by C#.
/// </summary> /// </summary>
class CheckOperatorsOverloadsPass : TranslationUnitPass class CheckOperatorsOverloadsPass : TranslationUnitPass
{ {
public CheckOperatorsOverloadsPass() public CheckOperatorsOverloadsPass()
{ {
ClearVisitedDeclarations = false; ClearVisitedDeclarations = false;
} }
public override bool VisitClassDecl(Class @class) public override bool VisitClassDecl(Class @class)
{ {
if (@class.CompleteDeclaration != null) if (@class.CompleteDeclaration != null)
return VisitClassDecl(@class.CompleteDeclaration as Class); return VisitClassDecl(@class.CompleteDeclaration as Class);
if (!VisitDeclarationContext(@class)) if (!VisitDeclarationContext(@class))
return false; return false;
// Check for C++ operators that cannot be represented in C#. // Check for C++ operators that cannot be represented in C#.
CheckInvalidOperators(@class); CheckInvalidOperators(@class);
if (Driver.Options.IsCSharpGenerator) if (Driver.Options.IsCSharpGenerator)
{ {
// The comparison operators, if overloaded, must be overloaded in pairs; // The comparison operators, if overloaded, must be overloaded in pairs;
// that is, if == is overloaded, != must also be overloaded. The reverse // that is, if == is overloaded, != must also be overloaded. The reverse
// is also true, and similar for < and >, and for <= and >=. // is also true, and similar for < and >, and for <= and >=.
HandleMissingOperatorOverloadPair(@class, CXXOperatorKind.EqualEqual, HandleMissingOperatorOverloadPair(@class, CXXOperatorKind.EqualEqual,
CXXOperatorKind.ExclaimEqual); CXXOperatorKind.ExclaimEqual);
HandleMissingOperatorOverloadPair(@class, CXXOperatorKind.Less, HandleMissingOperatorOverloadPair(@class, CXXOperatorKind.Less,
CXXOperatorKind.Greater); CXXOperatorKind.Greater);
HandleMissingOperatorOverloadPair(@class, CXXOperatorKind.LessEqual, HandleMissingOperatorOverloadPair(@class, CXXOperatorKind.LessEqual,
CXXOperatorKind.GreaterEqual); CXXOperatorKind.GreaterEqual);
} }
return false; return false;
} }
private void CheckInvalidOperators(Class @class) private void CheckInvalidOperators(Class @class)
{ {
foreach (var @operator in @class.Operators.Where(o => o.IsGenerated)) foreach (var @operator in @class.Operators.Where(o => o.IsGenerated))
{ {
if (!IsValidOperatorOverload(@operator)) if (!IsValidOperatorOverload(@operator))
{ {
Driver.Diagnostics.Debug(DiagnosticId.InvalidOperatorOverload, Driver.Diagnostics.Debug(DiagnosticId.InvalidOperatorOverload,
"Invalid operator overload {0}::{1}", "Invalid operator overload {0}::{1}",
@class.OriginalName, @operator.OperatorKind); @class.OriginalName, @operator.OperatorKind);
@operator.ExplicitlyIgnore(); @operator.ExplicitlyIgnore();
continue; continue;
} }
if (@operator.SynthKind == FunctionSynthKind.NonMemberOperator) if (@operator.SynthKind == FunctionSynthKind.NonMemberOperator)
continue; continue;
if (@operator.OperatorKind == CXXOperatorKind.Subscript) if (@operator.OperatorKind == CXXOperatorKind.Subscript)
{ {
CreateIndexer(@class, @operator); CreateIndexer(@class, @operator);
} }
else else
{ {
// Handle missing operator parameters // Handle missing operator parameters
if (@operator.IsStatic) if (@operator.IsStatic)
@operator.Parameters = @operator.Parameters.Skip(1).ToList(); @operator.Parameters = @operator.Parameters.Skip(1).ToList();
var type = new PointerType() var type = new PointerType()
{ {
QualifiedPointee = new QualifiedType(new TagType(@class)), QualifiedPointee = new QualifiedType(new TagType(@class)),
Modifier = PointerType.TypeModifier.LVReference Modifier = PointerType.TypeModifier.LVReference
}; };
@operator.Parameters.Insert(0, new Parameter @operator.Parameters.Insert(0, new Parameter
{ {
Name = Generator.GeneratedIdentifier("op"), Name = Generator.GeneratedIdentifier("op"),
QualifiedType = new QualifiedType(type), QualifiedType = new QualifiedType(type),
Kind = ParameterKind.OperatorParameter Kind = ParameterKind.OperatorParameter
}); });
} }
} }
} }
void CreateIndexer(Class @class, Method @operator) void CreateIndexer(Class @class, Method @operator)
{ {
var property = new Property var property = new Property
{ {
Name = "Item", Name = "Item",
QualifiedType = @operator.ReturnType, QualifiedType = @operator.ReturnType,
Access = @operator.Access, Access = @operator.Access,
Namespace = @class, Namespace = @class,
GetMethod = @operator GetMethod = @operator
}; };
var returnType = @operator.Type; var returnType = @operator.Type;
if (returnType.IsAddress()) if (returnType.IsAddress())
{ {
var pointer = returnType as PointerType; var pointer = returnType as PointerType;
var qualifiedPointee = pointer.QualifiedPointee; var qualifiedPointee = pointer.QualifiedPointee;
if (!qualifiedPointee.Qualifiers.IsConst) if (!qualifiedPointee.Qualifiers.IsConst)
property.SetMethod = @operator; property.SetMethod = @operator;
} }
// If we've a setter use the pointee as the type of the property. // If we've a setter use the pointee as the type of the property.
@ -111,68 +111,68 @@ namespace CppSharp.Passes
if (pointerType != null && property.HasSetter) if (pointerType != null && property.HasSetter)
property.QualifiedType = new QualifiedType( property.QualifiedType = new QualifiedType(
pointerType.Pointee, property.QualifiedType.Qualifiers); pointerType.Pointee, property.QualifiedType.Qualifiers);
if (Driver.Options.IsCLIGenerator) if (Driver.Options.IsCLIGenerator)
// C++/CLI uses "default" as the indexer property name. // C++/CLI uses "default" as the indexer property name.
property.Name = "default"; property.Name = "default";
property.Parameters.AddRange(@operator.Parameters); property.Parameters.AddRange(@operator.Parameters);
@class.Properties.Add(property); @class.Properties.Add(property);
@operator.GenerationKind = GenerationKind.Internal; @operator.GenerationKind = GenerationKind.Internal;
} }
static void HandleMissingOperatorOverloadPair(Class @class, CXXOperatorKind op1, static void HandleMissingOperatorOverloadPair(Class @class, CXXOperatorKind op1,
CXXOperatorKind op2) CXXOperatorKind op2)
{ {
foreach (var op in @class.Operators.Where( foreach (var op in @class.Operators.Where(
o => o.OperatorKind == op1 || o.OperatorKind == op2).ToList()) o => o.OperatorKind == op1 || o.OperatorKind == op2).ToList())
{ {
int index; int index;
var missingKind = CheckMissingOperatorOverloadPair(@class, out index, op1, op2, var missingKind = CheckMissingOperatorOverloadPair(@class, out index, op1, op2,
op.Parameters.Last().Type); op.Parameters.Last().Type);
if (missingKind == CXXOperatorKind.None || !op.IsGenerated) if (missingKind == CXXOperatorKind.None || !op.IsGenerated)
continue; continue;
var method = new Method() var method = new Method()
{ {
Name = Operators.GetOperatorIdentifier(missingKind), Name = Operators.GetOperatorIdentifier(missingKind),
Namespace = @class, Namespace = @class,
IsSynthetized = true, IsSynthetized = true,
Kind = CXXMethodKind.Operator, Kind = CXXMethodKind.Operator,
OperatorKind = missingKind, OperatorKind = missingKind,
ReturnType = op.ReturnType, ReturnType = op.ReturnType,
Parameters = op.Parameters Parameters = op.Parameters
}; };
@class.Methods.Insert(index, method); @class.Methods.Insert(index, method);
} }
} }
static CXXOperatorKind CheckMissingOperatorOverloadPair(Class @class, static CXXOperatorKind CheckMissingOperatorOverloadPair(Class @class,
out int index, CXXOperatorKind op1, CXXOperatorKind op2, Type type) out int index, CXXOperatorKind op1, CXXOperatorKind op2, Type type)
{ {
var first = @class.Operators.FirstOrDefault(o => o.OperatorKind == op1 && var first = @class.Operators.FirstOrDefault(o => o.OperatorKind == op1 &&
o.Parameters.Last().Type.Equals(type)); o.Parameters.Last().Type.Equals(type));
var second = @class.Operators.FirstOrDefault(o => o.OperatorKind == op2 && var second = @class.Operators.FirstOrDefault(o => o.OperatorKind == op2 &&
o.Parameters.Last().Type.Equals(type)); o.Parameters.Last().Type.Equals(type));
var hasFirst = first != null; var hasFirst = first != null;
var hasSecond = second != null; var hasSecond = second != null;
if (hasFirst && (!hasSecond || !second.IsGenerated)) if (hasFirst && (!hasSecond || !second.IsGenerated))
{ {
index = @class.Methods.IndexOf(first); index = @class.Methods.IndexOf(first);
return op2; return op2;
} }
if (hasSecond && (!hasFirst || !first.IsGenerated)) if (hasSecond && (!hasFirst || !first.IsGenerated))
{ {
index = @class.Methods.IndexOf(second); index = @class.Methods.IndexOf(second);
return op1; return op1;
} }
index = 0; index = 0;
return CXXOperatorKind.None; return CXXOperatorKind.None;
@ -200,66 +200,66 @@ namespace CppSharp.Passes
// The array indexing operator can be overloaded // The array indexing operator can be overloaded
case CXXOperatorKind.Subscript: case CXXOperatorKind.Subscript:
// The conversion operators can be overloaded // The conversion operators can be overloaded
case CXXOperatorKind.Conversion: case CXXOperatorKind.Conversion:
case CXXOperatorKind.ExplicitConversion: case CXXOperatorKind.ExplicitConversion:
return true; return true;
// The comparison operators can be overloaded if their return type is bool // The comparison operators can be overloaded if their return type is bool
case CXXOperatorKind.EqualEqual: case CXXOperatorKind.EqualEqual:
case CXXOperatorKind.ExclaimEqual: case CXXOperatorKind.ExclaimEqual:
case CXXOperatorKind.Less: case CXXOperatorKind.Less:
case CXXOperatorKind.Greater: case CXXOperatorKind.Greater:
case CXXOperatorKind.LessEqual: case CXXOperatorKind.LessEqual:
case CXXOperatorKind.GreaterEqual: case CXXOperatorKind.GreaterEqual:
return @operator.ReturnType.Type.IsPrimitiveType(PrimitiveType.Bool); return @operator.ReturnType.Type.IsPrimitiveType(PrimitiveType.Bool);
// Only prefix operators can be overloaded // Only prefix operators can be overloaded
case CXXOperatorKind.PlusPlus: case CXXOperatorKind.PlusPlus:
case CXXOperatorKind.MinusMinus: case CXXOperatorKind.MinusMinus:
return @operator.Parameters.Count == 0; return @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
case CXXOperatorKind.LessLess: case CXXOperatorKind.LessLess:
case CXXOperatorKind.GreaterGreater: case CXXOperatorKind.GreaterGreater:
PrimitiveType primitiveType; PrimitiveType primitiveType;
return @operator.Parameters.Last().Type.IsPrimitiveType(out primitiveType) && return @operator.Parameters.Last().Type.IsPrimitiveType(out primitiveType) &&
primitiveType == PrimitiveType.Int32; primitiveType == PrimitiveType.Int32;
// No parameters means the dereference operator - cannot be overloaded // No parameters means the dereference operator - cannot be overloaded
case CXXOperatorKind.Star: case CXXOperatorKind.Star:
return @operator.Parameters.Count > 0; return @operator.Parameters.Count > 0;
// Assignment operators cannot be overloaded // Assignment operators cannot be overloaded
case CXXOperatorKind.PlusEqual: case CXXOperatorKind.PlusEqual:
case CXXOperatorKind.MinusEqual: case CXXOperatorKind.MinusEqual:
case CXXOperatorKind.StarEqual: case CXXOperatorKind.StarEqual:
case CXXOperatorKind.SlashEqual: case CXXOperatorKind.SlashEqual:
case CXXOperatorKind.PercentEqual: case CXXOperatorKind.PercentEqual:
case CXXOperatorKind.AmpEqual: case CXXOperatorKind.AmpEqual:
case CXXOperatorKind.PipeEqual: case CXXOperatorKind.PipeEqual:
case CXXOperatorKind.CaretEqual: case CXXOperatorKind.CaretEqual:
case CXXOperatorKind.LessLessEqual: case CXXOperatorKind.LessLessEqual:
case CXXOperatorKind.GreaterGreaterEqual: case CXXOperatorKind.GreaterGreaterEqual:
// The conditional logical operators cannot be overloaded // The conditional logical operators cannot be overloaded
case CXXOperatorKind.AmpAmp: case CXXOperatorKind.AmpAmp:
case CXXOperatorKind.PipePipe: case CXXOperatorKind.PipePipe:
// These operators cannot be overloaded. // These operators cannot be overloaded.
case CXXOperatorKind.Equal: case CXXOperatorKind.Equal:
case CXXOperatorKind.Comma: case CXXOperatorKind.Comma:
case CXXOperatorKind.ArrowStar: case CXXOperatorKind.ArrowStar:
case CXXOperatorKind.Arrow: case CXXOperatorKind.Arrow:
case CXXOperatorKind.Call: case CXXOperatorKind.Call:
case CXXOperatorKind.Conditional: case CXXOperatorKind.Conditional:
case CXXOperatorKind.New: case CXXOperatorKind.New:
case CXXOperatorKind.Delete: case CXXOperatorKind.Delete:
case CXXOperatorKind.Array_New: case CXXOperatorKind.Array_New:
case CXXOperatorKind.Array_Delete: case CXXOperatorKind.Array_Delete:
default: default:
return false; return false;
} }
} }
} }
} }

116
src/Generator/Passes/ConstructorToConversionOperatorPass.cs

@ -1,58 +1,58 @@
using System.Linq; using System.Linq;
using CppSharp.AST; using CppSharp.AST;
using CppSharp.AST.Extensions; using CppSharp.AST.Extensions;
using CppSharp.Generators; using CppSharp.Generators;
namespace CppSharp.Passes namespace CppSharp.Passes
{ {
/// <summary> /// <summary>
/// This pass will create conversion operators out of single argument /// This pass will create conversion operators out of single argument
/// constructors. /// constructors.
/// </summary> /// </summary>
public class ConstructorToConversionOperatorPass : TranslationUnitPass public class ConstructorToConversionOperatorPass : TranslationUnitPass
{ {
public override bool VisitMethodDecl(Method method) public override bool VisitMethodDecl(Method method)
{ {
if (!method.IsConstructor) if (!method.IsConstructor)
return false; return false;
if (method.IsCopyConstructor) if (method.IsCopyConstructor)
return false; return false;
if (method.Parameters.Count != 1) if (method.Parameters.Count != 1)
return false; return false;
var parameter = method.Parameters[0]; var parameter = method.Parameters[0];
var parameterType = parameter.Type as PointerType; var parameterType = parameter.Type as PointerType;
if (parameterType == null) if (parameterType == null)
return false; return false;
if (!parameterType.IsReference) if (!parameterType.IsReference)
return false; return false;
var qualifiedPointee = parameterType.QualifiedPointee; var qualifiedPointee = parameterType.QualifiedPointee;
Class castFromClass; Class castFromClass;
if (!qualifiedPointee.Type.TryGetClass(out castFromClass)) if (!qualifiedPointee.Type.TryGetClass(out castFromClass))
return false; return false;
var castToClass = method.OriginalNamespace as Class; var castToClass = method.OriginalNamespace as Class;
if (castToClass == null) if (castToClass == null)
return false; return false;
if (castFromClass == castToClass) if (castFromClass == castToClass)
return false; return false;
var operatorKind = method.IsExplicit var operatorKind = method.IsExplicit
? CXXOperatorKind.ExplicitConversion ? CXXOperatorKind.ExplicitConversion
: CXXOperatorKind.Conversion; : CXXOperatorKind.Conversion;
var castToType = new TagType(castToClass); var castToType = new TagType(castToClass);
var qualifiedCastToType = new QualifiedType(castToType); var qualifiedCastToType = new QualifiedType(castToType);
var conversionOperator = new Method() var conversionOperator = new Method()
{ {
Name = Operators.GetOperatorIdentifier(operatorKind), Name = Operators.GetOperatorIdentifier(operatorKind),
Namespace = castFromClass, Namespace = castFromClass,
Kind = CXXMethodKind.Conversion, Kind = CXXMethodKind.Conversion,
IsSynthetized = true, IsSynthetized = true,
ConversionType = qualifiedCastToType, ConversionType = qualifiedCastToType,
ReturnType = qualifiedCastToType ReturnType = qualifiedCastToType
}; };
conversionOperator.OperatorKind = operatorKind; conversionOperator.OperatorKind = operatorKind;
castFromClass.Methods.Add(conversionOperator); castFromClass.Methods.Add(conversionOperator);
return true; return true;
} }
} }
} }

12
src/Generator/Passes/GenerateAbstractImplementationsPass.cs

@ -25,12 +25,12 @@ namespace CppSharp.Passes
public override bool VisitTranslationUnit(TranslationUnit unit) public override bool VisitTranslationUnit(TranslationUnit unit)
{ {
var result = base.VisitTranslationUnit(unit); var result = base.VisitTranslationUnit(unit);
foreach (var internalImpl in internalImpls) foreach (var internalImpl in internalImpls)
if (internalImpl.Namespace != null) if (internalImpl.Namespace != null)
internalImpl.Namespace.Classes.Add(internalImpl); internalImpl.Namespace.Classes.Add(internalImpl);
else else
unit.Classes.AddRange(internalImpls); unit.Classes.AddRange(internalImpls);
internalImpls.Clear(); internalImpls.Clear();
return result; return result;

18
src/Generator/Passes/GetterSetterToPropertyPass.cs

@ -74,8 +74,8 @@ namespace CppSharp.Passes
public override bool VisitMethodDecl(Method method) public override bool VisitMethodDecl(Method method)
{ {
if (!VisitDeclaration(method)) if (!VisitDeclaration(method))
return false; return false;
if (ASTUtils.CheckIgnoreMethod(method, Driver.Options)) if (ASTUtils.CheckIgnoreMethod(method, Driver.Options))
return false; return false;
@ -84,12 +84,12 @@ namespace CppSharp.Passes
if (@class == null || @class.IsIncomplete) if (@class == null || @class.IsIncomplete)
return false; return false;
if (method.IsConstructor) if (method.IsConstructor)
return false; return false;
if (method.IsSynthetized) if (method.IsSynthetized)
return false; return false;
if (IsGetter(method)) if (IsGetter(method))
{ {
var name = method.Name.Substring("get".Length); var name = method.Name.Substring("get".Length);
@ -114,7 +114,7 @@ namespace CppSharp.Passes
prop.SetMethod = method; prop.SetMethod = method;
prop.Access = method.Access; prop.Access = method.Access;
// Ignore the original method now that we know it is a setter. // Ignore the original method now that we know it is a setter.
method.GenerationKind = GenerationKind.Internal; method.GenerationKind = GenerationKind.Internal;
Driver.Diagnostics.Debug("Setter created: {0}::{1}", @class.Name, name); Driver.Diagnostics.Debug("Setter created: {0}::{1}", @class.Name, name);

10
src/Generator/Passes/MultipleInheritancePass.cs

@ -67,7 +67,7 @@ namespace CppSharp.Passes
select new BaseClassSpecifier { Type = new TagType(i) }); select new BaseClassSpecifier { Type = new TagType(i) });
@interface.Methods.AddRange( @interface.Methods.AddRange(
from m in @base.Methods from m in @base.Methods
where !m.IsConstructor && !m.IsDestructor && !m.IsStatic && m.IsDeclared && !m.IsOperator where !m.IsConstructor && !m.IsDestructor && !m.IsStatic && m.IsDeclared && !m.IsOperator
select new Method(m) { Namespace = @interface }); select new Method(m) { Namespace = @interface });
@ -76,8 +76,8 @@ namespace CppSharp.Passes
where property.IsDeclared where property.IsDeclared
select new Property(property) { Namespace = @interface }); select new Property(property) { Namespace = @interface });
@interface.Fields.AddRange(@base.Fields); @interface.Fields.AddRange(@base.Fields);
if (@interface.Bases.Count == 0) if (@interface.Bases.Count == 0)
{ {
Property instance = new Property(); Property instance = new Property();
@ -112,7 +112,7 @@ namespace CppSharp.Passes
IsVirtual = false, IsVirtual = false,
IsOverride = false IsOverride = false
}; };
var rootBaseMethod = @class.GetRootBaseMethod(method, true); var rootBaseMethod = @class.GetRootBaseMethod(method, true);
if (rootBaseMethod != null && rootBaseMethod.IsDeclared) if (rootBaseMethod != null && rootBaseMethod.IsDeclared)
impl.ExplicitInterfaceImpl = @interface; impl.ExplicitInterfaceImpl = @interface;
@class.Methods.Add(impl); @class.Methods.Add(impl);
@ -126,7 +126,7 @@ namespace CppSharp.Passes
foreach (var property in @interface.Properties.Where(p => p.Name != Helpers.InstanceIdentifier)) foreach (var property in @interface.Properties.Where(p => p.Name != Helpers.InstanceIdentifier))
{ {
var impl = new Property(property) { Namespace = @class }; var impl = new Property(property) { Namespace = @class };
var rootBaseProperty = @class.GetRootBaseProperty(property, true); var rootBaseProperty = @class.GetRootBaseProperty(property, true);
if (rootBaseProperty != null && rootBaseProperty.IsDeclared) if (rootBaseProperty != null && rootBaseProperty.IsDeclared)
impl.ExplicitInterfaceImpl = @interface; impl.ExplicitInterfaceImpl = @interface;
@class.Properties.Add(impl); @class.Properties.Add(impl);

660
src/Generator/Types/CppTypePrinter.cs

@ -1,330 +1,330 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using CppSharp.AST; using CppSharp.AST;
using Type = CppSharp.AST.Type; using Type = CppSharp.AST.Type;
namespace CppSharp.Types namespace CppSharp.Types
{ {
public enum CppTypePrintScopeKind public enum CppTypePrintScopeKind
{ {
Local, Local,
Qualified, Qualified,
GlobalQualified GlobalQualified
} }
public class CppTypePrinter : ITypePrinter<string>, IDeclVisitor<string> public class CppTypePrinter : ITypePrinter<string>, IDeclVisitor<string>
{ {
public CppTypePrintScopeKind PrintScopeKind; public CppTypePrintScopeKind PrintScopeKind;
public bool PrintLogicalNames; public bool PrintLogicalNames;
public bool PrintTypeQualifiers; public bool PrintTypeQualifiers;
public CppTypePrinter(ITypeMapDatabase database, bool printTypeQualifiers = true) public CppTypePrinter(ITypeMapDatabase database, bool printTypeQualifiers = true)
{ {
PrintScopeKind = CppTypePrintScopeKind.GlobalQualified; PrintScopeKind = CppTypePrintScopeKind.GlobalQualified;
PrintTypeQualifiers = printTypeQualifiers; PrintTypeQualifiers = printTypeQualifiers;
} }
public string VisitTagType(TagType tag, TypeQualifiers quals) public string VisitTagType(TagType tag, TypeQualifiers quals)
{ {
return tag.Declaration.Visit(this); return tag.Declaration.Visit(this);
} }
public string VisitArrayType(ArrayType array, TypeQualifiers quals) public string VisitArrayType(ArrayType array, TypeQualifiers quals)
{ {
var typeName = array.Type.Visit(this); var typeName = array.Type.Visit(this);
switch (array.SizeType) switch (array.SizeType)
{ {
case ArrayType.ArraySize.Constant: case ArrayType.ArraySize.Constant:
return string.Format("{0}[{1}]", typeName, array.Size); return string.Format("{0}[{1}]", typeName, array.Size);
case ArrayType.ArraySize.Variable: case ArrayType.ArraySize.Variable:
case ArrayType.ArraySize.Dependent: case ArrayType.ArraySize.Dependent:
case ArrayType.ArraySize.Incomplete: case ArrayType.ArraySize.Incomplete:
return string.Format("{0}[]", typeName); return string.Format("{0}[]", typeName);
} }
throw new NotSupportedException(); throw new NotSupportedException();
} }
static string ConvertModifierToString(PointerType.TypeModifier modifier) static string ConvertModifierToString(PointerType.TypeModifier modifier)
{ {
switch (modifier) switch (modifier)
{ {
case PointerType.TypeModifier.Value: return string.Empty; case PointerType.TypeModifier.Value: return string.Empty;
case PointerType.TypeModifier.Pointer: return "*"; case PointerType.TypeModifier.Pointer: return "*";
case PointerType.TypeModifier.LVReference: return "&"; case PointerType.TypeModifier.LVReference: return "&";
case PointerType.TypeModifier.RVReference: return "&&"; case PointerType.TypeModifier.RVReference: return "&&";
} }
return string.Empty; return string.Empty;
} }
public string VisitPointerType(PointerType pointer, TypeQualifiers quals) public string VisitPointerType(PointerType pointer, TypeQualifiers quals)
{ {
var pointee = pointer.Pointee; var pointee = pointer.Pointee;
var function = pointee as FunctionType; var function = pointee as FunctionType;
if (function != null) if (function != null)
{ {
var arguments = function.Parameters; var arguments = function.Parameters;
var returnType = function.ReturnType; var returnType = function.ReturnType;
var args = string.Empty; var args = string.Empty;
if (arguments.Count > 0) if (arguments.Count > 0)
args = VisitParameters(function.Parameters, hasNames: false); args = VisitParameters(function.Parameters, hasNames: false);
return string.Format("{0} (*)({1})", returnType.Visit(this), args); return string.Format("{0} (*)({1})", returnType.Visit(this), args);
} }
var pointeeType = pointer.Pointee.Visit(this, quals); var pointeeType = pointer.Pointee.Visit(this, quals);
var mod = ConvertModifierToString(pointer.Modifier); var mod = ConvertModifierToString(pointer.Modifier);
var s = PrintTypeQualifiers && quals.IsConst ? "const " : string.Empty; var s = PrintTypeQualifiers && quals.IsConst ? "const " : string.Empty;
s += string.Format("{0}{1}", pointeeType, mod); s += string.Format("{0}{1}", pointeeType, mod);
return s; return s;
} }
public string VisitMemberPointerType(MemberPointerType member, TypeQualifiers quals) public string VisitMemberPointerType(MemberPointerType member, TypeQualifiers quals)
{ {
return string.Empty; return string.Empty;
} }
public string VisitBuiltinType(BuiltinType builtin, TypeQualifiers quals) public string VisitBuiltinType(BuiltinType builtin, TypeQualifiers quals)
{ {
return VisitPrimitiveType(builtin.Type); return VisitPrimitiveType(builtin.Type);
} }
public string VisitPrimitiveType(PrimitiveType primitive) public string VisitPrimitiveType(PrimitiveType primitive)
{ {
switch (primitive) switch (primitive)
{ {
case PrimitiveType.Bool: return "bool"; case PrimitiveType.Bool: return "bool";
case PrimitiveType.Void: return "void"; case PrimitiveType.Void: return "void";
case PrimitiveType.Char16: case PrimitiveType.Char16:
case PrimitiveType.WideChar: return "char"; case PrimitiveType.WideChar: return "char";
case PrimitiveType.Int8: return "char"; case PrimitiveType.Int8: return "char";
case PrimitiveType.UInt8: return "unsigned char"; case PrimitiveType.UInt8: return "unsigned char";
case PrimitiveType.Int16: return "short"; case PrimitiveType.Int16: return "short";
case PrimitiveType.UInt16: return "unsigned short"; case PrimitiveType.UInt16: return "unsigned short";
case PrimitiveType.Int32: return "int"; case PrimitiveType.Int32: return "int";
case PrimitiveType.UInt32: return "unsigned int"; case PrimitiveType.UInt32: return "unsigned int";
case PrimitiveType.Int64: return "long long"; case PrimitiveType.Int64: return "long long";
case PrimitiveType.UInt64: return "unsigned long long"; case PrimitiveType.UInt64: return "unsigned long long";
case PrimitiveType.Float: return "float"; case PrimitiveType.Float: return "float";
case PrimitiveType.Double: return "double"; case PrimitiveType.Double: return "double";
case PrimitiveType.IntPtr: return "void*"; case PrimitiveType.IntPtr: return "void*";
case PrimitiveType.UIntPtr: return "uintptr_t"; case PrimitiveType.UIntPtr: return "uintptr_t";
case PrimitiveType.Null: return "std::nullptr_t"; case PrimitiveType.Null: return "std::nullptr_t";
} }
throw new NotSupportedException(); throw new NotSupportedException();
} }
public string VisitTypedefType(TypedefType typedef, TypeQualifiers quals) public string VisitTypedefType(TypedefType typedef, TypeQualifiers quals)
{ {
return GetDeclName(typedef.Declaration); return GetDeclName(typedef.Declaration);
} }
public string VisitAttributedType(AttributedType attributed, TypeQualifiers quals) public string VisitAttributedType(AttributedType attributed, TypeQualifiers quals)
{ {
return attributed.Modified.Visit(this); return attributed.Modified.Visit(this);
} }
public string VisitDecayedType(DecayedType decayed, TypeQualifiers quals) public string VisitDecayedType(DecayedType decayed, TypeQualifiers quals)
{ {
return decayed.Decayed.Visit(this); return decayed.Decayed.Visit(this);
} }
public string VisitTemplateSpecializationType(TemplateSpecializationType template, TypeQualifiers quals) public string VisitTemplateSpecializationType(TemplateSpecializationType template, TypeQualifiers quals)
{ {
return string.Format("{0}<{1}>", template.Template.TemplatedDecl.Visit(this), return string.Format("{0}<{1}>", template.Template.TemplatedDecl.Visit(this),
string.Join(", ", string.Join(", ",
template.Arguments.Where( template.Arguments.Where(
a => a.Type.Type != null && a => a.Type.Type != null &&
!(a.Type.Type is DependentNameType)).Select(a => a.Type.Visit(this)))); !(a.Type.Type is DependentNameType)).Select(a => a.Type.Visit(this))));
} }
public string VisitTemplateParameterType(TemplateParameterType param, TypeQualifiers quals) public string VisitTemplateParameterType(TemplateParameterType param, TypeQualifiers quals)
{ {
if (param.Parameter.Name == null) if (param.Parameter.Name == null)
return string.Empty; return string.Empty;
return param.Parameter.Name; return param.Parameter.Name;
} }
public string VisitTemplateParameterSubstitutionType( public string VisitTemplateParameterSubstitutionType(
TemplateParameterSubstitutionType param, TypeQualifiers quals) TemplateParameterSubstitutionType param, TypeQualifiers quals)
{ {
return param.Replacement.Visit(this); return param.Replacement.Visit(this);
} }
public string VisitInjectedClassNameType(InjectedClassNameType injected, TypeQualifiers quals) public string VisitInjectedClassNameType(InjectedClassNameType injected, TypeQualifiers quals)
{ {
return injected.Class.Visit(this); return injected.Class.Visit(this);
} }
public string VisitDependentNameType(DependentNameType dependent, TypeQualifiers quals) public string VisitDependentNameType(DependentNameType dependent, TypeQualifiers quals)
{ {
throw new System.NotImplementedException(); throw new System.NotImplementedException();
} }
public string VisitPackExpansionType(PackExpansionType packExpansionType, TypeQualifiers quals) public string VisitPackExpansionType(PackExpansionType packExpansionType, TypeQualifiers quals)
{ {
return string.Empty; return string.Empty;
} }
public string VisitCILType(CILType type, TypeQualifiers quals) public string VisitCILType(CILType type, TypeQualifiers quals)
{ {
return string.Empty; return string.Empty;
} }
public string VisitPrimitiveType(PrimitiveType type, TypeQualifiers quals) public string VisitPrimitiveType(PrimitiveType type, TypeQualifiers quals)
{ {
throw new System.NotImplementedException(); throw new System.NotImplementedException();
} }
public string VisitDeclaration(Declaration decl, TypeQualifiers quals) public string VisitDeclaration(Declaration decl, TypeQualifiers quals)
{ {
throw new System.NotImplementedException(); throw new System.NotImplementedException();
} }
public string VisitFunctionType(FunctionType function, TypeQualifiers quals) public string VisitFunctionType(FunctionType function, TypeQualifiers quals)
{ {
var arguments = function.Parameters; var arguments = function.Parameters;
var returnType = function.ReturnType; var returnType = function.ReturnType;
var args = string.Empty; var args = string.Empty;
if (arguments.Count > 0) if (arguments.Count > 0)
args = VisitParameters(function.Parameters, hasNames: false); args = VisitParameters(function.Parameters, hasNames: false);
return string.Format("{0} ({1})", returnType.Visit(this), args); return string.Format("{0} ({1})", returnType.Visit(this), args);
} }
public string VisitParameters(IEnumerable<Parameter> @params, public string VisitParameters(IEnumerable<Parameter> @params,
bool hasNames) bool hasNames)
{ {
var args = new List<string>(); var args = new List<string>();
foreach (var param in @params) foreach (var param in @params)
args.Add(VisitParameter(param, hasNames)); args.Add(VisitParameter(param, hasNames));
return string.Join(", ", args); return string.Join(", ", args);
} }
public string VisitParameter(Parameter arg, bool hasName = true) public string VisitParameter(Parameter arg, bool hasName = true)
{ {
var type = arg.Type.Visit(this, arg.QualifiedType.Qualifiers); var type = arg.Type.Visit(this, arg.QualifiedType.Qualifiers);
var name = arg.Name; var name = arg.Name;
if (hasName && !string.IsNullOrEmpty(name)) if (hasName && !string.IsNullOrEmpty(name))
return string.Format("{0} {1}", type, name); return string.Format("{0} {1}", type, name);
return type; return type;
} }
public string VisitDelegate(FunctionType function) public string VisitDelegate(FunctionType function)
{ {
throw new System.NotImplementedException(); throw new System.NotImplementedException();
} }
public string GetDeclName(Declaration declaration) public string GetDeclName(Declaration declaration)
{ {
switch (PrintScopeKind) switch (PrintScopeKind)
{ {
case CppTypePrintScopeKind.Local: case CppTypePrintScopeKind.Local:
return PrintLogicalNames ? declaration.LogicalOriginalName return PrintLogicalNames ? declaration.LogicalOriginalName
: declaration.OriginalName; : declaration.OriginalName;
case CppTypePrintScopeKind.Qualified: case CppTypePrintScopeKind.Qualified:
return PrintLogicalNames ? declaration.QualifiedLogicalOriginalName return PrintLogicalNames ? declaration.QualifiedLogicalOriginalName
: declaration.QualifiedOriginalName; : declaration.QualifiedOriginalName;
case CppTypePrintScopeKind.GlobalQualified: case CppTypePrintScopeKind.GlobalQualified:
return "::" + (PrintLogicalNames ? declaration.QualifiedLogicalOriginalName return "::" + (PrintLogicalNames ? declaration.QualifiedLogicalOriginalName
: declaration.QualifiedOriginalName); : declaration.QualifiedOriginalName);
} }
throw new NotSupportedException(); throw new NotSupportedException();
} }
public string VisitDeclaration(Declaration decl) public string VisitDeclaration(Declaration decl)
{ {
return GetDeclName(decl); return GetDeclName(decl);
} }
public string VisitClassDecl(Class @class) public string VisitClassDecl(Class @class)
{ {
return VisitDeclaration(@class); return VisitDeclaration(@class);
} }
public string VisitFieldDecl(Field field) public string VisitFieldDecl(Field field)
{ {
return VisitDeclaration(field); return VisitDeclaration(field);
} }
public string VisitFunctionDecl(Function function) public string VisitFunctionDecl(Function function)
{ {
return VisitDeclaration(function); return VisitDeclaration(function);
} }
public string VisitMethodDecl(Method method) public string VisitMethodDecl(Method method)
{ {
return VisitDeclaration(method); return VisitDeclaration(method);
} }
public string VisitParameterDecl(Parameter parameter) public string VisitParameterDecl(Parameter parameter)
{ {
return VisitParameter(parameter, hasName: false); return VisitParameter(parameter, hasName: false);
} }
public string VisitTypedefDecl(TypedefDecl typedef) public string VisitTypedefDecl(TypedefDecl typedef)
{ {
return VisitDeclaration(typedef); return VisitDeclaration(typedef);
} }
public string VisitEnumDecl(Enumeration @enum) public string VisitEnumDecl(Enumeration @enum)
{ {
return VisitDeclaration(@enum); return VisitDeclaration(@enum);
} }
public string VisitVariableDecl(Variable variable) public string VisitVariableDecl(Variable variable)
{ {
return VisitDeclaration(variable); return VisitDeclaration(variable);
} }
public string VisitClassTemplateDecl(ClassTemplate template) public string VisitClassTemplateDecl(ClassTemplate template)
{ {
return VisitDeclaration(template); return VisitDeclaration(template);
} }
public string VisitFunctionTemplateDecl(FunctionTemplate template) public string VisitFunctionTemplateDecl(FunctionTemplate template)
{ {
return VisitDeclaration(template); return VisitDeclaration(template);
} }
public string VisitMacroDefinition(MacroDefinition macro) public string VisitMacroDefinition(MacroDefinition macro)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public string VisitNamespace(Namespace @namespace) public string VisitNamespace(Namespace @namespace)
{ {
return VisitDeclaration(@namespace); return VisitDeclaration(@namespace);
} }
public string VisitEvent(Event @event) public string VisitEvent(Event @event)
{ {
return string.Empty; return string.Empty;
} }
public string VisitProperty(Property property) public string VisitProperty(Property property)
{ {
return VisitDeclaration(property); return VisitDeclaration(property);
} }
public string ToString(Type type) public string ToString(Type type)
{ {
return type.Visit(this); return type.Visit(this);
} }
} }
} }

48
src/Generator/Types/Types.cs

@ -112,19 +112,19 @@ namespace CppSharp
} }
return base.VisitMemberPointerType(member, quals); return base.VisitMemberPointerType(member, quals);
} }
public override bool VisitParameterDecl(Parameter parameter) public override bool VisitParameterDecl(Parameter parameter)
{ {
if (parameter.Type.IsPrimitiveType(PrimitiveType.Null)) if (parameter.Type.IsPrimitiveType(PrimitiveType.Null))
{ {
Ignore(); Ignore();
return false; return false;
} }
return base.VisitParameterDecl(parameter); return base.VisitParameterDecl(parameter);
} }
public override bool VisitTemplateSpecializationType( public override bool VisitTemplateSpecializationType(
TemplateSpecializationType template, TypeQualifiers quals) TemplateSpecializationType template, TypeQualifiers quals)
{ {
@ -138,17 +138,17 @@ namespace CppSharp
Ignore(); Ignore();
return base.VisitTemplateSpecializationType(template, quals); return base.VisitTemplateSpecializationType(template, quals);
} }
public override bool VisitFunctionType(FunctionType function, TypeQualifiers quals) public override bool VisitFunctionType(FunctionType function, TypeQualifiers quals)
{ {
// We don't know how to marshal non-static member functions // We don't know how to marshal non-static member functions
if (function.CallingConvention == CallingConvention.ThisCall) if (function.CallingConvention == CallingConvention.ThisCall)
{ {
Ignore(); Ignore();
return false; return false;
} }
return base.VisitFunctionType(function, quals); return base.VisitFunctionType(function, quals);
} }
} }

30
src/Generator/Utils/Utils.cs

@ -235,19 +235,19 @@ namespace CppSharp
return assembly.GetTypes().Where(baseType.IsAssignableFrom); return assembly.GetTypes().Where(baseType.IsAssignableFrom);
} }
} }
public static class PathHelpers public static class PathHelpers
{ {
public static string GetRelativePath(string fromPath, string toPath) public static string GetRelativePath(string fromPath, string toPath)
{ {
var path1 = fromPath.Trim('\\', '/'); var path1 = fromPath.Trim('\\', '/');
var path2 = toPath.Trim('\\', '/'); var path2 = toPath.Trim('\\', '/');
var uri1 = new System.Uri("c:\\" + path1 + "\\"); var uri1 = new System.Uri("c:\\" + path1 + "\\");
var uri2 = new System.Uri("c:\\" + path2 + "\\"); var uri2 = new System.Uri("c:\\" + path2 + "\\");
return uri1.MakeRelativeUri(uri2).ToString(); return uri1.MakeRelativeUri(uri2).ToString();
} }
} }
} }

104
tests/Basic/Basic.Tests.cs

@ -22,16 +22,16 @@ public class BasicTests : GeneratorTestFixture
Assert.That(hello.AddFoo(foo), Is.EqualTo(11)); Assert.That(hello.AddFoo(foo), Is.EqualTo(11));
Assert.That(hello.AddFooPtr(foo), Is.EqualTo(11)); Assert.That(hello.AddFooPtr(foo), Is.EqualTo(11));
Assert.That(hello.AddFooPtr(foo), Is.EqualTo(11)); Assert.That(hello.AddFooPtr(foo), Is.EqualTo(11));
Assert.That(hello.AddFooRef(foo), Is.EqualTo(11)); Assert.That(hello.AddFooRef(foo), Is.EqualTo(11));
unsafe unsafe
{ {
var pointer = foo.SomePointer; var pointer = foo.SomePointer;
var pointerPointer = foo.SomePointerPointer; var pointerPointer = foo.SomePointerPointer;
for (int i = 0; i < 4; i++) for (int i = 0; i < 4; i++)
{ {
Assert.AreEqual(i, pointer[i]); Assert.AreEqual(i, pointer[i]);
Assert.AreEqual(i, (*pointerPointer)[i]); Assert.AreEqual(i, (*pointerPointer)[i]);
} }
} }
var bar = new Bar { A = 4, B = 7 }; var bar = new Bar { A = 4, B = 7 };
@ -178,9 +178,9 @@ public class BasicTests : GeneratorTestFixture
Assert.AreEqual(8, doubleSum); Assert.AreEqual(8, doubleSum);
var stdcall = delegates.StdCall(i => i); var stdcall = delegates.StdCall(i => i);
Assert.AreEqual(1, stdcall); Assert.AreEqual(1, stdcall);
var cdecl = delegates.CDecl(i => i); var cdecl = delegates.CDecl(i => i);
Assert.AreEqual(1, cdecl); Assert.AreEqual(1, cdecl);
} }
@ -204,7 +204,7 @@ public class BasicTests : GeneratorTestFixture
[Test] [Test]
public void TestStaticClasses() public void TestStaticClasses()
{ {
Assert.That(TestStaticClass.Add(1, 2), Is.EqualTo(3)); Assert.That(TestStaticClass.Add(1, 2), Is.EqualTo(3));
Assert.That(TestStaticClassDerived.Foo(), Is.EqualTo(0)); Assert.That(TestStaticClassDerived.Foo(), Is.EqualTo(0));
} }
@ -239,22 +239,22 @@ public class BasicTests : GeneratorTestFixture
[Test] [Test]
public unsafe void TestIndexers() public unsafe void TestIndexers()
{ {
var indexedProperties = new TestIndexedProperties(); var indexedProperties = new TestIndexedProperties();
Assert.AreEqual(1, indexedProperties[0]); Assert.AreEqual(1, indexedProperties[0]);
Assert.AreEqual(1, indexedProperties["foo"]); Assert.AreEqual(1, indexedProperties["foo"]);
indexedProperties[0] = 2; indexedProperties[0] = 2;
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);
} }
@ -304,30 +304,30 @@ public class BasicTests : GeneratorTestFixture
var @class = new TestGetterSetterToProperties(); var @class = new TestGetterSetterToProperties();
Assert.That(@class.Width, Is.EqualTo(640)); Assert.That(@class.Width, Is.EqualTo(640));
Assert.That(@class.Height, Is.EqualTo(480)); Assert.That(@class.Height, Is.EqualTo(480));
} }
[Test] [Test]
public unsafe void TestSingleArgumentCtorToCastOperator() public unsafe void TestSingleArgumentCtorToCastOperator()
{ {
var classA = new ClassA(10); var classA = new ClassA(10);
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);
} }
[Test] [Test]
public unsafe void TestDecltype() public unsafe void TestDecltype()
{ {
var ret = basic.TestDecltype(); var ret = basic.TestDecltype();
Assert.AreEqual(0, ret); Assert.AreEqual(0, ret);
} }
[Test] [Test]
public unsafe void TestNullPtrType() public unsafe void TestNullPtrType()
{ {
var ret = basic.TestNullPtrTypeRet(); var ret = basic.TestNullPtrTypeRet();
Assert.AreEqual(IntPtr.Zero, new IntPtr(ret)); Assert.AreEqual(IntPtr.Zero, new IntPtr(ret));
} }
} }

2
tests/Basic/Basic.cs

@ -20,7 +20,7 @@ namespace CppSharp.Tests
driver.Options.GenerateVirtualTables = true; driver.Options.GenerateVirtualTables = true;
driver.Options.GenerateCopyConstructors = true; driver.Options.GenerateCopyConstructors = true;
driver.Options.MarshalCharAsManagedChar = true; driver.Options.MarshalCharAsManagedChar = true;
driver.Options.GenerateProperties = true; driver.Options.GenerateProperties = true;
driver.Options.GenerateConversionOperators = true; driver.Options.GenerateConversionOperators = true;
} }

214
tests/Basic/Basic.h

@ -11,12 +11,12 @@ public:
const char* GetANSI(); const char* GetANSI();
// TODO: VC++ does not support char16 // TODO: VC++ does not support char16
// char16 chr16; // char16 chr16;
// Not properly handled yet - ignore // Not properly handled yet - ignore
float nested_array[2][2]; float nested_array[2][2];
// Primitive pointer types // Primitive pointer types
const int* SomePointer; const int* SomePointer;
const int** SomePointerPointer; const int** SomePointerPointer;
}; };
struct DLL_API Bar struct DLL_API Bar
@ -234,12 +234,12 @@ DLL_API TestMoveOperatorToClass operator+(const TestMoveOperatorToClass& b1,
return b; return b;
} }
// Not a valid operator overload for Foo2 in managed code - comparison operators need to return bool. // Not a valid operator overload for Foo2 in managed code - comparison operators need to return bool.
DLL_API int operator==(const Foo2& a, const Foo2& b) DLL_API int operator==(const Foo2& a, const Foo2& b)
{ {
return 0; return 0;
} }
// Tests delegates // Tests delegates
typedef int (*DelegateInGlobalNamespace)(int); typedef int (*DelegateInGlobalNamespace)(int);
typedef int (STDCALL *DelegateStdCall)(int); typedef int (STDCALL *DelegateStdCall)(int);
@ -325,14 +325,14 @@ public:
float B; float B;
}; };
TestCopyConstructorRef::TestCopyConstructorRef() TestCopyConstructorRef::TestCopyConstructorRef()
{ {
} }
TestCopyConstructorRef::TestCopyConstructorRef(const TestCopyConstructorRef& other) TestCopyConstructorRef::TestCopyConstructorRef(const TestCopyConstructorRef& other)
{ {
A = other.A; A = other.A;
B = other.B; B = other.B;
} }
template <class T> template <class T>
@ -340,28 +340,28 @@ struct EmptyNamedNestedEnum
{ {
enum { Value = 10 }; enum { Value = 10 };
}; };
typedef unsigned long foo_t; typedef unsigned long foo_t;
typedef struct DLL_API SomeStruct typedef struct DLL_API SomeStruct
{ {
SomeStruct(); SomeStruct();
foo_t p; foo_t p;
} SomeStruct; } SomeStruct;
SomeStruct::SomeStruct() : p(1) {} SomeStruct::SomeStruct() : p(1) {}
class DLL_API SomeClassExtendingTheStruct : public SomeStruct class DLL_API SomeClassExtendingTheStruct : public SomeStruct
{ {
}; };
namespace SomeNamespace namespace SomeNamespace
{ {
class DLL_API AbstractClass class DLL_API AbstractClass
{ {
public: public:
virtual void AbstractMethod() = 0; virtual void AbstractMethod() = 0;
}; };
} }
// Test operator overloads // Test operator overloads
class DLL_API ClassWithOverloadedOperators class DLL_API ClassWithOverloadedOperators
@ -380,72 +380,72 @@ ClassWithOverloadedOperators::operator int() { return 2; }
ClassWithOverloadedOperators::operator short() { return 3; } ClassWithOverloadedOperators::operator short() { return 3; }
// Tests global static function generation // Tests global static function generation
DLL_API int Function() DLL_API int Function()
{ {
return 5; return 5;
} }
// Tests properties // Tests properties
struct DLL_API TestProperties struct DLL_API TestProperties
{ {
TestProperties(); TestProperties();
int Field; int Field;
int getFieldValue(); int getFieldValue();
void setFieldValue(int Value); void setFieldValue(int Value);
}; };
TestProperties::TestProperties() : Field(0) {} TestProperties::TestProperties() : Field(0) {}
int TestProperties::getFieldValue() { return Field; } int TestProperties::getFieldValue() { return Field; }
void TestProperties::setFieldValue(int Value) { Field = Value; } void TestProperties::setFieldValue(int Value) { Field = Value; }
class DLL_API TestIndexedProperties class DLL_API TestIndexedProperties
{ {
foo_t p; foo_t p;
TestProperties f; TestProperties f;
public: public:
TestIndexedProperties(); TestIndexedProperties();
// Should lead to a read/write indexer with return type uint // Should lead to a read/write indexer with return type uint
foo_t& operator[](int i); foo_t& operator[](int i);
// Should lead to a read/write indexer with return type uint // Should lead to a read/write indexer with return type uint
foo_t* operator[](float f); foo_t* operator[](float f);
// Should lead to a read-only indexer with return type uint // Should lead to a read-only indexer with return type uint
foo_t operator[](const char* name); foo_t operator[](const char* name);
// Should lead to a read-only indexer with return type uint* // Should lead to a read-only indexer with return type uint*
const foo_t& operator[](double d); const foo_t& operator[](double d);
// Should lead to a read/write indexer with return type TestProperties // Should lead to a read/write indexer with return type TestProperties
TestProperties* operator[](unsigned char b); TestProperties* operator[](unsigned char b);
// Should lead to a read-only indexer with return type TestProperties // Should lead to a read-only indexer with return type TestProperties
const TestProperties& operator[](short b); const TestProperties& operator[](short b);
}; };
TestIndexedProperties::TestIndexedProperties() : p(1), f() {} TestIndexedProperties::TestIndexedProperties() : p(1), f() {}
foo_t& TestIndexedProperties::operator[](int i) { return p; } foo_t& TestIndexedProperties::operator[](int i) { return p; }
foo_t TestIndexedProperties::operator[](const char* name) { return p; } foo_t TestIndexedProperties::operator[](const char* name) { return p; }
foo_t* TestIndexedProperties::operator[](float f) { return &p; } foo_t* TestIndexedProperties::operator[](float f) { return &p; }
const foo_t& TestIndexedProperties::operator[](double f) { return p; } const foo_t& TestIndexedProperties::operator[](double f) { return p; }
TestProperties* TestIndexedProperties::operator[](unsigned char b) { return &f; } TestProperties* TestIndexedProperties::operator[](unsigned char b) { return &f; }
const TestProperties& TestIndexedProperties::operator[](short b) { return f; } const TestProperties& TestIndexedProperties::operator[](short b) { return f; }
enum struct MyEnum { A, B, C }; enum struct MyEnum { A, B, C };
class DLL_API TestArraysPointers class DLL_API TestArraysPointers
{ {
public: public:
TestArraysPointers(MyEnum *values, int count); TestArraysPointers(MyEnum *values, int count);
MyEnum Value; MyEnum Value;
}; };
TestArraysPointers::TestArraysPointers(MyEnum *values, int count) TestArraysPointers::TestArraysPointers(MyEnum *values, int count)
{ {
if (values && count) Value = values[0]; if (values && count) Value = values[0];
} }
struct DLL_API TestGetterSetterToProperties struct DLL_API TestGetterSetterToProperties
{ {
int getWidth(); int getWidth();
int getHeight(); int getHeight();
}; };
int TestGetterSetterToProperties::getWidth() { return 640; } int TestGetterSetterToProperties::getWidth() { return 640; }

6
tests/CSharpTemp/CSharpTemp.cs

@ -62,9 +62,9 @@ namespace CppSharp.Tests
driver.Options.GenerateInterfacesForMultipleInheritance = true; driver.Options.GenerateInterfacesForMultipleInheritance = true;
driver.Options.GeneratePropertiesAdvanced = true; driver.Options.GeneratePropertiesAdvanced = true;
driver.Options.GenerateVirtualTables = true; driver.Options.GenerateVirtualTables = true;
driver.Options.GenerateCopyConstructors = true; driver.Options.GenerateCopyConstructors = true;
// To ensure that calls to constructors in conversion operators // To ensure that calls to constructors in conversion operators
// are not ambiguous with multiple inheritance pass enabled. // are not ambiguous with multiple inheritance pass enabled.
driver.Options.GenerateConversionOperators = true; driver.Options.GenerateConversionOperators = true;
driver.TranslationUnitPasses.AddPass(new TestAttributesPass()); driver.TranslationUnitPasses.AddPass(new TestAttributesPass());
} }

Loading…
Cancel
Save