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. 110
      src/CppParser/APValuePrinter.h
  10. 1915
      src/CppParser/AST.cpp
  11. 400
      src/CppParser/AST.h
  12. 71
      src/CppParser/ASTNameMangler.cpp
  13. 30
      src/CppParser/ASTNameMangler.h
  14. 29
      src/CppParser/CXXABI.h
  15. 336
      src/CppParser/Comments.cpp
  16. 119
      src/CppParser/CppParser.cpp
  17. 240
      src/CppParser/CppParser.h
  18. 1658
      src/CppParser/Decl.h
  19. 256
      src/CppParser/ELFDumper.h
  20. 78
      src/CppParser/Helpers.h
  21. 68
      src/CppParser/Link.cpp
  22. 3189
      src/CppParser/Parser.cpp
  23. 328
      src/CppParser/Parser.h
  24. 18
      src/CppParser/Sources.cpp
  25. 34
      src/CppParser/Sources.h
  26. 82
      src/CppParser/Target.cpp
  27. 132
      src/CppParser/Target.h
  28. 612
      src/CppParser/Types.h
  29. 6
      src/Generator.Tests/AST/TestAST.cs
  30. 10
      src/Generator/Generators/QuickJS/Runtime/CppSharp_QuickJS.cpp
  31. 391
      src/Generator/Generators/QuickJS/Runtime/CppSharp_QuickJS.h
  32. 266
      src/Generator/Generators/QuickJS/Runtime/CppSharp_QuickJS_Signal.cpp
  33. 194
      tests/Builtins.h
  34. 10
      tests/Classes.h
  35. 1
      tests/Classes2.h
  36. 6
      tests/Delegates.h
  37. 10
      tests/Enums.h
  38. 45
      tests/Overloads.h
  39. 193
      tests/dotnet/CSharp/AnonTypes.h
  40. 9
      tests/dotnet/CSharp/AnotherUnit.cpp
  41. 10
      tests/dotnet/CSharp/AnotherUnit.h
  42. 337
      tests/dotnet/CSharp/CSharp.cpp
  43. 448
      tests/dotnet/CSharp/CSharp.h
  44. 28
      tests/dotnet/CSharp/CSharpTemplates.cpp
  45. 190
      tests/dotnet/CSharp/CSharpTemplates.h
  46. 17
      tests/dotnet/CSharp/ExcludedUnit.hpp
  47. 19
      tests/dotnet/Common/AnotherUnit.h
  48. 228
      tests/dotnet/Common/Common.cpp
  49. 476
      tests/dotnet/Common/Common.h
  50. 1
      tests/dotnet/Empty/Empty.h
  51. 4
      tests/dotnet/Encodings/Encodings.h
  52. 6
      tests/dotnet/NamespacesBase/NamespacesBase.cpp
  53. 26
      tests/dotnet/NamespacesBase/NamespacesBase.h
  54. 3
      tests/dotnet/NamespacesDerived/Independent.h
  55. 12
      tests/dotnet/NamespacesDerived/NamespacesDerived.cpp
  56. 82
      tests/dotnet/NamespacesDerived/NamespacesDerived.h
  57. 98
      tests/dotnet/Native/AST.h
  58. 3
      tests/dotnet/Native/Enums.h
  59. 77
      tests/dotnet/Native/Passes.h
  60. 12
      tests/dotnet/Native/Templates.h
  61. 2
      tests/dotnet/StandardLib/StandardLib.h
  62. 4
      tests/dotnet/Tests.h
  63. 1
      tests/dotnet/VTables/VTables.cpp
  64. 1
      tests/dotnet/VTables/VTables.h

80
.clang-format

@ -0,0 +1,80 @@ @@ -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 @@ @@ -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 @@ @@ -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 @@ @@ -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: @@ -35,8 +35,6 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
fetch-depth: '0'
- name: Setup emsdk
uses: mymindstorm/setup-emsdk@v11
@ -127,8 +125,6 @@ jobs: @@ -127,8 +125,6 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
fetch-depth: '0'
- name: Set version
run: nbgv cloud --all-vars

1
.gitignore vendored

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

5
CppSharp.sln.DotSettings

@ -0,0 +1,5 @@ @@ -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 @@ @@ -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

110
src/CppParser/APValuePrinter.h

@ -10,82 +10,82 @@ @@ -10,82 +10,82 @@
namespace CppSharp { namespace CppParser {
struct APValuePrinter
{
clang::ASTContext &ctx;
clang::raw_ostream &out;
clang::ASTContext& ctx;
clang::raw_ostream& out;
bool Print(clang::APValue &value, clang::QualType type)
bool Print(clang::APValue& value, clang::QualType type)
{
using namespace clang;
switch (value.getKind())
{
case APValue::Int:
if (type->isBooleanType())
out << (value.getInt().getBoolValue() ? "true" : "false");
else
out << value.getInt();
return true;
case APValue::Float:
{
SmallString<50> str;
value.getFloat().toString(str);
out << str.str().str();
return true;
}
case APValue::Vector:
{
out << '{';
const auto elementType = type->castAs<clang::VectorType>()->getElementType();
if (!Print(value.getVectorElt(0), elementType))
return false;
for (unsigned i = 1; i != value.getVectorLength(); ++i)
case APValue::Int:
if (type->isBooleanType())
out << (value.getInt().getBoolValue() ? "true" : "false");
else
out << value.getInt();
return true;
case APValue::Float:
{
out << ", ";
Print(value.getVectorElt(i), elementType);
SmallString<50> str;
value.getFloat().toString(str);
out << str.str().str();
return true;
}
out << '}';
return true;
}
case APValue::Array:
{
const auto *arrayType = ctx.getAsArrayType(type);
const auto elementType = arrayType->getElementType();
out << '{';
if (unsigned n = value.getArrayInitializedElts())
case APValue::Vector:
{
if (!Print(value.getArrayInitializedElt(0), elementType))
out << '{';
const auto elementType = type->castAs<clang::VectorType>()->getElementType();
if (!Print(value.getVectorElt(0), elementType))
return false;
for (unsigned i = 1; i != n; ++i)
for (unsigned i = 1; i != value.getVectorLength(); ++i)
{
out << ", ";
Print(value.getArrayInitializedElt(i), elementType);
Print(value.getVectorElt(i), elementType);
}
out << '}';
return true;
}
out << '}';
return true;
}
case APValue::LValue:
{
auto base = value.getLValueBase();
if (const ValueDecl *VD = base.dyn_cast<const ValueDecl *>())
case APValue::Array:
{
out << *VD;
const auto* arrayType = ctx.getAsArrayType(type);
const auto elementType = arrayType->getElementType();
out << '{';
if (unsigned n = value.getArrayInitializedElts())
{
if (!Print(value.getArrayInitializedElt(0), elementType))
return false;
for (unsigned i = 1; i != n; ++i)
{
out << ", ";
Print(value.getArrayInitializedElt(i), elementType);
}
}
out << '}';
return true;
}
else if (TypeInfoLValue TI = base.dyn_cast<TypeInfoLValue>())
return false;
else if (DynamicAllocLValue DA = base.dyn_cast<DynamicAllocLValue>())
return false;
else
case APValue::LValue:
{
base.get<const clang::Expr *>()->printPretty(out, nullptr, ctx.getPrintingPolicy());
return true;
auto base = value.getLValueBase();
if (const ValueDecl* VD = base.dyn_cast<const ValueDecl*>())
{
out << *VD;
return true;
}
else if (TypeInfoLValue TI = base.dyn_cast<TypeInfoLValue>())
return false;
else if (DynamicAllocLValue DA = base.dyn_cast<DynamicAllocLValue>())
return false;
else
{
base.get<const clang::Expr*>()->printPretty(out, nullptr, ctx.getPrintingPolicy());
return true;
}
}
}
}
return false;
}
};
} }
}} // namespace CppSharp::CppParser

1915
src/CppParser/AST.cpp

File diff suppressed because it is too large Load Diff

400
src/CppParser/AST.h

@ -1,9 +1,9 @@ @@ -1,9 +1,9 @@
/************************************************************************
*
* CppSharp
* Licensed under the MIT license.
*
************************************************************************/
*
* CppSharp
* Licensed under the MIT license.
*
************************************************************************/
#pragma once
@ -19,236 +19,236 @@ namespace CppSharp { namespace CppParser { namespace AST { @@ -19,236 +19,236 @@ namespace CppSharp { namespace CppParser { namespace AST {
#pragma region Libraries
enum class ArchType
{
UnknownArch,
x86,
x86_64,
aarch64,
aarch64_be,
aarch64_32
};
enum class ArchType
{
UnknownArch,
x86,
x86_64,
aarch64,
aarch64_be,
aarch64_32
};
class CS_API NativeLibrary
{
public:
NativeLibrary();
~NativeLibrary();
std::string fileName;
ArchType archType;
VECTOR_STRING(Symbols)
VECTOR_STRING(Dependencies)
};
class CS_API NativeLibrary
{
public:
NativeLibrary();
~NativeLibrary();
std::string fileName;
ArchType archType;
VECTOR_STRING(Symbols)
VECTOR_STRING(Dependencies)
};
#pragma endregion
#pragma region Comments
enum struct CommentKind
{
FullComment,
BlockContentComment,
BlockCommandComment,
ParamCommandComment,
TParamCommandComment,
VerbatimBlockComment,
VerbatimLineComment,
ParagraphComment,
HTMLTagComment,
HTMLStartTagComment,
HTMLEndTagComment,
TextComment,
InlineContentComment,
InlineCommandComment,
VerbatimBlockLineComment
};
class CS_API CS_ABSTRACT Comment
{
public:
Comment(CommentKind kind);
CommentKind kind;
};
class CS_API BlockContentComment : public Comment
{
public:
BlockContentComment();
BlockContentComment(CommentKind Kind);
};
enum struct CommentKind
{
FullComment,
BlockContentComment,
BlockCommandComment,
ParamCommandComment,
TParamCommandComment,
VerbatimBlockComment,
VerbatimLineComment,
ParagraphComment,
HTMLTagComment,
HTMLStartTagComment,
HTMLEndTagComment,
TextComment,
InlineContentComment,
InlineCommandComment,
VerbatimBlockLineComment
};
class CS_API FullComment : public Comment
{
public:
FullComment();
~FullComment();
VECTOR(BlockContentComment*, Blocks)
};
class CS_API CS_ABSTRACT Comment
{
public:
Comment(CommentKind kind);
CommentKind kind;
};
class CS_API InlineContentComment : public Comment
{
public:
InlineContentComment();
InlineContentComment(CommentKind Kind);
bool hasTrailingNewline;
};
class CS_API BlockContentComment : public Comment
{
public:
BlockContentComment();
BlockContentComment(CommentKind Kind);
};
class CS_API ParagraphComment : public BlockContentComment
{
public:
ParagraphComment();
~ParagraphComment();
bool isWhitespace;
VECTOR(InlineContentComment*, Content)
};
class CS_API FullComment : public Comment
{
public:
FullComment();
~FullComment();
VECTOR(BlockContentComment*, Blocks)
};
class CS_API BlockCommandComment : public BlockContentComment
{
public:
class CS_API Argument
class CS_API InlineContentComment : public Comment
{
public:
Argument();
Argument(const Argument&);
~Argument();
std::string text;
InlineContentComment();
InlineContentComment(CommentKind Kind);
bool hasTrailingNewline;
};
BlockCommandComment();
BlockCommandComment(CommentKind Kind);
~BlockCommandComment();
unsigned commandId;
ParagraphComment* paragraphComment;
VECTOR(Argument, Arguments)
};
class CS_API ParamCommandComment : public BlockCommandComment
{
public:
enum PassDirection
class CS_API ParagraphComment : public BlockContentComment
{
In,
Out,
InOut
public:
ParagraphComment();
~ParagraphComment();
bool isWhitespace;
VECTOR(InlineContentComment*, Content)
};
ParamCommandComment();
PassDirection direction;
unsigned paramIndex;
};
class CS_API TParamCommandComment : public BlockCommandComment
{
public:
TParamCommandComment();
VECTOR(unsigned, Position)
};
class CS_API BlockCommandComment : public BlockContentComment
{
public:
class CS_API Argument
{
public:
Argument();
Argument(const Argument&);
~Argument();
std::string text;
};
BlockCommandComment();
BlockCommandComment(CommentKind Kind);
~BlockCommandComment();
unsigned commandId;
ParagraphComment* paragraphComment;
VECTOR(Argument, Arguments)
};
class CS_API VerbatimBlockLineComment : public Comment
{
public:
VerbatimBlockLineComment();
std::string text;
};
class CS_API ParamCommandComment : public BlockCommandComment
{
public:
enum PassDirection
{
In,
Out,
InOut
};
ParamCommandComment();
PassDirection direction;
unsigned paramIndex;
};
class CS_API VerbatimBlockComment : public BlockCommandComment
{
public:
VerbatimBlockComment();
~VerbatimBlockComment();
VECTOR(VerbatimBlockLineComment*, Lines)
};
class CS_API TParamCommandComment : public BlockCommandComment
{
public:
TParamCommandComment();
VECTOR(unsigned, Position)
};
class CS_API VerbatimLineComment : public BlockCommandComment
{
public:
VerbatimLineComment();
std::string text;
};
class CS_API VerbatimBlockLineComment : public Comment
{
public:
VerbatimBlockLineComment();
std::string text;
};
class CS_API InlineCommandComment : public InlineContentComment
{
public:
enum RenderKind
class CS_API VerbatimBlockComment : public BlockCommandComment
{
RenderNormal,
RenderBold,
RenderMonospaced,
RenderEmphasized,
RenderAnchor
public:
VerbatimBlockComment();
~VerbatimBlockComment();
VECTOR(VerbatimBlockLineComment*, Lines)
};
class CS_API Argument
class CS_API VerbatimLineComment : public BlockCommandComment
{
public:
Argument();
Argument(const Argument&);
~Argument();
VerbatimLineComment();
std::string text;
};
InlineCommandComment();
unsigned commandId;
RenderKind commentRenderKind;
VECTOR(Argument, Arguments)
};
class CS_API HTMLTagComment : public InlineContentComment
{
public:
HTMLTagComment();
HTMLTagComment(CommentKind Kind);
};
class CS_API InlineCommandComment : public InlineContentComment
{
public:
enum RenderKind
{
RenderNormal,
RenderBold,
RenderMonospaced,
RenderEmphasized,
RenderAnchor
};
class CS_API Argument
{
public:
Argument();
Argument(const Argument&);
~Argument();
std::string text;
};
InlineCommandComment();
unsigned commandId;
RenderKind commentRenderKind;
VECTOR(Argument, Arguments)
};
class CS_API HTMLStartTagComment : public HTMLTagComment
{
public:
class CS_API Attribute
class CS_API HTMLTagComment : public InlineContentComment
{
public:
Attribute();
Attribute(const Attribute&);
~Attribute();
std::string name;
std::string value;
HTMLTagComment();
HTMLTagComment(CommentKind Kind);
};
HTMLStartTagComment();
std::string tagName;
VECTOR(Attribute, Attributes)
};
class CS_API HTMLEndTagComment : public HTMLTagComment
{
public:
HTMLEndTagComment();
std::string tagName;
};
class CS_API HTMLStartTagComment : public HTMLTagComment
{
public:
class CS_API Attribute
{
public:
Attribute();
Attribute(const Attribute&);
~Attribute();
std::string name;
std::string value;
};
HTMLStartTagComment();
std::string tagName;
VECTOR(Attribute, Attributes)
};
class CS_API TextComment : public InlineContentComment
{
public:
TextComment();
std::string text;
};
class CS_API HTMLEndTagComment : public HTMLTagComment
{
public:
HTMLEndTagComment();
std::string tagName;
};
enum class RawCommentKind
{
Invalid,
OrdinaryBCPL,
OrdinaryC,
BCPLSlash,
BCPLExcl,
JavaDoc,
Qt,
Merged
};
class CS_API TextComment : public InlineContentComment
{
public:
TextComment();
std::string text;
};
class CS_API RawComment
{
public:
RawComment();
~RawComment();
RawCommentKind kind;
std::string text;
std::string briefText;
FullComment* fullCommentBlock;
};
enum class RawCommentKind
{
Invalid,
OrdinaryBCPL,
OrdinaryC,
BCPLSlash,
BCPLExcl,
JavaDoc,
Qt,
Merged
};
class CS_API RawComment
{
public:
RawComment();
~RawComment();
RawCommentKind kind;
std::string text;
std::string briefText;
FullComment* fullCommentBlock;
};
#pragma region Commands
@ -256,4 +256,4 @@ public: @@ -256,4 +256,4 @@ public:
#pragma endregion
} } }
}}} // namespace CppSharp::CppParser::AST

71
src/CppParser/ASTNameMangler.cpp

@ -1,9 +1,9 @@ @@ -1,9 +1,9 @@
/************************************************************************
*
* CppSharp
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
*
* CppSharp
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
#include "ASTNameMangler.h"
@ -17,30 +17,34 @@ using namespace clang; @@ -17,30 +17,34 @@ using namespace clang;
using namespace CppSharp::CppParser;
namespace {
enum ObjCKind {
ObjCClass,
ObjCMetaclass,
};
StringRef getClassSymbolPrefix(ObjCKind Kind, const ASTContext& Context) {
if (Context.getLangOpts().ObjCRuntime.isGNUFamily())
return Kind == ObjCMetaclass ? "_OBJC_METACLASS_" : "_OBJC_CLASS_";
return Kind == ObjCMetaclass ? "OBJC_METACLASS_$_" : "OBJC_CLASS_$_";
}
enum ObjCKind
{
ObjCClass,
ObjCMetaclass,
};
void WriteObjCClassName(const ObjCInterfaceDecl* D, raw_ostream& OS) {
OS << getClassSymbolPrefix(ObjCClass, D->getASTContext());
OS << D->getObjCRuntimeNameAsString();
}
StringRef getClassSymbolPrefix(ObjCKind Kind, const ASTContext& Context)
{
if (Context.getLangOpts().ObjCRuntime.isGNUFamily())
return Kind == ObjCMetaclass ? "_OBJC_METACLASS_" : "_OBJC_CLASS_";
return Kind == ObjCMetaclass ? "OBJC_METACLASS_$_" : "OBJC_CLASS_$_";
}
void WriteObjCClassName(const ObjCInterfaceDecl* D, raw_ostream& OS)
{
OS << getClassSymbolPrefix(ObjCClass, D->getASTContext());
OS << D->getObjCRuntimeNameAsString();
}
} // namespace
ASTNameMangler::ASTNameMangler(ASTContext& Ctx)
: DL(Ctx.getTargetInfo().getDataLayoutString())
, MC(Ctx.createMangleContext())
{
}
std::string ASTNameMangler::GetName(const Decl* D) const {
std::string ASTNameMangler::GetName(const Decl* D) const
{
std::string Name;
{
llvm::raw_string_ostream OS(Name);
@ -49,32 +53,39 @@ std::string ASTNameMangler::GetName(const Decl* D) const { @@ -49,32 +53,39 @@ std::string ASTNameMangler::GetName(const Decl* D) const {
return Name;
}
bool ASTNameMangler::WriteName(const Decl* D, raw_ostream& OS) const {
if (auto* FD = dyn_cast<FunctionDecl>(D)) {
bool ASTNameMangler::WriteName(const Decl* D, raw_ostream& OS) const
{
if (auto* FD = dyn_cast<FunctionDecl>(D))
{
if (FD->isDependentContext())
return true;
if (WriteFuncOrVarName(FD, OS))
return true;
}
else if (auto* VD = dyn_cast<VarDecl>(D)) {
else if (auto* VD = dyn_cast<VarDecl>(D))
{
if (WriteFuncOrVarName(VD, OS))
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);
return false;
}
else if (auto* ID = dyn_cast<ObjCInterfaceDecl>(D)) {
else if (auto* ID = dyn_cast<ObjCInterfaceDecl>(D))
{
WriteObjCClassName(ID, OS);
}
else {
else
{
return true;
}
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;
llvm::raw_string_ostream FOS(FrontendBuf);
@ -88,7 +99,8 @@ std::string ASTNameMangler::GetMangledStructor(const NamedDecl* ND, unsigned Str @@ -88,7 +99,8 @@ std::string ASTNameMangler::GetMangledStructor(const NamedDecl* ND, unsigned Str
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;
llvm::raw_string_ostream FOS(FrontendBuf);
@ -100,7 +112,8 @@ std::string ASTNameMangler::GetMangledThunk(const CXXMethodDecl* MD, const Thunk @@ -100,7 +112,8 @@ std::string ASTNameMangler::GetMangledThunk(const CXXMethodDecl* MD, const Thunk
bool ASTNameMangler::WriteFuncOrVarName(const NamedDecl* D, raw_ostream& OS) const
{
if (!MC->shouldMangleDeclName(D)) {
if (!MC->shouldMangleDeclName(D))
{
const IdentifierInfo* II = D->getIdentifier();
if (!II)
return true;

30
src/CppParser/ASTNameMangler.h

@ -1,9 +1,9 @@ @@ -1,9 +1,9 @@
/************************************************************************
*
* CppSharp
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
*
* CppSharp
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
#pragma once
@ -12,16 +12,14 @@ @@ -12,16 +12,14 @@
#include <string>
namespace clang
{
class ASTContext;
class MangleContext;
struct ThunkInfo;
}
namespace clang {
class ASTContext;
class MangleContext;
struct ThunkInfo;
} // namespace clang
namespace llvm
{
class raw_ostream;
namespace llvm {
class raw_ostream;
}
namespace CppSharp::CppParser {
@ -42,9 +40,9 @@ private: @@ -42,9 +40,9 @@ private:
std::string GetMangledStructor(const clang::NamedDecl* ND, unsigned StructorType) const;
std::string GetMangledThunk(const clang::CXXMethodDecl* MD, const clang::ThunkInfo& T, bool ElideOverrideInfo) const;
bool WriteFuncOrVarName(const clang::NamedDecl* D, llvm::raw_ostream& OS) const;
llvm::DataLayout DL;
std::unique_ptr<clang::MangleContext> MC;
};
}
} // namespace CppSharp::CppParser

29
src/CppParser/CXXABI.h

@ -21,26 +21,27 @@ class ASTContext; @@ -21,26 +21,27 @@ class ASTContext;
class MemberPointerType;
/// Implements C++ ABI-specific semantic analysis functions.
class CXXABI {
class CXXABI
{
public:
virtual ~CXXABI();
virtual ~CXXABI();
/// Returns the size of a member pointer in multiples of the target
/// pointer size.
virtual unsigned getMemberPointerSize(const MemberPointerType *MPT) const = 0;
/// Returns the size of a member pointer in multiples of the target
/// pointer size.
virtual unsigned getMemberPointerSize(const MemberPointerType* MPT) const = 0;
/// Returns the default calling convention for C++ methods.
virtual CallingConv getDefaultMethodCallConv() const = 0;
/// Returns the default calling convention for C++ methods.
virtual CallingConv getDefaultMethodCallConv() const = 0;
// Returns whether the given class is nearly empty, with just virtual pointers
// and no data except possibly virtual bases.
virtual bool isNearlyEmpty(const CXXRecordDecl *RD) const = 0;
// Returns whether the given class is nearly empty, with just virtual pointers
// and no data except possibly virtual bases.
virtual bool isNearlyEmpty(const CXXRecordDecl* RD) const = 0;
};
/// Creates an instance of a C++ ABI class.
CXXABI *CreateARMCXXABI(ASTContext &Ctx);
CXXABI *CreateItaniumCXXABI(ASTContext &Ctx);
CXXABI *CreateMicrosoftCXXABI(ASTContext &Ctx);
}
CXXABI* CreateARMCXXABI(ASTContext& Ctx);
CXXABI* CreateItaniumCXXABI(ASTContext& Ctx);
CXXABI* CreateMicrosoftCXXABI(ASTContext& Ctx);
} // namespace clang
#endif

336
src/CppParser/Comments.cpp

@ -1,9 +1,9 @@ @@ -1,9 +1,9 @@
/************************************************************************
*
* CppSharp
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
*
* CppSharp
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
#include "Parser.h"
@ -20,16 +20,16 @@ ConvertRawCommentKind(clang::RawComment::CommentKind Kind) @@ -20,16 +20,16 @@ ConvertRawCommentKind(clang::RawComment::CommentKind Kind)
{
using clang::RawComment;
switch(Kind)
switch (Kind)
{
case RawComment::RCK_Invalid: return RawCommentKind::Invalid;
case RawComment::RCK_OrdinaryBCPL: return RawCommentKind::OrdinaryBCPL;
case RawComment::RCK_OrdinaryC: return RawCommentKind::OrdinaryC;
case RawComment::RCK_BCPLSlash: return RawCommentKind::BCPLSlash;
case RawComment::RCK_BCPLExcl: return RawCommentKind::BCPLExcl;
case RawComment::RCK_JavaDoc: return RawCommentKind::JavaDoc;
case RawComment::RCK_Qt: return RawCommentKind::Qt;
case RawComment::RCK_Merged: return RawCommentKind::Merged;
case RawComment::RCK_Invalid: return RawCommentKind::Invalid;
case RawComment::RCK_OrdinaryBCPL: return RawCommentKind::OrdinaryBCPL;
case RawComment::RCK_OrdinaryC: return RawCommentKind::OrdinaryC;
case RawComment::RCK_BCPLSlash: return RawCommentKind::BCPLSlash;
case RawComment::RCK_BCPLExcl: return RawCommentKind::BCPLExcl;
case RawComment::RCK_JavaDoc: return RawCommentKind::JavaDoc;
case RawComment::RCK_Qt: return RawCommentKind::Qt;
case RawComment::RCK_Merged: return RawCommentKind::Merged;
}
llvm_unreachable("Unknown comment kind");
@ -52,18 +52,18 @@ static InlineCommandComment::RenderKind @@ -52,18 +52,18 @@ static InlineCommandComment::RenderKind
ConvertRenderKind(clang::comments::InlineCommandComment::RenderKind Kind)
{
using namespace clang::comments;
switch(Kind)
switch (Kind)
{
case clang::comments::InlineCommandComment::RenderNormal:
return CppSharp::CppParser::AST::InlineCommandComment::RenderKind::RenderNormal;
case clang::comments::InlineCommandComment::RenderBold:
return CppSharp::CppParser::AST::InlineCommandComment::RenderKind::RenderBold;
case clang::comments::InlineCommandComment::RenderMonospaced:
return CppSharp::CppParser::AST::InlineCommandComment::RenderKind::RenderMonospaced;
case clang::comments::InlineCommandComment::RenderEmphasized:
return CppSharp::CppParser::AST::InlineCommandComment::RenderKind::RenderEmphasized;
case clang::comments::InlineCommandComment::RenderAnchor:
return CppSharp::CppParser::AST::InlineCommandComment::RenderKind::RenderAnchor;
case clang::comments::InlineCommandComment::RenderNormal:
return CppSharp::CppParser::AST::InlineCommandComment::RenderKind::RenderNormal;
case clang::comments::InlineCommandComment::RenderBold:
return CppSharp::CppParser::AST::InlineCommandComment::RenderKind::RenderBold;
case clang::comments::InlineCommandComment::RenderMonospaced:
return CppSharp::CppParser::AST::InlineCommandComment::RenderKind::RenderMonospaced;
case clang::comments::InlineCommandComment::RenderEmphasized:
return CppSharp::CppParser::AST::InlineCommandComment::RenderKind::RenderEmphasized;
case clang::comments::InlineCommandComment::RenderAnchor:
return CppSharp::CppParser::AST::InlineCommandComment::RenderKind::RenderAnchor;
}
llvm_unreachable("Unknown render kind");
}
@ -72,25 +72,25 @@ static ParamCommandComment::PassDirection @@ -72,25 +72,25 @@ static ParamCommandComment::PassDirection
ConvertParamPassDirection(clang::comments::ParamCommandComment::PassDirection Dir)
{
using namespace clang::comments;
switch(Dir)
switch (Dir)
{
case clang::comments::ParamCommandComment::In:
return CppSharp::CppParser::AST::ParamCommandComment::PassDirection::In;
case clang::comments::ParamCommandComment::Out:
return CppSharp::CppParser::AST::ParamCommandComment::PassDirection::Out;
case clang::comments::ParamCommandComment::InOut:
return CppSharp::CppParser::AST::ParamCommandComment::PassDirection::InOut;
case clang::comments::ParamCommandComment::In:
return CppSharp::CppParser::AST::ParamCommandComment::PassDirection::In;
case clang::comments::ParamCommandComment::Out:
return CppSharp::CppParser::AST::ParamCommandComment::PassDirection::Out;
case clang::comments::ParamCommandComment::InOut:
return CppSharp::CppParser::AST::ParamCommandComment::PassDirection::InOut;
}
llvm_unreachable("Unknown parameter pass direction");
}
static void HandleInlineContent(const clang::comments::InlineContentComment *CK,
InlineContentComment* IC)
static void HandleInlineContent(const clang::comments::InlineContentComment* CK,
InlineContentComment* IC)
{
IC->hasTrailingNewline = CK->hasTrailingNewline();
}
static void HandleBlockCommand(const clang::comments::BlockCommandComment *CK,
static void HandleBlockCommand(const clang::comments::BlockCommandComment* CK,
BlockCommandComment* BC)
{
BC->commandId = CK->getCommandID();
@ -110,149 +110,149 @@ static Comment* ConvertCommentBlock(clang::comments::Comment* C) @@ -110,149 +110,149 @@ static Comment* ConvertCommentBlock(clang::comments::Comment* C)
// This needs to have an underscore else we get an ICE under VS2012.
CppSharp::CppParser::AST::Comment* _Comment = 0;
switch(C->getCommentKind())
switch (C->getCommentKind())
{
case Comment::FullCommentKind:
{
auto CK = cast<clang::comments::FullComment>(C);
auto FC = new FullComment();
_Comment = FC;
for (auto I = CK->child_begin(), E = CK->child_end(); I != E; ++I)
case Comment::FullCommentKind:
{
auto Content = ConvertCommentBlock(*I);
FC->Blocks.push_back(static_cast<BlockContentComment*>(Content));
auto CK = cast<clang::comments::FullComment>(C);
auto FC = new FullComment();
_Comment = FC;
for (auto I = CK->child_begin(), E = CK->child_end(); I != E; ++I)
{
auto Content = ConvertCommentBlock(*I);
FC->Blocks.push_back(static_cast<BlockContentComment*>(Content));
}
break;
}
break;
}
case Comment::BlockCommandCommentKind:
{
auto CK = cast<const clang::comments::BlockCommandComment>(C);
auto BC = new BlockCommandComment();
_Comment = BC;
HandleBlockCommand(CK, BC);
BC->paragraphComment = static_cast<ParagraphComment*>(ConvertCommentBlock(CK->getParagraph()));
break;
}
case Comment::ParamCommandCommentKind:
{
auto CK = cast<clang::comments::ParamCommandComment>(C);
auto PC = new ParamCommandComment();
_Comment = PC;
HandleBlockCommand(CK, PC);
PC->direction = ConvertParamPassDirection(CK->getDirection());
if (CK->isParamIndexValid() && !CK->isVarArgParam())
PC->paramIndex = CK->getParamIndex();
PC->paragraphComment = static_cast<ParagraphComment*>(ConvertCommentBlock(CK->getParagraph()));
break;
}
case Comment::TParamCommandCommentKind:
{
auto CK = cast<clang::comments::TParamCommandComment>(C);
_Comment = new TParamCommandComment();
auto TC = new TParamCommandComment();
_Comment = TC;
HandleBlockCommand(CK, TC);
if (CK->isPositionValid())
for (unsigned I = 0, E = CK->getDepth(); I != E; ++I)
TC->Position.push_back(CK->getIndex(I));
TC->paragraphComment = static_cast<ParagraphComment*>(ConvertCommentBlock(CK->getParagraph()));
break;
}
case Comment::VerbatimBlockCommentKind:
{
auto CK = cast<clang::comments::VerbatimBlockComment>(C);
auto VB = new VerbatimBlockComment();
_Comment = VB;
for (auto I = CK->child_begin(), E = CK->child_end(); I != E; ++I)
case Comment::BlockCommandCommentKind:
{
auto Line = ConvertCommentBlock(*I);
VB->Lines.push_back(static_cast<VerbatimBlockLineComment*>(Line));
auto CK = cast<const clang::comments::BlockCommandComment>(C);
auto BC = new BlockCommandComment();
_Comment = BC;
HandleBlockCommand(CK, BC);
BC->paragraphComment = static_cast<ParagraphComment*>(ConvertCommentBlock(CK->getParagraph()));
break;
}
break;
}
case Comment::VerbatimLineCommentKind:
{
auto CK = cast<clang::comments::VerbatimLineComment>(C);
auto VL = new VerbatimLineComment();
_Comment = VL;
VL->text = CK->getText().str();
break;
}
case Comment::ParagraphCommentKind:
{
auto CK = cast<clang::comments::ParagraphComment>(C);
auto PC = new ParagraphComment();
_Comment = PC;
for (auto I = CK->child_begin(), E = CK->child_end(); I != E; ++I)
case Comment::ParamCommandCommentKind:
{
auto Content = ConvertCommentBlock(*I);
PC->Content.push_back(static_cast<InlineContentComment*>(Content));
auto CK = cast<clang::comments::ParamCommandComment>(C);
auto PC = new ParamCommandComment();
_Comment = PC;
HandleBlockCommand(CK, PC);
PC->direction = ConvertParamPassDirection(CK->getDirection());
if (CK->isParamIndexValid() && !CK->isVarArgParam())
PC->paramIndex = CK->getParamIndex();
PC->paragraphComment = static_cast<ParagraphComment*>(ConvertCommentBlock(CK->getParagraph()));
break;
}
PC->isWhitespace = CK->isWhitespace();
break;
}
case Comment::HTMLStartTagCommentKind:
{
auto CK = cast<clang::comments::HTMLStartTagComment>(C);
auto TC = new HTMLStartTagComment();
_Comment = TC;
HandleInlineContent(CK, TC);
TC->tagName = CK->getTagName().str();
for (unsigned I = 0, E = CK->getNumAttrs(); I != E; ++I)
case Comment::TParamCommandCommentKind:
{
auto A = CK->getAttr(I);
auto Attr = HTMLStartTagComment::Attribute();
Attr.name = A.Name.str();
Attr.value = A.Value.str();
TC->Attributes.push_back(Attr);
auto CK = cast<clang::comments::TParamCommandComment>(C);
_Comment = new TParamCommandComment();
auto TC = new TParamCommandComment();
_Comment = TC;
HandleBlockCommand(CK, TC);
if (CK->isPositionValid())
for (unsigned I = 0, E = CK->getDepth(); I != E; ++I)
TC->Position.push_back(CK->getIndex(I));
TC->paragraphComment = static_cast<ParagraphComment*>(ConvertCommentBlock(CK->getParagraph()));
break;
}
break;
}
case Comment::HTMLEndTagCommentKind:
{
auto CK = cast<clang::comments::HTMLEndTagComment>(C);
auto TC = new HTMLEndTagComment();
_Comment = TC;
HandleInlineContent(CK, TC);
TC->tagName = CK->getTagName().str();
break;
}
case Comment::TextCommentKind:
{
auto CK = cast<clang::comments::TextComment>(C);
auto TC = new TextComment();
_Comment = TC;
HandleInlineContent(CK, TC);
TC->text = CK->getText().str();
break;
}
case Comment::InlineCommandCommentKind:
{
auto CK = cast<clang::comments::InlineCommandComment>(C);
auto IC = new InlineCommandComment();
_Comment = IC;
HandleInlineContent(CK, IC);
IC->commandId = CK->getCommandID();
IC->commentRenderKind = ConvertRenderKind(CK->getRenderKind());
for (unsigned I = 0, E = CK->getNumArgs(); I != E; ++I)
case Comment::VerbatimBlockCommentKind:
{
auto Arg = InlineCommandComment::Argument();
Arg.text = CK->getArgText(I).str();
IC->Arguments.push_back(Arg);
}
break;
}
case Comment::VerbatimBlockLineCommentKind:
{
auto CK = cast<clang::comments::VerbatimBlockLineComment>(C);
auto VL = new VerbatimBlockLineComment();
_Comment = VL;
VL->text = CK->getText().str();
break;
}
case Comment::NoCommentKind: return nullptr;
default:
llvm_unreachable("Unknown comment kind");
auto CK = cast<clang::comments::VerbatimBlockComment>(C);
auto VB = new VerbatimBlockComment();
_Comment = VB;
for (auto I = CK->child_begin(), E = CK->child_end(); I != E; ++I)
{
auto Line = ConvertCommentBlock(*I);
VB->Lines.push_back(static_cast<VerbatimBlockLineComment*>(Line));
}
break;
}
case Comment::VerbatimLineCommentKind:
{
auto CK = cast<clang::comments::VerbatimLineComment>(C);
auto VL = new VerbatimLineComment();
_Comment = VL;
VL->text = CK->getText().str();
break;
}
case Comment::ParagraphCommentKind:
{
auto CK = cast<clang::comments::ParagraphComment>(C);
auto PC = new ParagraphComment();
_Comment = PC;
for (auto I = CK->child_begin(), E = CK->child_end(); I != E; ++I)
{
auto Content = ConvertCommentBlock(*I);
PC->Content.push_back(static_cast<InlineContentComment*>(Content));
}
PC->isWhitespace = CK->isWhitespace();
break;
}
case Comment::HTMLStartTagCommentKind:
{
auto CK = cast<clang::comments::HTMLStartTagComment>(C);
auto TC = new HTMLStartTagComment();
_Comment = TC;
HandleInlineContent(CK, TC);
TC->tagName = CK->getTagName().str();
for (unsigned I = 0, E = CK->getNumAttrs(); I != E; ++I)
{
auto A = CK->getAttr(I);
auto Attr = HTMLStartTagComment::Attribute();
Attr.name = A.Name.str();
Attr.value = A.Value.str();
TC->Attributes.push_back(Attr);
}
break;
}
case Comment::HTMLEndTagCommentKind:
{
auto CK = cast<clang::comments::HTMLEndTagComment>(C);
auto TC = new HTMLEndTagComment();
_Comment = TC;
HandleInlineContent(CK, TC);
TC->tagName = CK->getTagName().str();
break;
}
case Comment::TextCommentKind:
{
auto CK = cast<clang::comments::TextComment>(C);
auto TC = new TextComment();
_Comment = TC;
HandleInlineContent(CK, TC);
TC->text = CK->getText().str();
break;
}
case Comment::InlineCommandCommentKind:
{
auto CK = cast<clang::comments::InlineCommandComment>(C);
auto IC = new InlineCommandComment();
_Comment = IC;
HandleInlineContent(CK, IC);
IC->commandId = CK->getCommandID();
IC->commentRenderKind = ConvertRenderKind(CK->getRenderKind());
for (unsigned I = 0, E = CK->getNumArgs(); I != E; ++I)
{
auto Arg = InlineCommandComment::Argument();
Arg.text = CK->getArgText(I).str();
IC->Arguments.push_back(Arg);
}
break;
}
case Comment::VerbatimBlockLineCommentKind:
{
auto CK = cast<clang::comments::VerbatimBlockLineComment>(C);
auto VL = new VerbatimBlockLineComment();
_Comment = VL;
VL->text = CK->getText().str();
break;
}
case Comment::NoCommentKind: return nullptr;
default:
llvm_unreachable("Unknown comment kind");
}
assert(_Comment && "Invalid comment instance");

119
src/CppParser/CppParser.cpp

@ -1,9 +1,9 @@ @@ -1,9 +1,9 @@
/************************************************************************
*
* CppSharp
* Licensed under the MIT license.
*
************************************************************************/
*
* CppSharp
* Licensed under the MIT license.
*
************************************************************************/
#include "CppParser.h"
#include "Parser.h"
@ -12,65 +12,70 @@ @@ -12,65 +12,70 @@
namespace CppSharp { namespace CppParser {
CppParserOptions::CppParserOptions()
: clangVersion(CLANG_VERSION_STRING)
{
}
CppParserOptions::~CppParserOptions() {}
std::string CppParserOptions::getClangVersion() { return clangVersion; }
DEF_VECTOR_STRING(CppParserOptions, Arguments)
DEF_VECTOR_STRING(CppParserOptions, CompilationOptions)
DEF_VECTOR_STRING(CppParserOptions, SourceFiles)
DEF_VECTOR_STRING(CppParserOptions, IncludeDirs)
DEF_VECTOR_STRING(CppParserOptions, SystemIncludeDirs)
DEF_VECTOR_STRING(CppParserOptions, Defines)
DEF_VECTOR_STRING(CppParserOptions, Undefines)
DEF_VECTOR_STRING(CppParserOptions, SupportedStdTypes)
DEF_VECTOR_STRING(CppParserOptions, SupportedFunctionTemplates)
ParserResult::ParserResult() {}
ParserResult::ParserResult(const ParserResult& rhs)
: kind(rhs.kind)
, Diagnostics(rhs.Diagnostics)
, Libraries(rhs.Libraries)
, targetInfo(rhs.targetInfo)
{}
ParserResult::~ParserResult()
{
for (auto Library : Libraries)
CppParserOptions::CppParserOptions()
: clangVersion(CLANG_VERSION_STRING)
{
delete Library;
}
}
DEF_VECTOR(ParserResult, ParserDiagnostic, Diagnostics)
DEF_VECTOR(ParserResult, AST::NativeLibrary*, Libraries)
CppParserOptions::~CppParserOptions() {}
CppLinkerOptions::CppLinkerOptions()
{
}
std::string CppParserOptions::getClangVersion()
{
return clangVersion;
}
DEF_VECTOR_STRING(CppParserOptions, Arguments)
DEF_VECTOR_STRING(CppParserOptions, CompilationOptions)
DEF_VECTOR_STRING(CppParserOptions, SourceFiles)
DEF_VECTOR_STRING(CppParserOptions, IncludeDirs)
DEF_VECTOR_STRING(CppParserOptions, SystemIncludeDirs)
DEF_VECTOR_STRING(CppParserOptions, Defines)
DEF_VECTOR_STRING(CppParserOptions, Undefines)
DEF_VECTOR_STRING(CppParserOptions, SupportedStdTypes)
DEF_VECTOR_STRING(CppParserOptions, SupportedFunctionTemplates)
ParserResult::ParserResult() {}
ParserResult::ParserResult(const ParserResult& rhs)
: kind(rhs.kind)
, Diagnostics(rhs.Diagnostics)
, Libraries(rhs.Libraries)
, targetInfo(rhs.targetInfo)
{
}
ParserResult::~ParserResult()
{
for (auto Library : Libraries)
{
delete Library;
}
}
DEF_VECTOR(ParserResult, ParserDiagnostic, Diagnostics)
DEF_VECTOR(ParserResult, AST::NativeLibrary*, Libraries)
CppLinkerOptions::~CppLinkerOptions() {}
CppLinkerOptions::CppLinkerOptions()
{
}
DEF_VECTOR_STRING(CppLinkerOptions, Arguments)
DEF_VECTOR_STRING(CppLinkerOptions, LibraryDirs)
DEF_VECTOR_STRING(CppLinkerOptions, Libraries)
CppLinkerOptions::~CppLinkerOptions() {}
ParserDiagnostic::ParserDiagnostic() {}
DEF_VECTOR_STRING(CppLinkerOptions, Arguments)
DEF_VECTOR_STRING(CppLinkerOptions, LibraryDirs)
DEF_VECTOR_STRING(CppLinkerOptions, Libraries)
ParserDiagnostic::ParserDiagnostic(const ParserDiagnostic& rhs)
: fileName(rhs.fileName)
, message(rhs.message)
, level(rhs.level)
, lineNumber(rhs.lineNumber)
, columnNumber(rhs.columnNumber)
{}
ParserDiagnostic::ParserDiagnostic() {}
ParserDiagnostic::ParserDiagnostic(const ParserDiagnostic& rhs)
: fileName(rhs.fileName)
, message(rhs.message)
, level(rhs.level)
, lineNumber(rhs.lineNumber)
, columnNumber(rhs.columnNumber)
{
}
ParserDiagnostic::~ParserDiagnostic() {}
ParserDiagnostic::~ParserDiagnostic() {}
} }
}} // namespace CppSharp::CppParser

240
src/CppParser/CppParser.h

@ -1,9 +1,9 @@ @@ -1,9 +1,9 @@
/************************************************************************
*
* CppSharp
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
*
* CppSharp
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
#pragma once
@ -16,116 +16,120 @@ @@ -16,116 +16,120 @@
namespace CppSharp { namespace CppParser {
struct CS_API CppParserOptions
{
CppParserOptions();
~CppParserOptions();
std::string getClangVersion();
VECTOR_STRING(Arguments)
VECTOR_STRING(CompilationOptions)
// C/C++ header file names.
VECTOR_STRING(SourceFiles)
// Include directories
VECTOR_STRING(IncludeDirs)
VECTOR_STRING(SystemIncludeDirs)
VECTOR_STRING(Defines)
VECTOR_STRING(Undefines)
VECTOR_STRING(SupportedStdTypes)
VECTOR_STRING(SupportedFunctionTemplates)
AST::ASTContext* ASTContext = nullptr;
int toolSetToUse = 0;
std::string targetTriple;
bool noStandardIncludes = false;
bool noBuiltinIncludes = false;
bool microsoftMode = false;
bool verbose = false;
bool unityBuild = false;
bool skipPrivateDeclarations = true;
bool skipLayoutInfo = false;
bool skipFunctionBodies = true;
private:
std::string clangVersion;
};
struct CS_API CppLinkerOptions
{
CppLinkerOptions();
~CppLinkerOptions();
VECTOR_STRING(Arguments)
VECTOR_STRING(LibraryDirs)
VECTOR_STRING(Libraries)
};
enum class ParserDiagnosticLevel
{
Ignored,
Note,
Warning,
Error,
Fatal
};
struct CS_API ParserDiagnostic
{
ParserDiagnostic();
ParserDiagnostic(const ParserDiagnostic&);
~ParserDiagnostic();
std::string fileName;
std::string message;
ParserDiagnosticLevel level { ParserDiagnosticLevel::Ignored };
int lineNumber {0};
int columnNumber {0};
};
enum class ParserResultKind
{
Success,
Error,
FileNotFound
};
class Parser;
struct CS_API ParserResult
{
ParserResult();
ParserResult(const ParserResult&);
~ParserResult();
ParserResultKind kind = ParserResultKind::Error;
VECTOR(ParserDiagnostic, Diagnostics)
VECTOR(AST::NativeLibrary*, Libraries)
ParserTargetInfo* targetInfo = nullptr;
};
enum class SourceLocationKind
{
Invalid,
Builtin,
CommandLine,
System,
User
};
class CS_API ClangParser
{
public:
static ParserResult* ParseHeader(CppParserOptions* Opts);
static ParserResult* ParseLibrary(CppLinkerOptions* Opts);
static ParserResult* Build(CppParserOptions* Opts,
const CppLinkerOptions* LinkerOptions, const std::string& File, bool Last);
static ParserResult* Compile(CppParserOptions* Opts, const std::string& File);
static ParserResult* Link(CppParserOptions* Opts,
const CppLinkerOptions* LinkerOptions, const std::string& File, bool Last);
};
} }
struct CS_API CppParserOptions
{
CppParserOptions();
~CppParserOptions();
std::string getClangVersion();
VECTOR_STRING(Arguments)
VECTOR_STRING(CompilationOptions)
// C/C++ header file names.
VECTOR_STRING(SourceFiles)
// Include directories
VECTOR_STRING(IncludeDirs)
VECTOR_STRING(SystemIncludeDirs)
VECTOR_STRING(Defines)
VECTOR_STRING(Undefines)
VECTOR_STRING(SupportedStdTypes)
VECTOR_STRING(SupportedFunctionTemplates)
AST::ASTContext* ASTContext = nullptr;
int toolSetToUse = 0;
std::string targetTriple;
bool noStandardIncludes = false;
bool noBuiltinIncludes = false;
bool microsoftMode = false;
bool verbose = false;
bool unityBuild = false;
bool skipPrivateDeclarations = true;
bool skipLayoutInfo = false;
bool skipFunctionBodies = true;
private:
std::string clangVersion;
};
struct CS_API CppLinkerOptions
{
CppLinkerOptions();
~CppLinkerOptions();
VECTOR_STRING(Arguments)
VECTOR_STRING(LibraryDirs)
VECTOR_STRING(Libraries)
};
enum class ParserDiagnosticLevel
{
Ignored,
Note,
Warning,
Error,
Fatal
};
struct CS_API ParserDiagnostic
{
ParserDiagnostic();
ParserDiagnostic(const ParserDiagnostic&);
~ParserDiagnostic();
std::string fileName;
std::string message;
ParserDiagnosticLevel level{ ParserDiagnosticLevel::Ignored };
int lineNumber{ 0 };
int columnNumber{ 0 };
};
enum class ParserResultKind
{
Success,
Error,
FileNotFound
};
class Parser;
struct CS_API ParserResult
{
ParserResult();
ParserResult(const ParserResult&);
~ParserResult();
ParserResultKind kind = ParserResultKind::Error;
VECTOR(ParserDiagnostic, Diagnostics)
VECTOR(AST::NativeLibrary*, Libraries)
ParserTargetInfo* targetInfo = nullptr;
};
enum class SourceLocationKind
{
Invalid,
Builtin,
CommandLine,
System,
User
};
class CS_API ClangParser
{
public:
static ParserResult* ParseHeader(CppParserOptions* Opts);
static ParserResult* ParseLibrary(CppLinkerOptions* Opts);
static ParserResult* Build(CppParserOptions* Opts,
const CppLinkerOptions* LinkerOptions,
const std::string& File,
bool Last);
static ParserResult* Compile(CppParserOptions* Opts, const std::string& File);
static ParserResult* Link(CppParserOptions* Opts,
const CppLinkerOptions* LinkerOptions,
const std::string& File,
bool Last);
};
}} // namespace CppSharp::CppParser

1658
src/CppParser/Decl.h

File diff suppressed because it is too large Load Diff

256
src/CppParser/ELFDumper.h

@ -1,9 +1,9 @@ @@ -1,9 +1,9 @@
/************************************************************************
*
* CppSharp
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
*
* CppSharp
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
#pragma once
@ -11,128 +11,146 @@ @@ -11,128 +11,146 @@
namespace CppSharp { namespace CppParser {
template<typename ELFT>
class ELFDumper {
public:
ELFDumper(const llvm::object::ELFFile<ELFT> *Obj);
std::vector<llvm::StringRef> getNeededLibraries() const;
private:
typedef llvm::object::ELFFile<ELFT> ELFO;
typedef typename ELFO::Elf_Sym Elf_Sym;
typedef typename ELFO::Elf_Dyn Elf_Dyn;
typedef typename ELFO::Elf_Dyn_Range Elf_Dyn_Range;
typedef typename ELFO::Elf_Phdr Elf_Phdr;
typedef typename ELFO::uintX_t uintX_t;
/// \brief Represents a region described by entries in the .dynamic table.
struct DynRegionInfo {
DynRegionInfo() : Addr(nullptr), Size(0), EntSize(0) {}
/// \brief Address in current address space.
const void *Addr;
/// \brief Size in bytes of the region.
uintX_t Size;
/// \brief Size of each entity in the region.
uintX_t EntSize;
template <typename ELFT>
class ELFDumper
{
public:
ELFDumper(const llvm::object::ELFFile<ELFT>* Obj);
std::vector<llvm::StringRef> getNeededLibraries() const;
private:
typedef llvm::object::ELFFile<ELFT> ELFO;
typedef typename ELFO::Elf_Sym Elf_Sym;
typedef typename ELFO::Elf_Dyn Elf_Dyn;
typedef typename ELFO::Elf_Dyn_Range Elf_Dyn_Range;
typedef typename ELFO::Elf_Phdr Elf_Phdr;
typedef typename ELFO::uintX_t uintX_t;
/// \brief Represents a region described by entries in the .dynamic table.
struct DynRegionInfo
{
DynRegionInfo()
: Addr(nullptr)
, Size(0)
, EntSize(0)
{
}
/// \brief Address in current address space.
const void* Addr;
/// \brief Size in bytes of the region.
uintX_t Size;
/// \brief Size of each entity in the region.
uintX_t EntSize;
};
llvm::StringRef getDynamicString(uint64_t Offset) const;
const Elf_Dyn* dynamic_table_begin() const;
const Elf_Dyn* dynamic_table_end() const;
llvm::iterator_range<const Elf_Dyn*> dynamic_table() const
{
return llvm::make_range(dynamic_table_begin(), dynamic_table_end());
}
const ELFO* Obj;
DynRegionInfo DynamicRegion;
llvm::StringRef DynamicStringTable;
};
llvm::StringRef getDynamicString(uint64_t Offset) const;
const Elf_Dyn *dynamic_table_begin() const;
const Elf_Dyn *dynamic_table_end() const;
llvm::iterator_range<const Elf_Dyn*> dynamic_table() const {
return llvm::make_range(dynamic_table_begin(), dynamic_table_end());
}
template <typename ELFT>
ELFDumper<ELFT>::ELFDumper(const llvm::object::ELFFile<ELFT>* Obj)
{
const ELFO *Obj;
DynRegionInfo DynamicRegion;
llvm::StringRef DynamicStringTable;
};
llvm::SmallVector<const Elf_Phdr*, 4> LoadSegments;
auto ProgramHeaders = Obj->program_headers();
if (ProgramHeaders.takeError())
{
llvm::report_fatal_error("Error reading program headers");
return;
}
for (const Elf_Phdr& Phdr : ProgramHeaders.get())
{
if (Phdr.p_type == llvm::ELF::PT_DYNAMIC)
{
DynamicRegion.Addr = Obj->base() + Phdr.p_offset;
uint64_t Size = Phdr.p_filesz;
if (Size % sizeof(Elf_Dyn))
llvm::report_fatal_error("Invalid dynamic table size");
DynamicRegion.Size = Phdr.p_filesz;
continue;
}
if (Phdr.p_type != llvm::ELF::PT_LOAD || Phdr.p_filesz == 0)
continue;
LoadSegments.push_back(&Phdr);
}
auto toMappedAddr = [&](uint64_t VAddr) -> const uint8_t*
{
const Elf_Phdr** I = std::upper_bound(
LoadSegments.begin(), LoadSegments.end(), VAddr,
[](uint64_t VAddr, const Elf_Phdr* Phdr)
{
return VAddr < Phdr->p_vaddr;
});
if (I == LoadSegments.begin())
llvm::report_fatal_error("Virtual address is not in any segment");
--I;
const Elf_Phdr& Phdr = **I;
uint64_t Delta = VAddr - Phdr.p_vaddr;
if (Delta >= Phdr.p_filesz)
llvm::report_fatal_error("Virtual address is not in any segment");
return Obj->base() + Phdr.p_offset + Delta;
};
const char* StringTableBegin = nullptr;
uint64_t StringTableSize = 0;
for (const Elf_Dyn& Dyn : dynamic_table())
{
switch (Dyn.d_tag)
{
case llvm::ELF::DT_STRTAB:
StringTableBegin = (const char*)toMappedAddr(Dyn.getPtr());
break;
case llvm::ELF::DT_STRSZ:
StringTableSize = Dyn.getVal();
break;
}
}
if (StringTableBegin)
DynamicStringTable = llvm::StringRef(StringTableBegin, StringTableSize);
}
template <typename ELFT>
ELFDumper<ELFT>::ELFDumper(const llvm::object::ELFFile<ELFT> *Obj) {
template <typename ELFT>
const typename ELFDumper<ELFT>::Elf_Dyn*
ELFDumper<ELFT>::dynamic_table_begin() const
{
return reinterpret_cast<const Elf_Dyn*>(DynamicRegion.Addr);
}
llvm::SmallVector<const Elf_Phdr *, 4> LoadSegments;
auto ProgramHeaders = Obj->program_headers();
if (ProgramHeaders.takeError())
template <typename ELFT>
const typename ELFDumper<ELFT>::Elf_Dyn*
ELFDumper<ELFT>::dynamic_table_end() const
{
llvm::report_fatal_error("Error reading program headers");
return;
uint64_t Size = DynamicRegion.Size;
return dynamic_table_begin() + Size / sizeof(Elf_Dyn);
}
for (const Elf_Phdr &Phdr : ProgramHeaders.get()) {
if (Phdr.p_type == llvm::ELF::PT_DYNAMIC) {
DynamicRegion.Addr = Obj->base() + Phdr.p_offset;
uint64_t Size = Phdr.p_filesz;
if (Size % sizeof(Elf_Dyn))
llvm::report_fatal_error("Invalid dynamic table size");
DynamicRegion.Size = Phdr.p_filesz;
continue;
}
if (Phdr.p_type != llvm::ELF::PT_LOAD || Phdr.p_filesz == 0)
continue;
LoadSegments.push_back(&Phdr);
template <class ELFT>
llvm::StringRef ELFDumper<ELFT>::getDynamicString(uint64_t Value) const
{
return llvm::StringRef(DynamicStringTable.data() + Value);
}
auto toMappedAddr = [&](uint64_t VAddr) -> const uint8_t *{
const Elf_Phdr **I = std::upper_bound(
LoadSegments.begin(), LoadSegments.end(), VAddr,
[](uint64_t VAddr, const Elf_Phdr *Phdr)
{
return VAddr < Phdr->p_vaddr;
});
if (I == LoadSegments.begin())
llvm::report_fatal_error("Virtual address is not in any segment");
--I;
const Elf_Phdr &Phdr = **I;
uint64_t Delta = VAddr - Phdr.p_vaddr;
if (Delta >= Phdr.p_filesz)
llvm::report_fatal_error("Virtual address is not in any segment");
return Obj->base() + Phdr.p_offset + Delta;
};
template <class ELFT>
std::vector<llvm::StringRef> ELFDumper<ELFT>::getNeededLibraries() const
{
std::vector<llvm::StringRef> Libs;
const char *StringTableBegin = nullptr;
uint64_t StringTableSize = 0;
for (const Elf_Dyn &Dyn : dynamic_table()) {
switch (Dyn.d_tag) {
case llvm::ELF::DT_STRTAB:
StringTableBegin = (const char *)toMappedAddr(Dyn.getPtr());
break;
case llvm::ELF::DT_STRSZ:
StringTableSize = Dyn.getVal();
break;
}
for (const auto& Entry : dynamic_table())
if (Entry.d_tag == llvm::ELF::DT_NEEDED)
Libs.push_back(getDynamicString(Entry.d_un.d_val));
return Libs;
}
if (StringTableBegin)
DynamicStringTable = llvm::StringRef(StringTableBegin, StringTableSize);
}
template <typename ELFT>
const typename ELFDumper<ELFT>::Elf_Dyn *
ELFDumper<ELFT>::dynamic_table_begin() const {
return reinterpret_cast<const Elf_Dyn *>(DynamicRegion.Addr);
}
template <typename ELFT>
const typename ELFDumper<ELFT>::Elf_Dyn *
ELFDumper<ELFT>::dynamic_table_end() const {
uint64_t Size = DynamicRegion.Size;
return dynamic_table_begin() + Size / sizeof(Elf_Dyn);
}
template <class ELFT>
llvm::StringRef ELFDumper<ELFT>::getDynamicString(uint64_t Value) const {
return llvm::StringRef(DynamicStringTable.data() + Value);
}
template<class ELFT>
std::vector<llvm::StringRef> ELFDumper<ELFT>::getNeededLibraries() const {
std::vector<llvm::StringRef> Libs;
for (const auto &Entry : dynamic_table())
if (Entry.d_tag == llvm::ELF::DT_NEEDED)
Libs.push_back(getDynamicString(Entry.d_un.d_val));
return Libs;
}
} }
}} // namespace CppSharp::CppParser

78
src/CppParser/Helpers.h

@ -1,9 +1,9 @@ @@ -1,9 +1,9 @@
/************************************************************************
*
* CppSharp
* Licensed under the simplified BSD license.
*
************************************************************************/
*
* CppSharp
* Licensed under the simplified BSD license.
*
************************************************************************/
#pragma once
@ -18,7 +18,7 @@ @@ -18,7 +18,7 @@
#if defined(_MSC_VER) && !defined(__clang__)
#define CS_API __declspec(dllexport)
#else
#define CS_API
#define CS_API
#endif
#define CS_ABSTRACT
@ -28,28 +28,52 @@ @@ -28,28 +28,52 @@
/** We use these macros to workaround the lack of good standard C++
* containers/string support in the C# binding backend. */
#define VECTOR(type, name) \
std::vector<type> name; \
type get##name (unsigned i); \
void add##name (type& s); \
unsigned get##name##Count (); \
#define VECTOR(type, name) \
std::vector<type> name; \
type get##name(unsigned i); \
void add##name(type& s); \
unsigned get##name##Count(); \
void clear##name();
#define DEF_VECTOR(klass, type, name) \
type klass::get##name (unsigned i) { return name[i]; } \
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) \
std::vector<std::string> name; \
const char* get##name (unsigned i); \
void add##name (const char* s); \
unsigned get##name##Count (); \
#define DEF_VECTOR(klass, type, name) \
type klass::get##name(unsigned i) \
{ \
return name[i]; \
} \
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) \
std::vector<std::string> name; \
const char* get##name(unsigned i); \
void add##name(const char* s); \
unsigned get##name##Count(); \
void clear##name();
#define DEF_VECTOR_STRING(klass, name) \
const char* klass::get##name (unsigned i) { return name[i].c_str(); } \
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(); }
#define DEF_VECTOR_STRING(klass, name) \
const char* klass::get##name(unsigned i) \
{ \
return name[i].c_str(); \
} \
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(); \
}

68
src/CppParser/Link.cpp

@ -1,9 +1,9 @@ @@ -1,9 +1,9 @@
/************************************************************************
*
* CppSharp
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
*
* CppSharp
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
#include "CppParser.h"
#include "Parser.h"
@ -27,36 +27,38 @@ bool Parser::Link(const std::string& File, const CppLinkerOptions* LinkerOptions @@ -27,36 +27,38 @@ bool Parser::Link(const std::string& File, const CppLinkerOptions* LinkerOptions
const llvm::Triple Triple = c->getTarget().getTriple();
switch (Triple.getOS())
{
case llvm::Triple::OSType::Win32:
args.push_back("-subsystem:windows");
switch (Triple.getEnvironment())
{
case llvm::Triple::EnvironmentType::MSVC:
return LinkWindows(LinkerOptions, args, Dir, Stem);
case llvm::Triple::OSType::Win32:
args.push_back("-subsystem:windows");
switch (Triple.getEnvironment())
{
case llvm::Triple::EnvironmentType::MSVC:
return LinkWindows(LinkerOptions, args, Dir, Stem);
case llvm::Triple::EnvironmentType::GNU:
return LinkWindows(LinkerOptions, args, Dir, Stem, true);
case llvm::Triple::EnvironmentType::GNU:
return LinkWindows(LinkerOptions, args, Dir, Stem, true);
default:
throw std::invalid_argument("Target triple environment");
}
break;
default:
throw std::invalid_argument("Target triple environment");
}
break;
case llvm::Triple::OSType::Linux:
return LinkELF(LinkerOptions, args, Dir, Stem);
case llvm::Triple::OSType::Linux:
return LinkELF(LinkerOptions, args, Dir, Stem);
case llvm::Triple::OSType::Darwin:
case llvm::Triple::OSType::MacOSX:
return LinkMachO(LinkerOptions, args, Dir, Stem);
case llvm::Triple::OSType::Darwin:
case llvm::Triple::OSType::MacOSX:
return LinkMachO(LinkerOptions, args, Dir, Stem);
default:
throw std::invalid_argument("Target triple operating system");
default:
throw std::invalid_argument("Target triple operating system");
}
}
bool Parser::LinkWindows(const CppLinkerOptions* LinkerOptions,
std::vector<const char*>& args,
const llvm::StringRef& Dir, llvm::StringRef& Stem, bool MinGW)
std::vector<const char*>& args,
const llvm::StringRef& Dir,
llvm::StringRef& Stem,
bool MinGW)
{
#ifdef _WIN32
using namespace llvm;
@ -74,7 +76,7 @@ bool Parser::LinkWindows(const CppLinkerOptions* LinkerOptions, @@ -74,7 +76,7 @@ bool Parser::LinkWindows(const CppLinkerOptions* LinkerOptions,
std::vector<std::string> LibraryPaths;
LibraryPaths.push_back("-libpath:" + TC.getSubDirectoryPath(
llvm::SubDirectoryType::Lib));
llvm::SubDirectoryType::Lib));
std::string CRTPath;
if (TC.getUniversalCRTLibraryPath(Args, CRTPath))
LibraryPaths.push_back("-libpath:" + CRTPath);
@ -112,8 +114,9 @@ bool Parser::LinkWindows(const CppLinkerOptions* LinkerOptions, @@ -112,8 +114,9 @@ bool Parser::LinkWindows(const CppLinkerOptions* LinkerOptions,
}
bool Parser::LinkELF(const CppLinkerOptions* LinkerOptions,
std::vector<const char*>& args,
llvm::StringRef& Dir, llvm::StringRef& Stem)
std::vector<const char*>& args,
llvm::StringRef& Dir,
llvm::StringRef& Stem)
{
#ifdef __linux__
using namespace llvm;
@ -153,8 +156,9 @@ bool Parser::LinkELF(const CppLinkerOptions* LinkerOptions, @@ -153,8 +156,9 @@ bool Parser::LinkELF(const CppLinkerOptions* LinkerOptions,
}
bool Parser::LinkMachO(const CppLinkerOptions* LinkerOptions,
std::vector<const char*>& args,
llvm::StringRef& Dir, llvm::StringRef& Stem)
std::vector<const char*>& args,
llvm::StringRef& Dir,
llvm::StringRef& Stem)
{
#ifdef __APPLE__
using namespace llvm;
@ -187,7 +191,7 @@ bool Parser::LinkMachO(const CppLinkerOptions* LinkerOptions, @@ -187,7 +191,7 @@ bool Parser::LinkMachO(const CppLinkerOptions* LinkerOptions,
std::string Out(Output);
args.push_back(Out.data());
return lld::macho::link(args, outs(), errs(), /*exitEarly=*/false, /*disableOutput=*/false);
return lld::macho::link(args, outs(), errs(), /*exitEarly=*/false, /*disableOutput=*/false);
#else
return false;
#endif

3189
src/CppParser/Parser.cpp

File diff suppressed because it is too large Load Diff

328
src/CppParser/Parser.h

@ -1,9 +1,9 @@ @@ -1,9 +1,9 @@
/************************************************************************
*
* CppSharp
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
*
* CppSharp
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
#pragma once
@ -29,171 +29,169 @@ @@ -29,171 +29,169 @@
#include <unordered_set>
namespace clang {
namespace CodeGen {
namespace CodeGen {
class CodeGenTypes;
}
struct ASTTemplateArgumentListInfo;
class FunctionTemplateSpecialization;
class FunctionTemplateSpecializationInfo;
class PreprocessingRecord;
class PreprocessedEntity;
class RawComment;
class TemplateSpecializationTypeLoc;
class TemplateArgumentList;
class VTableLayout;
class VTableComponent;
}
struct ASTTemplateArgumentListInfo;
class FunctionTemplateSpecialization;
class FunctionTemplateSpecializationInfo;
class PreprocessingRecord;
class PreprocessedEntity;
class RawComment;
class TemplateSpecializationTypeLoc;
class TemplateArgumentList;
class VTableLayout;
class VTableComponent;
} // namespace clang
#define Debug printf
namespace CppSharp { namespace CppParser {
class ASTNameMangler;
class Parser
{
friend class ASTNodeVisitor;
public:
Parser(CppParserOptions* Opts);
void Setup(bool Compile = false);
ParserResult* Parse(const std::vector<std::string>& SourceFiles);
static ParserResult* ParseLibrary(const CppLinkerOptions* Opts);
ParserResult* Build(const CppLinkerOptions* LinkerOptions, const std::string& File, bool Last);
ParserResult* Compile(const std::string& File);
bool Link(const std::string& File, const CppLinkerOptions* LinkerOptions);
void WalkAST(clang::TranslationUnitDecl* TU);
void HandleDeclaration(const clang::Decl* D, AST::Declaration* Decl);
CppParserOptions* opts = nullptr;
private:
void SetupLLVMCodegen();
bool SetupSourceFiles(const std::vector<std::string>& SourceFiles,
std::vector<const clang::FileEntry*>& FileEntries);
bool IsSupported(const clang::NamedDecl* ND);
bool IsSupported(const clang::CXXMethodDecl* MD);
// AST traversers
AST::Declaration* WalkDeclaration(const clang::Decl* D);
AST::Declaration* WalkDeclarationDef(clang::Decl* D);
AST::Enumeration* WalkEnum(const clang::EnumDecl* ED);
AST::Enumeration::Item* WalkEnumItem(clang::EnumConstantDecl* ECD);
AST::Function* WalkFunction(const clang::FunctionDecl* FD);
void EnsureCompleteRecord(const clang::RecordDecl* Record, AST::DeclarationContext* NS, AST::Class* RC);
AST::Class* GetRecord(const clang::RecordDecl* Record, bool& IsComplete);
AST::Class* WalkRecord(const clang::RecordDecl* Record);
void WalkRecord(const clang::RecordDecl* Record, AST::Class* RC);
AST::Class* WalkRecordCXX(const clang::CXXRecordDecl* Record);
void WalkRecordCXX(const clang::CXXRecordDecl* Record, AST::Class* RC);
AST::ClassTemplateSpecialization*
WalkClassTemplateSpecialization(const clang::ClassTemplateSpecializationDecl* CTS);
AST::ClassTemplatePartialSpecialization*
WalkClassTemplatePartialSpecialization(const clang::ClassTemplatePartialSpecializationDecl* CTS);
AST::Method* WalkMethodCXX(const clang::CXXMethodDecl* MD);
AST::Field* WalkFieldCXX(const clang::FieldDecl* FD, AST::Class* Class);
AST::FunctionTemplateSpecialization* WalkFunctionTemplateSpec(clang::FunctionTemplateSpecializationInfo* FTS, AST::Function* Function);
AST::Variable* WalkVariable(const clang::VarDecl* VD);
void WalkVariable(const clang::VarDecl* VD, AST::Variable* Var);
AST::Friend* WalkFriend(const clang::FriendDecl* FD);
AST::RawComment* WalkRawComment(const clang::RawComment* RC);
AST::Type* WalkType(clang::QualType QualType, const clang::TypeLoc* TL = 0,
bool DesugarType = false);
AST::TemplateArgument WalkTemplateArgument(const clang::TemplateArgument& TA, clang::TemplateArgumentLoc* ArgLoc = 0);
AST::TemplateTemplateParameter* WalkTemplateTemplateParameter(const clang::TemplateTemplateParmDecl* TTP);
AST::TypeTemplateParameter* WalkTypeTemplateParameter(const clang::TemplateTypeParmDecl* TTPD);
AST::NonTypeTemplateParameter* WalkNonTypeTemplateParameter(const clang::NonTypeTemplateParmDecl* TTPD);
AST::UnresolvedUsingTypename* WalkUnresolvedUsingTypename(const clang::UnresolvedUsingTypenameDecl* UUTD);
std::vector<AST::Declaration*> WalkTemplateParameterList(const clang::TemplateParameterList* TPL);
AST::TypeAliasTemplate* WalkTypeAliasTemplate(const clang::TypeAliasTemplateDecl* TD);
AST::ClassTemplate* WalkClassTemplate(const clang::ClassTemplateDecl* TD);
AST::FunctionTemplate* WalkFunctionTemplate(const clang::FunctionTemplateDecl* TD);
AST::VarTemplate* WalkVarTemplate(const clang::VarTemplateDecl* VT);
AST::VarTemplateSpecialization*
WalkVarTemplateSpecialization(const clang::VarTemplateSpecializationDecl* VTS);
AST::VarTemplatePartialSpecialization*
WalkVarTemplatePartialSpecialization(const clang::VarTemplatePartialSpecializationDecl* VTS);
template<typename TypeLoc>
std::vector<AST::TemplateArgument> WalkTemplateArgumentList(const clang::TemplateArgumentList* TAL, TypeLoc* TSTL);
std::vector<AST::TemplateArgument> WalkTemplateArgumentList(const clang::TemplateArgumentList* TAL, const clang::ASTTemplateArgumentListInfo* TSTL);
void WalkVTable(const clang::CXXRecordDecl* RD, AST::Class* C);
AST::QualifiedType GetQualifiedType(clang::QualType qual, const clang::TypeLoc* TL = 0);
void ReadClassLayout(AST::Class* Class, const clang::RecordDecl* RD, clang::CharUnits Offset, bool IncludeVirtualBases);
AST::LayoutField WalkVTablePointer(AST::Class* Class, const clang::CharUnits& Offset, const std::string& prefix);
AST::VTableLayout WalkVTableLayout(const clang::VTableLayout& VTLayout);
AST::VTableComponent WalkVTableComponent(const clang::VTableComponent& Component);
AST::PreprocessedEntity* WalkPreprocessedEntity(AST::Declaration* Decl,
clang::PreprocessedEntity* PPEntity);
AST::ExpressionObsolete* WalkVariableInitializerExpression(const clang::Expr* Expression);
AST::ExpressionObsolete* WalkExpressionObsolete(const clang::Expr* Expression);
AST::Stmt* WalkStatement(const clang::Stmt* Stmt);
AST::Expr* WalkExpression(const clang::Expr* Stmt);
std::string GetStringFromStatement(const clang::Stmt* Statement);
std::string GetFunctionBody(const clang::FunctionDecl* FD);
static bool IsCastStmt(clang::Stmt::StmtClass stmt);
static bool IsLiteralStmt(clang::Stmt::StmtClass stmt);
// Clang helpers
SourceLocationKind GetLocationKind(const clang::SourceLocation& Loc);
bool IsValidDeclaration(const clang::SourceLocation& Loc);
std::string GetDeclMangledName(const clang::Decl* D) const;
std::string GetTypeName(const clang::Type* Type) const;
bool CanCheckCodeGenInfo(const clang::Type* Ty);
void CompleteIfSpecializationType(const clang::QualType& QualType);
AST::Parameter* WalkParameter(const clang::ParmVarDecl* PVD,
const clang::SourceLocation& ParamStartLoc);
void SetBody(const clang::FunctionDecl* FD, AST::Function* F);
void MarkValidity(AST::Function* F);
void WalkFunction(const clang::FunctionDecl* FD, AST::Function* F);
int GetAlignAs(const clang::AlignedAttr* alignedAttr);
void HandlePreprocessedEntities(AST::Declaration* Decl);
void HandlePreprocessedEntities(AST::Declaration* Decl, clang::SourceRange sourceRange,
AST::MacroLocation macroLocation = AST::MacroLocation::Unknown);
bool GetDeclText(clang::SourceRange SR, std::string& Text);
bool HasLayout(const clang::RecordDecl* Record);
AST::TranslationUnit* GetTranslationUnit(clang::SourceLocation Loc,
SourceLocationKind *Kind = 0);
AST::TranslationUnit* GetTranslationUnit(const clang::Decl* D);
AST::DeclarationContext* GetNamespace(const clang::Decl* D, const clang::DeclContext* Ctx);
AST::DeclarationContext* GetNamespace(const clang::Decl* D);
void HandleOriginalText(const clang::Decl* D, AST::Declaration* Decl);
void HandleComments(const clang::Decl* D, AST::Declaration* Decl);
void HandleDiagnostics(ParserResult* res);
ParserResultKind ReadSymbols(llvm::StringRef File,
llvm::object::basic_symbol_iterator Begin,
llvm::object::basic_symbol_iterator End,
AST::NativeLibrary*& NativeLib);
AST::Declaration* GetDeclarationFromFriend(clang::NamedDecl* FriendDecl);
static ParserResultKind ParseArchive(const std::string& File,
llvm::object::Archive* Archive, std::vector<AST::NativeLibrary*>& NativeLibs);
static ParserResultKind ParseSharedLib(const std::string& File,
llvm::object::ObjectFile* ObjectFile, std::vector<AST::NativeLibrary*>& NativeLibs);
ParserTargetInfo* GetTargetInfo();
bool LinkWindows(const CppLinkerOptions* LinkerOptions, std::vector<const char*>& args,
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 LinkMachO(const CppLinkerOptions* LinkerOptions, std::vector<const char*>& args,
llvm::StringRef& Dir, llvm::StringRef& Stem);
int index = 0;
std::unique_ptr<clang::CompilerInstance> c;
llvm::LLVMContext LLVMCtx;
std::unique_ptr<ASTNameMangler> NameMangler;
std::unique_ptr<llvm::Module> LLVMModule;
std::unique_ptr<clang::CodeGen::CodeGenModule> CGM;
std::unique_ptr<clang::CodeGen::CodeGenTypes> codeGenTypes;
std::unordered_map<const clang::DeclContext*, AST::DeclarationContext*> walkedNamespaces;
std::unordered_map<const clang::TemplateTypeParmDecl*, AST::TypeTemplateParameter*> walkedTypeTemplateParameters;
std::unordered_map<const clang::TemplateTemplateParmDecl*, AST::TemplateTemplateParameter*> walkedTemplateTemplateParameters;
std::unordered_map<const clang::NonTypeTemplateParmDecl*, AST::NonTypeTemplateParameter*> walkedNonTypeTemplateParameters;
std::unordered_map<const clang::ParmVarDecl*, AST::Parameter*> walkedParameters;
std::unordered_set<std::string> supportedStdTypes;
std::unordered_set<std::string> supportedFunctionTemplates;
};
} }
class Parser
{
friend class ASTNodeVisitor;
public:
Parser(CppParserOptions* Opts);
void Setup(bool Compile = false);
ParserResult* Parse(const std::vector<std::string>& SourceFiles);
static ParserResult* ParseLibrary(const CppLinkerOptions* Opts);
ParserResult* Build(const CppLinkerOptions* LinkerOptions, const std::string& File, bool Last);
ParserResult* Compile(const std::string& File);
bool Link(const std::string& File, const CppLinkerOptions* LinkerOptions);
void WalkAST(clang::TranslationUnitDecl* TU);
void HandleDeclaration(const clang::Decl* D, AST::Declaration* Decl);
CppParserOptions* opts = nullptr;
private:
void SetupLLVMCodegen();
bool SetupSourceFiles(const std::vector<std::string>& SourceFiles,
std::vector<const clang::FileEntry*>& FileEntries);
bool IsSupported(const clang::NamedDecl* ND);
bool IsSupported(const clang::CXXMethodDecl* MD);
// AST traversers
AST::Declaration* WalkDeclaration(const clang::Decl* D);
AST::Declaration* WalkDeclarationDef(clang::Decl* D);
AST::Enumeration* WalkEnum(const clang::EnumDecl* ED);
AST::Enumeration::Item* WalkEnumItem(clang::EnumConstantDecl* ECD);
AST::Function* WalkFunction(const clang::FunctionDecl* FD);
void EnsureCompleteRecord(const clang::RecordDecl* Record, AST::DeclarationContext* NS, AST::Class* RC);
AST::Class* GetRecord(const clang::RecordDecl* Record, bool& IsComplete);
AST::Class* WalkRecord(const clang::RecordDecl* Record);
void WalkRecord(const clang::RecordDecl* Record, AST::Class* RC);
AST::Class* WalkRecordCXX(const clang::CXXRecordDecl* Record);
void WalkRecordCXX(const clang::CXXRecordDecl* Record, AST::Class* RC);
AST::ClassTemplateSpecialization*
WalkClassTemplateSpecialization(const clang::ClassTemplateSpecializationDecl* CTS);
AST::ClassTemplatePartialSpecialization*
WalkClassTemplatePartialSpecialization(const clang::ClassTemplatePartialSpecializationDecl* CTS);
AST::Method* WalkMethodCXX(const clang::CXXMethodDecl* MD);
AST::Field* WalkFieldCXX(const clang::FieldDecl* FD, AST::Class* Class);
AST::FunctionTemplateSpecialization* WalkFunctionTemplateSpec(clang::FunctionTemplateSpecializationInfo* FTS, AST::Function* Function);
AST::Variable* WalkVariable(const clang::VarDecl* VD);
void WalkVariable(const clang::VarDecl* VD, AST::Variable* Var);
AST::Friend* WalkFriend(const clang::FriendDecl* FD);
AST::RawComment* WalkRawComment(const clang::RawComment* RC);
AST::Type* WalkType(clang::QualType QualType, const clang::TypeLoc* TL = 0, bool DesugarType = false);
AST::TemplateArgument WalkTemplateArgument(const clang::TemplateArgument& TA, clang::TemplateArgumentLoc* ArgLoc = 0);
AST::TemplateTemplateParameter* WalkTemplateTemplateParameter(const clang::TemplateTemplateParmDecl* TTP);
AST::TypeTemplateParameter* WalkTypeTemplateParameter(const clang::TemplateTypeParmDecl* TTPD);
AST::NonTypeTemplateParameter* WalkNonTypeTemplateParameter(const clang::NonTypeTemplateParmDecl* TTPD);
AST::UnresolvedUsingTypename* WalkUnresolvedUsingTypename(const clang::UnresolvedUsingTypenameDecl* UUTD);
std::vector<AST::Declaration*> WalkTemplateParameterList(const clang::TemplateParameterList* TPL);
AST::TypeAliasTemplate* WalkTypeAliasTemplate(const clang::TypeAliasTemplateDecl* TD);
AST::ClassTemplate* WalkClassTemplate(const clang::ClassTemplateDecl* TD);
AST::FunctionTemplate* WalkFunctionTemplate(const clang::FunctionTemplateDecl* TD);
AST::VarTemplate* WalkVarTemplate(const clang::VarTemplateDecl* VT);
AST::VarTemplateSpecialization*
WalkVarTemplateSpecialization(const clang::VarTemplateSpecializationDecl* VTS);
AST::VarTemplatePartialSpecialization*
WalkVarTemplatePartialSpecialization(const clang::VarTemplatePartialSpecializationDecl* VTS);
template <typename TypeLoc>
std::vector<AST::TemplateArgument> WalkTemplateArgumentList(const clang::TemplateArgumentList* TAL, TypeLoc* TSTL);
std::vector<AST::TemplateArgument> WalkTemplateArgumentList(const clang::TemplateArgumentList* TAL, const clang::ASTTemplateArgumentListInfo* TSTL);
void WalkVTable(const clang::CXXRecordDecl* RD, AST::Class* C);
AST::QualifiedType GetQualifiedType(clang::QualType qual, const clang::TypeLoc* TL = 0);
void ReadClassLayout(AST::Class* Class, const clang::RecordDecl* RD, clang::CharUnits Offset, bool IncludeVirtualBases);
AST::LayoutField WalkVTablePointer(AST::Class* Class, const clang::CharUnits& Offset, const std::string& prefix);
AST::VTableLayout WalkVTableLayout(const clang::VTableLayout& VTLayout);
AST::VTableComponent WalkVTableComponent(const clang::VTableComponent& Component);
AST::PreprocessedEntity* WalkPreprocessedEntity(AST::Declaration* Decl,
clang::PreprocessedEntity* PPEntity);
AST::ExpressionObsolete* WalkVariableInitializerExpression(const clang::Expr* Expression);
AST::ExpressionObsolete* WalkExpressionObsolete(const clang::Expr* Expression);
AST::Stmt* WalkStatement(const clang::Stmt* Stmt);
AST::Expr* WalkExpression(const clang::Expr* Stmt);
std::string GetStringFromStatement(const clang::Stmt* Statement);
std::string GetFunctionBody(const clang::FunctionDecl* FD);
static bool IsCastStmt(clang::Stmt::StmtClass stmt);
static bool IsLiteralStmt(clang::Stmt::StmtClass stmt);
// Clang helpers
SourceLocationKind GetLocationKind(const clang::SourceLocation& Loc);
bool IsValidDeclaration(const clang::SourceLocation& Loc);
std::string GetDeclMangledName(const clang::Decl* D) const;
std::string GetTypeName(const clang::Type* Type) const;
bool CanCheckCodeGenInfo(const clang::Type* Ty);
void CompleteIfSpecializationType(const clang::QualType& QualType);
AST::Parameter* WalkParameter(const clang::ParmVarDecl* PVD,
const clang::SourceLocation& ParamStartLoc);
void SetBody(const clang::FunctionDecl* FD, AST::Function* F);
void MarkValidity(AST::Function* F);
void WalkFunction(const clang::FunctionDecl* FD, AST::Function* F);
int GetAlignAs(const clang::AlignedAttr* alignedAttr);
void HandlePreprocessedEntities(AST::Declaration* Decl);
void HandlePreprocessedEntities(AST::Declaration* Decl, clang::SourceRange sourceRange, AST::MacroLocation macroLocation = AST::MacroLocation::Unknown);
bool GetDeclText(clang::SourceRange SR, std::string& Text);
bool HasLayout(const clang::RecordDecl* Record);
AST::TranslationUnit* GetTranslationUnit(clang::SourceLocation Loc,
SourceLocationKind* Kind = 0);
AST::TranslationUnit* GetTranslationUnit(const clang::Decl* D);
AST::DeclarationContext* GetNamespace(const clang::Decl* D, const clang::DeclContext* Ctx);
AST::DeclarationContext* GetNamespace(const clang::Decl* D);
void HandleOriginalText(const clang::Decl* D, AST::Declaration* Decl);
void HandleComments(const clang::Decl* D, AST::Declaration* Decl);
void HandleDiagnostics(ParserResult* res);
ParserResultKind ReadSymbols(llvm::StringRef File,
llvm::object::basic_symbol_iterator Begin,
llvm::object::basic_symbol_iterator End,
AST::NativeLibrary*& NativeLib);
AST::Declaration* GetDeclarationFromFriend(clang::NamedDecl* FriendDecl);
static ParserResultKind ParseArchive(const std::string& File,
llvm::object::Archive* Archive,
std::vector<AST::NativeLibrary*>& NativeLibs);
static ParserResultKind ParseSharedLib(const std::string& File,
llvm::object::ObjectFile* ObjectFile,
std::vector<AST::NativeLibrary*>& NativeLibs);
ParserTargetInfo* GetTargetInfo();
bool LinkWindows(const CppLinkerOptions* LinkerOptions, std::vector<const char*>& args, 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 LinkMachO(const CppLinkerOptions* LinkerOptions, std::vector<const char*>& args, llvm::StringRef& Dir, llvm::StringRef& Stem);
int index = 0;
std::unique_ptr<clang::CompilerInstance> c;
llvm::LLVMContext LLVMCtx;
std::unique_ptr<ASTNameMangler> NameMangler;
std::unique_ptr<llvm::Module> LLVMModule;
std::unique_ptr<clang::CodeGen::CodeGenModule> CGM;
std::unique_ptr<clang::CodeGen::CodeGenTypes> codeGenTypes;
std::unordered_map<const clang::DeclContext*, AST::DeclarationContext*> walkedNamespaces;
std::unordered_map<const clang::TemplateTypeParmDecl*, AST::TypeTemplateParameter*> walkedTypeTemplateParameters;
std::unordered_map<const clang::TemplateTemplateParmDecl*, AST::TemplateTemplateParameter*> walkedTemplateTemplateParameters;
std::unordered_map<const clang::NonTypeTemplateParmDecl*, AST::NonTypeTemplateParameter*> walkedNonTypeTemplateParameters;
std::unordered_map<const clang::ParmVarDecl*, AST::Parameter*> walkedParameters;
std::unordered_set<std::string> supportedStdTypes;
std::unordered_set<std::string> supportedFunctionTemplates;
};
}} // namespace CppSharp::CppParser

18
src/CppParser/Sources.cpp

@ -2,14 +2,14 @@ @@ -2,14 +2,14 @@
namespace CppSharp { namespace CppParser {
SourceLocation::SourceLocation()
: ID(0)
{
}
SourceLocation::SourceLocation()
: ID(0)
{
}
SourceLocation::SourceLocation(unsigned ID)
: ID(ID)
{
}
SourceLocation::SourceLocation(unsigned ID)
: ID(ID)
{
}
} }
}} // namespace CppSharp::CppParser

34
src/CppParser/Sources.h

@ -1,9 +1,9 @@ @@ -1,9 +1,9 @@
/************************************************************************
*
* CppSharp
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
*
* CppSharp
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
#pragma once
@ -11,17 +11,17 @@ @@ -11,17 +11,17 @@
namespace CppSharp { namespace CppParser {
struct CS_API CS_VALUE_TYPE SourceLocation
{
SourceLocation();
SourceLocation(unsigned ID);
unsigned ID;
};
struct CS_API CS_VALUE_TYPE SourceLocation
{
SourceLocation();
SourceLocation(unsigned ID);
unsigned ID;
};
struct CS_API SourceRange
{
SourceLocation beginLoc;
SourceLocation endLoc;
};
struct CS_API SourceRange
{
SourceLocation beginLoc;
SourceLocation endLoc;
};
} }
}} // namespace CppSharp::CppParser

82
src/CppParser/Target.cpp

@ -1,49 +1,49 @@ @@ -1,49 +1,49 @@
/************************************************************************
*
* CppSharp
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
*
* CppSharp
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
#include "Target.h"
namespace CppSharp { namespace CppParser {
ParserTargetInfo::ParserTargetInfo() :
boolAlign(0),
boolWidth(0),
charAlign(0),
charWidth(0),
char16Align(0),
char16Width(0),
char32Align(0),
char32Width(0),
halfAlign(0),
halfWidth(0),
floatAlign(0),
floatWidth(0),
doubleAlign(0),
doubleWidth(0),
shortAlign(0),
shortWidth(0),
intAlign(0),
intWidth(0),
intMaxTWidth(0),
longAlign(0),
longWidth(0),
longDoubleAlign(0),
longDoubleWidth(0),
longLongAlign(0),
longLongWidth(0),
pointerAlign(0),
pointerWidth(0),
wCharAlign(0),
wCharWidth(0),
float128Align(0),
float128Width(0)
{
}
ParserTargetInfo::ParserTargetInfo()
: boolAlign(0)
, boolWidth(0)
, charAlign(0)
, charWidth(0)
, char16Align(0)
, char16Width(0)
, char32Align(0)
, char32Width(0)
, halfAlign(0)
, halfWidth(0)
, floatAlign(0)
, floatWidth(0)
, doubleAlign(0)
, doubleWidth(0)
, shortAlign(0)
, shortWidth(0)
, intAlign(0)
, intWidth(0)
, intMaxTWidth(0)
, longAlign(0)
, longWidth(0)
, longDoubleAlign(0)
, longDoubleWidth(0)
, longLongAlign(0)
, longLongWidth(0)
, pointerAlign(0)
, pointerWidth(0)
, wCharAlign(0)
, wCharWidth(0)
, float128Align(0)
, float128Width(0)
{
}
ParserTargetInfo::~ParserTargetInfo() {}
ParserTargetInfo::~ParserTargetInfo() {}
} }
}} // namespace CppSharp::CppParser

132
src/CppParser/Target.h

@ -1,9 +1,9 @@ @@ -1,9 +1,9 @@
/************************************************************************
*
* CppSharp
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
*
* CppSharp
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
#pragma once
@ -11,68 +11,68 @@ @@ -11,68 +11,68 @@
namespace CppSharp { namespace CppParser {
enum class ParserIntType
{
NoInt = 0,
SignedChar,
UnsignedChar,
SignedShort,
UnsignedShort,
SignedInt,
UnsignedInt,
SignedLong,
UnsignedLong,
SignedLongLong,
UnsignedLongLong
};
enum class ParserIntType
{
NoInt = 0,
SignedChar,
UnsignedChar,
SignedShort,
UnsignedShort,
SignedInt,
UnsignedInt,
SignedLong,
UnsignedLong,
SignedLongLong,
UnsignedLongLong
};
struct CS_API ParserTargetInfo
{
ParserTargetInfo();
~ParserTargetInfo();
std::string ABI;
struct CS_API ParserTargetInfo
{
ParserTargetInfo();
~ParserTargetInfo();
std::string ABI;
ParserIntType char16Type;
ParserIntType char32Type;
ParserIntType int64Type;
ParserIntType intMaxType;
ParserIntType intPtrType;
ParserIntType sizeType;
ParserIntType uIntMaxType;
ParserIntType wCharType;
ParserIntType wIntType;
ParserIntType char16Type;
ParserIntType char32Type;
ParserIntType int64Type;
ParserIntType intMaxType;
ParserIntType intPtrType;
ParserIntType sizeType;
ParserIntType uIntMaxType;
ParserIntType wCharType;
ParserIntType wIntType;
unsigned int boolAlign;
unsigned int boolWidth;
unsigned int charAlign;
unsigned int charWidth;
unsigned int char16Align;
unsigned int char16Width;
unsigned int char32Align;
unsigned int char32Width;
unsigned int halfAlign;
unsigned int halfWidth;
unsigned int floatAlign;
unsigned int floatWidth;
unsigned int doubleAlign;
unsigned int doubleWidth;
unsigned int shortAlign;
unsigned int shortWidth;
unsigned int intAlign;
unsigned int intWidth;
unsigned int intMaxTWidth;
unsigned int longAlign;
unsigned int longWidth;
unsigned int longDoubleAlign;
unsigned int longDoubleWidth;
unsigned int longLongAlign;
unsigned int longLongWidth;
unsigned int pointerAlign;
unsigned int pointerWidth;
unsigned int wCharAlign;
unsigned int wCharWidth;
unsigned int float128Align;
unsigned int float128Width;
};
unsigned int boolAlign;
unsigned int boolWidth;
unsigned int charAlign;
unsigned int charWidth;
unsigned int char16Align;
unsigned int char16Width;
unsigned int char32Align;
unsigned int char32Width;
unsigned int halfAlign;
unsigned int halfWidth;
unsigned int floatAlign;
unsigned int floatWidth;
unsigned int doubleAlign;
unsigned int doubleWidth;
unsigned int shortAlign;
unsigned int shortWidth;
unsigned int intAlign;
unsigned int intWidth;
unsigned int intMaxTWidth;
unsigned int longAlign;
unsigned int longWidth;
unsigned int longDoubleAlign;
unsigned int longDoubleWidth;
unsigned int longLongAlign;
unsigned int longLongWidth;
unsigned int pointerAlign;
unsigned int pointerWidth;
unsigned int wCharAlign;
unsigned int wCharWidth;
unsigned int float128Align;
unsigned int float128Width;
};
} }
}} // namespace CppSharp::CppParser

612
src/CppParser/Types.h

@ -1,9 +1,9 @@ @@ -1,9 +1,9 @@
/************************************************************************
*
* CppSharp
* Licensed under the MIT license.
*
************************************************************************/
*
* CppSharp
* Licensed under the MIT license.
*
************************************************************************/
#pragma once
@ -11,322 +11,322 @@ @@ -11,322 +11,322 @@
namespace CppSharp { namespace CppParser { namespace AST {
enum class TypeKind
{
Tag,
Array,
Function,
Pointer,
MemberPointer,
Typedef,
Attributed,
Decayed,
TemplateSpecialization,
DependentTemplateSpecialization,
TemplateParameter,
TemplateParameterSubstitution,
InjectedClassName,
DependentName,
PackExpansion,
Builtin,
UnaryTransform,
UnresolvedUsing,
Vector
};
enum class TypeKind
{
Tag,
Array,
Function,
Pointer,
MemberPointer,
Typedef,
Attributed,
Decayed,
TemplateSpecialization,
DependentTemplateSpecialization,
TemplateParameter,
TemplateParameterSubstitution,
InjectedClassName,
DependentName,
PackExpansion,
Builtin,
UnaryTransform,
UnresolvedUsing,
Vector
};
#define DECLARE_TYPE_KIND(kind) \
kind##Type();
class CS_API Type
{
public:
Type(TypeKind kind);
Type(const Type&);
TypeKind kind;
bool isDependent;
};
struct CS_API TypeQualifiers
{
bool isConst;
bool isVolatile;
bool isRestrict;
};
struct CS_API QualifiedType
{
QualifiedType();
Type* type;
TypeQualifiers qualifiers;
};
class Declaration;
class CS_API TagType : public Type
{
public:
DECLARE_TYPE_KIND(Tag)
Declaration* declaration;
};
class CS_API ArrayType : public Type
{
public:
enum class ArraySize
kind##Type();
class CS_API Type
{
Constant,
Variable,
Dependent,
Incomplete
public:
Type(TypeKind kind);
Type(const Type&);
TypeKind kind;
bool isDependent;
};
DECLARE_TYPE_KIND(Array)
QualifiedType qualifiedType;
ArraySize sizeType;
long size;
long elementSize;
};
class Parameter;
enum class CallingConvention
{
Default,
C,
StdCall,
ThisCall,
FastCall,
Unknown
};
enum class ExceptionSpecType
{
None,
DynamicNone,
Dynamic,
MSAny,
BasicNoexcept,
DependentNoexcept,
NoexceptFalse,
NoexceptTrue,
Unevaluated,
Uninstantiated,
Unparsed
};
class CS_API FunctionType : public Type
{
public:
DECLARE_TYPE_KIND(Function)
~FunctionType();
QualifiedType returnType;
CallingConvention callingConvention;
ExceptionSpecType exceptionSpecType;
VECTOR(Parameter*, Parameters)
};
class CS_API PointerType : public Type
{
public:
enum struct TypeModifier
struct CS_API TypeQualifiers
{
Value,
Pointer,
LVReference,
RVReference
bool isConst;
bool isVolatile;
bool isRestrict;
};
DECLARE_TYPE_KIND(Pointer)
QualifiedType qualifiedPointee;
TypeModifier modifier;
};
class CS_API MemberPointerType : public Type
{
public:
DECLARE_TYPE_KIND(MemberPointer)
QualifiedType pointee;
};
class TypedefNameDecl;
class CS_API TypedefType : public Type
{
public:
TypedefType();
TypedefNameDecl* declaration;
};
class CS_API AttributedType : public Type
{
public:
DECLARE_TYPE_KIND(Attributed)
QualifiedType modified;
QualifiedType equivalent;
};
class CS_API DecayedType : public Type
{
public:
DECLARE_TYPE_KIND(Decayed)
QualifiedType decayed;
QualifiedType original;
QualifiedType pointee;
};
struct CS_API TemplateArgument
{
TemplateArgument();
enum struct ArgumentKind
struct CS_API QualifiedType
{
Type,
Declaration,
NullPtr,
Integral,
Template,
TemplateExpansion,
Expression,
Pack
QualifiedType();
Type* type;
TypeQualifiers qualifiers;
};
ArgumentKind kind;
QualifiedType type;
Declaration* declaration;
long integral;
};
class Declaration;
class Template;
class CS_API TagType : public Type
{
public:
DECLARE_TYPE_KIND(Tag)
Declaration* declaration;
};
class CS_API ArrayType : public Type
{
public:
enum class ArraySize
{
Constant,
Variable,
Dependent,
Incomplete
};
DECLARE_TYPE_KIND(Array)
QualifiedType qualifiedType;
ArraySize sizeType;
long size;
long elementSize;
};
class CS_API TemplateSpecializationType : public Type
{
public:
TemplateSpecializationType();
TemplateSpecializationType(const TemplateSpecializationType&);
~TemplateSpecializationType();
class Parameter;
VECTOR(TemplateArgument, Arguments)
enum class CallingConvention
{
Default,
C,
StdCall,
ThisCall,
FastCall,
Unknown
};
enum class ExceptionSpecType
{
None,
DynamicNone,
Dynamic,
MSAny,
BasicNoexcept,
DependentNoexcept,
NoexceptFalse,
NoexceptTrue,
Unevaluated,
Uninstantiated,
Unparsed
};
class CS_API FunctionType : public Type
{
public:
DECLARE_TYPE_KIND(Function)
~FunctionType();
QualifiedType returnType;
CallingConvention callingConvention;
ExceptionSpecType exceptionSpecType;
VECTOR(Parameter*, Parameters)
};
class CS_API PointerType : public Type
{
public:
enum struct TypeModifier
{
Value,
Pointer,
LVReference,
RVReference
};
DECLARE_TYPE_KIND(Pointer)
QualifiedType qualifiedPointee;
TypeModifier modifier;
};
class CS_API MemberPointerType : public Type
{
public:
DECLARE_TYPE_KIND(MemberPointer)
QualifiedType pointee;
};
class TypedefNameDecl;
class CS_API TypedefType : public Type
{
public:
TypedefType();
TypedefNameDecl* declaration;
};
class CS_API AttributedType : public Type
{
public:
DECLARE_TYPE_KIND(Attributed)
QualifiedType modified;
QualifiedType equivalent;
};
class CS_API DecayedType : public Type
{
public:
DECLARE_TYPE_KIND(Decayed)
QualifiedType decayed;
QualifiedType original;
QualifiedType pointee;
};
struct CS_API TemplateArgument
{
TemplateArgument();
enum struct ArgumentKind
{
Type,
Declaration,
NullPtr,
Integral,
Template,
TemplateExpansion,
Expression,
Pack
};
ArgumentKind kind;
QualifiedType type;
Declaration* declaration;
long integral;
};
class Template;
class CS_API TemplateSpecializationType : public Type
{
public:
TemplateSpecializationType();
TemplateSpecializationType(const TemplateSpecializationType&);
~TemplateSpecializationType();
VECTOR(TemplateArgument, Arguments)
Template* _template;
QualifiedType desugared;
};
QualifiedType desugared;
};
class CS_API DependentTemplateSpecializationType : public Type
{
public:
DependentTemplateSpecializationType();
DependentTemplateSpecializationType(const DependentTemplateSpecializationType&);
~DependentTemplateSpecializationType();
VECTOR(TemplateArgument, Arguments)
QualifiedType desugared;
};
class TypeTemplateParameter;
class CS_API TemplateParameterType : public Type
{
public:
DECLARE_TYPE_KIND(TemplateParameter)
~TemplateParameterType();
TypeTemplateParameter* parameter;
unsigned int depth;
unsigned int index;
bool isParameterPack;
};
class CS_API TemplateParameterSubstitutionType : public Type
{
public:
DECLARE_TYPE_KIND(TemplateParameterSubstitution)
QualifiedType replacement;
TemplateParameterType* replacedParameter;
};
class Class;
class CS_API InjectedClassNameType : public Type
{
public:
DECLARE_TYPE_KIND(InjectedClassName)
QualifiedType injectedSpecializationType;
Class* _class;
};
class CS_API DependentNameType : public Type
{
public:
DECLARE_TYPE_KIND(DependentName)
~DependentNameType();
QualifiedType qualifier;
std::string identifier;
};
class CS_API DependentTemplateSpecializationType : public Type
{
public:
DependentTemplateSpecializationType();
DependentTemplateSpecializationType(const DependentTemplateSpecializationType&);
~DependentTemplateSpecializationType();
class CS_API PackExpansionType : public Type
{
public:
DECLARE_TYPE_KIND(PackExpansion)
};
VECTOR(TemplateArgument, Arguments)
class CS_API UnaryTransformType : public Type
{
public:
DECLARE_TYPE_KIND(UnaryTransform)
QualifiedType desugared;
};
class TypeTemplateParameter;
class CS_API TemplateParameterType : public Type
{
public:
DECLARE_TYPE_KIND(TemplateParameter)
~TemplateParameterType();
TypeTemplateParameter* parameter;
unsigned int depth;
unsigned int index;
bool isParameterPack;
};
class CS_API TemplateParameterSubstitutionType : public Type
{
public:
DECLARE_TYPE_KIND(TemplateParameterSubstitution)
QualifiedType replacement;
TemplateParameterType* replacedParameter;
};
class Class;
class CS_API InjectedClassNameType : public Type
{
public:
DECLARE_TYPE_KIND(InjectedClassName)
QualifiedType injectedSpecializationType;
Class* _class;
};
class CS_API DependentNameType : public Type
{
public:
DECLARE_TYPE_KIND(DependentName)
~DependentNameType();
QualifiedType qualifier;
std::string identifier;
};
class CS_API PackExpansionType : public Type
{
public:
DECLARE_TYPE_KIND(PackExpansion)
};
class CS_API UnaryTransformType : public Type
{
public:
DECLARE_TYPE_KIND(UnaryTransform)
QualifiedType desugared;
QualifiedType baseType;
};
class UnresolvedUsingTypename;
class CS_API UnresolvedUsingType : public Type
{
public:
DECLARE_TYPE_KIND(UnresolvedUsing)
UnresolvedUsingTypename* declaration;
};
class CS_API VectorType : public Type
{
public:
DECLARE_TYPE_KIND(Vector)
QualifiedType elementType;
unsigned numElements;
};
enum class PrimitiveType
{
Null,
Void,
Bool,
WideChar,
Char,
SChar,
UChar,
Char16,
Char32,
Short,
UShort,
Int,
UInt,
Long,
ULong,
LongLong,
ULongLong,
Int128,
UInt128,
Half,
Float,
Double,
LongDouble,
Float128,
IntPtr
};
class CS_API BuiltinType : public Type
{
public:
DECLARE_TYPE_KIND(Builtin)
PrimitiveType type;
};
} } }
QualifiedType baseType;
};
class UnresolvedUsingTypename;
class CS_API UnresolvedUsingType : public Type
{
public:
DECLARE_TYPE_KIND(UnresolvedUsing)
UnresolvedUsingTypename* declaration;
};
class CS_API VectorType : public Type
{
public:
DECLARE_TYPE_KIND(Vector)
QualifiedType elementType;
unsigned numElements;
};
enum class PrimitiveType
{
Null,
Void,
Bool,
WideChar,
Char,
SChar,
UChar,
Char16,
Char32,
Short,
UShort,
Int,
UInt,
Long,
ULong,
LongLong,
ULongLong,
Int128,
UInt128,
Half,
Float,
Double,
LongDouble,
Float128,
IntPtr
};
class CS_API BuiltinType : public Type
{
public:
DECLARE_TYPE_KIND(Builtin)
PrimitiveType type;
};
}}} // namespace CppSharp::CppParser::AST

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

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

10
src/Generator/Generators/QuickJS/Runtime/CppSharp_QuickJS.cpp

@ -3,11 +3,11 @@ @@ -3,11 +3,11 @@
extern "C"
{
extern void register_signal(JSContext *ctx, JSModuleDef *m, bool set, int phase);
extern void register_signal(JSContext* ctx, JSModuleDef* m, bool set, int phase);
void register_CppSharp_QuickJS(JSContext *ctx, JSModuleDef *m, bool set, int phase)
{
register_signal(ctx, m, set, phase);
}
void register_CppSharp_QuickJS(JSContext* ctx, JSModuleDef* m, bool set, int phase)
{
register_signal(ctx, m, set, phase);
}
} // extern "C"

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

@ -12,253 +12,258 @@ extern "C" @@ -12,253 +12,258 @@ extern "C"
#include <cutils.h>
#if defined(__GNUC__) || defined(__clang__)
#define js_force_inline inline __attribute__((always_inline))
#define js_force_inline inline __attribute__((always_inline))
#else
#define js_force_inline inline
#define js_force_inline inline
#endif
#define countof(x) (sizeof(x) / sizeof((x)[0]))
enum
{
__JS_ATOM_NULL = JS_ATOM_NULL,
#define DEF(name, str) JS_ATOM_ ## name,
enum
{
__JS_ATOM_NULL = JS_ATOM_NULL,
#define DEF(name, str) JS_ATOM_##name,
#include <quickjs-atom.h>
#undef DEF
JS_ATOM_END,
};
struct JS_SignalContext
{
// TODO: List
JSValue function;
JSValue link;
JSContext *ctx;
};
typedef int JS_EventId;
typedef int JS_ClassId;
typedef DynBuf JS_EventMap;
JS_ATOM_END,
};
struct JS_EventEntry
{
JS_EventId eventId;
JSValue value;
};
static JS_EventMap* JS_Interop_InitEventMap(JS_EventMap* map)
{
dbuf_init(map);
return map;
}
static void JS_Interop_FreeEventMap(JSContext* ctx, JS_EventMap* map)
{
JS_EventEntry* events = (JS_EventEntry*) map->buf;
int numEvents = (map->size / sizeof(JS_EventEntry));
for (int i = 0; i < numEvents; i++)
if (!JS_IsUndefined(events[i].value))
JS_FreeValue(ctx, events[i].value);
struct JS_SignalContext
{
// TODO: List
JSValue function;
JSValue link;
JSContext* ctx;
};
dbuf_free(map);
}
typedef int JS_EventId;
typedef int JS_ClassId;
typedef DynBuf JS_EventMap;
static int JS_Interop_BinarySearch(JS_EventEntry* arr, int l, int r, JS_EventId id)
{
if (r >= l) {
int mid = l + (r - l) / 2;
struct JS_EventEntry
{
JS_EventId eventId;
JSValue value;
};
// If the element is present at the middle itself
if (arr[mid].eventId == id)
return mid;
static JS_EventMap* JS_Interop_InitEventMap(JS_EventMap* map)
{
dbuf_init(map);
return map;
}
// If element is smaller than mid, then it can only be present in left subarray
if (arr[mid].eventId > id)
return JS_Interop_BinarySearch(arr, l, mid - 1, id);
static void JS_Interop_FreeEventMap(JSContext* ctx, JS_EventMap* map)
{
JS_EventEntry* events = (JS_EventEntry*)map->buf;
int numEvents = (map->size / sizeof(JS_EventEntry));
for (int i = 0; i < numEvents; i++)
if (!JS_IsUndefined(events[i].value))
JS_FreeValue(ctx, events[i].value);
// Else the element can only be present in right subarray
return JS_Interop_BinarySearch(arr, mid + 1, r, id);
dbuf_free(map);
}
// We reach here when element is not present in array
return -1;
}
static int JS_Interop_BinarySearch(JS_EventEntry* arr, int l, int r, JS_EventId id)
{
if (r >= l)
{
int mid = l + (r - l) / 2;
static JSValue JS_Interop_FindEvent(JS_EventMap* map, JS_EventId eventId)
{
JS_EventEntry* events = (JS_EventEntry*) map->buf;
int numEvents = (map->size / sizeof(JS_EventEntry));
if (numEvents == 0)
return JS_UNDEFINED;
// If the element is present at the middle itself
if (arr[mid].eventId == id)
return mid;
int index = JS_Interop_BinarySearch(events, 0, numEvents, eventId);
return index >= 0 ? events[index].value : JS_UNDEFINED;
}
// If element is smaller than mid, then it can only be present in left subarray
if (arr[mid].eventId > id)
return JS_Interop_BinarySearch(arr, l, mid - 1, id);
static int JS_Interop_InsertEvent(JS_EventMap* map, JS_EventId eventId,
JSValue value)
{
JS_EventEntry* events = (JS_EventEntry*) map->buf;
int numEvents = (map->size / sizeof(JS_EventEntry));
// Else the element can only be present in right subarray
return JS_Interop_BinarySearch(arr, mid + 1, r, id);
}
int index = 0;
for (int i = 0; i < numEvents; i++)
{
if (events[i].eventId == eventId) { index=-1; break; }
if (events[i].eventId > eventId) { index = i; break; }
index++;
// We reach here when element is not present in array
return -1;
}
if (index == -1)
return -1;
static JSValue JS_Interop_FindEvent(JS_EventMap* map, JS_EventId eventId)
{
JS_EventEntry* events = (JS_EventEntry*)map->buf;
int numEvents = (map->size / sizeof(JS_EventEntry));
if (numEvents == 0)
return JS_UNDEFINED;
JS_EventEntry entry;
entry.eventId = eventId;
entry.value = value;
int index = JS_Interop_BinarySearch(events, 0, numEvents, eventId);
return index >= 0 ? events[index].value : JS_UNDEFINED;
}
dbuf_write(map, index * sizeof(JS_EventEntry), (const uint8_t*) &entry,
sizeof(JS_EventEntry));
static int JS_Interop_InsertEvent(JS_EventMap* map, JS_EventId eventId, JSValue value)
{
JS_EventEntry* events = (JS_EventEntry*)map->buf;
int numEvents = (map->size / sizeof(JS_EventEntry));
return 0;
}
int index = 0;
for (int i = 0; i < numEvents; i++)
{
if (events[i].eventId == eventId)
{
index = -1;
break;
}
if (events[i].eventId > eventId)
{
index = i;
break;
}
index++;
}
static JSValue JS_Interop_InvokeConstructor(JSContext *ctx, JS_ClassId eventId,
JSValue argv[], int argc)
{
// TODO: Error handling.
JSValue proto = JS_GetClassProto(ctx, eventId);
JSValue ctor = JS_GetProperty(ctx, proto, JS_ATOM_constructor);
JSValue instance = JS_CallConstructor(ctx, ctor, argc, argv);
JS_FreeValue(ctx, ctor);
JS_FreeValue(ctx, proto);
if (index == -1)
return -1;
return instance;
}
JS_EventEntry entry;
entry.eventId = eventId;
entry.value = value;
enum JS_Interop_InstanceKind
{
JS_INTEROP_INSTANCE_RAW_POINTER = 1,
JS_INTEROP_INSTANCE_SIGNAL_CONTEXT,
};
dbuf_write(map, index * sizeof(JS_EventEntry), (const uint8_t*)&entry,
sizeof(JS_EventEntry));
struct JS_Interop_ClassData
{
void* instance;
JSContext* ctx;
JS_EventMap events;
};
return 0;
}
static JSValue JS_Interop_InitObject(JSContext *ctx, JSValue obj, JS_Interop_InstanceKind kind,
void* instance)
{
switch (kind)
static JSValue JS_Interop_InvokeConstructor(JSContext* ctx, JS_ClassId eventId, JSValue argv[], int argc)
{
case JS_INTEROP_INSTANCE_RAW_POINTER:
JS_SetOpaque(obj, instance);
return obj;
case JS_INTEROP_INSTANCE_SIGNAL_CONTEXT:
JS_Interop_ClassData* data = (JS_Interop_ClassData*) js_mallocz(ctx, \
sizeof(JS_Interop_ClassData));
data->ctx = ctx;
data->instance = instance;
JS_Interop_InitEventMap(&data->events);
JS_SetOpaque(obj, data);
return obj;
// TODO: Error handling.
JSValue proto = JS_GetClassProto(ctx, eventId);
JSValue ctor = JS_GetProperty(ctx, proto, JS_ATOM_constructor);
JSValue instance = JS_CallConstructor(ctx, ctor, argc, argv);
JS_FreeValue(ctx, ctor);
JS_FreeValue(ctx, proto);
return instance;
}
return JS_UNDEFINED;
}
enum JS_Interop_InstanceKind
{
JS_INTEROP_INSTANCE_RAW_POINTER = 1,
JS_INTEROP_INSTANCE_SIGNAL_CONTEXT,
};
static JSValue JS_Interop_CleanupObject(JSValue obj, JS_Interop_InstanceKind kind)
{
switch (kind)
struct JS_Interop_ClassData
{
case JS_INTEROP_INSTANCE_SIGNAL_CONTEXT:
void* instance;
JSContext* ctx;
JS_EventMap events;
};
static JSValue JS_Interop_InitObject(JSContext* ctx, JSValue obj, JS_Interop_InstanceKind kind, void* instance)
{
JS_Interop_ClassData* data = (JS_Interop_ClassData*) JS_GetOpaque(obj, JS_GetClassID(obj));
if (data)
switch (kind)
{
JS_Interop_FreeEventMap(data->ctx, &data->events);
js_free(data->ctx, data);
case JS_INTEROP_INSTANCE_RAW_POINTER:
JS_SetOpaque(obj, instance);
return obj;
case JS_INTEROP_INSTANCE_SIGNAL_CONTEXT:
JS_Interop_ClassData* data = (JS_Interop_ClassData*)js_mallocz(ctx,
sizeof(JS_Interop_ClassData));
data->ctx = ctx;
data->instance = instance;
JS_Interop_InitEventMap(&data->events);
JS_SetOpaque(obj, data);
return obj;
}
break;
}
case JS_INTEROP_INSTANCE_RAW_POINTER:
break;
}
return JS_UNDEFINED;
}
return JS_UNDEFINED;
}
static void* JS_Interop_GetInstance(JSValue obj, JS_ClassId classId, JS_Interop_InstanceKind kind)
{
switch (kind)
static JSValue JS_Interop_CleanupObject(JSValue obj, JS_Interop_InstanceKind kind)
{
case JS_INTEROP_INSTANCE_RAW_POINTER:
return JS_GetOpaque(obj, classId);
case JS_INTEROP_INSTANCE_SIGNAL_CONTEXT:
JS_Interop_ClassData* data = (JS_Interop_ClassData*) JS_GetOpaque(obj, classId);
return data != nullptr ? data->instance : nullptr;
switch (kind)
{
case JS_INTEROP_INSTANCE_SIGNAL_CONTEXT:
{
JS_Interop_ClassData* data = (JS_Interop_ClassData*)JS_GetOpaque(obj, JS_GetClassID(obj));
if (data)
{
JS_Interop_FreeEventMap(data->ctx, &data->events);
js_free(data->ctx, data);
}
break;
}
case JS_INTEROP_INSTANCE_RAW_POINTER:
break;
}
return JS_UNDEFINED;
}
return nullptr;
}
static void* JS_Interop_GetInstance(JSValue obj, JS_ClassId classId, JS_Interop_InstanceKind kind)
{
switch (kind)
{
case JS_INTEROP_INSTANCE_RAW_POINTER:
return JS_GetOpaque(obj, classId);
case JS_INTEROP_INSTANCE_SIGNAL_CONTEXT:
JS_Interop_ClassData* data = (JS_Interop_ClassData*)JS_GetOpaque(obj, classId);
return data != nullptr ? data->instance : nullptr;
}
static JSValue JS_Interop_CreateFromInstance(JSContext* ctx, JS_ClassId classId,
JS_Interop_InstanceKind kind, void* instance)
{
if (instance == nullptr)
return JS_NULL;
return nullptr;
}
// TODO: Error handling.
JSValue obj = JS_NewObjectClass(ctx, classId);
JS_Interop_InitObject(ctx, obj, kind, instance);
static JSValue JS_Interop_CreateFromInstance(JSContext* ctx, JS_ClassId classId, JS_Interop_InstanceKind kind, void* instance)
{
if (instance == nullptr)
return JS_NULL;
return obj;
}
// TODO: Error handling.
JSValue obj = JS_NewObjectClass(ctx, classId);
JS_Interop_InitObject(ctx, obj, kind, instance);
static inline JS_BOOL JS_IsInt(JSValueConst v)
{
return JS_IsNumber(v);
}
return obj;
}
static inline JS_BOOL JS_IsInt8(JSValueConst v)
{
return JS_IsInt(v);
}
static inline JS_BOOL JS_IsInt(JSValueConst v)
{
return JS_IsNumber(v);
}
static inline JS_BOOL JS_IsUInt8(JSValueConst v)
{
return JS_IsInt(v);
}
static inline JS_BOOL JS_IsInt8(JSValueConst v)
{
return JS_IsInt(v);
}
static inline JS_BOOL JS_IsInt16(JSValueConst v)
{
return JS_IsInt(v);
}
static inline JS_BOOL JS_IsUInt8(JSValueConst v)
{
return JS_IsInt(v);
}
static inline JS_BOOL JS_IsUInt16(JSValueConst v)
{
return JS_IsInt(v);
}
static inline JS_BOOL JS_IsInt16(JSValueConst v)
{
return JS_IsInt(v);
}
static inline JS_BOOL JS_IsInt32(JSValueConst v)
{
return JS_IsInt(v);
}
static inline JS_BOOL JS_IsUInt16(JSValueConst v)
{
return JS_IsInt(v);
}
static inline JS_BOOL JS_IsUInt32(JSValueConst v)
{
return JS_IsInt(v);
}
static inline JS_BOOL JS_IsInt32(JSValueConst v)
{
return JS_IsInt(v);
}
static inline JS_BOOL JS_IsFloat(JSValueConst v)
{
int tag = JS_VALUE_GET_TAG(v);
return JS_TAG_IS_FLOAT64(tag);
}
static inline JS_BOOL JS_IsUInt32(JSValueConst v)
{
return JS_IsInt(v);
}
static inline JS_BOOL JS_IsFloat(JSValueConst v)
{
int tag = JS_VALUE_GET_TAG(v);
return JS_TAG_IS_FLOAT64(tag);
}
void register_CppSharp_QuickJS(JSContext *ctx, JSModuleDef *m, bool set, int phase);
void register_CppSharp_QuickJS(JSContext* ctx, JSModuleDef* m, bool set, int phase);
#undef js_force_inline

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

@ -8,106 +8,104 @@ @@ -8,106 +8,104 @@
#include <CppSharp_QuickJS.h>
#include <assert.h>
extern "C" {
extern "C"
{
JSClassID classId__Signal;
JSClassID classId__Signal;
// Signal::Signal
static JSValue callback_method_Signal_Signal(JSContext* ctx, JSValueConst this_val,
int argc, JSValueConst* argv)
{
// if (argc != 1)
// {
// return JS_ThrowRangeError(ctx, "Unsupported number of arguments");
// }
wrap:
JSValue proto;
if (JS_IsUndefined(this_val))
proto = JS_GetClassProto(ctx, classId__Signal);
else
proto = JS_GetPropertyStr(ctx, this_val, "prototype");
if (JS_IsException(proto))
return proto;
JSValue __obj = JS_NewObjectProtoClass(ctx, proto, classId__Signal);
JS_FreeValue(ctx, proto);
JS_SignalContext* signalCtx = new JS_SignalContext;
signalCtx->ctx = ctx;
signalCtx->function = JS_UNDEFINED;
signalCtx->link = JS_UNDEFINED;
if (argc >= 1)
// Signal::Signal
static JSValue callback_method_Signal_Signal(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv)
{
JSValue link = argv[0];
assert(JS_IsObject(link));
//JS_FreeValue(ctx, link);
signalCtx->link = link;
// if (argc != 1)
// {
// return JS_ThrowRangeError(ctx, "Unsupported number of arguments");
// }
wrap:
JSValue proto;
if (JS_IsUndefined(this_val))
proto = JS_GetClassProto(ctx, classId__Signal);
else
proto = JS_GetPropertyStr(ctx, this_val, "prototype");
if (JS_IsException(proto))
return proto;
JSValue __obj = JS_NewObjectProtoClass(ctx, proto, classId__Signal);
JS_FreeValue(ctx, proto);
JS_SignalContext* signalCtx = new JS_SignalContext;
signalCtx->ctx = ctx;
signalCtx->function = JS_UNDEFINED;
signalCtx->link = JS_UNDEFINED;
if (argc >= 1)
{
JSValue link = argv[0];
assert(JS_IsObject(link));
// JS_FreeValue(ctx, link);
signalCtx->link = link;
}
JS_SetOpaque(__obj, signalCtx);
return __obj;
}
JS_SetOpaque(__obj, signalCtx);
return __obj;
}
// Signal::connect
static JSValue callback_method_Signal_connect(JSContext* ctx, JSValueConst this_val,
int argc, JSValueConst* argv)
{
if (argc < 1 || argc > 1)
// Signal::connect
static JSValue callback_method_Signal_connect(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv)
{
return JS_ThrowRangeError(ctx, "Expected one argument of function type");
}
if (argc < 1 || argc > 1)
{
return JS_ThrowRangeError(ctx, "Expected one argument of function type");
}
// Signal* instance = (Signal*) JS_GetOpaque(this_val, classId__Signal);
// Signal* instance = (Signal*) JS_GetOpaque(this_val, classId__Signal);
if (!JS_IsFunction(ctx, argv[0]))
return JS_ThrowTypeError(ctx, "Unsupported argument type");
if (!JS_IsFunction(ctx, argv[0]))
return JS_ThrowTypeError(ctx, "Unsupported argument type");
// Connect logic
// Connect logic
JS_SignalContext* signalCtx = (JS_SignalContext*) JS_GetOpaque(this_val, classId__Signal);
if (signalCtx == nullptr)
return JS_ThrowTypeError(ctx, "Could not find signal context");
JS_SignalContext* signalCtx = (JS_SignalContext*)JS_GetOpaque(this_val, classId__Signal);
if (signalCtx == nullptr)
return JS_ThrowTypeError(ctx, "Could not find signal context");
assert(JS_IsObject(signalCtx->link));
assert(JS_IsObject(signalCtx->link));
if (!JS_IsUndefined(signalCtx->function))
return JS_ThrowRangeError(ctx, "Signal already contains a connected function");
if (!JS_IsUndefined(signalCtx->function))
return JS_ThrowRangeError(ctx, "Signal already contains a connected function");
signalCtx->function = JS_DupValue(ctx, argv[0]);
signalCtx->function = JS_DupValue(ctx, argv[0]);
JSValue ____ret = JS_NewInt32(ctx, 0);
JSValue ____ret = JS_NewInt32(ctx, 0);
return ____ret;
}
return ____ret;
}
// Signal::disconnect
static JSValue callback_method_Signal_disconnect(JSContext* ctx, JSValueConst this_val,
int argc, JSValueConst* argv)
{
if (argc < 1 || argc > 1)
// Signal::disconnect
static JSValue callback_method_Signal_disconnect(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv)
{
return JS_ThrowRangeError(ctx, "Unsupported number of arguments");
}
if (argc < 1 || argc > 1)
{
return JS_ThrowRangeError(ctx, "Unsupported number of arguments");
}
// Signal* instance = (Signal*) JS_GetOpaque(this_val, classId__Signal);
// Signal* instance = (Signal*) JS_GetOpaque(this_val, classId__Signal);
if (JS_IsNumber(argv[0]))
goto overload0;
if (JS_IsNumber(argv[0]))
goto overload0;
goto error;
goto error;
error:
return JS_ThrowTypeError(ctx, "Unsupported argument type");
error:
return JS_ThrowTypeError(ctx, "Unsupported argument type");
// bool disconnect(Slot slot) { return 0; }
overload0:
// bool disconnect(Slot slot) { return 0; }
overload0:
{
int slot;
if (JS_ToInt32(ctx, (int32_t*) &slot, argv[0]))
if (JS_ToInt32(ctx, (int32_t*)&slot, argv[0]))
return JS_EXCEPTION;
// auto __arg0 = (::Slot)slot;
@ -117,86 +115,82 @@ overload0: @@ -117,86 +115,82 @@ overload0:
return ____ret;
}
}
}
// Signal::isEmpty
static JSValue callback_method_Signal_isEmpty(JSContext* ctx, JSValueConst this_val,
int argc, JSValueConst* argv)
{
if (argc > 0)
// Signal::isEmpty
static JSValue callback_method_Signal_isEmpty(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv)
{
return JS_ThrowRangeError(ctx, "Unsupported number of arguments");
}
if (argc > 0)
{
return JS_ThrowRangeError(ctx, "Unsupported number of arguments");
}
JS_SignalContext* signalCtx = (JS_SignalContext*) JS_GetOpaque(this_val, classId__Signal);
JS_SignalContext* signalCtx = (JS_SignalContext*)JS_GetOpaque(this_val, classId__Signal);
JSValue ____ret = JS_NewBool(ctx, JS_IsUndefined(signalCtx->function));
JSValue ____ret = JS_NewBool(ctx, JS_IsUndefined(signalCtx->function));
return ____ret;
}
return ____ret;
}
static JSValue callback_class__Signal_toString(JSContext* ctx, JSValueConst this_val,
int argc, JSValueConst* argv)
{
return JS_NewString(ctx, "Signal");
}
static JSValue callback_class__Signal_toString(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv)
{
return JS_NewString(ctx, "Signal");
}
void finalizer__Signal(JSRuntime *rt, JSValue val)
{
JS_SignalContext* signalCtx = (JS_SignalContext*) JS_GetOpaque(val, classId__Signal);
if (signalCtx == nullptr)
return;
void finalizer__Signal(JSRuntime* rt, JSValue val)
{
JS_SignalContext* signalCtx = (JS_SignalContext*)JS_GetOpaque(val, classId__Signal);
if (signalCtx == nullptr)
return;
if (!JS_IsUndefined(signalCtx->function))
return JS_FreeValue(signalCtx->ctx, signalCtx->function);
if (!JS_IsUndefined(signalCtx->function))
return JS_FreeValue(signalCtx->ctx, signalCtx->function);
js_free_rt(rt, signalCtx);
js_free_rt(rt, signalCtx);
JS_SetOpaque(val, nullptr);
}
JS_SetOpaque(val, nullptr);
}
static JSClassDef classDef__Signal =
{
.class_name = "Signal",
.finalizer = finalizer__Signal
};
static JSClassDef classDef__Signal = {
.class_name = "Signal",
.finalizer = finalizer__Signal
};
static JSCFunctionListEntry funcDef__Signal[] =
{
JS_CFUNC_DEF("connect", 1, callback_method_Signal_connect),
JS_CFUNC_DEF("disconnect", 1, callback_method_Signal_disconnect),
JS_CFUNC_DEF("isEmpty", 0, callback_method_Signal_isEmpty),
JS_CFUNC_DEF("toString", 0, callback_class__Signal_toString),
};
static JSCFunctionListEntry funcDef__Signal[] = {
JS_CFUNC_DEF("connect", 1, callback_method_Signal_connect),
JS_CFUNC_DEF("disconnect", 1, callback_method_Signal_disconnect),
JS_CFUNC_DEF("isEmpty", 0, callback_method_Signal_isEmpty),
JS_CFUNC_DEF("toString", 0, callback_class__Signal_toString),
};
static void register_class__Signal(JSContext *ctx, JSModuleDef *m, bool set, int phase)
{
if (!set)
static void register_class__Signal(JSContext* ctx, JSModuleDef* m, bool set, int phase)
{
JS_AddModuleExport(ctx, m, "Signal");
return;
}
if (!set)
{
JS_AddModuleExport(ctx, m, "Signal");
return;
}
if (phase == 0)
{
JS_NewClassID(JS_GetRuntime(ctx), &classId__Signal);
if (phase == 0)
{
JS_NewClassID(JS_GetRuntime(ctx), &classId__Signal);
JS_NewClass(JS_GetRuntime(ctx), classId__Signal, &classDef__Signal);
JS_NewClass(JS_GetRuntime(ctx), classId__Signal, &classDef__Signal);
JSValue proto = JS_NewObject(ctx);
JS_SetPropertyFunctionList(ctx, proto, funcDef__Signal, sizeof(funcDef__Signal) / sizeof(funcDef__Signal[0]));
JS_SetClassProto(ctx, classId__Signal, proto);
JSValue proto = JS_NewObject(ctx);
JS_SetPropertyFunctionList(ctx, proto, funcDef__Signal, sizeof(funcDef__Signal) / sizeof(funcDef__Signal[0]));
JS_SetClassProto(ctx, classId__Signal, proto);
JSValue ctor = JS_NewCFunction2(ctx, callback_method_Signal_Signal, "Signal", 1, JS_CFUNC_constructor, 0);
JS_SetConstructor(ctx, ctor, proto);
JSValue ctor = JS_NewCFunction2(ctx, callback_method_Signal_Signal, "Signal", 1, JS_CFUNC_constructor, 0);
JS_SetConstructor(ctx, ctor, proto);
JS_SetModuleExport(ctx, m, "Signal", ctor);
JS_SetModuleExport(ctx, m, "Signal", ctor);
}
}
}
void register_signal(JSContext *ctx, JSModuleDef *m, bool set, int phase)
{
register_class__Signal(ctx, m, set, phase);
}
void register_signal(JSContext* ctx, JSModuleDef* m, bool set, int phase)
{
register_class__Signal(ctx, m, set, phase);
}
} // extern "C"

194
tests/Builtins.h

@ -3,62 +3,174 @@ @@ -3,62 +3,174 @@
#include <cstddef>
#include <cstdint>
void ReturnsVoid () { }
void ReturnsVoid() {}
std::nullptr_t ReturnsNullptr () { return nullptr; }
std::nullptr_t PassAndReturnsNullptr (std::nullptr_t t) { return t; }
std::nullptr_t ReturnsNullptr()
{
return nullptr;
}
std::nullptr_t PassAndReturnsNullptr(std::nullptr_t t)
{
return t;
}
bool ReturnsBool () { return true; }
bool PassAndReturnsBool (bool v) { return v; }
bool ReturnsBool()
{
return true;
}
bool PassAndReturnsBool(bool v)
{
return v;
}
// Character types
char ReturnsChar () { return 'a'; }
signed char ReturnsSChar () { 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; }
char ReturnsChar()
{
return 'a';
}
signed char ReturnsSChar()
{
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
char8_t ReturnsChar8 () { return 'a'; }
char8_t ReturnsChar8()
{
return 'a';
}
#endif
char16_t ReturnsChar16 () { return 'a'; }
char32_t ReturnsChar32 () { return 'a'; }
char16_t ReturnsChar16()
{
return 'a';
}
char32_t ReturnsChar32()
{
return 'a';
}
// Floating-point types
float ReturnsFloat () { return 5.0; }
double ReturnsDouble () { return -5.0; }
long double ReturnsLongDouble () { return -5.0; }
float ReturnsFloat()
{
return 5.0;
}
double ReturnsDouble()
{
return -5.0;
}
long double ReturnsLongDouble()
{
return -5.0;
}
float PassAndReturnsFloat (float v) { return v; }
double PassAndReturnsDouble (double v) { return v; }
long double PassAndReturnsLongDouble (long double v) { return v; }
float PassAndReturnsFloat(float v)
{
return v;
}
double PassAndReturnsDouble(double v)
{
return v;
}
long double PassAndReturnsLongDouble(long double v)
{
return v;
}
// Integer types
int8_t ReturnsInt8 () { return -5; }
uint8_t ReturnsUInt8 () { return 5; }
int16_t ReturnsInt16 () { return -5; }
uint16_t ReturnsUInt16 () { return 5; }
int32_t ReturnsInt32 () { return -5; }
uint32_t ReturnsUInt32 () { return 5; }
int8_t ReturnsInt8()
{
return -5;
}
uint8_t ReturnsUInt8()
{
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__)
int64_t ReturnsInt64 () { return -5; }
uint64_t ReturnsUInt64 () { return 5; }
int64_t ReturnsInt64()
{
return -5;
}
uint64_t ReturnsUInt64()
{
return 5;
}
#endif
int8_t PassAndReturnsInt8 (int8_t v) { return v; }
uint8_t PassAndReturnsUInt8 (uint8_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; }
int8_t PassAndReturnsInt8(int8_t v)
{
return v;
}
uint8_t PassAndReturnsUInt8(uint8_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
const char* ReturnsConstCharPtr() { return "Hello"; }
const char* PassAndReturnsConstCharPtr(const char* ptr) { return ptr; }
const char* ReturnsConstCharPtr()
{
return "Hello";
}
const char* PassAndReturnsConstCharPtr(const char* ptr)
{
return ptr;
}

10
tests/Classes.h

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

1
tests/Classes2.h

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

6
tests/Delegates.h

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

10
tests/Enums.h

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

45
tests/Overloads.h

@ -2,15 +2,42 @@ @@ -2,15 +2,42 @@
void Overload0() {}
int Overload1() { return 1; }
int Overload1(int) { return 2; }
int Overload1()
{
return 1;
}
int Overload1(int)
{
return 2;
}
int Overload(int, int) { return 1; }
int Overload(int, float) { return 2; }
int Overload(float, int) { return 3; }
int Overload(int, int)
{
return 1;
}
int Overload(int, float)
{
return 2;
}
int Overload(float, int)
{
return 3;
}
int DefaultParamsOverload() { return 0; }
int DefaultParamsOverload(int a, int b) { return 2; }
int DefaultParamsOverload(int a, float b = 2) { return 3; }
int DefaultParamsOverload()
{
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;
}

193
tests/dotnet/CSharp/AnonTypes.h

@ -1,154 +1,193 @@ @@ -1,154 +1,193 @@
#ifndef KONAN_EXAMPLE_LIB_H
#define KONAN_EXAMPLE_LIB_H
#ifdef __cplusplus
extern "C" {
extern "C"
{
#endif
#ifdef __cplusplus
typedef bool example_lib_KBoolean;
typedef bool example_lib_KBoolean;
#else
typedef _Bool example_lib_KBoolean;
typedef _Bool example_lib_KBoolean;
#endif
typedef unsigned short example_lib_KChar;
typedef signed char example_lib_KByte;
typedef short example_lib_KShort;
typedef int example_lib_KInt;
typedef long long example_lib_KLong;
typedef unsigned char example_lib_KUByte;
typedef unsigned short example_lib_KUShort;
typedef unsigned int example_lib_KUInt;
typedef unsigned short example_lib_KChar;
typedef signed char example_lib_KByte;
typedef short example_lib_KShort;
typedef int example_lib_KInt;
typedef long long example_lib_KLong;
typedef unsigned char example_lib_KUByte;
typedef unsigned short example_lib_KUShort;
typedef unsigned int example_lib_KUInt;
typedef unsigned long long example_lib_KULong;
typedef float example_lib_KFloat;
typedef double example_lib_KDouble;
typedef void* example_lib_KNativePtr;
typedef float example_lib_KFloat;
typedef double example_lib_KDouble;
typedef void* example_lib_KNativePtr;
struct example_lib_KType;
typedef struct example_lib_KType example_lib_KType;
typedef struct {
typedef struct
{
example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_APIHost;
typedef struct {
typedef struct
{
example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_APIHost_CACAHUETE;
typedef struct {
typedef struct
{
example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_APIHost_CAPI;
typedef struct {
typedef struct
{
example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_Request;
typedef struct {
typedef struct
{
example_lib_KNativePtr pinned;
} example_lib_kref_kotlin_collections_Map;
typedef struct {
typedef struct
{
example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_Request_Method;
typedef struct {
typedef struct
{
example_lib_KNativePtr pinned;
} example_lib_kref_kotlin_Any;
typedef struct {
typedef struct
{
example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_Request_Method_GET;
typedef struct {
typedef struct
{
example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_Request_Method_POST;
typedef struct {
typedef struct
{
example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_Request_Method_PUT;
typedef struct {
typedef struct
{
example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_Request_Method_DELETE;
typedef struct {
typedef struct
{
example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_Request_Method_PATCH;
typedef struct {
typedef struct
{
example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_Request_Response;
typedef struct {
typedef struct
{
example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_Request_Response_DataResponse;
typedef struct {
typedef struct
{
example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_Request_Response_FileResponse;
typedef struct {
typedef struct
{
example_lib_KNativePtr pinned;
} example_lib_kref_com_plangrid_example_Request_Response_ErrorResponse;
typedef struct {
typedef struct
{
example_lib_KNativePtr pinned;
} example_lib_kref_kotlin_Error;
typedef struct {
typedef struct
{
/* Service functions. */
void(*DisposeStablePointer)(example_lib_KNativePtr ptr);
void(*DisposeString)(const char* string);
example_lib_KBoolean(*IsInstance)(example_lib_KNativePtr ref, const example_lib_KType* type);
void (*DisposeStablePointer)(example_lib_KNativePtr ptr);
void (*DisposeString)(const char* string);
example_lib_KBoolean (*IsInstance)(example_lib_KNativePtr ref, const example_lib_KType* type);
/* User functions. */
struct {
struct {
struct {
struct {
struct {
struct {
struct
{
struct
{
struct
{
struct
{
struct
{
struct
{
example_lib_KType* (*_type)(void);
struct {
example_lib_kref_com_plangrid_example_APIHost(*get)(); /* enum entry for CACAHUETE. */
struct
{
example_lib_kref_com_plangrid_example_APIHost (*get)(); /* enum entry for CACAHUETE. */
} CACAHUETE;
struct {
example_lib_kref_com_plangrid_example_APIHost(*get)(); /* enum entry for CAPI. */
struct
{
example_lib_kref_com_plangrid_example_APIHost (*get)(); /* enum entry for CAPI. */
} CAPI;
} APIHost;
struct {
struct
{
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);
example_lib_kref_kotlin_collections_Map(*get_queryParams)(example_lib_kref_com_plangrid_example_Request thiz);
example_lib_kref_kotlin_collections_Map (*get_queryParams)(example_lib_kref_com_plangrid_example_Request thiz);
const char* (*get_body)(example_lib_kref_com_plangrid_example_Request thiz);
example_lib_kref_com_plangrid_example_Request_Method(*get_method)(example_lib_kref_com_plangrid_example_Request thiz);
example_lib_KBoolean(*equals)(example_lib_kref_com_plangrid_example_Request thiz, example_lib_kref_kotlin_Any other);
example_lib_KInt(*hashCode)(example_lib_kref_com_plangrid_example_Request thiz);
example_lib_kref_com_plangrid_example_Request_Method (*get_method)(example_lib_kref_com_plangrid_example_Request thiz);
example_lib_KBoolean (*equals)(example_lib_kref_com_plangrid_example_Request thiz, example_lib_kref_kotlin_Any other);
example_lib_KInt (*hashCode)(example_lib_kref_com_plangrid_example_Request thiz);
const char* (*toString)(example_lib_kref_com_plangrid_example_Request thiz);
const char* (*component1)(example_lib_kref_com_plangrid_example_Request thiz);
example_lib_kref_kotlin_collections_Map(*component2)(example_lib_kref_com_plangrid_example_Request thiz);
example_lib_kref_kotlin_collections_Map (*component2)(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(*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 {
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);
struct
{
example_lib_KType* (*_type)(void);
struct {
example_lib_kref_com_plangrid_example_Request_Method(*get)(); /* enum entry for GET. */
struct
{
example_lib_kref_com_plangrid_example_Request_Method (*get)(); /* enum entry for GET. */
} GET;
struct {
example_lib_kref_com_plangrid_example_Request_Method(*get)(); /* enum entry for POST. */
struct
{
example_lib_kref_com_plangrid_example_Request_Method (*get)(); /* enum entry for POST. */
} POST;
struct {
example_lib_kref_com_plangrid_example_Request_Method(*get)(); /* enum entry for PUT. */
struct
{
example_lib_kref_com_plangrid_example_Request_Method (*get)(); /* enum entry for PUT. */
} PUT;
struct {
example_lib_kref_com_plangrid_example_Request_Method(*get)(); /* enum entry for DELETE. */
struct
{
example_lib_kref_com_plangrid_example_Request_Method (*get)(); /* enum entry for DELETE. */
} DELETE;
struct {
example_lib_kref_com_plangrid_example_Request_Method(*get)(); /* enum entry for PATCH. */
struct
{
example_lib_kref_com_plangrid_example_Request_Method (*get)(); /* enum entry for PATCH. */
} PATCH;
} Method;
struct {
struct
{
example_lib_KType* (*_type)(void);
struct {
struct
{
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);
} DataResponse;
struct {
struct
{
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);
} FileResponse;
struct {
struct
{
example_lib_KType* (*_type)(void);
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_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);
} ErrorResponse;
struct {
int i;
struct
{
int i;
} $serializer;
} Response;
} Request;
@ -160,9 +199,9 @@ extern "C" { @@ -160,9 +199,9 @@ extern "C" {
} example_lib_ExportedSymbols;
extern example_lib_ExportedSymbols* example_lib_symbols(void);
#ifdef __cplusplus
} /* extern "C" */
} /* extern "C" */
#endif
#endif /* KONAN_EXAMPLE_LIB_H */
#endif /* KONAN_EXAMPLE_LIB_H */
// Code like below would hardly appear in practice
// but it's worth noting we don't support it

9
tests/dotnet/CSharp/AnotherUnit.cpp

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

10
tests/dotnet/CSharp/AnotherUnit.h

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

337
tests/dotnet/CSharp/CSharp.cpp

@ -4,7 +4,8 @@ Foo::Foo(const QString& name) @@ -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;
P = 50;
@ -14,7 +15,8 @@ Foo::Foo(const char* name) : publicFieldMappedToEnum(TestFlag::Flag2) @@ -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;
P = p;
@ -28,8 +30,11 @@ Foo::Foo(wchar_t ch) @@ -28,8 +30,11 @@ Foo::Foo(wchar_t ch)
{
}
Foo::Foo(const Foo& other) : A(other.A), P(other.P),
templateInAnotherUnit(other.templateInAnotherUnit), _name(other._name)
Foo::Foo(const Foo& other)
: A(other.A)
, P(other.P)
, templateInAnotherUnit(other.templateInAnotherUnit)
, _name(other._name)
{
}
@ -106,16 +111,25 @@ int Foo::getGetPropertyCall() @@ -106,16 +111,25 @@ int Foo::getGetPropertyCall()
return 1;
}
SmallPOD Foo::getSmallPod_cdecl() { return { 10000, 40000 }; }
SmallPOD Foo::getSmallPod_stdcall() { return { 10000, 40000 }; }
SmallPOD Foo::getSmallPod_thiscall() { return { 10000, 40000 }; }
SmallPOD Foo::getSmallPod_cdecl()
{
return { 10000, 40000 };
}
SmallPOD Foo::getSmallPod_stdcall()
{
return { 10000, 40000 };
}
SmallPOD Foo::getSmallPod_thiscall()
{
return { 10000, 40000 };
}
int Foo::operator ++()
int Foo::operator++()
{
return 5;
}
int Foo::operator --()
int Foo::operator--()
{
return 4;
}
@ -130,24 +144,25 @@ const Foo& Bar::operator[](int i) const @@ -130,24 +144,25 @@ const Foo& Bar::operator[](int i) const
return m_foo;
}
Quux::Quux() : _setterWithDefaultOverload(0)
Quux::Quux()
: _setterWithDefaultOverload(0)
{
}
Quux::Quux(int i) : Quux()
Quux::Quux(int i)
: Quux()
{
priv = i;
}
Quux::Quux(char c) : Quux()
Quux::Quux(char c)
: Quux()
{
}
Quux::Quux(Foo f) : Quux()
Quux::Quux(Foo f)
: Quux()
{
}
Quux::~Quux()
@ -176,7 +191,6 @@ void Quux::setSetterWithDefaultOverload(Foo* value) @@ -176,7 +191,6 @@ void Quux::setSetterWithDefaultOverload(Foo* value)
QColor::QColor(Qt::GlobalColor color)
{
}
Qux::Qux()
@ -206,7 +220,6 @@ int Qux::farAwayFunc() const @@ -206,7 +220,6 @@ int Qux::farAwayFunc() const
void Qux::obsolete()
{
}
Qux* Qux::getInterface()
@ -214,7 +227,7 @@ Qux* Qux::getInterface() @@ -214,7 +227,7 @@ Qux* Qux::getInterface()
return this;
}
void Qux::setInterface(Qux *qux)
void Qux::setInterface(Qux* qux)
{
}
@ -232,7 +245,8 @@ int Qux::type() const @@ -232,7 +245,8 @@ int Qux::type() const
return 0;
}
Bar::Bar() : index(0)
Bar::Bar()
: index(0)
{
}
@ -254,24 +268,24 @@ Foo& Bar::operator[](int i) @@ -254,24 +268,24 @@ Foo& Bar::operator[](int i)
return m_foo;
}
Bar Bar::operator *()
Bar Bar::operator*()
{
return *this;
}
const Bar& Bar::operator *(int m)
const Bar& Bar::operator*(int m)
{
index *= m;
return *this;
}
const Bar& Bar::operator ++()
const Bar& Bar::operator++()
{
++index;
return *this;
}
Bar Bar::operator ++(int i)
Bar Bar::operator++(int i)
{
Bar bar = *this;
bar.index++;
@ -293,9 +307,14 @@ int Bar::type() const @@ -293,9 +307,14 @@ int Bar::type() const
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 @@ -342,18 +361,27 @@ int AbstractProprietor::parent() const
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),
_items(Bar::Items::Item1), _itemsByValue(Bar::Items::Item1)
Proprietor::Proprietor(int i)
: AbstractProprietor(i)
, _items(Bar::Items::Item1)
, _itemsByValue(Bar::Items::Item1)
{
}
@ -403,11 +431,13 @@ long P::prop() @@ -403,11 +431,13 @@ long P::prop()
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() @@ -427,17 +457,14 @@ QFlags<TestFlag> ComplexType::returnsQFlags()
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()
@ -452,7 +479,6 @@ void P::setComplexType(const ComplexType& value) @@ -452,7 +479,6 @@ void P::setComplexType(const ComplexType& value)
void P::parent(int i)
{
}
bool P::isTest()
@ -462,12 +488,10 @@ bool P::isTest() @@ -462,12 +488,10 @@ bool P::isTest()
void P::setTest(bool value)
{
}
void P::test()
{
}
bool P::isBool()
@ -477,7 +501,6 @@ bool P::isBool() @@ -477,7 +501,6 @@ bool P::isBool()
void P::setIsBool(bool value)
{
}
void TestDestructors::InitMarker()
@ -485,12 +508,20 @@ void TestDestructors::InitMarker() @@ -485,12 +508,20 @@ void TestDestructors::InitMarker()
Marker = 0;
}
TestDestructors::TestDestructors() { Marker = 0xf00d; }
TestDestructors::~TestDestructors() { Marker = 0xcafe; }
TestDestructors::TestDestructors()
{
Marker = 0xf00d;
}
TestDestructors::~TestDestructors()
{
Marker = 0xcafe;
}
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 @@ -527,7 +558,8 @@ QFlags<Flags> UsesPointerToEnumInParamOfVirtual::hasPointerToEnumInParam(const Q
}
QFlags<Flags> UsesPointerToEnumInParamOfVirtual::callOverrideOfHasPointerToEnumInParam(
const UsesPointerToEnumInParamOfVirtual* object, const QFlags<Flags>& pointerToEnum)
const UsesPointerToEnumInParamOfVirtual* object,
const QFlags<Flags>& pointerToEnum)
{
return object->hasPointerToEnumInParam(pointerToEnum);
}
@ -542,8 +574,8 @@ UntypedFlags operator|(UntypedFlags lhs, UntypedFlags rhs) @@ -542,8 +574,8 @@ UntypedFlags operator|(UntypedFlags lhs, UntypedFlags rhs)
return static_cast<UntypedFlags>(static_cast<int>(lhs) | static_cast<int>(rhs));
}
QGenericArgument::QGenericArgument(const char* name, const void* data) :
fixedArrayInValueType { 0 }
QGenericArgument::QGenericArgument(const char* name, const void* data)
: fixedArrayInValueType{ 0 }
{
_name = name;
}
@ -599,7 +631,7 @@ MethodsWithDefaultValues::~MethodsWithDefaultValues() @@ -599,7 +631,7 @@ MethodsWithDefaultValues::~MethodsWithDefaultValues()
{
}
void MethodsWithDefaultValues::defaultPointer(Foo *ptr1, Foo *ptr2)
void MethodsWithDefaultValues::defaultPointer(Foo* ptr1, Foo* ptr2)
{
}
@ -607,7 +639,7 @@ void MethodsWithDefaultValues::defaultVoidStar(void* ptr) @@ -607,7 +639,7 @@ void MethodsWithDefaultValues::defaultVoidStar(void* ptr)
{
}
void MethodsWithDefaultValues::defaultFunctionPointer(void(*functionPtr)(int p))
void MethodsWithDefaultValues::defaultFunctionPointer(void (*functionPtr)(int p))
{
}
@ -647,11 +679,11 @@ void MethodsWithDefaultValues::defaultIntAssignedAnEnum(int i) @@ -647,11 +679,11 @@ void MethodsWithDefaultValues::defaultIntAssignedAnEnum(int i)
{
}
void MethodsWithDefaultValues::defaultRefAssignedValue(const Foo &fooRef)
void MethodsWithDefaultValues::defaultRefAssignedValue(const Foo& fooRef)
{
}
void MethodsWithDefaultValues::DefaultRefAssignedValue(const Foo &fooRef)
void MethodsWithDefaultValues::DefaultRefAssignedValue(const Foo& fooRef)
{
}
@ -717,7 +749,7 @@ void MethodsWithDefaultValues::defaultIntWithLongExpression(unsigned int i) @@ -717,7 +749,7 @@ void MethodsWithDefaultValues::defaultIntWithLongExpression(unsigned int i)
{
}
void MethodsWithDefaultValues::defaultRefTypeEnumImplicitCtor(const QColor &fillColor)
void MethodsWithDefaultValues::defaultRefTypeEnumImplicitCtor(const QColor& fillColor)
{
}
@ -891,8 +923,14 @@ void PropertyWithIgnoredType::setIgnoredType(const IgnoredType& value) @@ -891,8 +923,14 @@ void PropertyWithIgnoredType::setIgnoredType(const IgnoredType& value)
_ignoredType = value;
}
MI_A0::MI_A0() : F(50) {}
int MI_A0::get() { return F; };
MI_A0::MI_A0()
: F(50)
{
}
int MI_A0::get()
{
return F;
};
MI_A::MI_A() {}
void MI_A::v(int i) {}
@ -1010,47 +1048,49 @@ void TestOverrideFromSecondaryBase::setProperty(int value) @@ -1010,47 +1048,49 @@ void TestOverrideFromSecondaryBase::setProperty(int value)
int TestParamToInterfacePassBaseTwo::getM()
{
return m;
return m;
}
void TestParamToInterfacePassBaseTwo::setM(int n)
{
m = n;
m = n;
}
const TestParamToInterfacePassBaseTwo& TestParamToInterfacePassBaseTwo::operator++()
{
++m;
return *this;
++m;
return *this;
}
TestParamToInterfacePassBaseTwo::TestParamToInterfacePassBaseTwo()
{
m = 0;
m = 0;
}
TestParamToInterfacePassBaseTwo::TestParamToInterfacePassBaseTwo(int n)
{
m = n;
m = n;
}
TestParamToInterfacePassBaseTwo TestParamToInterfacePass::addM(TestParamToInterfacePassBaseTwo b)
{
this->setM(this->getM() + b.getM());
return *this;
this->setM(this->getM() + b.getM());
return *this;
}
TestParamToInterfacePassBaseTwo TestParamToInterfacePass::operator+(TestParamToInterfacePassBaseTwo b)
{
return TestParamToInterfacePassBaseTwo(this->getM() + b.getM());
return TestParamToInterfacePassBaseTwo(this->getM() + b.getM());
}
TestParamToInterfacePass::TestParamToInterfacePass(TestParamToInterfacePassBaseTwo b)
{
this->setM(b.getM());
this->setM(b.getM());
}
TestParamToInterfacePass::TestParamToInterfacePass() : TestParamToInterfacePassBaseOne(), TestParamToInterfacePassBaseTwo()
TestParamToInterfacePass::TestParamToInterfacePass()
: TestParamToInterfacePassBaseOne()
, TestParamToInterfacePassBaseTwo()
{
}
@ -1066,9 +1106,9 @@ void freeFunctionWithUnsupportedDefaultArg(Foo foo) @@ -1066,9 +1106,9 @@ void freeFunctionWithUnsupportedDefaultArg(Foo foo)
{
}
int TypeMappedWithOperator::operator |(int i)
int TypeMappedWithOperator::operator|(int i)
{
return 0;
return 0;
}
void HasPropertyWithDerivedType::causeRenamingError()
@ -1093,7 +1133,7 @@ void MultiOverloadPtrToRef::funcPrimitivePtrToRefWithMultiOverload(int* pOne, ch @@ -1093,7 +1133,7 @@ void MultiOverloadPtrToRef::funcPrimitivePtrToRefWithMultiOverload(int* pOne, ch
MultiOverloadPtrToRef::MultiOverloadPtrToRef(int* param)
{
arr = new int[3]{0};
arr = new int[3]{ 0 };
}
int* MultiOverloadPtrToRef::ReturnPrimTypePtr()
@ -1126,12 +1166,12 @@ void TestOutTypeInterfaces::funcTryInterfaceTypeOut(CS_OUT TestParamToInterfaceP @@ -1126,12 +1166,12 @@ void TestOutTypeInterfaces::funcTryInterfaceTypeOut(CS_OUT TestParamToInterfaceP
{
}
int PassConstantArrayRef(int(&arr)[2])
int PassConstantArrayRef(int (&arr)[2])
{
return arr[0];
}
bool TestComparison::operator ==(const TestComparison& other) const
bool TestComparison::operator==(const TestComparison& other) const
{
return A == other.A && B == other.B;
}
@ -1161,7 +1201,8 @@ void QObject::event() @@ -1161,7 +1201,8 @@ void QObject::event()
{
}
QPaintDevice::QPaintDevice() : test(0)
QPaintDevice::QPaintDevice()
: test(0)
{
}
@ -1209,15 +1250,18 @@ InheritsFromHasSamePropertyInDerivedAbstractType::~InheritsFromHasSamePropertyIn @@ -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)
{
}
@ -1228,7 +1272,7 @@ VirtualDtorAddedInDerived::~VirtualDtorAddedInDerived() @@ -1228,7 +1272,7 @@ VirtualDtorAddedInDerived::~VirtualDtorAddedInDerived()
bool VirtualDtorAddedInDerived::dtorCalled = false;
void NamespaceB::B::Function(CS_OUT NamespaceA::A &a)
void NamespaceB::B::Function(CS_OUT NamespaceA::A& a)
{
}
@ -1284,7 +1328,7 @@ int HasConflictWithAbstractProperty::conflictWithProperty() @@ -1284,7 +1328,7 @@ int HasConflictWithAbstractProperty::conflictWithProperty()
int TestOverrideOfPropertyInNamespacedClass::property()
{
return 0;
return 0;
}
const char* HasVirtualTakesReturnsProblematicTypes::virtualTakesAndReturnsString(const char* c)
@ -1316,18 +1360,20 @@ const unsigned char StaticVariables::UChr = (unsigned char)'G'; @@ -1316,18 +1360,20 @@ const unsigned char StaticVariables::UChr = (unsigned char)'G';
const int StaticVariables::Int = 1020304050;
const float StaticVariables::Float = 0.5020f;
const std::string StaticVariables::String = "Str";
const char StaticVariables::ChrArray[2] { 'A', 'B' };
const int StaticVariables::IntArray[2] { 1020304050, 1526374850 };
const float StaticVariables::FloatArray[2] { 0.5020f, 0.6020f };
const bool StaticVariables::BoolArray[2] { false, true };
const void* StaticVariables::VoidPtrArray[2] { (void*)0x10203040, (void*)0x40302010 };
const char StaticVariables::ChrArray[2]{ 'A', 'B' };
const int StaticVariables::IntArray[2]{ 1020304050, 1526374850 };
const float StaticVariables::FloatArray[2]{ 0.5020f, 0.6020f };
const bool StaticVariables::BoolArray[2]{ false, true };
const void* StaticVariables::VoidPtrArray[2]{ (void*)0x10203040, (void*)0x40302010 };
TestString::TestString() : unicodeConst(L"ქართული ენა"), unicode(0)
TestString::TestString()
: unicodeConst(L"ქართული ენა")
, unicode(0)
{
}
TestChar32String::TestChar32String() :
thirtyTwoBitConst(U"ქართული ენა")
TestChar32String::TestChar32String()
: thirtyTwoBitConst(U"ქართული ენა")
{
static std::u32string nonConst = U"Test String";
thirtyTwoBitNonConst = &nonConst[0];
@ -1340,11 +1386,14 @@ void TestChar32String::UpdateString(const char32_t* s) @@ -1340,11 +1386,14 @@ void TestChar32String::UpdateString(const char32_t* s)
thirtyTwoBitConst = nativeOwnedMemory.data();
}
const char32_t* TestChar32String::RetrieveString() { return thirtyTwoBitConst; }
void TestChar32String::functionPointerUTF32(void(*ptr)(const char32_t*)) {}
const char32_t* TestChar32String::RetrieveString()
{
return thirtyTwoBitConst;
}
void TestChar32String::functionPointerUTF32(void (*ptr)(const char32_t*)) {}
TestChar16String::TestChar16String() :
sixteenBitConst(u"ქართული ენა")
TestChar16String::TestChar16String()
: sixteenBitConst(u"ქართული ენა")
{
static std::u16string nonConst = u"Test String";
sixteenBitNonConst = &nonConst[0];
@ -1357,7 +1406,10 @@ void TestChar16String::UpdateString(const char16_t* s) @@ -1357,7 +1406,10 @@ void TestChar16String::UpdateString(const char16_t* s)
static std::u16string nativeOwnedMemory = s;
sixteenBitConst = nativeOwnedMemory.data();
}
const char16_t* TestChar16String::RetrieveString() { return sixteenBitConst; }
const char16_t* TestChar16String::RetrieveString()
{
return sixteenBitConst;
}
void decltypeFunctionPointer() {}
@ -1399,7 +1451,8 @@ AbstractSecondaryBase::~AbstractSecondaryBase() @@ -1399,7 +1451,8 @@ AbstractSecondaryBase::~AbstractSecondaryBase()
{
}
ImplementsAbstractsFromPrimaryAndSecondary::ImplementsAbstractsFromPrimaryAndSecondary() : field(200)
ImplementsAbstractsFromPrimaryAndSecondary::ImplementsAbstractsFromPrimaryAndSecondary()
: field(200)
{
}
@ -1445,19 +1498,21 @@ void hasArrayOfConstChar(const char* const arrayOfConstChar[]) @@ -1445,19 +1498,21 @@ void hasArrayOfConstChar(const char* const arrayOfConstChar[])
{
}
struct IncompleteStruct {};
struct IncompleteStruct
{};
IncompleteStruct* createIncompleteStruct()
{
return new IncompleteStruct();
}
DLL_API void useIncompleteStruct(IncompleteStruct * a)
DLL_API void useIncompleteStruct(IncompleteStruct* a)
{
return;
}
struct DuplicateDeclaredStruct {
struct DuplicateDeclaredStruct
{
int i = 0;
};
@ -1485,11 +1540,15 @@ DLL_API int useDuplicateDeclaredStruct(DuplicateDeclaredStruct* s) @@ -1485,11 +1540,15 @@ DLL_API int useDuplicateDeclaredStruct(DuplicateDeclaredStruct* s)
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 @@ -1531,8 +1590,7 @@ int TestArrays::takeArrays(Foo* arrayOfPointersToObjects[], int arrayOfPrimitive
arrayOfObjects[0].A + arrayOfObjects[1].A;
}
int TestArrays::takeArrays(Foo* fixedArrayOfPointersToObjects[3], int fixedArrayOfPrimitives[4],
int* fixedArrayOfPointersToPrimitives[5]) const
int TestArrays::takeArrays(Foo* fixedArrayOfPointersToObjects[3], int fixedArrayOfPrimitives[4], int* fixedArrayOfPointersToPrimitives[5]) const
{
int sum = 0;
for (int i = 0; i < 3; i++)
@ -1570,12 +1628,13 @@ int TestArrays::virtualTakeArrays(Foo* arrayOfPointersToObjects[], int arrayOfPr @@ -1570,12 +1628,13 @@ int TestArrays::virtualTakeArrays(Foo* arrayOfPointersToObjects[], int arrayOfPr
return takeArrays(arrayOfPointersToObjects, arrayOfPrimitives, arrayOfObjects);
}
int TestArrays::virtualTakeArrays(Foo *fixedArrayOfPointersToObjects[3], int fixedArrayOfPrimitives[4], int *fixedArrayOfPointersToPrimitives[5]) const
int TestArrays::virtualTakeArrays(Foo* fixedArrayOfPointersToObjects[3], int fixedArrayOfPrimitives[4], int* fixedArrayOfPointersToPrimitives[5]) const
{
return takeArrays(fixedArrayOfPointersToObjects, fixedArrayOfPrimitives, fixedArrayOfPointersToPrimitives);
}
InterfaceTester::InterfaceTester() : interface(0)
InterfaceTester::InterfaceTester()
: interface(0)
{
}
@ -1625,7 +1684,7 @@ const char*& takeConstCharStarRef(const char*& c) @@ -1625,7 +1684,7 @@ const char*& takeConstCharStarRef(const char*& c)
const void*& rValueReferenceToPointer(void*&& v)
{
return (const void*&) v;
return (const void*&)v;
}
const Foo*& takeReturnReferenceToPointer(const Foo*& foo)
@ -1678,15 +1737,32 @@ const char32_t* TestCSharpString32(const char32_t* in, const char32_t** out) @@ -1678,15 +1737,32 @@ const char32_t* TestCSharpString32(const char32_t* in, const char32_t** out)
return ret.data();
}
ConversionFunctions::operator short* () { return &field; }
ConversionFunctions::operator short& () { return field; }
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]
ConversionFunctions::operator short*()
{
return &field;
}
ConversionFunctions::operator short&()
{
return field;
}
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, align16),
offsetof(ClassCustomTypeAlignment, align1),
@ -1694,33 +1770,52 @@ const unsigned ClassCustomTypeAlignmentOffsets[5] @@ -1694,33 +1770,52 @@ const unsigned ClassCustomTypeAlignmentOffsets[5]
offsetof(ClassCustomTypeAlignment, align8),
};
const unsigned ClassCustomObjectAlignmentOffsets[2] {
const unsigned ClassCustomObjectAlignmentOffsets[2]{
offsetof(ClassCustomObjectAlignment, boolean),
offsetof(ClassCustomObjectAlignment, charAligned8),
};
const unsigned ClassMicrosoftObjectAlignmentOffsets[4]
{
const unsigned ClassMicrosoftObjectAlignmentOffsets[4]{
offsetof(ClassMicrosoftObjectAlignment, u8),
offsetof(ClassMicrosoftObjectAlignment, dbl),
offsetof(ClassMicrosoftObjectAlignment, i16),
offsetof(ClassMicrosoftObjectAlignment, boolean),
};
const unsigned StructWithEmbeddedArrayOfStructObjectAlignmentOffsets[2]
{
const unsigned StructWithEmbeddedArrayOfStructObjectAlignmentOffsets[2]{
offsetof(StructWithEmbeddedArrayOfStructObjectAlignment, boolean),
offsetof(StructWithEmbeddedArrayOfStructObjectAlignment, embedded_struct),
};
DLL_API FTIStruct TestFunctionToStaticMethod(FTIStruct* bb) { return { 6 }; }
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 FTIStruct TestFunctionToStaticMethod(FTIStruct* bb)
{
return { 6 };
}
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, FTIStruct& value) { return value.a * value.a; }
DLL_API int TestClassFunctionToInstanceMethod(TestClass* bb, int value)
{
return value * value;
}
DLL_API int TestClassFunctionToInstanceMethod(TestClass* bb, FTIStruct& value)
{
return value.a * value.a;
}
int RuleOfThreeTester::constructorCalls = 0;
int RuleOfThreeTester::destructorCalls = 0;

448
tests/dotnet/CSharp/CSharp.h

@ -32,7 +32,7 @@ public: @@ -32,7 +32,7 @@ public:
int& operator[](int i);
int A;
int* (*functionPtrReturnsPtrParam)();
int (STDCALL *attributedFunctionPtr)();
int(STDCALL* attributedFunctionPtr)();
bool isNoParams();
void setNoParams();
void foo(int i);
@ -51,8 +51,8 @@ public: @@ -51,8 +51,8 @@ public:
SmallPOD STDCALL getSmallPod_stdcall();
SmallPOD THISCALL getSmallPod_thiscall();
int operator ++();
int operator --();
int operator++();
int operator--();
operator const char*() const;
bool btest[5];
@ -150,13 +150,16 @@ class DLL_API ForceCreationOfInterface : public Foo, public Bar @@ -150,13 +150,16 @@ class DLL_API ForceCreationOfInterface : public Foo, public Bar
class DLL_API Baz : public Foo, public Bar
{
public:
class NestedBase1 {
class NestedBase1
{
int f1;
double f2;
void* f3;
};
class NestedBase2 {};
class NestedDerived : public NestedBase1, public NestedBase2 {};
class NestedBase2
{};
class NestedDerived : public NestedBase1, public NestedBase2
{};
Baz();
Baz(Bar::Items item);
@ -168,7 +171,7 @@ public: @@ -168,7 +171,7 @@ public:
void setMethod(ProtectedNestedEnum value);
int type() const override;
typedef bool (*FunctionTypedef)(const void *);
typedef bool (*FunctionTypedef)(const void*);
FunctionTypedef functionTypedef;
};
@ -222,6 +225,7 @@ public: @@ -222,6 +225,7 @@ public:
Bar::Items itemsByValue() const;
void setItemsByValue(Bar::Items value);
private:
Bar::Items _items;
Bar::Items _itemsByValue;
@ -238,6 +242,7 @@ public: @@ -238,6 +242,7 @@ public:
int check();
QFlags<TestFlag> returnsQFlags();
void takesQFlags(const QFlags<int> f);
private:
QFlags<TestFlag> qFlags;
};
@ -293,6 +298,7 @@ public: @@ -293,6 +298,7 @@ public:
void name();
void Name();
int property();
protected:
int _property;
};
@ -317,7 +323,8 @@ public: @@ -317,7 +323,8 @@ public:
virtual ~UsesPointerToEnumInParamOfVirtual();
virtual QFlags<Flags> hasPointerToEnumInParam(const QFlags<Flags>& pointerToEnum) const;
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);
@ -334,8 +341,9 @@ UntypedFlags operator|(UntypedFlags lhs, UntypedFlags rhs); @@ -334,8 +341,9 @@ UntypedFlags operator|(UntypedFlags lhs, UntypedFlags rhs);
struct DLL_API QGenericArgument
{
public:
QGenericArgument(const char* name = 0, const void *data = 0);
QGenericArgument(const char* name = 0, const void* data = 0);
void* fixedArrayInValueType[1];
private:
const char* _name;
};
@ -346,13 +354,13 @@ class TestObjectMapWithClassDerivedFromStruct : public QGenericArgument @@ -346,13 +354,13 @@ class TestObjectMapWithClassDerivedFromStruct : public QGenericArgument
#define DEFAULT_INT (2 * 1000UL + 500UL)
namespace Qt
namespace Qt {
enum GlobalColor
{
enum GlobalColor {
black,
white,
};
}
black,
white,
};
} // namespace Qt
class DLL_API QColor
{
@ -383,14 +391,13 @@ public: @@ -383,14 +391,13 @@ public:
QRect(QPoint p, QSize s);
};
namespace lowerCaseNameSpace
namespace lowerCaseNameSpace {
enum class Enum
{
enum class Enum
{
Item1,
Item2
};
}
Item1,
Item2
};
} // namespace lowerCaseNameSpace
class DLL_API DefaultZeroMappedToEnum
{
@ -402,7 +409,8 @@ enum class Empty : unsigned long long int @@ -402,7 +409,8 @@ enum class Empty : unsigned long long int
{
};
class _ClassWithLeadingUnderscore {
class _ClassWithLeadingUnderscore
{
};
const int ConstFlag1 = 1;
@ -432,7 +440,7 @@ public: @@ -432,7 +440,7 @@ public:
~MethodsWithDefaultValues();
void defaultPointer(Foo* ptr1 = 0, Foo* ptr2 = nullptr);
void defaultVoidStar(void* ptr = 0);
void defaultFunctionPointer(void(*functionPtr)(int p) = nullptr);
void defaultFunctionPointer(void (*functionPtr)(int p) = nullptr);
void defaultValueType(QGenericArgument valueType = QGenericArgument());
void defaultChar(char c = 'a', char uc = u'u', char Uc = U'U', char Lc = L'L', unsigned char b = 'z');
void defaultString(const wchar_t* wideString = L"Str");
@ -464,7 +472,7 @@ public: @@ -464,7 +472,7 @@ public:
void defaultImplicitCtorEnum(Baz arg = Bar::Item1);
void defaultImplicitCtorEnumTwo(Bar arg = Bar::Items::Item1);
void defaultIntWithLongExpression(unsigned int i = DEFAULT_INT);
void defaultRefTypeEnumImplicitCtor(const QColor &fillColor = Qt::white);
void defaultRefTypeEnumImplicitCtor(const QColor& fillColor = Qt::white);
void rotate4x4Matrix(float angle, float x, float y, float z = 0.0f);
void defaultPointerToValueType(QGenericArgument* pointer = 0);
void defaultDoubleWithoutF(double d1 = 1.0, double d2 = 1.);
@ -492,6 +500,7 @@ public: @@ -492,6 +500,7 @@ public:
SmallPOD* defaultWithNonPrimitiveType(SmallPOD& pod = DefaultSmallPODInstance);
int DefaultWithParamNamedSameAsMethod(int DefaultWithParamNamedSameAsMethod, const Foo& defaultArg = Foo());
int getA();
private:
Foo m_foo;
};
@ -502,6 +511,7 @@ class HasPureVirtualWithDefaultArg @@ -502,6 +511,7 @@ class HasPureVirtualWithDefaultArg
public:
virtual ~HasPureVirtualWithDefaultArg() {}
virtual void pureVirtualWithDefaultArg(Foo* foo = nullptr) = 0;
protected:
HasPureVirtualWithDefaultArg() {}
};
@ -510,8 +520,10 @@ class DLL_API HasOverridesWithChangedAccessBase @@ -510,8 +520,10 @@ class DLL_API HasOverridesWithChangedAccessBase
{
public:
virtual void privateOverride(int i = 5);
protected:
virtual void publicOverride();
private:
virtual void differentIncreasedAccessOverride();
};
@ -520,6 +532,7 @@ class DLL_API HasOverridesWithChangedAccess : public HasOverridesWithChangedAcce @@ -520,6 +532,7 @@ class DLL_API HasOverridesWithChangedAccess : public HasOverridesWithChangedAcce
{
public:
void publicOverride();
private:
virtual void privateOverride(int i);
};
@ -544,9 +557,7 @@ public: @@ -544,9 +557,7 @@ public:
virtual int property() = 0;
};
class DLL_API IgnoredType
{
};
class DLL_API IgnoredType{};
class DLL_API IgnoredTypeInheritingNonIgnoredWithNoEmptyCtor : public P
{
@ -555,8 +566,9 @@ class DLL_API IgnoredTypeInheritingNonIgnoredWithNoEmptyCtor : public P @@ -555,8 +566,9 @@ class DLL_API IgnoredTypeInheritingNonIgnoredWithNoEmptyCtor : public P
class DLL_API HasOverriddenInManaged
{
public:
void setOverriddenInManaged(Baz *value);
void setOverriddenInManaged(Baz* value);
int callOverriddenInManaged();
private:
Baz* overriddenInManaged = 0;
};
@ -566,6 +578,7 @@ class DLL_API PropertyWithIgnoredType @@ -566,6 +578,7 @@ class DLL_API PropertyWithIgnoredType
public:
IgnoredType ignoredType();
void setIgnoredType(const IgnoredType& value);
private:
IgnoredType _ignoredType;
};
@ -611,8 +624,10 @@ public: @@ -611,8 +624,10 @@ public:
StructWithPrivateFields(int simplePrivateField, Foo complexPrivateField);
int getSimplePrivateField();
Foo getComplexPrivateField();
protected:
int protectedField;
private:
int simplePrivateField;
Foo complexPrivateField;
@ -629,14 +644,15 @@ class QMap @@ -629,14 +644,15 @@ class QMap
};
public:
QMap(const QMap<Key, T> &other);
QMap(const QMap<Key, T>& other);
class const_iterator;
class iterator
{
public:
int test() {
int test()
{
return 1;
}
friend class const_iterator;
@ -653,11 +669,32 @@ public: @@ -653,11 +669,32 @@ public:
};
#define Q_PROCESSOR_WORDSIZE 8
template <int> struct QIntegerForSize;
template <> struct QIntegerForSize<1> { 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; };
template <int>
struct QIntegerForSize;
template <>
struct QIntegerForSize<1>
{
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>::Unsigned qregisteruint;
@ -684,6 +721,7 @@ public: @@ -684,6 +721,7 @@ public:
virtual ~HasVirtualDtor2();
HasVirtualDtor1* getHasVirtualDtor1();
virtual void virtualFunction(const HasVirtualDtor1& param1, const HasVirtualDtor1& param2);
private:
HasVirtualDtor1* hasVirtualDtor1;
};
@ -696,6 +734,7 @@ public: @@ -696,6 +734,7 @@ public:
HasVirtualDtor2* getHasVirtualDtor2();
Bar* propertyWithNoVirtualDtor() const;
void setPropertyWithNoVirtualDtor(Bar* bar);
private:
HasVirtualDtor2* hasVirtualDtor2;
Bar* bar;
@ -727,13 +766,12 @@ public: @@ -727,13 +766,12 @@ public:
void setProperty(int value);
};
class DLL_API TestParamToInterfacePassBaseOne
{
};
class DLL_API TestParamToInterfacePassBaseOne{};
class DLL_API TestParamToInterfacePassBaseTwo
{
int m;
public:
int getM();
void setM(int n);
@ -772,7 +810,7 @@ void DLL_API freeFunctionWithUnsupportedDefaultArg(Foo foo = Foo()); @@ -772,7 +810,7 @@ void DLL_API freeFunctionWithUnsupportedDefaultArg(Foo foo = Foo());
class DLL_API TypeMappedWithOperator
{
public:
int operator |(int i);
int operator|(int i);
};
class HasOverrideOfHasPropertyWithDerivedType;
@ -792,10 +830,11 @@ public: @@ -792,10 +830,11 @@ public:
class DLL_API MultiOverloadPtrToRef
{
int * arr;
int* arr;
public:
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);
void funcPrimitivePtrToRefWithDefVal(int* pOne, char* pTwo, Foo* pThree, int* pFour = 0);
virtual void funcPrimitivePtrToRefWithMultiOverload(int* pOne, char* pTwo, Foo* pThree, int* pFour = 0, long* pFive = 0);
@ -849,14 +888,14 @@ class DLL_API DerivesFromTemplateInstantiation : public TemplateWithDependentFie @@ -849,14 +888,14 @@ class DLL_API DerivesFromTemplateInstantiation : public TemplateWithDependentFie
{
};
DLL_API int PassConstantArrayRef(int(&arr)[2]);
DLL_API int PassConstantArrayRef(int (&arr)[2]);
class DLL_API TestComparison
{
public:
int A;
float B;
bool operator ==(const TestComparison& other) const;
bool operator==(const TestComparison& other) const;
};
class DLL_API OverridePropertyFromIndirectPrimaryBaseBase
@ -906,6 +945,7 @@ class DLL_API QWidget : public QObject, QPaintDevice @@ -906,6 +945,7 @@ class DLL_API QWidget : public QObject, QPaintDevice
public:
QWidget();
virtual void event();
private:
QObject child;
};
@ -971,26 +1011,23 @@ class DLL_API ClassWithVirtualBase : public virtual Foo @@ -971,26 +1011,23 @@ class DLL_API ClassWithVirtualBase : public virtual Foo
{
};
namespace NamespaceA
{
CS_VALUE_TYPE class DLL_API A
{
};
namespace NamespaceA {
CS_VALUE_TYPE class DLL_API A{};
}
namespace NamespaceB
namespace NamespaceB {
class DLL_API B
{
class DLL_API B
{
public:
void Function(CS_OUT NamespaceA::A &a);
};
}
public:
void Function(CS_OUT NamespaceA::A& a);
};
} // namespace NamespaceB
class DLL_API HasPrivateVirtualProperty
{
public:
virtual ~HasPrivateVirtualProperty();
private:
virtual int property();
virtual void protectedAbstractMethod() = 0;
@ -1004,6 +1041,7 @@ protected: @@ -1004,6 +1041,7 @@ protected:
virtual void protectedAbstractMethod();
virtual void protectedMethod();
virtual int protectedProperty();
private:
virtual int property();
};
@ -1031,13 +1069,15 @@ public: @@ -1031,13 +1069,15 @@ public:
// https://github.com/mono/CppSharp/issues/1283
namespace NamespaceWithVirtualPropertyClass {
class DLL_API HasOverriddenPropertyInNamespacedClass {
public:
virtual int property() = 0;
};
}
class DLL_API HasOverriddenPropertyInNamespacedClass
{
public:
virtual int property() = 0;
};
} // namespace NamespaceWithVirtualPropertyClass
class DLL_API TestOverrideOfPropertyInNamespacedClass : public NamespaceWithVirtualPropertyClass::HasOverriddenPropertyInNamespacedClass {
class DLL_API TestOverrideOfPropertyInNamespacedClass : public NamespaceWithVirtualPropertyClass::HasOverriddenPropertyInNamespacedClass
{
public:
virtual int property() override;
};
@ -1068,7 +1108,8 @@ public: @@ -1068,7 +1108,8 @@ public:
DLL_API extern const unsigned char variableWithFixedPrimitiveArray[2];
DLL_API extern const unsigned int variableWithVariablePrimitiveArray[];
class DLL_API StaticVariables {
class DLL_API StaticVariables
{
public:
static const bool Boolean;
static const char Chr;
@ -1083,40 +1124,72 @@ public: @@ -1083,40 +1124,72 @@ public:
static const void* VoidPtrArray[2];
};
DLL_API constexpr double ConstexprCreateDoubleValue(double value) {
DLL_API constexpr double ConstexprCreateDoubleValue(double value)
{
return value;
}
class DLL_API VariablesWithInitializer {
public:
static constexpr const char* String = "Str";
static constexpr const wchar_t* WideString = L"Str";
static constexpr bool Boolean = true;
static constexpr char Chr = 'G';
static constexpr unsigned char UChr = (unsigned char)'G';
static constexpr int Int = 1020304050;
static constexpr int IntSum = Int + 500;
static constexpr float Float = 0.5020f;
static constexpr double Double = 0.700020235;
static constexpr double DoubleSum = 0.700020235 + 23.17376;
static constexpr double DoubleFromConstexprFunction = ConstexprCreateDoubleValue(0.700020235 + 23.17376);
static constexpr int64_t Int64 = 602030405045;
static constexpr uint64_t UInt64 = 9602030405045;
static constexpr const char* StringArray1[1] { "Str" "F,\"or" };
static constexpr const char* StringArray3[3] { "Str" "F,\"or", "C#", String };
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",
};
static constexpr const char* StringArray3EmptyInitList[3] { };
static constexpr const wchar_t* WideStringArray[2] { L"Str", L"C#" };
static constexpr char ChrArray[2] { 'A', 'B' };
static constexpr unsigned char ByteArray[2] { 'A', 10 };
static constexpr int IntArray[2] = { 1020304050, 1526374850 };
static constexpr int IntArray3[3] = { 1020304050, 1526374850 };
static constexpr bool BoolArray[2] { false, true };
static constexpr float FloatArray[2] { 0.5020f, 0.6020f };
class DLL_API VariablesWithInitializer
{
public:
static constexpr const char* String = "Str";
static constexpr const wchar_t* WideString = L"Str";
static constexpr bool Boolean = true;
static constexpr char Chr = 'G';
static constexpr unsigned char UChr = (unsigned char)'G';
static constexpr int Int = 1020304050;
static constexpr int IntSum = Int + 500;
static constexpr float Float = 0.5020f;
static constexpr double Double = 0.700020235;
static constexpr double DoubleSum = 0.700020235 + 23.17376;
static constexpr double DoubleFromConstexprFunction = ConstexprCreateDoubleValue(0.700020235 + 23.17376);
static constexpr int64_t Int64 = 602030405045;
static constexpr uint64_t UInt64 = 9602030405045;
static constexpr const char* StringArray1[1]{ "Str"
"F,\"or" };
static constexpr const char* StringArray3[3]{ "Str"
"F,\"or",
"C#", String };
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",
};
static constexpr const char* StringArray3EmptyInitList[3]{};
static constexpr const wchar_t* WideStringArray[2]{ L"Str", L"C#" };
static constexpr char ChrArray[2]{ 'A', 'B' };
static constexpr unsigned char ByteArray[2]{ 'A', 10 };
static constexpr int IntArray[2] = { 1020304050, 1526374850 };
static constexpr int IntArray3[3] = { 1020304050, 1526374850 };
static constexpr bool BoolArray[2]{ false, true };
static constexpr float FloatArray[2]{ 0.5020f, 0.6020f };
};
// Try to precipitate an ArgumentOutOfRangeException in ExpressionHelper.CheckForString.
@ -1151,7 +1224,7 @@ public: @@ -1151,7 +1224,7 @@ public:
void UpdateString(const char32_t* s);
const char32_t* RetrieveString();
void functionPointerUTF32(void(*ptr)(const char32_t*));
void functionPointerUTF32(void (*ptr)(const char32_t*));
};
class DLL_API TestChar16String
@ -1213,6 +1286,7 @@ class DLL_API HasMissingObjectOnVirtualCall @@ -1213,6 +1286,7 @@ class DLL_API HasMissingObjectOnVirtualCall
public:
int makeMissingObjectOnVirtualCall();
void setMissingObjectOnVirtualCall(MissingObjectOnVirtualCall* value);
private:
MissingObjectOnVirtualCall* stackOverflowOnVirtualCall;
};
@ -1242,6 +1316,7 @@ public: @@ -1242,6 +1316,7 @@ public:
virtual int abstractInSecondaryBase();
virtual int abstractReturnsFieldInPrimaryBase();
virtual int abstractReturnsFieldInSecondaryBase();
private:
int field;
};
@ -1257,6 +1332,7 @@ class DLL_API HasGetterAndOverriddenSetter : public HasBaseSetter @@ -1257,6 +1332,7 @@ class DLL_API HasGetterAndOverriddenSetter : public HasBaseSetter
public:
void setBaseSetter(int value);
int baseSetter();
protected:
int field;
};
@ -1275,7 +1351,8 @@ struct DLL_API DuplicateDeclaredStruct; @@ -1275,7 +1351,8 @@ struct DLL_API DuplicateDeclaredStruct;
DLL_API DuplicateDeclaredStruct* createDuplicateDeclaredStruct(int i);
DLL_API int useDuplicateDeclaredStruct(DuplicateDeclaredStruct* s);
struct DLL_API ForwardDeclaredStruct {
struct DLL_API ForwardDeclaredStruct
{
int i = 0;
};
@ -1291,22 +1368,26 @@ struct StructTestArrayTypeFromTypedef @@ -1291,22 +1368,26 @@ struct StructTestArrayTypeFromTypedef
#define MY_MACRO_TEST_1 '1'
#define MY_MACRO_TEST_2 '2'
#define MY_MACRO_TEST2_0 0_invalid
#define MY_MACRO_TEST2_1 1
#define MY_MACRO_TEST2_2 0x2
#define MY_MACRO_TEST2_3 (1 << 2)
#define MY_MACRO_TEST2_1_2 (MY_MACRO_TEST2_1 | MY_MACRO_TEST2_2)
#define MY_MACRO_TEST2_0 0_invalid
#define MY_MACRO_TEST2_1 1
#define MY_MACRO_TEST2_2 0x2
#define MY_MACRO_TEST2_3 (1 << 2)
#define MY_MACRO_TEST2_1_2 (MY_MACRO_TEST2_1 | MY_MACRO_TEST2_2)
#define MY_MACRO_TEST2_1_2_3 (MY_MACRO_TEST2_1 | MY_MACRO_TEST2_2 | \
MY_MACRO_TEST2_3)
#define MY_MACRO_TEST2_4 (1 << 3)
#define MY_MACRO_TEST2_ALL (1 << 4) - 1
MY_MACRO_TEST2_3)
#define MY_MACRO_TEST2_4 (1 << 3)
#define MY_MACRO_TEST2_ALL (1 << 4) - 1
#define SIGNED_MACRO_VALUES_TO_ENUM_TEST_1 1 << 5
#define SIGNED_MACRO_VALUES_TO_ENUM_TEST_2 1 << 22
#define SIGNED_MACRO_VALUES_TO_ENUM_TEST_3 1L << 32
#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
struct DLL_API ComplexArrayElement
@ -1337,7 +1418,7 @@ extern const ComplexArrayElement ArrayOfVariableSize[]; @@ -1337,7 +1418,7 @@ extern const ComplexArrayElement ArrayOfVariableSize[];
DLL_API void useStdStringJustAsParameter(std::string s);
typedef int (typedefedFuncPtr)(Foo* a, Bar b);
typedef int(typedefedFuncPtr)(Foo* a, Bar b);
int DLL_API funcWithTypedefedFuncPtrAsParam(typedefedFuncPtr* func);
class DLL_API TestDuplicateDelegate
@ -1347,22 +1428,19 @@ public: @@ -1347,22 +1428,19 @@ public:
};
inline namespace InlineNamespace
{
DLL_API void FunctionInsideInlineNamespace();
inline namespace InlineNamespace {
DLL_API void FunctionInsideInlineNamespace();
}
class DLL_API TestArrays
{
public:
int takeArrays(Foo* arrayOfPointersToObjects[], int arrayOfPrimitives[], Foo arrayOfObjects[]) const;
int takeArrays(Foo* fixedArrayOfPointersToObjects[3], int fixedArrayOfPrimitives[4],
int* fixedArrayOfPointersToPrimitives[5]) const;
int takeArrays(Foo* fixedArrayOfPointersToObjects[3], int fixedArrayOfPrimitives[4], int* fixedArrayOfPointersToPrimitives[5]) const;
std::string takeStringArray(const char* arrayOfStrings[]);
std::string takeConstStringArray(const char* const arrayOfStrings[]);
virtual int virtualTakeArrays(Foo* arrayOfPointersToObjects[], int arrayOfPrimitives[], Foo arrayOfObjects[]) const;
virtual int virtualTakeArrays(Foo* fixedArrayOfPointersToObjects[3], int fixedArrayOfPrimitives[4],
int* fixedArrayOfPointersToPrimitives[5]) const;
virtual int virtualTakeArrays(Foo* fixedArrayOfPointersToObjects[3], int fixedArrayOfPrimitives[4], int* fixedArrayOfPointersToPrimitives[5]) const;
};
@ -1376,14 +1454,11 @@ public: @@ -1376,14 +1454,11 @@ public:
Foo* fixedArrayOfPointers[3];
};
struct DLL_API CSharp
{
};
struct DLL_API CSharp{};
static int FOOBAR_CONSTANT = 42;
class DLL_API SimpleInterface
{
public:
@ -1401,6 +1476,7 @@ public: @@ -1401,6 +1476,7 @@ public:
int size();
void* get(int n);
void setInterface(SimpleInterface* i);
private:
SimpleInterface* interface;
};
@ -1409,7 +1485,7 @@ class DLL_API HasFunctionPtrField @@ -1409,7 +1485,7 @@ class DLL_API HasFunctionPtrField
{
public:
int (*functionPtrField)(const char*);
int (*functionPtrTakeFunctionPtrField)(int(*TakenInFuncPtrField)());
int (*functionPtrTakeFunctionPtrField)(int (*TakenInFuncPtrField)());
};
DLL_API void va_listFunction(va_list v);
@ -1423,14 +1499,19 @@ typedef QFlags<TestFlag> TestFlags; @@ -1423,14 +1499,19 @@ typedef QFlags<TestFlag> TestFlags;
DLL_API void takeMappedEnum(TestFlag value);
DLL_API void takeMappedEnum(TestFlags value);
struct {
struct {
struct {
int(*forIntegers)(int b, short s, unsigned int i);
struct {
struct
{
struct
{
struct
{
int (*forIntegers)(int b, short s, unsigned int i);
struct
{
int i;
} APIHost;
struct {
struct
{
int i;
} Method;
} example;
@ -1440,26 +1521,29 @@ struct { @@ -1440,26 +1521,29 @@ struct {
typedef int boolean_t;
DLL_API boolean_t takeTypemapTypedefParam(boolean_t b);
class DLL_API TestAnonymousMemberNameCollision : public ClassUsingUnion {
class DLL_API TestAnonymousMemberNameCollision : public ClassUsingUnion
{
};
namespace CXXRecordDeclWithoutDefinition
{
template<typename... T>
struct list;
namespace CXXRecordDeclWithoutDefinition {
template <typename... T>
struct list;
template<typename T>
struct it;
template <typename T>
struct it;
template <> struct it<list<>> { };
template <> struct it<list<> const> { };
}
template <>
struct it<list<>>
{};
template <>
struct it<list<> const>
{};
} // namespace CXXRecordDeclWithoutDefinition
template<int... n>
template <int... n>
struct TestVariableWithoutType
{
template<typename... Args>
template <typename... Args>
static constexpr int create(Args... args)
{
return {};
@ -1471,15 +1555,19 @@ struct TestVariableWithoutType @@ -1471,15 +1555,19 @@ struct TestVariableWithoutType
struct DLL_API ClassZeroAllocatedMemoryTest
{
int p1;
struct { int p2p1; int p2p2; } p2;
struct
{
int p2p1;
int p2p2;
} p2;
bool p3;
char p4;
};
struct DLL_API ConversionFunctions
{
operator short* ();
operator short& ();
operator short*();
operator short&();
operator short();
operator const short*() const;
operator const short&() const;
@ -1490,9 +1578,12 @@ struct DLL_API ConversionFunctions @@ -1490,9 +1578,12 @@ struct DLL_API ConversionFunctions
struct DLL_API ClassCustomTypeAlignment
{
struct alignas(1) Align1 { };
struct alignas(8) Align8 { };
struct alignas(16) Align16 {
struct alignas(1) Align1
{};
struct alignas(8) Align8
{};
struct alignas(16) Align16
{
double a;
double b;
};
@ -1515,7 +1606,7 @@ struct DLL_API ClassMicrosoftObjectAlignmentBase @@ -1515,7 +1606,7 @@ struct DLL_API ClassMicrosoftObjectAlignmentBase
uint8_t u8;
double dbl;
int16_t i16;
virtual void Method() { }
virtual void Method() {}
};
struct DLL_API ClassMicrosoftObjectAlignment : ClassMicrosoftObjectAlignmentBase
@ -1533,11 +1624,9 @@ struct DLL_API StructWithEmbeddedArrayOfStructObjectAlignment @@ -1533,11 +1624,9 @@ struct DLL_API StructWithEmbeddedArrayOfStructObjectAlignment
EmbeddedStruct embedded_struct[2];
};
class DLL_API ProtectedConstructorDestructor
{
protected:
ProtectedConstructorDestructor() {}
~ProtectedConstructorDestructor() {}
class DLL_API ProtectedConstructorDestructor{
protected :
ProtectedConstructorDestructor(){} ~ProtectedConstructorDestructor(){}
};
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 @@ -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 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 int TestFunctionToStaticMethodStruct(FTIStruct* bb, FTIStruct defaultValue);
@ -1558,30 +1650,38 @@ DLL_API int TestFunctionToStaticMethodRefStruct(FTIStruct* bb, FTIStruct& defaul @@ -1558,30 +1650,38 @@ DLL_API int TestFunctionToStaticMethodRefStruct(FTIStruct* bb, FTIStruct& defaul
DLL_API int TestFunctionToStaticMethodConstStruct(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, FTIStruct& cc);
class ClassWithoutNativeToManaged { };
class ClassWithoutNativeToManaged
{};
struct DLL_API ClassWithIntValue {
struct DLL_API ClassWithIntValue
{
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;
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->value = 20;
return nullptr;
}
struct DLL_API RuleOfThreeTester {
struct DLL_API RuleOfThreeTester
{
int a;
static int constructorCalls;
static int destructorCalls;
@ -1596,7 +1696,8 @@ struct DLL_API RuleOfThreeTester { @@ -1596,7 +1696,8 @@ struct DLL_API RuleOfThreeTester {
RuleOfThreeTester& operator=(const RuleOfThreeTester& other);
};
struct DLL_API CallByValueInterface {
struct DLL_API CallByValueInterface
{
virtual void CallByValue(RuleOfThreeTester value) = 0;
virtual void CallByReference(RuleOfThreeTester& value) = 0;
virtual void CallByPointer(RuleOfThreeTester* value) = 0;
@ -1609,6 +1710,7 @@ void DLL_API CallCallByValueInterfacePointer(CallByValueInterface*); @@ -1609,6 +1710,7 @@ void DLL_API CallCallByValueInterfacePointer(CallByValueInterface*);
class DLL_API PointerTester
{
int a;
public:
PointerTester();
bool IsDefaultInstance();
@ -1617,10 +1719,12 @@ public: @@ -1617,10 +1719,12 @@ public:
DLL_API extern PointerTester* PointerToClass;
union DLL_API UnionTester {
union DLL_API UnionTester
{
float a;
int b;
inline bool operator ==(const UnionTester& other) const {
inline bool operator==(const UnionTester& other) const
{
return b == other.b;
}
};
@ -1628,42 +1732,48 @@ union DLL_API UnionTester { @@ -1628,42 +1732,48 @@ union DLL_API UnionTester {
int DLL_API ValueTypeOutParameter(CS_OUT UnionTester* testerA, CS_OUT UnionTester* testerB);
template <class T>
class Optional {
class Optional
{
public:
T m_value;
bool m_hasValue;
Optional() {
Optional()
{
m_hasValue = false;
}
Optional(T value) {
Optional(T value)
{
m_value = std::move(value);
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));
}
inline bool operator ==(const T& rhs) const {
inline bool operator==(const T& rhs) const
{
return (m_hasValue && m_value == rhs);
}
};
// We just need a method that uses various instantiations of Optional.
inline void DLL_API InstantiateOptionalTemplate(Optional<unsigned int>, Optional<std::string>,
Optional<TestComparison>, Optional<char*>, Optional<UnionTester>) { }
inline void DLL_API InstantiateOptionalTemplate(Optional<unsigned int>, Optional<std::string>, Optional<TestComparison>, Optional<char*>, Optional<UnionTester>) {}
CS_VALUE_TYPE class DLL_API ValueType {
CS_VALUE_TYPE class DLL_API ValueType
{
public:
ValueType() { }
ValueType() {}
std::string string_member;
const char* char_ptr_member;
};
CS_VALUE_TYPE class DLL_API ValueTypeNoCtor {
CS_VALUE_TYPE class DLL_API ValueTypeNoCtor
{
public:
std::string string_member;
const char* char_ptr_member;

28
tests/dotnet/CSharp/CSharpTemplates.cpp

@ -1,6 +1,7 @@ @@ -1,6 +1,7 @@
#include "CSharpTemplates.h"
T2::T2() : field(0)
T2::T2()
: field(0)
{
}
@ -71,15 +72,15 @@ void TemplateSpecializer::completeSpecializationInParameter(DependentValueFields @@ -71,15 +72,15 @@ void TemplateSpecializer::completeSpecializationInParameter(DependentValueFields
{
}
void TemplateSpecializer::completeSpecializationInParameter(TwoTemplateArgs<int *, int *> p1,
TwoTemplateArgs<int *, int> p2,
TwoTemplateArgs<int *, float> p3,
TwoTemplateArgs<const char *, int> p4,
void TemplateSpecializer::completeSpecializationInParameter(TwoTemplateArgs<int*, int*> p1,
TwoTemplateArgs<int*, int> p2,
TwoTemplateArgs<int*, float> p3,
TwoTemplateArgs<const char*, int> p4,
TwoTemplateArgs<QString, int> p5)
{
}
void TemplateSpecializer::completeSpecializationInParameter(TwoTemplateArgs<const char *, int>::iterator p6,
void TemplateSpecializer::completeSpecializationInParameter(TwoTemplateArgs<const char*, int>::iterator p6,
TwoTemplateArgs<QString, int>::iterator p7)
{
}
@ -103,20 +104,7 @@ int ImplementAbstractTemplate::callFunction() @@ -103,20 +104,7 @@ int ImplementAbstractTemplate::callFunction()
return 65;
}
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)
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)
{
}

190
tests/dotnet/CSharp/CSharpTemplates.h

@ -12,13 +12,9 @@ protected: @@ -12,13 +12,9 @@ protected:
~DeriveProtectedDtor() {}
};
class DLL_API QString
{
};
class DLL_API QString{};
class DLL_API T1
{
};
class DLL_API T1{};
class DLL_API T2
{
@ -28,13 +24,12 @@ public: @@ -28,13 +24,12 @@ public:
virtual ~T2();
int getField() const;
void setField(int value);
private:
int field;
};
class DLL_API Ignored
{
};
class DLL_API Ignored{};
template <typename T>
class HasAbstractReturnPointer
@ -84,6 +79,7 @@ template <typename T> @@ -84,6 +79,7 @@ template <typename T>
class IndependentFields : public T1
{
typedef T Type;
public:
class Nested
{
@ -97,7 +93,7 @@ public: @@ -97,7 +93,7 @@ public:
IndependentFields(T2* t2);
IndependentFields(float f);
~IndependentFields();
explicit IndependentFields(const std::map<T, T> &other);
explicit IndependentFields(const std::map<T, T>& other);
float getIndependent();
T getDependent(const T& t);
Type property();
@ -105,6 +101,7 @@ public: @@ -105,6 +101,7 @@ public:
template <typename AdditionalDependentType>
void usesAdditionalDependentType(AdditionalDependentType additionalDependentType);
static const int independentConst;
private:
float independent;
};
@ -113,7 +110,8 @@ template <typename T> @@ -113,7 +110,8 @@ template <typename T>
const int IndependentFields<T>::independentConst = 15;
template <typename T>
IndependentFields<T>::IndependentFields() : independent(1)
IndependentFields<T>::IndependentFields()
: independent(1)
{
}
@ -124,17 +122,20 @@ IndependentFields<T>::IndependentFields(const IndependentFields<T>& other) @@ -124,17 +122,20 @@ IndependentFields<T>::IndependentFields(const IndependentFields<T>& other)
}
template <typename T>
IndependentFields<T>::IndependentFields(const T& t) : independent(1)
IndependentFields<T>::IndependentFields(const T& t)
: independent(1)
{
}
template <typename T>
IndependentFields<T>::IndependentFields(T1* t1) : independent(1)
IndependentFields<T>::IndependentFields(T1* t1)
: independent(1)
{
}
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) @@ -145,7 +146,8 @@ IndependentFields<T>::IndependentFields(float f)
}
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: @@ -266,15 +268,19 @@ public:
HasAbstractReturnPointer<T>* getAbstractReturnPointer();
typedef void (*DependentFunctionPointer)(T);
DependentFunctionPointer dependentFunctionPointerField;
private:
T field{};
union {
union
{
int unionField;
};
};
template <typename T>
DependentValueFields<T>::DependentValueFields() : unionField(0), dependentFunctionPointerField(0)
DependentValueFields<T>::DependentValueFields()
: unionField(0)
, dependentFunctionPointerField(0)
{
}
@ -284,7 +290,8 @@ DependentValueFields<T>::~DependentValueFields() @@ -284,7 +290,8 @@ DependentValueFields<T>::~DependentValueFields()
}
template <typename T>
DependentValueFields<T>::DependentValueFields(IndependentFields<T> i) : DependentValueFields()
DependentValueFields<T>::DependentValueFields(IndependentFields<T> i)
: DependentValueFields()
{
}
@ -363,7 +370,8 @@ public: @@ -363,7 +370,8 @@ public:
};
template <typename T>
DependentPointerFields<T>::DependentPointerFields(T* t) : field(t)
DependentPointerFields<T>::DependentPointerFields(T* t)
: field(t)
{
}
@ -396,6 +404,7 @@ public: @@ -396,6 +404,7 @@ public:
};
void takeDependentPtrToFirstTemplateArg(iterator i, const K& k);
void takeDependentPtrToSecondTemplateArg(const V& v);
private:
K key;
V value;
@ -434,6 +443,7 @@ public: @@ -434,6 +443,7 @@ public:
bool operator==(const HasDefaultTemplateArgument& other);
DependentValueFields<D> returnTemplateWithRenamedTypeArg(const DependentValueFields<D>& value);
DependentValueFields<D> propertyReturnsTemplateWithRenamedTypeArg();
private:
T field{};
static T staticField;
@ -447,6 +457,7 @@ public: @@ -447,6 +457,7 @@ public:
void setProperty(const bool& t);
static bool staticProperty();
static void setStaticProperty(const bool& t);
private:
bool field;
static bool staticField;
@ -551,6 +562,7 @@ public: @@ -551,6 +562,7 @@ public:
T& operator[](int i);
T& operator[](const T& key);
T& operator[](const char* string);
private:
T t[1];
HasDefaultTemplateArgument<char> h;
@ -586,8 +598,7 @@ T& TemplateWithIndexer<T>::operator[](const char* string) @@ -586,8 +598,7 @@ T& TemplateWithIndexer<T>::operator[](const char* string)
return t[0];
}
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>
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>
class OptionalTemplateArgs
{
};
@ -664,6 +675,7 @@ public: @@ -664,6 +675,7 @@ public:
VirtualTemplate<int> getVCopy();
void setV(VirtualTemplate<int>* value);
int function();
private:
VirtualTemplate<int>* v;
HasDefaultTemplateArgument<bool, bool> explicitSpecialization;
@ -701,6 +713,7 @@ public: @@ -701,6 +713,7 @@ public:
void completeSpecializationInParameter(TwoTemplateArgs<const char*, int>::iterator p6,
TwoTemplateArgs<QString, int>::iterator p7);
VirtualTemplate<void> returnSpecializedWithVoid();
private:
IndependentFields<int> independentFields;
DependentValueFields<bool> dependentValueFields;
@ -732,20 +745,33 @@ class PartiallySpecialized<Key, int> @@ -732,20 +745,33 @@ class PartiallySpecialized<Key, int>
};
};
template<class T>
class HasResultType {
template <class T>
class HasResultType
{
typedef char Yes;
typedef void *No;
template<typename U> static Yes test(int, const typename U::result_type * = 0);
template<typename U> static No test(double);
typedef void* No;
template <typename U>
static Yes test(int, const typename U::result_type* = 0);
template <typename U>
static No test(double);
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>
struct LazyResultType { typedef typename Functor::result_type Type; };
struct LazyResultType
{
typedef typename Functor::result_type Type;
};
template <typename Functor>
struct LazyResultType<Functor, false> { typedef void Type; };
struct LazyResultType<Functor, false>
{
typedef void Type;
};
template <class InputSequence, class MapFunctor>
struct MapResultType
@ -765,7 +791,7 @@ public: @@ -765,7 +791,7 @@ public:
virtual void virtualFunction();
};
template<typename T>
template <typename T>
class TemplateDerivedFromRegularDynamic : public RegularDynamic
{
public:
@ -773,12 +799,12 @@ public: @@ -773,12 +799,12 @@ public:
~TemplateDerivedFromRegularDynamic();
};
template<typename T>
template <typename T>
TemplateDerivedFromRegularDynamic<T>::TemplateDerivedFromRegularDynamic()
{
}
template<typename T>
template <typename T>
TemplateDerivedFromRegularDynamic<T>::~TemplateDerivedFromRegularDynamic()
{
}
@ -807,22 +833,26 @@ class QFlags @@ -807,22 +833,26 @@ class QFlags
{
typedef int Int;
struct Private;
typedef int (Private::*Zero);
typedef int(Private::* Zero);
public:
QFlags(T t);
QFlags(Zero = nullptr);
operator Int();
private:
int flag;
};
template <typename T>
QFlags<T>::QFlags(T t) : flag(Int(t))
QFlags<T>::QFlags(T t)
: flag(Int(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 @@ -872,20 +902,7 @@ enum class TestFlag
};
// we optimise specialisations so that only actually used ones are wrapped
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);
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);
void hasIgnoredParam(DependentValueFields<IndependentFields<Ignored>> ii, Base<void> _24);
@ -893,8 +910,10 @@ std::map<int, int> usesValidSpecialisationOfIgnoredTemplate(); @@ -893,8 +910,10 @@ std::map<int, int> usesValidSpecialisationOfIgnoredTemplate();
DLL_API DependentValueFields<double> specialiseReturnOnly();
template <int Size> 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
template <int Size>
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;
}
@ -902,30 +921,34 @@ template<> inline void* qbswap<1>(const void *source, size_t count, void *dest) @@ -902,30 +921,34 @@ template<> inline void* qbswap<1>(const void *source, size_t count, void *dest)
class TestForwardedClassInAnotherUnit;
// Forward declaration of class as friend
template<class T> class ForwardTemplateFriendClassContainer;
template<class T> class ForwardTemplateFriendClass;
template <class T>
class ForwardTemplateFriendClassContainer;
template <class T>
class ForwardTemplateFriendClass;
template<class T>
template <class T>
class ForwardTemplateFriendClassContainer
{
template<class K> friend class ForwardTemplateFriendClass;
template <class K>
friend class ForwardTemplateFriendClass;
};
template<class T>
template <class T>
class ForwardTemplateFriendClass
{
protected:
ForwardTemplateFriendClass() { }
ForwardTemplateFriendClass() {}
};
class ForwardTemplateFriendClassUser : public ForwardTemplateFriendClass<ForwardTemplateFriendClassUser>
{ };
{};
template<int I>
template <int I>
class ClassWithNonTypeTemplateArgument
{
public:
ClassWithNonTypeTemplateArgument() { }
ClassWithNonTypeTemplateArgument() {}
private:
union
{
@ -935,19 +958,19 @@ private: @@ -935,19 +958,19 @@ private:
};
class SpecializationOfClassWithNonTypeTemplateArgument : public ClassWithNonTypeTemplateArgument<0>
{ };
template<std::size_t N>
class DLL_API FloatArrayF
{
public:
template<typename... V, class = typename std::enable_if_t<sizeof...(V) == N>>
FloatArrayF(V... x) { }
{};
template <std::size_t N>
class DLL_API FloatArrayF{
public :
template <typename... V, class = typename std::enable_if_t<sizeof...(V) == N>>
FloatArrayF(V... x){}
};
const FloatArrayF<6> I6{ 1., 1., 1., 0., 0., 0. };
template <typename T>
DLL_API inline T FunctionTemplate(T value) {
DLL_API inline T FunctionTemplate(T value)
{
if (std::is_same<T, double>::value)
return 4.2 + value;
else if (std::is_same<T, float>::value)
@ -963,20 +986,21 @@ inline void FunctionTemplateInstantiation() @@ -963,20 +986,21 @@ inline void FunctionTemplateInstantiation()
}
// KEEP ORDER OTHERWISE TEST WONT WORK
namespace IncompleteClassTemplatesTests
{
template <size_t Size>
struct StructSizeT {};
namespace IncompleteClassTemplatesTests {
template <size_t Size>
struct StructSizeT
{};
template <typename T>
struct StructT
{
template<typename U>
struct Inc { };
};
template <typename T>
struct StructT
{
template <typename U>
struct Inc
{};
};
struct Instantiation
{
StructT<StructSizeT<4000>> st;
};
}
struct Instantiation
{
StructT<StructSizeT<4000>> st;
};
} // namespace IncompleteClassTemplatesTests

17
tests/dotnet/CSharp/ExcludedUnit.hpp

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

19
tests/dotnet/Common/AnotherUnit.h

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

228
tests/dotnet/Common/Common.cpp

@ -14,7 +14,9 @@ Foo::Foo() @@ -14,7 +14,9 @@ Foo::Foo()
SomePointerPointer = &SomePointer;
}
Foo::Foo(const Foo& other) : A(other.A), B(other.B)
Foo::Foo(const Foo& other)
: A(other.A)
, B(other.B)
{
}
@ -45,7 +47,7 @@ int Foo::TakesRef(const Foo& other) @@ -45,7 +47,7 @@ int Foo::TakesRef(const Foo& other)
return other.A;
}
bool Foo::operator ==(const Foo& other) const
bool Foo::operator==(const Foo& other) const
{
return A == other.A && B == other.B;
}
@ -64,7 +66,12 @@ Foo Foo::staticField; @@ -64,7 +66,12 @@ Foo Foo::staticField;
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)
{
@ -111,12 +118,12 @@ Bar* Bar::returnPointerToValueType() @@ -111,12 +118,12 @@ Bar* Bar::returnPointerToValueType()
return this;
}
bool Bar::operator ==(const Bar& arg1) const
bool Bar::operator==(const Bar& arg1) const
{
return A == arg1.A && B == arg1.B;
}
bool operator ==(Bar::Item item, const Bar& bar)
bool operator==(Bar::Item item, const Bar& bar)
{
return item == bar.RetItem1();
}
@ -153,7 +160,7 @@ Foo2 Bar2::needFixedInstance() const @@ -153,7 +160,7 @@ Foo2 Bar2::needFixedInstance() const
void Hello::PrintHello(const char* s)
{
//cout << "PrintHello: " << s << "\n";
// cout << "PrintHello: " << s << "\n";
}
bool Hello::test1(int i, float f)
@ -310,7 +317,10 @@ Bar indirectReturn() @@ -310,7 +317,10 @@ Bar indirectReturn()
return Bar();
}
TestDelegates::TestDelegates() : A(Double), B(Double), C(&TestDelegates::Triple)
TestDelegates::TestDelegates()
: A(Double)
, B(Double)
, C(&TestDelegates::Triple)
{
}
@ -388,7 +398,7 @@ int test(common& s) @@ -388,7 +398,7 @@ int test(common& s)
return 5;
}
int operator *(TestMoveOperatorToClass klass, int b)
int operator*(TestMoveOperatorToClass klass, int b)
{
return klass.A * b;
}
@ -406,7 +416,7 @@ TestMoveOperatorToClass operator-(const TestMoveOperatorToClass& b) @@ -406,7 +416,7 @@ TestMoveOperatorToClass operator-(const TestMoveOperatorToClass& b)
}
TestMoveOperatorToClass operator+(const TestMoveOperatorToClass& b1,
const TestMoveOperatorToClass& b2)
const TestMoveOperatorToClass& b2)
{
TestMoveOperatorToClass b;
b.A = b1.A + b2.A;
@ -450,12 +460,12 @@ int (*TestDelegates::MarshalAnonymousDelegate4())(int n) @@ -450,12 +460,12 @@ int (*TestDelegates::MarshalAnonymousDelegate4())(int n)
return f;
}
int TestDelegates::MarshalAnonymousDelegate5(int (STDCALL* del)(int))
int TestDelegates::MarshalAnonymousDelegate5(int(STDCALL* del)(int))
{
return del(2);
}
int TestDelegates::MarshalAnonymousDelegate6(int (STDCALL* del)(int))
int TestDelegates::MarshalAnonymousDelegate6(int(STDCALL* del)(int))
{
return del(3);
}
@ -541,22 +551,29 @@ int Function() @@ -541,22 +551,29 @@ int Function()
return 5;
}
TestProperties::TestProperties() : Field(0), ArchiveName(0),
FieldValue(0), _refToPrimitiveInSetter(0),
_getterAndSetterWithTheSameName(0), _setterReturnsBoolean(0),
_virtualSetterReturnsBoolean(0), _conflict(Conflict::Value1),
ConstRefField(Field)
TestProperties::TestProperties()
: Field(0)
, ArchiveName(0)
, FieldValue(0)
, _refToPrimitiveInSetter(0)
, _getterAndSetterWithTheSameName(0)
, _setterReturnsBoolean(0)
, _virtualSetterReturnsBoolean(0)
, _conflict(Conflict::Value1)
, ConstRefField(Field)
{
}
TestProperties::TestProperties(const TestProperties& other) :
Field(other.Field), ArchiveName(other.ArchiveName),
FieldValue(other.FieldValue),
_refToPrimitiveInSetter(other._refToPrimitiveInSetter),
_getterAndSetterWithTheSameName(other._getterAndSetterWithTheSameName),
_setterReturnsBoolean(other._setterReturnsBoolean),
_virtualSetterReturnsBoolean(other._virtualSetterReturnsBoolean),
_conflict(other._conflict), ConstRefField(other.ConstRefField)
TestProperties::TestProperties(const TestProperties& other)
: Field(other.Field)
, ArchiveName(other.ArchiveName)
, FieldValue(other.FieldValue)
, _refToPrimitiveInSetter(other._refToPrimitiveInSetter)
, _getterAndSetterWithTheSameName(other._getterAndSetterWithTheSameName)
, _setterReturnsBoolean(other._setterReturnsBoolean)
, _virtualSetterReturnsBoolean(other._virtualSetterReturnsBoolean)
, _conflict(other._conflict)
, ConstRefField(other.ConstRefField)
{
}
@ -721,12 +738,12 @@ void TestProperties::SetConflict(Conflict conflict) @@ -721,12 +738,12 @@ void TestProperties::SetConflict(Conflict conflict)
_conflict = conflict;
}
int(*TestProperties::getCallback())(int)
int (*TestProperties::getCallback())(int)
{
return _callback;
}
void TestProperties::setCallback(int(*value)(int))
void TestProperties::setCallback(int (*value)(int))
{
_callback = value;
}
@ -758,15 +775,32 @@ void HasOverridenSetter::setVirtualGetter(int value) @@ -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; }
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; }
foo_t& TestIndexedProperties::operator[](int i)
{
return p;
}
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)
{
return bar;
@ -776,8 +810,14 @@ Bar& TestIndexedProperties::operator[](const TypeMappedIndex& key) @@ -776,8 +810,14 @@ Bar& TestIndexedProperties::operator[](const TypeMappedIndex& key)
return bar;
}
const foo_t& TestIndexedProperties::operator[](double f) { return p; }
foo_t TestIndexedProperties::operator[](TestProperties b) { return p; }
const foo_t& TestIndexedProperties::operator[](double f)
{
return p;
}
foo_t TestIndexedProperties::operator[](TestProperties b)
{
return p;
}
int TestIndexedProperties::operator[](CS_OUT char key)
{
@ -794,11 +834,20 @@ Bar& TestIndexedProperties::operator[](const Foo& key) @@ -794,11 +834,20 @@ Bar& TestIndexedProperties::operator[](const Foo& key)
}
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)
{
@ -806,7 +855,8 @@ InternalCtorAmbiguity::InternalCtorAmbiguity(void* param) @@ -806,7 +855,8 @@ InternalCtorAmbiguity::InternalCtorAmbiguity(void* param)
throw;
}
InvokesInternalCtorAmbiguity::InvokesInternalCtorAmbiguity() : ptr(0)
InvokesInternalCtorAmbiguity::InvokesInternalCtorAmbiguity()
: ptr(0)
{
}
@ -835,7 +885,8 @@ DLL_API const HasFriend operator-(const HasFriend& f1, const HasFriend& f2) @@ -835,7 +885,8 @@ DLL_API const HasFriend operator-(const HasFriend& f1, const HasFriend& f2)
return HasFriend(f1.m - f2.m);
}
DifferentConstOverloads::DifferentConstOverloads() : i(5)
DifferentConstOverloads::DifferentConstOverloads()
: i(5)
{
}
@ -844,27 +895,27 @@ int DifferentConstOverloads::getI() const @@ -844,27 +895,27 @@ int DifferentConstOverloads::getI() const
return i;
}
bool DifferentConstOverloads::operator ==(const DifferentConstOverloads& other)
bool DifferentConstOverloads::operator==(const DifferentConstOverloads& other)
{
return i == other.i;
}
bool DifferentConstOverloads::operator !=(const DifferentConstOverloads& other)
bool DifferentConstOverloads::operator!=(const DifferentConstOverloads& other)
{
return i != other.i;
}
bool DifferentConstOverloads::operator ==(int number) const
bool DifferentConstOverloads::operator==(int number) const
{
return i == number;
}
bool DifferentConstOverloads::operator ==(std::string s) const
bool DifferentConstOverloads::operator==(std::string s) const
{
return i == s.length();
}
bool operator ==(const DifferentConstOverloads& d, const char* s)
bool operator==(const DifferentConstOverloads& d, const char* s)
{
return d.getI() == strlen(s);
}
@ -926,7 +977,9 @@ void funcTryValTypeOut(CS_OUT ValueTypeClassPassTry classTry) @@ -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() @@ -1059,17 +1112,32 @@ TestNotStaticClass TestNotStaticClass::StaticFunction()
return TestNotStaticClass();
}
int TestStaticClass::Add(int a, int b) { return a + b; }
int TestStaticClass::GetOneTwoThree() { return 123; }
int TestStaticClass::_Mult(int a, int b) { return a * b; }
int TestStaticClass::GetFourFiveSix() { return 456; }
int TestStaticClass::Add(int a, int b)
{
return a + b;
}
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)
{
return *this;
}
int TestStaticClassDerived::Foo() { return 0; }
int TestStaticClassDerived::Foo()
{
return 0;
}
HasCopyAndMoveConstructor::HasCopyAndMoveConstructor(int value)
{
@ -1137,7 +1205,10 @@ AmbiguousParamNames::AmbiguousParamNames(int instance, int in) @@ -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()
{
@ -1193,8 +1264,14 @@ LPCSTR TakeTypedefedMappedType(LPCSTR string) @@ -1193,8 +1264,14 @@ LPCSTR TakeTypedefedMappedType(LPCSTR string)
return UTF8.data();
}
StructWithCopyCtor::StructWithCopyCtor() : mBits(0) {}
StructWithCopyCtor::StructWithCopyCtor(const StructWithCopyCtor& other) : mBits(other.mBits) {}
StructWithCopyCtor::StructWithCopyCtor()
: mBits(0)
{
}
StructWithCopyCtor::StructWithCopyCtor(const StructWithCopyCtor& other)
: mBits(other.mBits)
{
}
uint16_t TestStructWithCopyCtorByValue(StructWithCopyCtor s)
{
@ -1214,8 +1291,14 @@ int NonPrimitiveType::GetFoo() @@ -1214,8 +1291,14 @@ int NonPrimitiveType::GetFoo()
return foo;
}
int TestGetterSetterToProperties::getWidth() { return 640; }
int TestGetterSetterToProperties::getHeight() { return 480; }
int TestGetterSetterToProperties::getWidth()
{
return 640;
}
int TestGetterSetterToProperties::getHeight()
{
return 480;
}
void DLL_API PointerToTypedefPointerTestMethod(LPPointerToTypedefPointerTest* lp, int valToSet)
{
@ -1229,10 +1312,13 @@ void DLL_API PointerToPrimitiveTypedefPointerTestMethod(LPINT lp, int valToSet) @@ -1229,10 +1312,13 @@ void DLL_API PointerToPrimitiveTypedefPointerTestMethod(LPINT lp, int valToSet)
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 @@ -1243,20 +1329,36 @@ TestCopyConstructorRef::TestCopyConstructorRef(const TestCopyConstructorRef& oth
}
SomeStruct::SomeStruct() : p(1) {}
SomeStruct::SomeStruct()
: p(1)
{
}
void SomeNamespace::NamespacedAbstractImpl::AbstractMethod()
{
}
ClassWithOverloadedOperators::ClassWithOverloadedOperators::operator char() { return 1; }
ClassWithOverloadedOperators::operator int() { return 2; }
ClassWithOverloadedOperators::operator short() { return 3; }
bool ClassWithOverloadedOperators::operator<(const ClassWithOverloadedOperators& other) const {
ClassWithOverloadedOperators::ClassWithOverloadedOperators::operator char()
{
return 1;
}
ClassWithOverloadedOperators::operator int()
{
return 2;
}
ClassWithOverloadedOperators::operator short()
{
return 3;
}
bool ClassWithOverloadedOperators::operator<(const ClassWithOverloadedOperators& other) const
{
return true;
}
int TestIndexedPropertiesInValueType::operator[](int i) { return i; }
int TestIndexedPropertiesInValueType::operator[](int i)
{
return i;
}
extern "C"
{

476
tests/dotnet/Common/Common.h

@ -17,22 +17,22 @@ public: @@ -17,22 +17,22 @@ public:
};
#pragma pack(1)
class DLL_API TestPacking1: public TestPacking
class DLL_API TestPacking1 : public TestPacking
{
};
#pragma pack(2)
class DLL_API TestPacking2: public TestPacking
class DLL_API TestPacking2 : public TestPacking
{
};
#pragma pack(4)
class DLL_API TestPacking4: public TestPacking
class DLL_API TestPacking4 : public TestPacking
{
};
#pragma pack(8)
class DLL_API TestPacking8: public TestPacking
class DLL_API TestPacking8 : public TestPacking
{
};
#pragma pack()
@ -44,6 +44,7 @@ class DLL_API IgnoredType @@ -44,6 +44,7 @@ class DLL_API IgnoredType
private:
int i;
};
private:
int i;
};
@ -56,6 +57,7 @@ private: @@ -56,6 +57,7 @@ private:
Value1,
Value2
};
public:
enum
{
@ -101,7 +103,7 @@ public: @@ -101,7 +103,7 @@ public:
void TakesTypedefedPtr(FooPtr date);
int TakesRef(const Foo& other);
bool operator ==(const Foo& other) const;
bool operator==(const Foo& other) const;
int fooPtr();
char16_t returnChar16();
@ -127,14 +129,15 @@ struct DLL_API Bar @@ -127,14 +129,15 @@ struct DLL_API Bar
Bar* returnPointerToValueType();
bool operator ==(const Bar& arg1) const;
bool operator==(const Bar& arg1) const;
};
DLL_API bool operator ==(Bar::Item item, const Bar& bar);
DLL_API bool operator==(Bar::Item item, const Bar& bar);
class DLL_API Foo2 : public Foo
{
struct Copy {
struct Copy
{
Foo A;
}* copy;
@ -152,7 +155,7 @@ public: @@ -152,7 +155,7 @@ public:
void testKeywordParam(void* where, Bar::Item event, int ref);
};
DLL_API Bar::Item operator |(Bar::Item left, Bar::Item right);
DLL_API Bar::Item operator|(Bar::Item left, Bar::Item right);
struct DLL_API Bar2 : public Bar
{
@ -167,7 +170,7 @@ struct DLL_API Bar2 : public Bar @@ -167,7 +170,7 @@ struct DLL_API Bar2 : public Bar
operator Foo2();
Foo2 needFixedInstance() const;
typedef void *Bar2::*FunctionPointerResolvedAsVoidStar;
typedef void* Bar2::* FunctionPointerResolvedAsVoidStar;
operator FunctionPointerResolvedAsVoidStar() const { return 0; }
int C;
@ -179,8 +182,10 @@ struct DLL_API Bar2 : public Bar @@ -179,8 +182,10 @@ struct DLL_API Bar2 : public Bar
enum Enum
{
A = 0, B = 2, C = 5,
//D = 0x80000000,
A = 0,
B = 2,
C = 5,
// D = 0x80000000,
E = 0x1,
F = -9,
NAME_A = 10,
@ -191,13 +196,15 @@ typedef char TypedefChar; @@ -191,13 +196,15 @@ typedef char TypedefChar;
class DLL_API Hello
{
union NestedPrivate {
union NestedPrivate
{
int i;
float f;
};
public:
union NestedPublic {
union NestedPublic
{
int j;
float g;
long l;
@ -256,6 +263,7 @@ public: @@ -256,6 +263,7 @@ public:
typedef int typedefInOverride;
virtual int pureFunction(typedefInOverride i = 0);
virtual int pureFunction1();
private:
virtual int pureFunction2(bool* ok = 0);
};
@ -302,7 +310,7 @@ struct DLL_API DefaultParameters @@ -302,7 +310,7 @@ struct DLL_API DefaultParameters
};
// The Curiously Recurring Template Pattern (CRTP)
template<class Derived>
template <class Derived>
class Base
{
// methods within Base can use template to access members of Derived
@ -314,9 +322,7 @@ class Derived : public Base<Derived> @@ -314,9 +322,7 @@ class Derived : public Base<Derived>
};
// Tests the MoveFunctionToClassPass
class DLL_API common
{
};
class DLL_API common{};
DLL_API int test(common& s);
@ -328,26 +334,26 @@ struct DLL_API TestMoveOperatorToClass @@ -328,26 +334,26 @@ struct DLL_API TestMoveOperatorToClass
int B;
};
DLL_API int operator *(TestMoveOperatorToClass klass, int b);
DLL_API int operator*(TestMoveOperatorToClass klass, int b);
DLL_API TestMoveOperatorToClass operator-(const TestMoveOperatorToClass& b);
DLL_API TestMoveOperatorToClass operator+(const TestMoveOperatorToClass& b1,
const TestMoveOperatorToClass& b2);
const TestMoveOperatorToClass& b2);
// Not a valid operator overload for Foo2 in managed code - comparison operators need to return bool.
DLL_API int operator==(const Foo2& a, const Foo2& b);
// Tests delegates
typedef int (*DelegateInGlobalNamespace)(int);
typedef int (STDCALL *DelegateStdCall)(int);
typedef int (CDECL *DelegateCDecl)(int n);
typedef void(*DelegateNullCheck)(void);
typedef int(STDCALL* DelegateStdCall)(int);
typedef int(CDECL* DelegateCDecl)(int n);
typedef void (*DelegateNullCheck)(void);
struct DLL_API TestDelegates
{
typedef int (*DelegateInClass)(int);
typedef int(TestDelegates::*MemberDelegate)(int);
typedef int (TestDelegates::*MemberDelegate)(int);
TestDelegates();
static int Double(int N);
@ -361,8 +367,8 @@ struct DLL_API TestDelegates @@ -361,8 +367,8 @@ struct DLL_API TestDelegates
void MarshalAnonymousDelegate2(int (*del)(int n));
void MarshalAnonymousDelegate3(float (*del)(float n));
int (*MarshalAnonymousDelegate4())(int n);
int MarshalAnonymousDelegate5(int (STDCALL *del)(int n));
int MarshalAnonymousDelegate6(int (STDCALL *del)(int n));
int MarshalAnonymousDelegate5(int(STDCALL* del)(int n));
int MarshalAnonymousDelegate6(int(STDCALL* del)(int n));
void MarshalDelegateInAnotherUnit(DelegateInAnotherUnit del);
@ -374,28 +380,23 @@ struct DLL_API TestDelegates @@ -374,28 +380,23 @@ struct DLL_API TestDelegates
MemberDelegate C;
};
namespace DelegateNamespace
{
namespace Nested
{
void DLL_API f1(void (*)());
}
void DLL_API f2(void (*)());
namespace DelegateNamespace {
namespace Nested {
void DLL_API f1(void (*)());
}
void DLL_API f2(void (*)());
} // namespace DelegateNamespace
// Tests memory leaks in constructors
// C#: Marshal.FreeHGlobal(arg0);
struct DLL_API TestMemoryLeaks
{
TestMemoryLeaks(const char* name) {}
struct DLL_API TestMemoryLeaks{
TestMemoryLeaks(const char* name){}
};
// Tests that finalizers are generated
/* CLI: ~TestFinalizers() */
struct DLL_API TestFinalizers
{
};
struct DLL_API TestFinalizers{};
// Tests static classes
struct DLL_API TestStaticClass
@ -427,6 +428,7 @@ class DLL_API TestNotStaticClass @@ -427,6 +428,7 @@ class DLL_API TestNotStaticClass
{
public:
static TestNotStaticClass StaticFunction();
private:
TestNotStaticClass();
};
@ -460,51 +462,54 @@ public: @@ -460,51 +462,54 @@ public:
template <class T>
struct EmptyNamedNestedEnum
{
enum { Value = 10 };
enum
{
Value = 10
};
};
typedef unsigned long foo_t;
typedef struct DLL_API SomeStruct
{
SomeStruct();
foo_t p;
SomeStruct();
foo_t p;
} SomeStruct;
class DLL_API SomeClassExtendingTheStruct : public SomeStruct
{
};
namespace SomeNamespace
namespace SomeNamespace {
class DLL_API NamespacedAbstractClass
{
class DLL_API NamespacedAbstractClass
{
public:
virtual void AbstractMethod() = 0;
};
public:
virtual void AbstractMethod() = 0;
};
class DLL_API NamespacedAbstractImpl
{
public:
virtual void AbstractMethod();
};
class DLL_API NamespacedAbstractImpl
{
public:
virtual void AbstractMethod();
};
class Inlines
{
public:
constexpr Inlines(float param, const char* name) {}
inline operator NamespacedAbstractImpl () const { return NamespacedAbstractImpl(); }
protected:
void protectedInlined() {}
};
class Inlines
{
public:
constexpr Inlines(float param, const char* name) {}
inline operator NamespacedAbstractImpl() const { return NamespacedAbstractImpl(); }
constexpr Inlines constWithParams(5.f, "test");
protected:
void protectedInlined() {}
};
class AbstractInlines
{
public:
virtual void hasVariadicArgs(int regular, ...) = 0;
};
}
constexpr Inlines constWithParams(5.f, "test");
class AbstractInlines
{
public:
virtual void hasVariadicArgs(int regular, ...) = 0;
};
} // namespace SomeNamespace
// Test operator overloads
class DLL_API ClassWithOverloadedOperators
@ -514,7 +519,7 @@ public: @@ -514,7 +519,7 @@ public:
operator int();
operator short();
virtual bool operator<(const ClassWithOverloadedOperators &other) const;
virtual bool operator<(const ClassWithOverloadedOperators& other) const;
};
// Tests global static function generation
@ -587,8 +592,8 @@ public: @@ -587,8 +592,8 @@ public:
Conflict GetConflict();
void SetConflict(Conflict _conflict);
virtual int(*getCallback())(int);
virtual void setCallback(int(*value)(int));
virtual int (*getCallback())(int);
virtual void setCallback(int (*value)(int));
int GetArchiveName() const;
@ -602,7 +607,7 @@ private: @@ -602,7 +607,7 @@ private:
int _setterReturnsBoolean;
int _virtualSetterReturnsBoolean;
Conflict _conflict;
int(*_callback)(int);
int (*_callback)(int);
};
class DLL_API HasOverridenSetter : public TestProperties
@ -666,16 +671,21 @@ struct DLL_API TestVariables @@ -666,16 +671,21 @@ struct DLL_API TestVariables
void SetValue(int value = VALUE);
};
typedef const wchar_t * LPCWSTR;
typedef const wchar_t* LPCWSTR;
struct DLL_API TestWideStrings
{
LPCWSTR GetWidePointer();
LPCWSTR GetWideNullPointer();
};
enum struct MyEnum { A, B, C };
enum struct MyEnum
{
A,
B,
C
};
typedef void (*VoidPtrRetFunctionTypedef) ();
typedef void (*VoidPtrRetFunctionTypedef)();
class DLL_API TestFixedArrays
{
@ -691,7 +701,7 @@ public: @@ -691,7 +701,7 @@ public:
class DLL_API TestArraysPointers
{
public:
TestArraysPointers(MyEnum *values, int count);
TestArraysPointers(MyEnum* values, int count);
MyEnum Value;
};
@ -731,9 +741,9 @@ public: @@ -731,9 +741,9 @@ public:
ClassB(const ClassA& x);
int Value;
// conversion from ClassA (assignment):
//ClassB& operator= (const ClassA& x) { return *this; }
// ClassB& operator= (const ClassA& x) { return *this; }
// conversion to ClassA (type-cast operator)
//operator ClassA() { return ClassA(); }
// operator ClassA() { return ClassA(); }
};
class DLL_API ClassC
{
@ -762,12 +772,16 @@ DLL_API void TestNullPtrType(decltype(nullptr)); @@ -762,12 +772,16 @@ DLL_API void TestNullPtrType(decltype(nullptr));
DLL_API decltype(nullptr) TestNullPtrTypeRet();
// 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:
struct Bitset { int length : sizeof(T); };
struct Bitset
{
int length : sizeof(T);
};
};
class PureDtor
@ -828,6 +842,7 @@ class DLL_API InvokesInternalCtorAmbiguity @@ -828,6 +842,7 @@ class DLL_API InvokesInternalCtorAmbiguity
public:
InvokesInternalCtorAmbiguity();
InternalCtorAmbiguity* InvokeInternalCtor();
private:
InternalCtorAmbiguity* ptr;
};
@ -839,16 +854,18 @@ public: @@ -839,16 +854,18 @@ 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);
int getM();
private:
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>&);
template<typename TT>
template <typename TT>
friend class FriendTemplate;
};
@ -857,32 +874,35 @@ class DLL_API DifferentConstOverloads @@ -857,32 +874,35 @@ class DLL_API DifferentConstOverloads
public:
DifferentConstOverloads();
int getI() const;
bool operator ==(const DifferentConstOverloads& other);
bool operator !=(const DifferentConstOverloads& other);
bool operator ==(int number) const;
bool operator ==(std::string s) const;
bool operator==(const DifferentConstOverloads& other);
bool operator!=(const DifferentConstOverloads& other);
bool operator==(int number) const;
bool operator==(std::string s) const;
private:
int i;
};
DLL_API bool operator ==(const DifferentConstOverloads& d, const char* s);
DLL_API bool operator==(const DifferentConstOverloads& d, const char* s);
class TestNamingAnonymousTypesInUnion
{
public:
union {
struct {
union
{
struct
{
} argb;
struct {
struct
{
} ahsv;
struct {
struct
{
} acmyk;
} ct;
};
class DLL_API RefTypeClassPassTry
{
};
class DLL_API RefTypeClassPassTry{};
void DLL_API funcTryRefTypePtrOut(CS_OUT RefTypeClassPassTry* classTry);
void DLL_API funcTryRefTypeOut(CS_OUT RefTypeClassPassTry classTry);
@ -891,10 +911,10 @@ void DLL_API funcTryRefTypeOut(CS_OUT RefTypeClassPassTry classTry); @@ -891,10 +911,10 @@ void DLL_API funcTryRefTypeOut(CS_OUT RefTypeClassPassTry classTry);
#define CS_VALUE_TYPE
struct CS_VALUE_TYPE ValueTypeArrays
{
float firstValueTypeArrray[ARRAY_LENGTH];
int secondValueTypeArray[ARRAY_LENGTH];
char thirdValueTypeArray[ARRAY_LENGTH];
size_t size;
float firstValueTypeArrray[ARRAY_LENGTH];
int secondValueTypeArray[ARRAY_LENGTH];
char thirdValueTypeArray[ARRAY_LENGTH];
size_t size;
};
class DLL_API HasVirtualProperty
@ -902,6 +922,7 @@ class DLL_API HasVirtualProperty @@ -902,6 +922,7 @@ class DLL_API HasVirtualProperty
public:
virtual int getProperty();
virtual void setProperty(int target);
protected:
virtual int getProtectedProperty();
virtual void setProtectedProperty(int value);
@ -912,14 +933,13 @@ class DLL_API ChangedAccessOfInheritedProperty : public HasVirtualProperty @@ -912,14 +933,13 @@ class DLL_API ChangedAccessOfInheritedProperty : public HasVirtualProperty
public:
int getProtectedProperty();
void setProtectedProperty(int value);
protected:
int getProperty();
void setProperty(int value);
};
class DLL_API Empty
{
};
class DLL_API Empty{};
class DLL_API ReturnsEmpty
{
@ -927,7 +947,7 @@ public: @@ -927,7 +947,7 @@ public:
Empty getEmpty();
};
class DLL_API CS_VALUE_TYPE ValueTypeClassPassTry { };
class DLL_API CS_VALUE_TYPE ValueTypeClassPassTry{};
void DLL_API funcTryValTypePtrOut(CS_OUT ValueTypeClassPassTry* classTry);
void DLL_API funcTryValTypeOut(CS_OUT ValueTypeClassPassTry classTry);
@ -983,63 +1003,70 @@ public: @@ -983,63 +1003,70 @@ public:
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; };
template <class T, class U>struct is_member_pointer_cv<T U::*> { static const bool value = true; };
static const bool value = false;
};
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
template<class T>
struct make_tuple_traits
{
typedef T type;
// all of this below tests corner cases with type locations
template <class T>
struct make_tuple_traits
{
typedef T type;
// commented away, see below (JJ)
// typedef typename IF<
// boost::is_function<T>::value,
// T&,
// T>::RET type;
};
// commented away, see below (JJ)
// typedef typename IF<
// boost::is_function<T>::value,
// T&,
// T>::RET type;
};
namespace detail
namespace detail {
struct swallow_assign;
typedef void (detail::swallow_assign::*ignore_t)();
struct swallow_assign
{
struct swallow_assign;
typedef void (detail::swallow_assign::*ignore_t)();
struct swallow_assign
{
swallow_assign(ignore_t(*)(ignore_t));
template<typename T>
swallow_assign const& operator=(const T&) const;
};
swallow_assign(ignore_t (*)(ignore_t));
template <typename T>
swallow_assign const& operator=(const T&) const;
};
swallow_assign::swallow_assign(ignore_t (*)(ignore_t))
{
}
swallow_assign::swallow_assign(ignore_t (*)(ignore_t))
{
}
template<typename T>
swallow_assign const& swallow_assign::operator=(const T&) const
{
return *this;
}
template <typename T>
swallow_assign const& swallow_assign::operator=(const T&) const
{
return *this;
}
} // namespace detail
} // namespace detail
template<>
struct make_tuple_traits<detail::ignore_t(detail::ignore_t)>
{
typedef detail::swallow_assign type;
};
template <>
struct make_tuple_traits<detail::ignore_t(detail::ignore_t)>
{
typedef detail::swallow_assign type;
};
template<class T>
struct is_class_or_union
{
template <class U>
static char is_class_or_union_tester(void(U::*)(void));
};
}
template <class T>
struct is_class_or_union
{
template <class U>
static char is_class_or_union_tester(void (U::*)(void));
};
} // namespace boost
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>
class AbstractTemplate
@ -1074,15 +1101,18 @@ public: @@ -1074,15 +1101,18 @@ public:
~NonTrivialDtor();
static bool getDtorCalled();
static void setDtorCalled(bool value);
private:
static bool dtorCalled;
};
template <class T> class ForwardedTemplate;
template <class T>
class ForwardedTemplate;
ForwardedTemplate<int> returnsForwardedTemplate();
template <class T> class ForwardedTemplate
template <class T>
class ForwardedTemplate
{
ForwardedTemplate<T> functionInForwardedTemplate() const;
};
@ -1112,8 +1142,9 @@ void TemplateWithVirtual<T>::v() @@ -1112,8 +1142,9 @@ void TemplateWithVirtual<T>::v()
}
template <typename T>
int FunctionTemplateWithDependentTypeDefaultExpr(size_t size = sizeof(T)) {
return size;
int FunctionTemplateWithDependentTypeDefaultExpr(size_t size = sizeof(T))
{
return size;
}
class DLL_API DerivedFromTemplateInstantiationWithVirtual : public TemplateWithVirtual<int>
@ -1141,13 +1172,13 @@ protected: @@ -1141,13 +1172,13 @@ protected:
using custom_int_t = int;
DLL_API void FuncWithTypeAlias(custom_int_t i);
template<typename T>
template <typename T>
using TypeAliasTemplate = TemplateWithVirtual<T>;
DLL_API void FuncWithTemplateTypeAlias(TypeAliasTemplate<int> i);
struct TestsTypes
{
int(*FunctionNoProto)();
int (*FunctionNoProto)();
};
template <class T>
@ -1160,7 +1191,8 @@ private: @@ -1160,7 +1191,8 @@ private:
template <class T>
class SpecialisesVoidInUnion
{
union {
union
{
SpecialisesVoid<T>* e;
}* u;
};
@ -1181,16 +1213,16 @@ public: @@ -1181,16 +1213,16 @@ public:
virtual bool operator==(const HasAbstractOperator& other) = 0;
};
template<size_t _Len, class _Ty>
template <size_t _Len, class _Ty>
struct _Aligned;
template<size_t _Len>
template <size_t _Len>
struct _Aligned<_Len, int>
{
typedef int type;
};
template<size_t _Len>
template <size_t _Len>
struct _Aligned<_Len, char>
{
typedef typename _Aligned<_Len, int>::type type;
@ -1250,9 +1282,17 @@ public: @@ -1250,9 +1282,17 @@ public:
DLL_API void hasPointerParam(Foo* foo, int i);
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();
@ -1263,6 +1303,7 @@ public: @@ -1263,6 +1303,7 @@ public:
HasCopyAndMoveConstructor(const HasCopyAndMoveConstructor& other);
HasCopyAndMoveConstructor(HasCopyAndMoveConstructor&& other);
int getField();
private:
int field;
};
@ -1354,18 +1395,16 @@ struct DLL_API NestedUnionWithNested @@ -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
{
@ -1383,20 +1422,19 @@ union @@ -1383,20 +1422,19 @@ union
} ProtocolSpecific;
template<class _Other>
using UsingTemplatePtr = _Other *;
template <class _Other>
using UsingTemplatePtr = _Other*;
struct TemplateWithUsingTemplateMember
{
UsingTemplatePtr<TemplateWithUsingTemplateMember> _Ref;
};
namespace hasUnnamedDecl
namespace hasUnnamedDecl {
extern "C"
{
extern "C"
{
}
}
} // namespace hasUnnamedDecl
enum ItemsDifferByCase
{
@ -1404,7 +1442,8 @@ enum ItemsDifferByCase @@ -1404,7 +1442,8 @@ enum ItemsDifferByCase
Case_A
};
template <typename T> struct MyListBase
template <typename T>
struct MyListBase
{
protected:
~MyListBase() {}
@ -1414,27 +1453,32 @@ template <typename T> @@ -1414,27 +1453,32 @@ template <typename T>
class MyList : public MyListBase<T>
{
public:
inline MyList() { }
inline MyList() {}
};
template <> struct MyListBase<int>
template <>
struct MyListBase<int>
{
};
class MyIntList : public MyList<int>
{
inline MyIntList(MyList<int> &&l) { }
inline MyIntList(MyList<int>&& l) {}
};
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> using TypeAlias = InvokeGenSeq<DerivedTypeAlias<N>>;
template <int N>
struct DerivedTypeAlias;
template <int N>
using TypeAlias = InvokeGenSeq<DerivedTypeAlias<N>>;
template<int N>
struct DerivedTypeAlias : TypeAlias<N / 2> {};
template <int N>
struct DerivedTypeAlias : TypeAlias<N / 2>
{};
DLL_API ImplementsAbstractFoo freeFunctionReturnsVirtualDtor();
DLL_API void integerOverload(int i);
@ -1450,22 +1494,27 @@ typedef const char* LPCSTR; @@ -1450,22 +1494,27 @@ typedef const char* LPCSTR;
DLL_API LPCSTR TakeTypedefedMappedType(LPCSTR string);
DLL_API std::string UTF8;
typedef enum SE4IpAddr_Tag {
typedef enum SE4IpAddr_Tag
{
V4,
V6,
} SE4IpAddr_Tag;
typedef struct {
typedef struct
{
uint8_t _0[4];
} SE4V4_Body;
typedef struct {
typedef struct
{
uint8_t _0[16];
} SE4V6_Body;
typedef struct {
typedef struct
{
SE4IpAddr_Tag tag;
union {
union
{
SE4V4_Body v4;
SE4V6_Body v6;
};
@ -1484,27 +1533,32 @@ uint16_t DLL_API TestStructWithCopyCtorByValue(StructWithCopyCtor s); @@ -1484,27 +1533,32 @@ uint16_t DLL_API TestStructWithCopyCtorByValue(StructWithCopyCtor s);
struct BaseCovariant;
typedef std::unique_ptr<BaseCovariant> PtrCovariant;
struct DLL_API BaseCovariant {
struct DLL_API BaseCovariant
{
virtual ~BaseCovariant();
virtual PtrCovariant clone() const = 0;
};
struct DLL_API DerivedCovariant: public BaseCovariant {
struct DLL_API DerivedCovariant : public BaseCovariant
{
virtual ~DerivedCovariant();
std::unique_ptr<BaseCovariant> clone() const override {
return PtrCovariant(new DerivedCovariant());
}
std::unique_ptr<BaseCovariant> clone() const override
{
return PtrCovariant(new DerivedCovariant());
}
};
// Issue: https://github.com/mono/CppSharp/issues/1268
template <typename T>
class AbstractClassTemplate {
public:
class AbstractClassTemplate
{
public:
virtual void func() = 0;
};
class DerivedClass: public AbstractClassTemplate<int> {
public:
class DerivedClass : public AbstractClassTemplate<int>
{
public:
void func() override {}
};
@ -1512,15 +1566,17 @@ class DerivedClass: public AbstractClassTemplate<int> { @@ -1512,15 +1566,17 @@ class DerivedClass: public AbstractClassTemplate<int> {
#include <functional>
template <typename X, typename Y>
class TemplateClassBase {
public:
class TemplateClassBase
{
public:
using XType = X;
};
template <typename A, typename B = A>
class TemplateClass : TemplateClassBase<A,B> {
public:
using typename TemplateClassBase<A,B>::XType;
class TemplateClass : TemplateClassBase<A, B>
{
public:
using typename TemplateClassBase<A, B>::XType;
using Func = std::function<B(XType)>;
explicit TemplateClass(Func function) {}
};
@ -1536,9 +1592,13 @@ public: @@ -1536,9 +1592,13 @@ public:
};
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;
@ -1547,11 +1607,11 @@ struct DLL_API PointerToTypedefPointerTest @@ -1547,11 +1607,11 @@ struct DLL_API PointerToTypedefPointerTest
{
int val;
};
typedef PointerToTypedefPointerTest *LPPointerToTypedefPointerTest;
typedef PointerToTypedefPointerTest* LPPointerToTypedefPointerTest;
void DLL_API PointerToTypedefPointerTestMethod(LPPointerToTypedefPointerTest* lp, int valToSet);
typedef int *LPINT;
typedef int* LPINT;
void DLL_API PointerToPrimitiveTypedefPointerTestMethod(LPINT lp, int valToSet);

1
tests/dotnet/Empty/Empty.h

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

4
tests/dotnet/Encodings/Encodings.h

@ -7,8 +7,8 @@ public: @@ -7,8 +7,8 @@ public:
const char* Unicode;
static std::string StringVariable;
// TODO: VC++ does not support char16
// char16 chr16;
// TODO: VC++ does not support char16
// char16 chr16;
// TODO: move this, it has nothing to do with Unicode, it's here only not to break the CLI branch
int operator[](int i) const;

6
tests/dotnet/NamespacesBase/NamespacesBase.cpp

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

26
tests/dotnet/NamespacesBase/NamespacesBase.h

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

3
tests/dotnet/NamespacesDerived/Independent.h

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

12
tests/dotnet/NamespacesDerived/NamespacesDerived.cpp

@ -1,11 +1,17 @@ @@ -1,11 +1,17 @@
#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)
{
}
@ -107,7 +113,7 @@ int TestComments::SBAttachInfo(const char* path, bool wait_for) @@ -107,7 +113,7 @@ int TestComments::SBAttachInfo(const char* path, bool wait_for)
return 0;
}
void TestComments::glfwDestroyWindow(int *window)
void TestComments::glfwDestroyWindow(int* window)
{
}

82
tests/dotnet/NamespacesDerived/NamespacesDerived.h

@ -7,16 +7,15 @@ @@ -7,16 +7,15 @@
// Namespace clashes with NamespacesBase.OverlappingNamespace
// Test whether qualified names turn out right.
namespace OverlappingNamespace
namespace OverlappingNamespace {
class DLL_API InDerivedLib
{
class DLL_API InDerivedLib
{
public:
InDerivedLib();
Base parentNSComponent;
ColorsEnum color;
};
}
public:
InDerivedLib();
Base parentNSComponent;
ColorsEnum color;
};
} // namespace OverlappingNamespace
// Using a type imported from a different library.
@ -46,7 +45,8 @@ class Base3 @@ -46,7 +45,8 @@ class Base3
{
};
template <typename T> class TemplateClass;
template <typename T>
class TemplateClass;
class DLL_API Derived2 : public Base3
{
@ -66,6 +66,7 @@ public: @@ -66,6 +66,7 @@ public:
typedef DependentFields<int> LocalTypedefSpecialization;
LocalTypedefSpecialization getLocalTypedefSpecialization();
Abstract* getAbstract();
private:
TemplateClass<int> t;
TemplateClass<Derived> d;
@ -97,7 +98,7 @@ class DLL_API DerivedFromSecondaryBaseInDependency : public Derived, public Seco @@ -97,7 +98,7 @@ class DLL_API DerivedFromSecondaryBaseInDependency : public Derived, public Seco
{
};
template<typename T>
template <typename T>
class CustomAllocator
{
public:
@ -107,7 +108,8 @@ public: @@ -107,7 +108,8 @@ public:
CustomAllocator() = default;
template <typename U>
CustomAllocator(const CustomAllocator<U>&) noexcept {
CustomAllocator(const CustomAllocator<U>&) noexcept
{
}
T* allocate(size_t cnt, const void* = 0) { return 0; }
@ -121,25 +123,24 @@ private: @@ -121,25 +123,24 @@ private:
std::basic_string<char, std::char_traits<char>, CustomAllocator<char>> customAllocatedString;
};
template<class T, class Alloc = CustomAllocator<T>>
template <class T, class Alloc = CustomAllocator<T>>
using vector = ::std::vector<T, Alloc>;
class DLL_API StdFields
{
private:
vector<unsigned int, CustomAllocator<unsigned int>> customAllocatedVector;
vector<unsigned int, CustomAllocator<unsigned int>> customAllocatedVector;
};
DLL_API bool operator<<(const Base& b, const char* str);
namespace NamespacesBase
namespace NamespacesBase {
class DLL_API ClassInNamespaceNamedAfterDependency
{
class DLL_API ClassInNamespaceNamedAfterDependency
{
private:
Base base;
};
}
private:
Base base;
};
} // namespace NamespacesBase
/// Hash set/map base class.
/** Note that to prevent extra memory use due to vtable pointer, %HashBase intentionally does not declare a virtual destructor
@ -183,30 +184,31 @@ public: @@ -183,30 +184,31 @@ public:
int SBAttachInfo(const char* path, bool wait_for);
/*! @brief Destroys the specified window and its context.
*
* This function destroys the specified window and its context. On calling
* this function, no further callbacks will be called for that window.
*
* If the context of the specified window is current on the main thread, it is
* detached before being destroyed.
*
* @param[in] window The window to destroy.
*
* @note The context of the specified window must not be current on any other
* thread when this function is called.
*
* @reentrancy This function must not be called from a callback.
*
* @thread_safety This function must only be called from the main thread.
*
* @since Added in version 3.0. Replaces `glfwCloseWindow`.
*/
*
* This function destroys the specified window and its context. On calling
* this function, no further callbacks will be called for that window.
*
* If the context of the specified window is current on the main thread, it is
* detached before being destroyed.
*
* @param[in] window The window to destroy.
*
* @note The context of the specified window must not be current on any other
* thread when this function is called.
*
* @reentrancy This function must not be called from a callback.
*
* @thread_safety This function must only be called from the main thread.
*
* @since Added in version 3.0. Replaces `glfwCloseWindow`.
*/
void glfwDestroyWindow(int* window);
/**
* <sip:alice@example.net>
*/
class LinphoneAddress {};
class LinphoneAddress
{};
};
DLL_API void forceUseSpecializations(ForwardedInIndependentHeader value);

98
tests/dotnet/Native/AST.h

@ -4,32 +4,41 @@ @@ -4,32 +4,41 @@
void TestParameterProperties(bool a, const short& b, int* c = nullptr) {};
// Tests various AST helper methods (like FindClass, FindOperator etc.)
namespace Math
{
// Tests FindClass("Math::Complex")
struct Complex {
Complex(double r, double i) : re(r), im(i) {}
Complex operator+(Complex &other);
private:
double re, im;
};
namespace Math {
// Tests FindClass("Math::Complex")
struct Complex
{
Complex(double r, double i)
: re(r)
, im(i)
{
}
Complex operator+(Complex& other);
// Tests FindTypedef("Math::Single")
typedef float Single;
private:
double re, im;
};
// Tests FindOperator method
Complex Complex::operator+(Complex &other) {
return Complex(re + other.re, im + other.im);
}
// Tests FindTypedef("Math::Single")
typedef float Single;
void function();
// Tests FindOperator method
Complex Complex::operator+(Complex& other)
{
return Complex(re + other.re, im + other.im);
}
void function();
} // namespace Math
// Tests Enum.ItemByName
enum TestASTEnumItemByName { TestItemByName };
enum TestASTEnumItemByName
{
TestItemByName
};
// Tests class templates
template<typename T>
template <typename T>
class TestTemplateClass
{
public:
@ -45,12 +54,27 @@ public: @@ -45,12 +54,27 @@ public:
class TestTemplateFunctions
{
public:
template<typename T> T Identity(T x) { 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; }
template <typename T>
T Identity(T x)
{
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
@ -65,12 +89,11 @@ public: @@ -65,12 +89,11 @@ public:
TestTemplateClassInt* CreateIntTemplate();
};
namespace HidesClass
namespace HidesClass {
class HiddenInNamespace
{
class HiddenInNamespace
{
};
}
};
} // namespace HidesClass
void testSignature();
@ -105,10 +128,10 @@ Q_SIGNALS: @@ -105,10 +128,10 @@ Q_SIGNALS:
class Atomics
{
#if defined( __clang__ ) && defined( __has_extension )
# if __has_extension( __c_atomic__ )
#if defined(__clang__) && defined(__has_extension)
#if __has_extension(__c_atomic__)
_Atomic(int) AtomicInt;
# endif
#endif
#endif
};
@ -145,7 +168,7 @@ void noExceptFalse() noexcept(false); @@ -145,7 +168,7 @@ void noExceptFalse() noexcept(false);
template <typename T1, typename T2>
bool functionWithSpecInfo(const T1& t11, const T1& t12, const T2& t2);
template<>
template <>
bool functionWithSpecInfo(const float& t11, const float& t12, const float& t2);
void functionWithSpecializationArg(const TestTemplateClass<int>);
@ -162,12 +185,15 @@ void testInlineAssembly() @@ -162,12 +185,15 @@ void testInlineAssembly()
}
// Tests redeclarations
class ClassA {};
class ClassA
{};
class ClassB {};
class ClassB
{};
class ClassB;
class ClassC {};
class ClassC
{};
class ClassC;
class ClassC;

3
tests/dotnet/Native/Enums.h

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

77
tests/dotnet/Native/Passes.h

@ -1,17 +1,17 @@ @@ -1,17 +1,17 @@
enum FlagEnum
{
A = 1 << 0,
B = 1 << 1,
C = 1 << 2,
D = 1 << 3,
A = 1 << 0,
B = 1 << 1,
C = 1 << 2,
D = 1 << 3,
};
enum FlagEnum2
{
A1 = 1 << 0,
B1 = 3,
C1 = 1 << 2,
D1 = 1 << 4,
A1 = 1 << 0,
B1 = 3,
C1 = 1 << 2,
D1 = 1 << 4,
};
enum class BoolEnum : bool
@ -30,14 +30,14 @@ enum class UCharEnum : unsigned char @@ -30,14 +30,14 @@ enum class UCharEnum : unsigned char
class Foo
{
void toIgnore() { }
void toIgnore() {}
};
void FooStart(Foo*, int);
struct TestRename
{
int lowerCaseMethod();
int lowerCaseField;
int lowerCaseMethod();
int lowerCaseField;
};
/// <summary>A simple test.</summary>
@ -49,7 +49,7 @@ struct TestReadOnlyProperties @@ -49,7 +49,7 @@ struct TestReadOnlyProperties
{
int readOnlyProperty;
int getReadOnlyPropertyMethod() { return 0; }
void setReadOnlyPropertyMethod(int value) { }
void setReadOnlyPropertyMethod(int value) {}
};
#define TEST_ENUM_ITEM_NAME_0 0
@ -66,15 +66,15 @@ enum @@ -66,15 +66,15 @@ enum
#define TEST_ENUM_MAX_BYTE 255
#define TEST_ENUM_MAX_SHORT 32767
#define TEST_ENUM_MAX_USHORT 65535
#define TEST_ENUM_MAX_INT 2147483647
#define TEST_ENUM_MAX_UINT 4294967295
#define TEST_ENUM_MAX_LONG 9223372036854775807
#define TEST_ENUM_MAX_ULONG 18446744073709551615
#define TEST_ENUM_MAX_INT 2147483647
#define TEST_ENUM_MAX_UINT 4294967295
#define TEST_ENUM_MAX_LONG 9223372036854775807
#define TEST_ENUM_MAX_ULONG 18446744073709551615
#define TEST_ENUM_MIN_SBYTE -128
#define TEST_ENUM_MIN_SHORT -32768
#define TEST_ENUM_MIN_INT -2147483648
#define TEST_ENUM_MIN_LONG -9223372036854775808
#define TEST_ENUM_MIN_INT -2147483648
#define TEST_ENUM_MIN_LONG -9223372036854775808
// Test #defines with bit operators
#define TEST_BITWISE_OR_1 0x7F | 0x80
@ -92,12 +92,26 @@ enum @@ -92,12 +92,26 @@ enum
#define TEST_INT_PLUS_LONG 5 + 2147483648
// TestStructInheritance
struct S1 { int F1, F2; };
struct S2 : S1 { int F3; };
struct S1
{
int F1, F2;
};
struct S2 : S1
{
int F3;
};
// Tests unnamed enums
enum { Unnamed_Enum_1_A = 1, Unnamed_Enum_1_B = 2 };
enum { Unnamed_Enum_2_A = 3, Unnamed_Enum_2_B = 4 };
enum
{
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
#include "Enums.h"
@ -124,25 +138,26 @@ struct TestMethodAsInternal @@ -124,25 +138,26 @@ struct TestMethodAsInternal
class ClassWithAbstractOperator
{
virtual operator int() = 0;
virtual operator int() = 0;
};
enum ConnectionRole
{
Role1, Role2
Role1,
Role2
};
bool ConnectionRoleToString(const ConnectionRole& role, const char* role_str);
class TestFlattenAnonymousTypesToFields
{
/* TODO: Enable this code (and respective test in TestPasses).
public:
union
{
int Public;
};
*/
/* TODO: Enable this code (and respective test in TestPasses).
public:
union
{
int Public;
};
*/
protected:
union
{

12
tests/dotnet/Native/Templates.h

@ -1,16 +1,16 @@ @@ -1,16 +1,16 @@
template<typename T, T Value>
template <typename T, T Value>
struct integral_constant
{
static constexpr T value = Value;
};
template<bool Value>
template <bool Value>
using bool_constant = integral_constant<bool, Value>;
template<class T>
template <class T>
struct is_integral : integral_constant<bool, false>
{ };
{};
template<typename T>
template <typename T>
struct is_arithmetic : bool_constant<is_integral<T>::value>
{ };
{};

2
tests/dotnet/StandardLib/StandardLib.h

@ -19,7 +19,7 @@ struct DLL_API TestVectors @@ -19,7 +19,7 @@ struct DLL_API TestVectors
TestVectors();
std::vector<int> GetIntVector();
int SumIntVector(std::vector<int>& vec);
// Should get mapped to List<int>
std::vector<int> IntVector;
// Should get mapped to List<IntPtr>

4
tests/dotnet/Tests.h

@ -22,10 +22,10 @@ @@ -22,10 +22,10 @@
// HACK: work around https://developercommunity.visualstudio.com/content/problem/1269158/c4251-shown-for-any-not-explicitly-exported-templa.html
// harmless and requires exporting all template specializations
#pragma warning (disable : 4251 )
#pragma warning(disable : 4251)
#else
#define DLL_API __attribute__ ((visibility ("default")))
#define DLL_API __attribute__((visibility("default")))
#ifndef STDCALL
#if defined(WINDOWS)

1
tests/dotnet/VTables/VTables.cpp

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

1
tests/dotnet/VTables/VTables.h

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

Loading…
Cancel
Save