Browse Source

Feat/code formatting (#1912)

* Add resharper workspace shared settings

* Add formatting settings

- Added `RunClangFormat` shell script
- Added workflow to check if formatting was applied to PR's

* Remove include sorting

* Convert to shell script

* Fix failing tests

* Format all c++ files

* Create .git-blame-ignore-revs

* Update clang-format-check.yml

* Update namespace formatting to inner
pull/1916/head
Jelle 4 months ago committed by GitHub
parent
commit
9d1c484815
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 80
      .clang-format
  2. 90
      .editorconfig
  3. 11
      .git-blame-ignore-revs
  4. 30
      .github/workflows/clang-format-check.yml
  5. 4
      .github/workflows/main.yml
  6. 1
      .gitignore
  7. 5
      CppSharp.sln.DotSettings
  8. 97
      RunClangFormat.sh
  9. 2
      src/CppParser/APValuePrinter.h
  10. 587
      src/CppParser/AST.cpp
  11. 2
      src/CppParser/AST.h
  12. 41
      src/CppParser/ASTNameMangler.cpp
  13. 10
      src/CppParser/ASTNameMangler.h
  14. 5
      src/CppParser/CXXABI.h
  15. 13
      src/CppParser/CppParser.cpp
  16. 10
      src/CppParser/CppParser.h
  17. 18
      src/CppParser/Decl.h
  18. 48
      src/CppParser/ELFDumper.h
  19. 40
      src/CppParser/Helpers.h
  20. 10
      src/CppParser/Link.cpp
  21. 217
      src/CppParser/Parser.cpp
  22. 26
      src/CppParser/Parser.h
  23. 2
      src/CppParser/Sources.cpp
  24. 2
      src/CppParser/Sources.h
  25. 66
      src/CppParser/Target.cpp
  26. 2
      src/CppParser/Target.h
  27. 2
      src/CppParser/Types.h
  28. 6
      src/Generator.Tests/AST/TestAST.cs
  29. 29
      src/Generator/Generators/QuickJS/Runtime/CppSharp_QuickJS.h
  30. 24
      src/Generator/Generators/QuickJS/Runtime/CppSharp_QuickJS_Signal.cpp
  31. 192
      tests/Builtins.h
  32. 6
      tests/Classes.h
  33. 1
      tests/Classes2.h
  34. 6
      tests/Delegates.h
  35. 10
      tests/Enums.h
  36. 45
      tests/Overloads.h
  37. 117
      tests/dotnet/CSharp/AnonTypes.h
  38. 5
      tests/dotnet/CSharp/AnotherUnit.cpp
  39. 6
      tests/dotnet/CSharp/AnotherUnit.h
  40. 255
      tests/dotnet/CSharp/CSharp.cpp
  41. 296
      tests/dotnet/CSharp/CSharp.h
  42. 18
      tests/dotnet/CSharp/CSharpTemplates.cpp
  43. 134
      tests/dotnet/CSharp/CSharpTemplates.h
  44. 9
      tests/dotnet/CSharp/ExcludedUnit.hpp
  45. 11
      tests/dotnet/Common/AnotherUnit.h
  46. 198
      tests/dotnet/Common/Common.cpp
  47. 214
      tests/dotnet/Common/Common.h
  48. 1
      tests/dotnet/Empty/Empty.h
  49. 6
      tests/dotnet/NamespacesBase/NamespacesBase.cpp
  50. 14
      tests/dotnet/NamespacesBase/NamespacesBase.h
  51. 3
      tests/dotnet/NamespacesDerived/Independent.h
  52. 10
      tests/dotnet/NamespacesDerived/NamespacesDerived.cpp
  53. 20
      tests/dotnet/NamespacesDerived/NamespacesDerived.h
  54. 64
      tests/dotnet/Native/AST.h
  55. 3
      tests/dotnet/Native/Enums.h
  56. 25
      tests/dotnet/Native/Passes.h
  57. 1
      tests/dotnet/VTables/VTables.cpp
  58. 1
      tests/dotnet/VTables/VTables.h

80
.clang-format

@ -0,0 +1,80 @@
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-
Language : Cpp
BasedOnStyle : Microsoft
Standard : Latest
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-
AccessModifierOffset : -4
AlignTrailingComments :
Kind : Always
OverEmptyLines : 0
AllowAllParametersOfDeclarationOnNextLine : false
AllowShortBlocksOnASingleLine : Empty
AllowShortIfStatementsOnASingleLine : Never
AllowShortLoopsOnASingleLine : false
AllowShortCaseLabelsOnASingleLine : true
AllowShortFunctionsOnASingleLine : Inline
AllowShortLambdasOnASingleLine : Empty
AlwaysBreakTemplateDeclarations : Yes
BinPackParameters : false
BreakBeforeBraces : Custom
BraceWrapping :
AfterCaseLabel : true
AfterClass : true
AfterControlStatement : Always
AfterEnum : true
AfterFunction : true
AfterNamespace : false
AfterObjCDeclaration : true
AfterStruct : true
AfterUnion : true
AfterExternBlock : true
BeforeCatch : true
BeforeElse : true
BeforeLambdaBody : true
BeforeWhile : true
IndentBraces : false
SplitEmptyFunction : true
SplitEmptyRecord : false
SplitEmptyNamespace : true
BreakAfterAttributes : Leave
BreakBeforeTernaryOperators : false
BreakConstructorInitializers : BeforeComma
BreakBeforeConceptDeclarations : Always
ColumnLimit : 0
Cpp11BracedListStyle : false
CompactNamespaces : true
IndentWidth : 4
IndentCaseLabels : true
IndentRequiresClause : true
SortIncludes : Never
IncludeBlocks : Preserve
KeepEmptyLinesAtTheStartOfBlocks : true
MaxEmptyLinesToKeep : 2
EmptyLineAfterAccessModifier : Leave
EmptyLineBeforeAccessModifier : LogicalBlock
NamespaceIndentation : Inner
PointerAlignment : Left
SpacesBeforeTrailingComments : 1
SpacesInAngles : Never
SpacesInSquareBrackets : false
RequiresClausePosition : OwnLine
RequiresExpressionIndentation : Keyword
SpacesInLineCommentPrefix :
Minimum : 1
Maximum : -1
TabWidth : 4
UseTab : Never
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-
---
Language: CSharp
BasedOnStyle : Microsoft
Standard : Latest

90
.editorconfig

@ -0,0 +1,90 @@
[*.cs]
# IDE0011: Add braces
csharp_prefer_braces = false:silent
# IDE0008: Use explicit type
dotnet_diagnostic.IDE0008.severity = none
csharp_indent_labels = one_less_than_current
csharp_using_directive_placement = outside_namespace:silent
csharp_prefer_simple_using_statement = true:suggestion
csharp_style_namespace_declarations = block_scoped:silent
csharp_style_expression_bodied_methods = false:silent
csharp_style_expression_bodied_constructors = false:silent
csharp_style_expression_bodied_operators = false:silent
csharp_style_expression_bodied_properties = true:silent
csharp_style_expression_bodied_indexers = true:silent
csharp_style_expression_bodied_accessors = true:silent
csharp_style_expression_bodied_lambdas = true:silent
csharp_style_expression_bodied_local_functions = false:silent
csharp_style_throw_expression = true:suggestion
csharp_style_prefer_null_check_over_type_check = true:suggestion
csharp_style_prefer_method_group_conversion = true:silent
csharp_space_around_binary_operators = before_and_after
[*.{cs,vb}]
#### Naming styles ####
# Naming rules
dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.types_should_be_pascal_case.symbols = types
dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
# Symbol specifications
dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.interface.required_modifiers =
dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.types.required_modifiers =
dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.non_field_members.required_modifiers =
# Naming styles
dotnet_naming_style.begins_with_i.required_prefix = I
dotnet_naming_style.begins_with_i.required_suffix =
dotnet_naming_style.begins_with_i.word_separator =
dotnet_naming_style.begins_with_i.capitalization = pascal_case
dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case
dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case
dotnet_style_operator_placement_when_wrapping = beginning_of_line
tab_width = 4
indent_size = 4
end_of_line = lf
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion
dotnet_style_prefer_auto_properties = true:silent
dotnet_style_object_initializer = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
dotnet_style_prefer_conditional_expression_over_assignment = true:silent
dotnet_style_prefer_conditional_expression_over_return = true:silent
dotnet_style_explicit_tuple_names = true:suggestion
dotnet_style_prefer_inferred_tuple_names = true:suggestion
dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
dotnet_style_prefer_compound_assignment = true:suggestion
dotnet_style_prefer_simplified_interpolation = true:suggestion
dotnet_style_namespace_match_folder = true:suggestion

11
.git-blame-ignore-revs

@ -0,0 +1,11 @@
# When making commits that are strictly formatting/style changes, add the
# commit hash here, so git blame can ignore the change. See docs for more
# details:
# https://git-scm.com/docs/git-config#Documentation/git-config.txt-blameignoreRevsFile
#
#
# Example entries:
#
# <full commit hash> # Formating changes
# <full commit hash> # rename something internal
4352a86efc9a0270ecd0c1712c9f470a9bd8fb75 # Format all c++ files

30
.github/workflows/clang-format-check.yml

@ -0,0 +1,30 @@
name: clang-format Check
on: [push, pull_request, workflow_dispatch]
# Cancel any previous workflows if the pull request was updated
concurrency:
group: ${{ github.workflow }}-${{ github.ref || github.run_id }}
cancel-in-progress: true
jobs:
formatting-check:
name: Formatting Check
runs-on: ubuntu-latest
strategy:
matrix:
path:
- 'src'
- 'tests'
steps:
- uses: actions/checkout@v4
- name: Run clang-format style check for C/C++/Protobuf programs.
uses: jidicula/clang-format-action@v4.14.0
with:
clang-format-version: 19
fallback-style: none
check-path: ${{ matrix.path }}
exclude-regex: '(Bindings|CLI)/|(CppParser/(Parse)?(Expr|Stmt))'

4
.github/workflows/main.yml

@ -35,8 +35,6 @@ jobs:
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with:
fetch-depth: '0'
- name: Setup emsdk - name: Setup emsdk
uses: mymindstorm/setup-emsdk@v11 uses: mymindstorm/setup-emsdk@v11
@ -127,8 +125,6 @@ jobs:
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with:
fetch-depth: '0'
- name: Set version - name: Set version
run: nbgv cloud --all-vars run: nbgv cloud --all-vars

1
.gitignore vendored

@ -17,7 +17,6 @@ src/generator/generator
.DS_Store .DS_Store
*.user *.user
*.suo *.suo
*.DotSettings
*.sdf *.sdf
*.opensdf *.opensdf
*.pdb *.pdb

5
CppSharp.sln.DotSettings

@ -0,0 +1,5 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=CLI/@EntryIndexedValue">CLI</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=MSVC/@EntryIndexedValue">MSVC</s:String>
<s:Boolean x:Key="/Default/UserDictionary/Words/=diag/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=undefine/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>

97
RunClangFormat.sh

@ -0,0 +1,97 @@
#!/usr/bin/env bash
set -e
solution_dir=$(cd "$(dirname "$0")"; pwd)
FOLDERS="src tests"
ALLOWED_EXTENSIONS_RE=".*\.\(cpp\|hpp\|c\|h\|inl\)"
EXCLUSION_RE="\(Bindings\|CLI\)/\|\(CppParser/\(Parse\)?\(Expr\|Stmt\)\)"
CLANG_FORMAT_OPTIONS="--fallback-style=none -i --verbose"
clang_format=""
VS_INSTALL_DIR=""
format()
{
find_clang_format
DRY_RUN=0
# read -p "Dry run? (1/0): " DRY_RUN
if [ "$DRY_RUN" -eq 1 ]; then
CLANG_FORMAT_OPTIONS="$CLANG_FORMAT_OPTIONS --dry-run --Werror"
fi
# Format all files, in the specified list of directories
# Loop through each file in the directory (and subdirectories)
for p in $FOLDERS; do
echo "Formatting files in folder \"$p\"..."
cd "$solution_dir/$p"
file_list=$(find . -type f -regex $ALLOWED_EXTENSIONS_RE -and -not -regex ".*/\($EXCLUSION_RE\).*" -print)
"$clang_format" $CLANG_FORMAT_OPTIONS $file_list
cd ..
done
}
find_vswhere()
{
echo "Looking for 'vswhere'..."
VSWHERE_PATH="$(printenv 'ProgramFiles(x86)')/Microsoft Visual Studio/Installer/vswhere.exe"
if [ -x "$(command -v vswhere.exe)" ]; then
vswhere="vswhere.exe"
elif [ -f "$VSWHERE_PATH" ]; then
vswhere=$VSWHERE_PATH
else
echo -e "Could not locate vswhere.exe at:\n " $VSWHERE_PATH
read -n 1 -s -r -p "Press any key to continue, or Ctrl+C to exit" key
exit 1
fi
echo -e "Found 'vswhere.exe':\n @" $vswhere "\n"
}
find_visual_studio()
{
find_vswhere
echo "Looking for visual studio..."
# Find visual studio installation path
VS_INSTALL_DIR=$("$vswhere" -latest -property installationPath)
# Find visual studio installation path
if [ ! -d "$VS_INSTALL_DIR" ]; then
echo -e "Visual Studio Installation directory not found at vswhere specified path:\n " $VS_INSTALL_DIR
read -n 1 -s -r -p "Press any key to continue, or Ctrl+C to exit" key
exit 1
fi
echo -e "Found Visual Studio:\n @" $VS_INSTALL_DIR "\n"
}
find_clang_format()
{
echo "Looking for clang-format..."
find_visual_studio
CLANG_FORMAT_PATH="VC/Tools/Llvm/bin/clang-format.exe"
clang_format="$VS_INSTALL_DIR/$CLANG_FORMAT_PATH"
# Verify clang-format actually exists as well
if ! [ -f "$clang_format" ]; then
echo "clang-format.exe could not be located at: $clang_format"
read -n 1 -s -r -p "Press any key to continue, or Ctrl+C to exit" key
exit 1
fi
echo -e "Found clang-format.exe:\n" " Using" $("$clang_format" --version) "\n" " @" $clang_format "\n"
}
format
echo "Done!"
read -n 1 -s -r -p "Press any key to continue, or Ctrl+C to exit" key
exit 0

2
src/CppParser/APValuePrinter.h

@ -88,4 +88,4 @@ namespace CppSharp { namespace CppParser {
return false; return false;
} }
}; };
} } }} // namespace CppSharp::CppParser

587
src/CppParser/AST.cpp

@ -12,12 +12,14 @@
#include <llvm/Support/Path.h> #include <llvm/Support/Path.h>
// copy from widenPath ('llvm/lib/Support/Windows/Path.inc') // copy from widenPath ('llvm/lib/Support/Windows/Path.inc')
static std::string normalizePath(const std::string & File) { static std::string normalizePath(const std::string& File)
{
llvm::SmallString<2 * 128> Result; llvm::SmallString<2 * 128> Result;
for (llvm::sys::path::const_iterator I = llvm::sys::path::begin(File), for (llvm::sys::path::const_iterator I = llvm::sys::path::begin(File),
E = llvm::sys::path::end(File); E = llvm::sys::path::end(File);
I != E; ++I) { I != E; ++I)
{
if (I->size() == 1 && *I == ".") if (I->size() == 1 && *I == ".")
continue; continue;
if (I->size() == 2 && *I == "..") if (I->size() == 2 && *I == "..")
@ -35,15 +37,18 @@ static std::string normalizePath(const std::string & File) {
} }
template <typename T> template <typename T>
static std::vector<T> split(const T & str, const T & delimiters) { static std::vector<T> split(const T& str, const T& delimiters)
{
std::vector<T> v; std::vector<T> v;
if (str.length() == 0) { if (str.length() == 0)
{
v.push_back(str); v.push_back(str);
return v; return v;
} }
typename T::size_type start = 0; typename T::size_type start = 0;
auto pos = str.find_first_of(delimiters, start); auto pos = str.find_first_of(delimiters, start);
while(pos != T::npos) { while (pos != T::npos)
{
if (pos != start) // ignore empty tokens if (pos != start) // ignore empty tokens
v.emplace_back(str, start, pos - start); v.emplace_back(str, start, pos - start);
start = pos + 1; start = pos + 1;
@ -80,14 +85,32 @@ static void deleteExpression(ExpressionObsolete* expression)
} }
} }
Type::Type(TypeKind kind) : kind(kind) {} Type::Type(TypeKind kind)
Type::Type(const Type& rhs) : kind(rhs.kind), isDependent(rhs.isDependent) {} : kind(kind)
{
}
Type::Type(const Type& rhs)
: kind(rhs.kind)
, isDependent(rhs.isDependent)
{
}
QualifiedType::QualifiedType() : type(0) {} QualifiedType::QualifiedType()
: type(0)
{
}
TagType::TagType() : Type(TypeKind::Tag) {} TagType::TagType()
: Type(TypeKind::Tag)
{
}
ArrayType::ArrayType() : Type(TypeKind::Array), size(0), elementSize(0) {} ArrayType::ArrayType()
: Type(TypeKind::Array)
, size(0)
, elementSize(0)
{
}
FunctionType::FunctionType() FunctionType::FunctionType()
: Type(TypeKind::Function) : Type(TypeKind::Function)
@ -100,15 +123,31 @@ FunctionType::~FunctionType() {}
DEF_VECTOR(FunctionType, Parameter*, Parameters) DEF_VECTOR(FunctionType, Parameter*, Parameters)
PointerType::PointerType() : Type(TypeKind::Pointer) {} PointerType::PointerType()
: Type(TypeKind::Pointer)
{
}
MemberPointerType::MemberPointerType() : Type(TypeKind::MemberPointer) {} MemberPointerType::MemberPointerType()
: Type(TypeKind::MemberPointer)
{
}
TypedefType::TypedefType() : Type(TypeKind::Typedef), declaration(0) {} TypedefType::TypedefType()
: Type(TypeKind::Typedef)
, declaration(0)
{
}
AttributedType::AttributedType() : Type(TypeKind::Attributed) {} AttributedType::AttributedType()
: Type(TypeKind::Attributed)
{
}
DecayedType::DecayedType() : Type(TypeKind::Decayed) {} DecayedType::DecayedType()
: Type(TypeKind::Decayed)
{
}
// Template // Template
TemplateParameter::TemplateParameter(DeclarationKind kind) TemplateParameter::TemplateParameter(DeclarationKind kind)
@ -173,36 +212,61 @@ NonTypeTemplateParameter::~NonTypeTemplateParameter()
deleteExpression(defaultArgument); deleteExpression(defaultArgument);
} }
TemplateArgument::TemplateArgument() : declaration(0), integral(0) {} TemplateArgument::TemplateArgument()
: declaration(0)
, integral(0)
{
}
TemplateSpecializationType::TemplateSpecializationType() TemplateSpecializationType::TemplateSpecializationType()
: Type(TypeKind::TemplateSpecialization), _template(0) {} : Type(TypeKind::TemplateSpecialization)
, _template(0)
{
}
TemplateSpecializationType::TemplateSpecializationType( TemplateSpecializationType::TemplateSpecializationType(
const TemplateSpecializationType& rhs) : Type(rhs), const TemplateSpecializationType& rhs)
Arguments(rhs.Arguments), _template(rhs._template), desugared(rhs.desugared) {} : Type(rhs)
, Arguments(rhs.Arguments)
, _template(rhs._template)
, desugared(rhs.desugared)
{
}
TemplateSpecializationType::~TemplateSpecializationType() {} TemplateSpecializationType::~TemplateSpecializationType() {}
DEF_VECTOR(TemplateSpecializationType, TemplateArgument, Arguments) DEF_VECTOR(TemplateSpecializationType, TemplateArgument, Arguments)
DependentTemplateSpecializationType::DependentTemplateSpecializationType() DependentTemplateSpecializationType::DependentTemplateSpecializationType()
: Type(TypeKind::DependentTemplateSpecialization) {} : Type(TypeKind::DependentTemplateSpecialization)
{
}
DependentTemplateSpecializationType::DependentTemplateSpecializationType( DependentTemplateSpecializationType::DependentTemplateSpecializationType(
const DependentTemplateSpecializationType& rhs) : Type(rhs), const DependentTemplateSpecializationType& rhs)
Arguments(rhs.Arguments), desugared(rhs.desugared) {} : Type(rhs)
, Arguments(rhs.Arguments)
, desugared(rhs.desugared)
{
}
DependentTemplateSpecializationType::~DependentTemplateSpecializationType() {} DependentTemplateSpecializationType::~DependentTemplateSpecializationType() {}
DEF_VECTOR(DependentTemplateSpecializationType, TemplateArgument, Arguments) DEF_VECTOR(DependentTemplateSpecializationType, TemplateArgument, Arguments)
TemplateParameterType::TemplateParameterType() : Type(TypeKind::TemplateParameter), parameter(0) {} TemplateParameterType::TemplateParameterType()
: Type(TypeKind::TemplateParameter)
, parameter(0)
{
}
TemplateParameterType::~TemplateParameterType() {} TemplateParameterType::~TemplateParameterType() {}
TemplateParameterSubstitutionType::TemplateParameterSubstitutionType() TemplateParameterSubstitutionType::TemplateParameterSubstitutionType()
: Type(TypeKind::TemplateParameterSubstitution), replacedParameter(0) {} : Type(TypeKind::TemplateParameterSubstitution)
, replacedParameter(0)
{
}
InjectedClassNameType::InjectedClassNameType() InjectedClassNameType::InjectedClassNameType()
: Type(TypeKind::InjectedClassName) : Type(TypeKind::InjectedClassName)
@ -210,35 +274,74 @@ InjectedClassNameType::InjectedClassNameType()
{ {
} }
DependentNameType::DependentNameType() : Type(TypeKind::DependentName) {} DependentNameType::DependentNameType()
: Type(TypeKind::DependentName)
{
}
DependentNameType::~DependentNameType() {} DependentNameType::~DependentNameType() {}
PackExpansionType::PackExpansionType() : Type(TypeKind::PackExpansion) {} PackExpansionType::PackExpansionType()
: Type(TypeKind::PackExpansion)
{
}
UnaryTransformType::UnaryTransformType() : Type(TypeKind::UnaryTransform) {} UnaryTransformType::UnaryTransformType()
: Type(TypeKind::UnaryTransform)
{
}
UnresolvedUsingType::UnresolvedUsingType() : Type(TypeKind::UnresolvedUsing) {} UnresolvedUsingType::UnresolvedUsingType()
: Type(TypeKind::UnresolvedUsing)
{
}
VectorType::VectorType() : Type(TypeKind::Vector), numElements(0) {} VectorType::VectorType()
: Type(TypeKind::Vector)
, numElements(0)
{
}
BuiltinType::BuiltinType() : CppSharp::CppParser::AST::Type(TypeKind::Builtin) {} BuiltinType::BuiltinType()
: CppSharp::CppParser::AST::Type(TypeKind::Builtin)
{
}
VTableComponent::VTableComponent() : offset(0), declaration(0) {} VTableComponent::VTableComponent()
: offset(0)
, declaration(0)
{
}
// VTableLayout // VTableLayout
VTableLayout::VTableLayout() {} VTableLayout::VTableLayout() {}
VTableLayout::VTableLayout(const VTableLayout& rhs) : Components(rhs.Components) {} VTableLayout::VTableLayout(const VTableLayout& rhs)
: Components(rhs.Components)
{
}
VTableLayout::~VTableLayout() {} VTableLayout::~VTableLayout() {}
DEF_VECTOR(VTableLayout, VTableComponent, Components) DEF_VECTOR(VTableLayout, VTableComponent, Components)
VFTableInfo::VFTableInfo() : VBTableIndex(0), VFPtrOffset(0), VFPtrFullOffset(0) {} VFTableInfo::VFTableInfo()
VFTableInfo::VFTableInfo(const VFTableInfo& rhs) : VBTableIndex(rhs.VBTableIndex), : VBTableIndex(0)
VFPtrOffset(rhs.VFPtrOffset), VFPtrFullOffset(rhs.VFPtrFullOffset), , VFPtrOffset(0)
layout(rhs.layout) {} , VFPtrFullOffset(0)
{
}
VFTableInfo::VFTableInfo(const VFTableInfo& rhs)
: VBTableIndex(rhs.VBTableIndex)
, VFPtrOffset(rhs.VFPtrOffset)
, VFPtrFullOffset(rhs.VFPtrFullOffset)
, layout(rhs.layout)
{
}
LayoutField::LayoutField() : offset(0), fieldPtr(0) {} LayoutField::LayoutField()
: offset(0)
, fieldPtr(0)
{
}
LayoutField::LayoutField(const LayoutField& other) LayoutField::LayoutField(const LayoutField& other)
: offset(other.offset) : offset(other.offset)
@ -250,14 +353,30 @@ LayoutField::LayoutField(const LayoutField & other)
LayoutField::~LayoutField() {} LayoutField::~LayoutField() {}
LayoutBase::LayoutBase() : offset(0), _class(0) {} LayoutBase::LayoutBase()
: offset(0)
, _class(0)
{
}
LayoutBase::LayoutBase(const LayoutBase& other) : offset(other.offset), _class(other._class) {} LayoutBase::LayoutBase(const LayoutBase& other)
: offset(other.offset)
, _class(other._class)
{
}
LayoutBase::~LayoutBase() {} LayoutBase::~LayoutBase() {}
ClassLayout::ClassLayout() : ABI(CppAbi::Itanium), argABI(RecordArgABI::Default), ClassLayout::ClassLayout()
hasOwnVFPtr(false), VBPtrOffset(0), alignment(0), size(0), dataSize(0) {} : ABI(CppAbi::Itanium)
, argABI(RecordArgABI::Default)
, hasOwnVFPtr(false)
, VBPtrOffset(0)
, alignment(0)
, size(0)
, dataSize(0)
{
}
DEF_VECTOR(ClassLayout, VFTableInfo, VFTables) DEF_VECTOR(ClassLayout, VFTableInfo, VFTables)
@ -318,7 +437,8 @@ DEF_VECTOR(Declaration, Declaration*, Redeclarations)
DeclarationContext::DeclarationContext(DeclarationKind kind) DeclarationContext::DeclarationContext(DeclarationKind kind)
: Declaration(kind) : Declaration(kind)
, isAnonymous(false) , isAnonymous(false)
{} {
}
DEF_VECTOR(DeclarationContext, Namespace*, Namespaces) DEF_VECTOR(DeclarationContext, Namespace*, Namespaces)
DEF_VECTOR(DeclarationContext, Enumeration*, Enums) DEF_VECTOR(DeclarationContext, Enumeration*, Enums)
@ -352,7 +472,8 @@ DeclarationContext::FindNamespace(const std::vector<std::string>& Namespaces)
auto childNamespace = std::find_if(currentNamespace->Namespaces.begin(), auto childNamespace = std::find_if(currentNamespace->Namespaces.begin(),
currentNamespace->Namespaces.end(), currentNamespace->Namespaces.end(),
[&](CppSharp::CppParser::AST::Namespace* ns) { [&](CppSharp::CppParser::AST::Namespace* ns)
{
return ns->name == _namespace; return ns->name == _namespace;
}); });
@ -382,18 +503,22 @@ Namespace* DeclarationContext::FindCreateNamespace(const std::string& Name)
} }
Class* DeclarationContext::FindClass(const void* OriginalPtr, Class* DeclarationContext::FindClass(const void* OriginalPtr,
const std::string& Name, bool IsComplete) const std::string& Name,
bool IsComplete)
{ {
if (Name.empty()) return nullptr; if (Name.empty())
return nullptr;
auto entries = split<std::string>(Name, "::"); auto entries = split<std::string>(Name, "::");
if (entries.size() == 1) if (entries.size() == 1)
{ {
auto _class = std::find_if(Classes.begin(), Classes.end(), auto _class = std::find_if(Classes.begin(), Classes.end(),
[OriginalPtr, Name, IsComplete](Class* klass) { [OriginalPtr, Name, IsComplete](Class* klass)
{
return (OriginalPtr && klass->originalPtr == OriginalPtr) || return (OriginalPtr && klass->originalPtr == OriginalPtr) ||
(klass->name == Name && klass->isIncomplete == !IsComplete); }); (klass->name == Name && klass->isIncomplete == !IsComplete);
});
return _class != Classes.end() ? *_class : nullptr; return _class != Classes.end() ? *_class : nullptr;
} }
@ -421,7 +546,9 @@ Class* DeclarationContext::CreateClass(const std::string& Name, bool IsComplete)
} }
Class* DeclarationContext::FindClass(const void* OriginalPtr, Class* DeclarationContext::FindClass(const void* OriginalPtr,
const std::string& Name, bool IsComplete, bool Create) const std::string& Name,
bool IsComplete,
bool Create)
{ {
auto _class = FindClass(OriginalPtr, Name, IsComplete); auto _class = FindClass(OriginalPtr, Name, IsComplete);
@ -442,7 +569,10 @@ Class* DeclarationContext::FindClass(const void* OriginalPtr,
Enumeration* DeclarationContext::FindEnum(const void* OriginalPtr) Enumeration* DeclarationContext::FindEnum(const void* OriginalPtr)
{ {
auto foundEnum = std::find_if(Enums.begin(), Enums.end(), auto foundEnum = std::find_if(Enums.begin(), Enums.end(),
[&](Enumeration* enumeration) { return enumeration->originalPtr == OriginalPtr; }); [&](Enumeration* enumeration)
{
return enumeration->originalPtr == OriginalPtr;
});
if (foundEnum != Enums.end()) if (foundEnum != Enums.end())
return *foundEnum; return *foundEnum;
@ -457,7 +587,10 @@ Enumeration* DeclarationContext::FindEnum(const std::string& Name, bool Create)
if (entries.size() == 1) if (entries.size() == 1)
{ {
auto foundEnum = std::find_if(Enums.begin(), Enums.end(), auto foundEnum = std::find_if(Enums.begin(), Enums.end(),
[&](Enumeration* _enum) { return _enum->name == Name; }); [&](Enumeration* _enum)
{
return _enum->name == Name;
});
if (foundEnum != Enums.end()) if (foundEnum != Enums.end())
return *foundEnum; return *foundEnum;
@ -487,7 +620,10 @@ Enumeration* DeclarationContext::FindEnum(const std::string& Name, bool Create)
Enumeration* DeclarationContext::FindEnumWithItem(const std::string& Name) Enumeration* DeclarationContext::FindEnumWithItem(const std::string& Name)
{ {
auto foundEnumIt = std::find_if(Enums.begin(), Enums.end(), auto foundEnumIt = std::find_if(Enums.begin(), Enums.end(),
[&](Enumeration* _enum) { return _enum->FindItemByName(Name) != nullptr; }); [&](Enumeration* _enum)
{
return _enum->FindItemByName(Name) != nullptr;
});
if (foundEnumIt != Enums.end()) if (foundEnumIt != Enums.end())
return *foundEnumIt; return *foundEnumIt;
for (auto it = Namespaces.begin(); it != Namespaces.end(); ++it) for (auto it = Namespaces.begin(); it != Namespaces.end(); ++it)
@ -508,13 +644,19 @@ Enumeration* DeclarationContext::FindEnumWithItem(const std::string& Name)
Function* DeclarationContext::FindFunction(const std::string& USR) Function* DeclarationContext::FindFunction(const std::string& USR)
{ {
auto foundFunction = std::find_if(Functions.begin(), Functions.end(), auto foundFunction = std::find_if(Functions.begin(), Functions.end(),
[&](Function* func) { return func->USR == USR; }); [&](Function* func)
{
return func->USR == USR;
});
if (foundFunction != Functions.end()) if (foundFunction != Functions.end())
return *foundFunction; return *foundFunction;
auto foundTemplate = std::find_if(Templates.begin(), Templates.end(), auto foundTemplate = std::find_if(Templates.begin(), Templates.end(),
[&](Template* t) { return t->TemplatedDecl && t->TemplatedDecl->USR == USR; }); [&](Template* t)
{
return t->TemplatedDecl && t->TemplatedDecl->USR == USR;
});
if (foundTemplate != Templates.end()) if (foundTemplate != Templates.end())
return static_cast<Function*>((*foundTemplate)->TemplatedDecl); return static_cast<Function*>((*foundTemplate)->TemplatedDecl);
@ -525,7 +667,10 @@ Function* DeclarationContext::FindFunction(const std::string& USR)
TypedefDecl* DeclarationContext::FindTypedef(const std::string& Name, bool Create) TypedefDecl* DeclarationContext::FindTypedef(const std::string& Name, bool Create)
{ {
auto foundTypedef = std::find_if(Typedefs.begin(), Typedefs.end(), auto foundTypedef = std::find_if(Typedefs.begin(), Typedefs.end(),
[&](TypedefDecl* tdef) { return tdef->name == Name; }); [&](TypedefDecl* tdef)
{
return tdef->name == Name;
});
if (foundTypedef != Typedefs.end()) if (foundTypedef != Typedefs.end())
return *foundTypedef; return *foundTypedef;
@ -543,7 +688,10 @@ TypedefDecl* DeclarationContext::FindTypedef(const std::string& Name, bool Creat
TypeAlias* DeclarationContext::FindTypeAlias(const std::string& Name, bool Create) TypeAlias* DeclarationContext::FindTypeAlias(const std::string& Name, bool Create)
{ {
auto foundTypeAlias = std::find_if(TypeAliases.begin(), TypeAliases.end(), auto foundTypeAlias = std::find_if(TypeAliases.begin(), TypeAliases.end(),
[&](TypeAlias* talias) { return talias->name == Name; }); [&](TypeAlias* talias)
{
return talias->name == Name;
});
if (foundTypeAlias != TypeAliases.end()) if (foundTypeAlias != TypeAliases.end())
return *foundTypeAlias; return *foundTypeAlias;
@ -561,7 +709,10 @@ TypeAlias* DeclarationContext::FindTypeAlias(const std::string& Name, bool Creat
Variable* DeclarationContext::FindVariable(const std::string& USR) Variable* DeclarationContext::FindVariable(const std::string& USR)
{ {
auto found = std::find_if(Variables.begin(), Variables.end(), auto found = std::find_if(Variables.begin(), Variables.end(),
[&](Variable* var) { return var->USR == USR; }); [&](Variable* var)
{
return var->USR == USR;
});
if (found != Variables.end()) if (found != Variables.end())
return *found; return *found;
@ -572,7 +723,10 @@ Variable* DeclarationContext::FindVariable(const std::string& USR)
Friend* DeclarationContext::FindFriend(const std::string& USR) Friend* DeclarationContext::FindFriend(const std::string& USR)
{ {
auto found = std::find_if(Friends.begin(), Friends.end(), auto found = std::find_if(Friends.begin(), Friends.end(),
[&](Friend* var) { return var->USR == USR; }); [&](Friend* var)
{
return var->USR == USR;
});
if (found != Friends.end()) if (found != Friends.end())
return *found; return *found;
@ -580,29 +734,55 @@ Friend* DeclarationContext::FindFriend(const std::string& USR)
return nullptr; return nullptr;
} }
TypedefNameDecl::TypedefNameDecl(DeclarationKind Kind) : Declaration(Kind) {} TypedefNameDecl::TypedefNameDecl(DeclarationKind Kind)
: Declaration(Kind)
{
}
TypedefNameDecl::~TypedefNameDecl() {} TypedefNameDecl::~TypedefNameDecl() {}
TypedefDecl::TypedefDecl() : TypedefNameDecl(DeclarationKind::Typedef) {} TypedefDecl::TypedefDecl()
: TypedefNameDecl(DeclarationKind::Typedef)
{
}
TypedefDecl::~TypedefDecl() {} TypedefDecl::~TypedefDecl() {}
TypeAlias::TypeAlias() : TypedefNameDecl(DeclarationKind::TypeAlias), describedAliasTemplate(0) {} TypeAlias::TypeAlias()
: TypedefNameDecl(DeclarationKind::TypeAlias)
, describedAliasTemplate(0)
{
}
TypeAlias::~TypeAlias() {} TypeAlias::~TypeAlias() {}
Friend::Friend() : CppSharp::CppParser::AST::Declaration(DeclarationKind::Friend), declaration(0) {} Friend::Friend()
: CppSharp::CppParser::AST::Declaration(DeclarationKind::Friend)
, declaration(0)
{
}
Friend::~Friend() {} Friend::~Friend() {}
StatementObsolete::StatementObsolete(const std::string& str, StatementClassObsolete stmtClass, Declaration* decl) : string(str), _class(stmtClass), decl(decl) {} StatementObsolete::StatementObsolete(const std::string& str, StatementClassObsolete stmtClass, Declaration* decl)
: string(str)
, _class(stmtClass)
, decl(decl)
{
}
ExpressionObsolete::ExpressionObsolete(const std::string& str, StatementClassObsolete stmtClass, Declaration* decl) ExpressionObsolete::ExpressionObsolete(const std::string& str, StatementClassObsolete stmtClass, Declaration* decl)
: StatementObsolete(str, stmtClass, decl) {} : StatementObsolete(str, stmtClass, decl)
{
}
BinaryOperatorObsolete::BinaryOperatorObsolete(const std::string& str, ExpressionObsolete* lhs, ExpressionObsolete* rhs, const std::string& opcodeStr) BinaryOperatorObsolete::BinaryOperatorObsolete(const std::string& str, ExpressionObsolete* lhs, ExpressionObsolete* rhs, const std::string& opcodeStr)
: ExpressionObsolete(str, StatementClassObsolete::BinaryOperator), LHS(lhs), RHS(rhs), opcodeStr(opcodeStr) {} : ExpressionObsolete(str, StatementClassObsolete::BinaryOperator)
, LHS(lhs)
, RHS(rhs)
, opcodeStr(opcodeStr)
{
}
BinaryOperatorObsolete::~BinaryOperatorObsolete() BinaryOperatorObsolete::~BinaryOperatorObsolete()
{ {
@ -612,7 +792,9 @@ BinaryOperatorObsolete::~BinaryOperatorObsolete()
CallExprObsolete::CallExprObsolete(const std::string& str, Declaration* decl) CallExprObsolete::CallExprObsolete(const std::string& str, Declaration* decl)
: ExpressionObsolete(str, StatementClassObsolete::CallExprClass, decl) {} : ExpressionObsolete(str, StatementClassObsolete::CallExprClass, decl)
{
}
CallExprObsolete::~CallExprObsolete() CallExprObsolete::~CallExprObsolete()
{ {
@ -623,7 +805,9 @@ CallExprObsolete::~CallExprObsolete()
DEF_VECTOR(CallExprObsolete, ExpressionObsolete*, Arguments) DEF_VECTOR(CallExprObsolete, ExpressionObsolete*, Arguments)
CXXConstructExprObsolete::CXXConstructExprObsolete(const std::string& str, Declaration* decl) CXXConstructExprObsolete::CXXConstructExprObsolete(const std::string& str, Declaration* decl)
: ExpressionObsolete(str, StatementClassObsolete::CXXConstructExprClass, decl) {} : ExpressionObsolete(str, StatementClassObsolete::CXXConstructExprClass, decl)
{
}
CXXConstructExprObsolete::~CXXConstructExprObsolete() CXXConstructExprObsolete::~CXXConstructExprObsolete()
{ {
@ -689,43 +873,73 @@ DEF_VECTOR(Method, Method*, OverriddenMethods)
// Enumeration // Enumeration
Enumeration::Enumeration() : DeclarationContext(DeclarationKind::Enumeration), Enumeration::Enumeration()
modifiers((EnumModifiers)0), type(0), builtinType(0) {} : DeclarationContext(DeclarationKind::Enumeration)
, modifiers((EnumModifiers)0)
, type(0)
, builtinType(0)
{
}
Enumeration::~Enumeration() {} Enumeration::~Enumeration() {}
DEF_VECTOR(Enumeration, Enumeration::Item*, Items) DEF_VECTOR(Enumeration, Enumeration::Item*, Items)
Enumeration::Item::Item() : Declaration(DeclarationKind::EnumerationItem) {} Enumeration::Item::Item()
: Declaration(DeclarationKind::EnumerationItem)
{
}
Enumeration::Item::Item(const Item& rhs) : Declaration(rhs), Enumeration::Item::Item(const Item& rhs)
expression(rhs.expression), value(rhs.value) {} : Declaration(rhs)
, expression(rhs.expression)
, value(rhs.value)
{
}
Enumeration::Item::~Item() {} Enumeration::Item::~Item() {}
Enumeration::Item* Enumeration::FindItemByName(const std::string& Name) Enumeration::Item* Enumeration::FindItemByName(const std::string& Name)
{ {
auto foundEnumItem = std::find_if(Items.begin(), Items.end(), auto foundEnumItem = std::find_if(Items.begin(), Items.end(),
[&](Item* _item) { return _item->name == Name; }); [&](Item* _item)
{
return _item->name == Name;
});
if (foundEnumItem != Items.end()) if (foundEnumItem != Items.end())
return *foundEnumItem; return *foundEnumItem;
return nullptr; return nullptr;
} }
Variable::Variable() : Declaration(DeclarationKind::Variable), Variable::Variable()
isConstExpr(false), initializer(0) {} : Declaration(DeclarationKind::Variable)
, isConstExpr(false)
, initializer(0)
{
}
Variable::~Variable() {} Variable::~Variable() {}
BaseClassSpecifier::BaseClassSpecifier() : type(0), offset(0) {} BaseClassSpecifier::BaseClassSpecifier()
: type(0)
, offset(0)
{
}
Field::Field() : Declaration(DeclarationKind::Field), _class(0), Field::Field()
isBitField(false), bitWidth(0) {} : Declaration(DeclarationKind::Field)
, _class(0)
, isBitField(false)
, bitWidth(0)
{
}
Field::~Field() {} Field::~Field() {}
AccessSpecifierDecl::AccessSpecifierDecl() AccessSpecifierDecl::AccessSpecifierDecl()
: Declaration(DeclarationKind::AccessSpecifier) {} : Declaration(DeclarationKind::AccessSpecifier)
{
}
AccessSpecifierDecl::~AccessSpecifierDecl() {} AccessSpecifierDecl::~AccessSpecifierDecl() {}
@ -757,18 +971,31 @@ DEF_VECTOR(Class, Field*, Fields)
DEF_VECTOR(Class, Method*, Methods) DEF_VECTOR(Class, Method*, Methods)
DEF_VECTOR(Class, AccessSpecifierDecl*, Specifiers) DEF_VECTOR(Class, AccessSpecifierDecl*, Specifiers)
Template::Template() : Declaration(DeclarationKind::Template), Template::Template()
TemplatedDecl(0) {} : Declaration(DeclarationKind::Template)
, TemplatedDecl(0)
{
}
Template::Template(DeclarationKind kind) : Declaration(kind), TemplatedDecl(0) {} Template::Template(DeclarationKind kind)
: Declaration(kind)
, TemplatedDecl(0)
{
}
DEF_VECTOR(Template, Declaration*, Parameters) DEF_VECTOR(Template, Declaration*, Parameters)
TypeAliasTemplate::TypeAliasTemplate() : Template(DeclarationKind::TypeAliasTemplate) {} TypeAliasTemplate::TypeAliasTemplate()
: Template(DeclarationKind::TypeAliasTemplate)
{
}
TypeAliasTemplate::~TypeAliasTemplate() {} TypeAliasTemplate::~TypeAliasTemplate() {}
ClassTemplate::ClassTemplate() : Template(DeclarationKind::ClassTemplate) {} ClassTemplate::ClassTemplate()
: Template(DeclarationKind::ClassTemplate)
{
}
ClassTemplate::~ClassTemplate() {} ClassTemplate::~ClassTemplate() {}
@ -795,7 +1022,10 @@ ClassTemplatePartialSpecialization::~ClassTemplatePartialSpecialization() {}
DEF_VECTOR(ClassTemplatePartialSpecialization, Declaration*, Parameters) DEF_VECTOR(ClassTemplatePartialSpecialization, Declaration*, Parameters)
FunctionTemplate::FunctionTemplate() : Template(DeclarationKind::FunctionTemplate) {} FunctionTemplate::FunctionTemplate()
: Template(DeclarationKind::FunctionTemplate)
{
}
FunctionTemplate::~FunctionTemplate() {} FunctionTemplate::~FunctionTemplate() {}
@ -804,7 +1034,10 @@ DEF_VECTOR(FunctionTemplate, FunctionTemplateSpecialization*, Specializations)
FunctionTemplateSpecialization* FunctionTemplate::FindSpecialization(const std::string& usr) FunctionTemplateSpecialization* FunctionTemplate::FindSpecialization(const std::string& usr)
{ {
auto foundSpec = std::find_if(Specializations.begin(), Specializations.end(), auto foundSpec = std::find_if(Specializations.begin(), Specializations.end(),
[&](FunctionTemplateSpecialization* cts) { return cts->specializedFunction->USR == usr; }); [&](FunctionTemplateSpecialization* cts)
{
return cts->specializedFunction->USR == usr;
});
if (foundSpec != Specializations.end()) if (foundSpec != Specializations.end())
return static_cast<FunctionTemplateSpecialization*>(*foundSpec); return static_cast<FunctionTemplateSpecialization*>(*foundSpec);
@ -824,7 +1057,10 @@ FunctionTemplateSpecialization::~FunctionTemplateSpecialization()
DEF_VECTOR(FunctionTemplateSpecialization, TemplateArgument, Arguments) DEF_VECTOR(FunctionTemplateSpecialization, TemplateArgument, Arguments)
VarTemplate::VarTemplate() : Template(DeclarationKind::VarTemplate) {} VarTemplate::VarTemplate()
: Template(DeclarationKind::VarTemplate)
{
}
VarTemplate::~VarTemplate() {} VarTemplate::~VarTemplate() {}
@ -833,7 +1069,10 @@ DEF_VECTOR(VarTemplate, VarTemplateSpecialization*, Specializations)
VarTemplateSpecialization* VarTemplate::FindSpecialization(const std::string& usr) VarTemplateSpecialization* VarTemplate::FindSpecialization(const std::string& usr)
{ {
auto foundSpec = std::find_if(Specializations.begin(), Specializations.end(), auto foundSpec = std::find_if(Specializations.begin(), Specializations.end(),
[&](VarTemplateSpecialization* cts) { return cts->USR == usr; }); [&](VarTemplateSpecialization* cts)
{
return cts->USR == usr;
});
if (foundSpec != Specializations.end()) if (foundSpec != Specializations.end())
return static_cast<VarTemplateSpecialization*>(*foundSpec); return static_cast<VarTemplateSpecialization*>(*foundSpec);
@ -870,7 +1109,10 @@ VarTemplatePartialSpecialization::~VarTemplatePartialSpecialization()
{ {
} }
UnresolvedUsingTypename::UnresolvedUsingTypename() : Declaration(DeclarationKind::UnresolvedUsingTypename) {} UnresolvedUsingTypename::UnresolvedUsingTypename()
: Declaration(DeclarationKind::UnresolvedUsingTypename)
{
}
UnresolvedUsingTypename::~UnresolvedUsingTypename() {} UnresolvedUsingTypename::~UnresolvedUsingTypename() {}
@ -883,25 +1125,41 @@ Namespace::Namespace()
Namespace::~Namespace() {} Namespace::~Namespace() {}
PreprocessedEntity::PreprocessedEntity() PreprocessedEntity::PreprocessedEntity()
: macroLocation(AST::MacroLocation::Unknown), : macroLocation(AST::MacroLocation::Unknown)
originalPtr(0), kind(DeclarationKind::PreprocessedEntity) {} , originalPtr(0)
, kind(DeclarationKind::PreprocessedEntity)
{
}
MacroDefinition::MacroDefinition() MacroDefinition::MacroDefinition()
: lineNumberStart(0), lineNumberEnd(0) { kind = DeclarationKind::MacroDefinition; } : lineNumberStart(0)
, lineNumberEnd(0)
{
kind = DeclarationKind::MacroDefinition;
}
MacroDefinition::~MacroDefinition() {} MacroDefinition::~MacroDefinition() {}
MacroExpansion::MacroExpansion() : definition(0) { kind = DeclarationKind::MacroExpansion; } MacroExpansion::MacroExpansion()
: definition(0)
{
kind = DeclarationKind::MacroExpansion;
}
MacroExpansion::~MacroExpansion() {} MacroExpansion::~MacroExpansion() {}
TranslationUnit::TranslationUnit() { kind = DeclarationKind::TranslationUnit; } TranslationUnit::TranslationUnit()
{
kind = DeclarationKind::TranslationUnit;
}
TranslationUnit::~TranslationUnit() {} TranslationUnit::~TranslationUnit() {}
DEF_VECTOR(TranslationUnit, MacroDefinition*, Macros) DEF_VECTOR(TranslationUnit, MacroDefinition*, Macros)
NativeLibrary::NativeLibrary() NativeLibrary::NativeLibrary()
: archType(AST::ArchType::UnknownArch) {} : archType(AST::ArchType::UnknownArch)
{
}
NativeLibrary::~NativeLibrary() {} NativeLibrary::~NativeLibrary() {}
@ -915,7 +1173,10 @@ DEF_VECTOR(ASTContext, TranslationUnit*, TranslationUnits)
ClassTemplateSpecialization* ClassTemplate::FindSpecialization(const std::string& usr) ClassTemplateSpecialization* ClassTemplate::FindSpecialization(const std::string& usr)
{ {
auto foundSpec = std::find_if(Specializations.begin(), Specializations.end(), auto foundSpec = std::find_if(Specializations.begin(), Specializations.end(),
[&](ClassTemplateSpecialization* cts) { return cts->USR == usr; }); [&](ClassTemplateSpecialization* cts)
{
return cts->USR == usr;
});
if (foundSpec != Specializations.end()) if (foundSpec != Specializations.end())
return static_cast<ClassTemplateSpecialization*>(*foundSpec); return static_cast<ClassTemplateSpecialization*>(*foundSpec);
@ -940,7 +1201,8 @@ TranslationUnit* ASTContext::FindOrCreateModule(const std::string& File)
auto normalizedFile = normalizePath(File); auto normalizedFile = normalizePath(File);
auto existingUnit = std::find_if(TranslationUnits.begin(), auto existingUnit = std::find_if(TranslationUnits.begin(),
TranslationUnits.end(), [&](TranslationUnit* unit) { TranslationUnits.end(), [&](TranslationUnit* unit)
{
return unit && unit->fileName == normalizedFile; return unit && unit->fileName == normalizedFile;
}); });
@ -955,9 +1217,15 @@ TranslationUnit* ASTContext::FindOrCreateModule(const std::string& File)
} }
// Comments // Comments
Comment::Comment(CommentKind kind) : kind(kind) {} Comment::Comment(CommentKind kind)
: kind(kind)
{
}
RawComment::RawComment() : fullCommentBlock(0) {} RawComment::RawComment()
: fullCommentBlock(0)
{
}
RawComment::~RawComment() RawComment::~RawComment()
{ {
@ -965,7 +1233,10 @@ RawComment::~RawComment()
delete fullCommentBlock; delete fullCommentBlock;
} }
FullComment::FullComment() : Comment(CommentKind::FullComment) {} FullComment::FullComment()
: Comment(CommentKind::FullComment)
{
}
FullComment::~FullComment() FullComment::~FullComment()
{ {
@ -1001,19 +1272,38 @@ FullComment::~FullComment()
DEF_VECTOR(FullComment, BlockContentComment*, Blocks) DEF_VECTOR(FullComment, BlockContentComment*, Blocks)
BlockContentComment::BlockContentComment() : Comment(CommentKind::BlockContentComment) {} BlockContentComment::BlockContentComment()
: Comment(CommentKind::BlockContentComment)
{
}
BlockContentComment::BlockContentComment(CommentKind Kind) : Comment(Kind) {} BlockContentComment::BlockContentComment(CommentKind Kind)
: Comment(Kind)
{
}
BlockCommandComment::Argument::Argument() {} BlockCommandComment::Argument::Argument() {}
BlockCommandComment::Argument::Argument(const Argument& rhs) : text(rhs.text) {} BlockCommandComment::Argument::Argument(const Argument& rhs)
: text(rhs.text)
{
}
BlockCommandComment::Argument::~Argument() {} BlockCommandComment::Argument::~Argument() {}
BlockCommandComment::BlockCommandComment() : BlockContentComment(CommentKind::BlockCommandComment), commandId(0), paragraphComment(0) {} BlockCommandComment::BlockCommandComment()
: BlockContentComment(CommentKind::BlockCommandComment)
, commandId(0)
, paragraphComment(0)
{
}
BlockCommandComment::BlockCommandComment(CommentKind Kind) : BlockContentComment(Kind), commandId(0), paragraphComment(0) {} BlockCommandComment::BlockCommandComment(CommentKind Kind)
: BlockContentComment(Kind)
, commandId(0)
, paragraphComment(0)
{
}
BlockCommandComment::~BlockCommandComment() BlockCommandComment::~BlockCommandComment()
{ {
@ -1022,13 +1312,24 @@ BlockCommandComment::~BlockCommandComment()
DEF_VECTOR(BlockCommandComment, BlockCommandComment::Argument, Arguments) DEF_VECTOR(BlockCommandComment, BlockCommandComment::Argument, Arguments)
ParamCommandComment::ParamCommandComment() : BlockCommandComment(CommentKind::ParamCommandComment), direction(PassDirection::In), paramIndex(0) {} ParamCommandComment::ParamCommandComment()
: BlockCommandComment(CommentKind::ParamCommandComment)
, direction(PassDirection::In)
, paramIndex(0)
{
}
TParamCommandComment::TParamCommandComment() : BlockCommandComment(CommentKind::TParamCommandComment) {} TParamCommandComment::TParamCommandComment()
: BlockCommandComment(CommentKind::TParamCommandComment)
{
}
DEF_VECTOR(TParamCommandComment, unsigned, Position) DEF_VECTOR(TParamCommandComment, unsigned, Position)
VerbatimBlockComment::VerbatimBlockComment() : BlockCommandComment(CommentKind::VerbatimBlockComment) {} VerbatimBlockComment::VerbatimBlockComment()
: BlockCommandComment(CommentKind::VerbatimBlockComment)
{
}
VerbatimBlockComment::~VerbatimBlockComment() VerbatimBlockComment::~VerbatimBlockComment()
{ {
@ -1038,9 +1339,16 @@ VerbatimBlockComment::~VerbatimBlockComment()
DEF_VECTOR(VerbatimBlockComment, VerbatimBlockLineComment*, Lines) DEF_VECTOR(VerbatimBlockComment, VerbatimBlockLineComment*, Lines)
VerbatimLineComment::VerbatimLineComment() : BlockCommandComment(CommentKind::VerbatimLineComment) {} VerbatimLineComment::VerbatimLineComment()
: BlockCommandComment(CommentKind::VerbatimLineComment)
{
}
ParagraphComment::ParagraphComment() : BlockContentComment(CommentKind::ParagraphComment), isWhitespace(false) {} ParagraphComment::ParagraphComment()
: BlockContentComment(CommentKind::ParagraphComment)
, isWhitespace(false)
{
}
ParagraphComment::~ParagraphComment() ParagraphComment::~ParagraphComment()
{ {
@ -1073,39 +1381,76 @@ ParagraphComment::~ParagraphComment()
DEF_VECTOR(ParagraphComment, InlineContentComment*, Content) DEF_VECTOR(ParagraphComment, InlineContentComment*, Content)
HTMLTagComment::HTMLTagComment() : InlineContentComment(CommentKind::HTMLTagComment) {} HTMLTagComment::HTMLTagComment()
: InlineContentComment(CommentKind::HTMLTagComment)
{
}
HTMLTagComment::HTMLTagComment(CommentKind Kind) : InlineContentComment(Kind) {} HTMLTagComment::HTMLTagComment(CommentKind Kind)
: InlineContentComment(Kind)
{
}
HTMLStartTagComment::Attribute::Attribute() {} HTMLStartTagComment::Attribute::Attribute() {}
HTMLStartTagComment::Attribute::Attribute(const Attribute& rhs) : name(rhs.name), value(rhs.value) {} HTMLStartTagComment::Attribute::Attribute(const Attribute& rhs)
: name(rhs.name)
, value(rhs.value)
{
}
HTMLStartTagComment::Attribute::~Attribute() {} HTMLStartTagComment::Attribute::~Attribute() {}
HTMLStartTagComment::HTMLStartTagComment() : HTMLTagComment(CommentKind::HTMLStartTagComment) {} HTMLStartTagComment::HTMLStartTagComment()
: HTMLTagComment(CommentKind::HTMLStartTagComment)
{
}
DEF_VECTOR(HTMLStartTagComment, HTMLStartTagComment::Attribute, Attributes) DEF_VECTOR(HTMLStartTagComment, HTMLStartTagComment::Attribute, Attributes)
HTMLEndTagComment::HTMLEndTagComment() : HTMLTagComment(CommentKind::HTMLEndTagComment) {} HTMLEndTagComment::HTMLEndTagComment()
: HTMLTagComment(CommentKind::HTMLEndTagComment)
{
}
InlineContentComment::InlineContentComment() : Comment(CommentKind::InlineContentComment), hasTrailingNewline(false) {} InlineContentComment::InlineContentComment()
: Comment(CommentKind::InlineContentComment)
, hasTrailingNewline(false)
{
}
InlineContentComment::InlineContentComment(CommentKind Kind) : Comment(Kind), hasTrailingNewline(false) {} InlineContentComment::InlineContentComment(CommentKind Kind)
: Comment(Kind)
, hasTrailingNewline(false)
{
}
TextComment::TextComment() : InlineContentComment(CommentKind::TextComment) {} TextComment::TextComment()
: InlineContentComment(CommentKind::TextComment)
{
}
InlineCommandComment::Argument::Argument() {} InlineCommandComment::Argument::Argument() {}
InlineCommandComment::Argument::Argument(const Argument& rhs) : text(rhs.text) {} InlineCommandComment::Argument::Argument(const Argument& rhs)
: text(rhs.text)
{
}
InlineCommandComment::Argument::~Argument() {} InlineCommandComment::Argument::~Argument() {}
InlineCommandComment::InlineCommandComment() InlineCommandComment::InlineCommandComment()
: InlineContentComment(CommentKind::InlineCommandComment), commandId(0), commentRenderKind(RenderNormal) {} : InlineContentComment(CommentKind::InlineCommandComment)
, commandId(0)
, commentRenderKind(RenderNormal)
{
}
DEF_VECTOR(InlineCommandComment, InlineCommandComment::Argument, Arguments) DEF_VECTOR(InlineCommandComment, InlineCommandComment::Argument, Arguments)
VerbatimBlockLineComment::VerbatimBlockLineComment() : Comment(CommentKind::VerbatimBlockLineComment) {} VerbatimBlockLineComment::VerbatimBlockLineComment()
: Comment(CommentKind::VerbatimBlockLineComment)
{
}
} } } }}} // namespace CppSharp::CppParser::AST

2
src/CppParser/AST.h

@ -256,4 +256,4 @@ public:
#pragma endregion #pragma endregion
} } } }}} // namespace CppSharp::CppParser::AST

41
src/CppParser/ASTNameMangler.cpp

@ -17,22 +17,25 @@ using namespace clang;
using namespace CppSharp::CppParser; using namespace CppSharp::CppParser;
namespace { namespace {
enum ObjCKind { enum ObjCKind
{
ObjCClass, ObjCClass,
ObjCMetaclass, ObjCMetaclass,
}; };
StringRef getClassSymbolPrefix(ObjCKind Kind, const ASTContext& Context) { StringRef getClassSymbolPrefix(ObjCKind Kind, const ASTContext& Context)
{
if (Context.getLangOpts().ObjCRuntime.isGNUFamily()) if (Context.getLangOpts().ObjCRuntime.isGNUFamily())
return Kind == ObjCMetaclass ? "_OBJC_METACLASS_" : "_OBJC_CLASS_"; return Kind == ObjCMetaclass ? "_OBJC_METACLASS_" : "_OBJC_CLASS_";
return Kind == ObjCMetaclass ? "OBJC_METACLASS_$_" : "OBJC_CLASS_$_"; return Kind == ObjCMetaclass ? "OBJC_METACLASS_$_" : "OBJC_CLASS_$_";
} }
void WriteObjCClassName(const ObjCInterfaceDecl* D, raw_ostream& OS) { void WriteObjCClassName(const ObjCInterfaceDecl* D, raw_ostream& OS)
{
OS << getClassSymbolPrefix(ObjCClass, D->getASTContext()); OS << getClassSymbolPrefix(ObjCClass, D->getASTContext());
OS << D->getObjCRuntimeNameAsString(); OS << D->getObjCRuntimeNameAsString();
} }
} } // namespace
ASTNameMangler::ASTNameMangler(ASTContext& Ctx) ASTNameMangler::ASTNameMangler(ASTContext& Ctx)
: DL(Ctx.getTargetInfo().getDataLayoutString()) : DL(Ctx.getTargetInfo().getDataLayoutString())
@ -40,7 +43,8 @@ ASTNameMangler::ASTNameMangler(ASTContext& Ctx)
{ {
} }
std::string ASTNameMangler::GetName(const Decl* D) const { std::string ASTNameMangler::GetName(const Decl* D) const
{
std::string Name; std::string Name;
{ {
llvm::raw_string_ostream OS(Name); llvm::raw_string_ostream OS(Name);
@ -49,32 +53,39 @@ std::string ASTNameMangler::GetName(const Decl* D) const {
return Name; return Name;
} }
bool ASTNameMangler::WriteName(const Decl* D, raw_ostream& OS) const { bool ASTNameMangler::WriteName(const Decl* D, raw_ostream& OS) const
if (auto* FD = dyn_cast<FunctionDecl>(D)) { {
if (auto* FD = dyn_cast<FunctionDecl>(D))
{
if (FD->isDependentContext()) if (FD->isDependentContext())
return true; return true;
if (WriteFuncOrVarName(FD, OS)) if (WriteFuncOrVarName(FD, OS))
return true; return true;
} }
else if (auto* VD = dyn_cast<VarDecl>(D)) { else if (auto* VD = dyn_cast<VarDecl>(D))
{
if (WriteFuncOrVarName(VD, OS)) if (WriteFuncOrVarName(VD, OS))
return true; return true;
} }
else if (auto* MD = dyn_cast<ObjCMethodDecl>(D)) { else if (auto* MD = dyn_cast<ObjCMethodDecl>(D))
{
MC->mangleObjCMethodName(MD, OS, /*includePrefixByte=*/false, /*includeCategoryNamespace=*/true); MC->mangleObjCMethodName(MD, OS, /*includePrefixByte=*/false, /*includeCategoryNamespace=*/true);
return false; return false;
} }
else if (auto* ID = dyn_cast<ObjCInterfaceDecl>(D)) { else if (auto* ID = dyn_cast<ObjCInterfaceDecl>(D))
{
WriteObjCClassName(ID, OS); WriteObjCClassName(ID, OS);
} }
else { else
{
return true; return true;
} }
return false; return false;
} }
std::string ASTNameMangler::GetMangledStructor(const NamedDecl* ND, unsigned StructorType) const { std::string ASTNameMangler::GetMangledStructor(const NamedDecl* ND, unsigned StructorType) const
{
std::string FrontendBuf; std::string FrontendBuf;
llvm::raw_string_ostream FOS(FrontendBuf); llvm::raw_string_ostream FOS(FrontendBuf);
@ -88,7 +99,8 @@ std::string ASTNameMangler::GetMangledStructor(const NamedDecl* ND, unsigned Str
return FrontendBuf; return FrontendBuf;
} }
std::string ASTNameMangler::GetMangledThunk(const CXXMethodDecl* MD, const ThunkInfo& T, bool /*ElideOverrideInfo*/) const { std::string ASTNameMangler::GetMangledThunk(const CXXMethodDecl* MD, const ThunkInfo& T, bool /*ElideOverrideInfo*/) const
{
std::string FrontendBuf; std::string FrontendBuf;
llvm::raw_string_ostream FOS(FrontendBuf); llvm::raw_string_ostream FOS(FrontendBuf);
@ -100,7 +112,8 @@ std::string ASTNameMangler::GetMangledThunk(const CXXMethodDecl* MD, const Thunk
bool ASTNameMangler::WriteFuncOrVarName(const NamedDecl* D, raw_ostream& OS) const bool ASTNameMangler::WriteFuncOrVarName(const NamedDecl* D, raw_ostream& OS) const
{ {
if (!MC->shouldMangleDeclName(D)) { if (!MC->shouldMangleDeclName(D))
{
const IdentifierInfo* II = D->getIdentifier(); const IdentifierInfo* II = D->getIdentifier();
if (!II) if (!II)
return true; return true;

10
src/CppParser/ASTNameMangler.h

@ -12,15 +12,13 @@
#include <string> #include <string>
namespace clang namespace clang {
{
class ASTContext; class ASTContext;
class MangleContext; class MangleContext;
struct ThunkInfo; struct ThunkInfo;
} } // namespace clang
namespace llvm namespace llvm {
{
class raw_ostream; class raw_ostream;
} }
@ -47,4 +45,4 @@ private:
std::unique_ptr<clang::MangleContext> MC; std::unique_ptr<clang::MangleContext> MC;
}; };
} } // namespace CppSharp::CppParser

5
src/CppParser/CXXABI.h

@ -21,7 +21,8 @@ class ASTContext;
class MemberPointerType; class MemberPointerType;
/// Implements C++ ABI-specific semantic analysis functions. /// Implements C++ ABI-specific semantic analysis functions.
class CXXABI { class CXXABI
{
public: public:
virtual ~CXXABI(); virtual ~CXXABI();
@ -41,6 +42,6 @@ public:
CXXABI* CreateARMCXXABI(ASTContext& Ctx); CXXABI* CreateARMCXXABI(ASTContext& Ctx);
CXXABI* CreateItaniumCXXABI(ASTContext& Ctx); CXXABI* CreateItaniumCXXABI(ASTContext& Ctx);
CXXABI* CreateMicrosoftCXXABI(ASTContext& Ctx); CXXABI* CreateMicrosoftCXXABI(ASTContext& Ctx);
} } // namespace clang
#endif #endif

13
src/CppParser/CppParser.cpp

@ -19,7 +19,10 @@ CppParserOptions::CppParserOptions()
CppParserOptions::~CppParserOptions() {} CppParserOptions::~CppParserOptions() {}
std::string CppParserOptions::getClangVersion() { return clangVersion; } std::string CppParserOptions::getClangVersion()
{
return clangVersion;
}
DEF_VECTOR_STRING(CppParserOptions, Arguments) DEF_VECTOR_STRING(CppParserOptions, Arguments)
DEF_VECTOR_STRING(CppParserOptions, CompilationOptions) DEF_VECTOR_STRING(CppParserOptions, CompilationOptions)
@ -38,7 +41,8 @@ ParserResult::ParserResult(const ParserResult& rhs)
, Diagnostics(rhs.Diagnostics) , Diagnostics(rhs.Diagnostics)
, Libraries(rhs.Libraries) , Libraries(rhs.Libraries)
, targetInfo(rhs.targetInfo) , targetInfo(rhs.targetInfo)
{} {
}
ParserResult::~ParserResult() ParserResult::~ParserResult()
{ {
@ -69,8 +73,9 @@ ParserDiagnostic::ParserDiagnostic(const ParserDiagnostic& rhs)
, level(rhs.level) , level(rhs.level)
, lineNumber(rhs.lineNumber) , lineNumber(rhs.lineNumber)
, columnNumber(rhs.columnNumber) , columnNumber(rhs.columnNumber)
{} {
}
ParserDiagnostic::~ParserDiagnostic() {} ParserDiagnostic::~ParserDiagnostic() {}
} } }} // namespace CppSharp::CppParser

10
src/CppParser/CppParser.h

@ -122,10 +122,14 @@ public:
static ParserResult* ParseHeader(CppParserOptions* Opts); static ParserResult* ParseHeader(CppParserOptions* Opts);
static ParserResult* ParseLibrary(CppLinkerOptions* Opts); static ParserResult* ParseLibrary(CppLinkerOptions* Opts);
static ParserResult* Build(CppParserOptions* Opts, static ParserResult* Build(CppParserOptions* Opts,
const CppLinkerOptions* LinkerOptions, const std::string& File, bool Last); const CppLinkerOptions* LinkerOptions,
const std::string& File,
bool Last);
static ParserResult* Compile(CppParserOptions* Opts, const std::string& File); static ParserResult* Compile(CppParserOptions* Opts, const std::string& File);
static ParserResult* Link(CppParserOptions* Opts, static ParserResult* Link(CppParserOptions* Opts,
const CppLinkerOptions* LinkerOptions, const std::string& File, bool Last); const CppLinkerOptions* LinkerOptions,
const std::string& File,
bool Last);
}; };
} } }} // namespace CppSharp::CppParser

18
src/CppParser/Decl.h

@ -12,12 +12,9 @@
#include "Types.h" #include "Types.h"
#include <algorithm> #include <algorithm>
namespace CppSharp namespace CppSharp {
{ namespace CppParser {
namespace CppParser namespace AST {
{
namespace AST
{
enum class DeclarationKind enum class DeclarationKind
{ {
@ -126,8 +123,7 @@ namespace CppSharp
CS_IGNORE Class* CreateClass(const std::string& Name, bool IsComplete); CS_IGNORE Class* CreateClass(const std::string& Name, bool IsComplete);
CS_IGNORE Class* FindClass(const void* OriginalPtr, const std::string& Name, bool IsComplete); CS_IGNORE Class* FindClass(const void* OriginalPtr, const std::string& Name, bool IsComplete);
CS_IGNORE Class *FindClass(const void *OriginalPtr, const std::string &Name, bool IsComplete, CS_IGNORE Class* FindClass(const void* OriginalPtr, const std::string& Name, bool IsComplete, bool Create);
bool Create);
CS_IGNORE template <typename T> CS_IGNORE template <typename T>
T* FindTemplate(const std::string& USR); T* FindTemplate(const std::string& USR);
@ -619,7 +615,9 @@ namespace CppSharp
{ {
auto foundTemplate = std::find_if(Templates.begin(), Templates.end(), auto foundTemplate = std::find_if(Templates.begin(), Templates.end(),
[&](Template* t) [&](Template* t)
{ return t->USR == USR; }); {
return t->USR == USR;
});
if (foundTemplate != Templates.end()) if (foundTemplate != Templates.end())
return static_cast<T*>(*foundTemplate); return static_cast<T*>(*foundTemplate);
@ -847,4 +845,4 @@ namespace CppSharp
} }
} }
} } // namespace CppSharp::CppParser::AST

48
src/CppParser/ELFDumper.h

@ -12,7 +12,8 @@
namespace CppSharp { namespace CppParser { namespace CppSharp { namespace CppParser {
template <typename ELFT> template <typename ELFT>
class ELFDumper { class ELFDumper
{
public: public:
ELFDumper(const llvm::object::ELFFile<ELFT>* Obj); ELFDumper(const llvm::object::ELFFile<ELFT>* Obj);
@ -27,8 +28,14 @@ private:
typedef typename ELFO::uintX_t uintX_t; typedef typename ELFO::uintX_t uintX_t;
/// \brief Represents a region described by entries in the .dynamic table. /// \brief Represents a region described by entries in the .dynamic table.
struct DynRegionInfo { struct DynRegionInfo
DynRegionInfo() : Addr(nullptr), Size(0), EntSize(0) {} {
DynRegionInfo()
: Addr(nullptr)
, Size(0)
, EntSize(0)
{
}
/// \brief Address in current address space. /// \brief Address in current address space.
const void* Addr; const void* Addr;
/// \brief Size in bytes of the region. /// \brief Size in bytes of the region.
@ -40,7 +47,8 @@ private:
llvm::StringRef getDynamicString(uint64_t Offset) const; llvm::StringRef getDynamicString(uint64_t Offset) const;
const Elf_Dyn* dynamic_table_begin() const; const Elf_Dyn* dynamic_table_begin() const;
const Elf_Dyn* dynamic_table_end() const; const Elf_Dyn* dynamic_table_end() const;
llvm::iterator_range<const Elf_Dyn*> dynamic_table() const { llvm::iterator_range<const Elf_Dyn*> dynamic_table() const
{
return llvm::make_range(dynamic_table_begin(), dynamic_table_end()); return llvm::make_range(dynamic_table_begin(), dynamic_table_end());
} }
@ -50,7 +58,8 @@ private:
}; };
template <typename ELFT> template <typename ELFT>
ELFDumper<ELFT>::ELFDumper(const llvm::object::ELFFile<ELFT> *Obj) { ELFDumper<ELFT>::ELFDumper(const llvm::object::ELFFile<ELFT>* Obj)
{
llvm::SmallVector<const Elf_Phdr*, 4> LoadSegments; llvm::SmallVector<const Elf_Phdr*, 4> LoadSegments;
auto ProgramHeaders = Obj->program_headers(); auto ProgramHeaders = Obj->program_headers();
@ -59,8 +68,10 @@ ELFDumper<ELFT>::ELFDumper(const llvm::object::ELFFile<ELFT> *Obj) {
llvm::report_fatal_error("Error reading program headers"); llvm::report_fatal_error("Error reading program headers");
return; return;
} }
for (const Elf_Phdr &Phdr : ProgramHeaders.get()) { for (const Elf_Phdr& Phdr : ProgramHeaders.get())
if (Phdr.p_type == llvm::ELF::PT_DYNAMIC) { {
if (Phdr.p_type == llvm::ELF::PT_DYNAMIC)
{
DynamicRegion.Addr = Obj->base() + Phdr.p_offset; DynamicRegion.Addr = Obj->base() + Phdr.p_offset;
uint64_t Size = Phdr.p_filesz; uint64_t Size = Phdr.p_filesz;
if (Size % sizeof(Elf_Dyn)) if (Size % sizeof(Elf_Dyn))
@ -73,7 +84,8 @@ ELFDumper<ELFT>::ELFDumper(const llvm::object::ELFFile<ELFT> *Obj) {
LoadSegments.push_back(&Phdr); LoadSegments.push_back(&Phdr);
} }
auto toMappedAddr = [&](uint64_t VAddr) -> const uint8_t *{ auto toMappedAddr = [&](uint64_t VAddr) -> const uint8_t*
{
const Elf_Phdr** I = std::upper_bound( const Elf_Phdr** I = std::upper_bound(
LoadSegments.begin(), LoadSegments.end(), VAddr, LoadSegments.begin(), LoadSegments.end(), VAddr,
[](uint64_t VAddr, const Elf_Phdr* Phdr) [](uint64_t VAddr, const Elf_Phdr* Phdr)
@ -92,8 +104,10 @@ ELFDumper<ELFT>::ELFDumper(const llvm::object::ELFFile<ELFT> *Obj) {
const char* StringTableBegin = nullptr; const char* StringTableBegin = nullptr;
uint64_t StringTableSize = 0; uint64_t StringTableSize = 0;
for (const Elf_Dyn &Dyn : dynamic_table()) { for (const Elf_Dyn& Dyn : dynamic_table())
switch (Dyn.d_tag) { {
switch (Dyn.d_tag)
{
case llvm::ELF::DT_STRTAB: case llvm::ELF::DT_STRTAB:
StringTableBegin = (const char*)toMappedAddr(Dyn.getPtr()); StringTableBegin = (const char*)toMappedAddr(Dyn.getPtr());
break; break;
@ -108,24 +122,28 @@ ELFDumper<ELFT>::ELFDumper(const llvm::object::ELFFile<ELFT> *Obj) {
template <typename ELFT> template <typename ELFT>
const typename ELFDumper<ELFT>::Elf_Dyn* const typename ELFDumper<ELFT>::Elf_Dyn*
ELFDumper<ELFT>::dynamic_table_begin() const { ELFDumper<ELFT>::dynamic_table_begin() const
{
return reinterpret_cast<const Elf_Dyn*>(DynamicRegion.Addr); return reinterpret_cast<const Elf_Dyn*>(DynamicRegion.Addr);
} }
template <typename ELFT> template <typename ELFT>
const typename ELFDumper<ELFT>::Elf_Dyn* const typename ELFDumper<ELFT>::Elf_Dyn*
ELFDumper<ELFT>::dynamic_table_end() const { ELFDumper<ELFT>::dynamic_table_end() const
{
uint64_t Size = DynamicRegion.Size; uint64_t Size = DynamicRegion.Size;
return dynamic_table_begin() + Size / sizeof(Elf_Dyn); return dynamic_table_begin() + Size / sizeof(Elf_Dyn);
} }
template <class ELFT> template <class ELFT>
llvm::StringRef ELFDumper<ELFT>::getDynamicString(uint64_t Value) const { llvm::StringRef ELFDumper<ELFT>::getDynamicString(uint64_t Value) const
{
return llvm::StringRef(DynamicStringTable.data() + Value); return llvm::StringRef(DynamicStringTable.data() + Value);
} }
template <class ELFT> template <class ELFT>
std::vector<llvm::StringRef> ELFDumper<ELFT>::getNeededLibraries() const { std::vector<llvm::StringRef> ELFDumper<ELFT>::getNeededLibraries() const
{
std::vector<llvm::StringRef> Libs; std::vector<llvm::StringRef> Libs;
for (const auto& Entry : dynamic_table()) for (const auto& Entry : dynamic_table())
@ -135,4 +153,4 @@ std::vector<llvm::StringRef> ELFDumper<ELFT>::getNeededLibraries() const {
return Libs; return Libs;
} }
} } }} // namespace CppSharp::CppParser

40
src/CppParser/Helpers.h

@ -36,10 +36,22 @@
void clear##name(); void clear##name();
#define DEF_VECTOR(klass, type, name) \ #define DEF_VECTOR(klass, type, name) \
type klass::get##name (unsigned i) { return name[i]; } \ type klass::get##name(unsigned i) \
void klass::add##name (type& s) { return name.push_back(s); } \ { \
unsigned klass::get##name##Count () { return name.size(); } \ return name[i]; \
void klass::clear##name() { name.clear(); } } \
void klass::add##name(type& s) \
{ \
return name.push_back(s); \
} \
unsigned klass::get##name##Count() \
{ \
return name.size(); \
} \
void klass::clear##name() \
{ \
name.clear(); \
}
#define VECTOR_STRING(name) \ #define VECTOR_STRING(name) \
std::vector<std::string> name; \ std::vector<std::string> name; \
@ -49,7 +61,19 @@
void clear##name(); void clear##name();
#define DEF_VECTOR_STRING(klass, name) \ #define DEF_VECTOR_STRING(klass, name) \
const char* klass::get##name (unsigned i) { return name[i].c_str(); } \ const char* klass::get##name(unsigned i) \
void klass::add##name (const char* s) { return name.push_back(std::string(s)); } \ { \
unsigned klass::get##name##Count () { return name.size(); } \ return name[i].c_str(); \
void klass::clear##name() { name.clear(); } } \
void klass::add##name(const char* s) \
{ \
return name.push_back(std::string(s)); \
} \
unsigned klass::get##name##Count() \
{ \
return name.size(); \
} \
void klass::clear##name() \
{ \
name.clear(); \
}

10
src/CppParser/Link.cpp

@ -56,7 +56,9 @@ bool Parser::Link(const std::string& File, const CppLinkerOptions* LinkerOptions
bool Parser::LinkWindows(const CppLinkerOptions* LinkerOptions, bool Parser::LinkWindows(const CppLinkerOptions* LinkerOptions,
std::vector<const char*>& args, std::vector<const char*>& args,
const llvm::StringRef& Dir, llvm::StringRef& Stem, bool MinGW) const llvm::StringRef& Dir,
llvm::StringRef& Stem,
bool MinGW)
{ {
#ifdef _WIN32 #ifdef _WIN32
using namespace llvm; using namespace llvm;
@ -113,7 +115,8 @@ bool Parser::LinkWindows(const CppLinkerOptions* LinkerOptions,
bool Parser::LinkELF(const CppLinkerOptions* LinkerOptions, bool Parser::LinkELF(const CppLinkerOptions* LinkerOptions,
std::vector<const char*>& args, std::vector<const char*>& args,
llvm::StringRef& Dir, llvm::StringRef& Stem) llvm::StringRef& Dir,
llvm::StringRef& Stem)
{ {
#ifdef __linux__ #ifdef __linux__
using namespace llvm; using namespace llvm;
@ -154,7 +157,8 @@ bool Parser::LinkELF(const CppLinkerOptions* LinkerOptions,
bool Parser::LinkMachO(const CppLinkerOptions* LinkerOptions, bool Parser::LinkMachO(const CppLinkerOptions* LinkerOptions,
std::vector<const char*>& args, std::vector<const char*>& args,
llvm::StringRef& Dir, llvm::StringRef& Stem) llvm::StringRef& Dir,
llvm::StringRef& Stem)
{ {
#ifdef __APPLE__ #ifdef __APPLE__
using namespace llvm; using namespace llvm;

217
src/CppParser/Parser.cpp

@ -71,8 +71,10 @@
// Internals of assertm with or without abort. // Internals of assertm with or without abort.
#define _assertm(condition, message, call) \ #define _assertm(condition, message, call) \
do{ \ do \
if (!(condition)) { \ { \
if (!(condition)) \
{ \
std::cerr << "Assert at `" \ std::cerr << "Assert at `" \
<< __FILE__ \ << __FILE__ \
<< ":" \ << ":" \
@ -83,12 +85,15 @@
<< message; \ << message; \
call; \ call; \
} \ } \
} while (0) } \
while (0)
// Internals of assertml with or without abort. // Internals of assertml with or without abort.
#define _assertml(condition, message, sm, loc, call) \ #define _assertml(condition, message, sm, loc, call) \
do{ \ do \
if (!(condition)) { \ { \
if (!(condition)) \
{ \
const clang::SourceManager& _sm = sm; \ const clang::SourceManager& _sm = sm; \
clang::SourceLocation _loc = loc; \ clang::SourceLocation _loc = loc; \
std::cerr << "Assert at `" \ std::cerr << "Assert at `" \
@ -106,7 +111,8 @@
<< "`\n"; \ << "`\n"; \
call; \ call; \
} \ } \
}while(0) } \
while (0)
// Macros which output messages to console if parsing encounters oddity. // Macros which output messages to console if parsing encounters oddity.
// In debug builds, macros abort unless DEBUG_NO_ABORT is defined. // In debug builds, macros abort unless DEBUG_NO_ABORT is defined.
@ -134,7 +140,9 @@
#ifdef DEBUG_NO_ABORT #ifdef DEBUG_NO_ABORT
#define debug_fail() debug_break() #define debug_fail() debug_break()
#else #else
#define debug_fail() debug_break(); abort() #define debug_fail() \
debug_break(); \
abort()
#endif #endif
#endif #endif
@ -160,7 +168,8 @@ Parser::Parser(CppParserOptions* Opts)
} }
LayoutField Parser::WalkVTablePointer(Class* Class, LayoutField Parser::WalkVTablePointer(Class* Class,
const clang::CharUnits& Offset, const std::string& prefix) const clang::CharUnits& Offset,
const std::string& prefix)
{ {
LayoutField LayoutField; LayoutField LayoutField;
LayoutField.offset = Offset.getQuantity(); LayoutField.offset = Offset.getQuantity();
@ -192,8 +201,7 @@ static CppAbi GetClassLayoutAbi(clang::TargetCXXABI::Kind abi)
} }
} }
void Parser::ReadClassLayout(Class* Class, const clang::RecordDecl* RD, void Parser::ReadClassLayout(Class* Class, const clang::RecordDecl* RD, clang::CharUnits Offset, bool IncludeVirtualBases)
clang::CharUnits Offset, bool IncludeVirtualBases)
{ {
using namespace clang; using namespace clang;
@ -212,25 +220,29 @@ void Parser::ReadClassLayout(Class* Class, const clang::RecordDecl* RD,
} }
// Dump bases. // Dump bases.
if (CXXRD) { if (CXXRD)
{
const CXXRecordDecl* PrimaryBase = Layout.getPrimaryBase(); const CXXRecordDecl* PrimaryBase = Layout.getPrimaryBase();
bool HasOwnVFPtr = Layout.hasOwnVFPtr(); bool HasOwnVFPtr = Layout.hasOwnVFPtr();
bool HasOwnVBPtr = Layout.hasOwnVBPtr(); bool HasOwnVBPtr = Layout.hasOwnVBPtr();
// Vtable pointer. // Vtable pointer.
if (CXXRD->isDynamicClass() && !PrimaryBase && if (CXXRD->isDynamicClass() && !PrimaryBase &&
!c->getTarget().getCXXABI().isMicrosoft()) { !c->getTarget().getCXXABI().isMicrosoft())
{
auto VPtr = WalkVTablePointer(Parent, Offset, "vptr"); auto VPtr = WalkVTablePointer(Parent, Offset, "vptr");
Class->layout->Fields.push_back(VPtr); Class->layout->Fields.push_back(VPtr);
} }
else if (HasOwnVFPtr) { else if (HasOwnVFPtr)
{
auto VTPtr = WalkVTablePointer(Parent, Offset, "vfptr"); auto VTPtr = WalkVTablePointer(Parent, Offset, "vfptr");
Class->layout->Fields.push_back(VTPtr); Class->layout->Fields.push_back(VTPtr);
} }
// Collect nvbases. // Collect nvbases.
SmallVector<const CXXRecordDecl*, 4> Bases; SmallVector<const CXXRecordDecl*, 4> Bases;
for (const CXXBaseSpecifier &Base : CXXRD->bases()) { for (const CXXBaseSpecifier& Base : CXXRD->bases())
{
assertm(!Base.getType()->isDependentType(), "Cannot layout class with dependent bases.\n"); assertm(!Base.getType()->isDependentType(), "Cannot layout class with dependent bases.\n");
if (!Base.isVirtual()) if (!Base.isVirtual())
@ -239,19 +251,22 @@ void Parser::ReadClassLayout(Class* Class, const clang::RecordDecl* RD,
// Sort nvbases by offset. // Sort nvbases by offset.
std::stable_sort(Bases.begin(), Bases.end(), std::stable_sort(Bases.begin(), Bases.end(),
[&](const CXXRecordDecl *L, const CXXRecordDecl *R) { [&](const CXXRecordDecl* L, const CXXRecordDecl* R)
{
return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R); return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
}); });
// Dump (non-virtual) bases // Dump (non-virtual) bases
for (const CXXRecordDecl *Base : Bases) { for (const CXXRecordDecl* Base : Bases)
{
CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base); CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
ReadClassLayout(Class, Base, BaseOffset, ReadClassLayout(Class, Base, BaseOffset,
/*IncludeVirtualBases=*/false); /*IncludeVirtualBases=*/false);
} }
// vbptr (for Microsoft C++ ABI) // vbptr (for Microsoft C++ ABI)
if (HasOwnVBPtr) { if (HasOwnVBPtr)
{
auto VBPtr = WalkVTablePointer(Parent, auto VBPtr = WalkVTablePointer(Parent,
Offset + Layout.getVBPtrOffset(), "vbptr"); Offset + Layout.getVBPtrOffset(), "vbptr");
Class->layout->Fields.push_back(VBPtr); Class->layout->Fields.push_back(VBPtr);
@ -260,7 +275,8 @@ void Parser::ReadClassLayout(Class* Class, const clang::RecordDecl* RD,
// Dump fields. // Dump fields.
uint64_t FieldNo = 0; uint64_t FieldNo = 0;
for (const FieldDecl* Field : RD->fields()) { for (const FieldDecl* Field : RD->fields())
{
uint64_t LocalFieldOffsetInBits = Layout.getFieldOffset(FieldNo++); uint64_t LocalFieldOffsetInBits = Layout.getFieldOffset(FieldNo++);
CharUnits FieldOffset = CharUnits FieldOffset =
Offset + c->getASTContext().toCharUnitsFromBits(LocalFieldOffsetInBits); Offset + c->getASTContext().toCharUnitsFromBits(LocalFieldOffsetInBits);
@ -275,18 +291,21 @@ void Parser::ReadClassLayout(Class* Class, const clang::RecordDecl* RD,
} }
// Dump virtual bases. // Dump virtual bases.
if (CXXRD && IncludeVirtualBases) { if (CXXRD && IncludeVirtualBases)
{
const ASTRecordLayout::VBaseOffsetsMapTy& VtorDisps = const ASTRecordLayout::VBaseOffsetsMapTy& VtorDisps =
Layout.getVBaseOffsetsMap(); Layout.getVBaseOffsetsMap();
for (const CXXBaseSpecifier &Base : CXXRD->vbases()) { for (const CXXBaseSpecifier& Base : CXXRD->vbases())
{
assertm(Base.isVirtual(), "Found non-virtual class!\n"); assertm(Base.isVirtual(), "Found non-virtual class!\n");
const CXXRecordDecl* VBase = Base.getType()->getAsCXXRecordDecl(); const CXXRecordDecl* VBase = Base.getType()->getAsCXXRecordDecl();
CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase); CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
if (VtorDisps.find(VBase)->second.hasVtorDisp()) { if (VtorDisps.find(VBase)->second.hasVtorDisp())
{
auto VtorDisp = WalkVTablePointer(Parent, auto VtorDisp = WalkVTablePointer(Parent,
VBaseOffset - CharUnits::fromQuantity(4), "vtordisp"); VBaseOffset - CharUnits::fromQuantity(4), "vtordisp");
Class->layout->Fields.push_back(VtorDisp); Class->layout->Fields.push_back(VtorDisp);
@ -433,7 +452,8 @@ void Parser::Setup(bool Compile)
if (opts->microsoftMode) if (opts->microsoftMode)
{ {
LangOpts.MSCompatibilityVersion = opts->toolSetToUse; LangOpts.MSCompatibilityVersion = opts->toolSetToUse;
if (!LangOpts.MSCompatibilityVersion) LangOpts.MSCompatibilityVersion = 1700; if (!LangOpts.MSCompatibilityVersion)
LangOpts.MSCompatibilityVersion = 1700;
} }
#endif #endif
@ -447,11 +467,13 @@ void Parser::Setup(bool Compile)
else if (Target.getEnvironment() == llvm::Triple::EnvironmentType::MSVC) else if (Target.getEnvironment() == llvm::Triple::EnvironmentType::MSVC)
TC = new driver::toolchains::MSVCToolChain(D, Target, Args); TC = new driver::toolchains::MSVCToolChain(D, Target, Args);
if (TC && !opts->noStandardIncludes) { if (TC && !opts->noStandardIncludes)
{
llvm::opt::ArgStringList Includes; llvm::opt::ArgStringList Includes;
TC->AddClangSystemIncludeArgs(Args, Includes); TC->AddClangSystemIncludeArgs(Args, Includes);
TC->AddClangCXXStdlibIncludeArgs(Args, Includes); TC->AddClangCXXStdlibIncludeArgs(Args, Includes);
for (auto& Arg : Includes) { for (auto& Arg : Includes)
{
if (strlen(Arg) > 0 && Arg[0] != '-') if (strlen(Arg) > 0 && Arg[0] != '-')
HSOpts.AddPath(Arg, frontend::System, /*IsFramework=*/false, HSOpts.AddPath(Arg, frontend::System, /*IsFramework=*/false,
/*IgnoreSysRoot=*/false); /*IgnoreSysRoot=*/false);
@ -809,7 +831,8 @@ void Parser::WalkVTable(const clang::CXXRecordDecl* RD, Class* C)
} }
void Parser::EnsureCompleteRecord(const clang::RecordDecl* Record, void Parser::EnsureCompleteRecord(const clang::RecordDecl* Record,
DeclarationContext* NS, Class* RC) DeclarationContext* NS,
Class* RC)
{ {
using namespace clang; using namespace clang;
@ -946,7 +969,8 @@ static clang::CXXRecordDecl* GetCXXRecordDeclFromTemplateName(const clang::Templ
{ {
using namespace clang; using namespace clang;
switch (Name.getKind()) { switch (Name.getKind())
{
case TemplateName::Template: case TemplateName::Template:
return dyn_cast<CXXRecordDecl>(Name.getAsTemplateDecl()->getTemplatedDecl()); return dyn_cast<CXXRecordDecl>(Name.getAsTemplateDecl()->getTemplatedDecl());
case TemplateName::QualifiedTemplate: case TemplateName::QualifiedTemplate:
@ -967,10 +991,12 @@ static clang::CXXRecordDecl* GetCXXRecordDeclFromBaseType(const clang::ASTContex
return GetCXXRecordDeclFromTemplateName(TST->getTemplateName()); return GetCXXRecordDeclFromTemplateName(TST->getTemplateName());
else if (auto Injected = Ty->getAs<clang::InjectedClassNameType>()) else if (auto Injected = Ty->getAs<clang::InjectedClassNameType>())
return Injected->getDecl(); return Injected->getDecl();
else if (auto TTPT = Ty->getAs<TemplateTypeParmType>()) { else if (auto TTPT = Ty->getAs<TemplateTypeParmType>())
{
return nullptr; return nullptr;
} }
else if (auto DNT = Ty->getAs<clang::DependentNameType>()) { else if (auto DNT = Ty->getAs<clang::DependentNameType>())
{
return nullptr; return nullptr;
} }
@ -1187,7 +1213,8 @@ void Parser::WalkRecord(const clang::RecordDecl* Record, Class* RC)
{ {
WalkDeclaration(D); WalkDeclaration(D);
break; break;
} } }
}
} }
} }
@ -1241,8 +1268,7 @@ void Parser::WalkRecordCXX(const clang::CXXRecordDecl* Record, Class* RC)
auto BaseDecl = GetCXXRecordDeclFromBaseType(c->getASTContext(), BS, BS.getType()); auto BaseDecl = GetCXXRecordDeclFromBaseType(c->getASTContext(), BS, BS.getType());
if (BaseDecl && Layout) if (BaseDecl && Layout)
{ {
auto Offset = BS.isVirtual() ? Layout->getVBaseClassOffset(BaseDecl) auto Offset = BS.isVirtual() ? Layout->getVBaseClassOffset(BaseDecl) : Layout->getBaseClassOffset(BaseDecl);
: Layout->getBaseClassOffset(BaseDecl);
Base->offset = Offset.getQuantity(); Base->offset = Offset.getQuantity();
} }
@ -1287,7 +1313,8 @@ struct Diagnostic
struct DiagnosticConsumer : public clang::DiagnosticConsumer struct DiagnosticConsumer : public clang::DiagnosticConsumer
{ {
virtual void HandleDiagnostic(clang::DiagnosticsEngine::Level Level, virtual void HandleDiagnostic(clang::DiagnosticsEngine::Level Level,
const clang::Diagnostic& Info) override { const clang::Diagnostic& Info) override
{
// Update the base type NumWarnings and NumErrors variables. // Update the base type NumWarnings and NumErrors variables.
if (Level == clang::DiagnosticsEngine::Warning) if (Level == clang::DiagnosticsEngine::Warning)
NumWarnings++; NumWarnings++;
@ -2038,7 +2065,10 @@ Field* Parser::WalkFieldCXX(const clang::FieldDecl* FD, Class* Class)
const auto& USR = GetDeclUSR(FD); const auto& USR = GetDeclUSR(FD);
auto FoundField = std::find_if(Class->Fields.begin(), Class->Fields.end(), auto FoundField = std::find_if(Class->Fields.begin(), Class->Fields.end(),
[&](Field* Field) { return Field->USR == USR; }); [&](Field* Field)
{
return Field->USR == USR;
});
if (FoundField != Class->Fields.end()) if (FoundField != Class->Fields.end())
return *FoundField; return *FoundField;
@ -2199,7 +2229,8 @@ DeclarationContext* Parser::GetNamespace(const clang::Decl* D,
auto Decl = WalkDeclaration(D); auto Decl = WalkDeclaration(D);
DC = static_cast<DeclarationContext*>(Decl); DC = static_cast<DeclarationContext*>(Decl);
break; break;
} } }
}
walkedNamespaces[Ctx] = DC; walkedNamespaces[Ctx] = DC;
} }
@ -2404,8 +2435,7 @@ static const clang::Type* GetFinalType(const clang::Type* Ty)
} }
} }
Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL, Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL, bool DesugarType)
bool DesugarType)
{ {
using namespace clang; using namespace clang;
@ -2435,7 +2465,8 @@ Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL,
assertm(Atomic, "Expected an atomic type!\n"); assertm(Atomic, "Expected an atomic type!\n");
TypeLoc Next; TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc(); if (LocValid)
Next = TL->getNextTypeLoc();
Ty = WalkType(Atomic->getValueType(), &Next); Ty = WalkType(Atomic->getValueType(), &Next);
break; break;
@ -2446,7 +2477,8 @@ Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL,
assertm(Attributed, "Expected an attributed type!\n"); assertm(Attributed, "Expected an attributed type!\n");
TypeLoc Next; TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc(); if (LocValid)
Next = TL->getNextTypeLoc();
auto AT = new AST::AttributedType(); auto AT = new AST::AttributedType();
@ -2489,7 +2521,8 @@ Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL,
P->modifier = AST::PointerType::TypeModifier::Pointer; P->modifier = AST::PointerType::TypeModifier::Pointer;
TypeLoc Next; TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc(); if (LocValid)
Next = TL->getNextTypeLoc();
auto Pointee = Pointer->getPointeeType(); auto Pointee = Pointer->getPointeeType();
P->qualifiedPointee = GetQualifiedType(Pointee, &Next); P->qualifiedPointee = GetQualifiedType(Pointee, &Next);
@ -2516,7 +2549,8 @@ Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL,
auto DT = Type->getAs<clang::DecayedType>(); auto DT = Type->getAs<clang::DecayedType>();
TypeLoc Next; TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc(); if (LocValid)
Next = TL->getNextTypeLoc();
auto Type = new AST::DecayedType(); auto Type = new AST::DecayedType();
Type->decayed = GetQualifiedType(DT->getDecayedType(), &Next); Type->decayed = GetQualifiedType(DT->getDecayedType(), &Next);
@ -2531,7 +2565,8 @@ Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL,
auto ET = Type->getAs<ElaboratedType>(); auto ET = Type->getAs<ElaboratedType>();
TypeLoc Next; TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc(); if (LocValid)
Next = TL->getNextTypeLoc();
Ty = WalkType(ET->getNamedType(), &Next); Ty = WalkType(ET->getNamedType(), &Next);
break; break;
@ -2552,7 +2587,8 @@ Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL,
auto PT = Type->getAs<ParenType>(); auto PT = Type->getAs<ParenType>();
TypeLoc Next; TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc(); if (LocValid)
Next = TL->getNextTypeLoc();
Ty = WalkType(PT->getInnerType(), &Next); Ty = WalkType(PT->getInnerType(), &Next);
break; break;
@ -2562,7 +2598,8 @@ Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL,
auto AT = AST.getAsConstantArrayType(QualType); auto AT = AST.getAsConstantArrayType(QualType);
TypeLoc Next; TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc(); if (LocValid)
Next = TL->getNextTypeLoc();
auto A = new AST::ArrayType(); auto A = new AST::ArrayType();
auto ElemTy = AT->getElementType(); auto ElemTy = AT->getElementType();
@ -2581,7 +2618,8 @@ Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL,
auto AT = AST.getAsIncompleteArrayType(QualType); auto AT = AST.getAsIncompleteArrayType(QualType);
TypeLoc Next; TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc(); if (LocValid)
Next = TL->getNextTypeLoc();
auto A = new AST::ArrayType(); auto A = new AST::ArrayType();
A->qualifiedType = GetQualifiedType(AT->getElementType(), &Next); A->qualifiedType = GetQualifiedType(AT->getElementType(), &Next);
@ -2595,7 +2633,8 @@ Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL,
auto AT = AST.getAsDependentSizedArrayType(QualType); auto AT = AST.getAsDependentSizedArrayType(QualType);
TypeLoc Next; TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc(); if (LocValid)
Next = TL->getNextTypeLoc();
auto A = new AST::ArrayType(); auto A = new AST::ArrayType();
A->qualifiedType = GetQualifiedType(AT->getElementType(), &Next); A->qualifiedType = GetQualifiedType(AT->getElementType(), &Next);
@ -2610,7 +2649,8 @@ Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL,
auto UT = Type->getAs<clang::UnresolvedUsingType>(); auto UT = Type->getAs<clang::UnresolvedUsingType>();
TypeLoc Next; TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc(); if (LocValid)
Next = TL->getNextTypeLoc();
auto U = new AST::UnresolvedUsingType(); auto U = new AST::UnresolvedUsingType();
U->declaration = static_cast<UnresolvedUsingTypename*>( U->declaration = static_cast<UnresolvedUsingTypename*>(
@ -2722,7 +2762,8 @@ Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL,
auto MP = Type->getAs<clang::MemberPointerType>(); auto MP = Type->getAs<clang::MemberPointerType>();
TypeLoc Next; TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc(); if (LocValid)
Next = TL->getNextTypeLoc();
auto MPT = new AST::MemberPointerType(); auto MPT = new AST::MemberPointerType();
MPT->pointee = GetQualifiedType(MP->getPointeeType(), &Next); MPT->pointee = GetQualifiedType(MP->getPointeeType(), &Next);
@ -2764,7 +2805,8 @@ Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL,
TL = &ITL; TL = &ITL;
} }
switch (TL->getTypeLocClass()) { switch (TL->getTypeLocClass())
{
case TypeLoc::DependentTemplateSpecialization: case TypeLoc::DependentTemplateSpecialization:
{ {
DependentTemplateSpecializationTypeLoc TSpecTL = TL->getAs<DependentTemplateSpecializationTypeLoc>(); DependentTemplateSpecializationTypeLoc TSpecTL = TL->getAs<DependentTemplateSpecializationTypeLoc>();
@ -2824,7 +2866,8 @@ Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL,
TL = &ITL; TL = &ITL;
} }
switch (TL->getTypeLocClass()) { switch (TL->getTypeLocClass())
{
case TypeLoc::DependentTemplateSpecialization: case TypeLoc::DependentTemplateSpecialization:
{ {
DependentTemplateSpecializationTypeLoc TSpecTL = TL->getAs<DependentTemplateSpecializationTypeLoc>(); DependentTemplateSpecializationTypeLoc TSpecTL = TL->getAs<DependentTemplateSpecializationTypeLoc>();
@ -2906,7 +2949,8 @@ Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL,
auto TPT = new TemplateParameterSubstitutionType(); auto TPT = new TemplateParameterSubstitutionType();
TypeLoc Next; TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc(); if (LocValid)
Next = TL->getNextTypeLoc();
auto RepTy = TP->getReplacementType(); auto RepTy = TP->getReplacementType();
TPT->replacement = GetQualifiedType(RepTy, &Next); TPT->replacement = GetQualifiedType(RepTy, &Next);
@ -2975,7 +3019,8 @@ Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL,
P->modifier = AST::PointerType::TypeModifier::LVReference; P->modifier = AST::PointerType::TypeModifier::LVReference;
TypeLoc Next; TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc(); if (LocValid)
Next = TL->getNextTypeLoc();
auto Pointee = LR->getPointeeType(); auto Pointee = LR->getPointeeType();
P->qualifiedPointee = GetQualifiedType(Pointee, &Next); P->qualifiedPointee = GetQualifiedType(Pointee, &Next);
@ -2991,7 +3036,8 @@ Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL,
P->modifier = AST::PointerType::TypeModifier::RVReference; P->modifier = AST::PointerType::TypeModifier::RVReference;
TypeLoc Next; TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc(); if (LocValid)
Next = TL->getNextTypeLoc();
auto Pointee = LR->getPointeeType(); auto Pointee = LR->getPointeeType();
P->qualifiedPointee = GetQualifiedType(Pointee, &Next); P->qualifiedPointee = GetQualifiedType(Pointee, &Next);
@ -3065,7 +3111,8 @@ Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL,
{ {
Debug("Unhandled type class '%s'\n", Type->getTypeClassName()); Debug("Unhandled type class '%s'\n", Type->getTypeClassName());
return nullptr; return nullptr;
} } }
}
Ty->isDependent = Type->isDependentType(); Ty->isDependent = Type->isDependentType();
return Ty; return Ty;
@ -3121,8 +3168,7 @@ Enumeration* Parser::WalkEnum(const clang::EnumDecl* ED)
} }
if (ED->isScoped()) if (ED->isScoped())
E->modifiers = (Enumeration::EnumModifiers) E->modifiers = (Enumeration::EnumModifiers)((int)E->modifiers | (int)Enumeration::EnumModifiers::Scoped);
((int)E->modifiers | (int)Enumeration::EnumModifiers::Scoped);
// Get the underlying integer backing the enum. // Get the underlying integer backing the enum.
QualType IntType = ED->getIntegerType(); QualType IntType = ED->getIntegerType();
@ -3151,8 +3197,7 @@ Enumeration::Item* Parser::WalkEnumItem(clang::EnumConstantDecl* ECD)
EnumItem->name = ECD->getNameAsString(); EnumItem->name = ECD->getNameAsString();
auto Value = ECD->getInitVal(); auto Value = ECD->getInitVal();
EnumItem->value = Value.isSigned() ? Value.getSExtValue() EnumItem->value = Value.isSigned() ? Value.getSExtValue() : Value.getZExtValue();
: Value.getZExtValue();
EnumItem->_namespace = GetNamespace(ECD); EnumItem->_namespace = GetNamespace(ECD);
std::string Text; std::string Text;
@ -3165,7 +3210,8 @@ Enumeration::Item* Parser::WalkEnumItem(clang::EnumConstantDecl* ECD)
//-----------------------------------// //-----------------------------------//
static const clang::CodeGen::CGFunctionInfo& GetCodeGenFunctionInfo( static const clang::CodeGen::CGFunctionInfo& GetCodeGenFunctionInfo(
clang::CodeGen::CodeGenTypes* CodeGenTypes, const clang::FunctionDecl* FD) clang::CodeGen::CodeGenTypes* CodeGenTypes,
const clang::FunctionDecl* FD)
{ {
auto FTy = FD->getType()->getCanonicalTypeUnqualified(); auto FTy = FD->getType()->getCanonicalTypeUnqualified();
return CodeGenTypes->arrangeFreeFunctionType( return CodeGenTypes->arrangeFreeFunctionType(
@ -3546,7 +3592,10 @@ void Parser::WalkFunction(const clang::FunctionDecl* FD, Function* F)
!HasLayout(cast<CXXRecordDecl>(MD->getDeclContext()))) || !HasLayout(cast<CXXRecordDecl>(MD->getDeclContext()))) ||
!CanCheckCodeGenInfo(FD->getReturnType().getTypePtr()) || !CanCheckCodeGenInfo(FD->getReturnType().getTypePtr()) ||
std::any_of(FD->parameters().begin(), FD->parameters().end(), std::any_of(FD->parameters().begin(), FD->parameters().end(),
[this](auto* P) { return !CanCheckCodeGenInfo(P->getType().getTypePtr()); })) [this](auto* P)
{
return !CanCheckCodeGenInfo(P->getType().getTypePtr());
}))
{ {
return; return;
} }
@ -3642,7 +3691,8 @@ void Parser::WalkVariable(const clang::VarDecl* VD, Variable* Var)
auto Init = VD->getAnyInitializer(); auto Init = VD->getAnyInitializer();
Var->initializer = (Init && !Init->getType()->isDependentType()) ? Var->initializer = (Init && !Init->getType()->isDependentType()) ?
WalkVariableInitializerExpression(Init) : nullptr; WalkVariableInitializerExpression(Init) :
nullptr;
auto TL = VD->getTypeSourceInfo()->getTypeLoc(); auto TL = VD->getTypeSourceInfo()->getTypeLoc();
Var->qualifiedType = GetQualifiedType(VD->getType(), &TL); Var->qualifiedType = GetQualifiedType(VD->getType(), &TL);
@ -3720,7 +3770,8 @@ bool Parser::GetDeclText(clang::SourceRange SR, std::string& Text)
} }
PreprocessedEntity* Parser::WalkPreprocessedEntity( PreprocessedEntity* Parser::WalkPreprocessedEntity(
Declaration* Decl, clang::PreprocessedEntity* PPEntity) Declaration* Decl,
clang::PreprocessedEntity* PPEntity)
{ {
using namespace clang; using namespace clang;
@ -3931,8 +3982,7 @@ ExpressionObsolete* Parser::WalkExpressionObsolete(const clang::Expr* Expr)
} }
else if (Expr->getStmtClass() != clang::Stmt::CXXBoolLiteralExprClass && else if (Expr->getStmtClass() != clang::Stmt::CXXBoolLiteralExprClass &&
Expr->getStmtClass() != clang::Stmt::UnaryExprOrTypeTraitExprClass && Expr->getStmtClass() != clang::Stmt::UnaryExprOrTypeTraitExprClass &&
Expr->EvaluateAsInt(integer, c->getASTContext()) Expr->EvaluateAsInt(integer, c->getASTContext()))
)
{ {
return new ExpressionObsolete(toString(integer.Val.getInt(), 10)); return new ExpressionObsolete(toString(integer.Val.getInt(), 10));
} }
@ -4029,13 +4079,15 @@ void Parser::HandlePreprocessedEntities(Declaration* Decl,
clang::SourceRange sourceRange, clang::SourceRange sourceRange,
MacroLocation macroLocation) MacroLocation macroLocation)
{ {
if (sourceRange.isInvalid()) return; if (sourceRange.isInvalid())
return;
auto& SourceMgr = c->getSourceManager(); auto& SourceMgr = c->getSourceManager();
auto isBefore = SourceMgr.isBeforeInTranslationUnit(sourceRange.getEnd(), auto isBefore = SourceMgr.isBeforeInTranslationUnit(sourceRange.getEnd(),
sourceRange.getBegin()); sourceRange.getBegin());
if (isBefore) return; if (isBefore)
return;
using namespace clang; using namespace clang;
auto PPRecord = c->getPreprocessor().getPreprocessingRecord(); auto PPRecord = c->getPreprocessor().getPreprocessingRecord();
@ -4045,7 +4097,8 @@ void Parser::HandlePreprocessedEntities(Declaration* Decl,
for (auto PPEntity : Range) for (auto PPEntity : Range)
{ {
auto Entity = WalkPreprocessedEntity(Decl, PPEntity); auto Entity = WalkPreprocessedEntity(Decl, PPEntity);
if (!Entity) continue; if (!Entity)
continue;
if (Entity->macroLocation == MacroLocation::Unknown) if (Entity->macroLocation == MacroLocation::Unknown)
Entity->macroLocation = macroLocation; Entity->macroLocation = macroLocation;
@ -4270,7 +4323,8 @@ Declaration* Parser::WalkDeclaration(const clang::Decl* D)
auto NS = GetNamespace(TD); auto NS = GetNamespace(TD);
auto Name = GetDeclName(TD); auto Name = GetDeclName(TD);
auto Typedef = NS->FindTypedef(Name, /*Create=*/false); auto Typedef = NS->FindTypedef(Name, /*Create=*/false);
if (Typedef) return Typedef; if (Typedef)
return Typedef;
Typedef = NS->FindTypedef(Name, /*Create=*/true); Typedef = NS->FindTypedef(Name, /*Create=*/true);
HandleDeclaration(TD, Typedef); HandleDeclaration(TD, Typedef);
@ -4296,7 +4350,8 @@ Declaration* Parser::WalkDeclaration(const clang::Decl* D)
auto NS = GetNamespace(TD); auto NS = GetNamespace(TD);
auto Name = GetDeclName(TD); auto Name = GetDeclName(TD);
auto TypeAlias = NS->FindTypeAlias(Name, /*Create=*/false); auto TypeAlias = NS->FindTypeAlias(Name, /*Create=*/false);
if (TypeAlias) return TypeAlias; if (TypeAlias)
return TypeAlias;
TypeAlias = NS->FindTypeAlias(Name, /*Create=*/true); TypeAlias = NS->FindTypeAlias(Name, /*Create=*/true);
HandleDeclaration(TD, TypeAlias); HandleDeclaration(TD, TypeAlias);
@ -4417,7 +4472,8 @@ Declaration* Parser::WalkDeclaration(const clang::Decl* D)
Debug(" %s (line %u)\n", FileName.str().c_str(), LineNo); Debug(" %s (line %u)\n", FileName.str().c_str(), LineNo);
break; break;
} }; }
};
if (Decl && D->hasAttrs()) if (Decl && D->hasAttrs())
{ {
@ -4454,9 +4510,9 @@ int Parser::GetAlignAs(const clang::AlignedAttr* alignedAttr)
{ {
return alignedAttr->isAlignas() && return alignedAttr->isAlignas() &&
!alignedAttr->isAlignmentErrorDependent() && !alignedAttr->isAlignmentErrorDependent() &&
!alignedAttr->isAlignmentDependent() !alignedAttr->isAlignmentDependent() ?
? alignedAttr->getAlignment(c->getASTContext()) alignedAttr->getAlignment(c->getASTContext()) :
: 0; 0;
} }
void Parser::HandleDiagnostics(ParserResult* res) void Parser::HandleDiagnostics(ParserResult* res)
@ -4563,7 +4619,8 @@ bool Parser::SetupSourceFiles(const std::vector<std::string>& SourceFiles,
return true; return true;
} }
class SemaConsumer : public clang::SemaConsumer { class SemaConsumer : public clang::SemaConsumer
{
public: public:
SemaConsumer(Parser& parser, std::vector<const clang::FileEntry*>& entries) SemaConsumer(Parser& parser, std::vector<const clang::FileEntry*>& entries)
: Parser(parser) : Parser(parser)
@ -4870,7 +4927,8 @@ ParserResult* Parser::ParseLibrary(const CppLinkerOptions* Opts)
auto OwningBinary = std::move(BinaryOrErr.get()); auto OwningBinary = std::move(BinaryOrErr.get());
auto Bin = OwningBinary.getBinary(); auto Bin = OwningBinary.getBinary();
if (auto Archive = llvm::dyn_cast<llvm::object::Archive>(Bin)) { if (auto Archive = llvm::dyn_cast<llvm::object::Archive>(Bin))
{
res->kind = ParseArchive(FileName, Archive, res->Libraries); res->kind = ParseArchive(FileName, Archive, res->Libraries);
if (res->kind == ParserResultKind::Error) if (res->kind == ParserResultKind::Error)
return res; return res;
@ -4946,7 +5004,9 @@ ParserResult* ClangParser::ParseLibrary(CppLinkerOptions* Opts)
} }
ParserResult* ClangParser::Build(CppParserOptions* Opts, ParserResult* ClangParser::Build(CppParserOptions* Opts,
const CppLinkerOptions* LinkerOptions, const std::string& File, bool Last) const CppLinkerOptions* LinkerOptions,
const std::string& File,
bool Last)
{ {
if (!Opts) if (!Opts)
return 0; return 0;
@ -4966,7 +5026,9 @@ ParserResult* ClangParser::Compile(CppParserOptions* Opts,
} }
ParserResult* ClangParser::Link(CppParserOptions* Opts, ParserResult* ClangParser::Link(CppParserOptions* Opts,
const CppLinkerOptions* LinkerOptions, const std::string& File, bool Last) const CppLinkerOptions* LinkerOptions,
const std::string& File,
bool Last)
{ {
if (!Opts) if (!Opts)
return 0; return 0;
@ -5071,7 +5133,8 @@ ParserTargetInfo* Parser::GetTargetInfo()
Declaration* Parser::GetDeclarationFromFriend(clang::NamedDecl* FriendDecl) Declaration* Parser::GetDeclarationFromFriend(clang::NamedDecl* FriendDecl)
{ {
Declaration* Decl = WalkDeclarationDef(FriendDecl); Declaration* Decl = WalkDeclarationDef(FriendDecl);
if (!Decl) return nullptr; if (!Decl)
return nullptr;
int MinLineNumberStart = std::numeric_limits<int>::max(); int MinLineNumberStart = std::numeric_limits<int>::max();
int MinLineNumberEnd = std::numeric_limits<int>::max(); int MinLineNumberEnd = std::numeric_limits<int>::max();

26
src/CppParser/Parser.h

@ -42,7 +42,7 @@ namespace clang {
class TemplateArgumentList; class TemplateArgumentList;
class VTableLayout; class VTableLayout;
class VTableComponent; class VTableComponent;
} } // namespace clang
#define Debug printf #define Debug printf
@ -52,6 +52,7 @@ namespace CppSharp { namespace CppParser {
class Parser class Parser
{ {
friend class ASTNodeVisitor; friend class ASTNodeVisitor;
public: public:
Parser(CppParserOptions* Opts); Parser(CppParserOptions* Opts);
@ -96,8 +97,7 @@ private:
void WalkVariable(const clang::VarDecl* VD, AST::Variable* Var); void WalkVariable(const clang::VarDecl* VD, AST::Variable* Var);
AST::Friend* WalkFriend(const clang::FriendDecl* FD); AST::Friend* WalkFriend(const clang::FriendDecl* FD);
AST::RawComment* WalkRawComment(const clang::RawComment* RC); AST::RawComment* WalkRawComment(const clang::RawComment* RC);
AST::Type* WalkType(clang::QualType QualType, const clang::TypeLoc* TL = 0, AST::Type* WalkType(clang::QualType QualType, const clang::TypeLoc* TL = 0, bool DesugarType = false);
bool DesugarType = false);
AST::TemplateArgument WalkTemplateArgument(const clang::TemplateArgument& TA, clang::TemplateArgumentLoc* ArgLoc = 0); AST::TemplateArgument WalkTemplateArgument(const clang::TemplateArgument& TA, clang::TemplateArgumentLoc* ArgLoc = 0);
AST::TemplateTemplateParameter* WalkTemplateTemplateParameter(const clang::TemplateTemplateParmDecl* TTP); AST::TemplateTemplateParameter* WalkTemplateTemplateParameter(const clang::TemplateTemplateParmDecl* TTP);
AST::TypeTemplateParameter* WalkTypeTemplateParameter(const clang::TemplateTypeParmDecl* TTPD); AST::TypeTemplateParameter* WalkTypeTemplateParameter(const clang::TemplateTypeParmDecl* TTPD);
@ -146,8 +146,7 @@ private:
void WalkFunction(const clang::FunctionDecl* FD, AST::Function* F); void WalkFunction(const clang::FunctionDecl* FD, AST::Function* F);
int GetAlignAs(const clang::AlignedAttr* alignedAttr); int GetAlignAs(const clang::AlignedAttr* alignedAttr);
void HandlePreprocessedEntities(AST::Declaration* Decl); void HandlePreprocessedEntities(AST::Declaration* Decl);
void HandlePreprocessedEntities(AST::Declaration* Decl, clang::SourceRange sourceRange, void HandlePreprocessedEntities(AST::Declaration* Decl, clang::SourceRange sourceRange, AST::MacroLocation macroLocation = AST::MacroLocation::Unknown);
AST::MacroLocation macroLocation = AST::MacroLocation::Unknown);
bool GetDeclText(clang::SourceRange SR, std::string& Text); bool GetDeclText(clang::SourceRange SR, std::string& Text);
bool HasLayout(const clang::RecordDecl* Record); bool HasLayout(const clang::RecordDecl* Record);
@ -168,17 +167,16 @@ private:
AST::NativeLibrary*& NativeLib); AST::NativeLibrary*& NativeLib);
AST::Declaration* GetDeclarationFromFriend(clang::NamedDecl* FriendDecl); AST::Declaration* GetDeclarationFromFriend(clang::NamedDecl* FriendDecl);
static ParserResultKind ParseArchive(const std::string& File, static ParserResultKind ParseArchive(const std::string& File,
llvm::object::Archive* Archive, std::vector<AST::NativeLibrary*>& NativeLibs); llvm::object::Archive* Archive,
std::vector<AST::NativeLibrary*>& NativeLibs);
static ParserResultKind ParseSharedLib(const std::string& File, static ParserResultKind ParseSharedLib(const std::string& File,
llvm::object::ObjectFile* ObjectFile, std::vector<AST::NativeLibrary*>& NativeLibs); llvm::object::ObjectFile* ObjectFile,
std::vector<AST::NativeLibrary*>& NativeLibs);
ParserTargetInfo* GetTargetInfo(); ParserTargetInfo* GetTargetInfo();
bool LinkWindows(const CppLinkerOptions* LinkerOptions, std::vector<const char*>& args, bool LinkWindows(const CppLinkerOptions* LinkerOptions, std::vector<const char*>& args, const llvm::StringRef& Dir, llvm::StringRef& Stem, bool MinGW = false);
const llvm::StringRef& Dir, llvm::StringRef& Stem, bool MinGW = false); bool LinkELF(const CppLinkerOptions* LinkerOptions, std::vector<const char*>& args, llvm::StringRef& Dir, llvm::StringRef& Stem);
bool LinkELF(const CppLinkerOptions* LinkerOptions, std::vector<const char*>& args, bool LinkMachO(const CppLinkerOptions* LinkerOptions, std::vector<const char*>& args, llvm::StringRef& Dir, llvm::StringRef& Stem);
llvm::StringRef& Dir, llvm::StringRef& Stem);
bool LinkMachO(const CppLinkerOptions* LinkerOptions, std::vector<const char*>& args,
llvm::StringRef& Dir, llvm::StringRef& Stem);
int index = 0; int index = 0;
std::unique_ptr<clang::CompilerInstance> c; std::unique_ptr<clang::CompilerInstance> c;
@ -196,4 +194,4 @@ private:
std::unordered_set<std::string> supportedFunctionTemplates; std::unordered_set<std::string> supportedFunctionTemplates;
}; };
} } }} // namespace CppSharp::CppParser

2
src/CppParser/Sources.cpp

@ -12,4 +12,4 @@ SourceLocation::SourceLocation(unsigned ID)
{ {
} }
} } }} // namespace CppSharp::CppParser

2
src/CppParser/Sources.h

@ -24,4 +24,4 @@ struct CS_API SourceRange
SourceLocation endLoc; SourceLocation endLoc;
}; };
} } }} // namespace CppSharp::CppParser

66
src/CppParser/Target.cpp

@ -9,41 +9,41 @@
namespace CppSharp { namespace CppParser { namespace CppSharp { namespace CppParser {
ParserTargetInfo::ParserTargetInfo() : ParserTargetInfo::ParserTargetInfo()
boolAlign(0), : boolAlign(0)
boolWidth(0), , boolWidth(0)
charAlign(0), , charAlign(0)
charWidth(0), , charWidth(0)
char16Align(0), , char16Align(0)
char16Width(0), , char16Width(0)
char32Align(0), , char32Align(0)
char32Width(0), , char32Width(0)
halfAlign(0), , halfAlign(0)
halfWidth(0), , halfWidth(0)
floatAlign(0), , floatAlign(0)
floatWidth(0), , floatWidth(0)
doubleAlign(0), , doubleAlign(0)
doubleWidth(0), , doubleWidth(0)
shortAlign(0), , shortAlign(0)
shortWidth(0), , shortWidth(0)
intAlign(0), , intAlign(0)
intWidth(0), , intWidth(0)
intMaxTWidth(0), , intMaxTWidth(0)
longAlign(0), , longAlign(0)
longWidth(0), , longWidth(0)
longDoubleAlign(0), , longDoubleAlign(0)
longDoubleWidth(0), , longDoubleWidth(0)
longLongAlign(0), , longLongAlign(0)
longLongWidth(0), , longLongWidth(0)
pointerAlign(0), , pointerAlign(0)
pointerWidth(0), , pointerWidth(0)
wCharAlign(0), , wCharAlign(0)
wCharWidth(0), , wCharWidth(0)
float128Align(0), , float128Align(0)
float128Width(0) , float128Width(0)
{ {
} }
ParserTargetInfo::~ParserTargetInfo() {} ParserTargetInfo::~ParserTargetInfo() {}
} } }} // namespace CppSharp::CppParser

2
src/CppParser/Target.h

@ -75,4 +75,4 @@ struct CS_API ParserTargetInfo
unsigned int float128Width; unsigned int float128Width;
}; };
} } }} // namespace CppSharp::CppParser

2
src/CppParser/Types.h

@ -329,4 +329,4 @@ public:
PrimitiveType type; PrimitiveType type;
}; };
} } } }}} // namespace CppSharp::CppParser::AST

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

@ -332,13 +332,13 @@ namespace CppSharp.Generator.Tests.AST
[Test] [Test]
public void TestLineNumber() public void TestLineNumber()
{ {
Assert.AreEqual(70, AstContext.FindClass("HiddenInNamespace").First().LineNumberStart); Assert.AreEqual(93, AstContext.FindClass("HiddenInNamespace").First().LineNumberStart);
} }
[Test] [Test]
public void TestLineNumberOfFriend() public void TestLineNumberOfFriend()
{ {
Assert.AreEqual(93, AstContext.FindFunction("operator+").First().LineNumberStart); Assert.AreEqual(116, AstContext.FindFunction("operator+").First().LineNumberStart);
} }
static string StripWindowsNewLines(string text) static string StripWindowsNewLines(string text)
@ -379,7 +379,7 @@ namespace CppSharp.Generator.Tests.AST
[Test] [Test]
public void TestMacroLineNumber() public void TestMacroLineNumber()
{ {
Assert.AreEqual(103, AstContext.FindClass("HasAmbiguousFunctions").First().Specifiers.Last().LineNumberStart); Assert.AreEqual(126, AstContext.FindClass("HasAmbiguousFunctions").First().Specifiers.Last().LineNumberStart);
} }
[Test] [Test]

29
src/Generator/Generators/QuickJS/Runtime/CppSharp_QuickJS.h

@ -65,7 +65,8 @@ static void JS_Interop_FreeEventMap(JSContext* ctx, JS_EventMap* map)
static int JS_Interop_BinarySearch(JS_EventEntry* arr, int l, int r, JS_EventId id) static int JS_Interop_BinarySearch(JS_EventEntry* arr, int l, int r, JS_EventId id)
{ {
if (r >= l) { if (r >= l)
{
int mid = l + (r - l) / 2; int mid = l + (r - l) / 2;
// If the element is present at the middle itself // If the element is present at the middle itself
@ -95,8 +96,7 @@ static JSValue JS_Interop_FindEvent(JS_EventMap* map, JS_EventId eventId)
return index >= 0 ? events[index].value : JS_UNDEFINED; return index >= 0 ? events[index].value : JS_UNDEFINED;
} }
static int JS_Interop_InsertEvent(JS_EventMap* map, JS_EventId eventId, static int JS_Interop_InsertEvent(JS_EventMap* map, JS_EventId eventId, JSValue value)
JSValue value)
{ {
JS_EventEntry* events = (JS_EventEntry*)map->buf; JS_EventEntry* events = (JS_EventEntry*)map->buf;
int numEvents = (map->size / sizeof(JS_EventEntry)); int numEvents = (map->size / sizeof(JS_EventEntry));
@ -104,8 +104,16 @@ static int JS_Interop_InsertEvent(JS_EventMap* map, JS_EventId eventId,
int index = 0; int index = 0;
for (int i = 0; i < numEvents; i++) for (int i = 0; i < numEvents; i++)
{ {
if (events[i].eventId == eventId) { index=-1; break; } if (events[i].eventId == eventId)
if (events[i].eventId > eventId) { index = i; break; } {
index = -1;
break;
}
if (events[i].eventId > eventId)
{
index = i;
break;
}
index++; index++;
} }
@ -122,8 +130,7 @@ static int JS_Interop_InsertEvent(JS_EventMap* map, JS_EventId eventId,
return 0; return 0;
} }
static JSValue JS_Interop_InvokeConstructor(JSContext *ctx, JS_ClassId eventId, static JSValue JS_Interop_InvokeConstructor(JSContext* ctx, JS_ClassId eventId, JSValue argv[], int argc)
JSValue argv[], int argc)
{ {
// TODO: Error handling. // TODO: Error handling.
JSValue proto = JS_GetClassProto(ctx, eventId); JSValue proto = JS_GetClassProto(ctx, eventId);
@ -148,8 +155,7 @@ struct JS_Interop_ClassData
JS_EventMap events; JS_EventMap events;
}; };
static JSValue JS_Interop_InitObject(JSContext *ctx, JSValue obj, JS_Interop_InstanceKind kind, static JSValue JS_Interop_InitObject(JSContext* ctx, JSValue obj, JS_Interop_InstanceKind kind, void* instance)
void* instance)
{ {
switch (kind) switch (kind)
{ {
@ -157,7 +163,7 @@ static JSValue JS_Interop_InitObject(JSContext *ctx, JSValue obj, JS_Interop_Ins
JS_SetOpaque(obj, instance); JS_SetOpaque(obj, instance);
return obj; return obj;
case JS_INTEROP_INSTANCE_SIGNAL_CONTEXT: case JS_INTEROP_INSTANCE_SIGNAL_CONTEXT:
JS_Interop_ClassData* data = (JS_Interop_ClassData*) js_mallocz(ctx, \ JS_Interop_ClassData* data = (JS_Interop_ClassData*)js_mallocz(ctx,
sizeof(JS_Interop_ClassData)); sizeof(JS_Interop_ClassData));
data->ctx = ctx; data->ctx = ctx;
data->instance = instance; data->instance = instance;
@ -204,8 +210,7 @@ static void* JS_Interop_GetInstance(JSValue obj, JS_ClassId classId, JS_Interop_
return nullptr; return nullptr;
} }
static JSValue JS_Interop_CreateFromInstance(JSContext* ctx, JS_ClassId classId, static JSValue JS_Interop_CreateFromInstance(JSContext* ctx, JS_ClassId classId, JS_Interop_InstanceKind kind, void* instance)
JS_Interop_InstanceKind kind, void* instance)
{ {
if (instance == nullptr) if (instance == nullptr)
return JS_NULL; return JS_NULL;

24
src/Generator/Generators/QuickJS/Runtime/CppSharp_QuickJS_Signal.cpp

@ -8,13 +8,13 @@
#include <CppSharp_QuickJS.h> #include <CppSharp_QuickJS.h>
#include <assert.h> #include <assert.h>
extern "C" { extern "C"
{
JSClassID classId__Signal; JSClassID classId__Signal;
// Signal::Signal // Signal::Signal
static JSValue callback_method_Signal_Signal(JSContext* ctx, JSValueConst this_val, static JSValue callback_method_Signal_Signal(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv)
int argc, JSValueConst* argv)
{ {
// if (argc != 1) // if (argc != 1)
// { // {
@ -53,8 +53,7 @@ wrap:
} }
// Signal::connect // Signal::connect
static JSValue callback_method_Signal_connect(JSContext* ctx, JSValueConst this_val, static JSValue callback_method_Signal_connect(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv)
int argc, JSValueConst* argv)
{ {
if (argc < 1 || argc > 1) if (argc < 1 || argc > 1)
{ {
@ -85,8 +84,7 @@ static JSValue callback_method_Signal_connect(JSContext* ctx, JSValueConst this_
} }
// Signal::disconnect // Signal::disconnect
static JSValue callback_method_Signal_disconnect(JSContext* ctx, JSValueConst this_val, static JSValue callback_method_Signal_disconnect(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv)
int argc, JSValueConst* argv)
{ {
if (argc < 1 || argc > 1) if (argc < 1 || argc > 1)
{ {
@ -120,8 +118,7 @@ overload0:
} }
// Signal::isEmpty // Signal::isEmpty
static JSValue callback_method_Signal_isEmpty(JSContext* ctx, JSValueConst this_val, static JSValue callback_method_Signal_isEmpty(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv)
int argc, JSValueConst* argv)
{ {
if (argc > 0) if (argc > 0)
{ {
@ -135,8 +132,7 @@ static JSValue callback_method_Signal_isEmpty(JSContext* ctx, JSValueConst this_
return ____ret; return ____ret;
} }
static JSValue callback_class__Signal_toString(JSContext* ctx, JSValueConst this_val, static JSValue callback_class__Signal_toString(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv)
int argc, JSValueConst* argv)
{ {
return JS_NewString(ctx, "Signal"); return JS_NewString(ctx, "Signal");
} }
@ -155,14 +151,12 @@ void finalizer__Signal(JSRuntime *rt, JSValue val)
JS_SetOpaque(val, nullptr); JS_SetOpaque(val, nullptr);
} }
static JSClassDef classDef__Signal = static JSClassDef classDef__Signal = {
{
.class_name = "Signal", .class_name = "Signal",
.finalizer = finalizer__Signal .finalizer = finalizer__Signal
}; };
static JSCFunctionListEntry funcDef__Signal[] = static JSCFunctionListEntry funcDef__Signal[] = {
{
JS_CFUNC_DEF("connect", 1, callback_method_Signal_connect), JS_CFUNC_DEF("connect", 1, callback_method_Signal_connect),
JS_CFUNC_DEF("disconnect", 1, callback_method_Signal_disconnect), JS_CFUNC_DEF("disconnect", 1, callback_method_Signal_disconnect),
JS_CFUNC_DEF("isEmpty", 0, callback_method_Signal_isEmpty), JS_CFUNC_DEF("isEmpty", 0, callback_method_Signal_isEmpty),

192
tests/Builtins.h

@ -5,60 +5,172 @@
void ReturnsVoid() {} void ReturnsVoid() {}
std::nullptr_t ReturnsNullptr () { return nullptr; } std::nullptr_t ReturnsNullptr()
std::nullptr_t PassAndReturnsNullptr (std::nullptr_t t) { return t; } {
return nullptr;
}
std::nullptr_t PassAndReturnsNullptr(std::nullptr_t t)
{
return t;
}
bool ReturnsBool () { return true; } bool ReturnsBool()
bool PassAndReturnsBool (bool v) { return v; } {
return true;
}
bool PassAndReturnsBool(bool v)
{
return v;
}
// Character types // Character types
char ReturnsChar () { return 'a'; } char ReturnsChar()
signed char ReturnsSChar () { return 'a'; } {
unsigned char ReturnsUChar () { return 'a'; } return 'a';
char PassAndReturnsChar (char v) { return v; } }
signed char PassAndReturnsSChar (signed char v) { return v; } signed char ReturnsSChar()
unsigned char PassAndReturnsUChar (unsigned char v) { return v; } {
return 'a';
}
unsigned char ReturnsUChar()
{
return 'a';
}
char PassAndReturnsChar(char v)
{
return v;
}
signed char PassAndReturnsSChar(signed char v)
{
return v;
}
unsigned char PassAndReturnsUChar(unsigned char v)
{
return v;
}
wchar_t ReturnsWChar () { return 'a'; } wchar_t ReturnsWChar()
{
return 'a';
}
#if __cplusplus > 201703L #if __cplusplus > 201703L
char8_t ReturnsChar8 () { return 'a'; } char8_t ReturnsChar8()
{
return 'a';
}
#endif #endif
char16_t ReturnsChar16 () { return 'a'; } char16_t ReturnsChar16()
char32_t ReturnsChar32 () { return 'a'; } {
return 'a';
}
char32_t ReturnsChar32()
{
return 'a';
}
// Floating-point types // Floating-point types
float ReturnsFloat () { return 5.0; } float ReturnsFloat()
double ReturnsDouble () { return -5.0; } {
long double ReturnsLongDouble () { return -5.0; } return 5.0;
}
double ReturnsDouble()
{
return -5.0;
}
long double ReturnsLongDouble()
{
return -5.0;
}
float PassAndReturnsFloat (float v) { return v; } float PassAndReturnsFloat(float v)
double PassAndReturnsDouble (double v) { return v; } {
long double PassAndReturnsLongDouble (long double v) { return v; } return v;
}
double PassAndReturnsDouble(double v)
{
return v;
}
long double PassAndReturnsLongDouble(long double v)
{
return v;
}
// Integer types // Integer types
int8_t ReturnsInt8 () { return -5; } int8_t ReturnsInt8()
uint8_t ReturnsUInt8 () { return 5; } {
int16_t ReturnsInt16 () { return -5; } return -5;
uint16_t ReturnsUInt16 () { return 5; } }
int32_t ReturnsInt32 () { return -5; } uint8_t ReturnsUInt8()
uint32_t ReturnsUInt32 () { return 5; } {
return 5;
}
int16_t ReturnsInt16()
{
return -5;
}
uint16_t ReturnsUInt16()
{
return 5;
}
int32_t ReturnsInt32()
{
return -5;
}
uint32_t ReturnsUInt32()
{
return 5;
}
#if !defined(__EMSCRIPTEN__) #if !defined(__EMSCRIPTEN__)
int64_t ReturnsInt64 () { return -5; } int64_t ReturnsInt64()
uint64_t ReturnsUInt64 () { return 5; } {
return -5;
}
uint64_t ReturnsUInt64()
{
return 5;
}
#endif #endif
int8_t PassAndReturnsInt8 (int8_t v) { return v; } int8_t PassAndReturnsInt8(int8_t v)
uint8_t PassAndReturnsUInt8 (uint8_t v) { return v; } {
int16_t PassAndReturnsInt16 (int16_t v) { return v; } return v;
uint16_t PassAndReturnsUInt16 (uint16_t v) { return v; } }
int32_t PassAndReturnsInt32 (int32_t v) { return v; } uint8_t PassAndReturnsUInt8(uint8_t v)
uint32_t PassAndReturnsUInt32 (uint32_t v) { return v; } {
int64_t PassAndReturnsInt64 (int64_t v) { return v; } return v;
uint64_t PassAndReturnsUInt64 (uint64_t v) { return v; } }
int16_t PassAndReturnsInt16(int16_t v)
{
return v;
}
uint16_t PassAndReturnsUInt16(uint16_t v)
{
return v;
}
int32_t PassAndReturnsInt32(int32_t v)
{
return v;
}
uint32_t PassAndReturnsUInt32(uint32_t v)
{
return v;
}
int64_t PassAndReturnsInt64(int64_t v)
{
return v;
}
uint64_t PassAndReturnsUInt64(uint64_t v)
{
return v;
}
// Pointer types // Pointer types
const char* ReturnsConstCharPtr() { return "Hello"; } const char* ReturnsConstCharPtr()
const char* PassAndReturnsConstCharPtr(const char* ptr) { return ptr; } {
return "Hello";
}
const char* PassAndReturnsConstCharPtr(const char* ptr)
{
return ptr;
}

6
tests/Classes.h

@ -13,7 +13,10 @@ public:
class ClassWithField class ClassWithField
{ {
public: public:
ClassWithField() : Field(10) {} ClassWithField()
: Field(10)
{
}
int Field; int Field;
int ReturnsField() { return Field; } int ReturnsField() { return Field; }
}; };
@ -35,7 +38,6 @@ public:
class ClassWithExternalInheritance : public ClassFromAnotherUnit class ClassWithExternalInheritance : public ClassFromAnotherUnit
{ {
}; };
// void FunctionPassClassByRef(Class* klass) { } // void FunctionPassClassByRef(Class* klass) { }

1
tests/Classes2.h

@ -2,5 +2,4 @@
class ClassFromAnotherUnit class ClassFromAnotherUnit
{ {
}; };

6
tests/Delegates.h

@ -9,7 +9,11 @@ class ClassWithDelegate
public: public:
ClassWithDelegate() {} ClassWithDelegate() {}
FastDelegate<int(int)> OnEvent0; FastDelegate<int(int)> OnEvent0;
void FireEvent0(int value) { if (OnEvent0) OnEvent0(value); } void FireEvent0(int value)
{
if (OnEvent0)
OnEvent0(value);
}
}; };
class ClassInheritsDelegate : public ClassWithDelegate class ClassInheritsDelegate : public ClassWithDelegate

10
tests/Enums.h

@ -7,5 +7,11 @@ enum class Enum0
Item2 = 5 Item2 = 5
}; };
Enum0 ReturnsEnum() { return Enum0::Item0; } Enum0 ReturnsEnum()
Enum0 PassAndReturnsEnum(Enum0 e) { return e; } {
return Enum0::Item0;
}
Enum0 PassAndReturnsEnum(Enum0 e)
{
return e;
}

45
tests/Overloads.h

@ -2,15 +2,42 @@
void Overload0() {} void Overload0() {}
int Overload1() { return 1; } int Overload1()
int Overload1(int) { return 2; } {
return 1;
}
int Overload1(int)
{
return 2;
}
int Overload(int, int) { return 1; } int Overload(int, int)
int Overload(int, float) { return 2; } {
int Overload(float, int) { return 3; } return 1;
}
int Overload(int, float)
{
return 2;
}
int Overload(float, int)
{
return 3;
}
int DefaultParamsOverload() { return 0; } int DefaultParamsOverload()
int DefaultParamsOverload(int a, int b) { return 2; } {
int DefaultParamsOverload(int a, float b = 2) { return 3; } return 0;
}
int DefaultParamsOverload(int a, int b)
{
return 2;
}
int DefaultParamsOverload(int a, float b = 2)
{
return 3;
}
int DefaultParamsOverload2(int a = 0, int b = 0, int c = 0) { return 1; } int DefaultParamsOverload2(int a = 0, int b = 0, int c = 0)
{
return 1;
}

117
tests/dotnet/CSharp/AnonTypes.h

@ -1,7 +1,8 @@
#ifndef KONAN_EXAMPLE_LIB_H #ifndef KONAN_EXAMPLE_LIB_H
#define KONAN_EXAMPLE_LIB_H #define KONAN_EXAMPLE_LIB_H
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C"
{
#endif #endif
#ifdef __cplusplus #ifdef __cplusplus
typedef bool example_lib_KBoolean; typedef bool example_lib_KBoolean;
@ -23,81 +24,108 @@ extern "C" {
struct example_lib_KType; struct example_lib_KType;
typedef struct example_lib_KType example_lib_KType; typedef struct example_lib_KType example_lib_KType;
typedef struct { typedef struct
{
example_lib_KNativePtr pinned; example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_APIHost; } example_lib_kref_com_plangrid_example_APIHost;
typedef struct { typedef struct
{
example_lib_KNativePtr pinned; example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_APIHost_CACAHUETE; } example_lib_kref_com_plangrid_example_APIHost_CACAHUETE;
typedef struct { typedef struct
{
example_lib_KNativePtr pinned; example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_APIHost_CAPI; } example_lib_kref_com_plangrid_example_APIHost_CAPI;
typedef struct { typedef struct
{
example_lib_KNativePtr pinned; example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_Request; } example_lib_kref_com_plangrid_example_Request;
typedef struct { typedef struct
{
example_lib_KNativePtr pinned; example_lib_KNativePtr pinned;
} example_lib_kref_kotlin_collections_Map; } example_lib_kref_kotlin_collections_Map;
typedef struct { typedef struct
{
example_lib_KNativePtr pinned; example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_Request_Method; } example_lib_kref_com_plangrid_example_Request_Method;
typedef struct { typedef struct
{
example_lib_KNativePtr pinned; example_lib_KNativePtr pinned;
} example_lib_kref_kotlin_Any; } example_lib_kref_kotlin_Any;
typedef struct { typedef struct
{
example_lib_KNativePtr pinned; example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_Request_Method_GET; } example_lib_kref_com_plangrid_example_Request_Method_GET;
typedef struct { typedef struct
{
example_lib_KNativePtr pinned; example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_Request_Method_POST; } example_lib_kref_com_plangrid_example_Request_Method_POST;
typedef struct { typedef struct
{
example_lib_KNativePtr pinned; example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_Request_Method_PUT; } example_lib_kref_com_plangrid_example_Request_Method_PUT;
typedef struct { typedef struct
{
example_lib_KNativePtr pinned; example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_Request_Method_DELETE; } example_lib_kref_com_plangrid_example_Request_Method_DELETE;
typedef struct { typedef struct
{
example_lib_KNativePtr pinned; example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_Request_Method_PATCH; } example_lib_kref_com_plangrid_example_Request_Method_PATCH;
typedef struct { typedef struct
{
example_lib_KNativePtr pinned; example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_Request_Response; } example_lib_kref_com_plangrid_example_Request_Response;
typedef struct { typedef struct
{
example_lib_KNativePtr pinned; example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_Request_Response_DataResponse; } example_lib_kref_com_plangrid_example_Request_Response_DataResponse;
typedef struct { typedef struct
{
example_lib_KNativePtr pinned; example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_Request_Response_FileResponse; } example_lib_kref_com_plangrid_example_Request_Response_FileResponse;
typedef struct { typedef struct
{
example_lib_KNativePtr pinned; example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_Request_Response_ErrorResponse; } example_lib_kref_com_plangrid_example_Request_Response_ErrorResponse;
typedef struct { typedef struct
{
example_lib_KNativePtr pinned; example_lib_KNativePtr pinned;
} example_lib_kref_kotlin_Error; } example_lib_kref_kotlin_Error;
typedef struct { typedef struct
{
/* Service functions. */ /* Service functions. */
void (*DisposeStablePointer)(example_lib_KNativePtr ptr); void (*DisposeStablePointer)(example_lib_KNativePtr ptr);
void (*DisposeString)(const char* string); void (*DisposeString)(const char* string);
example_lib_KBoolean (*IsInstance)(example_lib_KNativePtr ref, const example_lib_KType* type); example_lib_KBoolean (*IsInstance)(example_lib_KNativePtr ref, const example_lib_KType* type);
/* User functions. */ /* User functions. */
struct { struct
struct { {
struct { struct
struct { {
struct { struct
struct { {
struct
{
struct
{
struct
{
example_lib_KType* (*_type)(void); example_lib_KType* (*_type)(void);
struct { struct
{
example_lib_kref_com_plangrid_example_APIHost (*get)(); /* enum entry for CACAHUETE. */ example_lib_kref_com_plangrid_example_APIHost (*get)(); /* enum entry for CACAHUETE. */
} CACAHUETE; } CACAHUETE;
struct { struct
{
example_lib_kref_com_plangrid_example_APIHost (*get)(); /* enum entry for CAPI. */ example_lib_kref_com_plangrid_example_APIHost (*get)(); /* enum entry for CAPI. */
} CAPI; } CAPI;
} APIHost; } APIHost;
struct { struct
{
example_lib_KType* (*_type)(void); example_lib_KType* (*_type)(void);
example_lib_kref_com_plangrid_example_Request (*Request)(const char* path, example_lib_kref_kotlin_collections_Map queryParams, const char* body, example_lib_kref_com_plangrid_example_Request_Method method); example_lib_kref_com_plangrid_example_Request (*Request)(const char* path, example_lib_kref_kotlin_collections_Map queryParams, const char* body, example_lib_kref_com_plangrid_example_Request_Method method);
const char* (*get_path)(example_lib_kref_com_plangrid_example_Request thiz); const char* (*get_path)(example_lib_kref_com_plangrid_example_Request thiz);
@ -112,42 +140,53 @@ extern "C" {
const char* (*component3)(example_lib_kref_com_plangrid_example_Request thiz); const char* (*component3)(example_lib_kref_com_plangrid_example_Request thiz);
example_lib_kref_com_plangrid_example_Request_Method (*component4)(example_lib_kref_com_plangrid_example_Request thiz); example_lib_kref_com_plangrid_example_Request_Method (*component4)(example_lib_kref_com_plangrid_example_Request thiz);
example_lib_kref_com_plangrid_example_Request (*copy)(example_lib_kref_com_plangrid_example_Request thiz, const char* path, example_lib_kref_kotlin_collections_Map queryParams, const char* body, example_lib_kref_com_plangrid_example_Request_Method method); example_lib_kref_com_plangrid_example_Request (*copy)(example_lib_kref_com_plangrid_example_Request thiz, const char* path, example_lib_kref_kotlin_collections_Map queryParams, const char* body, example_lib_kref_com_plangrid_example_Request_Method method);
struct { struct
{
example_lib_KType* (*_type)(void); example_lib_KType* (*_type)(void);
struct { struct
{
example_lib_kref_com_plangrid_example_Request_Method (*get)(); /* enum entry for GET. */ example_lib_kref_com_plangrid_example_Request_Method (*get)(); /* enum entry for GET. */
} GET; } GET;
struct { struct
{
example_lib_kref_com_plangrid_example_Request_Method (*get)(); /* enum entry for POST. */ example_lib_kref_com_plangrid_example_Request_Method (*get)(); /* enum entry for POST. */
} POST; } POST;
struct { struct
{
example_lib_kref_com_plangrid_example_Request_Method (*get)(); /* enum entry for PUT. */ example_lib_kref_com_plangrid_example_Request_Method (*get)(); /* enum entry for PUT. */
} PUT; } PUT;
struct { struct
{
example_lib_kref_com_plangrid_example_Request_Method (*get)(); /* enum entry for DELETE. */ example_lib_kref_com_plangrid_example_Request_Method (*get)(); /* enum entry for DELETE. */
} DELETE; } DELETE;
struct { struct
{
example_lib_kref_com_plangrid_example_Request_Method (*get)(); /* enum entry for PATCH. */ example_lib_kref_com_plangrid_example_Request_Method (*get)(); /* enum entry for PATCH. */
} PATCH; } PATCH;
} Method; } Method;
struct { struct
{
example_lib_KType* (*_type)(void); example_lib_KType* (*_type)(void);
struct { struct
{
example_lib_KType* (*_type)(void); example_lib_KType* (*_type)(void);
example_lib_kref_com_plangrid_example_Request_Response_DataResponse (*DataResponse)(const char* data); example_lib_kref_com_plangrid_example_Request_Response_DataResponse (*DataResponse)(const char* data);
const char* (*get_data)(example_lib_kref_com_plangrid_example_Request_Response_DataResponse thiz); const char* (*get_data)(example_lib_kref_com_plangrid_example_Request_Response_DataResponse thiz);
} DataResponse; } DataResponse;
struct { struct
{
example_lib_KType* (*_type)(void); example_lib_KType* (*_type)(void);
example_lib_kref_com_plangrid_example_Request_Response_FileResponse (*FileResponse)(const char* filePath); example_lib_kref_com_plangrid_example_Request_Response_FileResponse (*FileResponse)(const char* filePath);
const char* (*get_filePath)(example_lib_kref_com_plangrid_example_Request_Response_FileResponse thiz); const char* (*get_filePath)(example_lib_kref_com_plangrid_example_Request_Response_FileResponse thiz);
} FileResponse; } FileResponse;
struct { struct
{
example_lib_KType* (*_type)(void); example_lib_KType* (*_type)(void);
example_lib_kref_com_plangrid_example_Request_Response_ErrorResponse (*ErrorResponse)(example_lib_kref_kotlin_Error error); example_lib_kref_com_plangrid_example_Request_Response_ErrorResponse (*ErrorResponse)(example_lib_kref_kotlin_Error error);
example_lib_kref_kotlin_Error (*get_error)(example_lib_kref_com_plangrid_example_Request_Response_ErrorResponse thiz); example_lib_kref_kotlin_Error (*get_error)(example_lib_kref_com_plangrid_example_Request_Response_ErrorResponse thiz);
} ErrorResponse; } ErrorResponse;
struct { struct
{
int i; int i;
} $serializer; } $serializer;
} Response; } Response;

5
tests/dotnet/CSharp/AnotherUnit.cpp

@ -42,8 +42,7 @@ MultipleInheritance::~MultipleInheritance()
{ {
} }
namespace HasFreeConstant namespace HasFreeConstant {
{
extern const int DLL_API FREE_CONSTANT_IN_NAMESPACE = 5; extern const int DLL_API FREE_CONSTANT_IN_NAMESPACE = 5;
extern const std::string DLL_API STD_STRING_CONSTANT = "test"; extern const std::string DLL_API STD_STRING_CONSTANT = "test";
} } // namespace HasFreeConstant

6
tests/dotnet/CSharp/AnotherUnit.h

@ -23,6 +23,7 @@ public:
void function(bool* ok = 0); void function(bool* ok = 0);
typedef void HasPointerToEnum(Property* pointerToEnum); typedef void HasPointerToEnum(Property* pointerToEnum);
HasPointerToEnum* hasPointerToEnum; HasPointerToEnum* hasPointerToEnum;
protected: protected:
void protectedFunction(); void protectedFunction();
int protectedProperty(); int protectedProperty();
@ -52,8 +53,7 @@ public:
~MultipleInheritance(); ~MultipleInheritance();
}; };
namespace HasFreeConstant namespace HasFreeConstant {
{
extern const int DLL_API FREE_CONSTANT_IN_NAMESPACE; extern const int DLL_API FREE_CONSTANT_IN_NAMESPACE;
extern const std::string DLL_API STD_STRING_CONSTANT; extern const std::string DLL_API STD_STRING_CONSTANT;
} } // namespace HasFreeConstant

255
tests/dotnet/CSharp/CSharp.cpp

@ -4,7 +4,8 @@ Foo::Foo(const QString& name)
{ {
} }
Foo::Foo(const char* name) : publicFieldMappedToEnum(TestFlag::Flag2) Foo::Foo(const char* name)
: publicFieldMappedToEnum(TestFlag::Flag2)
{ {
A = 10; A = 10;
P = 50; P = 50;
@ -14,7 +15,8 @@ Foo::Foo(const char* name) : publicFieldMappedToEnum(TestFlag::Flag2)
} }
} }
Foo::Foo(int a, int p) : publicFieldMappedToEnum(TestFlag::Flag2) Foo::Foo(int a, int p)
: publicFieldMappedToEnum(TestFlag::Flag2)
{ {
A = a; A = a;
P = p; P = p;
@ -28,8 +30,11 @@ Foo::Foo(wchar_t ch)
{ {
} }
Foo::Foo(const Foo& other) : A(other.A), P(other.P), Foo::Foo(const Foo& other)
templateInAnotherUnit(other.templateInAnotherUnit), _name(other._name) : A(other.A)
, P(other.P)
, templateInAnotherUnit(other.templateInAnotherUnit)
, _name(other._name)
{ {
} }
@ -106,9 +111,18 @@ int Foo::getGetPropertyCall()
return 1; return 1;
} }
SmallPOD Foo::getSmallPod_cdecl() { return { 10000, 40000 }; } SmallPOD Foo::getSmallPod_cdecl()
SmallPOD Foo::getSmallPod_stdcall() { return { 10000, 40000 }; } {
SmallPOD Foo::getSmallPod_thiscall() { return { 10000, 40000 }; } return { 10000, 40000 };
}
SmallPOD Foo::getSmallPod_stdcall()
{
return { 10000, 40000 };
}
SmallPOD Foo::getSmallPod_thiscall()
{
return { 10000, 40000 };
}
int Foo::operator++() int Foo::operator++()
{ {
@ -130,24 +144,25 @@ const Foo& Bar::operator[](int i) const
return m_foo; return m_foo;
} }
Quux::Quux() : _setterWithDefaultOverload(0) Quux::Quux()
: _setterWithDefaultOverload(0)
{ {
} }
Quux::Quux(int i) : Quux() Quux::Quux(int i)
: Quux()
{ {
priv = i; priv = i;
} }
Quux::Quux(char c) : Quux() Quux::Quux(char c)
: Quux()
{ {
} }
Quux::Quux(Foo f) : Quux() Quux::Quux(Foo f)
: Quux()
{ {
} }
Quux::~Quux() Quux::~Quux()
@ -176,7 +191,6 @@ void Quux::setSetterWithDefaultOverload(Foo* value)
QColor::QColor(Qt::GlobalColor color) QColor::QColor(Qt::GlobalColor color)
{ {
} }
Qux::Qux() Qux::Qux()
@ -206,7 +220,6 @@ int Qux::farAwayFunc() const
void Qux::obsolete() void Qux::obsolete()
{ {
} }
Qux* Qux::getInterface() Qux* Qux::getInterface()
@ -232,7 +245,8 @@ int Qux::type() const
return 0; return 0;
} }
Bar::Bar() : index(0) Bar::Bar()
: index(0)
{ {
} }
@ -293,9 +307,14 @@ int Bar::type() const
return 1; return 1;
} }
Baz::Baz() : P(5), functionTypedef(0) {} Baz::Baz()
: P(5)
, functionTypedef(0)
{
}
Baz::Baz(Bar::Items item) : Baz() Baz::Baz(Bar::Items item)
: Baz()
{ {
} }
@ -342,18 +361,27 @@ int AbstractProprietor::parent() const
return 0; return 0;
} }
AbstractProprietor::AbstractProprietor() : m_value(0), m_property(0) AbstractProprietor::AbstractProprietor()
: m_value(0)
, m_property(0)
{ {
} }
AbstractProprietor::AbstractProprietor(int i) : AbstractProprietor() AbstractProprietor::AbstractProprietor(int i)
: AbstractProprietor()
{ {
} }
Proprietor::Proprietor() : _items(Bar::Items::Item1), _itemsByValue(Bar::Items::Item1) {} Proprietor::Proprietor()
: _items(Bar::Items::Item1)
, _itemsByValue(Bar::Items::Item1)
{
}
Proprietor::Proprietor(int i) : AbstractProprietor(i), Proprietor::Proprietor(int i)
_items(Bar::Items::Item1), _itemsByValue(Bar::Items::Item1) : AbstractProprietor(i)
, _items(Bar::Items::Item1)
, _itemsByValue(Bar::Items::Item1)
{ {
} }
@ -403,11 +431,13 @@ long P::prop()
return m_property + 100; return m_property + 100;
} }
ComplexType::ComplexType() : qFlags(QFlags<TestFlag>(TestFlag::Flag2)) ComplexType::ComplexType()
: qFlags(QFlags<TestFlag>(TestFlag::Flag2))
{ {
} }
ComplexType::ComplexType(const QFlags<TestFlag> f) : qFlags(f) ComplexType::ComplexType(const QFlags<TestFlag> f)
: qFlags(f)
{ {
} }
@ -427,17 +457,14 @@ QFlags<TestFlag> ComplexType::returnsQFlags()
void ComplexType::takesQFlags(const QFlags<int> f) void ComplexType::takesQFlags(const QFlags<int> f)
{ {
} }
P::P(const Qux& qux) P::P(const Qux& qux)
{ {
} }
P::P(Qux* qux) P::P(Qux* qux)
{ {
} }
ComplexType P::complexType() ComplexType P::complexType()
@ -452,7 +479,6 @@ void P::setComplexType(const ComplexType& value)
void P::parent(int i) void P::parent(int i)
{ {
} }
bool P::isTest() bool P::isTest()
@ -462,12 +488,10 @@ bool P::isTest()
void P::setTest(bool value) void P::setTest(bool value)
{ {
} }
void P::test() void P::test()
{ {
} }
bool P::isBool() bool P::isBool()
@ -477,7 +501,6 @@ bool P::isBool()
void P::setIsBool(bool value) void P::setIsBool(bool value)
{ {
} }
void TestDestructors::InitMarker() void TestDestructors::InitMarker()
@ -485,12 +508,20 @@ void TestDestructors::InitMarker()
Marker = 0; Marker = 0;
} }
TestDestructors::TestDestructors() { Marker = 0xf00d; } TestDestructors::TestDestructors()
TestDestructors::~TestDestructors() { Marker = 0xcafe; } {
Marker = 0xf00d;
}
TestDestructors::~TestDestructors()
{
Marker = 0xcafe;
}
int TestDestructors::Marker = 0; int TestDestructors::Marker = 0;
TestCopyConstructorVal::TestCopyConstructorVal() : A(0), B(0) TestCopyConstructorVal::TestCopyConstructorVal()
: A(0)
, B(0)
{ {
} }
@ -527,7 +558,8 @@ QFlags<Flags> UsesPointerToEnumInParamOfVirtual::hasPointerToEnumInParam(const Q
} }
QFlags<Flags> UsesPointerToEnumInParamOfVirtual::callOverrideOfHasPointerToEnumInParam( QFlags<Flags> UsesPointerToEnumInParamOfVirtual::callOverrideOfHasPointerToEnumInParam(
const UsesPointerToEnumInParamOfVirtual* object, const QFlags<Flags>& pointerToEnum) const UsesPointerToEnumInParamOfVirtual* object,
const QFlags<Flags>& pointerToEnum)
{ {
return object->hasPointerToEnumInParam(pointerToEnum); return object->hasPointerToEnumInParam(pointerToEnum);
} }
@ -542,8 +574,8 @@ UntypedFlags operator|(UntypedFlags lhs, UntypedFlags rhs)
return static_cast<UntypedFlags>(static_cast<int>(lhs) | static_cast<int>(rhs)); return static_cast<UntypedFlags>(static_cast<int>(lhs) | static_cast<int>(rhs));
} }
QGenericArgument::QGenericArgument(const char* name, const void* data) : QGenericArgument::QGenericArgument(const char* name, const void* data)
fixedArrayInValueType { 0 } : fixedArrayInValueType{ 0 }
{ {
_name = name; _name = name;
} }
@ -891,8 +923,14 @@ void PropertyWithIgnoredType::setIgnoredType(const IgnoredType& value)
_ignoredType = value; _ignoredType = value;
} }
MI_A0::MI_A0() : F(50) {} MI_A0::MI_A0()
int MI_A0::get() { return F; }; : F(50)
{
}
int MI_A0::get()
{
return F;
};
MI_A::MI_A() {} MI_A::MI_A() {}
void MI_A::v(int i) {} void MI_A::v(int i) {}
@ -1050,7 +1088,9 @@ TestParamToInterfacePass::TestParamToInterfacePass(TestParamToInterfacePassBaseT
this->setM(b.getM()); this->setM(b.getM());
} }
TestParamToInterfacePass::TestParamToInterfacePass() : TestParamToInterfacePassBaseOne(), TestParamToInterfacePassBaseTwo() TestParamToInterfacePass::TestParamToInterfacePass()
: TestParamToInterfacePassBaseOne()
, TestParamToInterfacePassBaseTwo()
{ {
} }
@ -1161,7 +1201,8 @@ void QObject::event()
{ {
} }
QPaintDevice::QPaintDevice() : test(0) QPaintDevice::QPaintDevice()
: test(0)
{ {
} }
@ -1209,15 +1250,18 @@ InheritsFromHasSamePropertyInDerivedAbstractType::~InheritsFromHasSamePropertyIn
{ {
} }
MultipleInheritanceFieldOffsetsSecondaryBase::MultipleInheritanceFieldOffsetsSecondaryBase() : secondary(2) MultipleInheritanceFieldOffsetsSecondaryBase::MultipleInheritanceFieldOffsetsSecondaryBase()
: secondary(2)
{ {
} }
MultipleInheritanceFieldOffsetsPrimaryBase::MultipleInheritanceFieldOffsetsPrimaryBase() : primary(1) MultipleInheritanceFieldOffsetsPrimaryBase::MultipleInheritanceFieldOffsetsPrimaryBase()
: primary(1)
{ {
} }
MultipleInheritanceFieldOffsets::MultipleInheritanceFieldOffsets() : own(3) MultipleInheritanceFieldOffsets::MultipleInheritanceFieldOffsets()
: own(3)
{ {
} }
@ -1322,12 +1366,14 @@ const float StaticVariables::FloatArray[2] { 0.5020f, 0.6020f };
const bool StaticVariables::BoolArray[2]{ false, true }; const bool StaticVariables::BoolArray[2]{ false, true };
const void* StaticVariables::VoidPtrArray[2]{ (void*)0x10203040, (void*)0x40302010 }; const void* StaticVariables::VoidPtrArray[2]{ (void*)0x10203040, (void*)0x40302010 };
TestString::TestString() : unicodeConst(L"ქართული ენა"), unicode(0) TestString::TestString()
: unicodeConst(L"ქართული ენა")
, unicode(0)
{ {
} }
TestChar32String::TestChar32String() : TestChar32String::TestChar32String()
thirtyTwoBitConst(U"ქართული ენა") : thirtyTwoBitConst(U"ქართული ენა")
{ {
static std::u32string nonConst = U"Test String"; static std::u32string nonConst = U"Test String";
thirtyTwoBitNonConst = &nonConst[0]; thirtyTwoBitNonConst = &nonConst[0];
@ -1340,11 +1386,14 @@ void TestChar32String::UpdateString(const char32_t* s)
thirtyTwoBitConst = nativeOwnedMemory.data(); thirtyTwoBitConst = nativeOwnedMemory.data();
} }
const char32_t* TestChar32String::RetrieveString() { return thirtyTwoBitConst; } const char32_t* TestChar32String::RetrieveString()
{
return thirtyTwoBitConst;
}
void TestChar32String::functionPointerUTF32(void (*ptr)(const char32_t*)) {} void TestChar32String::functionPointerUTF32(void (*ptr)(const char32_t*)) {}
TestChar16String::TestChar16String() : TestChar16String::TestChar16String()
sixteenBitConst(u"ქართული ენა") : sixteenBitConst(u"ქართული ენა")
{ {
static std::u16string nonConst = u"Test String"; static std::u16string nonConst = u"Test String";
sixteenBitNonConst = &nonConst[0]; sixteenBitNonConst = &nonConst[0];
@ -1357,7 +1406,10 @@ void TestChar16String::UpdateString(const char16_t* s)
static std::u16string nativeOwnedMemory = s; static std::u16string nativeOwnedMemory = s;
sixteenBitConst = nativeOwnedMemory.data(); sixteenBitConst = nativeOwnedMemory.data();
} }
const char16_t* TestChar16String::RetrieveString() { return sixteenBitConst; } const char16_t* TestChar16String::RetrieveString()
{
return sixteenBitConst;
}
void decltypeFunctionPointer() {} void decltypeFunctionPointer() {}
@ -1399,7 +1451,8 @@ AbstractSecondaryBase::~AbstractSecondaryBase()
{ {
} }
ImplementsAbstractsFromPrimaryAndSecondary::ImplementsAbstractsFromPrimaryAndSecondary() : field(200) ImplementsAbstractsFromPrimaryAndSecondary::ImplementsAbstractsFromPrimaryAndSecondary()
: field(200)
{ {
} }
@ -1445,7 +1498,8 @@ void hasArrayOfConstChar(const char* const arrayOfConstChar[])
{ {
} }
struct IncompleteStruct {}; struct IncompleteStruct
{};
IncompleteStruct* createIncompleteStruct() IncompleteStruct* createIncompleteStruct()
{ {
@ -1457,7 +1511,8 @@ DLL_API void useIncompleteStruct(IncompleteStruct * a)
return; return;
} }
struct DuplicateDeclaredStruct { struct DuplicateDeclaredStruct
{
int i = 0; int i = 0;
}; };
@ -1485,11 +1540,15 @@ DLL_API int useDuplicateDeclaredStruct(DuplicateDeclaredStruct* s)
return s->i; return s->i;
} }
ComplexArrayElement::ComplexArrayElement() : BoolField(false), IntField(0), FloatField(0) ComplexArrayElement::ComplexArrayElement()
: BoolField(false)
, IntField(0)
, FloatField(0)
{ {
} }
TestIndexedProperties::TestIndexedProperties() : field(0) TestIndexedProperties::TestIndexedProperties()
: field(0)
{ {
} }
@ -1531,8 +1590,7 @@ int TestArrays::takeArrays(Foo* arrayOfPointersToObjects[], int arrayOfPrimitive
arrayOfObjects[0].A + arrayOfObjects[1].A; arrayOfObjects[0].A + arrayOfObjects[1].A;
} }
int TestArrays::takeArrays(Foo* fixedArrayOfPointersToObjects[3], int fixedArrayOfPrimitives[4], int TestArrays::takeArrays(Foo* fixedArrayOfPointersToObjects[3], int fixedArrayOfPrimitives[4], int* fixedArrayOfPointersToPrimitives[5]) const
int* fixedArrayOfPointersToPrimitives[5]) const
{ {
int sum = 0; int sum = 0;
for (int i = 0; i < 3; i++) for (int i = 0; i < 3; i++)
@ -1575,7 +1633,8 @@ int TestArrays::virtualTakeArrays(Foo *fixedArrayOfPointersToObjects[3], int fix
return takeArrays(fixedArrayOfPointersToObjects, fixedArrayOfPrimitives, fixedArrayOfPointersToPrimitives); return takeArrays(fixedArrayOfPointersToObjects, fixedArrayOfPrimitives, fixedArrayOfPointersToPrimitives);
} }
InterfaceTester::InterfaceTester() : interface(0) InterfaceTester::InterfaceTester()
: interface(0)
{ {
} }
@ -1678,15 +1737,32 @@ const char32_t* TestCSharpString32(const char32_t* in, const char32_t** out)
return ret.data(); return ret.data();
} }
ConversionFunctions::operator short* () { return &field; } ConversionFunctions::operator short*()
ConversionFunctions::operator short& () { return field; } {
ConversionFunctions::operator short() { return field; } return &field;
ConversionFunctions::operator const short*() const { return &field; } }
ConversionFunctions::operator const short&() const { return field; } ConversionFunctions::operator short&()
ConversionFunctions::operator const short() const { return field; } {
return field;
const unsigned ClassCustomTypeAlignmentOffsets[5] }
ConversionFunctions::operator short()
{
return field;
}
ConversionFunctions::operator const short*() const
{ {
return &field;
}
ConversionFunctions::operator const short&() const
{
return field;
}
ConversionFunctions::operator const short() const
{
return field;
}
const unsigned ClassCustomTypeAlignmentOffsets[5]{
offsetof(ClassCustomTypeAlignment, boolean), offsetof(ClassCustomTypeAlignment, boolean),
offsetof(ClassCustomTypeAlignment, align16), offsetof(ClassCustomTypeAlignment, align16),
offsetof(ClassCustomTypeAlignment, align1), offsetof(ClassCustomTypeAlignment, align1),
@ -1699,28 +1775,47 @@ const unsigned ClassCustomObjectAlignmentOffsets[2] {
offsetof(ClassCustomObjectAlignment, charAligned8), offsetof(ClassCustomObjectAlignment, charAligned8),
}; };
const unsigned ClassMicrosoftObjectAlignmentOffsets[4] const unsigned ClassMicrosoftObjectAlignmentOffsets[4]{
{
offsetof(ClassMicrosoftObjectAlignment, u8), offsetof(ClassMicrosoftObjectAlignment, u8),
offsetof(ClassMicrosoftObjectAlignment, dbl), offsetof(ClassMicrosoftObjectAlignment, dbl),
offsetof(ClassMicrosoftObjectAlignment, i16), offsetof(ClassMicrosoftObjectAlignment, i16),
offsetof(ClassMicrosoftObjectAlignment, boolean), offsetof(ClassMicrosoftObjectAlignment, boolean),
}; };
const unsigned StructWithEmbeddedArrayOfStructObjectAlignmentOffsets[2] const unsigned StructWithEmbeddedArrayOfStructObjectAlignmentOffsets[2]{
{
offsetof(StructWithEmbeddedArrayOfStructObjectAlignment, boolean), offsetof(StructWithEmbeddedArrayOfStructObjectAlignment, boolean),
offsetof(StructWithEmbeddedArrayOfStructObjectAlignment, embedded_struct), offsetof(StructWithEmbeddedArrayOfStructObjectAlignment, embedded_struct),
}; };
DLL_API FTIStruct TestFunctionToStaticMethod(FTIStruct* bb) { return { 6 }; } DLL_API FTIStruct TestFunctionToStaticMethod(FTIStruct* bb)
DLL_API int TestFunctionToStaticMethodStruct(FTIStruct* bb, FTIStruct defaultValue) { return defaultValue.a; } {
DLL_API int TestFunctionToStaticMethodRefStruct(FTIStruct* bb, FTIStruct& defaultValue) { return defaultValue.a; } return { 6 };
DLL_API int TestFunctionToStaticMethodConstStruct(FTIStruct* bb, const FTIStruct defaultValue) { return defaultValue.a; } }
DLL_API int TestFunctionToStaticMethodConstRefStruct(FTIStruct* bb, const FTIStruct& defaultValue) { return defaultValue.a; } DLL_API int TestFunctionToStaticMethodStruct(FTIStruct* bb, FTIStruct defaultValue)
{
return defaultValue.a;
}
DLL_API int TestFunctionToStaticMethodRefStruct(FTIStruct* bb, FTIStruct& defaultValue)
{
return defaultValue.a;
}
DLL_API int TestFunctionToStaticMethodConstStruct(FTIStruct* bb, const FTIStruct defaultValue)
{
return defaultValue.a;
}
DLL_API int TestFunctionToStaticMethodConstRefStruct(FTIStruct* bb, const FTIStruct& defaultValue)
{
return defaultValue.a;
}
DLL_API int TestClassFunctionToInstanceMethod(TestClass* bb, int value) { return value * value; } DLL_API int TestClassFunctionToInstanceMethod(TestClass* bb, int value)
DLL_API int TestClassFunctionToInstanceMethod(TestClass* bb, FTIStruct& value) { return value.a * value.a; } {
return value * value;
}
DLL_API int TestClassFunctionToInstanceMethod(TestClass* bb, FTIStruct& value)
{
return value.a * value.a;
}
int RuleOfThreeTester::constructorCalls = 0; int RuleOfThreeTester::constructorCalls = 0;
int RuleOfThreeTester::destructorCalls = 0; int RuleOfThreeTester::destructorCalls = 0;

296
tests/dotnet/CSharp/CSharp.h

@ -150,13 +150,16 @@ class DLL_API ForceCreationOfInterface : public Foo, public Bar
class DLL_API Baz : public Foo, public Bar class DLL_API Baz : public Foo, public Bar
{ {
public: public:
class NestedBase1 { class NestedBase1
{
int f1; int f1;
double f2; double f2;
void* f3; void* f3;
}; };
class NestedBase2 {}; class NestedBase2
class NestedDerived : public NestedBase1, public NestedBase2 {}; {};
class NestedDerived : public NestedBase1, public NestedBase2
{};
Baz(); Baz();
Baz(Bar::Items item); Baz(Bar::Items item);
@ -222,6 +225,7 @@ public:
Bar::Items itemsByValue() const; Bar::Items itemsByValue() const;
void setItemsByValue(Bar::Items value); void setItemsByValue(Bar::Items value);
private: private:
Bar::Items _items; Bar::Items _items;
Bar::Items _itemsByValue; Bar::Items _itemsByValue;
@ -238,6 +242,7 @@ public:
int check(); int check();
QFlags<TestFlag> returnsQFlags(); QFlags<TestFlag> returnsQFlags();
void takesQFlags(const QFlags<int> f); void takesQFlags(const QFlags<int> f);
private: private:
QFlags<TestFlag> qFlags; QFlags<TestFlag> qFlags;
}; };
@ -293,6 +298,7 @@ public:
void name(); void name();
void Name(); void Name();
int property(); int property();
protected: protected:
int _property; int _property;
}; };
@ -317,7 +323,8 @@ public:
virtual ~UsesPointerToEnumInParamOfVirtual(); virtual ~UsesPointerToEnumInParamOfVirtual();
virtual QFlags<Flags> hasPointerToEnumInParam(const QFlags<Flags>& pointerToEnum) const; virtual QFlags<Flags> hasPointerToEnumInParam(const QFlags<Flags>& pointerToEnum) const;
static QFlags<Flags> callOverrideOfHasPointerToEnumInParam( static QFlags<Flags> callOverrideOfHasPointerToEnumInParam(
const UsesPointerToEnumInParamOfVirtual* object, const QFlags<Flags>& pointerToEnum); const UsesPointerToEnumInParamOfVirtual* object,
const QFlags<Flags>& pointerToEnum);
}; };
DLL_API Flags operator|(Flags lhs, Flags rhs); DLL_API Flags operator|(Flags lhs, Flags rhs);
@ -336,6 +343,7 @@ struct DLL_API QGenericArgument
public: public:
QGenericArgument(const char* name = 0, const void* data = 0); QGenericArgument(const char* name = 0, const void* data = 0);
void* fixedArrayInValueType[1]; void* fixedArrayInValueType[1];
private: private:
const char* _name; const char* _name;
}; };
@ -346,13 +354,13 @@ class TestObjectMapWithClassDerivedFromStruct : public QGenericArgument
#define DEFAULT_INT (2 * 1000UL + 500UL) #define DEFAULT_INT (2 * 1000UL + 500UL)
namespace Qt namespace Qt {
enum GlobalColor
{ {
enum GlobalColor {
black, black,
white, white,
}; };
} } // namespace Qt
class DLL_API QColor class DLL_API QColor
{ {
@ -383,14 +391,13 @@ public:
QRect(QPoint p, QSize s); QRect(QPoint p, QSize s);
}; };
namespace lowerCaseNameSpace namespace lowerCaseNameSpace {
{
enum class Enum enum class Enum
{ {
Item1, Item1,
Item2 Item2
}; };
} } // namespace lowerCaseNameSpace
class DLL_API DefaultZeroMappedToEnum class DLL_API DefaultZeroMappedToEnum
{ {
@ -402,7 +409,8 @@ enum class Empty : unsigned long long int
{ {
}; };
class _ClassWithLeadingUnderscore { class _ClassWithLeadingUnderscore
{
}; };
const int ConstFlag1 = 1; const int ConstFlag1 = 1;
@ -492,6 +500,7 @@ public:
SmallPOD* defaultWithNonPrimitiveType(SmallPOD& pod = DefaultSmallPODInstance); SmallPOD* defaultWithNonPrimitiveType(SmallPOD& pod = DefaultSmallPODInstance);
int DefaultWithParamNamedSameAsMethod(int DefaultWithParamNamedSameAsMethod, const Foo& defaultArg = Foo()); int DefaultWithParamNamedSameAsMethod(int DefaultWithParamNamedSameAsMethod, const Foo& defaultArg = Foo());
int getA(); int getA();
private: private:
Foo m_foo; Foo m_foo;
}; };
@ -502,6 +511,7 @@ class HasPureVirtualWithDefaultArg
public: public:
virtual ~HasPureVirtualWithDefaultArg() {} virtual ~HasPureVirtualWithDefaultArg() {}
virtual void pureVirtualWithDefaultArg(Foo* foo = nullptr) = 0; virtual void pureVirtualWithDefaultArg(Foo* foo = nullptr) = 0;
protected: protected:
HasPureVirtualWithDefaultArg() {} HasPureVirtualWithDefaultArg() {}
}; };
@ -510,8 +520,10 @@ class DLL_API HasOverridesWithChangedAccessBase
{ {
public: public:
virtual void privateOverride(int i = 5); virtual void privateOverride(int i = 5);
protected: protected:
virtual void publicOverride(); virtual void publicOverride();
private: private:
virtual void differentIncreasedAccessOverride(); virtual void differentIncreasedAccessOverride();
}; };
@ -520,6 +532,7 @@ class DLL_API HasOverridesWithChangedAccess : public HasOverridesWithChangedAcce
{ {
public: public:
void publicOverride(); void publicOverride();
private: private:
virtual void privateOverride(int i); virtual void privateOverride(int i);
}; };
@ -544,9 +557,7 @@ public:
virtual int property() = 0; virtual int property() = 0;
}; };
class DLL_API IgnoredType class DLL_API IgnoredType{};
{
};
class DLL_API IgnoredTypeInheritingNonIgnoredWithNoEmptyCtor : public P class DLL_API IgnoredTypeInheritingNonIgnoredWithNoEmptyCtor : public P
{ {
@ -557,6 +568,7 @@ class DLL_API HasOverriddenInManaged
public: public:
void setOverriddenInManaged(Baz* value); void setOverriddenInManaged(Baz* value);
int callOverriddenInManaged(); int callOverriddenInManaged();
private: private:
Baz* overriddenInManaged = 0; Baz* overriddenInManaged = 0;
}; };
@ -566,6 +578,7 @@ class DLL_API PropertyWithIgnoredType
public: public:
IgnoredType ignoredType(); IgnoredType ignoredType();
void setIgnoredType(const IgnoredType& value); void setIgnoredType(const IgnoredType& value);
private: private:
IgnoredType _ignoredType; IgnoredType _ignoredType;
}; };
@ -611,8 +624,10 @@ public:
StructWithPrivateFields(int simplePrivateField, Foo complexPrivateField); StructWithPrivateFields(int simplePrivateField, Foo complexPrivateField);
int getSimplePrivateField(); int getSimplePrivateField();
Foo getComplexPrivateField(); Foo getComplexPrivateField();
protected: protected:
int protectedField; int protectedField;
private: private:
int simplePrivateField; int simplePrivateField;
Foo complexPrivateField; Foo complexPrivateField;
@ -636,7 +651,8 @@ public:
class iterator class iterator
{ {
public: public:
int test() { int test()
{
return 1; return 1;
} }
friend class const_iterator; friend class const_iterator;
@ -653,11 +669,32 @@ public:
}; };
#define Q_PROCESSOR_WORDSIZE 8 #define Q_PROCESSOR_WORDSIZE 8
template <int> struct QIntegerForSize; template <int>
template <> struct QIntegerForSize<1> { typedef uint8_t Unsigned; typedef int8_t Signed; }; struct QIntegerForSize;
template <> struct QIntegerForSize<2> { typedef uint16_t Unsigned; typedef int16_t Signed; }; template <>
template <> struct QIntegerForSize<4> { typedef uint32_t Unsigned; typedef int32_t Signed; }; struct QIntegerForSize<1>
template <> struct QIntegerForSize<8> { typedef uint64_t Unsigned; typedef int64_t Signed; }; {
typedef uint8_t Unsigned;
typedef int8_t Signed;
};
template <>
struct QIntegerForSize<2>
{
typedef uint16_t Unsigned;
typedef int16_t Signed;
};
template <>
struct QIntegerForSize<4>
{
typedef uint32_t Unsigned;
typedef int32_t Signed;
};
template <>
struct QIntegerForSize<8>
{
typedef uint64_t Unsigned;
typedef int64_t Signed;
};
typedef QIntegerForSize<Q_PROCESSOR_WORDSIZE>::Signed qregisterint; typedef QIntegerForSize<Q_PROCESSOR_WORDSIZE>::Signed qregisterint;
typedef QIntegerForSize<Q_PROCESSOR_WORDSIZE>::Unsigned qregisteruint; typedef QIntegerForSize<Q_PROCESSOR_WORDSIZE>::Unsigned qregisteruint;
@ -684,6 +721,7 @@ public:
virtual ~HasVirtualDtor2(); virtual ~HasVirtualDtor2();
HasVirtualDtor1* getHasVirtualDtor1(); HasVirtualDtor1* getHasVirtualDtor1();
virtual void virtualFunction(const HasVirtualDtor1& param1, const HasVirtualDtor1& param2); virtual void virtualFunction(const HasVirtualDtor1& param1, const HasVirtualDtor1& param2);
private: private:
HasVirtualDtor1* hasVirtualDtor1; HasVirtualDtor1* hasVirtualDtor1;
}; };
@ -696,6 +734,7 @@ public:
HasVirtualDtor2* getHasVirtualDtor2(); HasVirtualDtor2* getHasVirtualDtor2();
Bar* propertyWithNoVirtualDtor() const; Bar* propertyWithNoVirtualDtor() const;
void setPropertyWithNoVirtualDtor(Bar* bar); void setPropertyWithNoVirtualDtor(Bar* bar);
private: private:
HasVirtualDtor2* hasVirtualDtor2; HasVirtualDtor2* hasVirtualDtor2;
Bar* bar; Bar* bar;
@ -727,13 +766,12 @@ public:
void setProperty(int value); void setProperty(int value);
}; };
class DLL_API TestParamToInterfacePassBaseOne class DLL_API TestParamToInterfacePassBaseOne{};
{
};
class DLL_API TestParamToInterfacePassBaseTwo class DLL_API TestParamToInterfacePassBaseTwo
{ {
int m; int m;
public: public:
int getM(); int getM();
void setM(int n); void setM(int n);
@ -793,6 +831,7 @@ public:
class DLL_API MultiOverloadPtrToRef class DLL_API MultiOverloadPtrToRef
{ {
int* arr; int* arr;
public: public:
MultiOverloadPtrToRef(int* param); MultiOverloadPtrToRef(int* param);
void funcPrimitivePtrToRef(int* pOne, char* pTwo, float* pThree, bool* pFour = 0); void funcPrimitivePtrToRef(int* pOne, char* pTwo, float* pThree, bool* pFour = 0);
@ -906,6 +945,7 @@ class DLL_API QWidget : public QObject, QPaintDevice
public: public:
QWidget(); QWidget();
virtual void event(); virtual void event();
private: private:
QObject child; QObject child;
}; };
@ -971,26 +1011,23 @@ class DLL_API ClassWithVirtualBase : public virtual Foo
{ {
}; };
namespace NamespaceA namespace NamespaceA {
{ CS_VALUE_TYPE class DLL_API A{};
CS_VALUE_TYPE class DLL_API A
{
};
} }
namespace NamespaceB namespace NamespaceB {
{
class DLL_API B class DLL_API B
{ {
public: public:
void Function(CS_OUT NamespaceA::A& a); void Function(CS_OUT NamespaceA::A& a);
}; };
} } // namespace NamespaceB
class DLL_API HasPrivateVirtualProperty class DLL_API HasPrivateVirtualProperty
{ {
public: public:
virtual ~HasPrivateVirtualProperty(); virtual ~HasPrivateVirtualProperty();
private: private:
virtual int property(); virtual int property();
virtual void protectedAbstractMethod() = 0; virtual void protectedAbstractMethod() = 0;
@ -1004,6 +1041,7 @@ protected:
virtual void protectedAbstractMethod(); virtual void protectedAbstractMethod();
virtual void protectedMethod(); virtual void protectedMethod();
virtual int protectedProperty(); virtual int protectedProperty();
private: private:
virtual int property(); virtual int property();
}; };
@ -1031,13 +1069,15 @@ public:
// https://github.com/mono/CppSharp/issues/1283 // https://github.com/mono/CppSharp/issues/1283
namespace NamespaceWithVirtualPropertyClass { namespace NamespaceWithVirtualPropertyClass {
class DLL_API HasOverriddenPropertyInNamespacedClass { class DLL_API HasOverriddenPropertyInNamespacedClass
{
public: public:
virtual int property() = 0; virtual int property() = 0;
}; };
} } // namespace NamespaceWithVirtualPropertyClass
class DLL_API TestOverrideOfPropertyInNamespacedClass : public NamespaceWithVirtualPropertyClass::HasOverriddenPropertyInNamespacedClass { class DLL_API TestOverrideOfPropertyInNamespacedClass : public NamespaceWithVirtualPropertyClass::HasOverriddenPropertyInNamespacedClass
{
public: public:
virtual int property() override; virtual int property() override;
}; };
@ -1068,7 +1108,8 @@ public:
DLL_API extern const unsigned char variableWithFixedPrimitiveArray[2]; DLL_API extern const unsigned char variableWithFixedPrimitiveArray[2];
DLL_API extern const unsigned int variableWithVariablePrimitiveArray[]; DLL_API extern const unsigned int variableWithVariablePrimitiveArray[];
class DLL_API StaticVariables { class DLL_API StaticVariables
{
public: public:
static const bool Boolean; static const bool Boolean;
static const char Chr; static const char Chr;
@ -1083,11 +1124,13 @@ public:
static const void* VoidPtrArray[2]; static const void* VoidPtrArray[2];
}; };
DLL_API constexpr double ConstexprCreateDoubleValue(double value) { DLL_API constexpr double ConstexprCreateDoubleValue(double value)
{
return value; return value;
} }
class DLL_API VariablesWithInitializer { class DLL_API VariablesWithInitializer
{
public: public:
static constexpr const char* String = "Str"; static constexpr const char* String = "Str";
static constexpr const wchar_t* WideString = L"Str"; static constexpr const wchar_t* WideString = L"Str";
@ -1102,12 +1145,42 @@ public:
static constexpr double DoubleFromConstexprFunction = ConstexprCreateDoubleValue(0.700020235 + 23.17376); static constexpr double DoubleFromConstexprFunction = ConstexprCreateDoubleValue(0.700020235 + 23.17376);
static constexpr int64_t Int64 = 602030405045; static constexpr int64_t Int64 = 602030405045;
static constexpr uint64_t UInt64 = 9602030405045; static constexpr uint64_t UInt64 = 9602030405045;
static constexpr const char* StringArray1[1] { "Str" "F,\"or" }; static constexpr const char* StringArray1[1]{ "Str"
static constexpr const char* StringArray3[3] { "Str" "F,\"or", "C#", String }; "F,\"or" };
static constexpr const char* StringArray3[3]{ "Str"
"F,\"or",
"C#", String };
static constexpr const char* StringArray30[30]{ static constexpr const char* StringArray30[30]{
"Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str",
"Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str",
"Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
}; };
static constexpr const char* StringArray3EmptyInitList[3]{}; static constexpr const char* StringArray3EmptyInitList[3]{};
static constexpr const wchar_t* WideStringArray[2]{ L"Str", L"C#" }; static constexpr const wchar_t* WideStringArray[2]{ L"Str", L"C#" };
@ -1213,6 +1286,7 @@ class DLL_API HasMissingObjectOnVirtualCall
public: public:
int makeMissingObjectOnVirtualCall(); int makeMissingObjectOnVirtualCall();
void setMissingObjectOnVirtualCall(MissingObjectOnVirtualCall* value); void setMissingObjectOnVirtualCall(MissingObjectOnVirtualCall* value);
private: private:
MissingObjectOnVirtualCall* stackOverflowOnVirtualCall; MissingObjectOnVirtualCall* stackOverflowOnVirtualCall;
}; };
@ -1242,6 +1316,7 @@ public:
virtual int abstractInSecondaryBase(); virtual int abstractInSecondaryBase();
virtual int abstractReturnsFieldInPrimaryBase(); virtual int abstractReturnsFieldInPrimaryBase();
virtual int abstractReturnsFieldInSecondaryBase(); virtual int abstractReturnsFieldInSecondaryBase();
private: private:
int field; int field;
}; };
@ -1257,6 +1332,7 @@ class DLL_API HasGetterAndOverriddenSetter : public HasBaseSetter
public: public:
void setBaseSetter(int value); void setBaseSetter(int value);
int baseSetter(); int baseSetter();
protected: protected:
int field; int field;
}; };
@ -1275,7 +1351,8 @@ struct DLL_API DuplicateDeclaredStruct;
DLL_API DuplicateDeclaredStruct* createDuplicateDeclaredStruct(int i); DLL_API DuplicateDeclaredStruct* createDuplicateDeclaredStruct(int i);
DLL_API int useDuplicateDeclaredStruct(DuplicateDeclaredStruct* s); DLL_API int useDuplicateDeclaredStruct(DuplicateDeclaredStruct* s);
struct DLL_API ForwardDeclaredStruct { struct DLL_API ForwardDeclaredStruct
{
int i = 0; int i = 0;
}; };
@ -1306,7 +1383,11 @@ struct StructTestArrayTypeFromTypedef
#define SIGNED_MACRO_VALUES_TO_ENUM_TEST_3 1L << 32 #define SIGNED_MACRO_VALUES_TO_ENUM_TEST_3 1L << 32
#define SIGNED_MACRO_VALUES_TO_ENUM_TEST_4 -1 #define SIGNED_MACRO_VALUES_TO_ENUM_TEST_4 -1
enum TEST_BOOL_VALUED_ENUMS { TEST_BOOL_VALUED_ENUMS_V1 = true, TEST_BOOL_VALUED_ENUMS_V2 = false}; enum TEST_BOOL_VALUED_ENUMS
{
TEST_BOOL_VALUED_ENUMS_V1 = true,
TEST_BOOL_VALUED_ENUMS_V2 = false
};
#define TEST_BOOL_VALUED_ENUMS_V3 42 #define TEST_BOOL_VALUED_ENUMS_V3 42
struct DLL_API ComplexArrayElement struct DLL_API ComplexArrayElement
@ -1347,8 +1428,7 @@ public:
}; };
inline namespace InlineNamespace inline namespace InlineNamespace {
{
DLL_API void FunctionInsideInlineNamespace(); DLL_API void FunctionInsideInlineNamespace();
} }
@ -1356,13 +1436,11 @@ class DLL_API TestArrays
{ {
public: public:
int takeArrays(Foo* arrayOfPointersToObjects[], int arrayOfPrimitives[], Foo arrayOfObjects[]) const; int takeArrays(Foo* arrayOfPointersToObjects[], int arrayOfPrimitives[], Foo arrayOfObjects[]) const;
int takeArrays(Foo* fixedArrayOfPointersToObjects[3], int fixedArrayOfPrimitives[4], int takeArrays(Foo* fixedArrayOfPointersToObjects[3], int fixedArrayOfPrimitives[4], int* fixedArrayOfPointersToPrimitives[5]) const;
int* fixedArrayOfPointersToPrimitives[5]) const;
std::string takeStringArray(const char* arrayOfStrings[]); std::string takeStringArray(const char* arrayOfStrings[]);
std::string takeConstStringArray(const char* const arrayOfStrings[]); std::string takeConstStringArray(const char* const arrayOfStrings[]);
virtual int virtualTakeArrays(Foo* arrayOfPointersToObjects[], int arrayOfPrimitives[], Foo arrayOfObjects[]) const; virtual int virtualTakeArrays(Foo* arrayOfPointersToObjects[], int arrayOfPrimitives[], Foo arrayOfObjects[]) const;
virtual int virtualTakeArrays(Foo* fixedArrayOfPointersToObjects[3], int fixedArrayOfPrimitives[4], virtual int virtualTakeArrays(Foo* fixedArrayOfPointersToObjects[3], int fixedArrayOfPrimitives[4], int* fixedArrayOfPointersToPrimitives[5]) const;
int* fixedArrayOfPointersToPrimitives[5]) const;
}; };
@ -1376,14 +1454,11 @@ public:
Foo* fixedArrayOfPointers[3]; Foo* fixedArrayOfPointers[3];
}; };
struct DLL_API CSharp struct DLL_API CSharp{};
{
};
static int FOOBAR_CONSTANT = 42; static int FOOBAR_CONSTANT = 42;
class DLL_API SimpleInterface class DLL_API SimpleInterface
{ {
public: public:
@ -1401,6 +1476,7 @@ public:
int size(); int size();
void* get(int n); void* get(int n);
void setInterface(SimpleInterface* i); void setInterface(SimpleInterface* i);
private: private:
SimpleInterface* interface; SimpleInterface* interface;
}; };
@ -1423,14 +1499,19 @@ typedef QFlags<TestFlag> TestFlags;
DLL_API void takeMappedEnum(TestFlag value); DLL_API void takeMappedEnum(TestFlag value);
DLL_API void takeMappedEnum(TestFlags value); DLL_API void takeMappedEnum(TestFlags value);
struct { struct
struct { {
struct { struct
{
struct
{
int (*forIntegers)(int b, short s, unsigned int i); int (*forIntegers)(int b, short s, unsigned int i);
struct { struct
{
int i; int i;
} APIHost; } APIHost;
struct { struct
{
int i; int i;
} Method; } Method;
} example; } example;
@ -1440,21 +1521,24 @@ struct {
typedef int boolean_t; typedef int boolean_t;
DLL_API boolean_t takeTypemapTypedefParam(boolean_t b); DLL_API boolean_t takeTypemapTypedefParam(boolean_t b);
class DLL_API TestAnonymousMemberNameCollision : public ClassUsingUnion { class DLL_API TestAnonymousMemberNameCollision : public ClassUsingUnion
{
}; };
namespace CXXRecordDeclWithoutDefinition namespace CXXRecordDeclWithoutDefinition {
{
template <typename... T> template <typename... T>
struct list; struct list;
template <typename T> template <typename T>
struct it; struct it;
template <> struct it<list<>> { }; template <>
template <> struct it<list<> const> { }; struct it<list<>>
} {};
template <>
struct it<list<> const>
{};
} // namespace CXXRecordDeclWithoutDefinition
template <int... n> template <int... n>
struct TestVariableWithoutType struct TestVariableWithoutType
@ -1471,7 +1555,11 @@ struct TestVariableWithoutType
struct DLL_API ClassZeroAllocatedMemoryTest struct DLL_API ClassZeroAllocatedMemoryTest
{ {
int p1; int p1;
struct { int p2p1; int p2p2; } p2; struct
{
int p2p1;
int p2p2;
} p2;
bool p3; bool p3;
char p4; char p4;
}; };
@ -1490,9 +1578,12 @@ struct DLL_API ConversionFunctions
struct DLL_API ClassCustomTypeAlignment struct DLL_API ClassCustomTypeAlignment
{ {
struct alignas(1) Align1 { }; struct alignas(1) Align1
struct alignas(8) Align8 { }; {};
struct alignas(16) Align16 { struct alignas(8) Align8
{};
struct alignas(16) Align16
{
double a; double a;
double b; double b;
}; };
@ -1533,11 +1624,9 @@ struct DLL_API StructWithEmbeddedArrayOfStructObjectAlignment
EmbeddedStruct embedded_struct[2]; EmbeddedStruct embedded_struct[2];
}; };
class DLL_API ProtectedConstructorDestructor class DLL_API ProtectedConstructorDestructor{
{
protected : protected :
ProtectedConstructorDestructor() {} ProtectedConstructorDestructor(){} ~ProtectedConstructorDestructor(){}
~ProtectedConstructorDestructor() {}
}; };
DLL_API extern const unsigned ClassCustomTypeAlignmentOffsets[5]; DLL_API extern const unsigned ClassCustomTypeAlignmentOffsets[5];
@ -1550,7 +1639,10 @@ DLL_API const wchar_t* TestCSharpStringWide(const wchar_t* in, CS_OUT const wcha
DLL_API const char16_t* TestCSharpString16(const char16_t* in, CS_OUT const char16_t** out); DLL_API const char16_t* TestCSharpString16(const char16_t* in, CS_OUT const char16_t** out);
DLL_API const char32_t* TestCSharpString32(const char32_t* in, CS_OUT const char32_t** out); DLL_API const char32_t* TestCSharpString32(const char32_t* in, CS_OUT const char32_t** out);
struct DLL_API FTIStruct { int a; }; struct DLL_API FTIStruct
{
int a;
};
DLL_API FTIStruct TestFunctionToStaticMethod(FTIStruct* bb); DLL_API FTIStruct TestFunctionToStaticMethod(FTIStruct* bb);
DLL_API int TestFunctionToStaticMethodStruct(FTIStruct* bb, FTIStruct defaultValue); DLL_API int TestFunctionToStaticMethodStruct(FTIStruct* bb, FTIStruct defaultValue);
@ -1558,30 +1650,38 @@ DLL_API int TestFunctionToStaticMethodRefStruct(FTIStruct* bb, FTIStruct& defaul
DLL_API int TestFunctionToStaticMethodConstStruct(FTIStruct* bb, const FTIStruct defaultValue); DLL_API int TestFunctionToStaticMethodConstStruct(FTIStruct* bb, const FTIStruct defaultValue);
DLL_API int TestFunctionToStaticMethodConstRefStruct(FTIStruct* bb, const FTIStruct& defaultValue); DLL_API int TestFunctionToStaticMethodConstRefStruct(FTIStruct* bb, const FTIStruct& defaultValue);
class DLL_API TestClass { int a; }; class DLL_API TestClass
{
int a;
};
DLL_API int TestClassFunctionToInstanceMethod(TestClass* bb, int value); DLL_API int TestClassFunctionToInstanceMethod(TestClass* bb, int value);
DLL_API int TestClassFunctionToInstanceMethod(TestClass* bb, FTIStruct& cc); DLL_API int TestClassFunctionToInstanceMethod(TestClass* bb, FTIStruct& cc);
class ClassWithoutNativeToManaged { }; class ClassWithoutNativeToManaged
{};
struct DLL_API ClassWithIntValue { struct DLL_API ClassWithIntValue
{
int value; int value;
}; };
DLL_API inline ClassWithIntValue* ModifyCore(CS_IN_OUT ClassWithIntValue*& pClass) { DLL_API inline ClassWithIntValue* ModifyCore(CS_IN_OUT ClassWithIntValue*& pClass)
{
pClass->value = 10; pClass->value = 10;
return nullptr; return nullptr;
} }
DLL_API inline ClassWithIntValue* CreateCore(CS_IN_OUT ClassWithIntValue*& pClass) { DLL_API inline ClassWithIntValue* CreateCore(CS_IN_OUT ClassWithIntValue*& pClass)
{
pClass = new ClassWithIntValue(); pClass = new ClassWithIntValue();
pClass->value = 20; pClass->value = 20;
return nullptr; return nullptr;
} }
struct DLL_API RuleOfThreeTester { struct DLL_API RuleOfThreeTester
{
int a; int a;
static int constructorCalls; static int constructorCalls;
static int destructorCalls; static int destructorCalls;
@ -1596,7 +1696,8 @@ struct DLL_API RuleOfThreeTester {
RuleOfThreeTester& operator=(const RuleOfThreeTester& other); RuleOfThreeTester& operator=(const RuleOfThreeTester& other);
}; };
struct DLL_API CallByValueInterface { struct DLL_API CallByValueInterface
{
virtual void CallByValue(RuleOfThreeTester value) = 0; virtual void CallByValue(RuleOfThreeTester value) = 0;
virtual void CallByReference(RuleOfThreeTester& value) = 0; virtual void CallByReference(RuleOfThreeTester& value) = 0;
virtual void CallByPointer(RuleOfThreeTester* value) = 0; virtual void CallByPointer(RuleOfThreeTester* value) = 0;
@ -1609,6 +1710,7 @@ void DLL_API CallCallByValueInterfacePointer(CallByValueInterface*);
class DLL_API PointerTester class DLL_API PointerTester
{ {
int a; int a;
public: public:
PointerTester(); PointerTester();
bool IsDefaultInstance(); bool IsDefaultInstance();
@ -1617,10 +1719,12 @@ public:
DLL_API extern PointerTester* PointerToClass; DLL_API extern PointerTester* PointerToClass;
union DLL_API UnionTester { union DLL_API UnionTester
{
float a; float a;
int b; int b;
inline bool operator ==(const UnionTester& other) const { inline bool operator==(const UnionTester& other) const
{
return b == other.b; return b == other.b;
} }
}; };
@ -1628,34 +1732,39 @@ union DLL_API UnionTester {
int DLL_API ValueTypeOutParameter(CS_OUT UnionTester* testerA, CS_OUT UnionTester* testerB); int DLL_API ValueTypeOutParameter(CS_OUT UnionTester* testerA, CS_OUT UnionTester* testerB);
template <class T> template <class T>
class Optional { class Optional
{
public: public:
T m_value; T m_value;
bool m_hasValue; bool m_hasValue;
Optional() { Optional()
{
m_hasValue = false; m_hasValue = false;
} }
Optional(T value) { Optional(T value)
{
m_value = std::move(value); m_value = std::move(value);
m_hasValue = true; m_hasValue = true;
} }
inline bool operator ==(const Optional<T>& rhs) const { inline bool operator==(const Optional<T>& rhs) const
{
return (m_hasValue == rhs.m_hasValue && (!m_hasValue || m_value == rhs.m_value)); return (m_hasValue == rhs.m_hasValue && (!m_hasValue || m_value == rhs.m_value));
} }
inline bool operator ==(const T& rhs) const { inline bool operator==(const T& rhs) const
{
return (m_hasValue && m_value == rhs); return (m_hasValue && m_value == rhs);
} }
}; };
// We just need a method that uses various instantiations of Optional. // We just need a method that uses various instantiations of Optional.
inline void DLL_API InstantiateOptionalTemplate(Optional<unsigned int>, Optional<std::string>, inline void DLL_API InstantiateOptionalTemplate(Optional<unsigned int>, Optional<std::string>, Optional<TestComparison>, Optional<char*>, Optional<UnionTester>) {}
Optional<TestComparison>, Optional<char*>, Optional<UnionTester>) { }
CS_VALUE_TYPE class DLL_API ValueType { CS_VALUE_TYPE class DLL_API ValueType
{
public: public:
ValueType() {} ValueType() {}
@ -1663,7 +1772,8 @@ public:
const char* char_ptr_member; const char* char_ptr_member;
}; };
CS_VALUE_TYPE class DLL_API ValueTypeNoCtor { CS_VALUE_TYPE class DLL_API ValueTypeNoCtor
{
public: public:
std::string string_member; std::string string_member;
const char* char_ptr_member; const char* char_ptr_member;

18
tests/dotnet/CSharp/CSharpTemplates.cpp

@ -1,6 +1,7 @@
#include "CSharpTemplates.h" #include "CSharpTemplates.h"
T2::T2() : field(0) T2::T2()
: field(0)
{ {
} }
@ -103,20 +104,7 @@ int ImplementAbstractTemplate::callFunction()
return 65; return 65;
} }
void forceUseSpecializations(IndependentFields<int> _1, IndependentFields<bool> _2, void forceUseSpecializations(IndependentFields<int> _1, IndependentFields<bool> _2, IndependentFields<T1> _3, IndependentFields<std::string> _4, DependentValueFields<int> _5, VirtualTemplate<int> _6, VirtualTemplate<bool> _7, HasDefaultTemplateArgument<int, int> _8, DerivedChangesTypeName<T1> _9, TemplateWithIndexer<int> _10, TemplateWithIndexer<T1> _11, TemplateWithIndexer<void*> _12, TemplateWithIndexer<UsedInTemplatedIndexer> _13, TemplateDerivedFromRegularDynamic<RegularDynamic> _14, IndependentFields<OnlySpecialisedInTypeArg<double>> _15, DependentPointerFields<float> _16, IndependentFields<const T1&> _17, TemplateWithIndexer<T2*> _18, IndependentFields<int (*)(int)> _19, TemplateWithIndexer<const char*> _20, VirtualDependentValueFields<int> _21, VirtualDependentValueFields<float> _22, VirtualDependentValueFields<const char*> _23, std::string s)
IndependentFields<T1> _3, IndependentFields<std::string> _4,
DependentValueFields<int> _5,
VirtualTemplate<int> _6, VirtualTemplate<bool> _7,
HasDefaultTemplateArgument<int, int> _8, DerivedChangesTypeName<T1> _9,
TemplateWithIndexer<int> _10, TemplateWithIndexer<T1> _11,
TemplateWithIndexer<void*> _12, TemplateWithIndexer<UsedInTemplatedIndexer> _13,
TemplateDerivedFromRegularDynamic<RegularDynamic> _14,
IndependentFields<OnlySpecialisedInTypeArg<double>> _15,
DependentPointerFields<float> _16, IndependentFields<const T1&> _17,
TemplateWithIndexer<T2*> _18, IndependentFields<int(*)(int)> _19,
TemplateWithIndexer<const char*> _20, VirtualDependentValueFields<int> _21,
VirtualDependentValueFields<float> _22, VirtualDependentValueFields<const char*> _23,
std::string s)
{ {
} }

134
tests/dotnet/CSharp/CSharpTemplates.h

@ -12,13 +12,9 @@ protected:
~DeriveProtectedDtor() {} ~DeriveProtectedDtor() {}
}; };
class DLL_API QString class DLL_API QString{};
{
};
class DLL_API T1 class DLL_API T1{};
{
};
class DLL_API T2 class DLL_API T2
{ {
@ -28,13 +24,12 @@ public:
virtual ~T2(); virtual ~T2();
int getField() const; int getField() const;
void setField(int value); void setField(int value);
private: private:
int field; int field;
}; };
class DLL_API Ignored class DLL_API Ignored{};
{
};
template <typename T> template <typename T>
class HasAbstractReturnPointer class HasAbstractReturnPointer
@ -84,6 +79,7 @@ template <typename T>
class IndependentFields : public T1 class IndependentFields : public T1
{ {
typedef T Type; typedef T Type;
public: public:
class Nested class Nested
{ {
@ -105,6 +101,7 @@ public:
template <typename AdditionalDependentType> template <typename AdditionalDependentType>
void usesAdditionalDependentType(AdditionalDependentType additionalDependentType); void usesAdditionalDependentType(AdditionalDependentType additionalDependentType);
static const int independentConst; static const int independentConst;
private: private:
float independent; float independent;
}; };
@ -113,7 +110,8 @@ template <typename T>
const int IndependentFields<T>::independentConst = 15; const int IndependentFields<T>::independentConst = 15;
template <typename T> template <typename T>
IndependentFields<T>::IndependentFields() : independent(1) IndependentFields<T>::IndependentFields()
: independent(1)
{ {
} }
@ -124,17 +122,20 @@ IndependentFields<T>::IndependentFields(const IndependentFields<T>& other)
} }
template <typename T> template <typename T>
IndependentFields<T>::IndependentFields(const T& t) : independent(1) IndependentFields<T>::IndependentFields(const T& t)
: independent(1)
{ {
} }
template <typename T> template <typename T>
IndependentFields<T>::IndependentFields(T1* t1) : independent(1) IndependentFields<T>::IndependentFields(T1* t1)
: independent(1)
{ {
} }
template <typename T> template <typename T>
IndependentFields<T>::IndependentFields(T2* t2) : independent(1) IndependentFields<T>::IndependentFields(T2* t2)
: independent(1)
{ {
} }
@ -145,7 +146,8 @@ IndependentFields<T>::IndependentFields(float f)
} }
template <typename T> template <typename T>
IndependentFields<T>::IndependentFields(const std::map<T, T> &v) : independent(1) IndependentFields<T>::IndependentFields(const std::map<T, T>& v)
: independent(1)
{ {
} }
@ -266,15 +268,19 @@ public:
HasAbstractReturnPointer<T>* getAbstractReturnPointer(); HasAbstractReturnPointer<T>* getAbstractReturnPointer();
typedef void (*DependentFunctionPointer)(T); typedef void (*DependentFunctionPointer)(T);
DependentFunctionPointer dependentFunctionPointerField; DependentFunctionPointer dependentFunctionPointerField;
private: private:
T field{}; T field{};
union { union
{
int unionField; int unionField;
}; };
}; };
template <typename T> template <typename T>
DependentValueFields<T>::DependentValueFields() : unionField(0), dependentFunctionPointerField(0) DependentValueFields<T>::DependentValueFields()
: unionField(0)
, dependentFunctionPointerField(0)
{ {
} }
@ -284,7 +290,8 @@ DependentValueFields<T>::~DependentValueFields()
} }
template <typename T> template <typename T>
DependentValueFields<T>::DependentValueFields(IndependentFields<T> i) : DependentValueFields() DependentValueFields<T>::DependentValueFields(IndependentFields<T> i)
: DependentValueFields()
{ {
} }
@ -363,7 +370,8 @@ public:
}; };
template <typename T> template <typename T>
DependentPointerFields<T>::DependentPointerFields(T* t) : field(t) DependentPointerFields<T>::DependentPointerFields(T* t)
: field(t)
{ {
} }
@ -396,6 +404,7 @@ public:
}; };
void takeDependentPtrToFirstTemplateArg(iterator i, const K& k); void takeDependentPtrToFirstTemplateArg(iterator i, const K& k);
void takeDependentPtrToSecondTemplateArg(const V& v); void takeDependentPtrToSecondTemplateArg(const V& v);
private: private:
K key; K key;
V value; V value;
@ -434,6 +443,7 @@ public:
bool operator==(const HasDefaultTemplateArgument& other); bool operator==(const HasDefaultTemplateArgument& other);
DependentValueFields<D> returnTemplateWithRenamedTypeArg(const DependentValueFields<D>& value); DependentValueFields<D> returnTemplateWithRenamedTypeArg(const DependentValueFields<D>& value);
DependentValueFields<D> propertyReturnsTemplateWithRenamedTypeArg(); DependentValueFields<D> propertyReturnsTemplateWithRenamedTypeArg();
private: private:
T field{}; T field{};
static T staticField; static T staticField;
@ -447,6 +457,7 @@ public:
void setProperty(const bool& t); void setProperty(const bool& t);
static bool staticProperty(); static bool staticProperty();
static void setStaticProperty(const bool& t); static void setStaticProperty(const bool& t);
private: private:
bool field; bool field;
static bool staticField; static bool staticField;
@ -551,6 +562,7 @@ public:
T& operator[](int i); T& operator[](int i);
T& operator[](const T& key); T& operator[](const T& key);
T& operator[](const char* string); T& operator[](const char* string);
private: private:
T t[1]; T t[1];
HasDefaultTemplateArgument<char> h; HasDefaultTemplateArgument<char> h;
@ -586,8 +598,7 @@ T& TemplateWithIndexer<T>::operator[](const char* string)
return t[0]; return t[0];
} }
template <typename T1 = void, typename T2 = void, typename T3 = void, typename T4 = void, template <typename T1 = void, typename T2 = void, typename T3 = void, typename T4 = void, typename T5 = void, typename T6 = void, typename T7 = void, typename T8 = void>
typename T5 = void, typename T6 = void, typename T7 = void, typename T8 = void>
class OptionalTemplateArgs class OptionalTemplateArgs
{ {
}; };
@ -664,6 +675,7 @@ public:
VirtualTemplate<int> getVCopy(); VirtualTemplate<int> getVCopy();
void setV(VirtualTemplate<int>* value); void setV(VirtualTemplate<int>* value);
int function(); int function();
private: private:
VirtualTemplate<int>* v; VirtualTemplate<int>* v;
HasDefaultTemplateArgument<bool, bool> explicitSpecialization; HasDefaultTemplateArgument<bool, bool> explicitSpecialization;
@ -701,6 +713,7 @@ public:
void completeSpecializationInParameter(TwoTemplateArgs<const char*, int>::iterator p6, void completeSpecializationInParameter(TwoTemplateArgs<const char*, int>::iterator p6,
TwoTemplateArgs<QString, int>::iterator p7); TwoTemplateArgs<QString, int>::iterator p7);
VirtualTemplate<void> returnSpecializedWithVoid(); VirtualTemplate<void> returnSpecializedWithVoid();
private: private:
IndependentFields<int> independentFields; IndependentFields<int> independentFields;
DependentValueFields<bool> dependentValueFields; DependentValueFields<bool> dependentValueFields;
@ -733,19 +746,32 @@ class PartiallySpecialized<Key, int>
}; };
template <class T> template <class T>
class HasResultType { class HasResultType
{
typedef char Yes; typedef char Yes;
typedef void* No; typedef void* No;
template<typename U> static Yes test(int, const typename U::result_type * = 0); template <typename U>
template<typename U> static No test(double); static Yes test(int, const typename U::result_type* = 0);
template <typename U>
static No test(double);
public: public:
enum { Value = (sizeof(test<T>(0)) == sizeof(Yes)) }; enum
{
Value = (sizeof(test<T>(0)) == sizeof(Yes))
};
}; };
template <typename Functor, bool foo = HasResultType<Functor>::Value> template <typename Functor, bool foo = HasResultType<Functor>::Value>
struct LazyResultType { typedef typename Functor::result_type Type; }; struct LazyResultType
{
typedef typename Functor::result_type Type;
};
template <typename Functor> template <typename Functor>
struct LazyResultType<Functor, false> { typedef void Type; }; struct LazyResultType<Functor, false>
{
typedef void Type;
};
template <class InputSequence, class MapFunctor> template <class InputSequence, class MapFunctor>
struct MapResultType struct MapResultType
@ -808,21 +834,25 @@ class QFlags
typedef int Int; typedef int Int;
struct Private; struct Private;
typedef int(Private::* Zero); typedef int(Private::* Zero);
public: public:
QFlags(T t); QFlags(T t);
QFlags(Zero = nullptr); QFlags(Zero = nullptr);
operator Int(); operator Int();
private: private:
int flag; int flag;
}; };
template <typename T> template <typename T>
QFlags<T>::QFlags(T t) : flag(Int(t)) QFlags<T>::QFlags(T t)
: flag(Int(t))
{ {
} }
template <typename T> template <typename T>
QFlags<T>::QFlags(Zero) : flag(Int(0)) QFlags<T>::QFlags(Zero)
: flag(Int(0))
{ {
} }
@ -872,20 +902,7 @@ enum class TestFlag
}; };
// we optimise specialisations so that only actually used ones are wrapped // we optimise specialisations so that only actually used ones are wrapped
void forceUseSpecializations(IndependentFields<int> _1, IndependentFields<bool> _2, void forceUseSpecializations(IndependentFields<int> _1, IndependentFields<bool> _2, IndependentFields<T1> _3, IndependentFields<std::string> _4, DependentValueFields<int> _5, VirtualTemplate<int> _6, VirtualTemplate<bool> _7, HasDefaultTemplateArgument<int, int> _8, DerivedChangesTypeName<T1> _9, TemplateWithIndexer<int> _10, TemplateWithIndexer<T1> _11, TemplateWithIndexer<void*> _12, TemplateWithIndexer<UsedInTemplatedIndexer> _13, TemplateDerivedFromRegularDynamic<RegularDynamic> _14, IndependentFields<OnlySpecialisedInTypeArg<double>> _15, DependentPointerFields<float> _16, IndependentFields<const T1&> _17, TemplateWithIndexer<T2*> _18, IndependentFields<int (*)(int)> _19, TemplateWithIndexer<const char*> _20, VirtualDependentValueFields<int> _21, VirtualDependentValueFields<float> _22, VirtualDependentValueFields<const char*> _23, std::string s);
IndependentFields<T1> _3, IndependentFields<std::string> _4,
DependentValueFields<int> _5,
VirtualTemplate<int> _6, VirtualTemplate<bool> _7,
HasDefaultTemplateArgument<int, int> _8, DerivedChangesTypeName<T1> _9,
TemplateWithIndexer<int> _10, TemplateWithIndexer<T1> _11,
TemplateWithIndexer<void*> _12, TemplateWithIndexer<UsedInTemplatedIndexer> _13,
TemplateDerivedFromRegularDynamic<RegularDynamic> _14,
IndependentFields<OnlySpecialisedInTypeArg<double>> _15,
DependentPointerFields<float> _16, IndependentFields<const T1&> _17,
TemplateWithIndexer<T2*> _18, IndependentFields<int(*)(int)> _19,
TemplateWithIndexer<const char*> _20, VirtualDependentValueFields<int> _21,
VirtualDependentValueFields<float> _22, VirtualDependentValueFields<const char*> _23,
std::string s);
void hasIgnoredParam(DependentValueFields<IndependentFields<Ignored>> ii, Base<void> _24); void hasIgnoredParam(DependentValueFields<IndependentFields<Ignored>> ii, Base<void> _24);
@ -893,8 +910,10 @@ std::map<int, int> usesValidSpecialisationOfIgnoredTemplate();
DLL_API DependentValueFields<double> specialiseReturnOnly(); DLL_API DependentValueFields<double> specialiseReturnOnly();
template <int Size> void* qbswap(const void *source, size_t count, void *dest) noexcept; template <int Size>
template<> inline void* qbswap<1>(const void *source, size_t count, void *dest) noexcept void* qbswap(const void* source, size_t count, void* dest) noexcept;
template <>
inline void* qbswap<1>(const void* source, size_t count, void* dest) noexcept
{ {
return 0; return 0;
} }
@ -902,13 +921,16 @@ template<> inline void* qbswap<1>(const void *source, size_t count, void *dest)
class TestForwardedClassInAnotherUnit; class TestForwardedClassInAnotherUnit;
// Forward declaration of class as friend // Forward declaration of class as friend
template<class T> class ForwardTemplateFriendClassContainer; template <class T>
template<class T> class ForwardTemplateFriendClass; class ForwardTemplateFriendClassContainer;
template <class T>
class ForwardTemplateFriendClass;
template <class T> template <class T>
class ForwardTemplateFriendClassContainer class ForwardTemplateFriendClassContainer
{ {
template<class K> friend class ForwardTemplateFriendClass; template <class K>
friend class ForwardTemplateFriendClass;
}; };
template <class T> template <class T>
@ -926,6 +948,7 @@ class ClassWithNonTypeTemplateArgument
{ {
public: public:
ClassWithNonTypeTemplateArgument() {} ClassWithNonTypeTemplateArgument() {}
private: private:
union union
{ {
@ -937,8 +960,7 @@ private:
class SpecializationOfClassWithNonTypeTemplateArgument : public ClassWithNonTypeTemplateArgument<0> class SpecializationOfClassWithNonTypeTemplateArgument : public ClassWithNonTypeTemplateArgument<0>
{}; {};
template <std::size_t N> template <std::size_t N>
class DLL_API FloatArrayF class DLL_API FloatArrayF{
{
public : public :
template <typename... V, class = typename std::enable_if_t<sizeof...(V) == N>> template <typename... V, class = typename std::enable_if_t<sizeof...(V) == N>>
FloatArrayF(V... x){} FloatArrayF(V... x){}
@ -947,7 +969,8 @@ public:
const FloatArrayF<6> I6{ 1., 1., 1., 0., 0., 0. }; const FloatArrayF<6> I6{ 1., 1., 1., 0., 0., 0. };
template <typename T> template <typename T>
DLL_API inline T FunctionTemplate(T value) { DLL_API inline T FunctionTemplate(T value)
{
if (std::is_same<T, double>::value) if (std::is_same<T, double>::value)
return 4.2 + value; return 4.2 + value;
else if (std::is_same<T, float>::value) else if (std::is_same<T, float>::value)
@ -963,20 +986,21 @@ inline void FunctionTemplateInstantiation()
} }
// KEEP ORDER OTHERWISE TEST WONT WORK // KEEP ORDER OTHERWISE TEST WONT WORK
namespace IncompleteClassTemplatesTests namespace IncompleteClassTemplatesTests {
{
template <size_t Size> template <size_t Size>
struct StructSizeT {}; struct StructSizeT
{};
template <typename T> template <typename T>
struct StructT struct StructT
{ {
template <typename U> template <typename U>
struct Inc { }; struct Inc
{};
}; };
struct Instantiation struct Instantiation
{ {
StructT<StructSizeT<4000>> st; StructT<StructSizeT<4000>> st;
}; };
} } // namespace IncompleteClassTemplatesTests

9
tests/dotnet/CSharp/ExcludedUnit.hpp

@ -1,10 +1,13 @@
#pragma once #pragma once
class ClassUsingUnion { class ClassUsingUnion
{
public: public:
union { union
{
float arr[2]; float arr[2];
struct { struct
{
float a, b; float a, b;
}; };
}; };

11
tests/dotnet/Common/AnotherUnit.h

@ -4,17 +4,14 @@
typedef void (*DelegateInAnotherUnit)(); typedef void (*DelegateInAnotherUnit)();
// Tests automatic generation of anonymous delegates in different translation units // Tests automatic generation of anonymous delegates in different translation units
namespace DelegateNamespace namespace DelegateNamespace {
{ namespace Nested {
namespace Nested
{
void DLL_API f3(void (*)()); void DLL_API f3(void (*)());
} }
void DLL_API f4(void (*)()); void DLL_API f4(void (*)());
} } // namespace DelegateNamespace
namespace AnotherUnit namespace AnotherUnit {
{
void DLL_API f(); void DLL_API f();
} }

198
tests/dotnet/Common/Common.cpp

@ -14,7 +14,9 @@ Foo::Foo()
SomePointerPointer = &SomePointer; SomePointerPointer = &SomePointer;
} }
Foo::Foo(const Foo& other) : A(other.A), B(other.B) Foo::Foo(const Foo& other)
: A(other.A)
, B(other.B)
{ {
} }
@ -64,7 +66,12 @@ Foo Foo::staticField;
Foo2::Foo2() {} Foo2::Foo2() {}
Foo2::Foo2(const Foo2& other) : Foo(other), C(other.C), valueTypeField(other.valueTypeField) {} Foo2::Foo2(const Foo2& other)
: Foo(other)
, C(other.C)
, valueTypeField(other.valueTypeField)
{
}
Foo2 Foo2::operator<<(signed int i) Foo2 Foo2::operator<<(signed int i)
{ {
@ -310,7 +317,10 @@ Bar indirectReturn()
return Bar(); return Bar();
} }
TestDelegates::TestDelegates() : A(Double), B(Double), C(&TestDelegates::Triple) TestDelegates::TestDelegates()
: A(Double)
, B(Double)
, C(&TestDelegates::Triple)
{ {
} }
@ -541,22 +551,29 @@ int Function()
return 5; return 5;
} }
TestProperties::TestProperties() : Field(0), ArchiveName(0), TestProperties::TestProperties()
FieldValue(0), _refToPrimitiveInSetter(0), : Field(0)
_getterAndSetterWithTheSameName(0), _setterReturnsBoolean(0), , ArchiveName(0)
_virtualSetterReturnsBoolean(0), _conflict(Conflict::Value1), , FieldValue(0)
ConstRefField(Field) , _refToPrimitiveInSetter(0)
, _getterAndSetterWithTheSameName(0)
, _setterReturnsBoolean(0)
, _virtualSetterReturnsBoolean(0)
, _conflict(Conflict::Value1)
, ConstRefField(Field)
{ {
} }
TestProperties::TestProperties(const TestProperties& other) : TestProperties::TestProperties(const TestProperties& other)
Field(other.Field), ArchiveName(other.ArchiveName), : Field(other.Field)
FieldValue(other.FieldValue), , ArchiveName(other.ArchiveName)
_refToPrimitiveInSetter(other._refToPrimitiveInSetter), , FieldValue(other.FieldValue)
_getterAndSetterWithTheSameName(other._getterAndSetterWithTheSameName), , _refToPrimitiveInSetter(other._refToPrimitiveInSetter)
_setterReturnsBoolean(other._setterReturnsBoolean), , _getterAndSetterWithTheSameName(other._getterAndSetterWithTheSameName)
_virtualSetterReturnsBoolean(other._virtualSetterReturnsBoolean), , _setterReturnsBoolean(other._setterReturnsBoolean)
_conflict(other._conflict), ConstRefField(other.ConstRefField) , _virtualSetterReturnsBoolean(other._virtualSetterReturnsBoolean)
, _conflict(other._conflict)
, ConstRefField(other.ConstRefField)
{ {
} }
@ -758,15 +775,32 @@ void HasOverridenSetter::setVirtualGetter(int value)
{ {
} }
TestIndexedProperties::TestIndexedProperties() : p(1), f() TestIndexedProperties::TestIndexedProperties()
: p(1)
, f()
{ {
} }
foo_t& TestIndexedProperties::operator[](int i) { return p; } foo_t& TestIndexedProperties::operator[](int i)
const TestProperties& TestIndexedProperties::operator[](short b) { return f; } {
foo_t TestIndexedProperties::operator[](const char* name) { return p; } return p;
foo_t* TestIndexedProperties::operator[](float f) { return &p; } }
TestProperties* TestIndexedProperties::operator[](unsigned char b) { return &f; } const TestProperties& TestIndexedProperties::operator[](short b)
{
return f;
}
foo_t TestIndexedProperties::operator[](const char* name)
{
return p;
}
foo_t* TestIndexedProperties::operator[](float f)
{
return &p;
}
TestProperties* TestIndexedProperties::operator[](unsigned char b)
{
return &f;
}
Bar& TestIndexedProperties::operator[](unsigned long i) Bar& TestIndexedProperties::operator[](unsigned long i)
{ {
return bar; return bar;
@ -776,8 +810,14 @@ Bar& TestIndexedProperties::operator[](const TypeMappedIndex& key)
return bar; return bar;
} }
const foo_t& TestIndexedProperties::operator[](double f) { return p; } const foo_t& TestIndexedProperties::operator[](double f)
foo_t TestIndexedProperties::operator[](TestProperties b) { return p; } {
return p;
}
foo_t TestIndexedProperties::operator[](TestProperties b)
{
return p;
}
int TestIndexedProperties::operator[](CS_OUT char key) int TestIndexedProperties::operator[](CS_OUT char key)
{ {
@ -794,11 +834,20 @@ Bar& TestIndexedProperties::operator[](const Foo& key)
} }
int TestVariables::VALUE; int TestVariables::VALUE;
void TestVariables::SetValue(int value) { VALUE = value; } void TestVariables::SetValue(int value)
{
VALUE = value;
}
LPCWSTR TestWideStrings::GetWidePointer() { return L"Hello"; } LPCWSTR TestWideStrings::GetWidePointer()
{
return L"Hello";
}
LPCWSTR TestWideStrings::GetWideNullPointer() { return 0; } LPCWSTR TestWideStrings::GetWideNullPointer()
{
return 0;
}
InternalCtorAmbiguity::InternalCtorAmbiguity(void* param) InternalCtorAmbiguity::InternalCtorAmbiguity(void* param)
{ {
@ -806,7 +855,8 @@ InternalCtorAmbiguity::InternalCtorAmbiguity(void* param)
throw; throw;
} }
InvokesInternalCtorAmbiguity::InvokesInternalCtorAmbiguity() : ptr(0) InvokesInternalCtorAmbiguity::InvokesInternalCtorAmbiguity()
: ptr(0)
{ {
} }
@ -835,7 +885,8 @@ DLL_API const HasFriend operator-(const HasFriend& f1, const HasFriend& f2)
return HasFriend(f1.m - f2.m); return HasFriend(f1.m - f2.m);
} }
DifferentConstOverloads::DifferentConstOverloads() : i(5) DifferentConstOverloads::DifferentConstOverloads()
: i(5)
{ {
} }
@ -926,7 +977,9 @@ void funcTryValTypeOut(CS_OUT ValueTypeClassPassTry classTry)
{ {
} }
HasProblematicFields::HasProblematicFields() : b(false), c(0) HasProblematicFields::HasProblematicFields()
: b(false)
, c(0)
{ {
} }
@ -1059,17 +1112,32 @@ TestNotStaticClass TestNotStaticClass::StaticFunction()
return TestNotStaticClass(); return TestNotStaticClass();
} }
int TestStaticClass::Add(int a, int b) { return a + b; } int TestStaticClass::Add(int a, int b)
int TestStaticClass::GetOneTwoThree() { return 123; } {
int TestStaticClass::_Mult(int a, int b) { return a * b; } return a + b;
int TestStaticClass::GetFourFiveSix() { return 456; } }
int TestStaticClass::GetOneTwoThree()
{
return 123;
}
int TestStaticClass::_Mult(int a, int b)
{
return a * b;
}
int TestStaticClass::GetFourFiveSix()
{
return 456;
}
TestStaticClass& TestStaticClass::operator=(const TestStaticClass& oth) TestStaticClass& TestStaticClass::operator=(const TestStaticClass& oth)
{ {
return *this; return *this;
} }
int TestStaticClassDerived::Foo() { return 0; } int TestStaticClassDerived::Foo()
{
return 0;
}
HasCopyAndMoveConstructor::HasCopyAndMoveConstructor(int value) HasCopyAndMoveConstructor::HasCopyAndMoveConstructor(int value)
{ {
@ -1137,7 +1205,10 @@ AmbiguousParamNames::AmbiguousParamNames(int instance, int in)
{ {
} }
int ReturnByValueWithReturnParam::getUseCount() { return _ptr.use_count(); } int ReturnByValueWithReturnParam::getUseCount()
{
return _ptr.use_count();
}
ReturnByValueWithReturnParam ReturnByValueWithReturnParamFactory::generate() ReturnByValueWithReturnParam ReturnByValueWithReturnParamFactory::generate()
{ {
@ -1193,8 +1264,14 @@ LPCSTR TakeTypedefedMappedType(LPCSTR string)
return UTF8.data(); return UTF8.data();
} }
StructWithCopyCtor::StructWithCopyCtor() : mBits(0) {} StructWithCopyCtor::StructWithCopyCtor()
StructWithCopyCtor::StructWithCopyCtor(const StructWithCopyCtor& other) : mBits(other.mBits) {} : mBits(0)
{
}
StructWithCopyCtor::StructWithCopyCtor(const StructWithCopyCtor& other)
: mBits(other.mBits)
{
}
uint16_t TestStructWithCopyCtorByValue(StructWithCopyCtor s) uint16_t TestStructWithCopyCtorByValue(StructWithCopyCtor s)
{ {
@ -1214,8 +1291,14 @@ int NonPrimitiveType::GetFoo()
return foo; return foo;
} }
int TestGetterSetterToProperties::getWidth() { return 640; } int TestGetterSetterToProperties::getWidth()
int TestGetterSetterToProperties::getHeight() { return 480; } {
return 640;
}
int TestGetterSetterToProperties::getHeight()
{
return 480;
}
void DLL_API PointerToTypedefPointerTestMethod(LPPointerToTypedefPointerTest* lp, int valToSet) void DLL_API PointerToTypedefPointerTestMethod(LPPointerToTypedefPointerTest* lp, int valToSet)
{ {
@ -1229,10 +1312,13 @@ void DLL_API PointerToPrimitiveTypedefPointerTestMethod(LPINT lp, int valToSet)
TestArraysPointers::TestArraysPointers(MyEnum* values, int count) TestArraysPointers::TestArraysPointers(MyEnum* values, int count)
{ {
if (values && count) Value = values[0]; if (values && count)
Value = values[0];
} }
TestCopyConstructorRef::TestCopyConstructorRef() : A(0), B(0) TestCopyConstructorRef::TestCopyConstructorRef()
: A(0)
, B(0)
{ {
} }
@ -1243,20 +1329,36 @@ TestCopyConstructorRef::TestCopyConstructorRef(const TestCopyConstructorRef& oth
} }
SomeStruct::SomeStruct() : p(1) {} SomeStruct::SomeStruct()
: p(1)
{
}
void SomeNamespace::NamespacedAbstractImpl::AbstractMethod() void SomeNamespace::NamespacedAbstractImpl::AbstractMethod()
{ {
} }
ClassWithOverloadedOperators::ClassWithOverloadedOperators::operator char() { return 1; } ClassWithOverloadedOperators::ClassWithOverloadedOperators::operator char()
ClassWithOverloadedOperators::operator int() { return 2; } {
ClassWithOverloadedOperators::operator short() { return 3; } return 1;
bool ClassWithOverloadedOperators::operator<(const ClassWithOverloadedOperators& other) const { }
ClassWithOverloadedOperators::operator int()
{
return 2;
}
ClassWithOverloadedOperators::operator short()
{
return 3;
}
bool ClassWithOverloadedOperators::operator<(const ClassWithOverloadedOperators& other) const
{
return true; return true;
} }
int TestIndexedPropertiesInValueType::operator[](int i) { return i; } int TestIndexedPropertiesInValueType::operator[](int i)
{
return i;
}
extern "C" extern "C"
{ {

214
tests/dotnet/Common/Common.h

@ -44,6 +44,7 @@ class DLL_API IgnoredType
private: private:
int i; int i;
}; };
private: private:
int i; int i;
}; };
@ -56,6 +57,7 @@ private:
Value1, Value1,
Value2 Value2
}; };
public: public:
enum enum
{ {
@ -134,7 +136,8 @@ DLL_API bool operator ==(Bar::Item item, const Bar& bar);
class DLL_API Foo2 : public Foo class DLL_API Foo2 : public Foo
{ {
struct Copy { struct Copy
{
Foo A; Foo A;
}* copy; }* copy;
@ -179,7 +182,9 @@ struct DLL_API Bar2 : public Bar
enum Enum enum Enum
{ {
A = 0, B = 2, C = 5, A = 0,
B = 2,
C = 5,
// D = 0x80000000, // D = 0x80000000,
E = 0x1, E = 0x1,
F = -9, F = -9,
@ -191,13 +196,15 @@ typedef char TypedefChar;
class DLL_API Hello class DLL_API Hello
{ {
union NestedPrivate { union NestedPrivate
{
int i; int i;
float f; float f;
}; };
public: public:
union NestedPublic { union NestedPublic
{
int j; int j;
float g; float g;
long l; long l;
@ -256,6 +263,7 @@ public:
typedef int typedefInOverride; typedef int typedefInOverride;
virtual int pureFunction(typedefInOverride i = 0); virtual int pureFunction(typedefInOverride i = 0);
virtual int pureFunction1(); virtual int pureFunction1();
private: private:
virtual int pureFunction2(bool* ok = 0); virtual int pureFunction2(bool* ok = 0);
}; };
@ -314,9 +322,7 @@ class Derived : public Base<Derived>
}; };
// Tests the MoveFunctionToClassPass // Tests the MoveFunctionToClassPass
class DLL_API common class DLL_API common{};
{
};
DLL_API int test(common& s); DLL_API int test(common& s);
@ -374,28 +380,23 @@ struct DLL_API TestDelegates
MemberDelegate C; MemberDelegate C;
}; };
namespace DelegateNamespace namespace DelegateNamespace {
{ namespace Nested {
namespace Nested
{
void DLL_API f1(void (*)()); void DLL_API f1(void (*)());
} }
void DLL_API f2(void (*)()); void DLL_API f2(void (*)());
} } // namespace DelegateNamespace
// Tests memory leaks in constructors // Tests memory leaks in constructors
// C#: Marshal.FreeHGlobal(arg0); // C#: Marshal.FreeHGlobal(arg0);
struct DLL_API TestMemoryLeaks struct DLL_API TestMemoryLeaks{
{
TestMemoryLeaks(const char* name){} TestMemoryLeaks(const char* name){}
}; };
// Tests that finalizers are generated // Tests that finalizers are generated
/* CLI: ~TestFinalizers() */ /* CLI: ~TestFinalizers() */
struct DLL_API TestFinalizers struct DLL_API TestFinalizers{};
{
};
// Tests static classes // Tests static classes
struct DLL_API TestStaticClass struct DLL_API TestStaticClass
@ -427,6 +428,7 @@ class DLL_API TestNotStaticClass
{ {
public: public:
static TestNotStaticClass StaticFunction(); static TestNotStaticClass StaticFunction();
private: private:
TestNotStaticClass(); TestNotStaticClass();
}; };
@ -460,7 +462,10 @@ public:
template <class T> template <class T>
struct EmptyNamedNestedEnum struct EmptyNamedNestedEnum
{ {
enum { Value = 10 }; enum
{
Value = 10
};
}; };
typedef unsigned long foo_t; typedef unsigned long foo_t;
@ -474,8 +479,7 @@ class DLL_API SomeClassExtendingTheStruct : public SomeStruct
{ {
}; };
namespace SomeNamespace namespace SomeNamespace {
{
class DLL_API NamespacedAbstractClass class DLL_API NamespacedAbstractClass
{ {
public: public:
@ -493,6 +497,7 @@ namespace SomeNamespace
public: public:
constexpr Inlines(float param, const char* name) {} constexpr Inlines(float param, const char* name) {}
inline operator NamespacedAbstractImpl() const { return NamespacedAbstractImpl(); } inline operator NamespacedAbstractImpl() const { return NamespacedAbstractImpl(); }
protected: protected:
void protectedInlined() {} void protectedInlined() {}
}; };
@ -504,7 +509,7 @@ namespace SomeNamespace
public: public:
virtual void hasVariadicArgs(int regular, ...) = 0; virtual void hasVariadicArgs(int regular, ...) = 0;
}; };
} } // namespace SomeNamespace
// Test operator overloads // Test operator overloads
class DLL_API ClassWithOverloadedOperators class DLL_API ClassWithOverloadedOperators
@ -673,7 +678,12 @@ struct DLL_API TestWideStrings
LPCWSTR GetWideNullPointer(); LPCWSTR GetWideNullPointer();
}; };
enum struct MyEnum { A, B, C }; enum struct MyEnum
{
A,
B,
C
};
typedef void (*VoidPtrRetFunctionTypedef)(); typedef void (*VoidPtrRetFunctionTypedef)();
@ -762,12 +772,16 @@ DLL_API void TestNullPtrType(decltype(nullptr));
DLL_API decltype(nullptr) TestNullPtrTypeRet(); DLL_API decltype(nullptr) TestNullPtrTypeRet();
// Tests dependent name types // Tests dependent name types
template<typename T> struct DependentType template <typename T>
struct DependentType
{ {
DependentType(typename T::Dependent* t) {} DependentType(typename T::Dependent* t) {}
private: private:
struct Bitset { int length : sizeof(T); }; struct Bitset
{
int length : sizeof(T);
};
}; };
class PureDtor class PureDtor
@ -828,6 +842,7 @@ class DLL_API InvokesInternalCtorAmbiguity
public: public:
InvokesInternalCtorAmbiguity(); InvokesInternalCtorAmbiguity();
InternalCtorAmbiguity* InvokeInternalCtor(); InternalCtorAmbiguity* InvokeInternalCtor();
private: private:
InternalCtorAmbiguity* ptr; InternalCtorAmbiguity* ptr;
}; };
@ -839,11 +854,13 @@ public:
DLL_API friend const HasFriend operator+(const HasFriend& f1, const HasFriend& f2); DLL_API friend const HasFriend operator+(const HasFriend& f1, const HasFriend& f2);
DLL_API friend const HasFriend operator-(const HasFriend& f1, const HasFriend& f2); DLL_API friend const HasFriend operator-(const HasFriend& f1, const HasFriend& f2);
int getM(); int getM();
private: private:
int m; int m;
}; };
template<typename T> class FriendTemplate template <typename T>
class FriendTemplate
{ {
template <typename TT> template <typename TT>
friend FriendTemplate<TT> func(const FriendTemplate<TT>&); friend FriendTemplate<TT> func(const FriendTemplate<TT>&);
@ -861,6 +878,7 @@ public:
bool operator!=(const DifferentConstOverloads& other); bool operator!=(const DifferentConstOverloads& other);
bool operator==(int number) const; bool operator==(int number) const;
bool operator==(std::string s) const; bool operator==(std::string s) const;
private: private:
int i; int i;
}; };
@ -870,19 +888,21 @@ DLL_API bool operator ==(const DifferentConstOverloads& d, const char* s);
class TestNamingAnonymousTypesInUnion class TestNamingAnonymousTypesInUnion
{ {
public: public:
union { union
struct { {
struct
{
} argb; } argb;
struct { struct
{
} ahsv; } ahsv;
struct { struct
{
} acmyk; } acmyk;
} ct; } ct;
}; };
class DLL_API RefTypeClassPassTry class DLL_API RefTypeClassPassTry{};
{
};
void DLL_API funcTryRefTypePtrOut(CS_OUT RefTypeClassPassTry* classTry); void DLL_API funcTryRefTypePtrOut(CS_OUT RefTypeClassPassTry* classTry);
void DLL_API funcTryRefTypeOut(CS_OUT RefTypeClassPassTry classTry); void DLL_API funcTryRefTypeOut(CS_OUT RefTypeClassPassTry classTry);
@ -902,6 +922,7 @@ class DLL_API HasVirtualProperty
public: public:
virtual int getProperty(); virtual int getProperty();
virtual void setProperty(int target); virtual void setProperty(int target);
protected: protected:
virtual int getProtectedProperty(); virtual int getProtectedProperty();
virtual void setProtectedProperty(int value); virtual void setProtectedProperty(int value);
@ -912,14 +933,13 @@ class DLL_API ChangedAccessOfInheritedProperty : public HasVirtualProperty
public: public:
int getProtectedProperty(); int getProtectedProperty();
void setProtectedProperty(int value); void setProtectedProperty(int value);
protected: protected:
int getProperty(); int getProperty();
void setProperty(int value); void setProperty(int value);
}; };
class DLL_API Empty class DLL_API Empty{};
{
};
class DLL_API ReturnsEmpty class DLL_API ReturnsEmpty
{ {
@ -983,10 +1003,17 @@ public:
virtual int retInt(const Foo& foo); virtual int retInt(const Foo& foo);
}; };
namespace boost namespace boost {
template <class T>
struct is_member_pointer_cv
{ {
template <class T> struct is_member_pointer_cv { static const bool value = false; }; static const bool value = false;
template <class T, class U>struct is_member_pointer_cv<T U::*> { static const bool value = true; }; };
template <class T, class U>
struct is_member_pointer_cv<T U::*>
{
static const bool value = true;
};
// all of this below tests corner cases with type locations // all of this below tests corner cases with type locations
template <class T> template <class T>
@ -1001,8 +1028,7 @@ namespace boost
// T>::RET type; // T>::RET type;
}; };
namespace detail namespace detail {
{
struct swallow_assign; struct swallow_assign;
typedef void (detail::swallow_assign::*ignore_t)(); typedef void (detail::swallow_assign::*ignore_t)();
struct swallow_assign struct swallow_assign
@ -1036,10 +1062,11 @@ namespace boost
template <class U> template <class U>
static char is_class_or_union_tester(void (U::*)(void)); static char is_class_or_union_tester(void (U::*)(void));
}; };
} } // namespace boost
template <std::size_t N, std::size_t... I> template <std::size_t N, std::size_t... I>
struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {}; struct build_index_impl : build_index_impl<N - 1, N - 1, I...>
{};
template <typename T> template <typename T>
class AbstractTemplate class AbstractTemplate
@ -1074,15 +1101,18 @@ public:
~NonTrivialDtor(); ~NonTrivialDtor();
static bool getDtorCalled(); static bool getDtorCalled();
static void setDtorCalled(bool value); static void setDtorCalled(bool value);
private: private:
static bool dtorCalled; static bool dtorCalled;
}; };
template <class T> class ForwardedTemplate; template <class T>
class ForwardedTemplate;
ForwardedTemplate<int> returnsForwardedTemplate(); ForwardedTemplate<int> returnsForwardedTemplate();
template <class T> class ForwardedTemplate template <class T>
class ForwardedTemplate
{ {
ForwardedTemplate<T> functionInForwardedTemplate() const; ForwardedTemplate<T> functionInForwardedTemplate() const;
}; };
@ -1112,7 +1142,8 @@ void TemplateWithVirtual<T>::v()
} }
template <typename T> template <typename T>
int FunctionTemplateWithDependentTypeDefaultExpr(size_t size = sizeof(T)) { int FunctionTemplateWithDependentTypeDefaultExpr(size_t size = sizeof(T))
{
return size; return size;
} }
@ -1160,7 +1191,8 @@ private:
template <class T> template <class T>
class SpecialisesVoidInUnion class SpecialisesVoidInUnion
{ {
union { union
{
SpecialisesVoid<T>* e; SpecialisesVoid<T>* e;
}* u; }* u;
}; };
@ -1250,9 +1282,17 @@ public:
DLL_API void hasPointerParam(Foo* foo, int i); DLL_API void hasPointerParam(Foo* foo, int i);
DLL_API void hasPointerParam(const Foo& foo); DLL_API void hasPointerParam(const Foo& foo);
enum EmptyEnum { }; enum EmptyEnum
{
};
enum __enum_with_underscores { lOWER_BEFORE_CAPITAL, CAPITALS_More, underscore_at_end_, usesDigits1_0 }; enum __enum_with_underscores
{
lOWER_BEFORE_CAPITAL,
CAPITALS_More,
underscore_at_end_,
usesDigits1_0
};
void DLL_API sMallFollowedByCapital(); void DLL_API sMallFollowedByCapital();
@ -1263,6 +1303,7 @@ public:
HasCopyAndMoveConstructor(const HasCopyAndMoveConstructor& other); HasCopyAndMoveConstructor(const HasCopyAndMoveConstructor& other);
HasCopyAndMoveConstructor(HasCopyAndMoveConstructor&& other); HasCopyAndMoveConstructor(HasCopyAndMoveConstructor&& other);
int getField(); int getField();
private: private:
int field; int field;
}; };
@ -1354,18 +1395,16 @@ struct DLL_API NestedUnionWithNested
}; };
}; };
template<typename T> void TemplatedFunction(T type) template <typename T>
void TemplatedFunction(T type)
{ {
} }
inline namespace InlineNamespace inline namespace InlineNamespace {
{
void FunctionInsideInlineNamespace() void FunctionInsideInlineNamespace()
{ {
}
} }
} // namespace InlineNamespace
union union
{ {
@ -1391,12 +1430,11 @@ struct TemplateWithUsingTemplateMember
UsingTemplatePtr<TemplateWithUsingTemplateMember> _Ref; UsingTemplatePtr<TemplateWithUsingTemplateMember> _Ref;
}; };
namespace hasUnnamedDecl namespace hasUnnamedDecl {
{
extern "C" extern "C"
{ {
} }
} } // namespace hasUnnamedDecl
enum ItemsDifferByCase enum ItemsDifferByCase
{ {
@ -1404,7 +1442,8 @@ enum ItemsDifferByCase
Case_A Case_A
}; };
template <typename T> struct MyListBase template <typename T>
struct MyListBase
{ {
protected: protected:
~MyListBase() {} ~MyListBase() {}
@ -1417,7 +1456,8 @@ public:
inline MyList() {} inline MyList() {}
}; };
template <> struct MyListBase<int> template <>
struct MyListBase<int>
{ {
}; };
@ -1428,13 +1468,17 @@ class MyIntList : public MyList<int>
void MyFunc(MyList<void*>* list); void MyFunc(MyList<void*>* list);
template<class T> using InvokeGenSeq = typename T::Type; template <class T>
using InvokeGenSeq = typename T::Type;
template<int N> struct DerivedTypeAlias; template <int N>
template<int N> using TypeAlias = InvokeGenSeq<DerivedTypeAlias<N>>; struct DerivedTypeAlias;
template <int N>
using TypeAlias = InvokeGenSeq<DerivedTypeAlias<N>>;
template <int N> template <int N>
struct DerivedTypeAlias : TypeAlias<N / 2> {}; struct DerivedTypeAlias : TypeAlias<N / 2>
{};
DLL_API ImplementsAbstractFoo freeFunctionReturnsVirtualDtor(); DLL_API ImplementsAbstractFoo freeFunctionReturnsVirtualDtor();
DLL_API void integerOverload(int i); DLL_API void integerOverload(int i);
@ -1450,22 +1494,27 @@ typedef const char* LPCSTR;
DLL_API LPCSTR TakeTypedefedMappedType(LPCSTR string); DLL_API LPCSTR TakeTypedefedMappedType(LPCSTR string);
DLL_API std::string UTF8; DLL_API std::string UTF8;
typedef enum SE4IpAddr_Tag { typedef enum SE4IpAddr_Tag
{
V4, V4,
V6, V6,
} SE4IpAddr_Tag; } SE4IpAddr_Tag;
typedef struct { typedef struct
{
uint8_t _0[4]; uint8_t _0[4];
} SE4V4_Body; } SE4V4_Body;
typedef struct { typedef struct
{
uint8_t _0[16]; uint8_t _0[16];
} SE4V6_Body; } SE4V6_Body;
typedef struct { typedef struct
{
SE4IpAddr_Tag tag; SE4IpAddr_Tag tag;
union { union
{
SE4V4_Body v4; SE4V4_Body v4;
SE4V6_Body v6; SE4V6_Body v6;
}; };
@ -1484,26 +1533,31 @@ uint16_t DLL_API TestStructWithCopyCtorByValue(StructWithCopyCtor s);
struct BaseCovariant; struct BaseCovariant;
typedef std::unique_ptr<BaseCovariant> PtrCovariant; typedef std::unique_ptr<BaseCovariant> PtrCovariant;
struct DLL_API BaseCovariant { struct DLL_API BaseCovariant
{
virtual ~BaseCovariant(); virtual ~BaseCovariant();
virtual PtrCovariant clone() const = 0; virtual PtrCovariant clone() const = 0;
}; };
struct DLL_API DerivedCovariant: public BaseCovariant { struct DLL_API DerivedCovariant : public BaseCovariant
{
virtual ~DerivedCovariant(); virtual ~DerivedCovariant();
std::unique_ptr<BaseCovariant> clone() const override { std::unique_ptr<BaseCovariant> clone() const override
{
return PtrCovariant(new DerivedCovariant()); return PtrCovariant(new DerivedCovariant());
} }
}; };
// Issue: https://github.com/mono/CppSharp/issues/1268 // Issue: https://github.com/mono/CppSharp/issues/1268
template <typename T> template <typename T>
class AbstractClassTemplate { class AbstractClassTemplate
{
public: public:
virtual void func() = 0; virtual void func() = 0;
}; };
class DerivedClass: public AbstractClassTemplate<int> { class DerivedClass : public AbstractClassTemplate<int>
{
public: public:
void func() override {} void func() override {}
}; };
@ -1512,13 +1566,15 @@ class DerivedClass: public AbstractClassTemplate<int> {
#include <functional> #include <functional>
template <typename X, typename Y> template <typename X, typename Y>
class TemplateClassBase { class TemplateClassBase
{
public: public:
using XType = X; using XType = X;
}; };
template <typename A, typename B = A> template <typename A, typename B = A>
class TemplateClass : TemplateClassBase<A,B> { class TemplateClass : TemplateClassBase<A, B>
{
public: public:
using typename TemplateClassBase<A, B>::XType; using typename TemplateClassBase<A, B>::XType;
using Func = std::function<B(XType)>; using Func = std::function<B(XType)>;
@ -1536,9 +1592,13 @@ public:
}; };
template <typename T> template <typename T>
struct dependentVariable { static const size_t var = alignof(T); }; struct dependentVariable
{
static const size_t var = alignof(T);
};
class QObjectData { class QObjectData
{
}; };
QScopedPointer<QObjectData> d_ptr; QScopedPointer<QObjectData> d_ptr;

1
tests/dotnet/Empty/Empty.h

@ -1,2 +1 @@
#include "../Tests.h" #include "../Tests.h"

6
tests/dotnet/NamespacesBase/NamespacesBase.cpp

@ -16,11 +16,13 @@ int Base::parent()
return 0; return 0;
} }
Base2::Base2() : Base() Base2::Base2()
: Base()
{ {
} }
Base2::Base2(int i) : Base(i) Base2::Base2(int i)
: Base(i)
{ {
} }

14
tests/dotnet/NamespacesBase/NamespacesBase.h

@ -1,9 +1,9 @@
#include "../Tests.h" #include "../Tests.h"
namespace OverlappingNamespace namespace OverlappingNamespace {
enum ColorsEnum
{ {
enum ColorsEnum {
white, white,
black, black,
red, red,
@ -11,11 +11,8 @@ namespace OverlappingNamespace
green, green,
}; };
class DLL_API InBaseLib class DLL_API InBaseLib{};
{ } // namespace OverlappingNamespace
};
}
class DLL_API Base class DLL_API Base
@ -49,6 +46,7 @@ class TemplateClass
public: public:
T getField() const; T getField() const;
void setField(const T& value); void setField(const T& value);
private: private:
union union
{ {
@ -79,6 +77,7 @@ public:
private: private:
T field; T field;
}; };
private: private:
union union
{ {
@ -96,6 +95,7 @@ public:
}; };
Nested useDependentPointer(const T* t); Nested useDependentPointer(const T* t);
const T& constField() const; const T& constField() const;
private: private:
T* t = new T; T* t = new T;
Nested nested; Nested nested;

3
tests/dotnet/NamespacesDerived/Independent.h

@ -1,3 +1,4 @@
class Derived; class Derived;
template<typename T> class DependentFields; template <typename T>
class DependentFields;
typedef DependentFields<Derived*> ForwardedInIndependentHeader; typedef DependentFields<Derived*> ForwardedInIndependentHeader;

10
tests/dotnet/NamespacesDerived/NamespacesDerived.cpp

@ -1,11 +1,17 @@
#include "NamespacesDerived.h" #include "NamespacesDerived.h"
OverlappingNamespace::InDerivedLib::InDerivedLib() : parentNSComponent(), color(black) OverlappingNamespace::InDerivedLib::InDerivedLib()
: parentNSComponent()
, color(black)
{ {
} }
Derived::Derived() : Base2(10), baseComponent(5), nestedNSComponent(), color(OverlappingNamespace::blue) Derived::Derived()
: Base2(10)
, baseComponent(5)
, nestedNSComponent()
, color(OverlappingNamespace::blue)
{ {
} }

20
tests/dotnet/NamespacesDerived/NamespacesDerived.h

@ -7,8 +7,7 @@
// Namespace clashes with NamespacesBase.OverlappingNamespace // Namespace clashes with NamespacesBase.OverlappingNamespace
// Test whether qualified names turn out right. // Test whether qualified names turn out right.
namespace OverlappingNamespace namespace OverlappingNamespace {
{
class DLL_API InDerivedLib class DLL_API InDerivedLib
{ {
public: public:
@ -16,7 +15,7 @@ namespace OverlappingNamespace
Base parentNSComponent; Base parentNSComponent;
ColorsEnum color; ColorsEnum color;
}; };
} } // namespace OverlappingNamespace
// Using a type imported from a different library. // Using a type imported from a different library.
@ -46,7 +45,8 @@ class Base3
{ {
}; };
template <typename T> class TemplateClass; template <typename T>
class TemplateClass;
class DLL_API Derived2 : public Base3 class DLL_API Derived2 : public Base3
{ {
@ -66,6 +66,7 @@ public:
typedef DependentFields<int> LocalTypedefSpecialization; typedef DependentFields<int> LocalTypedefSpecialization;
LocalTypedefSpecialization getLocalTypedefSpecialization(); LocalTypedefSpecialization getLocalTypedefSpecialization();
Abstract* getAbstract(); Abstract* getAbstract();
private: private:
TemplateClass<int> t; TemplateClass<int> t;
TemplateClass<Derived> d; TemplateClass<Derived> d;
@ -107,7 +108,8 @@ public:
CustomAllocator() = default; CustomAllocator() = default;
template <typename U> template <typename U>
CustomAllocator(const CustomAllocator<U>&) noexcept { CustomAllocator(const CustomAllocator<U>&) noexcept
{
} }
T* allocate(size_t cnt, const void* = 0) { return 0; } T* allocate(size_t cnt, const void* = 0) { return 0; }
@ -132,14 +134,13 @@ private:
DLL_API bool operator<<(const Base& b, const char* str); DLL_API bool operator<<(const Base& b, const char* str);
namespace NamespacesBase namespace NamespacesBase {
{
class DLL_API ClassInNamespaceNamedAfterDependency class DLL_API ClassInNamespaceNamedAfterDependency
{ {
private: private:
Base base; Base base;
}; };
} } // namespace NamespacesBase
/// Hash set/map base class. /// Hash set/map base class.
/** Note that to prevent extra memory use due to vtable pointer, %HashBase intentionally does not declare a virtual destructor /** Note that to prevent extra memory use due to vtable pointer, %HashBase intentionally does not declare a virtual destructor
@ -206,7 +207,8 @@ public:
/** /**
* <sip:alice@example.net> * <sip:alice@example.net>
*/ */
class LinphoneAddress {}; class LinphoneAddress
{};
}; };
DLL_API void forceUseSpecializations(ForwardedInIndependentHeader value); DLL_API void forceUseSpecializations(ForwardedInIndependentHeader value);

64
tests/dotnet/Native/AST.h

@ -4,12 +4,17 @@
void TestParameterProperties(bool a, const short& b, int* c = nullptr) {}; void TestParameterProperties(bool a, const short& b, int* c = nullptr) {};
// Tests various AST helper methods (like FindClass, FindOperator etc.) // Tests various AST helper methods (like FindClass, FindOperator etc.)
namespace Math namespace Math {
{
// Tests FindClass("Math::Complex") // Tests FindClass("Math::Complex")
struct Complex { struct Complex
Complex(double r, double i) : re(r), im(i) {} {
Complex(double r, double i)
: re(r)
, im(i)
{
}
Complex operator+(Complex& other); Complex operator+(Complex& other);
private: private:
double re, im; double re, im;
}; };
@ -18,15 +23,19 @@ namespace Math
typedef float Single; typedef float Single;
// Tests FindOperator method // Tests FindOperator method
Complex Complex::operator+(Complex &other) { Complex Complex::operator+(Complex& other)
{
return Complex(re + other.re, im + other.im); return Complex(re + other.re, im + other.im);
} }
void function(); void function();
} } // namespace Math
// Tests Enum.ItemByName // Tests Enum.ItemByName
enum TestASTEnumItemByName { TestItemByName }; enum TestASTEnumItemByName
{
TestItemByName
};
// Tests class templates // Tests class templates
template <typename T> template <typename T>
@ -45,12 +54,27 @@ public:
class TestTemplateFunctions class TestTemplateFunctions
{ {
public: public:
template<typename T> T Identity(T x) { return x; } template <typename T>
template<int N> void Ignore() { }; T Identity(T x)
template<typename T, typename S> void MethodTemplateWithTwoTypeParameter(T t, S s) { }; {
template<typename T> void Ignore(TestTemplateClass<T> v) { }; return x;
template<typename T> T Valid(TestTemplateClass<int> v, T x) { return x; }; }
template<typename T> T& Valid(TestTemplateClass<int> v, T x) const { return x; } template <int N>
void Ignore() {};
template <typename T, typename S>
void MethodTemplateWithTwoTypeParameter(T t, S s) {};
template <typename T>
void Ignore(TestTemplateClass<T> v) {};
template <typename T>
T Valid(TestTemplateClass<int> v, T x)
{
return x;
};
template <typename T>
T& Valid(TestTemplateClass<int> v, T x) const
{
return x;
}
}; };
// Explicit instantiation // Explicit instantiation
@ -65,12 +89,11 @@ public:
TestTemplateClassInt* CreateIntTemplate(); TestTemplateClassInt* CreateIntTemplate();
}; };
namespace HidesClass namespace HidesClass {
{
class HiddenInNamespace class HiddenInNamespace
{ {
}; };
} } // namespace HidesClass
void testSignature(); void testSignature();
@ -162,12 +185,15 @@ void testInlineAssembly()
} }
// Tests redeclarations // Tests redeclarations
class ClassA {}; class ClassA
{};
class ClassB {}; class ClassB
{};
class ClassB; class ClassB;
class ClassC {}; class ClassC
{};
class ClassC; class ClassC;
class ClassC; class ClassC;

3
tests/dotnet/Native/Enums.h

@ -6,4 +6,5 @@ enum
// This line will make sure that a visitor won't enumerate all enums across // This line will make sure that a visitor won't enumerate all enums across
// different translation units at once. // different translation units at once.
struct TestUniqueNames {}; struct TestUniqueNames
{};

25
tests/dotnet/Native/Passes.h

@ -92,12 +92,26 @@ enum
#define TEST_INT_PLUS_LONG 5 + 2147483648 #define TEST_INT_PLUS_LONG 5 + 2147483648
// TestStructInheritance // TestStructInheritance
struct S1 { int F1, F2; }; struct S1
struct S2 : S1 { int F3; }; {
int F1, F2;
};
struct S2 : S1
{
int F3;
};
// Tests unnamed enums // Tests unnamed enums
enum { Unnamed_Enum_1_A = 1, Unnamed_Enum_1_B = 2 }; enum
enum { Unnamed_Enum_2_A = 3, Unnamed_Enum_2_B = 4 }; {
Unnamed_Enum_1_A = 1,
Unnamed_Enum_1_B = 2
};
enum
{
Unnamed_Enum_2_A = 3,
Unnamed_Enum_2_B = 4
};
// Tests unique name for unnamed enums across translation units // Tests unique name for unnamed enums across translation units
#include "Enums.h" #include "Enums.h"
@ -129,7 +143,8 @@ class ClassWithAbstractOperator
enum ConnectionRole enum ConnectionRole
{ {
Role1, Role2 Role1,
Role2
}; };
bool ConnectionRoleToString(const ConnectionRole& role, const char* role_str); bool ConnectionRoleToString(const ConnectionRole& role, const char* role_str);

1
tests/dotnet/VTables/VTables.cpp

@ -60,4 +60,3 @@ int DerivedClassVirtual::retInt()
{ {
return 10; return 10;
} }

1
tests/dotnet/VTables/VTables.h

@ -6,7 +6,6 @@ class DLL_API Foo
public: public:
class Vfoo class Vfoo
{ {
}; };
virtual int vfoo(); virtual int vfoo();

Loading…
Cancel
Save