diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000..2e4d76b3 --- /dev/null +++ b/.clang-format @@ -0,0 +1,80 @@ +#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#- +Language : Cpp +BasedOnStyle : Microsoft +Standard : Latest +#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#- +AccessModifierOffset : -4 +AlignTrailingComments : + Kind : Always + OverEmptyLines : 0 + +AllowAllParametersOfDeclarationOnNextLine : false +AllowShortBlocksOnASingleLine : Empty +AllowShortIfStatementsOnASingleLine : Never +AllowShortLoopsOnASingleLine : false +AllowShortCaseLabelsOnASingleLine : true +AllowShortFunctionsOnASingleLine : Inline +AllowShortLambdasOnASingleLine : Empty +AlwaysBreakTemplateDeclarations : Yes +BinPackParameters : false + +BreakBeforeBraces : Custom +BraceWrapping : + AfterCaseLabel : true + AfterClass : true + AfterControlStatement : Always + AfterEnum : true + AfterFunction : true + AfterNamespace : false + AfterObjCDeclaration : true + AfterStruct : true + AfterUnion : true + AfterExternBlock : true + BeforeCatch : true + BeforeElse : true + BeforeLambdaBody : true + BeforeWhile : true + IndentBraces : false + SplitEmptyFunction : true + SplitEmptyRecord : false + SplitEmptyNamespace : true + +BreakAfterAttributes : Leave +BreakBeforeTernaryOperators : false +BreakConstructorInitializers : BeforeComma +BreakBeforeConceptDeclarations : Always + +ColumnLimit : 0 +Cpp11BracedListStyle : false +CompactNamespaces : true +IndentWidth : 4 +IndentCaseLabels : true +IndentRequiresClause : true +SortIncludes : Never +IncludeBlocks : Preserve +KeepEmptyLinesAtTheStartOfBlocks : true +MaxEmptyLinesToKeep : 2 +EmptyLineAfterAccessModifier : Leave +EmptyLineBeforeAccessModifier : LogicalBlock +NamespaceIndentation : Inner +PointerAlignment : Left +SpacesBeforeTrailingComments : 1 +SpacesInAngles : Never +SpacesInSquareBrackets : false +RequiresClausePosition : OwnLine +RequiresExpressionIndentation : Keyword + +SpacesInLineCommentPrefix : + Minimum : 1 + Maximum : -1 + +TabWidth : 4 +UseTab : Never + +#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#- +#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#- + +--- +Language: CSharp +BasedOnStyle : Microsoft +Standard : Latest \ No newline at end of file diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..8e9e04ad --- /dev/null +++ b/.editorconfig @@ -0,0 +1,90 @@ +[*.cs] + +# IDE0011: Add braces +csharp_prefer_braces = false:silent + +# IDE0008: Use explicit type +dotnet_diagnostic.IDE0008.severity = none +csharp_indent_labels = one_less_than_current +csharp_using_directive_placement = outside_namespace:silent +csharp_prefer_simple_using_statement = true:suggestion +csharp_style_namespace_declarations = block_scoped:silent +csharp_style_expression_bodied_methods = false:silent +csharp_style_expression_bodied_constructors = false:silent +csharp_style_expression_bodied_operators = false:silent +csharp_style_expression_bodied_properties = true:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_accessors = true:silent +csharp_style_expression_bodied_lambdas = true:silent +csharp_style_expression_bodied_local_functions = false:silent +csharp_style_throw_expression = true:suggestion +csharp_style_prefer_null_check_over_type_check = true:suggestion +csharp_style_prefer_method_group_conversion = true:silent +csharp_space_around_binary_operators = before_and_after + +[*.{cs,vb}] +#### Naming styles #### + +# Naming rules + +dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i + +dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case + +# Symbol specifications + +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface.required_modifiers = + +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types.required_modifiers = + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.required_modifiers = + +# Naming styles + +dotnet_naming_style.begins_with_i.required_prefix = I +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.capitalization = pascal_case + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case +dotnet_style_operator_placement_when_wrapping = beginning_of_line +tab_width = 4 +indent_size = 4 +end_of_line = lf +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_auto_properties = true:silent +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_prefer_simplified_boolean_expressions = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:silent +dotnet_style_prefer_conditional_expression_over_return = true:silent +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_compound_assignment = true:suggestion +dotnet_style_prefer_simplified_interpolation = true:suggestion +dotnet_style_namespace_match_folder = true:suggestion diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 00000000..094a1536 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,11 @@ +# When making commits that are strictly formatting/style changes, add the +# commit hash here, so git blame can ignore the change. See docs for more +# details: +# https://git-scm.com/docs/git-config#Documentation/git-config.txt-blameignoreRevsFile +# +# +# Example entries: +# +# # Formating changes +# # rename something internal +4352a86efc9a0270ecd0c1712c9f470a9bd8fb75 # Format all c++ files \ No newline at end of file diff --git a/.github/workflows/clang-format-check.yml b/.github/workflows/clang-format-check.yml new file mode 100644 index 00000000..63a04409 --- /dev/null +++ b/.github/workflows/clang-format-check.yml @@ -0,0 +1,30 @@ +name: clang-format Check + + +on: [push, pull_request, workflow_dispatch] + +# Cancel any previous workflows if the pull request was updated +concurrency: + group: ${{ github.workflow }}-${{ github.ref || github.run_id }} + cancel-in-progress: true + +jobs: + formatting-check: + name: Formatting Check + runs-on: ubuntu-latest + strategy: + matrix: + path: + - 'src' + - 'tests' + + steps: + - uses: actions/checkout@v4 + + - name: Run clang-format style check for C/C++/Protobuf programs. + uses: jidicula/clang-format-action@v4.14.0 + with: + clang-format-version: 19 + fallback-style: none + check-path: ${{ matrix.path }} + exclude-regex: '(Bindings|CLI)/|(CppParser/(Parse)?(Expr|Stmt))' diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 33827778..c98fea6f 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -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: steps: - uses: actions/checkout@v4 - with: - fetch-depth: '0' - name: Set version run: nbgv cloud --all-vars diff --git a/.gitignore b/.gitignore index 4d06c6b3..c6a831cb 100644 --- a/.gitignore +++ b/.gitignore @@ -17,7 +17,6 @@ src/generator/generator .DS_Store *.user *.suo -*.DotSettings *.sdf *.opensdf *.pdb diff --git a/CppSharp.sln.DotSettings b/CppSharp.sln.DotSettings new file mode 100644 index 00000000..68fb4a1a --- /dev/null +++ b/CppSharp.sln.DotSettings @@ -0,0 +1,5 @@ + + CLI + MSVC + True + True \ No newline at end of file diff --git a/RunClangFormat.sh b/RunClangFormat.sh new file mode 100644 index 00000000..454f37fd --- /dev/null +++ b/RunClangFormat.sh @@ -0,0 +1,97 @@ +#!/usr/bin/env bash +set -e +solution_dir=$(cd "$(dirname "$0")"; pwd) +FOLDERS="src tests" +ALLOWED_EXTENSIONS_RE=".*\.\(cpp\|hpp\|c\|h\|inl\)" +EXCLUSION_RE="\(Bindings\|CLI\)/\|\(CppParser/\(Parse\)?\(Expr\|Stmt\)\)" +CLANG_FORMAT_OPTIONS="--fallback-style=none -i --verbose" + +clang_format="" +VS_INSTALL_DIR="" + + +format() +{ + find_clang_format + + DRY_RUN=0 + # read -p "Dry run? (1/0): " DRY_RUN + + if [ "$DRY_RUN" -eq 1 ]; then + CLANG_FORMAT_OPTIONS="$CLANG_FORMAT_OPTIONS --dry-run --Werror" + fi + + # Format all files, in the specified list of directories + # Loop through each file in the directory (and subdirectories) + for p in $FOLDERS; do + echo "Formatting files in folder \"$p\"..." + cd "$solution_dir/$p" + + file_list=$(find . -type f -regex $ALLOWED_EXTENSIONS_RE -and -not -regex ".*/\($EXCLUSION_RE\).*" -print) + + "$clang_format" $CLANG_FORMAT_OPTIONS $file_list + + cd .. + done +} + +find_vswhere() +{ + echo "Looking for 'vswhere'..." + VSWHERE_PATH="$(printenv 'ProgramFiles(x86)')/Microsoft Visual Studio/Installer/vswhere.exe" + + if [ -x "$(command -v vswhere.exe)" ]; then + vswhere="vswhere.exe" + elif [ -f "$VSWHERE_PATH" ]; then + vswhere=$VSWHERE_PATH + else + echo -e "Could not locate vswhere.exe at:\n " $VSWHERE_PATH + read -n 1 -s -r -p "Press any key to continue, or Ctrl+C to exit" key + exit 1 + fi + + echo -e "Found 'vswhere.exe':\n @" $vswhere "\n" +} + +find_visual_studio() +{ + find_vswhere + + echo "Looking for visual studio..." + + # Find visual studio installation path + VS_INSTALL_DIR=$("$vswhere" -latest -property installationPath) + + # Find visual studio installation path + if [ ! -d "$VS_INSTALL_DIR" ]; then + echo -e "Visual Studio Installation directory not found at vswhere specified path:\n " $VS_INSTALL_DIR + read -n 1 -s -r -p "Press any key to continue, or Ctrl+C to exit" key + exit 1 + fi + + echo -e "Found Visual Studio:\n @" $VS_INSTALL_DIR "\n" +} + +find_clang_format() +{ + echo "Looking for clang-format..." + find_visual_studio + + CLANG_FORMAT_PATH="VC/Tools/Llvm/bin/clang-format.exe" + clang_format="$VS_INSTALL_DIR/$CLANG_FORMAT_PATH" + + # Verify clang-format actually exists as well + if ! [ -f "$clang_format" ]; then + echo "clang-format.exe could not be located at: $clang_format" + read -n 1 -s -r -p "Press any key to continue, or Ctrl+C to exit" key + exit 1 + fi + + echo -e "Found clang-format.exe:\n" " Using" $("$clang_format" --version) "\n" " @" $clang_format "\n" +} + +format + +echo "Done!" +read -n 1 -s -r -p "Press any key to continue, or Ctrl+C to exit" key +exit 0 \ No newline at end of file diff --git a/src/CppParser/APValuePrinter.h b/src/CppParser/APValuePrinter.h index d193c241..0d7c7343 100644 --- a/src/CppParser/APValuePrinter.h +++ b/src/CppParser/APValuePrinter.h @@ -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()->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()->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()) + 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()) - return false; - else if (DynamicAllocLValue DA = base.dyn_cast()) - return false; - else + case APValue::LValue: { - base.get()->printPretty(out, nullptr, ctx.getPrintingPolicy()); - return true; + auto base = value.getLValueBase(); + + if (const ValueDecl* VD = base.dyn_cast()) + { + out << *VD; + return true; + } + else if (TypeInfoLValue TI = base.dyn_cast()) + return false; + else if (DynamicAllocLValue DA = base.dyn_cast()) + return false; + else + { + base.get()->printPretty(out, nullptr, ctx.getPrintingPolicy()); + return true; + } } } - } return false; } }; -} } \ No newline at end of file +}} // namespace CppSharp::CppParser \ No newline at end of file diff --git a/src/CppParser/AST.cpp b/src/CppParser/AST.cpp index 0ab83c59..e5823a23 100644 --- a/src/CppParser/AST.cpp +++ b/src/CppParser/AST.cpp @@ -1,9 +1,9 @@ /************************************************************************ -* -* CppSharp -* Licensed under the MIT license. -* -************************************************************************/ + * + * CppSharp + * Licensed under the MIT license. + * + ************************************************************************/ #include "AST.h" #include @@ -12,12 +12,14 @@ #include // copy from widenPath ('llvm/lib/Support/Windows/Path.inc') -static std::string normalizePath(const std::string & File) { +static std::string normalizePath(const std::string& File) +{ llvm::SmallString<2 * 128> Result; for (llvm::sys::path::const_iterator I = llvm::sys::path::begin(File), - E = llvm::sys::path::end(File); - I != E; ++I) { + E = llvm::sys::path::end(File); + I != E; ++I) + { if (I->size() == 1 && *I == ".") continue; if (I->size() == 2 && *I == "..") @@ -34,1078 +36,1421 @@ static std::string normalizePath(const std::string & File) { return Result.c_str(); } -template -static std::vector split(const T & str, const T & delimiters) { +template +static std::vector split(const T& str, const T& delimiters) +{ std::vector v; - if (str.length() == 0) { + if (str.length() == 0) + { v.push_back(str); return v; } typename T::size_type start = 0; auto pos = str.find_first_of(delimiters, start); - while(pos != T::npos) { - if(pos != start) // ignore empty tokens + while (pos != T::npos) + { + if (pos != start) // ignore empty tokens v.emplace_back(str, start, pos - start); start = pos + 1; pos = str.find_first_of(delimiters, start); } - if(start < str.length()) // ignore trailing delimiter - // add what's left of the string + if (start < str.length()) // ignore trailing delimiter + // add what's left of the string v.emplace_back(str, start, str.length() - start); return v; } namespace CppSharp { namespace CppParser { namespace AST { -static void deleteExpression(ExpressionObsolete* expression) -{ - if (expression) + static void deleteExpression(ExpressionObsolete* expression) { - // HACK: see https://github.com/mono/CppSharp/issues/598 - switch (expression->_class) + if (expression) { - case StatementClassObsolete::BinaryOperator: - delete static_cast(expression); - break; - case StatementClassObsolete::CallExprClass: - delete static_cast(expression); - break; - case StatementClassObsolete::CXXConstructExprClass: - delete static_cast(expression); - break; - default: - delete expression; - break; + // HACK: see https://github.com/mono/CppSharp/issues/598 + switch (expression->_class) + { + case StatementClassObsolete::BinaryOperator: + delete static_cast(expression); + break; + case StatementClassObsolete::CallExprClass: + delete static_cast(expression); + break; + case StatementClassObsolete::CXXConstructExprClass: + delete static_cast(expression); + break; + default: + delete expression; + break; + } } } -} - -Type::Type(TypeKind kind) : kind(kind) {} -Type::Type(const Type& rhs) : kind(rhs.kind), isDependent(rhs.isDependent) {} - -QualifiedType::QualifiedType() : type(0) {} - -TagType::TagType() : Type(TypeKind::Tag) {} - -ArrayType::ArrayType() : Type(TypeKind::Array), size(0), elementSize(0) {} - -FunctionType::FunctionType() - : Type(TypeKind::Function) - , callingConvention(CallingConvention::Default) - , exceptionSpecType(ExceptionSpecType::None) -{ -} - -FunctionType::~FunctionType() {} -DEF_VECTOR(FunctionType, Parameter*, Parameters) + Type::Type(TypeKind kind) + : kind(kind) + { + } + Type::Type(const Type& rhs) + : kind(rhs.kind) + , isDependent(rhs.isDependent) + { + } -PointerType::PointerType() : Type(TypeKind::Pointer) {} + QualifiedType::QualifiedType() + : type(0) + { + } -MemberPointerType::MemberPointerType() : Type(TypeKind::MemberPointer) {} + TagType::TagType() + : Type(TypeKind::Tag) + { + } -TypedefType::TypedefType() : Type(TypeKind::Typedef), declaration(0) {} + ArrayType::ArrayType() + : Type(TypeKind::Array) + , size(0) + , elementSize(0) + { + } -AttributedType::AttributedType() : Type(TypeKind::Attributed) {} + FunctionType::FunctionType() + : Type(TypeKind::Function) + , callingConvention(CallingConvention::Default) + , exceptionSpecType(ExceptionSpecType::None) + { + } -DecayedType::DecayedType() : Type(TypeKind::Decayed) {} + FunctionType::~FunctionType() {} -// Template -TemplateParameter::TemplateParameter(DeclarationKind kind) - : Declaration(kind) - , depth(0) - , index(0) - , isParameterPack(false) -{ -} + DEF_VECTOR(FunctionType, Parameter*, Parameters) -TemplateParameter::~TemplateParameter() -{ -} - -TemplateTemplateParameter::TemplateTemplateParameter() - : Template(DeclarationKind::TemplateTemplateParm) - , isParameterPack(false) - , isPackExpansion(false) - , isExpandedParameterPack(false) -{ -} + PointerType::PointerType() + : Type(TypeKind::Pointer) + { + } -TemplateTemplateParameter::~TemplateTemplateParameter() -{ -} + MemberPointerType::MemberPointerType() + : Type(TypeKind::MemberPointer) + { + } -// TemplateParameter -TypeTemplateParameter::TypeTemplateParameter() - : TemplateParameter(DeclarationKind::TemplateTypeParm) -{ -} + TypedefType::TypedefType() + : Type(TypeKind::Typedef) + , declaration(0) + { + } -TypeTemplateParameter::TypeTemplateParameter(const TypeTemplateParameter& rhs) - : TemplateParameter(rhs.kind) - , defaultArgument(rhs.defaultArgument) -{ -} + AttributedType::AttributedType() + : Type(TypeKind::Attributed) + { + } -TypeTemplateParameter::~TypeTemplateParameter() {} + DecayedType::DecayedType() + : Type(TypeKind::Decayed) + { + } -NonTypeTemplateParameter::NonTypeTemplateParameter() - : TemplateParameter(DeclarationKind::NonTypeTemplateParm) - , defaultArgument(0) - , position(0) - , isPackExpansion(false) - , isExpandedParameterPack(false) -{ -} + // Template + TemplateParameter::TemplateParameter(DeclarationKind kind) + : Declaration(kind) + , depth(0) + , index(0) + , isParameterPack(false) + { + } -NonTypeTemplateParameter::NonTypeTemplateParameter(const NonTypeTemplateParameter& rhs) - : TemplateParameter(rhs.kind) - , defaultArgument(rhs.defaultArgument) - , position(rhs.position) - , isPackExpansion(rhs.isPackExpansion) - , isExpandedParameterPack(rhs.isExpandedParameterPack) - , type(rhs.type) -{ -} + TemplateParameter::~TemplateParameter() + { + } -NonTypeTemplateParameter::~NonTypeTemplateParameter() -{ - deleteExpression(defaultArgument); -} + TemplateTemplateParameter::TemplateTemplateParameter() + : Template(DeclarationKind::TemplateTemplateParm) + , isParameterPack(false) + , isPackExpansion(false) + , isExpandedParameterPack(false) + { + } -TemplateArgument::TemplateArgument() : declaration(0), integral(0) {} + TemplateTemplateParameter::~TemplateTemplateParameter() + { + } -TemplateSpecializationType::TemplateSpecializationType() - : Type(TypeKind::TemplateSpecialization), _template(0) {} + // TemplateParameter + TypeTemplateParameter::TypeTemplateParameter() + : TemplateParameter(DeclarationKind::TemplateTypeParm) + { + } -TemplateSpecializationType::TemplateSpecializationType( - const TemplateSpecializationType& rhs) : Type(rhs), - Arguments(rhs.Arguments), _template(rhs._template), desugared(rhs.desugared) {} + TypeTemplateParameter::TypeTemplateParameter(const TypeTemplateParameter& rhs) + : TemplateParameter(rhs.kind) + , defaultArgument(rhs.defaultArgument) + { + } -TemplateSpecializationType::~TemplateSpecializationType() {} + TypeTemplateParameter::~TypeTemplateParameter() {} -DEF_VECTOR(TemplateSpecializationType, TemplateArgument, Arguments) + NonTypeTemplateParameter::NonTypeTemplateParameter() + : TemplateParameter(DeclarationKind::NonTypeTemplateParm) + , defaultArgument(0) + , position(0) + , isPackExpansion(false) + , isExpandedParameterPack(false) + { + } -DependentTemplateSpecializationType::DependentTemplateSpecializationType() - : Type(TypeKind::DependentTemplateSpecialization) {} + NonTypeTemplateParameter::NonTypeTemplateParameter(const NonTypeTemplateParameter& rhs) + : TemplateParameter(rhs.kind) + , defaultArgument(rhs.defaultArgument) + , position(rhs.position) + , isPackExpansion(rhs.isPackExpansion) + , isExpandedParameterPack(rhs.isExpandedParameterPack) + , type(rhs.type) + { + } -DependentTemplateSpecializationType::DependentTemplateSpecializationType( - const DependentTemplateSpecializationType& rhs) : Type(rhs), - Arguments(rhs.Arguments), desugared(rhs.desugared) {} + NonTypeTemplateParameter::~NonTypeTemplateParameter() + { + deleteExpression(defaultArgument); + } -DependentTemplateSpecializationType::~DependentTemplateSpecializationType() {} + TemplateArgument::TemplateArgument() + : declaration(0) + , integral(0) + { + } -DEF_VECTOR(DependentTemplateSpecializationType, TemplateArgument, Arguments) + TemplateSpecializationType::TemplateSpecializationType() + : Type(TypeKind::TemplateSpecialization) + , _template(0) + { + } -TemplateParameterType::TemplateParameterType() : Type(TypeKind::TemplateParameter), parameter(0) {} + TemplateSpecializationType::TemplateSpecializationType( + const TemplateSpecializationType& rhs) + : Type(rhs) + , Arguments(rhs.Arguments) + , _template(rhs._template) + , desugared(rhs.desugared) + { + } -TemplateParameterType::~TemplateParameterType() {} + TemplateSpecializationType::~TemplateSpecializationType() {} -TemplateParameterSubstitutionType::TemplateParameterSubstitutionType() - : Type(TypeKind::TemplateParameterSubstitution), replacedParameter(0) {} + DEF_VECTOR(TemplateSpecializationType, TemplateArgument, Arguments) -InjectedClassNameType::InjectedClassNameType() - : Type(TypeKind::InjectedClassName) - , _class(0) -{ -} + DependentTemplateSpecializationType::DependentTemplateSpecializationType() + : Type(TypeKind::DependentTemplateSpecialization) + { + } -DependentNameType::DependentNameType() : Type(TypeKind::DependentName) {} + DependentTemplateSpecializationType::DependentTemplateSpecializationType( + const DependentTemplateSpecializationType& rhs) + : Type(rhs) + , Arguments(rhs.Arguments) + , desugared(rhs.desugared) + { + } -DependentNameType::~DependentNameType() {} + DependentTemplateSpecializationType::~DependentTemplateSpecializationType() {} -PackExpansionType::PackExpansionType() : Type(TypeKind::PackExpansion) {} + DEF_VECTOR(DependentTemplateSpecializationType, TemplateArgument, Arguments) -UnaryTransformType::UnaryTransformType() : Type(TypeKind::UnaryTransform) {} + TemplateParameterType::TemplateParameterType() + : Type(TypeKind::TemplateParameter) + , parameter(0) + { + } -UnresolvedUsingType::UnresolvedUsingType() : Type(TypeKind::UnresolvedUsing) {} + TemplateParameterType::~TemplateParameterType() {} -VectorType::VectorType() : Type(TypeKind::Vector), numElements(0) {} + TemplateParameterSubstitutionType::TemplateParameterSubstitutionType() + : Type(TypeKind::TemplateParameterSubstitution) + , replacedParameter(0) + { + } -BuiltinType::BuiltinType() : CppSharp::CppParser::AST::Type(TypeKind::Builtin) {} + InjectedClassNameType::InjectedClassNameType() + : Type(TypeKind::InjectedClassName) + , _class(0) + { + } -VTableComponent::VTableComponent() : offset(0), declaration(0) {} + DependentNameType::DependentNameType() + : Type(TypeKind::DependentName) + { + } -// VTableLayout -VTableLayout::VTableLayout() {} -VTableLayout::VTableLayout(const VTableLayout& rhs) : Components(rhs.Components) {} -VTableLayout::~VTableLayout() {} + DependentNameType::~DependentNameType() {} -DEF_VECTOR(VTableLayout, VTableComponent, Components) + PackExpansionType::PackExpansionType() + : Type(TypeKind::PackExpansion) + { + } -VFTableInfo::VFTableInfo() : VBTableIndex(0), VFPtrOffset(0), VFPtrFullOffset(0) {} -VFTableInfo::VFTableInfo(const VFTableInfo& rhs) : VBTableIndex(rhs.VBTableIndex), - VFPtrOffset(rhs.VFPtrOffset), VFPtrFullOffset(rhs.VFPtrFullOffset), - layout(rhs.layout) {} + UnaryTransformType::UnaryTransformType() + : Type(TypeKind::UnaryTransform) + { + } -LayoutField::LayoutField() : offset(0), fieldPtr(0) {} + UnresolvedUsingType::UnresolvedUsingType() + : Type(TypeKind::UnresolvedUsing) + { + } -LayoutField::LayoutField(const LayoutField & other) - : offset(other.offset) - , name(other.name) - , qualifiedType(other.qualifiedType) - , fieldPtr(other.fieldPtr) -{ -} + VectorType::VectorType() + : Type(TypeKind::Vector) + , numElements(0) + { + } -LayoutField::~LayoutField() {} + BuiltinType::BuiltinType() + : CppSharp::CppParser::AST::Type(TypeKind::Builtin) + { + } -LayoutBase::LayoutBase() : offset(0), _class(0) {} + VTableComponent::VTableComponent() + : offset(0) + , declaration(0) + { + } -LayoutBase::LayoutBase(const LayoutBase& other) : offset(other.offset), _class(other._class) {} + // VTableLayout + VTableLayout::VTableLayout() {} + VTableLayout::VTableLayout(const VTableLayout& rhs) + : Components(rhs.Components) + { + } + VTableLayout::~VTableLayout() {} -LayoutBase::~LayoutBase() {} + DEF_VECTOR(VTableLayout, VTableComponent, Components) -ClassLayout::ClassLayout() : ABI(CppAbi::Itanium), argABI(RecordArgABI::Default), - hasOwnVFPtr(false), VBPtrOffset(0), alignment(0), size(0), dataSize(0) {} + VFTableInfo::VFTableInfo() + : VBTableIndex(0) + , VFPtrOffset(0) + , VFPtrFullOffset(0) + { + } + VFTableInfo::VFTableInfo(const VFTableInfo& rhs) + : VBTableIndex(rhs.VBTableIndex) + , VFPtrOffset(rhs.VFPtrOffset) + , VFPtrFullOffset(rhs.VFPtrFullOffset) + , layout(rhs.layout) + { + } -DEF_VECTOR(ClassLayout, VFTableInfo, VFTables) + LayoutField::LayoutField() + : offset(0) + , fieldPtr(0) + { + } -DEF_VECTOR(ClassLayout, LayoutField, Fields) + LayoutField::LayoutField(const LayoutField& other) + : offset(other.offset) + , name(other.name) + , qualifiedType(other.qualifiedType) + , fieldPtr(other.fieldPtr) + { + } -DEF_VECTOR(ClassLayout, LayoutBase, Bases) + LayoutField::~LayoutField() {} -Declaration::Declaration(DeclarationKind kind) - : kind(kind) - , access(AccessSpecifier::Public) - , _namespace(0) - , location(0) - , lineNumberStart(0) - , lineNumberEnd(0) - , comment(0) - , isIncomplete(false) - , isDependent(false) - , isImplicit(false) - , isInvalid(false) - , isDeprecated(false) - , completeDeclaration(0) - , definitionOrder(0) - , originalPtr(0) - , alignAs(0) - , maxFieldAlignment(0) -{ -} + LayoutBase::LayoutBase() + : offset(0) + , _class(0) + { + } -Declaration::Declaration(const Declaration& rhs) - : kind(rhs.kind) - , access(rhs.access) - , _namespace(rhs._namespace) - , location(rhs.location.ID) - , lineNumberStart(rhs.lineNumberStart) - , lineNumberEnd(rhs.lineNumberEnd) - , name(rhs.name) - , comment(rhs.comment) - , debugText(rhs.debugText) - , isIncomplete(rhs.isIncomplete) - , isDependent(rhs.isDependent) - , isImplicit(rhs.isImplicit) - , isInvalid(rhs.isInvalid) - , isDeprecated(rhs.isDeprecated) - , completeDeclaration(rhs.completeDeclaration) - , definitionOrder(rhs.definitionOrder) - , PreprocessedEntities(rhs.PreprocessedEntities) - , originalPtr(rhs.originalPtr) -{ -} + LayoutBase::LayoutBase(const LayoutBase& other) + : offset(other.offset) + , _class(other._class) + { + } -Declaration::~Declaration() -{ -} + LayoutBase::~LayoutBase() {} -DEF_VECTOR(Declaration, PreprocessedEntity*, PreprocessedEntities) -DEF_VECTOR(Declaration, Declaration*, Redeclarations) - -DeclarationContext::DeclarationContext(DeclarationKind kind) - : Declaration(kind) - , isAnonymous(false) -{} - -DEF_VECTOR(DeclarationContext, Namespace*, Namespaces) -DEF_VECTOR(DeclarationContext, Enumeration*, Enums) -DEF_VECTOR(DeclarationContext, Function*, Functions) -DEF_VECTOR(DeclarationContext, Class*, Classes) -DEF_VECTOR(DeclarationContext, Template*, Templates) -DEF_VECTOR(DeclarationContext, TypedefDecl*, Typedefs) -DEF_VECTOR(DeclarationContext, TypeAlias*, TypeAliases) -DEF_VECTOR(DeclarationContext, Variable*, Variables) -DEF_VECTOR(DeclarationContext, Friend*, Friends) - -Declaration* DeclarationContext::FindAnonymous(const std::string& key) -{ - auto it = anonymous.find(key); - return (it != anonymous.end()) ? it->second : 0; -} + ClassLayout::ClassLayout() + : ABI(CppAbi::Itanium) + , argABI(RecordArgABI::Default) + , hasOwnVFPtr(false) + , VBPtrOffset(0) + , alignment(0) + , size(0) + , dataSize(0) + { + } -Namespace* DeclarationContext::FindNamespace(const std::string& Name) -{ - auto namespaces = split(Name, "::"); - return FindNamespace(namespaces); -} + DEF_VECTOR(ClassLayout, VFTableInfo, VFTables) + + DEF_VECTOR(ClassLayout, LayoutField, Fields) + + DEF_VECTOR(ClassLayout, LayoutBase, Bases) + + Declaration::Declaration(DeclarationKind kind) + : kind(kind) + , access(AccessSpecifier::Public) + , _namespace(0) + , location(0) + , lineNumberStart(0) + , lineNumberEnd(0) + , comment(0) + , isIncomplete(false) + , isDependent(false) + , isImplicit(false) + , isInvalid(false) + , isDeprecated(false) + , completeDeclaration(0) + , definitionOrder(0) + , originalPtr(0) + , alignAs(0) + , maxFieldAlignment(0) + { + } -Namespace* -DeclarationContext::FindNamespace(const std::vector& Namespaces) -{ - auto currentNamespace = this; - for (auto I = Namespaces.begin(), E = Namespaces.end(); I != E; ++I) + Declaration::Declaration(const Declaration& rhs) + : kind(rhs.kind) + , access(rhs.access) + , _namespace(rhs._namespace) + , location(rhs.location.ID) + , lineNumberStart(rhs.lineNumberStart) + , lineNumberEnd(rhs.lineNumberEnd) + , name(rhs.name) + , comment(rhs.comment) + , debugText(rhs.debugText) + , isIncomplete(rhs.isIncomplete) + , isDependent(rhs.isDependent) + , isImplicit(rhs.isImplicit) + , isInvalid(rhs.isInvalid) + , isDeprecated(rhs.isDeprecated) + , completeDeclaration(rhs.completeDeclaration) + , definitionOrder(rhs.definitionOrder) + , PreprocessedEntities(rhs.PreprocessedEntities) + , originalPtr(rhs.originalPtr) { - auto& _namespace = *I; + } - auto childNamespace = std::find_if(currentNamespace->Namespaces.begin(), - currentNamespace->Namespaces.end(), - [&](CppSharp::CppParser::AST::Namespace* ns) { - return ns->name == _namespace; - }); + Declaration::~Declaration() + { + } - if (childNamespace == currentNamespace->Namespaces.end()) - return nullptr; + DEF_VECTOR(Declaration, PreprocessedEntity*, PreprocessedEntities) + DEF_VECTOR(Declaration, Declaration*, Redeclarations) - currentNamespace = *childNamespace; + DeclarationContext::DeclarationContext(DeclarationKind kind) + : Declaration(kind) + , isAnonymous(false) + { } - return (CppSharp::CppParser::AST::Namespace*) currentNamespace; -} + DEF_VECTOR(DeclarationContext, Namespace*, Namespaces) + DEF_VECTOR(DeclarationContext, Enumeration*, Enums) + DEF_VECTOR(DeclarationContext, Function*, Functions) + DEF_VECTOR(DeclarationContext, Class*, Classes) + DEF_VECTOR(DeclarationContext, Template*, Templates) + DEF_VECTOR(DeclarationContext, TypedefDecl*, Typedefs) + DEF_VECTOR(DeclarationContext, TypeAlias*, TypeAliases) + DEF_VECTOR(DeclarationContext, Variable*, Variables) + DEF_VECTOR(DeclarationContext, Friend*, Friends) + + Declaration* DeclarationContext::FindAnonymous(const std::string& key) + { + auto it = anonymous.find(key); + return (it != anonymous.end()) ? it->second : 0; + } -Namespace* DeclarationContext::FindCreateNamespace(const std::string& Name) -{ - auto _namespace = FindNamespace(Name); + Namespace* DeclarationContext::FindNamespace(const std::string& Name) + { + auto namespaces = split(Name, "::"); + return FindNamespace(namespaces); + } - if (!_namespace) + Namespace* + DeclarationContext::FindNamespace(const std::vector& Namespaces) { - _namespace = new Namespace(); - _namespace->name = Name; - _namespace->_namespace = this; + auto currentNamespace = this; + for (auto I = Namespaces.begin(), E = Namespaces.end(); I != E; ++I) + { + auto& _namespace = *I; - Namespaces.push_back(_namespace); - } + auto childNamespace = std::find_if(currentNamespace->Namespaces.begin(), + currentNamespace->Namespaces.end(), + [&](CppSharp::CppParser::AST::Namespace* ns) + { + return ns->name == _namespace; + }); - return _namespace; -} + if (childNamespace == currentNamespace->Namespaces.end()) + return nullptr; -Class* DeclarationContext::FindClass(const void* OriginalPtr, - const std::string& Name, bool IsComplete) -{ - if (Name.empty()) return nullptr; + currentNamespace = *childNamespace; + } - auto entries = split(Name, "::"); + return (CppSharp::CppParser::AST::Namespace*)currentNamespace; + } - if (entries.size() == 1) + Namespace* DeclarationContext::FindCreateNamespace(const std::string& Name) { - auto _class = std::find_if(Classes.begin(), Classes.end(), - [OriginalPtr, Name, IsComplete](Class* klass) { - return (OriginalPtr && klass->originalPtr == OriginalPtr) || - (klass->name == Name && klass->isIncomplete == !IsComplete); }); + auto _namespace = FindNamespace(Name); + + if (!_namespace) + { + _namespace = new Namespace(); + _namespace->name = Name; + _namespace->_namespace = this; + + Namespaces.push_back(_namespace); + } - return _class != Classes.end() ? *_class : nullptr; + return _namespace; } - auto className = entries[entries.size() - 1]; + Class* DeclarationContext::FindClass(const void* OriginalPtr, + const std::string& Name, + bool IsComplete) + { + if (Name.empty()) + return nullptr; - std::vector namespaces; - std::copy_n(entries.begin(), entries.size() - 1, std::back_inserter(namespaces)); + auto entries = split(Name, "::"); - auto _namespace = FindNamespace(namespaces); - if (!_namespace) - return nullptr; + if (entries.size() == 1) + { + auto _class = std::find_if(Classes.begin(), Classes.end(), + [OriginalPtr, Name, IsComplete](Class* klass) + { + return (OriginalPtr && klass->originalPtr == OriginalPtr) || + (klass->name == Name && klass->isIncomplete == !IsComplete); + }); + + return _class != Classes.end() ? *_class : nullptr; + } - return _namespace->FindClass(OriginalPtr, className, IsComplete); -} + auto className = entries[entries.size() - 1]; -Class* DeclarationContext::CreateClass(const std::string& Name, bool IsComplete) -{ - auto _class = new Class(); - _class->name = Name; - _class->_namespace = this; - _class->isIncomplete = !IsComplete; + std::vector namespaces; + std::copy_n(entries.begin(), entries.size() - 1, std::back_inserter(namespaces)); - return _class; -} + auto _namespace = FindNamespace(namespaces); + if (!_namespace) + return nullptr; -Class* DeclarationContext::FindClass(const void* OriginalPtr, - const std::string& Name, bool IsComplete, bool Create) -{ - auto _class = FindClass(OriginalPtr, Name, IsComplete); + return _namespace->FindClass(OriginalPtr, className, IsComplete); + } - if (!_class) + Class* DeclarationContext::CreateClass(const std::string& Name, bool IsComplete) { - if (Create) - { - _class = CreateClass(Name, IsComplete); - Classes.push_back(_class); - } - + auto _class = new Class(); + _class->name = Name; + _class->_namespace = this; + _class->isIncomplete = !IsComplete; + return _class; } - return _class; -} - -Enumeration* DeclarationContext::FindEnum(const void* OriginalPtr) -{ - auto foundEnum = std::find_if(Enums.begin(), Enums.end(), - [&](Enumeration* enumeration) { return enumeration->originalPtr == OriginalPtr; }); + Class* DeclarationContext::FindClass(const void* OriginalPtr, + const std::string& Name, + bool IsComplete, + bool Create) + { + auto _class = FindClass(OriginalPtr, Name, IsComplete); - if (foundEnum != Enums.end()) - return *foundEnum; + if (!_class) + { + if (Create) + { + _class = CreateClass(Name, IsComplete); + Classes.push_back(_class); + } - return nullptr; -} + return _class; + } -Enumeration* DeclarationContext::FindEnum(const std::string& Name, bool Create) -{ - auto entries = split(Name, "::"); + return _class; + } - if (entries.size() == 1) + Enumeration* DeclarationContext::FindEnum(const void* OriginalPtr) { auto foundEnum = std::find_if(Enums.begin(), Enums.end(), - [&](Enumeration* _enum) { return _enum->name == Name; }); + [&](Enumeration* enumeration) + { + return enumeration->originalPtr == OriginalPtr; + }); if (foundEnum != Enums.end()) return *foundEnum; - if (!Create) - return nullptr; - - auto _enum = new Enumeration(); - _enum->name = Name; - _enum->_namespace = this; - Enums.push_back(_enum); - return _enum; + return nullptr; } - auto enumName = entries[entries.size() - 1]; + Enumeration* DeclarationContext::FindEnum(const std::string& Name, bool Create) + { + auto entries = split(Name, "::"); - std::vector namespaces; - std::copy_n(entries.begin(), entries.size() - 1, std::back_inserter(namespaces)); + if (entries.size() == 1) + { + auto foundEnum = std::find_if(Enums.begin(), Enums.end(), + [&](Enumeration* _enum) + { + return _enum->name == Name; + }); + + if (foundEnum != Enums.end()) + return *foundEnum; + + if (!Create) + return nullptr; + + auto _enum = new Enumeration(); + _enum->name = Name; + _enum->_namespace = this; + Enums.push_back(_enum); + return _enum; + } - auto _namespace = FindNamespace(namespaces); - if (!_namespace) - return nullptr; + auto enumName = entries[entries.size() - 1]; - return _namespace->FindEnum(enumName, Create); -} + std::vector namespaces; + std::copy_n(entries.begin(), entries.size() - 1, std::back_inserter(namespaces)); -Enumeration* DeclarationContext::FindEnumWithItem(const std::string& Name) -{ - auto foundEnumIt = std::find_if(Enums.begin(), Enums.end(), - [&](Enumeration* _enum) { return _enum->FindItemByName(Name) != nullptr; }); - if (foundEnumIt != Enums.end()) - return *foundEnumIt; - for (auto it = Namespaces.begin(); it != Namespaces.end(); ++it) - { - auto foundEnum = (*it)->FindEnumWithItem(Name); - if (foundEnum != nullptr) - return foundEnum; + auto _namespace = FindNamespace(namespaces); + if (!_namespace) + return nullptr; + + return _namespace->FindEnum(enumName, Create); } - for (auto it = Classes.begin(); it != Classes.end(); ++it) + + Enumeration* DeclarationContext::FindEnumWithItem(const std::string& Name) { - auto foundEnum = (*it)->FindEnumWithItem(Name); - if (foundEnum != nullptr) - return foundEnum; + auto foundEnumIt = std::find_if(Enums.begin(), Enums.end(), + [&](Enumeration* _enum) + { + return _enum->FindItemByName(Name) != nullptr; + }); + if (foundEnumIt != Enums.end()) + return *foundEnumIt; + for (auto it = Namespaces.begin(); it != Namespaces.end(); ++it) + { + auto foundEnum = (*it)->FindEnumWithItem(Name); + if (foundEnum != nullptr) + return foundEnum; + } + for (auto it = Classes.begin(); it != Classes.end(); ++it) + { + auto foundEnum = (*it)->FindEnumWithItem(Name); + if (foundEnum != nullptr) + return foundEnum; + } + return nullptr; } - return nullptr; -} -Function* DeclarationContext::FindFunction(const std::string& USR) -{ - auto foundFunction = std::find_if(Functions.begin(), Functions.end(), - [&](Function* func) { return func->USR == USR; }); + Function* DeclarationContext::FindFunction(const std::string& USR) + { + auto foundFunction = std::find_if(Functions.begin(), Functions.end(), + [&](Function* func) + { + return func->USR == USR; + }); - if (foundFunction != Functions.end()) - return *foundFunction; + if (foundFunction != Functions.end()) + return *foundFunction; - auto foundTemplate = std::find_if(Templates.begin(), Templates.end(), - [&](Template* t) { return t->TemplatedDecl && t->TemplatedDecl->USR == USR; }); + auto foundTemplate = std::find_if(Templates.begin(), Templates.end(), + [&](Template* t) + { + return t->TemplatedDecl && t->TemplatedDecl->USR == USR; + }); - if (foundTemplate != Templates.end()) - return static_cast((*foundTemplate)->TemplatedDecl); + if (foundTemplate != Templates.end()) + return static_cast((*foundTemplate)->TemplatedDecl); - return nullptr; -} + return nullptr; + } -TypedefDecl* DeclarationContext::FindTypedef(const std::string& Name, bool Create) -{ - auto foundTypedef = std::find_if(Typedefs.begin(), Typedefs.end(), - [&](TypedefDecl* tdef) { return tdef->name == Name; }); + TypedefDecl* DeclarationContext::FindTypedef(const std::string& Name, bool Create) + { + auto foundTypedef = std::find_if(Typedefs.begin(), Typedefs.end(), + [&](TypedefDecl* tdef) + { + return tdef->name == Name; + }); - if (foundTypedef != Typedefs.end()) - return *foundTypedef; + if (foundTypedef != Typedefs.end()) + return *foundTypedef; - if (!Create) - return nullptr; - - auto tdef = new TypedefDecl(); - tdef->name = Name; - tdef->_namespace = this; + if (!Create) + return nullptr; - return tdef; -} + auto tdef = new TypedefDecl(); + tdef->name = Name; + tdef->_namespace = this; -TypeAlias* DeclarationContext::FindTypeAlias(const std::string& Name, bool Create) -{ - auto foundTypeAlias = std::find_if(TypeAliases.begin(), TypeAliases.end(), - [&](TypeAlias* talias) { return talias->name == Name; }); + return tdef; + } - if (foundTypeAlias != TypeAliases.end()) - return *foundTypeAlias; + TypeAlias* DeclarationContext::FindTypeAlias(const std::string& Name, bool Create) + { + auto foundTypeAlias = std::find_if(TypeAliases.begin(), TypeAliases.end(), + [&](TypeAlias* talias) + { + return talias->name == Name; + }); - if (!Create) - return nullptr; + if (foundTypeAlias != TypeAliases.end()) + return *foundTypeAlias; - auto talias = new TypeAlias(); - talias->name = Name; - talias->_namespace = this; + if (!Create) + return nullptr; - return talias; -} + auto talias = new TypeAlias(); + talias->name = Name; + talias->_namespace = this; -Variable* DeclarationContext::FindVariable(const std::string& USR) -{ - auto found = std::find_if(Variables.begin(), Variables.end(), - [&](Variable* var) { return var->USR == USR; }); + return talias; + } - if (found != Variables.end()) - return *found; + Variable* DeclarationContext::FindVariable(const std::string& USR) + { + auto found = std::find_if(Variables.begin(), Variables.end(), + [&](Variable* var) + { + return var->USR == USR; + }); - return nullptr; -} + if (found != Variables.end()) + return *found; -Friend* DeclarationContext::FindFriend(const std::string& USR) -{ - auto found = std::find_if(Friends.begin(), Friends.end(), - [&](Friend* var) { return var->USR == USR; }); + return nullptr; + } - if (found != Friends.end()) - return *found; + Friend* DeclarationContext::FindFriend(const std::string& USR) + { + auto found = std::find_if(Friends.begin(), Friends.end(), + [&](Friend* var) + { + return var->USR == USR; + }); - return nullptr; -} + if (found != Friends.end()) + return *found; -TypedefNameDecl::TypedefNameDecl(DeclarationKind Kind) : Declaration(Kind) {} + return nullptr; + } -TypedefNameDecl::~TypedefNameDecl() {} + TypedefNameDecl::TypedefNameDecl(DeclarationKind Kind) + : Declaration(Kind) + { + } -TypedefDecl::TypedefDecl() : TypedefNameDecl(DeclarationKind::Typedef) {} + TypedefNameDecl::~TypedefNameDecl() {} -TypedefDecl::~TypedefDecl() {} + TypedefDecl::TypedefDecl() + : TypedefNameDecl(DeclarationKind::Typedef) + { + } -TypeAlias::TypeAlias() : TypedefNameDecl(DeclarationKind::TypeAlias), describedAliasTemplate(0) {} + TypedefDecl::~TypedefDecl() {} -TypeAlias::~TypeAlias() {} + TypeAlias::TypeAlias() + : TypedefNameDecl(DeclarationKind::TypeAlias) + , describedAliasTemplate(0) + { + } -Friend::Friend() : CppSharp::CppParser::AST::Declaration(DeclarationKind::Friend), declaration(0) {} + TypeAlias::~TypeAlias() {} -Friend::~Friend() {} + Friend::Friend() + : CppSharp::CppParser::AST::Declaration(DeclarationKind::Friend) + , declaration(0) + { + } -StatementObsolete::StatementObsolete(const std::string& str, StatementClassObsolete stmtClass, Declaration* decl) : string(str), _class(stmtClass), decl(decl) {} + Friend::~Friend() {} -ExpressionObsolete::ExpressionObsolete(const std::string& str, StatementClassObsolete stmtClass, Declaration* decl) - : StatementObsolete(str, stmtClass, decl) {} + StatementObsolete::StatementObsolete(const std::string& str, StatementClassObsolete stmtClass, Declaration* decl) + : string(str) + , _class(stmtClass) + , decl(decl) + { + } -BinaryOperatorObsolete::BinaryOperatorObsolete(const std::string& str, ExpressionObsolete* lhs, ExpressionObsolete* rhs, const std::string& opcodeStr) - : ExpressionObsolete(str, StatementClassObsolete::BinaryOperator), LHS(lhs), RHS(rhs), opcodeStr(opcodeStr) {} + ExpressionObsolete::ExpressionObsolete(const std::string& str, StatementClassObsolete stmtClass, Declaration* decl) + : StatementObsolete(str, stmtClass, decl) + { + } -BinaryOperatorObsolete::~BinaryOperatorObsolete() -{ - deleteExpression(LHS); - deleteExpression(RHS); -} + BinaryOperatorObsolete::BinaryOperatorObsolete(const std::string& str, ExpressionObsolete* lhs, ExpressionObsolete* rhs, const std::string& opcodeStr) + : ExpressionObsolete(str, StatementClassObsolete::BinaryOperator) + , LHS(lhs) + , RHS(rhs) + , opcodeStr(opcodeStr) + { + } + BinaryOperatorObsolete::~BinaryOperatorObsolete() + { + deleteExpression(LHS); + deleteExpression(RHS); + } -CallExprObsolete::CallExprObsolete(const std::string& str, Declaration* decl) - : ExpressionObsolete(str, StatementClassObsolete::CallExprClass, decl) {} -CallExprObsolete::~CallExprObsolete() -{ - for (auto& arg : Arguments) - deleteExpression(arg); -} + CallExprObsolete::CallExprObsolete(const std::string& str, Declaration* decl) + : ExpressionObsolete(str, StatementClassObsolete::CallExprClass, decl) + { + } -DEF_VECTOR(CallExprObsolete, ExpressionObsolete*, Arguments) + CallExprObsolete::~CallExprObsolete() + { + for (auto& arg : Arguments) + deleteExpression(arg); + } -CXXConstructExprObsolete::CXXConstructExprObsolete(const std::string& str, Declaration* decl) - : ExpressionObsolete(str, StatementClassObsolete::CXXConstructExprClass, decl) {} + DEF_VECTOR(CallExprObsolete, ExpressionObsolete*, Arguments) -CXXConstructExprObsolete::~CXXConstructExprObsolete() -{ - for (auto& arg : Arguments) - deleteExpression(arg); -} + CXXConstructExprObsolete::CXXConstructExprObsolete(const std::string& str, Declaration* decl) + : ExpressionObsolete(str, StatementClassObsolete::CXXConstructExprClass, decl) + { + } -DEF_VECTOR(CXXConstructExprObsolete, ExpressionObsolete*, Arguments) + CXXConstructExprObsolete::~CXXConstructExprObsolete() + { + for (auto& arg : Arguments) + deleteExpression(arg); + } -Parameter::Parameter() - : Declaration(DeclarationKind::Parameter) - , isIndirect(false) - , hasDefaultValue(false) - , defaultArgument(0) - , defaultValue(0) -{ -} + DEF_VECTOR(CXXConstructExprObsolete, ExpressionObsolete*, Arguments) -Parameter::~Parameter() -{ - deleteExpression(defaultArgument); -} + Parameter::Parameter() + : Declaration(DeclarationKind::Parameter) + , isIndirect(false) + , hasDefaultValue(false) + , defaultArgument(0) + , defaultValue(0) + { + } -Function::Function() - : DeclarationContext(DeclarationKind::Function) - , isReturnIndirect(false) - , isConstExpr(false) - , isVariadic(false) - , isInline(false) - , isPure(false) - , isDeleted(false) - , isDefaulted(false) - , friendKind(FriendKind::None) - , operatorKind(CXXOperatorKind::None) - , callingConvention(CallingConvention::Default) - , specializationInfo(0) - , instantiatedFrom(0) - , bodyStmt(0) -{ -} + Parameter::~Parameter() + { + deleteExpression(defaultArgument); + } -Function::~Function() {} -DEF_VECTOR(Function, Parameter*, Parameters) - -Method::Method() - : Function() - , isVirtual(false) - , isStatic(false) - , isConst(false) - , isExplicit(false) - , isVolatile(false) - , isDefaultConstructor(false) - , isCopyConstructor(false) - , isMoveConstructor(false) - , refQualifier(RefQualifierKind::None) -{ - kind = DeclarationKind::Method; -} + Function::Function() + : DeclarationContext(DeclarationKind::Function) + , isReturnIndirect(false) + , isConstExpr(false) + , isVariadic(false) + , isInline(false) + , isPure(false) + , isDeleted(false) + , isDefaulted(false) + , friendKind(FriendKind::None) + , operatorKind(CXXOperatorKind::None) + , callingConvention(CallingConvention::Default) + , specializationInfo(0) + , instantiatedFrom(0) + , bodyStmt(0) + { + } -Method::~Method() {} + Function::~Function() {} + DEF_VECTOR(Function, Parameter*, Parameters) + + Method::Method() + : Function() + , isVirtual(false) + , isStatic(false) + , isConst(false) + , isExplicit(false) + , isVolatile(false) + , isDefaultConstructor(false) + , isCopyConstructor(false) + , isMoveConstructor(false) + , refQualifier(RefQualifierKind::None) + { + kind = DeclarationKind::Method; + } -DEF_VECTOR(Method, Method*, OverriddenMethods) + Method::~Method() {} -// Enumeration + DEF_VECTOR(Method, Method*, OverriddenMethods) -Enumeration::Enumeration() : DeclarationContext(DeclarationKind::Enumeration), - modifiers((EnumModifiers)0), type(0), builtinType(0) {} + // Enumeration -Enumeration::~Enumeration() {} + Enumeration::Enumeration() + : DeclarationContext(DeclarationKind::Enumeration) + , modifiers((EnumModifiers)0) + , type(0) + , builtinType(0) + { + } -DEF_VECTOR(Enumeration, Enumeration::Item*, Items) + Enumeration::~Enumeration() {} -Enumeration::Item::Item() : Declaration(DeclarationKind::EnumerationItem) {} + DEF_VECTOR(Enumeration, Enumeration::Item*, Items) -Enumeration::Item::Item(const Item& rhs) : Declaration(rhs), - expression(rhs.expression), value(rhs.value) {} + Enumeration::Item::Item() + : Declaration(DeclarationKind::EnumerationItem) + { + } -Enumeration::Item::~Item() {} + Enumeration::Item::Item(const Item& rhs) + : Declaration(rhs) + , expression(rhs.expression) + , value(rhs.value) + { + } -Enumeration::Item* Enumeration::FindItemByName(const std::string& Name) -{ - auto foundEnumItem = std::find_if(Items.begin(), Items.end(), - [&](Item* _item) { return _item->name == Name; }); - if (foundEnumItem != Items.end()) - return *foundEnumItem; - return nullptr; -} + Enumeration::Item::~Item() {} -Variable::Variable() : Declaration(DeclarationKind::Variable), - isConstExpr(false), initializer(0) {} + Enumeration::Item* Enumeration::FindItemByName(const std::string& Name) + { + auto foundEnumItem = std::find_if(Items.begin(), Items.end(), + [&](Item* _item) + { + return _item->name == Name; + }); + if (foundEnumItem != Items.end()) + return *foundEnumItem; + return nullptr; + } -Variable::~Variable() {} + Variable::Variable() + : Declaration(DeclarationKind::Variable) + , isConstExpr(false) + , initializer(0) + { + } -BaseClassSpecifier::BaseClassSpecifier() : type(0), offset(0) {} + Variable::~Variable() {} -Field::Field() : Declaration(DeclarationKind::Field), _class(0), - isBitField(false), bitWidth(0) {} + BaseClassSpecifier::BaseClassSpecifier() + : type(0) + , offset(0) + { + } -Field::~Field() {} + Field::Field() + : Declaration(DeclarationKind::Field) + , _class(0) + , isBitField(false) + , bitWidth(0) + { + } -AccessSpecifierDecl::AccessSpecifierDecl() - : Declaration(DeclarationKind::AccessSpecifier) {} + Field::~Field() {} -AccessSpecifierDecl::~AccessSpecifierDecl() {} + AccessSpecifierDecl::AccessSpecifierDecl() + : Declaration(DeclarationKind::AccessSpecifier) + { + } -Class::Class() - : DeclarationContext(DeclarationKind::Class) - , isPOD(false) - , isAbstract(false) - , isUnion(false) - , isDynamic(false) - , isPolymorphic(false) - , hasNonTrivialDefaultConstructor(false) - , hasNonTrivialCopyConstructor(false) - , hasNonTrivialDestructor(false) - , isExternCContext(false) - , isInjected(false) - , layout(0) - , tagKind(TagKind::Struct) -{ -} + AccessSpecifierDecl::~AccessSpecifierDecl() {} + + Class::Class() + : DeclarationContext(DeclarationKind::Class) + , isPOD(false) + , isAbstract(false) + , isUnion(false) + , isDynamic(false) + , isPolymorphic(false) + , hasNonTrivialDefaultConstructor(false) + , hasNonTrivialCopyConstructor(false) + , hasNonTrivialDestructor(false) + , isExternCContext(false) + , isInjected(false) + , layout(0) + , tagKind(TagKind::Struct) + { + } -Class::~Class() -{ - if (layout) - delete layout; -} + Class::~Class() + { + if (layout) + delete layout; + } -DEF_VECTOR(Class, BaseClassSpecifier*, Bases) -DEF_VECTOR(Class, Field*, Fields) -DEF_VECTOR(Class, Method*, Methods) -DEF_VECTOR(Class, AccessSpecifierDecl*, Specifiers) + DEF_VECTOR(Class, BaseClassSpecifier*, Bases) + DEF_VECTOR(Class, Field*, Fields) + DEF_VECTOR(Class, Method*, Methods) + DEF_VECTOR(Class, AccessSpecifierDecl*, Specifiers) -Template::Template() : Declaration(DeclarationKind::Template), - TemplatedDecl(0) {} + Template::Template() + : Declaration(DeclarationKind::Template) + , TemplatedDecl(0) + { + } -Template::Template(DeclarationKind kind) : Declaration(kind), TemplatedDecl(0) {} + Template::Template(DeclarationKind kind) + : Declaration(kind) + , TemplatedDecl(0) + { + } -DEF_VECTOR(Template, Declaration*, Parameters) + DEF_VECTOR(Template, Declaration*, Parameters) -TypeAliasTemplate::TypeAliasTemplate() : Template(DeclarationKind::TypeAliasTemplate) {} + TypeAliasTemplate::TypeAliasTemplate() + : Template(DeclarationKind::TypeAliasTemplate) + { + } -TypeAliasTemplate::~TypeAliasTemplate() {} + TypeAliasTemplate::~TypeAliasTemplate() {} -ClassTemplate::ClassTemplate() : Template(DeclarationKind::ClassTemplate) {} + ClassTemplate::ClassTemplate() + : Template(DeclarationKind::ClassTemplate) + { + } -ClassTemplate::~ClassTemplate() {} + ClassTemplate::~ClassTemplate() {} -DEF_VECTOR(ClassTemplate, ClassTemplateSpecialization*, Specializations) + DEF_VECTOR(ClassTemplate, ClassTemplateSpecialization*, Specializations) -ClassTemplateSpecialization::ClassTemplateSpecialization() - : Class() - , templatedDecl(0) -{ - kind = DeclarationKind::ClassTemplateSpecialization; -} + ClassTemplateSpecialization::ClassTemplateSpecialization() + : Class() + , templatedDecl(0) + { + kind = DeclarationKind::ClassTemplateSpecialization; + } -ClassTemplateSpecialization::~ClassTemplateSpecialization() {} + ClassTemplateSpecialization::~ClassTemplateSpecialization() {} -DEF_VECTOR(ClassTemplateSpecialization, TemplateArgument, Arguments) + DEF_VECTOR(ClassTemplateSpecialization, TemplateArgument, Arguments) -ClassTemplatePartialSpecialization::ClassTemplatePartialSpecialization() - : ClassTemplateSpecialization() -{ - kind = DeclarationKind::ClassTemplatePartialSpecialization; -} + ClassTemplatePartialSpecialization::ClassTemplatePartialSpecialization() + : ClassTemplateSpecialization() + { + kind = DeclarationKind::ClassTemplatePartialSpecialization; + } -ClassTemplatePartialSpecialization::~ClassTemplatePartialSpecialization() {} + ClassTemplatePartialSpecialization::~ClassTemplatePartialSpecialization() {} -DEF_VECTOR(ClassTemplatePartialSpecialization, Declaration*, Parameters) + DEF_VECTOR(ClassTemplatePartialSpecialization, Declaration*, Parameters) -FunctionTemplate::FunctionTemplate() : Template(DeclarationKind::FunctionTemplate) {} + FunctionTemplate::FunctionTemplate() + : Template(DeclarationKind::FunctionTemplate) + { + } -FunctionTemplate::~FunctionTemplate() {} + FunctionTemplate::~FunctionTemplate() {} -DEF_VECTOR(FunctionTemplate, FunctionTemplateSpecialization*, Specializations) + DEF_VECTOR(FunctionTemplate, FunctionTemplateSpecialization*, Specializations) -FunctionTemplateSpecialization* FunctionTemplate::FindSpecialization(const std::string& usr) -{ - auto foundSpec = std::find_if(Specializations.begin(), Specializations.end(), - [&](FunctionTemplateSpecialization* cts) { return cts->specializedFunction->USR == usr; }); + FunctionTemplateSpecialization* FunctionTemplate::FindSpecialization(const std::string& usr) + { + auto foundSpec = std::find_if(Specializations.begin(), Specializations.end(), + [&](FunctionTemplateSpecialization* cts) + { + return cts->specializedFunction->USR == usr; + }); - if (foundSpec != Specializations.end()) - return static_cast(*foundSpec); + if (foundSpec != Specializations.end()) + return static_cast(*foundSpec); - return nullptr; -} + return nullptr; + } -FunctionTemplateSpecialization::FunctionTemplateSpecialization() - : _template(0) - , specializedFunction(0) -{ -} + FunctionTemplateSpecialization::FunctionTemplateSpecialization() + : _template(0) + , specializedFunction(0) + { + } -FunctionTemplateSpecialization::~FunctionTemplateSpecialization() -{ -} + FunctionTemplateSpecialization::~FunctionTemplateSpecialization() + { + } -DEF_VECTOR(FunctionTemplateSpecialization, TemplateArgument, Arguments) + DEF_VECTOR(FunctionTemplateSpecialization, TemplateArgument, Arguments) -VarTemplate::VarTemplate() : Template(DeclarationKind::VarTemplate) {} + VarTemplate::VarTemplate() + : Template(DeclarationKind::VarTemplate) + { + } -VarTemplate::~VarTemplate() {} + VarTemplate::~VarTemplate() {} -DEF_VECTOR(VarTemplate, VarTemplateSpecialization*, Specializations) + DEF_VECTOR(VarTemplate, VarTemplateSpecialization*, Specializations) -VarTemplateSpecialization* VarTemplate::FindSpecialization(const std::string& usr) -{ - auto foundSpec = std::find_if(Specializations.begin(), Specializations.end(), - [&](VarTemplateSpecialization* cts) { return cts->USR == usr; }); + VarTemplateSpecialization* VarTemplate::FindSpecialization(const std::string& usr) + { + auto foundSpec = std::find_if(Specializations.begin(), Specializations.end(), + [&](VarTemplateSpecialization* cts) + { + return cts->USR == usr; + }); - if (foundSpec != Specializations.end()) - return static_cast(*foundSpec); + if (foundSpec != Specializations.end()) + return static_cast(*foundSpec); - return nullptr; -} + return nullptr; + } -VarTemplatePartialSpecialization* VarTemplate::FindPartialSpecialization(const std::string& usr) -{ - auto foundSpec = FindSpecialization(usr); - if (foundSpec != nullptr) - return static_cast(foundSpec); - return nullptr; -} + VarTemplatePartialSpecialization* VarTemplate::FindPartialSpecialization(const std::string& usr) + { + auto foundSpec = FindSpecialization(usr); + if (foundSpec != nullptr) + return static_cast(foundSpec); + return nullptr; + } -VarTemplateSpecialization::VarTemplateSpecialization() - : Variable() - , templatedDecl(0) -{ - kind = DeclarationKind::VarTemplateSpecialization; -} + VarTemplateSpecialization::VarTemplateSpecialization() + : Variable() + , templatedDecl(0) + { + kind = DeclarationKind::VarTemplateSpecialization; + } -VarTemplateSpecialization::~VarTemplateSpecialization() {} + VarTemplateSpecialization::~VarTemplateSpecialization() {} -DEF_VECTOR(VarTemplateSpecialization, TemplateArgument, Arguments) + DEF_VECTOR(VarTemplateSpecialization, TemplateArgument, Arguments) -VarTemplatePartialSpecialization::VarTemplatePartialSpecialization() - : VarTemplateSpecialization() -{ - kind = DeclarationKind::VarTemplatePartialSpecialization; -} + VarTemplatePartialSpecialization::VarTemplatePartialSpecialization() + : VarTemplateSpecialization() + { + kind = DeclarationKind::VarTemplatePartialSpecialization; + } -VarTemplatePartialSpecialization::~VarTemplatePartialSpecialization() -{ -} + VarTemplatePartialSpecialization::~VarTemplatePartialSpecialization() + { + } -UnresolvedUsingTypename::UnresolvedUsingTypename() : Declaration(DeclarationKind::UnresolvedUsingTypename) {} + UnresolvedUsingTypename::UnresolvedUsingTypename() + : Declaration(DeclarationKind::UnresolvedUsingTypename) + { + } -UnresolvedUsingTypename::~UnresolvedUsingTypename() {} + UnresolvedUsingTypename::~UnresolvedUsingTypename() {} -Namespace::Namespace() - : DeclarationContext(DeclarationKind::Namespace) - , isInline(false) -{ -} + Namespace::Namespace() + : DeclarationContext(DeclarationKind::Namespace) + , isInline(false) + { + } -Namespace::~Namespace() {} + Namespace::~Namespace() {} -PreprocessedEntity::PreprocessedEntity() - : macroLocation(AST::MacroLocation::Unknown), - originalPtr(0), kind(DeclarationKind::PreprocessedEntity) {} + PreprocessedEntity::PreprocessedEntity() + : macroLocation(AST::MacroLocation::Unknown) + , originalPtr(0) + , kind(DeclarationKind::PreprocessedEntity) + { + } -MacroDefinition::MacroDefinition() - : lineNumberStart(0), lineNumberEnd(0) { kind = DeclarationKind::MacroDefinition; } + MacroDefinition::MacroDefinition() + : lineNumberStart(0) + , lineNumberEnd(0) + { + kind = DeclarationKind::MacroDefinition; + } -MacroDefinition::~MacroDefinition() {} + MacroDefinition::~MacroDefinition() {} -MacroExpansion::MacroExpansion() : definition(0) { kind = DeclarationKind::MacroExpansion; } + MacroExpansion::MacroExpansion() + : definition(0) + { + kind = DeclarationKind::MacroExpansion; + } -MacroExpansion::~MacroExpansion() {} + MacroExpansion::~MacroExpansion() {} -TranslationUnit::TranslationUnit() { kind = DeclarationKind::TranslationUnit; } + TranslationUnit::TranslationUnit() + { + kind = DeclarationKind::TranslationUnit; + } -TranslationUnit::~TranslationUnit() {} -DEF_VECTOR(TranslationUnit, MacroDefinition*, Macros) + TranslationUnit::~TranslationUnit() {} + DEF_VECTOR(TranslationUnit, MacroDefinition*, Macros) -NativeLibrary::NativeLibrary() - : archType(AST::ArchType::UnknownArch) {} + NativeLibrary::NativeLibrary() + : archType(AST::ArchType::UnknownArch) + { + } -NativeLibrary::~NativeLibrary() {} + NativeLibrary::~NativeLibrary() {} -// NativeLibrary -DEF_VECTOR_STRING(NativeLibrary, Symbols) -DEF_VECTOR_STRING(NativeLibrary, Dependencies) + // NativeLibrary + DEF_VECTOR_STRING(NativeLibrary, Symbols) + DEF_VECTOR_STRING(NativeLibrary, Dependencies) -// ASTContext -DEF_VECTOR(ASTContext, TranslationUnit*, TranslationUnits) + // ASTContext + DEF_VECTOR(ASTContext, TranslationUnit*, TranslationUnits) -ClassTemplateSpecialization* ClassTemplate::FindSpecialization(const std::string& usr) -{ - auto foundSpec = std::find_if(Specializations.begin(), Specializations.end(), - [&](ClassTemplateSpecialization* cts) { return cts->USR == usr; }); + ClassTemplateSpecialization* ClassTemplate::FindSpecialization(const std::string& usr) + { + auto foundSpec = std::find_if(Specializations.begin(), Specializations.end(), + [&](ClassTemplateSpecialization* cts) + { + return cts->USR == usr; + }); - if (foundSpec != Specializations.end()) - return static_cast(*foundSpec); + if (foundSpec != Specializations.end()) + return static_cast(*foundSpec); - return nullptr; -} + return nullptr; + } -ClassTemplatePartialSpecialization* ClassTemplate::FindPartialSpecialization(const std::string& usr) -{ - auto foundSpec = FindSpecialization(usr); - if (foundSpec != nullptr) - return static_cast(foundSpec); - return nullptr; -} + ClassTemplatePartialSpecialization* ClassTemplate::FindPartialSpecialization(const std::string& usr) + { + auto foundSpec = FindSpecialization(usr); + if (foundSpec != nullptr) + return static_cast(foundSpec); + return nullptr; + } -ASTContext::ASTContext() {} + ASTContext::ASTContext() {} -ASTContext::~ASTContext() {} + ASTContext::~ASTContext() {} -TranslationUnit* ASTContext::FindOrCreateModule(const std::string& File) -{ - auto normalizedFile = normalizePath(File); + TranslationUnit* ASTContext::FindOrCreateModule(const std::string& File) + { + auto normalizedFile = normalizePath(File); - auto existingUnit = std::find_if(TranslationUnits.begin(), - TranslationUnits.end(), [&](TranslationUnit* unit) { - return unit && unit->fileName == normalizedFile; - }); + auto existingUnit = std::find_if(TranslationUnits.begin(), + TranslationUnits.end(), [&](TranslationUnit* unit) + { + return unit && unit->fileName == normalizedFile; + }); - if (existingUnit != TranslationUnits.end()) - return *existingUnit; + if (existingUnit != TranslationUnits.end()) + return *existingUnit; - auto unit = new TranslationUnit(); - unit->fileName = normalizedFile; - TranslationUnits.push_back(unit); + auto unit = new TranslationUnit(); + unit->fileName = normalizedFile; + TranslationUnits.push_back(unit); - return unit; -} + return unit; + } -// Comments -Comment::Comment(CommentKind kind) : kind(kind) {} + // Comments + Comment::Comment(CommentKind kind) + : kind(kind) + { + } -RawComment::RawComment() : fullCommentBlock(0) {} + RawComment::RawComment() + : fullCommentBlock(0) + { + } -RawComment::~RawComment() -{ - if (fullCommentBlock) - delete fullCommentBlock; -} + RawComment::~RawComment() + { + if (fullCommentBlock) + delete fullCommentBlock; + } -FullComment::FullComment() : Comment(CommentKind::FullComment) {} + FullComment::FullComment() + : Comment(CommentKind::FullComment) + { + } -FullComment::~FullComment() -{ - for (auto& block : Blocks) + FullComment::~FullComment() { - // HACK: see https://github.com/mono/CppSharp/issues/599 - switch (block->kind) + for (auto& block : Blocks) { - case CommentKind::BlockCommandComment: - delete static_cast(block); - break; - case CommentKind::ParamCommandComment: - delete static_cast(block); - break; - case CommentKind::TParamCommandComment: - delete static_cast(block); - break; - case CommentKind::VerbatimBlockComment: - delete static_cast(block); - break; - case CommentKind::VerbatimLineComment: - delete static_cast(block); - break; - case CommentKind::ParagraphComment: - delete static_cast(block); - break; - default: - delete block; - break; + // HACK: see https://github.com/mono/CppSharp/issues/599 + switch (block->kind) + { + case CommentKind::BlockCommandComment: + delete static_cast(block); + break; + case CommentKind::ParamCommandComment: + delete static_cast(block); + break; + case CommentKind::TParamCommandComment: + delete static_cast(block); + break; + case CommentKind::VerbatimBlockComment: + delete static_cast(block); + break; + case CommentKind::VerbatimLineComment: + delete static_cast(block); + break; + case CommentKind::ParagraphComment: + delete static_cast(block); + break; + default: + delete block; + break; + } } } -} -DEF_VECTOR(FullComment, BlockContentComment*, Blocks) + DEF_VECTOR(FullComment, BlockContentComment*, Blocks) -BlockContentComment::BlockContentComment() : Comment(CommentKind::BlockContentComment) {} + BlockContentComment::BlockContentComment() + : Comment(CommentKind::BlockContentComment) + { + } -BlockContentComment::BlockContentComment(CommentKind Kind) : Comment(Kind) {} + BlockContentComment::BlockContentComment(CommentKind Kind) + : Comment(Kind) + { + } -BlockCommandComment::Argument::Argument() {} + BlockCommandComment::Argument::Argument() {} -BlockCommandComment::Argument::Argument(const Argument& rhs) : text(rhs.text) {} + BlockCommandComment::Argument::Argument(const Argument& rhs) + : text(rhs.text) + { + } -BlockCommandComment::Argument::~Argument() {} + BlockCommandComment::Argument::~Argument() {} -BlockCommandComment::BlockCommandComment() : BlockContentComment(CommentKind::BlockCommandComment), commandId(0), paragraphComment(0) {} + BlockCommandComment::BlockCommandComment() + : BlockContentComment(CommentKind::BlockCommandComment) + , commandId(0) + , paragraphComment(0) + { + } -BlockCommandComment::BlockCommandComment(CommentKind Kind) : BlockContentComment(Kind), commandId(0), paragraphComment(0) {} + BlockCommandComment::BlockCommandComment(CommentKind Kind) + : BlockContentComment(Kind) + , commandId(0) + , paragraphComment(0) + { + } -BlockCommandComment::~BlockCommandComment() -{ - delete paragraphComment; -} + BlockCommandComment::~BlockCommandComment() + { + delete paragraphComment; + } -DEF_VECTOR(BlockCommandComment, BlockCommandComment::Argument, Arguments) + DEF_VECTOR(BlockCommandComment, BlockCommandComment::Argument, Arguments) -ParamCommandComment::ParamCommandComment() : BlockCommandComment(CommentKind::ParamCommandComment), direction(PassDirection::In), paramIndex(0) {} + ParamCommandComment::ParamCommandComment() + : BlockCommandComment(CommentKind::ParamCommandComment) + , direction(PassDirection::In) + , paramIndex(0) + { + } -TParamCommandComment::TParamCommandComment() : BlockCommandComment(CommentKind::TParamCommandComment) {} + TParamCommandComment::TParamCommandComment() + : BlockCommandComment(CommentKind::TParamCommandComment) + { + } -DEF_VECTOR(TParamCommandComment, unsigned, Position) + DEF_VECTOR(TParamCommandComment, unsigned, Position) -VerbatimBlockComment::VerbatimBlockComment() : BlockCommandComment(CommentKind::VerbatimBlockComment) {} + VerbatimBlockComment::VerbatimBlockComment() + : BlockCommandComment(CommentKind::VerbatimBlockComment) + { + } -VerbatimBlockComment::~VerbatimBlockComment() -{ - for (auto& line : Lines) - delete line; -} + VerbatimBlockComment::~VerbatimBlockComment() + { + for (auto& line : Lines) + delete line; + } -DEF_VECTOR(VerbatimBlockComment, VerbatimBlockLineComment*, Lines) + DEF_VECTOR(VerbatimBlockComment, VerbatimBlockLineComment*, Lines) -VerbatimLineComment::VerbatimLineComment() : BlockCommandComment(CommentKind::VerbatimLineComment) {} + VerbatimLineComment::VerbatimLineComment() + : BlockCommandComment(CommentKind::VerbatimLineComment) + { + } -ParagraphComment::ParagraphComment() : BlockContentComment(CommentKind::ParagraphComment), isWhitespace(false) {} + ParagraphComment::ParagraphComment() + : BlockContentComment(CommentKind::ParagraphComment) + , isWhitespace(false) + { + } -ParagraphComment::~ParagraphComment() -{ - for (auto& content : Content) + ParagraphComment::~ParagraphComment() { - // HACK: see https://github.com/mono/CppSharp/issues/599 - switch (content->kind) + for (auto& content : Content) { - case CommentKind::InlineCommandComment: - delete static_cast(content); - break; - case CommentKind::HTMLTagComment: - delete static_cast(content); - break; - case CommentKind::HTMLStartTagComment: - delete static_cast(content); - break; - case CommentKind::HTMLEndTagComment: - delete static_cast(content); - break; - case CommentKind::TextComment: - delete static_cast(content); - break; - default: - delete content; - break; + // HACK: see https://github.com/mono/CppSharp/issues/599 + switch (content->kind) + { + case CommentKind::InlineCommandComment: + delete static_cast(content); + break; + case CommentKind::HTMLTagComment: + delete static_cast(content); + break; + case CommentKind::HTMLStartTagComment: + delete static_cast(content); + break; + case CommentKind::HTMLEndTagComment: + delete static_cast(content); + break; + case CommentKind::TextComment: + delete static_cast(content); + break; + default: + delete content; + break; + } } } -} -DEF_VECTOR(ParagraphComment, InlineContentComment*, Content) + DEF_VECTOR(ParagraphComment, InlineContentComment*, Content) -HTMLTagComment::HTMLTagComment() : InlineContentComment(CommentKind::HTMLTagComment) {} + HTMLTagComment::HTMLTagComment() + : InlineContentComment(CommentKind::HTMLTagComment) + { + } -HTMLTagComment::HTMLTagComment(CommentKind Kind) : InlineContentComment(Kind) {} + HTMLTagComment::HTMLTagComment(CommentKind Kind) + : InlineContentComment(Kind) + { + } -HTMLStartTagComment::Attribute::Attribute() {} + HTMLStartTagComment::Attribute::Attribute() {} -HTMLStartTagComment::Attribute::Attribute(const Attribute& rhs) : name(rhs.name), value(rhs.value) {} + HTMLStartTagComment::Attribute::Attribute(const Attribute& rhs) + : name(rhs.name) + , value(rhs.value) + { + } -HTMLStartTagComment::Attribute::~Attribute() {} + HTMLStartTagComment::Attribute::~Attribute() {} -HTMLStartTagComment::HTMLStartTagComment() : HTMLTagComment(CommentKind::HTMLStartTagComment) {} + HTMLStartTagComment::HTMLStartTagComment() + : HTMLTagComment(CommentKind::HTMLStartTagComment) + { + } -DEF_VECTOR(HTMLStartTagComment, HTMLStartTagComment::Attribute, Attributes) + DEF_VECTOR(HTMLStartTagComment, HTMLStartTagComment::Attribute, Attributes) -HTMLEndTagComment::HTMLEndTagComment() : HTMLTagComment(CommentKind::HTMLEndTagComment) {} + HTMLEndTagComment::HTMLEndTagComment() + : HTMLTagComment(CommentKind::HTMLEndTagComment) + { + } -InlineContentComment::InlineContentComment() : Comment(CommentKind::InlineContentComment), hasTrailingNewline(false) {} + InlineContentComment::InlineContentComment() + : Comment(CommentKind::InlineContentComment) + , hasTrailingNewline(false) + { + } -InlineContentComment::InlineContentComment(CommentKind Kind) : Comment(Kind), hasTrailingNewline(false) {} + InlineContentComment::InlineContentComment(CommentKind Kind) + : Comment(Kind) + , hasTrailingNewline(false) + { + } -TextComment::TextComment() : InlineContentComment(CommentKind::TextComment) {} + TextComment::TextComment() + : InlineContentComment(CommentKind::TextComment) + { + } -InlineCommandComment::Argument::Argument() {} + InlineCommandComment::Argument::Argument() {} -InlineCommandComment::Argument::Argument(const Argument& rhs) : text(rhs.text) {} + InlineCommandComment::Argument::Argument(const Argument& rhs) + : text(rhs.text) + { + } -InlineCommandComment::Argument::~Argument() {} + InlineCommandComment::Argument::~Argument() {} -InlineCommandComment::InlineCommandComment() - : InlineContentComment(CommentKind::InlineCommandComment), commandId(0), commentRenderKind(RenderNormal) {} + InlineCommandComment::InlineCommandComment() + : InlineContentComment(CommentKind::InlineCommandComment) + , commandId(0) + , commentRenderKind(RenderNormal) + { + } -DEF_VECTOR(InlineCommandComment, InlineCommandComment::Argument, Arguments) + DEF_VECTOR(InlineCommandComment, InlineCommandComment::Argument, Arguments) -VerbatimBlockLineComment::VerbatimBlockLineComment() : Comment(CommentKind::VerbatimBlockLineComment) {} + VerbatimBlockLineComment::VerbatimBlockLineComment() + : Comment(CommentKind::VerbatimBlockLineComment) + { + } -} } } \ No newline at end of file +}}} // namespace CppSharp::CppParser::AST \ No newline at end of file diff --git a/src/CppParser/AST.h b/src/CppParser/AST.h index 7bb740ec..3a09a332 100644 --- a/src/CppParser/AST.h +++ b/src/CppParser/AST.h @@ -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 { #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: #pragma endregion -} } } \ No newline at end of file +}}} // namespace CppSharp::CppParser::AST \ No newline at end of file diff --git a/src/CppParser/ASTNameMangler.cpp b/src/CppParser/ASTNameMangler.cpp index b39af3aa..454524f2 100644 --- a/src/CppParser/ASTNameMangler.cpp +++ b/src/CppParser/ASTNameMangler.cpp @@ -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; 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 { return Name; } -bool ASTNameMangler::WriteName(const Decl* D, raw_ostream& OS) const { - if (auto* FD = dyn_cast(D)) { +bool ASTNameMangler::WriteName(const Decl* D, raw_ostream& OS) const +{ + if (auto* FD = dyn_cast(D)) + { if (FD->isDependentContext()) return true; if (WriteFuncOrVarName(FD, OS)) return true; } - else if (auto* VD = dyn_cast(D)) { + else if (auto* VD = dyn_cast(D)) + { if (WriteFuncOrVarName(VD, OS)) return true; } - else if (auto* MD = dyn_cast(D)) { + else if (auto* MD = dyn_cast(D)) + { MC->mangleObjCMethodName(MD, OS, /*includePrefixByte=*/false, /*includeCategoryNamespace=*/true); return false; } - else if (auto* ID = dyn_cast(D)) { + else if (auto* ID = dyn_cast(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 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 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; diff --git a/src/CppParser/ASTNameMangler.h b/src/CppParser/ASTNameMangler.h index 82b50323..d94822a9 100644 --- a/src/CppParser/ASTNameMangler.h +++ b/src/CppParser/ASTNameMangler.h @@ -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 @@ #include -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: 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 MC; }; -} +} // namespace CppSharp::CppParser diff --git a/src/CppParser/CXXABI.h b/src/CppParser/CXXABI.h index 02e7a302..c98ad216 100644 --- a/src/CppParser/CXXABI.h +++ b/src/CppParser/CXXABI.h @@ -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 diff --git a/src/CppParser/Comments.cpp b/src/CppParser/Comments.cpp index b10069bc..71e6a55e 100644 --- a/src/CppParser/Comments.cpp +++ b/src/CppParser/Comments.cpp @@ -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) { 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 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 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) // 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(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(Content)); + auto CK = cast(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(Content)); + } + break; } - break; - } - case Comment::BlockCommandCommentKind: - { - auto CK = cast(C); - auto BC = new BlockCommandComment(); - _Comment = BC; - HandleBlockCommand(CK, BC); - BC->paragraphComment = static_cast(ConvertCommentBlock(CK->getParagraph())); - break; - } - case Comment::ParamCommandCommentKind: - { - auto CK = cast(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(ConvertCommentBlock(CK->getParagraph())); - break; - } - case Comment::TParamCommandCommentKind: - { - auto CK = cast(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(ConvertCommentBlock(CK->getParagraph())); - break; - } - case Comment::VerbatimBlockCommentKind: - { - auto CK = cast(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(Line)); + auto CK = cast(C); + auto BC = new BlockCommandComment(); + _Comment = BC; + HandleBlockCommand(CK, BC); + BC->paragraphComment = static_cast(ConvertCommentBlock(CK->getParagraph())); + break; } - break; - } - case Comment::VerbatimLineCommentKind: - { - auto CK = cast(C); - auto VL = new VerbatimLineComment(); - _Comment = VL; - VL->text = CK->getText().str(); - break; - } - case Comment::ParagraphCommentKind: - { - auto CK = cast(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(Content)); + auto CK = cast(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(ConvertCommentBlock(CK->getParagraph())); + break; } - PC->isWhitespace = CK->isWhitespace(); - break; - } - case Comment::HTMLStartTagCommentKind: - { - auto CK = cast(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(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(ConvertCommentBlock(CK->getParagraph())); + break; } - break; - } - case Comment::HTMLEndTagCommentKind: - { - auto CK = cast(C); - auto TC = new HTMLEndTagComment(); - _Comment = TC; - HandleInlineContent(CK, TC); - TC->tagName = CK->getTagName().str(); - break; - } - case Comment::TextCommentKind: - { - auto CK = cast(C); - auto TC = new TextComment(); - _Comment = TC; - HandleInlineContent(CK, TC); - TC->text = CK->getText().str(); - break; - } - case Comment::InlineCommandCommentKind: - { - auto CK = cast(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(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(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(Line)); + } + break; + } + case Comment::VerbatimLineCommentKind: + { + auto CK = cast(C); + auto VL = new VerbatimLineComment(); + _Comment = VL; + VL->text = CK->getText().str(); + break; + } + case Comment::ParagraphCommentKind: + { + auto CK = cast(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(Content)); + } + PC->isWhitespace = CK->isWhitespace(); + break; + } + case Comment::HTMLStartTagCommentKind: + { + auto CK = cast(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(C); + auto TC = new HTMLEndTagComment(); + _Comment = TC; + HandleInlineContent(CK, TC); + TC->tagName = CK->getTagName().str(); + break; + } + case Comment::TextCommentKind: + { + auto CK = cast(C); + auto TC = new TextComment(); + _Comment = TC; + HandleInlineContent(CK, TC); + TC->text = CK->getText().str(); + break; + } + case Comment::InlineCommandCommentKind: + { + auto CK = cast(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(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"); diff --git a/src/CppParser/CppParser.cpp b/src/CppParser/CppParser.cpp index 47131df6..9284b6e5 100644 --- a/src/CppParser/CppParser.cpp +++ b/src/CppParser/CppParser.cpp @@ -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 @@ 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() {} -} } \ No newline at end of file +}} // namespace CppSharp::CppParser \ No newline at end of file diff --git a/src/CppParser/CppParser.h b/src/CppParser/CppParser.h index df168448..79b62f50 100644 --- a/src/CppParser/CppParser.h +++ b/src/CppParser/CppParser.h @@ -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 @@ 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); -}; - -} } \ No newline at end of file + 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 \ No newline at end of file diff --git a/src/CppParser/Decl.h b/src/CppParser/Decl.h index ff78797c..b931e88e 100644 --- a/src/CppParser/Decl.h +++ b/src/CppParser/Decl.h @@ -12,839 +12,837 @@ #include "Types.h" #include -namespace CppSharp -{ - namespace CppParser - { - namespace AST - { +namespace CppSharp { +namespace CppParser { +namespace AST { - enum class DeclarationKind - { - DeclarationContext, - Typedef, - TypeAlias, - Parameter, - Function, - Method, - Enumeration, - EnumerationItem, - Variable, - Field, - AccessSpecifier, - Class, - Template, - TypeAliasTemplate, - ClassTemplate, - ClassTemplateSpecialization, - ClassTemplatePartialSpecialization, - FunctionTemplate, - Namespace, - PreprocessedEntity, - MacroDefinition, - MacroExpansion, - TranslationUnit, - Friend, - TemplateTemplateParm, - TemplateTypeParm, - NonTypeTemplateParm, - VarTemplate, - VarTemplateSpecialization, - VarTemplatePartialSpecialization, - UnresolvedUsingTypename, - }; + enum class DeclarationKind + { + DeclarationContext, + Typedef, + TypeAlias, + Parameter, + Function, + Method, + Enumeration, + EnumerationItem, + Variable, + Field, + AccessSpecifier, + Class, + Template, + TypeAliasTemplate, + ClassTemplate, + ClassTemplateSpecialization, + ClassTemplatePartialSpecialization, + FunctionTemplate, + Namespace, + PreprocessedEntity, + MacroDefinition, + MacroExpansion, + TranslationUnit, + Friend, + TemplateTemplateParm, + TemplateTypeParm, + NonTypeTemplateParm, + VarTemplate, + VarTemplateSpecialization, + VarTemplatePartialSpecialization, + UnresolvedUsingTypename, + }; #define DECLARE_DECL_KIND(klass, kind) \ klass(); - enum class AccessSpecifier - { - Private, - Protected, - Public - }; - - class DeclarationContext; - class RawComment; - class PreprocessedEntity; - - class ExpressionObsolete; - class CS_API Declaration - { - public: - Declaration(DeclarationKind kind); - Declaration(const Declaration &); - ~Declaration(); - - DeclarationKind kind; - int alignAs; - int maxFieldAlignment; - AccessSpecifier access; - DeclarationContext *_namespace; - SourceLocation location; - int lineNumberStart; - int lineNumberEnd; - std::string name; - std::string USR; - std::string debugText; - bool isIncomplete; - bool isDependent; - bool isImplicit; - bool isInvalid; - bool isDeprecated; - Declaration *completeDeclaration; - unsigned definitionOrder; - VECTOR(PreprocessedEntity *, PreprocessedEntities) - VECTOR(Declaration *, Redeclarations) - void *originalPtr; - RawComment *comment; - }; - - class Class; - class Enumeration; - class Function; - class TypedefDecl; - class TypeAlias; - class Namespace; - class Template; - class TypeAliasTemplate; - class ClassTemplate; - class FunctionTemplate; - class Variable; - class Friend; - - class CS_API DeclarationContext : public Declaration - { - public: - DeclarationContext(DeclarationKind kind); - - CS_IGNORE Declaration *FindAnonymous(const std::string &USR); - - CS_IGNORE Namespace *FindNamespace(const std::string &Name); - CS_IGNORE Namespace *FindNamespace(const std::vector &); - CS_IGNORE Namespace *FindCreateNamespace(const std::string &Name); - - CS_IGNORE Class *CreateClass(const std::string &Name, bool IsComplete); - CS_IGNORE Class *FindClass(const void *OriginalPtr, const std::string &Name, bool IsComplete); - CS_IGNORE Class *FindClass(const void *OriginalPtr, const std::string &Name, bool IsComplete, - bool Create); - - CS_IGNORE template - T *FindTemplate(const std::string &USR); - - CS_IGNORE Enumeration *FindEnum(const void *OriginalPtr); - CS_IGNORE Enumeration *FindEnum(const std::string &Name, bool Create = false); - CS_IGNORE Enumeration *FindEnumWithItem(const std::string &Name); - - CS_IGNORE Function *FindFunction(const std::string &USR); - - CS_IGNORE TypedefDecl *FindTypedef(const std::string &Name, bool Create = false); - - CS_IGNORE TypeAlias *FindTypeAlias(const std::string &Name, bool Create = false); - - CS_IGNORE Variable *FindVariable(const std::string &USR); - - CS_IGNORE Friend *FindFriend(const std::string &USR); - - VECTOR(Namespace *, Namespaces) - VECTOR(Enumeration *, Enums) - VECTOR(Function *, Functions) - VECTOR(Class *, Classes) - VECTOR(Template *, Templates) - VECTOR(TypedefDecl *, Typedefs) - VECTOR(TypeAlias *, TypeAliases) - VECTOR(Variable *, Variables) - VECTOR(Friend *, Friends) - - std::map anonymous; - - bool isAnonymous; - }; - - class CS_API TypedefNameDecl : public Declaration - { - public: - TypedefNameDecl(DeclarationKind kind); - ~TypedefNameDecl(); - QualifiedType qualifiedType; - }; - - class CS_API TypedefDecl : public TypedefNameDecl - { - public: - DECLARE_DECL_KIND(TypedefDecl, Typedef) - ~TypedefDecl(); - }; - - class CS_API TypeAlias : public TypedefNameDecl - { - public: - TypeAlias(); - ~TypeAlias(); - TypeAliasTemplate *describedAliasTemplate; - }; - - class CS_API Friend : public Declaration - { - public: - DECLARE_DECL_KIND(Friend, Friend) - ~Friend(); - Declaration *declaration; - }; - - enum class StatementClassObsolete - { - Any, - BinaryOperator, - CallExprClass, - DeclRefExprClass, - CXXConstructExprClass, - CXXOperatorCallExpr, - ImplicitCastExpr, - ExplicitCastExpr, - }; - - class CS_API StatementObsolete - { - public: - StatementObsolete(const std::string &str, StatementClassObsolete Class = StatementClassObsolete::Any, Declaration *decl = 0); - StatementClassObsolete _class; - Declaration *decl; - std::string string; - }; - - class CS_API ExpressionObsolete : public StatementObsolete - { - public: - ExpressionObsolete(const std::string &str, StatementClassObsolete Class = StatementClassObsolete::Any, Declaration *decl = 0); - }; - - class Expr; - - class CS_API BinaryOperatorObsolete : public ExpressionObsolete - { - public: - BinaryOperatorObsolete(const std::string &str, ExpressionObsolete *lhs, ExpressionObsolete *rhs, const std::string &opcodeStr); - ~BinaryOperatorObsolete(); - ExpressionObsolete *LHS; - ExpressionObsolete *RHS; - std::string opcodeStr; - }; - - class CS_API CallExprObsolete : public ExpressionObsolete - { - public: - CallExprObsolete(const std::string &str, Declaration *decl); - ~CallExprObsolete(); - VECTOR(ExpressionObsolete *, Arguments) - }; - - class CS_API CXXConstructExprObsolete : public ExpressionObsolete - { - public: - CXXConstructExprObsolete(const std::string &str, Declaration *decl = 0); - ~CXXConstructExprObsolete(); - VECTOR(ExpressionObsolete *, Arguments) - }; - - class CS_API Parameter : public Declaration - { - public: - Parameter(); - ~Parameter(); - - QualifiedType qualifiedType; - bool isIndirect; - bool hasDefaultValue; - unsigned int index; - ExpressionObsolete *defaultArgument; - Expr *defaultValue; - }; - - enum class CXXMethodKind - { - Normal, - Constructor, - Destructor, - Conversion, - Operator, - UsingDirective - }; - - enum class CXXOperatorKind - { - None, - New, - Delete, - Array_New, - Array_Delete, - Plus, - Minus, - Star, - Slash, - Percent, - Caret, - Amp, - Pipe, - Tilde, - Exclaim, - Equal, - Less, - Greater, - PlusEqual, - MinusEqual, - StarEqual, - SlashEqual, - PercentEqual, - CaretEqual, - AmpEqual, - PipeEqual, - LessLess, - GreaterGreater, - LessLessEqual, - GreaterGreaterEqual, - EqualEqual, - ExclaimEqual, - LessEqual, - GreaterEqual, - Spaceship, - AmpAmp, - PipePipe, - PlusPlus, - MinusMinus, - Comma, - ArrowStar, - Arrow, - Call, - Subscript, - Conditional, - Coawait - }; - - class FunctionTemplateSpecialization; - - enum class FriendKind - { - None, - Declared, - Undeclared - }; - - class Stmt; - - class CS_API Function : public DeclarationContext - { - public: - Function(); - ~Function(); - - QualifiedType returnType; - bool isReturnIndirect; - bool hasThisReturn; - - bool isConstExpr; - bool isVariadic; - bool isInline; - bool isPure; - bool isDeleted; - bool isDefaulted; - FriendKind friendKind; - CXXOperatorKind operatorKind; - std::string mangled; - std::string signature; - std::string body; - Stmt *bodyStmt; - CallingConvention callingConvention; - VECTOR(Parameter *, Parameters) - FunctionTemplateSpecialization *specializationInfo; - Function *instantiatedFrom; - QualifiedType qualifiedType; - }; - - class AccessSpecifierDecl; - - enum class RefQualifierKind - { - None, - LValue, - RValue - }; - - class CS_API Method : public Function - { - public: - Method(); - ~Method(); - - bool isVirtual; - bool isStatic; - bool isConst; - bool isExplicit; - bool isVolatile; - - CXXMethodKind methodKind; - - bool isDefaultConstructor; - bool isCopyConstructor; - bool isMoveConstructor; - - QualifiedType conversionType; - RefQualifierKind refQualifier; - VECTOR(Method *, OverriddenMethods) - }; - - class CS_API Enumeration : public DeclarationContext - { - public: - DECLARE_DECL_KIND(Enumeration, Enumeration) - ~Enumeration(); - - class CS_API Item : public Declaration - { - public: - DECLARE_DECL_KIND(Item, EnumerationItem) - Item(const Item &); - ~Item(); - std::string expression; - uint64_t value; - }; - - enum class CS_FLAGS EnumModifiers - { - Anonymous = 1 << 0, - Scoped = 1 << 1, - Flags = 1 << 2, - }; - - EnumModifiers modifiers; - Type *type; - BuiltinType *builtinType; - VECTOR(Item *, Items) - - Item *FindItemByName(const std::string &Name); - }; - - class CS_API Variable : public Declaration - { - public: - DECLARE_DECL_KIND(Variable, Variable) - ~Variable(); - bool isConstExpr; - std::string mangled; - QualifiedType qualifiedType; - ExpressionObsolete *initializer; - }; - - class PreprocessedEntity; - - struct CS_API BaseClassSpecifier - { - BaseClassSpecifier(); - AccessSpecifier access; - bool isVirtual; - Type *type; - int offset; - }; - - class Class; - - class CS_API Field : public Declaration - { - public: - DECLARE_DECL_KIND(Field, Field) - ~Field(); - QualifiedType qualifiedType; - Class *_class; - bool isBitField; - unsigned bitWidth; - }; - - class CS_API AccessSpecifierDecl : public Declaration - { - public: - DECLARE_DECL_KIND(AccessSpecifierDecl, AccessSpecifier) - ~AccessSpecifierDecl(); - }; - - enum class CppAbi - { - Itanium, - Microsoft, - ARM, - AArch64, - iOS, - AppleARM64, - WebAssembly - }; - - enum class VTableComponentKind - { - VCallOffset, - VBaseOffset, - OffsetToTop, - RTTI, - FunctionPointer, - CompleteDtorPointer, - DeletingDtorPointer, - UnusedFunctionPointer, - }; - - struct CS_API VTableComponent - { - VTableComponent(); - VTableComponentKind kind; - unsigned offset; - Declaration *declaration; - }; - - struct CS_API VTableLayout - { - VTableLayout(); - VTableLayout(const VTableLayout &); - ~VTableLayout(); - VECTOR(VTableComponent, Components) - }; - - struct CS_API VFTableInfo - { - VFTableInfo(); - VFTableInfo(const VFTableInfo &); - uint64_t VBTableIndex; - uint32_t VFPtrOffset; - uint32_t VFPtrFullOffset; - VTableLayout layout; - }; - - class CS_API LayoutField - { - public: - LayoutField(); - LayoutField(const LayoutField &other); - ~LayoutField(); - unsigned offset; - std::string name; - QualifiedType qualifiedType; - void *fieldPtr; - }; - - class Class; - - class CS_API LayoutBase - { - public: - LayoutBase(); - LayoutBase(const LayoutBase &other); - ~LayoutBase(); - unsigned offset; - Class *_class; - }; - - enum class RecordArgABI - { - /// Pass it using the normal C aggregate rules for the ABI, - /// potentially introducing extra copies and passing some - /// or all of it in registers. - Default = 0, - /// Pass it on the stack using its defined layout. - /// The argument must be evaluated directly into the correct - /// stack position in the arguments area, and the call machinery - /// must not move it or introduce extra copies. - DirectInMemory, - /// Pass it as a pointer to temporary memory. - Indirect - }; - - struct CS_API ClassLayout - { - ClassLayout(); - CppAbi ABI; - RecordArgABI argABI; - VECTOR(VFTableInfo, VFTables) - VTableLayout layout; - bool hasOwnVFPtr; - long VBPtrOffset; - int alignment; - int size; - int dataSize; - VECTOR(LayoutField, Fields) - VECTOR(LayoutBase, Bases) - }; - - enum class TagKind - { - Struct, - Interface, - Union, - Class, - Enum - }; - - class CS_API Class : public DeclarationContext - { - public: - Class(); - ~Class(); - - VECTOR(BaseClassSpecifier *, Bases) - VECTOR(Field *, Fields) - VECTOR(Method *, Methods) - VECTOR(AccessSpecifierDecl *, Specifiers) - - bool isPOD; - bool isAbstract; - bool isUnion; - bool isDynamic; - bool isPolymorphic; - bool hasNonTrivialDefaultConstructor; - bool hasNonTrivialCopyConstructor; - bool hasNonTrivialDestructor; - bool isExternCContext; - bool isInjected; - TagKind tagKind; - - ClassLayout *layout; - }; - - class CS_API Template : public Declaration - { - public: - Template(DeclarationKind kind); - DECLARE_DECL_KIND(Template, Template) - Declaration *TemplatedDecl; - VECTOR(Declaration *, Parameters) - }; - - template - T *DeclarationContext::FindTemplate(const std::string &USR) - { - auto foundTemplate = std::find_if(Templates.begin(), Templates.end(), - [&](Template *t) - { return t->USR == USR; }); - - if (foundTemplate != Templates.end()) - return static_cast(*foundTemplate); - - return nullptr; - } - - class CS_API TypeAliasTemplate : public Template - { - public: - TypeAliasTemplate(); - ~TypeAliasTemplate(); - - Declaration* CanonicalDecl = nullptr; - }; - - class CS_API TemplateParameter : public Declaration - { - public: - TemplateParameter(DeclarationKind kind); - ~TemplateParameter(); - unsigned int depth; - unsigned int index; - bool isParameterPack; - }; - - class CS_API TemplateTemplateParameter : public Template - { - public: - TemplateTemplateParameter(); - ~TemplateTemplateParameter(); - - bool isParameterPack; - bool isPackExpansion; - bool isExpandedParameterPack; - }; - - class CS_API TypeTemplateParameter : public TemplateParameter - { - public: - TypeTemplateParameter(); - TypeTemplateParameter(const TypeTemplateParameter &); - ~TypeTemplateParameter(); - - QualifiedType defaultArgument; - }; - - class CS_API NonTypeTemplateParameter : public TemplateParameter - { - public: - NonTypeTemplateParameter(); - NonTypeTemplateParameter(const NonTypeTemplateParameter &); - ~NonTypeTemplateParameter(); - ExpressionObsolete *defaultArgument; - Expr *defaultArgumentNew; - unsigned int position; - bool isPackExpansion; - bool isExpandedParameterPack; - QualifiedType type; - }; - - class ClassTemplateSpecialization; - class ClassTemplatePartialSpecialization; - - class CS_API ClassTemplate : public Template - { - public: - ClassTemplate(); - ~ClassTemplate(); - VECTOR(ClassTemplateSpecialization *, Specializations) - ClassTemplateSpecialization *FindSpecialization(const std::string &usr); - ClassTemplatePartialSpecialization *FindPartialSpecialization(const std::string &usr); - }; - - enum class TemplateSpecializationKind - { - Undeclared, - ImplicitInstantiation, - ExplicitSpecialization, - ExplicitInstantiationDeclaration, - ExplicitInstantiationDefinition - }; - - class CS_API ClassTemplateSpecialization : public Class - { - public: - ClassTemplateSpecialization(); - ~ClassTemplateSpecialization(); - ClassTemplate *templatedDecl; - VECTOR(TemplateArgument, Arguments) - TemplateSpecializationKind specializationKind; - }; - - class CS_API ClassTemplatePartialSpecialization : public ClassTemplateSpecialization - { - public: - ClassTemplatePartialSpecialization(); - ~ClassTemplatePartialSpecialization(); - VECTOR(Declaration *, Parameters) - }; - - class CS_API FunctionTemplate : public Template - { - public: - FunctionTemplate(); - ~FunctionTemplate(); - VECTOR(FunctionTemplateSpecialization *, Specializations) - FunctionTemplateSpecialization *FindSpecialization(const std::string &usr); - }; - - class CS_API FunctionTemplateSpecialization - { - public: - FunctionTemplateSpecialization(); - ~FunctionTemplateSpecialization(); - FunctionTemplate *_template; - VECTOR(TemplateArgument, Arguments) - Function *specializedFunction; - TemplateSpecializationKind specializationKind; - }; - - class VarTemplateSpecialization; - class VarTemplatePartialSpecialization; - - class CS_API VarTemplate : public Template - { - public: - VarTemplate(); - ~VarTemplate(); - VECTOR(VarTemplateSpecialization *, Specializations) - VarTemplateSpecialization *FindSpecialization(const std::string &usr); - VarTemplatePartialSpecialization *FindPartialSpecialization(const std::string &usr); - }; - - class CS_API VarTemplateSpecialization : public Variable - { - public: - VarTemplateSpecialization(); - ~VarTemplateSpecialization(); - VarTemplate *templatedDecl; - VECTOR(TemplateArgument, Arguments) - TemplateSpecializationKind specializationKind; - }; - - class CS_API VarTemplatePartialSpecialization : public VarTemplateSpecialization - { - public: - VarTemplatePartialSpecialization(); - ~VarTemplatePartialSpecialization(); - }; - - class CS_API UnresolvedUsingTypename : public Declaration - { - public: - UnresolvedUsingTypename(); - ~UnresolvedUsingTypename(); - }; - - class CS_API Namespace : public DeclarationContext - { - public: - Namespace(); - ~Namespace(); - bool isInline; - }; - - enum class MacroLocation - { - Unknown, - ClassHead, - ClassBody, - FunctionHead, - FunctionParameters, - FunctionBody, - }; - - class CS_API PreprocessedEntity - { - public: - PreprocessedEntity(); - MacroLocation macroLocation; - void *originalPtr; - DeclarationKind kind; - }; - - class CS_API MacroDefinition : public PreprocessedEntity - { - public: - MacroDefinition(); - ~MacroDefinition(); - std::string name; - std::string expression; - int lineNumberStart; - int lineNumberEnd; - }; - - class CS_API MacroExpansion : public PreprocessedEntity - { - public: - MacroExpansion(); - ~MacroExpansion(); - std::string name; - std::string text; - MacroDefinition *definition; - }; - - class CS_API TranslationUnit : public Namespace - { - public: - TranslationUnit(); - ~TranslationUnit(); - std::string fileName; - bool isSystemHeader; - VECTOR(MacroDefinition *, Macros) - }; - - class CS_API ASTContext - { - public: - ASTContext(); - ~ASTContext(); - TranslationUnit *FindOrCreateModule(const std::string& File); - VECTOR(TranslationUnit *, TranslationUnits) - }; - - } + enum class AccessSpecifier + { + Private, + Protected, + Public + }; + + class DeclarationContext; + class RawComment; + class PreprocessedEntity; + + class ExpressionObsolete; + class CS_API Declaration + { + public: + Declaration(DeclarationKind kind); + Declaration(const Declaration&); + ~Declaration(); + + DeclarationKind kind; + int alignAs; + int maxFieldAlignment; + AccessSpecifier access; + DeclarationContext* _namespace; + SourceLocation location; + int lineNumberStart; + int lineNumberEnd; + std::string name; + std::string USR; + std::string debugText; + bool isIncomplete; + bool isDependent; + bool isImplicit; + bool isInvalid; + bool isDeprecated; + Declaration* completeDeclaration; + unsigned definitionOrder; + VECTOR(PreprocessedEntity*, PreprocessedEntities) + VECTOR(Declaration*, Redeclarations) + void* originalPtr; + RawComment* comment; + }; + + class Class; + class Enumeration; + class Function; + class TypedefDecl; + class TypeAlias; + class Namespace; + class Template; + class TypeAliasTemplate; + class ClassTemplate; + class FunctionTemplate; + class Variable; + class Friend; + + class CS_API DeclarationContext : public Declaration + { + public: + DeclarationContext(DeclarationKind kind); + + CS_IGNORE Declaration* FindAnonymous(const std::string& USR); + + CS_IGNORE Namespace* FindNamespace(const std::string& Name); + CS_IGNORE Namespace* FindNamespace(const std::vector&); + CS_IGNORE Namespace* FindCreateNamespace(const std::string& Name); + + CS_IGNORE Class* CreateClass(const std::string& Name, bool IsComplete); + CS_IGNORE Class* FindClass(const void* OriginalPtr, const std::string& Name, bool IsComplete); + CS_IGNORE Class* FindClass(const void* OriginalPtr, const std::string& Name, bool IsComplete, bool Create); + + CS_IGNORE template + T* FindTemplate(const std::string& USR); + + CS_IGNORE Enumeration* FindEnum(const void* OriginalPtr); + CS_IGNORE Enumeration* FindEnum(const std::string& Name, bool Create = false); + CS_IGNORE Enumeration* FindEnumWithItem(const std::string& Name); + + CS_IGNORE Function* FindFunction(const std::string& USR); + + CS_IGNORE TypedefDecl* FindTypedef(const std::string& Name, bool Create = false); + + CS_IGNORE TypeAlias* FindTypeAlias(const std::string& Name, bool Create = false); + + CS_IGNORE Variable* FindVariable(const std::string& USR); + + CS_IGNORE Friend* FindFriend(const std::string& USR); + + VECTOR(Namespace*, Namespaces) + VECTOR(Enumeration*, Enums) + VECTOR(Function*, Functions) + VECTOR(Class*, Classes) + VECTOR(Template*, Templates) + VECTOR(TypedefDecl*, Typedefs) + VECTOR(TypeAlias*, TypeAliases) + VECTOR(Variable*, Variables) + VECTOR(Friend*, Friends) + + std::map anonymous; + + bool isAnonymous; + }; + + class CS_API TypedefNameDecl : public Declaration + { + public: + TypedefNameDecl(DeclarationKind kind); + ~TypedefNameDecl(); + QualifiedType qualifiedType; + }; + + class CS_API TypedefDecl : public TypedefNameDecl + { + public: + DECLARE_DECL_KIND(TypedefDecl, Typedef) + ~TypedefDecl(); + }; + + class CS_API TypeAlias : public TypedefNameDecl + { + public: + TypeAlias(); + ~TypeAlias(); + TypeAliasTemplate* describedAliasTemplate; + }; + + class CS_API Friend : public Declaration + { + public: + DECLARE_DECL_KIND(Friend, Friend) + ~Friend(); + Declaration* declaration; + }; + + enum class StatementClassObsolete + { + Any, + BinaryOperator, + CallExprClass, + DeclRefExprClass, + CXXConstructExprClass, + CXXOperatorCallExpr, + ImplicitCastExpr, + ExplicitCastExpr, + }; + + class CS_API StatementObsolete + { + public: + StatementObsolete(const std::string& str, StatementClassObsolete Class = StatementClassObsolete::Any, Declaration* decl = 0); + StatementClassObsolete _class; + Declaration* decl; + std::string string; + }; + + class CS_API ExpressionObsolete : public StatementObsolete + { + public: + ExpressionObsolete(const std::string& str, StatementClassObsolete Class = StatementClassObsolete::Any, Declaration* decl = 0); + }; + + class Expr; + + class CS_API BinaryOperatorObsolete : public ExpressionObsolete + { + public: + BinaryOperatorObsolete(const std::string& str, ExpressionObsolete* lhs, ExpressionObsolete* rhs, const std::string& opcodeStr); + ~BinaryOperatorObsolete(); + ExpressionObsolete* LHS; + ExpressionObsolete* RHS; + std::string opcodeStr; + }; + + class CS_API CallExprObsolete : public ExpressionObsolete + { + public: + CallExprObsolete(const std::string& str, Declaration* decl); + ~CallExprObsolete(); + VECTOR(ExpressionObsolete*, Arguments) + }; + + class CS_API CXXConstructExprObsolete : public ExpressionObsolete + { + public: + CXXConstructExprObsolete(const std::string& str, Declaration* decl = 0); + ~CXXConstructExprObsolete(); + VECTOR(ExpressionObsolete*, Arguments) + }; + + class CS_API Parameter : public Declaration + { + public: + Parameter(); + ~Parameter(); + + QualifiedType qualifiedType; + bool isIndirect; + bool hasDefaultValue; + unsigned int index; + ExpressionObsolete* defaultArgument; + Expr* defaultValue; + }; + + enum class CXXMethodKind + { + Normal, + Constructor, + Destructor, + Conversion, + Operator, + UsingDirective + }; + + enum class CXXOperatorKind + { + None, + New, + Delete, + Array_New, + Array_Delete, + Plus, + Minus, + Star, + Slash, + Percent, + Caret, + Amp, + Pipe, + Tilde, + Exclaim, + Equal, + Less, + Greater, + PlusEqual, + MinusEqual, + StarEqual, + SlashEqual, + PercentEqual, + CaretEqual, + AmpEqual, + PipeEqual, + LessLess, + GreaterGreater, + LessLessEqual, + GreaterGreaterEqual, + EqualEqual, + ExclaimEqual, + LessEqual, + GreaterEqual, + Spaceship, + AmpAmp, + PipePipe, + PlusPlus, + MinusMinus, + Comma, + ArrowStar, + Arrow, + Call, + Subscript, + Conditional, + Coawait + }; + + class FunctionTemplateSpecialization; + + enum class FriendKind + { + None, + Declared, + Undeclared + }; + + class Stmt; + + class CS_API Function : public DeclarationContext + { + public: + Function(); + ~Function(); + + QualifiedType returnType; + bool isReturnIndirect; + bool hasThisReturn; + + bool isConstExpr; + bool isVariadic; + bool isInline; + bool isPure; + bool isDeleted; + bool isDefaulted; + FriendKind friendKind; + CXXOperatorKind operatorKind; + std::string mangled; + std::string signature; + std::string body; + Stmt* bodyStmt; + CallingConvention callingConvention; + VECTOR(Parameter*, Parameters) + FunctionTemplateSpecialization* specializationInfo; + Function* instantiatedFrom; + QualifiedType qualifiedType; + }; + + class AccessSpecifierDecl; + + enum class RefQualifierKind + { + None, + LValue, + RValue + }; + + class CS_API Method : public Function + { + public: + Method(); + ~Method(); + + bool isVirtual; + bool isStatic; + bool isConst; + bool isExplicit; + bool isVolatile; + + CXXMethodKind methodKind; + + bool isDefaultConstructor; + bool isCopyConstructor; + bool isMoveConstructor; + + QualifiedType conversionType; + RefQualifierKind refQualifier; + VECTOR(Method*, OverriddenMethods) + }; + + class CS_API Enumeration : public DeclarationContext + { + public: + DECLARE_DECL_KIND(Enumeration, Enumeration) + ~Enumeration(); + + class CS_API Item : public Declaration + { + public: + DECLARE_DECL_KIND(Item, EnumerationItem) + Item(const Item&); + ~Item(); + std::string expression; + uint64_t value; + }; + + enum class CS_FLAGS EnumModifiers + { + Anonymous = 1 << 0, + Scoped = 1 << 1, + Flags = 1 << 2, + }; + + EnumModifiers modifiers; + Type* type; + BuiltinType* builtinType; + VECTOR(Item*, Items) + + Item* FindItemByName(const std::string& Name); + }; + + class CS_API Variable : public Declaration + { + public: + DECLARE_DECL_KIND(Variable, Variable) + ~Variable(); + bool isConstExpr; + std::string mangled; + QualifiedType qualifiedType; + ExpressionObsolete* initializer; + }; + + class PreprocessedEntity; + + struct CS_API BaseClassSpecifier + { + BaseClassSpecifier(); + AccessSpecifier access; + bool isVirtual; + Type* type; + int offset; + }; + + class Class; + + class CS_API Field : public Declaration + { + public: + DECLARE_DECL_KIND(Field, Field) + ~Field(); + QualifiedType qualifiedType; + Class* _class; + bool isBitField; + unsigned bitWidth; + }; + + class CS_API AccessSpecifierDecl : public Declaration + { + public: + DECLARE_DECL_KIND(AccessSpecifierDecl, AccessSpecifier) + ~AccessSpecifierDecl(); + }; + + enum class CppAbi + { + Itanium, + Microsoft, + ARM, + AArch64, + iOS, + AppleARM64, + WebAssembly + }; + + enum class VTableComponentKind + { + VCallOffset, + VBaseOffset, + OffsetToTop, + RTTI, + FunctionPointer, + CompleteDtorPointer, + DeletingDtorPointer, + UnusedFunctionPointer, + }; + + struct CS_API VTableComponent + { + VTableComponent(); + VTableComponentKind kind; + unsigned offset; + Declaration* declaration; + }; + + struct CS_API VTableLayout + { + VTableLayout(); + VTableLayout(const VTableLayout&); + ~VTableLayout(); + VECTOR(VTableComponent, Components) + }; + + struct CS_API VFTableInfo + { + VFTableInfo(); + VFTableInfo(const VFTableInfo&); + uint64_t VBTableIndex; + uint32_t VFPtrOffset; + uint32_t VFPtrFullOffset; + VTableLayout layout; + }; + + class CS_API LayoutField + { + public: + LayoutField(); + LayoutField(const LayoutField& other); + ~LayoutField(); + unsigned offset; + std::string name; + QualifiedType qualifiedType; + void* fieldPtr; + }; + + class Class; + + class CS_API LayoutBase + { + public: + LayoutBase(); + LayoutBase(const LayoutBase& other); + ~LayoutBase(); + unsigned offset; + Class* _class; + }; + + enum class RecordArgABI + { + /// Pass it using the normal C aggregate rules for the ABI, + /// potentially introducing extra copies and passing some + /// or all of it in registers. + Default = 0, + /// Pass it on the stack using its defined layout. + /// The argument must be evaluated directly into the correct + /// stack position in the arguments area, and the call machinery + /// must not move it or introduce extra copies. + DirectInMemory, + /// Pass it as a pointer to temporary memory. + Indirect + }; + + struct CS_API ClassLayout + { + ClassLayout(); + CppAbi ABI; + RecordArgABI argABI; + VECTOR(VFTableInfo, VFTables) + VTableLayout layout; + bool hasOwnVFPtr; + long VBPtrOffset; + int alignment; + int size; + int dataSize; + VECTOR(LayoutField, Fields) + VECTOR(LayoutBase, Bases) + }; + + enum class TagKind + { + Struct, + Interface, + Union, + Class, + Enum + }; + + class CS_API Class : public DeclarationContext + { + public: + Class(); + ~Class(); + + VECTOR(BaseClassSpecifier*, Bases) + VECTOR(Field*, Fields) + VECTOR(Method*, Methods) + VECTOR(AccessSpecifierDecl*, Specifiers) + + bool isPOD; + bool isAbstract; + bool isUnion; + bool isDynamic; + bool isPolymorphic; + bool hasNonTrivialDefaultConstructor; + bool hasNonTrivialCopyConstructor; + bool hasNonTrivialDestructor; + bool isExternCContext; + bool isInjected; + TagKind tagKind; + + ClassLayout* layout; + }; + + class CS_API Template : public Declaration + { + public: + Template(DeclarationKind kind); + DECLARE_DECL_KIND(Template, Template) + Declaration* TemplatedDecl; + VECTOR(Declaration*, Parameters) + }; + + template + T* DeclarationContext::FindTemplate(const std::string& USR) + { + auto foundTemplate = std::find_if(Templates.begin(), Templates.end(), + [&](Template* t) + { + return t->USR == USR; + }); + + if (foundTemplate != Templates.end()) + return static_cast(*foundTemplate); + + return nullptr; } -} \ No newline at end of file + + class CS_API TypeAliasTemplate : public Template + { + public: + TypeAliasTemplate(); + ~TypeAliasTemplate(); + + Declaration* CanonicalDecl = nullptr; + }; + + class CS_API TemplateParameter : public Declaration + { + public: + TemplateParameter(DeclarationKind kind); + ~TemplateParameter(); + unsigned int depth; + unsigned int index; + bool isParameterPack; + }; + + class CS_API TemplateTemplateParameter : public Template + { + public: + TemplateTemplateParameter(); + ~TemplateTemplateParameter(); + + bool isParameterPack; + bool isPackExpansion; + bool isExpandedParameterPack; + }; + + class CS_API TypeTemplateParameter : public TemplateParameter + { + public: + TypeTemplateParameter(); + TypeTemplateParameter(const TypeTemplateParameter&); + ~TypeTemplateParameter(); + + QualifiedType defaultArgument; + }; + + class CS_API NonTypeTemplateParameter : public TemplateParameter + { + public: + NonTypeTemplateParameter(); + NonTypeTemplateParameter(const NonTypeTemplateParameter&); + ~NonTypeTemplateParameter(); + ExpressionObsolete* defaultArgument; + Expr* defaultArgumentNew; + unsigned int position; + bool isPackExpansion; + bool isExpandedParameterPack; + QualifiedType type; + }; + + class ClassTemplateSpecialization; + class ClassTemplatePartialSpecialization; + + class CS_API ClassTemplate : public Template + { + public: + ClassTemplate(); + ~ClassTemplate(); + VECTOR(ClassTemplateSpecialization*, Specializations) + ClassTemplateSpecialization* FindSpecialization(const std::string& usr); + ClassTemplatePartialSpecialization* FindPartialSpecialization(const std::string& usr); + }; + + enum class TemplateSpecializationKind + { + Undeclared, + ImplicitInstantiation, + ExplicitSpecialization, + ExplicitInstantiationDeclaration, + ExplicitInstantiationDefinition + }; + + class CS_API ClassTemplateSpecialization : public Class + { + public: + ClassTemplateSpecialization(); + ~ClassTemplateSpecialization(); + ClassTemplate* templatedDecl; + VECTOR(TemplateArgument, Arguments) + TemplateSpecializationKind specializationKind; + }; + + class CS_API ClassTemplatePartialSpecialization : public ClassTemplateSpecialization + { + public: + ClassTemplatePartialSpecialization(); + ~ClassTemplatePartialSpecialization(); + VECTOR(Declaration*, Parameters) + }; + + class CS_API FunctionTemplate : public Template + { + public: + FunctionTemplate(); + ~FunctionTemplate(); + VECTOR(FunctionTemplateSpecialization*, Specializations) + FunctionTemplateSpecialization* FindSpecialization(const std::string& usr); + }; + + class CS_API FunctionTemplateSpecialization + { + public: + FunctionTemplateSpecialization(); + ~FunctionTemplateSpecialization(); + FunctionTemplate* _template; + VECTOR(TemplateArgument, Arguments) + Function* specializedFunction; + TemplateSpecializationKind specializationKind; + }; + + class VarTemplateSpecialization; + class VarTemplatePartialSpecialization; + + class CS_API VarTemplate : public Template + { + public: + VarTemplate(); + ~VarTemplate(); + VECTOR(VarTemplateSpecialization*, Specializations) + VarTemplateSpecialization* FindSpecialization(const std::string& usr); + VarTemplatePartialSpecialization* FindPartialSpecialization(const std::string& usr); + }; + + class CS_API VarTemplateSpecialization : public Variable + { + public: + VarTemplateSpecialization(); + ~VarTemplateSpecialization(); + VarTemplate* templatedDecl; + VECTOR(TemplateArgument, Arguments) + TemplateSpecializationKind specializationKind; + }; + + class CS_API VarTemplatePartialSpecialization : public VarTemplateSpecialization + { + public: + VarTemplatePartialSpecialization(); + ~VarTemplatePartialSpecialization(); + }; + + class CS_API UnresolvedUsingTypename : public Declaration + { + public: + UnresolvedUsingTypename(); + ~UnresolvedUsingTypename(); + }; + + class CS_API Namespace : public DeclarationContext + { + public: + Namespace(); + ~Namespace(); + bool isInline; + }; + + enum class MacroLocation + { + Unknown, + ClassHead, + ClassBody, + FunctionHead, + FunctionParameters, + FunctionBody, + }; + + class CS_API PreprocessedEntity + { + public: + PreprocessedEntity(); + MacroLocation macroLocation; + void* originalPtr; + DeclarationKind kind; + }; + + class CS_API MacroDefinition : public PreprocessedEntity + { + public: + MacroDefinition(); + ~MacroDefinition(); + std::string name; + std::string expression; + int lineNumberStart; + int lineNumberEnd; + }; + + class CS_API MacroExpansion : public PreprocessedEntity + { + public: + MacroExpansion(); + ~MacroExpansion(); + std::string name; + std::string text; + MacroDefinition* definition; + }; + + class CS_API TranslationUnit : public Namespace + { + public: + TranslationUnit(); + ~TranslationUnit(); + std::string fileName; + bool isSystemHeader; + VECTOR(MacroDefinition*, Macros) + }; + + class CS_API ASTContext + { + public: + ASTContext(); + ~ASTContext(); + TranslationUnit* FindOrCreateModule(const std::string& File); + VECTOR(TranslationUnit*, TranslationUnits) + }; + +} +} +} // namespace CppSharp::CppParser::AST \ No newline at end of file diff --git a/src/CppParser/ELFDumper.h b/src/CppParser/ELFDumper.h index 599e5f0f..1f5bdcb6 100644 --- a/src/CppParser/ELFDumper.h +++ b/src/CppParser/ELFDumper.h @@ -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 @@ namespace CppSharp { namespace CppParser { -template -class ELFDumper { -public: - ELFDumper(const llvm::object::ELFFile *Obj); - - std::vector getNeededLibraries() const; - -private: - typedef llvm::object::ELFFile 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 + class ELFDumper + { + public: + ELFDumper(const llvm::object::ELFFile* Obj); + + std::vector getNeededLibraries() const; + + private: + typedef llvm::object::ELFFile 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 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 dynamic_table() const { - return llvm::make_range(dynamic_table_begin(), dynamic_table_end()); - } + template + ELFDumper::ELFDumper(const llvm::object::ELFFile* Obj) + { - const ELFO *Obj; - DynRegionInfo DynamicRegion; - llvm::StringRef DynamicStringTable; -}; + llvm::SmallVector 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 -ELFDumper::ELFDumper(const llvm::object::ELFFile *Obj) { + template + const typename ELFDumper::Elf_Dyn* + ELFDumper::dynamic_table_begin() const + { + return reinterpret_cast(DynamicRegion.Addr); + } - llvm::SmallVector LoadSegments; - auto ProgramHeaders = Obj->program_headers(); - if (ProgramHeaders.takeError()) + template + const typename ELFDumper::Elf_Dyn* + ELFDumper::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 + llvm::StringRef ELFDumper::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 + std::vector ELFDumper::getNeededLibraries() const + { + std::vector 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 -const typename ELFDumper::Elf_Dyn * -ELFDumper::dynamic_table_begin() const { - return reinterpret_cast(DynamicRegion.Addr); -} - -template -const typename ELFDumper::Elf_Dyn * -ELFDumper::dynamic_table_end() const { - uint64_t Size = DynamicRegion.Size; - return dynamic_table_begin() + Size / sizeof(Elf_Dyn); -} - -template -llvm::StringRef ELFDumper::getDynamicString(uint64_t Value) const { - return llvm::StringRef(DynamicStringTable.data() + Value); -} - -template -std::vector ELFDumper::getNeededLibraries() const { - std::vector 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 diff --git a/src/CppParser/Helpers.h b/src/CppParser/Helpers.h index 1efc611d..4af8a193 100644 --- a/src/CppParser/Helpers.h +++ b/src/CppParser/Helpers.h @@ -1,9 +1,9 @@ /************************************************************************ -* -* CppSharp -* Licensed under the simplified BSD license. -* -************************************************************************/ + * + * CppSharp + * Licensed under the simplified BSD license. + * + ************************************************************************/ #pragma once @@ -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 @@ /** 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 name; \ - type get##name (unsigned i); \ - void add##name (type& s); \ - unsigned get##name##Count (); \ +#define VECTOR(type, name) \ + std::vector 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 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 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(); \ + } diff --git a/src/CppParser/Link.cpp b/src/CppParser/Link.cpp index 46d06621..13201811 100644 --- a/src/CppParser/Link.cpp +++ b/src/CppParser/Link.cpp @@ -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 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& args, - const llvm::StringRef& Dir, llvm::StringRef& Stem, bool MinGW) + std::vector& 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, std::vector 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, } bool Parser::LinkELF(const CppLinkerOptions* LinkerOptions, - std::vector& args, - llvm::StringRef& Dir, llvm::StringRef& Stem) + std::vector& args, + llvm::StringRef& Dir, + llvm::StringRef& Stem) { #ifdef __linux__ using namespace llvm; @@ -153,8 +156,9 @@ bool Parser::LinkELF(const CppLinkerOptions* LinkerOptions, } bool Parser::LinkMachO(const CppLinkerOptions* LinkerOptions, - std::vector& args, - llvm::StringRef& Dir, llvm::StringRef& Stem) + std::vector& args, + llvm::StringRef& Dir, + llvm::StringRef& Stem) { #ifdef __APPLE__ using namespace llvm; @@ -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 diff --git a/src/CppParser/Parser.cpp b/src/CppParser/Parser.cpp index b7d1d895..25b1e1ff 100644 --- a/src/CppParser/Parser.cpp +++ b/src/CppParser/Parser.cpp @@ -1,9 +1,9 @@ /************************************************************************ -* -* CppSharp -* Licensed under the simplified BSD license. All rights reserved. -* -************************************************************************/ + * + * CppSharp + * Licensed under the simplified BSD license. All rights reserved. + * + ************************************************************************/ #ifdef DEBUG #undef DEBUG // workaround DEBUG define messing with LLVM COFF headers @@ -71,42 +71,48 @@ // Internals of assertm with or without abort. #define _assertm(condition, message, call) \ - do{ \ - if (!(condition)) { \ - std::cerr << "Assert at `" \ - << __FILE__ \ - << ":" \ - << __LINE__ \ - << "` in `" \ - << __FUNCTION__ \ - << "` failed. " \ - << message; \ - call; \ - } \ - } while (0) + do \ + { \ + if (!(condition)) \ + { \ + std::cerr << "Assert at `" \ + << __FILE__ \ + << ":" \ + << __LINE__ \ + << "` in `" \ + << __FUNCTION__ \ + << "` failed. " \ + << message; \ + call; \ + } \ + } \ + while (0) // Internals of assertml with or without abort. -#define _assertml(condition, message, sm, loc, call) \ - do{ \ - if (!(condition)) { \ - const clang::SourceManager& _sm = sm; \ - clang::SourceLocation _loc = loc; \ - std::cerr << "Assert at `" \ - << __FILE__ \ - << ":" \ - << __LINE__ \ - << "` in `" \ - << __FUNCTION__ \ - << "` failed. " \ - << message \ - << " Filename `" \ - << _sm.getFilename(_loc).str() \ - << ":" \ - << _sm.getSpellingLineNumber(_loc) \ - << "`\n"; \ - call; \ - } \ - }while(0) +#define _assertml(condition, message, sm, loc, call) \ + do \ + { \ + if (!(condition)) \ + { \ + const clang::SourceManager& _sm = sm; \ + clang::SourceLocation _loc = loc; \ + std::cerr << "Assert at `" \ + << __FILE__ \ + << ":" \ + << __LINE__ \ + << "` in `" \ + << __FUNCTION__ \ + << "` failed. " \ + << message \ + << " Filename `" \ + << _sm.getFilename(_loc).str() \ + << ":" \ + << _sm.getSpellingLineNumber(_loc) \ + << "`\n"; \ + call; \ + } \ + } \ + while (0) // Macros which output messages to console if parsing encounters oddity. // In debug builds, macros abort unless DEBUG_NO_ABORT is defined. @@ -134,7 +140,9 @@ #ifdef DEBUG_NO_ABORT #define debug_fail() debug_break() #else -#define debug_fail() debug_break(); abort() +#define debug_fail() \ + debug_break(); \ + abort() #endif #endif @@ -160,7 +168,8 @@ Parser::Parser(CppParserOptions* Opts) } LayoutField Parser::WalkVTablePointer(Class* Class, - const clang::CharUnits& Offset, const std::string& prefix) + const clang::CharUnits& Offset, + const std::string& prefix) { LayoutField LayoutField; LayoutField.offset = Offset.getQuantity(); @@ -173,31 +182,30 @@ static CppAbi GetClassLayoutAbi(clang::TargetCXXABI::Kind abi) { switch (abi) { - case clang::TargetCXXABI::Microsoft: - return CppAbi::Microsoft; - case clang::TargetCXXABI::GenericItanium: - return CppAbi::Itanium; - case clang::TargetCXXABI::GenericARM: - return CppAbi::ARM; - case clang::TargetCXXABI::GenericAArch64: - return CppAbi::AArch64; - case clang::TargetCXXABI::iOS: - return CppAbi::iOS; - case clang::TargetCXXABI::AppleARM64: - return CppAbi::AppleARM64; - case clang::TargetCXXABI::WebAssembly: - return CppAbi::WebAssembly; - default: - llvm_unreachable("Unsupported C++ ABI kind"); + case clang::TargetCXXABI::Microsoft: + return CppAbi::Microsoft; + case clang::TargetCXXABI::GenericItanium: + return CppAbi::Itanium; + case clang::TargetCXXABI::GenericARM: + return CppAbi::ARM; + case clang::TargetCXXABI::GenericAArch64: + return CppAbi::AArch64; + case clang::TargetCXXABI::iOS: + return CppAbi::iOS; + case clang::TargetCXXABI::AppleARM64: + return CppAbi::AppleARM64; + case clang::TargetCXXABI::WebAssembly: + return CppAbi::WebAssembly; + default: + llvm_unreachable("Unsupported C++ ABI kind"); } } -void Parser::ReadClassLayout(Class* Class, const clang::RecordDecl* RD, - clang::CharUnits Offset, bool IncludeVirtualBases) +void Parser::ReadClassLayout(Class* Class, const clang::RecordDecl* RD, clang::CharUnits Offset, bool IncludeVirtualBases) { using namespace clang; - const auto &Layout = c->getASTContext().getASTRecordLayout(RD); + const auto& Layout = c->getASTContext().getASTRecordLayout(RD); auto CXXRD = dyn_cast(RD); auto Parent = static_cast( @@ -212,55 +220,63 @@ void Parser::ReadClassLayout(Class* Class, const clang::RecordDecl* RD, } // Dump bases. - if (CXXRD) { - const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); + if (CXXRD) + { + const CXXRecordDecl* PrimaryBase = Layout.getPrimaryBase(); bool HasOwnVFPtr = Layout.hasOwnVFPtr(); bool HasOwnVBPtr = Layout.hasOwnVBPtr(); // Vtable pointer. if (CXXRD->isDynamicClass() && !PrimaryBase && - !c->getTarget().getCXXABI().isMicrosoft()) { + !c->getTarget().getCXXABI().isMicrosoft()) + { auto VPtr = WalkVTablePointer(Parent, Offset, "vptr"); Class->layout->Fields.push_back(VPtr); } - else if (HasOwnVFPtr) { + else if (HasOwnVFPtr) + { auto VTPtr = WalkVTablePointer(Parent, Offset, "vfptr"); Class->layout->Fields.push_back(VTPtr); } // Collect nvbases. - SmallVector Bases; - for (const CXXBaseSpecifier &Base : CXXRD->bases()) { - assertm(!Base.getType()->isDependentType(),"Cannot layout class with dependent bases.\n"); - + SmallVector Bases; + for (const CXXBaseSpecifier& Base : CXXRD->bases()) + { + assertm(!Base.getType()->isDependentType(), "Cannot layout class with dependent bases.\n"); + if (!Base.isVirtual()) Bases.push_back(Base.getType()->getAsCXXRecordDecl()); } // Sort nvbases by offset. std::stable_sort(Bases.begin(), Bases.end(), - [&](const CXXRecordDecl *L, const CXXRecordDecl *R) { - return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R); - }); + [&](const CXXRecordDecl* L, const CXXRecordDecl* R) + { + return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R); + }); // Dump (non-virtual) bases - for (const CXXRecordDecl *Base : Bases) { + for (const CXXRecordDecl* Base : Bases) + { CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base); ReadClassLayout(Class, Base, BaseOffset, - /*IncludeVirtualBases=*/false); + /*IncludeVirtualBases=*/false); } // vbptr (for Microsoft C++ ABI) - if (HasOwnVBPtr) { + if (HasOwnVBPtr) + { auto VBPtr = WalkVTablePointer(Parent, - Offset + Layout.getVBPtrOffset(), "vbptr"); + Offset + Layout.getVBPtrOffset(), "vbptr"); Class->layout->Fields.push_back(VBPtr); } } // Dump fields. uint64_t FieldNo = 0; - for (const FieldDecl* Field : RD->fields()) { + for (const FieldDecl* Field : RD->fields()) + { uint64_t LocalFieldOffsetInBits = Layout.getFieldOffset(FieldNo++); CharUnits FieldOffset = Offset + c->getASTContext().toCharUnitsFromBits(LocalFieldOffsetInBits); @@ -275,25 +291,28 @@ void Parser::ReadClassLayout(Class* Class, const clang::RecordDecl* RD, } // Dump virtual bases. - if (CXXRD && IncludeVirtualBases) { - const ASTRecordLayout::VBaseOffsetsMapTy &VtorDisps = + if (CXXRD && IncludeVirtualBases) + { + const ASTRecordLayout::VBaseOffsetsMapTy& VtorDisps = Layout.getVBaseOffsetsMap(); - for (const CXXBaseSpecifier &Base : CXXRD->vbases()) { + for (const CXXBaseSpecifier& Base : CXXRD->vbases()) + { assertm(Base.isVirtual(), "Found non-virtual class!\n"); - - const CXXRecordDecl *VBase = Base.getType()->getAsCXXRecordDecl(); + + const CXXRecordDecl* VBase = Base.getType()->getAsCXXRecordDecl(); CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase); - if (VtorDisps.find(VBase)->second.hasVtorDisp()) { + if (VtorDisps.find(VBase)->second.hasVtorDisp()) + { auto VtorDisp = WalkVTablePointer(Parent, - VBaseOffset - CharUnits::fromQuantity(4), "vtordisp"); + VBaseOffset - CharUnits::fromQuantity(4), "vtordisp"); Class->layout->Fields.push_back(VtorDisp); } ReadClassLayout(Class, VBase, VBaseOffset, - /*IncludeVirtualBases=*/false); + /*IncludeVirtualBases=*/false); } } } @@ -307,18 +326,18 @@ ConvertToClangTargetCXXABI(CppAbi abi) switch (abi) { - case CppAbi::Itanium: - return TargetCXXABI::GenericItanium; - case CppAbi::Microsoft: - return TargetCXXABI::Microsoft; - case CppAbi::ARM: - return TargetCXXABI::GenericARM; - case CppAbi::AArch64: - return TargetCXXABI::GenericAArch64; - case CppAbi::iOS: - return TargetCXXABI::iOS; - case CppAbi::AppleARM64: - return TargetCXXABI::AppleARM64; + case CppAbi::Itanium: + return TargetCXXABI::GenericItanium; + case CppAbi::Microsoft: + return TargetCXXABI::Microsoft; + case CppAbi::ARM: + return TargetCXXABI::GenericARM; + case CppAbi::AArch64: + return TargetCXXABI::GenericAArch64; + case CppAbi::iOS: + return TargetCXXABI::iOS; + case CppAbi::AppleARM64: + return TargetCXXABI::AppleARM64; } llvm_unreachable("Unsupported C++ ABI."); @@ -433,13 +452,14 @@ void Parser::Setup(bool Compile) if (opts->microsoftMode) { LangOpts.MSCompatibilityVersion = opts->toolSetToUse; - if (!LangOpts.MSCompatibilityVersion) LangOpts.MSCompatibilityVersion = 1700; + if (!LangOpts.MSCompatibilityVersion) + LangOpts.MSCompatibilityVersion = 1700; } #endif llvm::opt::InputArgList Args(0, 0); driver::Driver D("", TO->Triple, c->getDiagnostics()); - driver::ToolChain *TC = nullptr; + driver::ToolChain* TC = nullptr; llvm::Triple Target(TO->Triple); if (Target.getOS() == llvm::Triple::Linux) @@ -447,14 +467,16 @@ void Parser::Setup(bool Compile) else if (Target.getEnvironment() == llvm::Triple::EnvironmentType::MSVC) TC = new driver::toolchains::MSVCToolChain(D, Target, Args); - if (TC && !opts->noStandardIncludes) { + if (TC && !opts->noStandardIncludes) + { llvm::opt::ArgStringList Includes; TC->AddClangSystemIncludeArgs(Args, Includes); TC->AddClangCXXStdlibIncludeArgs(Args, Includes); - for (auto& Arg : Includes) { + for (auto& Arg : Includes) + { if (strlen(Arg) > 0 && Arg[0] != '-') HSOpts.AddPath(Arg, frontend::System, /*IsFramework=*/false, - /*IgnoreSysRoot=*/false); + /*IgnoreSysRoot=*/false); } } @@ -468,7 +490,7 @@ void Parser::Setup(bool Compile) Preprocessor& PP = c->getPreprocessor(); PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(), - PP.getLangOpts()); + PP.getLangOpts()); c->createASTContext(); NameMangler.reset(new ASTNameMangler(c->getASTContext())); @@ -526,7 +548,7 @@ std::string Parser::GetDeclMangledName(const clang::Decl* D) const static std::string GetDeclName(const clang::NamedDecl* D) { - if (const clang::IdentifierInfo *II = D->getIdentifier()) + if (const clang::IdentifierInfo* II = D->getIdentifier()) return II->getName().str(); return D->getNameAsString(); } @@ -558,10 +580,10 @@ static clang::Decl* GetPreviousDeclInContext(const clang::Decl* D) assertm(!D->getLexicalDeclContext()->decls_empty(), "No previous declaration.\n"); clang::Decl* prevDecl = nullptr; - for(auto it = D->getDeclContext()->decls_begin(); - it != D->getDeclContext()->decls_end(); it++) + for (auto it = D->getDeclContext()->decls_begin(); + it != D->getDeclContext()->decls_end(); it++) { - if((*it) == D) + if ((*it) == D) return prevDecl; prevDecl = (*it); } @@ -575,9 +597,9 @@ static bool IsExplicit(const clang::Decl* D) auto CTS = llvm::dyn_cast(D); return !CTS || - CTS->getSpecializationKind() == TSK_ExplicitSpecialization || - CTS->getSpecializationKind() == TSK_ExplicitInstantiationDeclaration || - CTS->getSpecializationKind() == TSK_ExplicitInstantiationDefinition; + CTS->getSpecializationKind() == TSK_ExplicitSpecialization || + CTS->getSpecializationKind() == TSK_ExplicitInstantiationDeclaration || + CTS->getSpecializationKind() == TSK_ExplicitInstantiationDefinition; } static clang::SourceLocation GetDeclStartLocation(clang::CompilerInstance* C, @@ -599,23 +621,23 @@ static clang::SourceLocation GetDeclStartLocation(clang::CompilerInstance* C, return lineBeginLoc; auto prevDecl = GetPreviousDeclInContext(D); - if(!prevDecl || !IsExplicit(prevDecl)) + if (!prevDecl || !IsExplicit(prevDecl)) return lineBeginLoc; auto prevDeclEndLoc = SM.getExpansionLoc(prevDecl->getEndLoc()); auto prevDeclEndOffset = SM.getFileOffset(prevDeclEndLoc); - if(SM.getFileID(prevDeclEndLoc) != SM.getFileID(startLoc)) + if (SM.getFileID(prevDeclEndLoc) != SM.getFileID(startLoc)) return lineBeginLoc; // TODO: Figure out why this asserts - //assert(prevDeclEndOffset <= startOffset); + // assert(prevDeclEndOffset <= startOffset); - if(prevDeclEndOffset < lineBeginOffset) + if (prevDeclEndOffset < lineBeginOffset) return lineBeginLoc; // Declarations don't share same macro expansion - if(SM.getExpansionLoc(prevDecl->getBeginLoc()) != startLoc) + if (SM.getExpansionLoc(prevDecl->getBeginLoc()) != startLoc) return prevDeclEndLoc; return GetDeclStartLocation(C, prevDecl); @@ -625,10 +647,10 @@ std::string Parser::GetTypeName(const clang::Type* Type) const { using namespace clang; - if(Type->isAnyPointerType() || Type->isReferenceType()) + if (Type->isAnyPointerType() || Type->isReferenceType()) Type = Type->getPointeeType().getTypePtr(); - if(Type->isEnumeralType() || Type->isRecordType()) + if (Type->isEnumeralType() || Type->isRecordType()) { const clang::TagType* Tag = Type->getAs(); return GetTagDeclName(Tag->getDecl()); @@ -667,16 +689,16 @@ QualifiedType Parser::GetQualifiedType(clang::QualType qual, const clang::TypeLo static AccessSpecifier ConvertToAccess(clang::AccessSpecifier AS) { - switch(AS) + switch (AS) { - case clang::AS_private: - return AccessSpecifier::Private; - case clang::AS_protected: - return AccessSpecifier::Protected; - case clang::AS_public: - return AccessSpecifier::Public; - case clang::AS_none: - return AccessSpecifier::Public; + case clang::AS_private: + return AccessSpecifier::Private; + case clang::AS_protected: + return AccessSpecifier::Protected; + case clang::AS_public: + return AccessSpecifier::Public; + case clang::AS_none: + return AccessSpecifier::Public; } llvm_unreachable("Unknown AccessSpecifier"); @@ -688,63 +710,63 @@ Parser::WalkVTableComponent(const clang::VTableComponent& Component) using namespace clang; AST::VTableComponent VTC; - switch(Component.getKind()) + switch (Component.getKind()) { - case clang::VTableComponent::CK_VCallOffset: - { - VTC.kind = VTableComponentKind::VBaseOffset; - VTC.offset = Component.getVCallOffset().getQuantity(); - break; - } - case clang::VTableComponent::CK_VBaseOffset: - { - VTC.kind = VTableComponentKind::VBaseOffset; - VTC.offset = Component.getVBaseOffset().getQuantity(); - break; - } - case clang::VTableComponent::CK_OffsetToTop: - { - VTC.kind = VTableComponentKind::OffsetToTop; - VTC.offset = Component.getOffsetToTop().getQuantity(); - break; - } - case clang::VTableComponent::CK_RTTI: - { - VTC.kind = VTableComponentKind::RTTI; - auto RD = Component.getRTTIDecl(); - VTC.declaration = WalkRecordCXX(RD); - break; - } - case clang::VTableComponent::CK_FunctionPointer: - { - VTC.kind = VTableComponentKind::FunctionPointer; - auto MD = Component.getFunctionDecl(); - VTC.declaration = WalkMethodCXX(MD); - break; - } - case clang::VTableComponent::CK_CompleteDtorPointer: - { - VTC.kind = VTableComponentKind::CompleteDtorPointer; - auto MD = Component.getDestructorDecl(); - VTC.declaration = WalkMethodCXX(MD); - break; - } - case clang::VTableComponent::CK_DeletingDtorPointer: - { - VTC.kind = VTableComponentKind::DeletingDtorPointer; - auto MD = Component.getDestructorDecl(); - VTC.declaration = WalkMethodCXX(MD); - break; - } - case clang::VTableComponent::CK_UnusedFunctionPointer: - { - VTC.kind = VTableComponentKind::UnusedFunctionPointer; - auto MD = Component.getUnusedFunctionDecl(); - VTC.declaration = WalkMethodCXX(MD); - break; - } - default: - llvm_unreachable("Unknown vtable component kind"); + case clang::VTableComponent::CK_VCallOffset: + { + VTC.kind = VTableComponentKind::VBaseOffset; + VTC.offset = Component.getVCallOffset().getQuantity(); + break; + } + case clang::VTableComponent::CK_VBaseOffset: + { + VTC.kind = VTableComponentKind::VBaseOffset; + VTC.offset = Component.getVBaseOffset().getQuantity(); + break; + } + case clang::VTableComponent::CK_OffsetToTop: + { + VTC.kind = VTableComponentKind::OffsetToTop; + VTC.offset = Component.getOffsetToTop().getQuantity(); + break; + } + case clang::VTableComponent::CK_RTTI: + { + VTC.kind = VTableComponentKind::RTTI; + auto RD = Component.getRTTIDecl(); + VTC.declaration = WalkRecordCXX(RD); + break; + } + case clang::VTableComponent::CK_FunctionPointer: + { + VTC.kind = VTableComponentKind::FunctionPointer; + auto MD = Component.getFunctionDecl(); + VTC.declaration = WalkMethodCXX(MD); + break; + } + case clang::VTableComponent::CK_CompleteDtorPointer: + { + VTC.kind = VTableComponentKind::CompleteDtorPointer; + auto MD = Component.getDestructorDecl(); + VTC.declaration = WalkMethodCXX(MD); + break; + } + case clang::VTableComponent::CK_DeletingDtorPointer: + { + VTC.kind = VTableComponentKind::DeletingDtorPointer; + auto MD = Component.getDestructorDecl(); + VTC.declaration = WalkMethodCXX(MD); + break; + } + case clang::VTableComponent::CK_UnusedFunctionPointer: + { + VTC.kind = VTableComponentKind::UnusedFunctionPointer; + auto MD = Component.getUnusedFunctionDecl(); + VTC.declaration = WalkMethodCXX(MD); + break; + } + default: + llvm_unreachable("Unknown vtable component kind"); } return VTC; @@ -777,39 +799,40 @@ void Parser::WalkVTable(const clang::CXXRecordDecl* RD, Class* C) C->layout->ABI = GetClassLayoutAbi(targetABI); auto& AST = c->getASTContext(); - switch(targetABI) - { - case TargetCXXABI::Microsoft: + switch (targetABI) { - MicrosoftVTableContext VTContext(AST); - - const auto& VFPtrs = VTContext.getVFPtrOffsets(RD); - for (const auto& VFPtrInfo : VFPtrs) + case TargetCXXABI::Microsoft: { - VFTableInfo Info; - Info.VFPtrOffset = VFPtrInfo->NonVirtualOffset.getQuantity(); - Info.VFPtrFullOffset = VFPtrInfo->FullOffsetInMDC.getQuantity(); + MicrosoftVTableContext VTContext(AST); + + const auto& VFPtrs = VTContext.getVFPtrOffsets(RD); + for (const auto& VFPtrInfo : VFPtrs) + { + VFTableInfo Info; + Info.VFPtrOffset = VFPtrInfo->NonVirtualOffset.getQuantity(); + Info.VFPtrFullOffset = VFPtrInfo->FullOffsetInMDC.getQuantity(); - auto& VTLayout = VTContext.getVFTableLayout(RD, VFPtrInfo->FullOffsetInMDC); - Info.layout = WalkVTableLayout(VTLayout); + auto& VTLayout = VTContext.getVFTableLayout(RD, VFPtrInfo->FullOffsetInMDC); + Info.layout = WalkVTableLayout(VTLayout); - C->layout->VFTables.push_back(Info); + C->layout->VFTables.push_back(Info); + } + break; } - break; - } - default: - { - ItaniumVTableContext VTContext(AST); + default: + { + ItaniumVTableContext VTContext(AST); - auto& VTLayout = VTContext.getVTableLayout(RD); - C->layout->layout = WalkVTableLayout(VTLayout); - break; - } + auto& VTLayout = VTContext.getVTableLayout(RD); + C->layout->layout = WalkVTableLayout(VTLayout); + break; + } } } void Parser::EnsureCompleteRecord(const clang::RecordDecl* Record, - DeclarationContext* NS, Class* RC) + DeclarationContext* NS, + Class* RC) { using namespace clang; @@ -852,14 +875,14 @@ Class* Parser::GetRecord(const clang::RecordDecl* Record, bool& Process) else { RC = NS->FindClass(opts->unityBuild ? Record : 0, Name, - isCompleteDefinition, /*Create=*/false); + isCompleteDefinition, /*Create=*/false); } if (RC) return RC; RC = NS->FindClass(opts->unityBuild ? Record : 0, Name, - isCompleteDefinition, /*Create=*/true); + isCompleteDefinition, /*Create=*/true); RC->isInjected = Record->isInjectedClassName(); HandleDeclaration(Record, RC); EnsureCompleteRecord(Record, NS, RC); @@ -914,7 +937,7 @@ Class* Parser::WalkRecordCXX(const clang::CXXRecordDecl* Record) static int I = 0; static bool IsRecordValid(const clang::RecordDecl* RC, - std::unordered_set& Visited) + std::unordered_set& Visited) { using namespace clang; @@ -946,14 +969,15 @@ static clang::CXXRecordDecl* GetCXXRecordDeclFromTemplateName(const clang::Templ { using namespace clang; - switch (Name.getKind()) { - case TemplateName::Template: - return dyn_cast(Name.getAsTemplateDecl()->getTemplatedDecl()); - case TemplateName::QualifiedTemplate: - return GetCXXRecordDeclFromTemplateName(Name.getAsQualifiedTemplateName()->getUnderlyingTemplate()); - default: - assertm(0, "Unknown template name kind?\n"); - return nullptr; + switch (Name.getKind()) + { + case TemplateName::Template: + return dyn_cast(Name.getAsTemplateDecl()->getTemplatedDecl()); + case TemplateName::QualifiedTemplate: + return GetCXXRecordDeclFromTemplateName(Name.getAsQualifiedTemplateName()->getUnderlyingTemplate()); + default: + assertm(0, "Unknown template name kind?\n"); + return nullptr; } } @@ -967,10 +991,12 @@ static clang::CXXRecordDecl* GetCXXRecordDeclFromBaseType(const clang::ASTContex return GetCXXRecordDeclFromTemplateName(TST->getTemplateName()); else if (auto Injected = Ty->getAs()) return Injected->getDecl(); - else if (auto TTPT = Ty->getAs()) { + else if (auto TTPT = Ty->getAs()) + { return nullptr; } - else if (auto DNT = Ty->getAs()) { + else if (auto DNT = Ty->getAs()) + { return nullptr; } @@ -1003,8 +1029,8 @@ bool Parser::HasLayout(const clang::RecordDecl* Record) bool Parser::IsSupported(const clang::NamedDecl* ND) { return !c->getSourceManager().isInSystemHeader(ND->getBeginLoc()) || - (llvm::isa(ND) && - supportedStdTypes.find(ND->getName().str()) != supportedStdTypes.end()); + (llvm::isa(ND) && + supportedStdTypes.find(ND->getName().str()) != supportedStdTypes.end()); } bool Parser::IsSupported(const clang::CXXMethodDecl* MD) @@ -1012,14 +1038,14 @@ bool Parser::IsSupported(const clang::CXXMethodDecl* MD) using namespace clang; return !c->getSourceManager().isInSystemHeader(MD->getBeginLoc()) || - (isa(MD) && MD->getNumParams() == 0) || - isa(MD) || - (MD->getDeclName().isIdentifier() && - ((MD->getName() == "data" && MD->getNumParams() == 0 && MD->isConst()) || - (MD->getName() == "assign" && MD->getNumParams() == 1 && - MD->parameters()[0]->getType()->isPointerType())) && - supportedStdTypes.find(MD->getParent()->getName().str()) != - supportedStdTypes.end()); + (isa(MD) && MD->getNumParams() == 0) || + isa(MD) || + (MD->getDeclName().isIdentifier() && + ((MD->getName() == "data" && MD->getNumParams() == 0 && MD->isConst()) || + (MD->getName() == "assign" && MD->getNumParams() == 1 && + MD->parameters()[0]->getType()->isPointerType())) && + supportedStdTypes.find(MD->getParent()->getName().str()) != + supportedStdTypes.end()); } static RecordArgABI GetRecordArgABI( @@ -1028,12 +1054,12 @@ static RecordArgABI GetRecordArgABI( using namespace clang::CodeGen; switch (argAbi) { - case CGCXXABI::RecordArgABI::RAA_DirectInMemory: - return RecordArgABI::DirectInMemory; - case CGCXXABI::RecordArgABI::RAA_Indirect: - return RecordArgABI::Indirect; - default: - return RecordArgABI::Default; + case CGCXXABI::RecordArgABI::RAA_DirectInMemory: + return RecordArgABI::DirectInMemory; + case CGCXXABI::RecordArgABI::RAA_Indirect: + return RecordArgABI::Indirect; + default: + return RecordArgABI::Default; } } @@ -1041,16 +1067,16 @@ static TagKind ConvertToTagKind(clang::TagTypeKind AS) { switch (AS) { - case clang::TagTypeKind::TTK_Struct: - return TagKind::Struct; - case clang::TagTypeKind::TTK_Interface: - return TagKind::Interface; - case clang::TagTypeKind::TTK_Union: - return TagKind::Union; - case clang::TagTypeKind::TTK_Class: - return TagKind::Class; - case clang::TagTypeKind::TTK_Enum: - return TagKind::Enum; + case clang::TagTypeKind::TTK_Struct: + return TagKind::Struct; + case clang::TagTypeKind::TTK_Interface: + return TagKind::Interface; + case clang::TagTypeKind::TTK_Union: + return TagKind::Union; + case clang::TagTypeKind::TTK_Class: + return TagKind::Class; + case clang::TagTypeKind::TTK_Enum: + return TagKind::Enum; } llvm_unreachable("Unknown TagKind"); @@ -1118,18 +1144,18 @@ void Parser::WalkRecord(const clang::RecordDecl* Record, Class* RC) { switch (D->getKind()) { - case Decl::CXXConstructor: - case Decl::CXXDestructor: - case Decl::CXXConversion: - case Decl::CXXMethod: - { - auto MD = cast(D); - if (IsSupported(MD)) - WalkDeclaration(MD); - break; - } - default: - break; + case Decl::CXXConstructor: + case Decl::CXXDestructor: + case Decl::CXXConversion: + case Decl::CXXMethod: + { + auto MD = cast(D); + if (IsSupported(MD)) + WalkDeclaration(MD); + break; + } + default: + break; } } } @@ -1144,50 +1170,51 @@ void Parser::WalkRecord(const clang::RecordDecl* Record, Class* RC) { switch (D->getKind()) { - case Decl::AccessSpec: - { - AccessSpecDecl* AS = cast(D); + case Decl::AccessSpec: + { + AccessSpecDecl* AS = cast(D); - auto AccessDecl = new AccessSpecifierDecl(); - HandleDeclaration(AS, AccessDecl); + auto AccessDecl = new AccessSpecifierDecl(); + HandleDeclaration(AS, AccessDecl); - AccessDecl->access = ConvertToAccess(AS->getAccess()); - AccessDecl->_namespace = RC; + AccessDecl->access = ConvertToAccess(AS->getAccess()); + AccessDecl->_namespace = RC; - RC->Specifiers.push_back(AccessDecl); - break; - } - case Decl::Field: // fields already handled - case Decl::IndirectField: // FIXME: Handle indirect fields - break; - case Decl::CXXRecord: - // Handle implicit records inside the class. - if (D->isImplicit()) - continue; - WalkDeclaration(D); - break; - case Decl::Friend: - { - FriendDecl* FD = cast(D); - auto decl = FD->getFriendDecl(); + RC->Specifiers.push_back(AccessDecl); + break; + } + case Decl::Field: // fields already handled + case Decl::IndirectField: // FIXME: Handle indirect fields + break; + case Decl::CXXRecord: + // Handle implicit records inside the class. + if (D->isImplicit()) + continue; + WalkDeclaration(D); + break; + case Decl::Friend: + { + FriendDecl* FD = cast(D); + auto decl = FD->getFriendDecl(); - // Skip every friend declaration that isn't a function declaration - if (decl && !isa(decl)) - continue; - WalkDeclaration(D); - break; - } - case Decl::FriendTemplate: - { - // In this case always skip the declaration since, unlike Decl::Friend handled above, - // it never is a declaration of a friend function or method - break; + // Skip every friend declaration that isn't a function declaration + if (decl && !isa(decl)) + continue; + WalkDeclaration(D); + break; + } + case Decl::FriendTemplate: + { + // In this case always skip the declaration since, unlike Decl::Friend handled above, + // it never is a declaration of a friend function or method + break; + } + default: + { + WalkDeclaration(D); + break; + } } - default: - { - WalkDeclaration(D); - break; - } } } } @@ -1202,7 +1229,7 @@ void Parser::WalkRecordCXX(const clang::CXXRecordDecl* Record, Class* RC) Sema.ForceDeclarationOfImplicitMembers(const_cast(Record)); WalkRecord(Record, RC); - + if (!Record->hasDefinition()) return; @@ -1215,7 +1242,7 @@ void Parser::WalkRecordCXX(const clang::CXXRecordDecl* Record, Class* RC) RC->hasNonTrivialDestructor = Record->hasNonTrivialDestructor(); bool hasLayout = HasLayout(Record) && - Record->getDeclName() != c->getSema().VAListTagName; + Record->getDeclName() != c->getSema().VAListTagName; // Get the record layout information. const ASTRecordLayout* Layout = 0; @@ -1241,8 +1268,7 @@ void Parser::WalkRecordCXX(const clang::CXXRecordDecl* Record, Class* RC) auto BaseDecl = GetCXXRecordDeclFromBaseType(c->getASTContext(), BS, BS.getType()); if (BaseDecl && Layout) { - auto Offset = BS.isVirtual() ? Layout->getVBaseClassOffset(BaseDecl) - : Layout->getBaseClassOffset(BaseDecl); + auto Offset = BS.isVirtual() ? Layout->getVBaseClassOffset(BaseDecl) : Layout->getBaseClassOffset(BaseDecl); Base->offset = Offset.getQuantity(); } @@ -1258,18 +1284,18 @@ void Parser::WalkRecordCXX(const clang::CXXRecordDecl* Record, Class* RC) static TemplateSpecializationKind WalkTemplateSpecializationKind(clang::TemplateSpecializationKind Kind) { - switch(Kind) + switch (Kind) { - case clang::TSK_Undeclared: - return TemplateSpecializationKind::Undeclared; - case clang::TSK_ImplicitInstantiation: - return TemplateSpecializationKind::ImplicitInstantiation; - case clang::TSK_ExplicitSpecialization: - return TemplateSpecializationKind::ExplicitSpecialization; - case clang::TSK_ExplicitInstantiationDeclaration: - return TemplateSpecializationKind::ExplicitInstantiationDeclaration; - case clang::TSK_ExplicitInstantiationDefinition: - return TemplateSpecializationKind::ExplicitInstantiationDefinition; + case clang::TSK_Undeclared: + return TemplateSpecializationKind::Undeclared; + case clang::TSK_ImplicitInstantiation: + return TemplateSpecializationKind::ImplicitInstantiation; + case clang::TSK_ExplicitSpecialization: + return TemplateSpecializationKind::ExplicitSpecialization; + case clang::TSK_ExplicitInstantiationDeclaration: + return TemplateSpecializationKind::ExplicitInstantiationDeclaration; + case clang::TSK_ExplicitInstantiationDefinition: + return TemplateSpecializationKind::ExplicitInstantiationDefinition; } llvm_unreachable("Unknown template specialization kind"); @@ -1287,7 +1313,8 @@ struct Diagnostic struct DiagnosticConsumer : public clang::DiagnosticConsumer { virtual void HandleDiagnostic(clang::DiagnosticsEngine::Level Level, - const clang::Diagnostic& Info) override { + const clang::Diagnostic& Info) override + { // Update the base type NumWarnings and NumErrors variables. if (Level == clang::DiagnosticsEngine::Warning) NumWarnings++; @@ -1346,7 +1373,7 @@ Parser::WalkClassTemplateSpecialization(const clang::ClassTemplateSpecialization } else { - TS->Arguments = WalkTemplateArgumentList(&TAL, (TemplateSpecializationTypeLoc*) 0); + TS->Arguments = WalkTemplateArgumentList(&TAL, (TemplateSpecializationTypeLoc*)0); } if (CTS->isCompleteDefinition()) @@ -1484,7 +1511,7 @@ TemplateTemplateParameter* Parser::WalkTemplateTemplateParameter(const clang::Te TP->isParameterPack = TTP->isParameterPack(); TP->isPackExpansion = TTP->isPackExpansion(); TP->isExpandedParameterPack = TTP->isExpandedParameterPack(); - + if (TTP->getTemplatedDecl()) { auto TD = WalkDeclaration(TTP->getTemplatedDecl()); @@ -1555,7 +1582,7 @@ UnresolvedUsingTypename* Parser::WalkUnresolvedUsingTypename(const clang::Unreso //-----------------------------------// -template +template std::vector Parser::WalkTemplateArgumentList(const clang::TemplateArgumentList* TAL, TypeLoc* TSTL) { using namespace clang; @@ -1569,7 +1596,7 @@ std::vector Parser::WalkTemplateArgumentList(const clang::Temp { const clang::TemplateArgument& TA = TAL->get(i); TemplateArgumentLoc TArgLoc; - TemplateArgumentLoc *ArgLoc = 0; + TemplateArgumentLoc* ArgLoc = 0; if (i < typeLocNumArgs && e == typeLocNumArgs) { TArgLoc = TSTL->getArgLoc(i); @@ -1585,8 +1612,8 @@ std::vector Parser::WalkTemplateArgumentList(const clang::Temp //-----------------------------------// std::vector -Parser::WalkTemplateArgumentList(const clang::TemplateArgumentList* TAL, - const clang::ASTTemplateArgumentListInfo* TALI) +Parser::WalkTemplateArgumentList(const clang::TemplateArgumentList* TAL, + const clang::ASTTemplateArgumentListInfo* TALI) { using namespace clang; @@ -1614,58 +1641,58 @@ Parser::WalkTemplateArgumentList(const clang::TemplateArgumentList* TAL, //-----------------------------------// TemplateArgument Parser::WalkTemplateArgument(const clang::TemplateArgument& TA, - clang::TemplateArgumentLoc* ArgLoc) + clang::TemplateArgumentLoc* ArgLoc) { auto Arg = TemplateArgument(); switch (TA.getKind()) { - case clang::TemplateArgument::Type: - { - Arg.kind = TemplateArgument::ArgumentKind::Type; - clang::TypeLoc ArgTL; - if (ArgLoc && ArgLoc->getTypeSourceInfo()) - { - ArgTL = ArgLoc->getTypeSourceInfo()->getTypeLoc(); - } - auto Type = TA.getAsType(); - CompleteIfSpecializationType(Type); - Arg.type = GetQualifiedType(Type, &ArgTL); - break; - } - case clang::TemplateArgument::Declaration: - Arg.kind = TemplateArgument::ArgumentKind::Declaration; - Arg.declaration = WalkDeclaration(TA.getAsDecl()); - break; - case clang::TemplateArgument::NullPtr: - Arg.kind = TemplateArgument::ArgumentKind::NullPtr; - break; - case clang::TemplateArgument::Integral: - Arg.kind = TemplateArgument::ArgumentKind::Integral; - //Arg.Type = WalkType(TA.getIntegralType(), 0); + case clang::TemplateArgument::Type: { + Arg.kind = TemplateArgument::ArgumentKind::Type; clang::TypeLoc ArgTL; if (ArgLoc && ArgLoc->getTypeSourceInfo()) + { ArgTL = ArgLoc->getTypeSourceInfo()->getTypeLoc(); - Arg.type = GetQualifiedType(TA.getIntegralType(), &ArgTL); - } - Arg.integral = TA.getAsIntegral().getLimitedValue(); - break; - case clang::TemplateArgument::Template: - Arg.kind = TemplateArgument::ArgumentKind::Template; - break; - case clang::TemplateArgument::TemplateExpansion: - Arg.kind = TemplateArgument::ArgumentKind::TemplateExpansion; - break; - case clang::TemplateArgument::Expression: - Arg.kind = TemplateArgument::ArgumentKind::Expression; - break; - case clang::TemplateArgument::Pack: - Arg.kind = TemplateArgument::ArgumentKind::Pack; - break; - case clang::TemplateArgument::Null: - default: - llvm_unreachable("Unknown TemplateArgument"); + } + auto Type = TA.getAsType(); + CompleteIfSpecializationType(Type); + Arg.type = GetQualifiedType(Type, &ArgTL); + break; + } + case clang::TemplateArgument::Declaration: + Arg.kind = TemplateArgument::ArgumentKind::Declaration; + Arg.declaration = WalkDeclaration(TA.getAsDecl()); + break; + case clang::TemplateArgument::NullPtr: + Arg.kind = TemplateArgument::ArgumentKind::NullPtr; + break; + case clang::TemplateArgument::Integral: + Arg.kind = TemplateArgument::ArgumentKind::Integral; + // Arg.Type = WalkType(TA.getIntegralType(), 0); + { + clang::TypeLoc ArgTL; + if (ArgLoc && ArgLoc->getTypeSourceInfo()) + ArgTL = ArgLoc->getTypeSourceInfo()->getTypeLoc(); + Arg.type = GetQualifiedType(TA.getIntegralType(), &ArgTL); + } + Arg.integral = TA.getAsIntegral().getLimitedValue(); + break; + case clang::TemplateArgument::Template: + Arg.kind = TemplateArgument::ArgumentKind::Template; + break; + case clang::TemplateArgument::TemplateExpansion: + Arg.kind = TemplateArgument::ArgumentKind::TemplateExpansion; + break; + case clang::TemplateArgument::Expression: + Arg.kind = TemplateArgument::ArgumentKind::Expression; + break; + case clang::TemplateArgument::Pack: + Arg.kind = TemplateArgument::ArgumentKind::Pack; + break; + case clang::TemplateArgument::Null: + default: + llvm_unreachable("Unknown TemplateArgument"); } return Arg; @@ -1781,7 +1808,7 @@ Parser::WalkFunctionTemplateSpec(clang::FunctionTemplateSpecializationInfo* FTSI } } FTS->Arguments = WalkTemplateArgumentList(TSA, - (const ASTTemplateArgumentListInfo*) 0); + (const ASTTemplateArgumentListInfo*)0); } return FTS; @@ -1845,7 +1872,7 @@ Parser::WalkVarTemplateSpecialization(const clang::VarTemplateSpecializationDecl } else { - TS->Arguments = WalkTemplateArgumentList(&TAL, (TemplateSpecializationTypeLoc*) 0); + TS->Arguments = WalkTemplateArgumentList(&TAL, (TemplateSpecializationTypeLoc*)0); } WalkVariable(VTS, TS); @@ -1894,25 +1921,25 @@ static CXXMethodKind GetMethodKindFromDecl(clang::DeclarationName Name) { using namespace clang; - switch(Name.getNameKind()) - { - case DeclarationName::Identifier: - case DeclarationName::CXXDeductionGuideName: - case DeclarationName::ObjCZeroArgSelector: - case DeclarationName::ObjCOneArgSelector: - case DeclarationName::ObjCMultiArgSelector: - return CXXMethodKind::Normal; - case DeclarationName::CXXConstructorName: - return CXXMethodKind::Constructor; - case DeclarationName::CXXDestructorName: - return CXXMethodKind::Destructor; - case DeclarationName::CXXConversionFunctionName: - return CXXMethodKind::Conversion; - case DeclarationName::CXXOperatorName: - case DeclarationName::CXXLiteralOperatorName: - return CXXMethodKind::Operator; - case DeclarationName::CXXUsingDirective: - return CXXMethodKind::UsingDirective; + switch (Name.getNameKind()) + { + case DeclarationName::Identifier: + case DeclarationName::CXXDeductionGuideName: + case DeclarationName::ObjCZeroArgSelector: + case DeclarationName::ObjCOneArgSelector: + case DeclarationName::ObjCMultiArgSelector: + return CXXMethodKind::Normal; + case DeclarationName::CXXConstructorName: + return CXXMethodKind::Constructor; + case DeclarationName::CXXDestructorName: + return CXXMethodKind::Destructor; + case DeclarationName::CXXConversionFunctionName: + return CXXMethodKind::Conversion; + case DeclarationName::CXXOperatorName: + case DeclarationName::CXXLiteralOperatorName: + return CXXMethodKind::Operator; + case DeclarationName::CXXUsingDirective: + return CXXMethodKind::UsingDirective; } return CXXMethodKind::Normal; } @@ -1924,16 +1951,16 @@ static CXXOperatorKind GetOperatorKindFromDecl(clang::DeclarationName Name) if (Name.getNameKind() != DeclarationName::CXXOperatorName) return CXXOperatorKind::None; - switch(Name.getCXXOverloadedOperator()) + switch (Name.getCXXOverloadedOperator()) { - case OO_None: - return CXXOperatorKind::None; - case NUM_OVERLOADED_OPERATORS: - break; + case OO_None: + return CXXOperatorKind::None; + case NUM_OVERLOADED_OPERATORS: + break; - #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ +#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \ case OO_##Name: return CXXOperatorKind::Name; - #include "clang/Basic/OperatorKinds.def" +#include "clang/Basic/OperatorKinds.def" } llvm_unreachable("Unknown OverloadedOperator"); @@ -1994,15 +2021,15 @@ Method* Parser::WalkMethodCXX(const clang::CXXMethodDecl* MD) } switch (MD->getRefQualifier()) { - case RQ_None: - Method->refQualifier = AST::RefQualifierKind::None; - break; - case RQ_LValue: - Method->refQualifier = AST::RefQualifierKind::LValue; - break; - case RQ_RValue: - Method->refQualifier = AST::RefQualifierKind::RValue; - break; + case RQ_None: + Method->refQualifier = AST::RefQualifierKind::None; + break; + case RQ_LValue: + Method->refQualifier = AST::RefQualifierKind::LValue; + break; + case RQ_RValue: + Method->refQualifier = AST::RefQualifierKind::RValue; + break; } Class->Methods.push_back(Method); @@ -2038,7 +2065,10 @@ Field* Parser::WalkFieldCXX(const clang::FieldDecl* FD, Class* Class) const auto& USR = GetDeclUSR(FD); auto FoundField = std::find_if(Class->Fields.begin(), Class->Fields.end(), - [&](Field* Field) { return Field->USR == USR; }); + [&](Field* Field) + { + return Field->USR == USR; + }); if (FoundField != Class->Fields.end()) return *FoundField; @@ -2055,7 +2085,7 @@ Field* Parser::WalkFieldCXX(const clang::FieldDecl* FD, Class* Class) F->isBitField = FD->isBitField(); if (F->isBitField && !F->isDependent && !FD->getBitWidth()->isInstantiationDependent()) F->bitWidth = FD->getBitWidthValue(c->getASTContext()); - + if (auto alignedAttr = FD->getAttr()) F->alignAs = GetAlignAs(alignedAttr); @@ -2067,7 +2097,7 @@ Field* Parser::WalkFieldCXX(const clang::FieldDecl* FD, Class* Class) //-----------------------------------// TranslationUnit* Parser::GetTranslationUnit(clang::SourceLocation Loc, - SourceLocationKind *Kind) + SourceLocationKind* Kind) { using namespace clang; @@ -2079,21 +2109,21 @@ TranslationUnit* Parser::GetTranslationUnit(clang::SourceLocation Loc, StringRef File; auto LocKind = GetLocationKind(Loc); - switch(LocKind) - { - case SourceLocationKind::Invalid: - File = ""; - break; - case SourceLocationKind::Builtin: - File = ""; - break; - case SourceLocationKind::CommandLine: - File = ""; - break; - default: - File = SM.getFilename(Loc); - assertm(!File.empty(), "Expected to find a valid file!\n"); - break; + switch (LocKind) + { + case SourceLocationKind::Invalid: + File = ""; + break; + case SourceLocationKind::Builtin: + File = ""; + break; + case SourceLocationKind::CommandLine: + File = ""; + break; + default: + File = SM.getFilename(Loc); + assertm(!File.empty(), "Expected to find a valid file!\n"); + break; } if (Kind) @@ -2101,7 +2131,7 @@ TranslationUnit* Parser::GetTranslationUnit(clang::SourceLocation Loc, auto Unit = opts->ASTContext->FindOrCreateModule(File.str()); - Unit->originalPtr = (void*) Unit; + Unit->originalPtr = (void*)Unit; assertm(Unit->originalPtr != nullptr, "Module not found?\n"); if (LocKind != SourceLocationKind::Invalid) @@ -2123,7 +2153,7 @@ TranslationUnit* Parser::GetTranslationUnit(const clang::Decl* D) } DeclarationContext* Parser::GetNamespace(const clang::Decl* D, - const clang::DeclContext *Ctx) + const clang::DeclContext* Ctx) { using namespace clang; @@ -2141,10 +2171,10 @@ DeclarationContext* Parser::GetNamespace(const clang::Decl* D, // Else we need to do a more expensive check to get all the namespaces, // and then perform a reverse iteration to get the namespaces in order. - typedef SmallVector ContextsTy; + typedef SmallVector ContextsTy; ContextsTy Contexts; - for(; Context != nullptr; Context = Context->getParent()) + for (; Context != nullptr; Context = Context->getParent()) Contexts.push_back(Context); assertm(Contexts.back()->isTranslationUnit(), "Last element does not have translation unit!\n"); @@ -2163,43 +2193,44 @@ DeclarationContext* Parser::GetNamespace(const clang::Decl* D, continue; } - switch(Ctx->getDeclKind()) - { - case Decl::Namespace: + switch (Ctx->getDeclKind()) { - auto ND = cast(Ctx); - if (ND->isAnonymousNamespace()) - break; + case Decl::Namespace: + { + auto ND = cast(Ctx); + if (ND->isAnonymousNamespace()) + break; - auto Name = ND->getName(); - DC = DC->FindCreateNamespace(Name.str()); - ((Namespace*)DC)->isAnonymous = ND->isAnonymousNamespace(); - ((Namespace*)DC)->isInline = ND->isInline(); - HandleDeclaration(ND, DC); - break; - } - case Decl::LinkageSpec: - { - const LinkageSpecDecl* LD = cast(Ctx); - continue; - } - case Decl::CXXRecord: - { - auto RD = cast(Ctx); - DC = WalkRecordCXX(RD); - break; - } - case Decl::CXXDeductionGuide: - { - continue; + auto Name = ND->getName(); + DC = DC->FindCreateNamespace(Name.str()); + ((Namespace*)DC)->isAnonymous = ND->isAnonymousNamespace(); + ((Namespace*)DC)->isInline = ND->isInline(); + HandleDeclaration(ND, DC); + break; + } + case Decl::LinkageSpec: + { + const LinkageSpecDecl* LD = cast(Ctx); + continue; + } + case Decl::CXXRecord: + { + auto RD = cast(Ctx); + DC = WalkRecordCXX(RD); + break; + } + case Decl::CXXDeductionGuide: + { + continue; + } + default: + { + auto D = cast(Ctx); + auto Decl = WalkDeclaration(D); + DC = static_cast(Decl); + break; + } } - default: - { - auto D = cast(Ctx); - auto Decl = WalkDeclaration(D); - DC = static_cast(Decl); - break; - } } walkedNamespaces[Ctx] = DC; } @@ -2208,7 +2239,7 @@ DeclarationContext* Parser::GetNamespace(const clang::Decl* D, return DC; } -DeclarationContext* Parser::GetNamespace(const clang::Decl *D) +DeclarationContext* Parser::GetNamespace(const clang::Decl* D) { return GetNamespace(D, D->getDeclContext()); } @@ -2217,47 +2248,47 @@ static PrimitiveType WalkBuiltinType(const clang::BuiltinType* Builtin) { assertm(Builtin, "Expected a builtin type!\n"); - switch(Builtin->getKind()) + switch (Builtin->getKind()) { - case clang::BuiltinType::Void: return PrimitiveType::Void; - case clang::BuiltinType::Bool: return PrimitiveType::Bool; + case clang::BuiltinType::Void: return PrimitiveType::Void; + case clang::BuiltinType::Bool: return PrimitiveType::Bool; + + case clang::BuiltinType::SChar: return PrimitiveType::SChar; + case clang::BuiltinType::Char_S: return PrimitiveType::Char; - case clang::BuiltinType::SChar: return PrimitiveType::SChar; - case clang::BuiltinType::Char_S: return PrimitiveType::Char; - - case clang::BuiltinType::UChar: - case clang::BuiltinType::Char_U: return PrimitiveType::UChar; + case clang::BuiltinType::UChar: + case clang::BuiltinType::Char_U: return PrimitiveType::UChar; - case clang::BuiltinType::WChar_S: - case clang::BuiltinType::WChar_U: return PrimitiveType::WideChar; + case clang::BuiltinType::WChar_S: + case clang::BuiltinType::WChar_U: return PrimitiveType::WideChar; - case clang::BuiltinType::Char16: return PrimitiveType::Char16; - case clang::BuiltinType::Char32: return PrimitiveType::Char32; + case clang::BuiltinType::Char16: return PrimitiveType::Char16; + case clang::BuiltinType::Char32: return PrimitiveType::Char32; - case clang::BuiltinType::Short: return PrimitiveType::Short; - case clang::BuiltinType::UShort: return PrimitiveType::UShort; + case clang::BuiltinType::Short: return PrimitiveType::Short; + case clang::BuiltinType::UShort: return PrimitiveType::UShort; - case clang::BuiltinType::Int: return PrimitiveType::Int; - case clang::BuiltinType::UInt: return PrimitiveType::UInt; + case clang::BuiltinType::Int: return PrimitiveType::Int; + case clang::BuiltinType::UInt: return PrimitiveType::UInt; - case clang::BuiltinType::Long: return PrimitiveType::Long; - case clang::BuiltinType::ULong: return PrimitiveType::ULong; - - case clang::BuiltinType::LongLong: return PrimitiveType::LongLong; - case clang::BuiltinType::ULongLong: return PrimitiveType::ULongLong; + case clang::BuiltinType::Long: return PrimitiveType::Long; + case clang::BuiltinType::ULong: return PrimitiveType::ULong; - case clang::BuiltinType::Int128: return PrimitiveType::Int128; - case clang::BuiltinType::UInt128: return PrimitiveType::UInt128; + case clang::BuiltinType::LongLong: return PrimitiveType::LongLong; + case clang::BuiltinType::ULongLong: return PrimitiveType::ULongLong; - case clang::BuiltinType::Half: return PrimitiveType::Half; - case clang::BuiltinType::Float: return PrimitiveType::Float; - case clang::BuiltinType::Double: return PrimitiveType::Double; - case clang::BuiltinType::LongDouble: return PrimitiveType::LongDouble; - case clang::BuiltinType::Float128: return PrimitiveType::Float128; + case clang::BuiltinType::Int128: return PrimitiveType::Int128; + case clang::BuiltinType::UInt128: return PrimitiveType::UInt128; - case clang::BuiltinType::NullPtr: return PrimitiveType::Null; + case clang::BuiltinType::Half: return PrimitiveType::Half; + case clang::BuiltinType::Float: return PrimitiveType::Float; + case clang::BuiltinType::Double: return PrimitiveType::Double; + case clang::BuiltinType::LongDouble: return PrimitiveType::LongDouble; + case clang::BuiltinType::Float128: return PrimitiveType::Float128; - default: break; + case clang::BuiltinType::NullPtr: return PrimitiveType::Null; + + default: break; } return PrimitiveType::Null; @@ -2302,12 +2333,12 @@ static FriendKind ConvertFriendKind(clang::Decl::FriendObjectKind FK) switch (FK) { - case Decl::FriendObjectKind::FOK_Declared: - return FriendKind::Declared; - case Decl::FriendObjectKind::FOK_Undeclared: - return FriendKind::Undeclared; - default: - return FriendKind::None; + case Decl::FriendObjectKind::FOK_Declared: + return FriendKind::Declared; + case Decl::FriendObjectKind::FOK_Undeclared: + return FriendKind::Undeclared; + default: + return FriendKind::None; } } @@ -2315,18 +2346,18 @@ static CallingConvention ConvertCallConv(clang::CallingConv CC) { using namespace clang; - switch(CC) + switch (CC) { - case CC_C: - return CallingConvention::C; - case CC_X86StdCall: - return CallingConvention::StdCall; - case CC_X86FastCall: - return CallingConvention::FastCall; - case CC_X86ThisCall: - return CallingConvention::ThisCall; - default: - return CallingConvention::Unknown; + case CC_C: + return CallingConvention::C; + case CC_X86StdCall: + return CallingConvention::StdCall; + case CC_X86FastCall: + return CallingConvention::FastCall; + case CC_X86ThisCall: + return CallingConvention::ThisCall; + default: + return CallingConvention::Unknown; } } @@ -2336,28 +2367,28 @@ static ExceptionSpecType ConvertExceptionType(clang::ExceptionSpecificationType switch (EST) { - case EST_BasicNoexcept: - return ExceptionSpecType::BasicNoexcept; - case EST_DependentNoexcept: - return ExceptionSpecType::DependentNoexcept; - case EST_NoexceptFalse: - return ExceptionSpecType::NoexceptFalse; - case EST_NoexceptTrue: - return ExceptionSpecType::NoexceptTrue; - case EST_Dynamic: - return ExceptionSpecType::Dynamic; - case EST_DynamicNone: - return ExceptionSpecType::DynamicNone; - case EST_MSAny: - return ExceptionSpecType::MSAny; - case EST_Unevaluated: - return ExceptionSpecType::Unevaluated; - case EST_Uninstantiated: - return ExceptionSpecType::Uninstantiated; - case EST_Unparsed: - return ExceptionSpecType::Unparsed; - default: - return ExceptionSpecType::None; + case EST_BasicNoexcept: + return ExceptionSpecType::BasicNoexcept; + case EST_DependentNoexcept: + return ExceptionSpecType::DependentNoexcept; + case EST_NoexceptFalse: + return ExceptionSpecType::NoexceptFalse; + case EST_NoexceptTrue: + return ExceptionSpecType::NoexceptTrue; + case EST_Dynamic: + return ExceptionSpecType::Dynamic; + case EST_DynamicNone: + return ExceptionSpecType::DynamicNone; + case EST_MSAny: + return ExceptionSpecType::MSAny; + case EST_Unevaluated: + return ExceptionSpecType::Unevaluated; + case EST_Uninstantiated: + return ExceptionSpecType::Uninstantiated; + case EST_Unparsed: + return ExceptionSpecType::Unparsed; + default: + return ExceptionSpecType::None; } } @@ -2365,28 +2396,28 @@ static ParserIntType ConvertIntType(clang::TargetInfo::IntType IT) { switch (IT) { - case clang::TargetInfo::IntType::NoInt: - return ParserIntType::NoInt; - case clang::TargetInfo::IntType::SignedChar: - return ParserIntType::SignedChar; - case clang::TargetInfo::IntType::UnsignedChar: - return ParserIntType::UnsignedChar; - case clang::TargetInfo::IntType::SignedShort: - return ParserIntType::SignedShort; - case clang::TargetInfo::IntType::UnsignedShort: - return ParserIntType::UnsignedShort; - case clang::TargetInfo::IntType::SignedInt: - return ParserIntType::SignedInt; - case clang::TargetInfo::IntType::UnsignedInt: - return ParserIntType::UnsignedInt; - case clang::TargetInfo::IntType::SignedLong: - return ParserIntType::SignedLong; - case clang::TargetInfo::IntType::UnsignedLong: - return ParserIntType::UnsignedLong; - case clang::TargetInfo::IntType::SignedLongLong: - return ParserIntType::SignedLongLong; - case clang::TargetInfo::IntType::UnsignedLongLong: - return ParserIntType::UnsignedLongLong; + case clang::TargetInfo::IntType::NoInt: + return ParserIntType::NoInt; + case clang::TargetInfo::IntType::SignedChar: + return ParserIntType::SignedChar; + case clang::TargetInfo::IntType::UnsignedChar: + return ParserIntType::UnsignedChar; + case clang::TargetInfo::IntType::SignedShort: + return ParserIntType::SignedShort; + case clang::TargetInfo::IntType::UnsignedShort: + return ParserIntType::UnsignedShort; + case clang::TargetInfo::IntType::SignedInt: + return ParserIntType::SignedInt; + case clang::TargetInfo::IntType::UnsignedInt: + return ParserIntType::UnsignedInt; + case clang::TargetInfo::IntType::SignedLong: + return ParserIntType::SignedLong; + case clang::TargetInfo::IntType::UnsignedLong: + return ParserIntType::UnsignedLong; + case clang::TargetInfo::IntType::SignedLongLong: + return ParserIntType::SignedLongLong; + case clang::TargetInfo::IntType::UnsignedLongLong: + return ParserIntType::UnsignedLongLong; } llvm_unreachable("Unknown parser integer type"); @@ -2404,8 +2435,7 @@ static const clang::Type* GetFinalType(const clang::Type* Ty) } } -Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL, - bool DesugarType) +Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL, bool DesugarType) { using namespace clang; @@ -2427,645 +2457,662 @@ Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL, AST::Type* Ty = nullptr; assertm(Type, "Expected a valid type!\n"); - switch(Type->getTypeClass()) - { - case clang::Type::Atomic: + switch (Type->getTypeClass()) { - auto Atomic = Type->getAs(); - assertm(Atomic, "Expected an atomic type!\n"); + case clang::Type::Atomic: + { + auto Atomic = Type->getAs(); + assertm(Atomic, "Expected an atomic type!\n"); - TypeLoc Next; - if (LocValid) Next = TL->getNextTypeLoc(); + TypeLoc Next; + if (LocValid) + Next = TL->getNextTypeLoc(); - Ty = WalkType(Atomic->getValueType(), &Next); - break; - } - case clang::Type::Attributed: - { - auto Attributed = Type->getAs(); - assertm(Attributed, "Expected an attributed type!\n"); + Ty = WalkType(Atomic->getValueType(), &Next); + break; + } + case clang::Type::Attributed: + { + auto Attributed = Type->getAs(); + assertm(Attributed, "Expected an attributed type!\n"); - TypeLoc Next; - if (LocValid) Next = TL->getNextTypeLoc(); + TypeLoc Next; + if (LocValid) + Next = TL->getNextTypeLoc(); - auto AT = new AST::AttributedType(); + auto AT = new AST::AttributedType(); - auto Modified = Attributed->getModifiedType(); - AT->modified = GetQualifiedType(Modified, &Next); + auto Modified = Attributed->getModifiedType(); + AT->modified = GetQualifiedType(Modified, &Next); - auto Equivalent = Attributed->getEquivalentType(); - AT->equivalent = GetQualifiedType(Equivalent, &Next); + auto Equivalent = Attributed->getEquivalentType(); + AT->equivalent = GetQualifiedType(Equivalent, &Next); - Ty = AT; - break; - } - case clang::Type::Builtin: - { - auto Builtin = Type->getAs(); - assertm(Builtin, "Expected a builtin type!\n"); - - auto BT = new AST::BuiltinType(); - BT->type = WalkBuiltinType(Builtin); - - Ty = BT; - break; - } - case clang::Type::Enum: - { - auto ET = Type->getAs(); - EnumDecl* ED = ET->getDecl(); + Ty = AT; + break; + } + case clang::Type::Builtin: + { + auto Builtin = Type->getAs(); + assertm(Builtin, "Expected a builtin type!\n"); - auto TT = new AST::TagType(); - TT->declaration = TT->declaration = WalkDeclaration(ED); + auto BT = new AST::BuiltinType(); + BT->type = WalkBuiltinType(Builtin); - Ty = TT; - break; - } - case clang::Type::Pointer: - { - auto Pointer = Type->getAs(); - - auto P = new AST::PointerType(); - P->modifier = AST::PointerType::TypeModifier::Pointer; + Ty = BT; + break; + } + case clang::Type::Enum: + { + auto ET = Type->getAs(); + EnumDecl* ED = ET->getDecl(); - TypeLoc Next; - if (LocValid) Next = TL->getNextTypeLoc(); + auto TT = new AST::TagType(); + TT->declaration = TT->declaration = WalkDeclaration(ED); - auto Pointee = Pointer->getPointeeType(); - P->qualifiedPointee = GetQualifiedType(Pointee, &Next); + Ty = TT; + break; + } + case clang::Type::Pointer: + { + auto Pointer = Type->getAs(); - Ty = P; - break; - } - case clang::Type::Typedef: - { - auto TT = Type->getAs(); - auto TD = TT->getDecl(); + auto P = new AST::PointerType(); + P->modifier = AST::PointerType::TypeModifier::Pointer; - auto TTL = TD->getTypeSourceInfo()->getTypeLoc(); - auto TDD = static_cast(WalkDeclaration(TD)); + TypeLoc Next; + if (LocValid) + Next = TL->getNextTypeLoc(); - auto Type = new AST::TypedefType(); - Type->declaration = TDD; + auto Pointee = Pointer->getPointeeType(); + P->qualifiedPointee = GetQualifiedType(Pointee, &Next); - Ty = Type; - break; - } - case clang::Type::Decayed: - { - auto DT = Type->getAs(); + Ty = P; + break; + } + case clang::Type::Typedef: + { + auto TT = Type->getAs(); + auto TD = TT->getDecl(); - TypeLoc Next; - if (LocValid) Next = TL->getNextTypeLoc(); + auto TTL = TD->getTypeSourceInfo()->getTypeLoc(); + auto TDD = static_cast(WalkDeclaration(TD)); - auto Type = new AST::DecayedType(); - Type->decayed = GetQualifiedType(DT->getDecayedType(), &Next); - Type->original = GetQualifiedType(DT->getOriginalType(), &Next); - Type->pointee = GetQualifiedType(DT->getPointeeType(), &Next); + auto Type = new AST::TypedefType(); + Type->declaration = TDD; - Ty = Type; - break; - } - case clang::Type::Elaborated: - { - auto ET = Type->getAs(); + Ty = Type; + break; + } + case clang::Type::Decayed: + { + auto DT = Type->getAs(); - TypeLoc Next; - if (LocValid) Next = TL->getNextTypeLoc(); + TypeLoc Next; + if (LocValid) + Next = TL->getNextTypeLoc(); - Ty = WalkType(ET->getNamedType(), &Next); - break; - } - case clang::Type::Record: - { - auto RT = Type->getAs(); - RecordDecl* RD = RT->getDecl(); + auto Type = new AST::DecayedType(); + Type->decayed = GetQualifiedType(DT->getDecayedType(), &Next); + Type->original = GetQualifiedType(DT->getOriginalType(), &Next); + Type->pointee = GetQualifiedType(DT->getPointeeType(), &Next); - auto TT = new AST::TagType(); - TT->declaration = WalkDeclaration(RD); + Ty = Type; + break; + } + case clang::Type::Elaborated: + { + auto ET = Type->getAs(); - Ty = TT; - break; - } - case clang::Type::Paren: - { - auto PT = Type->getAs(); + TypeLoc Next; + if (LocValid) + Next = TL->getNextTypeLoc(); - TypeLoc Next; - if (LocValid) Next = TL->getNextTypeLoc(); + Ty = WalkType(ET->getNamedType(), &Next); + break; + } + case clang::Type::Record: + { + auto RT = Type->getAs(); + RecordDecl* RD = RT->getDecl(); - Ty = WalkType(PT->getInnerType(), &Next); - break; - } - case clang::Type::ConstantArray: - { - auto AT = AST.getAsConstantArrayType(QualType); + auto TT = new AST::TagType(); + TT->declaration = WalkDeclaration(RD); - TypeLoc Next; - if (LocValid) Next = TL->getNextTypeLoc(); + Ty = TT; + break; + } + case clang::Type::Paren: + { + auto PT = Type->getAs(); - auto A = new AST::ArrayType(); - auto ElemTy = AT->getElementType(); - A->qualifiedType = GetQualifiedType(ElemTy, &Next); - A->sizeType = AST::ArrayType::ArraySize::Constant; - A->size = AST.getConstantArrayElementCount(AT); + TypeLoc Next; + if (LocValid) + Next = TL->getNextTypeLoc(); - if (!ElemTy->isDependentType() && !opts->skipLayoutInfo) - A->elementSize = (long)AST.getTypeSize(ElemTy); + Ty = WalkType(PT->getInnerType(), &Next); + break; + } + case clang::Type::ConstantArray: + { + auto AT = AST.getAsConstantArrayType(QualType); - Ty = A; - break; - } - case clang::Type::IncompleteArray: - { - auto AT = AST.getAsIncompleteArrayType(QualType); + TypeLoc Next; + if (LocValid) + Next = TL->getNextTypeLoc(); - TypeLoc Next; - if (LocValid) Next = TL->getNextTypeLoc(); + auto A = new AST::ArrayType(); + auto ElemTy = AT->getElementType(); + A->qualifiedType = GetQualifiedType(ElemTy, &Next); + A->sizeType = AST::ArrayType::ArraySize::Constant; + A->size = AST.getConstantArrayElementCount(AT); - auto A = new AST::ArrayType(); - A->qualifiedType = GetQualifiedType(AT->getElementType(), &Next); - A->sizeType = AST::ArrayType::ArraySize::Incomplete; + if (!ElemTy->isDependentType() && !opts->skipLayoutInfo) + A->elementSize = (long)AST.getTypeSize(ElemTy); - Ty = A; - break; - } - case clang::Type::DependentSizedArray: - { - auto AT = AST.getAsDependentSizedArrayType(QualType); - - TypeLoc Next; - if (LocValid) Next = TL->getNextTypeLoc(); - - auto A = new AST::ArrayType(); - A->qualifiedType = GetQualifiedType(AT->getElementType(), &Next); - A->sizeType = AST::ArrayType::ArraySize::Dependent; - //A->Size = AT->getSizeExpr(); - - Ty = A; - break; - } - case clang::Type::UnresolvedUsing: - { - auto UT = Type->getAs(); - - TypeLoc Next; - if (LocValid) Next = TL->getNextTypeLoc(); + Ty = A; + break; + } + case clang::Type::IncompleteArray: + { + auto AT = AST.getAsIncompleteArrayType(QualType); - auto U = new AST::UnresolvedUsingType(); - U->declaration = static_cast( - WalkDeclaration(UT->getDecl())); + TypeLoc Next; + if (LocValid) + Next = TL->getNextTypeLoc(); - Ty = U; - break; - } - case clang::Type::FunctionNoProto: - { - auto FP = Type->getAs(); + auto A = new AST::ArrayType(); + A->qualifiedType = GetQualifiedType(AT->getElementType(), &Next); + A->sizeType = AST::ArrayType::ArraySize::Incomplete; - FunctionNoProtoTypeLoc FTL; - TypeLoc RL; - TypeLoc Next; - if (LocValid) + Ty = A; + break; + } + case clang::Type::DependentSizedArray: { - while (!TL->isNull() && TL->getTypeLocClass() != TypeLoc::FunctionNoProto) - { + auto AT = AST.getAsDependentSizedArrayType(QualType); + + TypeLoc Next; + if (LocValid) Next = TL->getNextTypeLoc(); - TL = &Next; - } - if (!TL->isNull() && TL->getTypeLocClass() == TypeLoc::FunctionNoProto) - { - FTL = TL->getAs(); - RL = FTL.getReturnLoc(); - } + auto A = new AST::ArrayType(); + A->qualifiedType = GetQualifiedType(AT->getElementType(), &Next); + A->sizeType = AST::ArrayType::ArraySize::Dependent; + // A->Size = AT->getSizeExpr(); + + Ty = A; + break; } + case clang::Type::UnresolvedUsing: + { + auto UT = Type->getAs(); - auto F = new AST::FunctionType(); - F->returnType = GetQualifiedType(FP->getReturnType(), &RL); - F->callingConvention = ConvertCallConv(FP->getCallConv()); + TypeLoc Next; + if (LocValid) + Next = TL->getNextTypeLoc(); - Ty = F; - break; - } - case clang::Type::FunctionProto: - { - auto FP = Type->getAs(); + auto U = new AST::UnresolvedUsingType(); + U->declaration = static_cast( + WalkDeclaration(UT->getDecl())); - FunctionProtoTypeLoc FTL; - TypeLoc RL; - TypeLoc Next; - clang::SourceLocation ParamStartLoc; - if (LocValid) + Ty = U; + break; + } + case clang::Type::FunctionNoProto: { - while (!TL->isNull() && TL->getTypeLocClass() != TypeLoc::FunctionProto) - { - Next = TL->getNextTypeLoc(); - TL = &Next; - } + auto FP = Type->getAs(); - if (!TL->isNull() && TL->getTypeLocClass() == TypeLoc::FunctionProto) + FunctionNoProtoTypeLoc FTL; + TypeLoc RL; + TypeLoc Next; + if (LocValid) { - FTL = TL->getAs(); - RL = FTL.getReturnLoc(); - ParamStartLoc = FTL.getLParenLoc(); - } - } - - auto F = new AST::FunctionType(); - F->returnType = GetQualifiedType(FP->getReturnType(), &RL); - F->callingConvention = ConvertCallConv(FP->getCallConv()); - F->exceptionSpecType = ConvertExceptionType(FP->getExceptionSpecType()); + while (!TL->isNull() && TL->getTypeLocClass() != TypeLoc::FunctionNoProto) + { + Next = TL->getNextTypeLoc(); + TL = &Next; + } - for (unsigned i = 0; i < FP->getNumParams(); ++i) - { - if (FTL && FTL.getParam(i)) - { - auto PVD = FTL.getParam(i); - auto FA = WalkParameter(PVD, ParamStartLoc); - F->Parameters.push_back(FA); - } - else - { - auto FA = new Parameter(); - auto Arg = FP->getParamType(i); - FA->name = ""; - FA->qualifiedType = GetQualifiedType(Arg); - - // In this case we have no valid value to use as a pointer so - // use a special value known to the managed side to make sure - // it gets ignored. - FA->originalPtr = IgnorePtr; - F->Parameters.push_back(FA); + if (!TL->isNull() && TL->getTypeLocClass() == TypeLoc::FunctionNoProto) + { + FTL = TL->getAs(); + RL = FTL.getReturnLoc(); + } } - } - Ty = F; - break; - } - case clang::Type::TypeOf: - { - auto TO = Type->getAs(); - - Ty = WalkType(TO->getUnmodifiedType()); - break; - } - case clang::Type::TypeOfExpr: - { - auto TO = Type->getAs(); + auto F = new AST::FunctionType(); + F->returnType = GetQualifiedType(FP->getReturnType(), &RL); + F->callingConvention = ConvertCallConv(FP->getCallConv()); - Ty = WalkType(TO->getUnderlyingExpr()->getType()); - break; - } - case clang::Type::MemberPointer: - { - auto MP = Type->getAs(); + Ty = F; + break; + } + case clang::Type::FunctionProto: + { + auto FP = Type->getAs(); - TypeLoc Next; - if (LocValid) Next = TL->getNextTypeLoc(); + FunctionProtoTypeLoc FTL; + TypeLoc RL; + TypeLoc Next; + clang::SourceLocation ParamStartLoc; + if (LocValid) + { + while (!TL->isNull() && TL->getTypeLocClass() != TypeLoc::FunctionProto) + { + Next = TL->getNextTypeLoc(); + TL = &Next; + } - auto MPT = new AST::MemberPointerType(); - MPT->pointee = GetQualifiedType(MP->getPointeeType(), &Next); - - Ty = MPT; - break; - } - case clang::Type::TemplateSpecialization: - { - auto TS = Type->getAs(); - auto TST = new AST::TemplateSpecializationType(); - - TemplateName Name = TS->getTemplateName(); - TST->_template = static_cast(WalkDeclaration(Name.getAsTemplateDecl())); + if (!TL->isNull() && TL->getTypeLocClass() == TypeLoc::FunctionProto) + { + FTL = TL->getAs(); + RL = FTL.getReturnLoc(); + ParamStartLoc = FTL.getLParenLoc(); + } + } - if (TS->isSugared()) - TST->desugared = GetQualifiedType(TS->getCanonicalTypeInternal(), TL); + auto F = new AST::FunctionType(); + F->returnType = GetQualifiedType(FP->getReturnType(), &RL); + F->callingConvention = ConvertCallConv(FP->getCallConv()); + F->exceptionSpecType = ConvertExceptionType(FP->getExceptionSpecType()); - TemplateArgumentList TArgs(TemplateArgumentList::OnStack, TS->template_arguments()); + for (unsigned i = 0; i < FP->getNumParams(); ++i) + { + if (FTL && FTL.getParam(i)) + { + auto PVD = FTL.getParam(i); + auto FA = WalkParameter(PVD, ParamStartLoc); + F->Parameters.push_back(FA); + } + else + { + auto FA = new Parameter(); + auto Arg = FP->getParamType(i); + FA->name = ""; + FA->qualifiedType = GetQualifiedType(Arg); + + // In this case we have no valid value to use as a pointer so + // use a special value known to the managed side to make sure + // it gets ignored. + FA->originalPtr = IgnorePtr; + F->Parameters.push_back(FA); + } + } - if (!LocValid) - { - TST->Arguments = WalkTemplateArgumentList(&TArgs, (TemplateSpecializationTypeLoc*)nullptr); - Ty = TST; + Ty = F; break; } - - TypeLoc UTL, ETL, ITL; - if (TL->getTypeLocClass() == TypeLoc::Qualified) - { - UTL = TL->getUnqualifiedLoc(); - TL = &UTL; - } - - if (TL->getTypeLocClass() == TypeLoc::Elaborated) + case clang::Type::TypeOf: { - ETL = TL->getAs(); - ITL = ETL.getNextTypeLoc(); - TL = &ITL; - } + auto TO = Type->getAs(); - switch (TL->getTypeLocClass()) { - case TypeLoc::DependentTemplateSpecialization: - { - DependentTemplateSpecializationTypeLoc TSpecTL = TL->getAs(); - TST->Arguments = WalkTemplateArgumentList(&TArgs, &TSpecTL); - Ty = TST; + Ty = WalkType(TO->getUnmodifiedType()); break; } - case TypeLoc::TemplateSpecialization: + case clang::Type::TypeOfExpr: { - TemplateSpecializationTypeLoc TSpecTL = TL->getAs(); - TST->Arguments = WalkTemplateArgumentList(&TArgs, &TSpecTL); - Ty = TST; + auto TO = Type->getAs(); + + Ty = WalkType(TO->getUnderlyingExpr()->getType()); break; } - case TypeLoc::TemplateTypeParm: + case clang::Type::MemberPointer: { - TemplateTypeParmTypeLoc TTPTL = TL->getAs(); - TST->Arguments = WalkTemplateArgumentList(&TArgs, (TemplateSpecializationTypeLoc*)nullptr); - break; - } - default: - assertml(0, "Unhandled TemplateSpecializationTypeLoc!\n", c->getSourceManager(), TL->getBeginLoc()); - break; - } + auto MP = Type->getAs(); - Ty = TST; - break; - } - case clang::Type::DependentTemplateSpecialization: - { - auto TS = Type->getAs(); - auto TST = new AST::DependentTemplateSpecializationType(); - - if (TS->isSugared()) - TST->desugared = GetQualifiedType(TS->getCanonicalTypeInternal(), TL); - - TemplateArgumentList TArgs(TemplateArgumentList::OnStack, TS->template_arguments()); - - if (!LocValid) - { - TST->Arguments = WalkTemplateArgumentList(&TArgs, (DependentTemplateSpecializationTypeLoc*)nullptr); - Ty = TST; - break; - } + TypeLoc Next; + if (LocValid) + Next = TL->getNextTypeLoc(); - TypeLoc UTL, ETL, ITL; - if (TL->getTypeLocClass() == TypeLoc::Qualified) - { - UTL = TL->getUnqualifiedLoc(); - TL = &UTL; - } - - if (TL->getTypeLocClass() == TypeLoc::Elaborated) - { - ETL = TL->getAs(); - ITL = ETL.getNextTypeLoc(); - TL = &ITL; - } + auto MPT = new AST::MemberPointerType(); + MPT->pointee = GetQualifiedType(MP->getPointeeType(), &Next); - switch (TL->getTypeLocClass()) { - case TypeLoc::DependentTemplateSpecialization: - { - DependentTemplateSpecializationTypeLoc TSpecTL = TL->getAs(); - TST->Arguments = WalkTemplateArgumentList(&TArgs, &TSpecTL); - break; - } - case TypeLoc::TemplateSpecialization: - { - TemplateSpecializationTypeLoc TSpecTL = TL->getAs(); - TST->Arguments = WalkTemplateArgumentList(&TArgs, &TSpecTL); + Ty = MPT; break; } - case TypeLoc::TemplateTypeParm: + case clang::Type::TemplateSpecialization: { - TST->Arguments = WalkTemplateArgumentList(&TArgs, (DependentTemplateSpecializationTypeLoc*)nullptr); - break; - } - default: - assertml(0, "Unhandled DependentTemplateSpecializationTypeLoc!\n", c->getSourceManager(), TL->getBeginLoc()); - break; - } + auto TS = Type->getAs(); + auto TST = new AST::TemplateSpecializationType(); - Ty = TST; - break; - } - case clang::Type::TemplateTypeParm: - { - auto TP = Type->getAs(); + TemplateName Name = TS->getTemplateName(); + TST->_template = static_cast(WalkDeclaration(Name.getAsTemplateDecl())); - auto TPT = new TemplateParameterType(); + if (TS->isSugared()) + TST->desugared = GetQualifiedType(TS->getCanonicalTypeInternal(), TL); - if (auto Ident = TP->getIdentifier()) - TPT->parameter->name = Ident->getName().str(); + TemplateArgumentList TArgs(TemplateArgumentList::OnStack, TS->template_arguments()); - TypeLoc UTL, ETL, ITL, Next; + if (!LocValid) + { + TST->Arguments = WalkTemplateArgumentList(&TArgs, (TemplateSpecializationTypeLoc*)nullptr); + Ty = TST; + break; + } - if (LocValid) - { - auto TypeLocClass = TL->getTypeLocClass(); - if (TypeLocClass == TypeLoc::Qualified) + TypeLoc UTL, ETL, ITL; + if (TL->getTypeLocClass() == TypeLoc::Qualified) { UTL = TL->getUnqualifiedLoc(); TL = &UTL; } - else if (TypeLocClass == TypeLoc::Elaborated) + + if (TL->getTypeLocClass() == TypeLoc::Elaborated) { ETL = TL->getAs(); ITL = ETL.getNextTypeLoc(); TL = &ITL; } - while (TL->getTypeLocClass() != TypeLoc::TemplateTypeParm) + switch (TL->getTypeLocClass()) { - Next = TL->getNextTypeLoc(); - TL = &Next; + case TypeLoc::DependentTemplateSpecialization: + { + DependentTemplateSpecializationTypeLoc TSpecTL = TL->getAs(); + TST->Arguments = WalkTemplateArgumentList(&TArgs, &TSpecTL); + Ty = TST; + break; + } + case TypeLoc::TemplateSpecialization: + { + TemplateSpecializationTypeLoc TSpecTL = TL->getAs(); + TST->Arguments = WalkTemplateArgumentList(&TArgs, &TSpecTL); + Ty = TST; + break; + } + case TypeLoc::TemplateTypeParm: + { + TemplateTypeParmTypeLoc TTPTL = TL->getAs(); + TST->Arguments = WalkTemplateArgumentList(&TArgs, (TemplateSpecializationTypeLoc*)nullptr); + break; + } + default: + assertml(0, "Unhandled TemplateSpecializationTypeLoc!\n", c->getSourceManager(), TL->getBeginLoc()); + break; } - assertm(TL->getTypeLocClass() == TypeLoc::TemplateTypeParm, "Token should be template type parameter!\n"); - auto TTPTL = TL->getAs(); - auto TTPD = TTPTL.getDecl(); + Ty = TST; + break; + } + case clang::Type::DependentTemplateSpecialization: + { + auto TS = Type->getAs(); + auto TST = new AST::DependentTemplateSpecializationType(); - if (!TTPD) - return nullptr; // Can happen when a template param is used in a nested template argument + if (TS->isSugared()) + TST->desugared = GetQualifiedType(TS->getCanonicalTypeInternal(), TL); - TPT->parameter = WalkTypeTemplateParameter(TTPD); - } - else if (TP->getDecl()) - TPT->parameter = WalkTypeTemplateParameter(TP->getDecl()); - TPT->depth = TP->getDepth(); - TPT->index = TP->getIndex(); - TPT->isParameterPack = TP->isParameterPack(); + TemplateArgumentList TArgs(TemplateArgumentList::OnStack, TS->template_arguments()); - Ty = TPT; - break; - } - case clang::Type::SubstTemplateTypeParm: - { - auto TP = Type->getAs(); - auto TPT = new TemplateParameterSubstitutionType(); + if (!LocValid) + { + TST->Arguments = WalkTemplateArgumentList(&TArgs, (DependentTemplateSpecializationTypeLoc*)nullptr); + Ty = TST; + break; + } - TypeLoc Next; - if (LocValid) Next = TL->getNextTypeLoc(); + TypeLoc UTL, ETL, ITL; + if (TL->getTypeLocClass() == TypeLoc::Qualified) + { + UTL = TL->getUnqualifiedLoc(); + TL = &UTL; + } - auto RepTy = TP->getReplacementType(); - TPT->replacement = GetQualifiedType(RepTy, &Next); - TPT->replacedParameter = (TemplateParameterType*) - WalkType(c->getASTContext().getTypeDeclType(TP->getReplacedParameter()), 0); - TPT->replacedParameter->parameter = WalkTypeTemplateParameter( - TP->getReplacedParameter()); + if (TL->getTypeLocClass() == TypeLoc::Elaborated) + { + ETL = TL->getAs(); + ITL = ETL.getNextTypeLoc(); + TL = &ITL; + } - Ty = TPT; - break; - } - case clang::Type::InjectedClassName: - { - auto ICN = Type->getAs(); - auto ICNT = new AST::InjectedClassNameType(); - ICNT->_class = static_cast(WalkDeclaration( - ICN->getDecl())); - ICNT->injectedSpecializationType = GetQualifiedType( - ICN->getInjectedSpecializationType()); + switch (TL->getTypeLocClass()) + { + case TypeLoc::DependentTemplateSpecialization: + { + DependentTemplateSpecializationTypeLoc TSpecTL = TL->getAs(); + TST->Arguments = WalkTemplateArgumentList(&TArgs, &TSpecTL); + break; + } + case TypeLoc::TemplateSpecialization: + { + TemplateSpecializationTypeLoc TSpecTL = TL->getAs(); + TST->Arguments = WalkTemplateArgumentList(&TArgs, &TSpecTL); + break; + } + case TypeLoc::TemplateTypeParm: + { + TST->Arguments = WalkTemplateArgumentList(&TArgs, (DependentTemplateSpecializationTypeLoc*)nullptr); + break; + } + default: + assertml(0, "Unhandled DependentTemplateSpecializationTypeLoc!\n", c->getSourceManager(), TL->getBeginLoc()); + break; + } - Ty = ICNT; - break; - } - case clang::Type::DependentName: - { - auto DN = Type->getAs(); - auto DNT = new AST::DependentNameType(); - switch (DN->getQualifier()->getKind()) - { - case NestedNameSpecifier::SpecifierKind::TypeSpec: - case NestedNameSpecifier::SpecifierKind::TypeSpecWithTemplate: + Ty = TST; + break; + } + case clang::Type::TemplateTypeParm: { - const auto& Qualifier = clang::QualType(DN->getQualifier()->getAsType(), 0); + auto TP = Type->getAs(); + + auto TPT = new TemplateParameterType(); + + if (auto Ident = TP->getIdentifier()) + TPT->parameter->name = Ident->getName().str(); + + TypeLoc UTL, ETL, ITL, Next; + if (LocValid) { - const auto& DNTL = TL->getAs(); - if (!DNTL.isNull()) + auto TypeLocClass = TL->getTypeLocClass(); + if (TypeLocClass == TypeLoc::Qualified) { - const auto& QL = DNTL.getQualifierLoc(); - const auto& NNSL = QL.getTypeLoc(); - DNT->qualifier = GetQualifiedType(Qualifier, &NNSL); + UTL = TL->getUnqualifiedLoc(); + TL = &UTL; } - else + else if (TypeLocClass == TypeLoc::Elaborated) + { + ETL = TL->getAs(); + ITL = ETL.getNextTypeLoc(); + TL = &ITL; + } + + while (TL->getTypeLocClass() != TypeLoc::TemplateTypeParm) { - DNT->qualifier = GetQualifiedType(Qualifier, 0); + Next = TL->getNextTypeLoc(); + TL = &Next; } + + assertm(TL->getTypeLocClass() == TypeLoc::TemplateTypeParm, "Token should be template type parameter!\n"); + auto TTPTL = TL->getAs(); + auto TTPD = TTPTL.getDecl(); + + if (!TTPD) + return nullptr; // Can happen when a template param is used in a nested template argument + + TPT->parameter = WalkTypeTemplateParameter(TTPD); } - else + else if (TP->getDecl()) + TPT->parameter = WalkTypeTemplateParameter(TP->getDecl()); + TPT->depth = TP->getDepth(); + TPT->index = TP->getIndex(); + TPT->isParameterPack = TP->isParameterPack(); + + Ty = TPT; + break; + } + case clang::Type::SubstTemplateTypeParm: + { + auto TP = Type->getAs(); + auto TPT = new TemplateParameterSubstitutionType(); + + TypeLoc Next; + if (LocValid) + Next = TL->getNextTypeLoc(); + + auto RepTy = TP->getReplacementType(); + TPT->replacement = GetQualifiedType(RepTy, &Next); + TPT->replacedParameter = (TemplateParameterType*) + WalkType(c->getASTContext().getTypeDeclType(TP->getReplacedParameter()), 0); + TPT->replacedParameter->parameter = WalkTypeTemplateParameter( + TP->getReplacedParameter()); + + Ty = TPT; + break; + } + case clang::Type::InjectedClassName: + { + auto ICN = Type->getAs(); + auto ICNT = new AST::InjectedClassNameType(); + ICNT->_class = static_cast(WalkDeclaration( + ICN->getDecl())); + ICNT->injectedSpecializationType = GetQualifiedType( + ICN->getInjectedSpecializationType()); + + Ty = ICNT; + break; + } + case clang::Type::DependentName: + { + auto DN = Type->getAs(); + auto DNT = new AST::DependentNameType(); + switch (DN->getQualifier()->getKind()) { - DNT->qualifier = GetQualifiedType(Qualifier, 0); + case NestedNameSpecifier::SpecifierKind::TypeSpec: + case NestedNameSpecifier::SpecifierKind::TypeSpecWithTemplate: + { + const auto& Qualifier = clang::QualType(DN->getQualifier()->getAsType(), 0); + if (LocValid) + { + const auto& DNTL = TL->getAs(); + if (!DNTL.isNull()) + { + const auto& QL = DNTL.getQualifierLoc(); + const auto& NNSL = QL.getTypeLoc(); + DNT->qualifier = GetQualifiedType(Qualifier, &NNSL); + } + else + { + DNT->qualifier = GetQualifiedType(Qualifier, 0); + } + } + else + { + DNT->qualifier = GetQualifiedType(Qualifier, 0); + } + break; + } + default: break; } + DNT->identifier = DN->getIdentifier()->getName().str(); + + Ty = DNT; break; } - default: break; - } - DNT->identifier = DN->getIdentifier()->getName().str(); + case clang::Type::LValueReference: + { + auto LR = Type->getAs(); - Ty = DNT; - break; - } - case clang::Type::LValueReference: - { - auto LR = Type->getAs(); + auto P = new AST::PointerType(); + P->modifier = AST::PointerType::TypeModifier::LVReference; - auto P = new AST::PointerType(); - P->modifier = AST::PointerType::TypeModifier::LVReference; + TypeLoc Next; + if (LocValid) + Next = TL->getNextTypeLoc(); - TypeLoc Next; - if (LocValid) Next = TL->getNextTypeLoc(); + auto Pointee = LR->getPointeeType(); + P->qualifiedPointee = GetQualifiedType(Pointee, &Next); - auto Pointee = LR->getPointeeType(); - P->qualifiedPointee = GetQualifiedType(Pointee, &Next); + Ty = P; + break; + } + case clang::Type::RValueReference: + { + auto LR = Type->getAs(); - Ty = P; - break; - } - case clang::Type::RValueReference: - { - auto LR = Type->getAs(); + auto P = new AST::PointerType(); + P->modifier = AST::PointerType::TypeModifier::RVReference; - auto P = new AST::PointerType(); - P->modifier = AST::PointerType::TypeModifier::RVReference; + TypeLoc Next; + if (LocValid) + Next = TL->getNextTypeLoc(); - TypeLoc Next; - if (LocValid) Next = TL->getNextTypeLoc(); + auto Pointee = LR->getPointeeType(); + P->qualifiedPointee = GetQualifiedType(Pointee, &Next); + + Ty = P; + break; + } + case clang::Type::UnaryTransform: + { + auto UT = Type->getAs(); - auto Pointee = LR->getPointeeType(); - P->qualifiedPointee = GetQualifiedType(Pointee, &Next); + TypeLoc Loc; + if (LocValid) + { + TypeSourceInfo* TSI = TL->getAs().getUnderlyingTInfo(); + Loc = TSI->getTypeLoc(); + } - Ty = P; - break; - } - case clang::Type::UnaryTransform: - { - auto UT = Type->getAs(); + auto UTT = new AST::UnaryTransformType(); + UTT->desugared = GetQualifiedType(UT->isSugared() ? UT->getCanonicalTypeInternal() : UT->getBaseType(), &Loc); + UTT->baseType = GetQualifiedType(UT->getBaseType(), &Loc); - TypeLoc Loc; - if (LocValid) + Ty = UTT; + break; + } + case clang::Type::TypeClass::Using: { - TypeSourceInfo* TSI = TL->getAs().getUnderlyingTInfo(); - Loc = TSI->getTypeLoc(); + auto U = Type->getAs(); + Ty = WalkType(U->getUnderlyingType(), TL); + break; } + case clang::Type::Vector: + { + auto V = Type->getAs(); - auto UTT = new AST::UnaryTransformType(); - UTT->desugared = GetQualifiedType(UT->isSugared() ? UT->getCanonicalTypeInternal() : UT->getBaseType(), &Loc); - UTT->baseType = GetQualifiedType(UT->getBaseType(), &Loc); - - Ty = UTT; - break; - } - case clang::Type::TypeClass::Using: - { - auto U = Type->getAs(); - Ty = WalkType(U->getUnderlyingType(), TL); - break; - } - case clang::Type::Vector: - { - auto V = Type->getAs(); - - auto VT = new AST::VectorType(); - VT->elementType = GetQualifiedType(V->getElementType()); - VT->numElements = V->getNumElements(); + auto VT = new AST::VectorType(); + VT->elementType = GetQualifiedType(V->getElementType()); + VT->numElements = V->getNumElements(); - Ty = VT; - break; - } - case clang::Type::PackExpansion: - { - // TODO: stubbed - Ty = new AST::PackExpansionType(); - break; - } - case clang::Type::Auto: - { - auto AT = Type->getAs(); - if (AT->isSugared()) - Ty = WalkType(AT->getCanonicalTypeInternal()); - else + Ty = VT; + break; + } + case clang::Type::PackExpansion: + { + // TODO: stubbed + Ty = new AST::PackExpansionType(); + break; + } + case clang::Type::Auto: + { + auto AT = Type->getAs(); + if (AT->isSugared()) + Ty = WalkType(AT->getCanonicalTypeInternal()); + else + return nullptr; + break; + } + case clang::Type::Decltype: + { + auto DT = Type->getAs(); + Ty = WalkType(DT->getUnderlyingType(), TL); + break; + } + case clang::Type::MacroQualified: + { + auto MT = Type->getAs(); + Ty = WalkType(MT->getUnderlyingType(), TL); + break; + } + default: + { + Debug("Unhandled type class '%s'\n", Type->getTypeClassName()); return nullptr; - break; - } - case clang::Type::Decltype: - { - auto DT = Type->getAs(); - Ty = WalkType(DT->getUnderlyingType(), TL); - break; - } - case clang::Type::MacroQualified: - { - auto MT = Type->getAs(); - Ty = WalkType(MT->getUnderlyingType(), TL); - break; + } } - default: - { - Debug("Unhandled type class '%s'\n", Type->getTypeClassName()); - return nullptr; - } } Ty->isDependent = Type->isDependentType(); return Ty; @@ -3121,8 +3168,7 @@ Enumeration* Parser::WalkEnum(const clang::EnumDecl* ED) } if (ED->isScoped()) - E->modifiers = (Enumeration::EnumModifiers) - ((int)E->modifiers | (int)Enumeration::EnumModifiers::Scoped); + E->modifiers = (Enumeration::EnumModifiers)((int)E->modifiers | (int)Enumeration::EnumModifiers::Scoped); // Get the underlying integer backing the enum. QualType IntType = ED->getIntegerType(); @@ -3136,7 +3182,7 @@ Enumeration* Parser::WalkEnum(const clang::EnumDecl* ED) } E->isIncomplete = false; - for(auto it = ED->enumerator_begin(); it != ED->enumerator_end(); ++it) + for (auto it = ED->enumerator_begin(); it != ED->enumerator_end(); ++it) { E->Items.push_back(WalkEnumItem(*it)); } @@ -3151,8 +3197,7 @@ Enumeration::Item* Parser::WalkEnumItem(clang::EnumConstantDecl* ECD) EnumItem->name = ECD->getNameAsString(); auto Value = ECD->getInitVal(); - EnumItem->value = Value.isSigned() ? Value.getSExtValue() - : Value.getZExtValue(); + EnumItem->value = Value.isSigned() ? Value.getSExtValue() : Value.getZExtValue(); EnumItem->_namespace = GetNamespace(ECD); std::string Text; @@ -3165,7 +3210,8 @@ Enumeration::Item* Parser::WalkEnumItem(clang::EnumConstantDecl* ECD) //-----------------------------------// static const clang::CodeGen::CGFunctionInfo& GetCodeGenFunctionInfo( - clang::CodeGen::CodeGenTypes* CodeGenTypes, const clang::FunctionDecl* FD) + clang::CodeGen::CodeGenTypes* CodeGenTypes, + const clang::FunctionDecl* FD) { auto FTy = FD->getType()->getCanonicalTypeUnqualified(); return CodeGenTypes->arrangeFreeFunctionType( @@ -3211,7 +3257,7 @@ bool Parser::CanCheckCodeGenInfo(const clang::Type* Ty) if (auto MPT = Ty->getAs()) if (!MPT->isDependentType()) c->getSema().RequireCompleteType(clang::SourceLocation(), - clang::QualType(Ty, 0), 1); + clang::QualType(Ty, 0), 1); } return true; @@ -3223,18 +3269,18 @@ static clang::TypeLoc DesugarTypeLoc(const clang::TypeLoc& Loc) switch (Loc.getTypeLocClass()) { - case TypeLoc::TypeLocClass::Attributed: - { - auto ATL = Loc.getAs(); - return ATL.getModifiedLoc(); - } - case TypeLoc::TypeLocClass::Paren: - { - auto PTL = Loc.getAs(); - return PTL.getInnerLoc(); - } - default: - break; + case TypeLoc::TypeLocClass::Attributed: + { + auto ATL = Loc.getAs(); + return ATL.getModifiedLoc(); + } + case TypeLoc::TypeLocClass::Paren: + { + auto PTL = Loc.getAs(); + return PTL.getInnerLoc(); + } + default: + break; } return Loc; @@ -3263,7 +3309,7 @@ void Parser::CompleteIfSpecializationType(const clang::QualType& QualType) if (!CTS->isCompleteDefinition()) c->getSema().InstantiateClassTemplateSpecialization(CTS->getBeginLoc(), - CTS, TSK_ImplicitInstantiation, false); + CTS, TSK_ImplicitInstantiation, false); c->getSema().getDiagnostics().setClient(existingClient, false); c->getSema().TUScope = nullptr; @@ -3280,7 +3326,7 @@ void Parser::CompleteIfSpecializationType(const clang::QualType& QualType) } Parameter* Parser::WalkParameter(const clang::ParmVarDecl* PVD, - const clang::SourceLocation& ParamStartLoc) + const clang::SourceLocation& ParamStartLoc) { using namespace clang; @@ -3353,14 +3399,14 @@ static bool IsInvalid(clang::Stmt* Body, std::unordered_set& Bodie Decl* D = 0; switch (Body->getStmtClass()) { - case clang::Stmt::StmtClass::DeclRefExprClass: - D = cast(Body)->getDecl(); - break; - case clang::Stmt::StmtClass::MemberExprClass: - D = cast(Body)->getMemberDecl(); - break; - default: - break; + case clang::Stmt::StmtClass::DeclRefExprClass: + D = cast(Body)->getDecl(); + break; + case clang::Stmt::StmtClass::MemberExprClass: + D = cast(Body)->getMemberDecl(); + break; + default: + break; } if (D) { @@ -3395,7 +3441,7 @@ void Parser::MarkValidity(Function* F) c->getSema().TUScope = &Scope; c->getSema().InstantiateFunctionDefinition(FD->getBeginLoc(), FD, - /*Recursive*/true); + /*Recursive*/ true); F->isInvalid = FD->isInvalidDecl(); if (!F->isInvalid) { @@ -3543,17 +3589,20 @@ void Parser::WalkFunction(const clang::FunctionDecl* FD, Function* F) const CXXMethodDecl* MD; if (FD->isDependentContext() || ((MD = dyn_cast(FD)) && !MD->isStatic() && - !HasLayout(cast(MD->getDeclContext()))) || + !HasLayout(cast(MD->getDeclContext()))) || !CanCheckCodeGenInfo(FD->getReturnType().getTypePtr()) || std::any_of(FD->parameters().begin(), FD->parameters().end(), - [this](auto* P) { return !CanCheckCodeGenInfo(P->getType().getTypePtr()); })) + [this](auto* P) + { + return !CanCheckCodeGenInfo(P->getType().getTypePtr()); + })) { return; } auto& CGInfo = GetCodeGenFunctionInfo(codeGenTypes.get(), FD); F->isReturnIndirect = CGInfo.getReturnInfo().isIndirect() || - CGInfo.getReturnInfo().isInAlloca(); + CGInfo.getReturnInfo().isInAlloca(); unsigned Index = 0; for (const auto& Arg : CGInfo.arguments()) @@ -3597,15 +3646,15 @@ SourceLocationKind Parser::GetLocationKind(const clang::SourceLocation& Loc) if (PLoc.isInvalid()) return SourceLocationKind::Invalid; - const char *FileName = PLoc.getFilename(); + const char* FileName = PLoc.getFilename(); - if(strcmp(FileName, "") == 0) + if (strcmp(FileName, "") == 0) return SourceLocationKind::Builtin; - if(strcmp(FileName, "") == 0) + if (strcmp(FileName, "") == 0) return SourceLocationKind::CommandLine; - if(SM.getFileCharacteristic(Loc) == SrcMgr::C_User) + if (SM.getFileCharacteristic(Loc) == SrcMgr::C_User) return SourceLocationKind::User; return SourceLocationKind::System; @@ -3642,7 +3691,8 @@ void Parser::WalkVariable(const clang::VarDecl* VD, Variable* Var) auto Init = VD->getAnyInitializer(); Var->initializer = (Init && !Init->getType()->isDependentType()) ? - WalkVariableInitializerExpression(Init) : nullptr; + WalkVariableInitializerExpression(Init) : + nullptr; auto TL = VD->getTypeSourceInfo()->getTypeLoc(); Var->qualifiedType = GetQualifiedType(VD->getType(), &TL); @@ -3651,7 +3701,7 @@ void Parser::WalkVariable(const clang::VarDecl* VD, Variable* Var) Var->mangled = Mangled; } -Variable* Parser::WalkVariable(const clang::VarDecl *VD) +Variable* Parser::WalkVariable(const clang::VarDecl* VD) { using namespace clang; @@ -3674,7 +3724,7 @@ Variable* Parser::WalkVariable(const clang::VarDecl *VD) //-----------------------------------// -Friend* Parser::WalkFriend(const clang::FriendDecl *FD) +Friend* Parser::WalkFriend(const clang::FriendDecl* FD) { using namespace clang; @@ -3709,7 +3759,7 @@ bool Parser::GetDeclText(clang::SourceRange SR, std::string& Text) { using namespace clang; SourceManager& SM = c->getSourceManager(); - const LangOptions &LangOpts = c->getLangOpts(); + const LangOptions& LangOpts = c->getLangOpts(); auto Range = CharSourceRange::getTokenRange(SR); @@ -3720,12 +3770,13 @@ bool Parser::GetDeclText(clang::SourceRange SR, std::string& Text) } PreprocessedEntity* Parser::WalkPreprocessedEntity( - Declaration* Decl, clang::PreprocessedEntity* PPEntity) + Declaration* Decl, + clang::PreprocessedEntity* PPEntity) { using namespace clang; for (unsigned I = 0, E = Decl->PreprocessedEntities.size(); - I != E; ++I) + I != E; ++I) { auto Entity = Decl->PreprocessedEntities[I]; if (Entity->originalPtr == PPEntity) @@ -3736,73 +3787,73 @@ PreprocessedEntity* Parser::WalkPreprocessedEntity( AST::PreprocessedEntity* Entity = 0; - switch(PPEntity->getKind()) - { - case clang::PreprocessedEntity::MacroExpansionKind: + switch (PPEntity->getKind()) { - auto ME = cast(PPEntity); - auto Expansion = new AST::MacroExpansion(); - auto MD = ME->getDefinition(); - if (MD && MD->getKind() != clang::PreprocessedEntity::InvalidKind) - Expansion->definition = (AST::MacroDefinition*) - WalkPreprocessedEntity(Decl, ME->getDefinition()); - Entity = Expansion; + case clang::PreprocessedEntity::MacroExpansionKind: + { + auto ME = cast(PPEntity); + auto Expansion = new AST::MacroExpansion(); + auto MD = ME->getDefinition(); + if (MD && MD->getKind() != clang::PreprocessedEntity::InvalidKind) + Expansion->definition = (AST::MacroDefinition*) + WalkPreprocessedEntity(Decl, ME->getDefinition()); + Entity = Expansion; + + std::string Text; + GetDeclText(PPEntity->getSourceRange(), Text); + + static_cast(Entity)->text = Text; + break; + } + case clang::PreprocessedEntity::MacroDefinitionKind: + { + auto MD = cast(PPEntity); - std::string Text; - GetDeclText(PPEntity->getSourceRange(), Text); + if (!IsValidDeclaration(MD->getLocation())) + break; - static_cast(Entity)->text = Text; - break; - } - case clang::PreprocessedEntity::MacroDefinitionKind: - { - auto MD = cast(PPEntity); + const IdentifierInfo* II = MD->getName(); + assertm(II, "Expected valid identifier info!\n"); - if (!IsValidDeclaration(MD->getLocation())) - break; + MacroInfo* MI = P.getMacroInfo((IdentifierInfo*)II); - const IdentifierInfo* II = MD->getName(); - assertm(II, "Expected valid identifier info!\n"); + if (!MI || MI->isBuiltinMacro()) + break; - MacroInfo* MI = P.getMacroInfo((IdentifierInfo*)II); + SourceManager& SM = c->getSourceManager(); + const LangOptions& LangOpts = c->getLangOpts(); - if (!MI || MI->isBuiltinMacro()) - break; + auto Loc = MI->getDefinitionLoc(); - SourceManager& SM = c->getSourceManager(); - const LangOptions &LangOpts = c->getLangOpts(); + if (!IsValidDeclaration(Loc)) + break; - auto Loc = MI->getDefinitionLoc(); + clang::SourceLocation BeginExpr = + Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts); - if (!IsValidDeclaration(Loc)) - break; + auto Range = CharSourceRange::getTokenRange( + BeginExpr, MI->getDefinitionEndLoc()); - clang::SourceLocation BeginExpr = - Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts); + bool Invalid; + StringRef Expression = Lexer::getSourceText(Range, SM, LangOpts, + &Invalid); - auto Range = CharSourceRange::getTokenRange( - BeginExpr, MI->getDefinitionEndLoc()); + if (Invalid || Expression.empty()) + break; - bool Invalid; - StringRef Expression = Lexer::getSourceText(Range, SM, LangOpts, - &Invalid); + auto Definition = new AST::MacroDefinition(); + Definition->lineNumberStart = SM.getExpansionLineNumber(MD->getLocation()); + Definition->lineNumberEnd = SM.getExpansionLineNumber(MD->getLocation()); + Entity = Definition; - if (Invalid || Expression.empty()) + Definition->name = II->getName().trim().str(); + Definition->expression = Expression.trim().str(); + } + case clang::PreprocessedEntity::InclusionDirectiveKind: + // nothing to be done for InclusionDirectiveKind break; - - auto Definition = new AST::MacroDefinition(); - Definition->lineNumberStart = SM.getExpansionLineNumber(MD->getLocation()); - Definition->lineNumberEnd = SM.getExpansionLineNumber(MD->getLocation()); - Entity = Definition; - - Definition->name = II->getName().trim().str(); - Definition->expression = Expression.trim().str(); - } - case clang::PreprocessedEntity::InclusionDirectiveKind: - // nothing to be done for InclusionDirectiveKind - break; - default: - llvm_unreachable("Unknown PreprocessedEntity"); + default: + llvm_unreachable("Unknown PreprocessedEntity"); } if (!Entity) @@ -3841,77 +3892,77 @@ ExpressionObsolete* Parser::WalkExpressionObsolete(const clang::Expr* Expr) switch (Expr->getStmtClass()) { - case clang::Stmt::BinaryOperatorClass: - { - auto BinaryOperator = cast(Expr); - return new BinaryOperatorObsolete(GetStringFromStatement(Expr), - WalkExpressionObsolete(BinaryOperator->getLHS()), WalkExpressionObsolete(BinaryOperator->getRHS()), - BinaryOperator->getOpcodeStr().str()); - } - case clang::Stmt::CallExprClass: - { - auto CallExpr = cast(Expr); - auto CallExpression = new CallExprObsolete(GetStringFromStatement(Expr), - CallExpr->getCalleeDecl() ? WalkDeclaration(CallExpr->getCalleeDecl()) : 0); - for (auto arg : CallExpr->arguments()) + case clang::Stmt::BinaryOperatorClass: { - CallExpression->Arguments.push_back(WalkExpressionObsolete(arg)); + auto BinaryOperator = cast(Expr); + return new BinaryOperatorObsolete(GetStringFromStatement(Expr), + WalkExpressionObsolete(BinaryOperator->getLHS()), WalkExpressionObsolete(BinaryOperator->getRHS()), + BinaryOperator->getOpcodeStr().str()); } - return CallExpression; - } - case clang::Stmt::DeclRefExprClass: - return new ExpressionObsolete(GetStringFromStatement(Expr), StatementClassObsolete::DeclRefExprClass, - WalkDeclaration(cast(Expr)->getDecl())); - case clang::Stmt::CStyleCastExprClass: - case clang::Stmt::CXXConstCastExprClass: - case clang::Stmt::CXXDynamicCastExprClass: - case clang::Stmt::CXXFunctionalCastExprClass: - case clang::Stmt::CXXReinterpretCastExprClass: - case clang::Stmt::CXXStaticCastExprClass: - case clang::Stmt::ImplicitCastExprClass: - return WalkExpressionObsolete(cast(Expr)->getSubExprAsWritten()); - case clang::Stmt::CXXOperatorCallExprClass: - { - auto OperatorCallExpr = cast(Expr); - return new ExpressionObsolete(GetStringFromStatement(Expr), StatementClassObsolete::CXXOperatorCallExpr, - OperatorCallExpr->getCalleeDecl() ? WalkDeclaration(OperatorCallExpr->getCalleeDecl()) : 0); - } - case clang::Stmt::CXXConstructExprClass: - case clang::Stmt::CXXTemporaryObjectExprClass: - { - auto ConstructorExpr = cast(Expr); - if (ConstructorExpr->getNumArgs() == 1) + case clang::Stmt::CallExprClass: { - auto Arg = ConstructorExpr->getArg(0); - auto TemporaryExpr = dyn_cast(Arg); - if (TemporaryExpr) + auto CallExpr = cast(Expr); + auto CallExpression = new CallExprObsolete(GetStringFromStatement(Expr), + CallExpr->getCalleeDecl() ? WalkDeclaration(CallExpr->getCalleeDecl()) : 0); + for (auto arg : CallExpr->arguments()) { - auto SubTemporaryExpr = TemporaryExpr->getSubExpr(); - auto Cast = dyn_cast(SubTemporaryExpr); - if (!Cast || - (Cast->getSubExprAsWritten()->getStmtClass() != clang::Stmt::IntegerLiteralClass && - Cast->getSubExprAsWritten()->getStmtClass() != clang::Stmt::CXXNullPtrLiteralExprClass)) - return WalkExpressionObsolete(SubTemporaryExpr); - return new CXXConstructExprObsolete(GetStringFromStatement(Expr), - WalkDeclaration(ConstructorExpr->getConstructor())); + CallExpression->Arguments.push_back(WalkExpressionObsolete(arg)); } + return CallExpression; } - auto ConstructorExpression = new CXXConstructExprObsolete(GetStringFromStatement(Expr), - WalkDeclaration(ConstructorExpr->getConstructor())); - for (auto arg : ConstructorExpr->arguments()) + case clang::Stmt::DeclRefExprClass: + return new ExpressionObsolete(GetStringFromStatement(Expr), StatementClassObsolete::DeclRefExprClass, + WalkDeclaration(cast(Expr)->getDecl())); + case clang::Stmt::CStyleCastExprClass: + case clang::Stmt::CXXConstCastExprClass: + case clang::Stmt::CXXDynamicCastExprClass: + case clang::Stmt::CXXFunctionalCastExprClass: + case clang::Stmt::CXXReinterpretCastExprClass: + case clang::Stmt::CXXStaticCastExprClass: + case clang::Stmt::ImplicitCastExprClass: + return WalkExpressionObsolete(cast(Expr)->getSubExprAsWritten()); + case clang::Stmt::CXXOperatorCallExprClass: { - ConstructorExpression->Arguments.push_back(WalkExpressionObsolete(arg)); + auto OperatorCallExpr = cast(Expr); + return new ExpressionObsolete(GetStringFromStatement(Expr), StatementClassObsolete::CXXOperatorCallExpr, + OperatorCallExpr->getCalleeDecl() ? WalkDeclaration(OperatorCallExpr->getCalleeDecl()) : 0); } - return ConstructorExpression; - } - case clang::Stmt::CXXBindTemporaryExprClass: - return WalkExpressionObsolete(cast(Expr)->getSubExpr()); - case clang::Stmt::CXXDefaultArgExprClass: - return WalkExpressionObsolete(cast(Expr)->getExpr()); - case clang::Stmt::MaterializeTemporaryExprClass: - return WalkExpressionObsolete(cast(Expr)->getSubExpr()); - default: - break; + case clang::Stmt::CXXConstructExprClass: + case clang::Stmt::CXXTemporaryObjectExprClass: + { + auto ConstructorExpr = cast(Expr); + if (ConstructorExpr->getNumArgs() == 1) + { + auto Arg = ConstructorExpr->getArg(0); + auto TemporaryExpr = dyn_cast(Arg); + if (TemporaryExpr) + { + auto SubTemporaryExpr = TemporaryExpr->getSubExpr(); + auto Cast = dyn_cast(SubTemporaryExpr); + if (!Cast || + (Cast->getSubExprAsWritten()->getStmtClass() != clang::Stmt::IntegerLiteralClass && + Cast->getSubExprAsWritten()->getStmtClass() != clang::Stmt::CXXNullPtrLiteralExprClass)) + return WalkExpressionObsolete(SubTemporaryExpr); + return new CXXConstructExprObsolete(GetStringFromStatement(Expr), + WalkDeclaration(ConstructorExpr->getConstructor())); + } + } + auto ConstructorExpression = new CXXConstructExprObsolete(GetStringFromStatement(Expr), + WalkDeclaration(ConstructorExpr->getConstructor())); + for (auto arg : ConstructorExpr->arguments()) + { + ConstructorExpression->Arguments.push_back(WalkExpressionObsolete(arg)); + } + return ConstructorExpression; + } + case clang::Stmt::CXXBindTemporaryExprClass: + return WalkExpressionObsolete(cast(Expr)->getSubExpr()); + case clang::Stmt::CXXDefaultArgExprClass: + return WalkExpressionObsolete(cast(Expr)->getExpr()); + case clang::Stmt::MaterializeTemporaryExprClass: + return WalkExpressionObsolete(cast(Expr)->getSubExpr()); + default: + break; } if (!Expr->isValueDependent()) @@ -3920,8 +3971,8 @@ ExpressionObsolete* Parser::WalkExpressionObsolete(const clang::Expr* Expr) if (Expr->getStmtClass() == clang::Stmt::CharacterLiteralClass) { auto result = GetStringFromStatement(Expr); - if (!result.empty() && - result.front() != '\'' && + if (!result.empty() && + result.front() != '\'' && Expr->EvaluateAsInt(integer, c->getASTContext())) { result = toString(integer.Val.getInt(), 10); @@ -3930,9 +3981,8 @@ ExpressionObsolete* Parser::WalkExpressionObsolete(const clang::Expr* Expr) return new ExpressionObsolete(result); } else if (Expr->getStmtClass() != clang::Stmt::CXXBoolLiteralExprClass && - Expr->getStmtClass() != clang::Stmt::UnaryExprOrTypeTraitExprClass && - Expr->EvaluateAsInt(integer, c->getASTContext()) - ) + Expr->getStmtClass() != clang::Stmt::UnaryExprOrTypeTraitExprClass && + Expr->EvaluateAsInt(integer, c->getASTContext())) { return new ExpressionObsolete(toString(integer.Val.getInt(), 10)); } @@ -3949,7 +3999,7 @@ ExpressionObsolete* Parser::WalkVariableInitializerExpression(const clang::Expr* return WalkVariableInitializerExpression(cast(Expr)->getSubExprAsWritten()); if (IsLiteralStmt(Expr->getStmtClass())) - return WalkExpressionObsolete(Expr); + return WalkExpressionObsolete(Expr); clang::Expr::EvalResult result; if (!Expr->isValueDependent() && @@ -3957,48 +4007,48 @@ ExpressionObsolete* Parser::WalkVariableInitializerExpression(const clang::Expr* { std::string s; llvm::raw_string_ostream out(s); - APValuePrinter printer{c->getASTContext(), out}; + APValuePrinter printer{ c->getASTContext(), out }; if (printer.Print(result.Val, Expr->getType())) return new ExpressionObsolete(out.str()); } - + return WalkExpressionObsolete(Expr); } -bool Parser::IsCastStmt(clang::Stmt::StmtClass stmt) +bool Parser::IsCastStmt(clang::Stmt::StmtClass stmt) { switch (stmt) { - case clang::Stmt::CStyleCastExprClass: - case clang::Stmt::CXXConstCastExprClass: - case clang::Stmt::CXXDynamicCastExprClass: - case clang::Stmt::CXXFunctionalCastExprClass: - case clang::Stmt::CXXReinterpretCastExprClass: - case clang::Stmt::CXXStaticCastExprClass: - case clang::Stmt::ImplicitCastExprClass: - return true; - default: - return false; + case clang::Stmt::CStyleCastExprClass: + case clang::Stmt::CXXConstCastExprClass: + case clang::Stmt::CXXDynamicCastExprClass: + case clang::Stmt::CXXFunctionalCastExprClass: + case clang::Stmt::CXXReinterpretCastExprClass: + case clang::Stmt::CXXStaticCastExprClass: + case clang::Stmt::ImplicitCastExprClass: + return true; + default: + return false; } } -bool Parser::IsLiteralStmt(clang::Stmt::StmtClass stmt) +bool Parser::IsLiteralStmt(clang::Stmt::StmtClass stmt) { switch (stmt) { - case clang::Stmt::CharacterLiteralClass: - case clang::Stmt::FixedPointLiteralClass: - case clang::Stmt::FloatingLiteralClass: - case clang::Stmt::IntegerLiteralClass: - case clang::Stmt::StringLiteralClass: - case clang::Stmt::ImaginaryLiteralClass: - case clang::Stmt::UserDefinedLiteralClass: - case clang::Stmt::CXXNullPtrLiteralExprClass: - case clang::Stmt::CXXBoolLiteralExprClass: - return true; - default: - return false; + case clang::Stmt::CharacterLiteralClass: + case clang::Stmt::FixedPointLiteralClass: + case clang::Stmt::FloatingLiteralClass: + case clang::Stmt::IntegerLiteralClass: + case clang::Stmt::StringLiteralClass: + case clang::Stmt::ImaginaryLiteralClass: + case clang::Stmt::UserDefinedLiteralClass: + case clang::Stmt::CXXNullPtrLiteralExprClass: + case clang::Stmt::CXXBoolLiteralExprClass: + return true; + default: + return false; } } @@ -4029,13 +4079,15 @@ void Parser::HandlePreprocessedEntities(Declaration* Decl, clang::SourceRange sourceRange, MacroLocation macroLocation) { - if (sourceRange.isInvalid()) return; + if (sourceRange.isInvalid()) + return; auto& SourceMgr = c->getSourceManager(); auto isBefore = SourceMgr.isBeforeInTranslationUnit(sourceRange.getEnd(), - sourceRange.getBegin()); + sourceRange.getBegin()); - if (isBefore) return; + if (isBefore) + return; using namespace clang; auto PPRecord = c->getPreprocessor().getPreprocessingRecord(); @@ -4045,8 +4097,9 @@ void Parser::HandlePreprocessedEntities(Declaration* Decl, for (auto PPEntity : Range) { auto Entity = WalkPreprocessedEntity(Decl, PPEntity); - if (!Entity) continue; - + if (!Entity) + continue; + if (Entity->macroLocation == MacroLocation::Unknown) Entity->macroLocation = macroLocation; } @@ -4061,7 +4114,7 @@ void Parser::HandleOriginalText(const clang::Decl* D, Declaration* Decl) bool Invalid; auto DeclText = clang::Lexer::getSourceText(Range, SM, LangOpts, &Invalid); - + if (!Invalid) Decl->debugText = DeclText.str(); } @@ -4071,7 +4124,7 @@ void Parser::HandleDeclaration(const clang::Decl* D, Declaration* Decl) if (Decl->originalPtr != nullptr) return; - Decl->originalPtr = (void*) D; + Decl->originalPtr = (void*)D; Decl->USR = GetDeclUSR(D); Decl->isImplicit = D->isImplicit(); Decl->location = SourceLocation(D->getLocation().getRawEncoding()); @@ -4111,10 +4164,10 @@ void Parser::HandleDeclaration(const clang::Decl* D, Declaration* Decl) HandleOriginalText(D, Decl); HandleComments(D, Decl); - if (const clang::ValueDecl *VD = clang::dyn_cast_or_null(D)) + if (const clang::ValueDecl* VD = clang::dyn_cast_or_null(D)) Decl->isDependent = VD->getType()->isDependentType(); - if (const clang::DeclContext *DC = clang::dyn_cast_or_null(D)) + if (const clang::DeclContext* DC = clang::dyn_cast_or_null(D)) Decl->isDependent |= DC->isDependentContext(); Decl->access = ConvertToAccess(D->getAccess()); @@ -4148,283 +4201,286 @@ Declaration* Parser::WalkDeclaration(const clang::Decl* D) Declaration* Decl = nullptr; auto Kind = D->getKind(); - switch(D->getKind()) - { - case Decl::Record: - { - auto RD = cast(D); - Decl = WalkRecord(RD); - break; - } - case Decl::CXXRecord: - { - auto RD = cast(D); - Decl = WalkRecordCXX(RD); - break; - } - case Decl::ClassTemplate: - { - auto TD = cast(D); - auto Template = WalkClassTemplate(TD); - - Decl = Template; - break; - } - case Decl::ClassTemplateSpecialization: + switch (D->getKind()) { - auto TS = cast(D); - auto CT = WalkClassTemplateSpecialization(TS); - - Decl = CT; - break; - } - case Decl::ClassTemplatePartialSpecialization: - { - auto TS = cast(D); - auto CT = WalkClassTemplatePartialSpecialization(TS); + case Decl::Record: + { + auto RD = cast(D); + Decl = WalkRecord(RD); + break; + } + case Decl::CXXRecord: + { + auto RD = cast(D); + Decl = WalkRecordCXX(RD); + break; + } + case Decl::ClassTemplate: + { + auto TD = cast(D); + auto Template = WalkClassTemplate(TD); - Decl = CT; - break; - } - case Decl::FunctionTemplate: - { - auto TD = cast(D); - auto FT = WalkFunctionTemplate(TD); + Decl = Template; + break; + } + case Decl::ClassTemplateSpecialization: + { + auto TS = cast(D); + auto CT = WalkClassTemplateSpecialization(TS); - Decl = FT; - break; - } - case Decl::VarTemplate: - { - auto TD = cast(D); - auto Template = WalkVarTemplate(TD); + Decl = CT; + break; + } + case Decl::ClassTemplatePartialSpecialization: + { + auto TS = cast(D); + auto CT = WalkClassTemplatePartialSpecialization(TS); - Decl = Template; - break; - } - case Decl::VarTemplateSpecialization: - { - auto TS = cast(D); - auto CT = WalkVarTemplateSpecialization(TS); + Decl = CT; + break; + } + case Decl::FunctionTemplate: + { + auto TD = cast(D); + auto FT = WalkFunctionTemplate(TD); - Decl = CT; - break; - } - case Decl::VarTemplatePartialSpecialization: - { - auto TS = cast(D); - auto CT = WalkVarTemplatePartialSpecialization(TS); + Decl = FT; + break; + } + case Decl::VarTemplate: + { + auto TD = cast(D); + auto Template = WalkVarTemplate(TD); - Decl = CT; - break; - } - case Decl::TypeAliasTemplate: - { - auto TD = cast(D); - auto TA = WalkTypeAliasTemplate(TD); + Decl = Template; + break; + } + case Decl::VarTemplateSpecialization: + { + auto TS = cast(D); + auto CT = WalkVarTemplateSpecialization(TS); - Decl = TA; - break; - } - case Decl::Enum: - { - auto ED = cast(D); - Decl = WalkEnum(ED); - break; - } - case Decl::EnumConstant: - { - auto ED = cast(D); - auto E = static_cast(GetNamespace(ED)); - assertm(E, "Expected a valid enumeration!\n"); - Decl = E->FindItemByName(ED->getNameAsString()); - break; - } - case Decl::Function: - { - auto FD = cast(D); + Decl = CT; + break; + } + case Decl::VarTemplatePartialSpecialization: + { + auto TS = cast(D); + auto CT = WalkVarTemplatePartialSpecialization(TS); - // Check for and ignore built-in functions. - if (FD->getBuiltinID() != 0) + Decl = CT; break; + } + case Decl::TypeAliasTemplate: + { + auto TD = cast(D); + auto TA = WalkTypeAliasTemplate(TD); - Decl = WalkFunction(FD); - break; - } - case Decl::LinkageSpec: - { - auto LS = cast(D); - - for (auto it = LS->decls_begin(); it != LS->decls_end(); ++it) + Decl = TA; + break; + } + case Decl::Enum: { - clang::Decl* D = (*it); - Decl = WalkDeclarationDef(D); + auto ED = cast(D); + Decl = WalkEnum(ED); + break; } - - break; - } - case Decl::Typedef: - { - auto TD = cast(D); - - auto NS = GetNamespace(TD); - auto Name = GetDeclName(TD); - auto Typedef = NS->FindTypedef(Name, /*Create=*/false); - if (Typedef) return Typedef; + case Decl::EnumConstant: + { + auto ED = cast(D); + auto E = static_cast(GetNamespace(ED)); + assertm(E, "Expected a valid enumeration!\n"); + Decl = E->FindItemByName(ED->getNameAsString()); + break; + } + case Decl::Function: + { + auto FD = cast(D); - Typedef = NS->FindTypedef(Name, /*Create=*/true); - HandleDeclaration(TD, Typedef); + // Check for and ignore built-in functions. + if (FD->getBuiltinID() != 0) + break; - auto TTL = TD->getTypeSourceInfo()->getTypeLoc(); - // resolve the typedef before adding it to the list otherwise it might be found and returned prematurely - // see "typedef _Aligned<16, char>::type type;" and the related classes in Common.h in the tests - Typedef->qualifiedType = GetQualifiedType(TD->getUnderlyingType(), &TTL); - AST::TypedefDecl* Existing; - // if the typedef was added along the way, the just created one is useless, delete it - if ((Existing = NS->FindTypedef(Name, /*Create=*/false))) - delete Typedef; - else - NS->Typedefs.push_back(Existing = Typedef); + Decl = WalkFunction(FD); + break; + } + case Decl::LinkageSpec: + { + auto LS = cast(D); - Decl = Existing; - break; - } - case Decl::TypeAlias: - { - auto TD = cast(D); + for (auto it = LS->decls_begin(); it != LS->decls_end(); ++it) + { + clang::Decl* D = (*it); + Decl = WalkDeclarationDef(D); + } - auto NS = GetNamespace(TD); - auto Name = GetDeclName(TD); - auto TypeAlias = NS->FindTypeAlias(Name, /*Create=*/false); - if (TypeAlias) return TypeAlias; + break; + } + case Decl::Typedef: + { + auto TD = cast(D); + + auto NS = GetNamespace(TD); + auto Name = GetDeclName(TD); + auto Typedef = NS->FindTypedef(Name, /*Create=*/false); + if (Typedef) + return Typedef; + + Typedef = NS->FindTypedef(Name, /*Create=*/true); + HandleDeclaration(TD, Typedef); + + auto TTL = TD->getTypeSourceInfo()->getTypeLoc(); + // resolve the typedef before adding it to the list otherwise it might be found and returned prematurely + // see "typedef _Aligned<16, char>::type type;" and the related classes in Common.h in the tests + Typedef->qualifiedType = GetQualifiedType(TD->getUnderlyingType(), &TTL); + AST::TypedefDecl* Existing; + // if the typedef was added along the way, the just created one is useless, delete it + if ((Existing = NS->FindTypedef(Name, /*Create=*/false))) + delete Typedef; + else + NS->Typedefs.push_back(Existing = Typedef); - TypeAlias = NS->FindTypeAlias(Name, /*Create=*/true); - HandleDeclaration(TD, TypeAlias); + Decl = Existing; + break; + } + case Decl::TypeAlias: + { + auto TD = cast(D); + + auto NS = GetNamespace(TD); + auto Name = GetDeclName(TD); + auto TypeAlias = NS->FindTypeAlias(Name, /*Create=*/false); + if (TypeAlias) + return TypeAlias; + + TypeAlias = NS->FindTypeAlias(Name, /*Create=*/true); + HandleDeclaration(TD, TypeAlias); + + auto TTL = TD->getTypeSourceInfo()->getTypeLoc(); + // see above the case for "Typedef" + TypeAlias->qualifiedType = GetQualifiedType(TD->getUnderlyingType(), &TTL); + AST::TypeAlias* Existing; + if ((Existing = NS->FindTypeAlias(Name, /*Create=*/false))) + delete TypeAlias; + else + NS->TypeAliases.push_back(Existing = TypeAlias); - auto TTL = TD->getTypeSourceInfo()->getTypeLoc(); - // see above the case for "Typedef" - TypeAlias->qualifiedType = GetQualifiedType(TD->getUnderlyingType(), &TTL); - AST::TypeAlias* Existing; - if ((Existing = NS->FindTypeAlias(Name, /*Create=*/false))) - delete TypeAlias; - else - NS->TypeAliases.push_back(Existing = TypeAlias); + if (auto TAT = TD->getDescribedAliasTemplate()) + TypeAlias->describedAliasTemplate = WalkTypeAliasTemplate(TAT); - if (auto TAT = TD->getDescribedAliasTemplate()) - TypeAlias->describedAliasTemplate = WalkTypeAliasTemplate(TAT); + Decl = Existing; + break; + } + case Decl::TranslationUnit: + { + Decl = GetTranslationUnit(D); + break; + } + case Decl::Namespace: + { + auto ND = cast(D); - Decl = Existing; - break; - } - case Decl::TranslationUnit: - { - Decl = GetTranslationUnit(D); - break; - } - case Decl::Namespace: - { - auto ND = cast(D); + for (auto D : ND->decls()) + { + if (!isa(D) || IsSupported(cast(D))) + Decl = WalkDeclarationDef(D); + } - for (auto D : ND->decls()) + break; + } + case Decl::Var: { - if (!isa(D) || IsSupported(cast(D))) - Decl = WalkDeclarationDef(D); + auto VD = cast(D); + Decl = WalkVariable(VD); + break; } + case Decl::CXXConstructor: + case Decl::CXXDestructor: + case Decl::CXXConversion: + case Decl::CXXMethod: + { + auto MD = cast(D); + Decl = WalkMethodCXX(MD); + if (Decl == nullptr) + return Decl; - break; - } - case Decl::Var: - { - auto VD = cast(D); - Decl = WalkVariable(VD); - break; - } - case Decl::CXXConstructor: - case Decl::CXXDestructor: - case Decl::CXXConversion: - case Decl::CXXMethod: - { - auto MD = cast(D); - Decl = WalkMethodCXX(MD); - if (Decl == nullptr) - return Decl; - - auto NS = GetNamespace(MD); - Decl->_namespace = NS; - break; - } - case Decl::Field: - { - auto FD = cast(D); - auto _Class = static_cast(WalkDeclaration(FD->getParent())); - Decl = WalkFieldCXX(FD, _Class); - break; - } - case Decl::Friend: - { - auto FD = cast(D); - Decl = WalkFriend(FD); - break; - } - case Decl::TemplateTemplateParm: - { - auto TTP = cast(D); - Decl = WalkTemplateTemplateParameter(TTP); - break; - } - case Decl::TemplateTypeParm: - { - auto TTPD = cast(D); - Decl = WalkTypeTemplateParameter(TTPD); - break; - } - case Decl::NonTypeTemplateParm: - { - auto NTTPD = cast(D); - Decl = WalkNonTypeTemplateParameter(NTTPD); - break; - } - case Decl::UnresolvedUsingTypename: - { - auto UUTD = cast(D); - Decl = WalkUnresolvedUsingTypename(UUTD); - break; - } - case Decl::BuiltinTemplate: - case Decl::ClassScopeFunctionSpecialization: - case Decl::PragmaComment: - case Decl::PragmaDetectMismatch: - case Decl::Empty: - case Decl::AccessSpec: - case Decl::Using: - case Decl::UsingDirective: - case Decl::UsingShadow: - case Decl::ConstructorUsingShadow: - case Decl::UnresolvedUsingValue: - case Decl::IndirectField: - case Decl::StaticAssert: - case Decl::NamespaceAlias: - break; - default: - { - Debug("Unhandled declaration kind: %s\n", D->getDeclKindName()); + auto NS = GetNamespace(MD); + Decl->_namespace = NS; + break; + } + case Decl::Field: + { + auto FD = cast(D); + auto _Class = static_cast(WalkDeclaration(FD->getParent())); + Decl = WalkFieldCXX(FD, _Class); + break; + } + case Decl::Friend: + { + auto FD = cast(D); + Decl = WalkFriend(FD); + break; + } + case Decl::TemplateTemplateParm: + { + auto TTP = cast(D); + Decl = WalkTemplateTemplateParameter(TTP); + break; + } + case Decl::TemplateTypeParm: + { + auto TTPD = cast(D); + Decl = WalkTypeTemplateParameter(TTPD); + break; + } + case Decl::NonTypeTemplateParm: + { + auto NTTPD = cast(D); + Decl = WalkNonTypeTemplateParameter(NTTPD); + break; + } + case Decl::UnresolvedUsingTypename: + { + auto UUTD = cast(D); + Decl = WalkUnresolvedUsingTypename(UUTD); + break; + } + case Decl::BuiltinTemplate: + case Decl::ClassScopeFunctionSpecialization: + case Decl::PragmaComment: + case Decl::PragmaDetectMismatch: + case Decl::Empty: + case Decl::AccessSpec: + case Decl::Using: + case Decl::UsingDirective: + case Decl::UsingShadow: + case Decl::ConstructorUsingShadow: + case Decl::UnresolvedUsingValue: + case Decl::IndirectField: + case Decl::StaticAssert: + case Decl::NamespaceAlias: + break; + default: + { + Debug("Unhandled declaration kind: %s\n", D->getDeclKindName()); - auto& SM = c->getSourceManager(); - auto Loc = D->getLocation(); - auto FileName = SM.getFilename(Loc); - auto Offset = SM.getFileOffset(Loc); - auto LineNo = SM.getLineNumber(SM.getFileID(Loc), Offset); - Debug(" %s (line %u)\n", FileName.str().c_str(), LineNo); + auto& SM = c->getSourceManager(); + auto Loc = D->getLocation(); + auto FileName = SM.getFilename(Loc); + auto Offset = SM.getFileOffset(Loc); + auto LineNo = SM.getLineNumber(SM.getFileID(Loc), Offset); + Debug(" %s (line %u)\n", FileName.str().c_str(), LineNo); - break; - } }; + break; + } + }; if (Decl && D->hasAttrs()) { for (auto it = D->attr_begin(); it != D->attr_end(); ++it) { Attr* Attr = (*it); - switch(Attr->getKind()) + switch (Attr->getKind()) { case attr::Kind::MaxFieldAlignment: { @@ -4453,15 +4509,15 @@ Declaration* Parser::WalkDeclaration(const clang::Decl* D) int Parser::GetAlignAs(const clang::AlignedAttr* alignedAttr) { return alignedAttr->isAlignas() && - !alignedAttr->isAlignmentErrorDependent() && - !alignedAttr->isAlignmentDependent() - ? alignedAttr->getAlignment(c->getASTContext()) - : 0; + !alignedAttr->isAlignmentErrorDependent() && + !alignedAttr->isAlignmentDependent() ? + alignedAttr->getAlignment(c->getASTContext()) : + 0; } void Parser::HandleDiagnostics(ParserResult* res) { - auto DiagClient = (DiagnosticConsumer&) c->getDiagnosticClient(); + auto DiagClient = (DiagnosticConsumer&)c->getDiagnosticClient(); auto& Diags = DiagClient.Diagnostics; // Convert the diagnostics to the managed types @@ -4477,35 +4533,35 @@ void Parser::HandleDiagnostics(ParserResult* res) PDiag.lineNumber = 0; PDiag.columnNumber = 0; - if( !Diag.Location.isInvalid() ) + if (!Diag.Location.isInvalid()) { - clang::PresumedLoc PLoc = Source.getPresumedLoc(Diag.Location); - if( PLoc.isValid() ) - { + clang::PresumedLoc PLoc = Source.getPresumedLoc(Diag.Location); + if (PLoc.isValid()) + { PDiag.lineNumber = PLoc.getLine(); PDiag.columnNumber = PLoc.getColumn(); - } + } } - switch( Diag.Level ) + switch (Diag.Level) { - case clang::DiagnosticsEngine::Ignored: - PDiag.level = ParserDiagnosticLevel::Ignored; - break; - case clang::DiagnosticsEngine::Note: - PDiag.level = ParserDiagnosticLevel::Note; - break; - case clang::DiagnosticsEngine::Warning: - PDiag.level = ParserDiagnosticLevel::Warning; - break; - case clang::DiagnosticsEngine::Error: - PDiag.level = ParserDiagnosticLevel::Error; - break; - case clang::DiagnosticsEngine::Fatal: - PDiag.level = ParserDiagnosticLevel::Fatal; - break; - default: - assertm(0, "Unhandled diagnostics level!\n"); + case clang::DiagnosticsEngine::Ignored: + PDiag.level = ParserDiagnosticLevel::Ignored; + break; + case clang::DiagnosticsEngine::Note: + PDiag.level = ParserDiagnosticLevel::Note; + break; + case clang::DiagnosticsEngine::Warning: + PDiag.level = ParserDiagnosticLevel::Warning; + break; + case clang::DiagnosticsEngine::Error: + PDiag.level = ParserDiagnosticLevel::Error; + break; + case clang::DiagnosticsEngine::Fatal: + PDiag.level = ParserDiagnosticLevel::Fatal; + break; + default: + assertm(0, "Unhandled diagnostics level!\n"); } res->Diagnostics.push_back(PDiag); @@ -4521,24 +4577,24 @@ void Parser::SetupLLVMCodegen() LLVMModule->setDataLayout(c->getTarget().getDataLayoutString()); CGM.reset(new clang::CodeGen::CodeGenModule(c->getASTContext(), nullptr, - c->getHeaderSearchOpts(), c->getPreprocessorOpts(), - c->getCodeGenOpts(), *LLVMModule, c->getDiagnostics())); + c->getHeaderSearchOpts(), c->getPreprocessorOpts(), + c->getCodeGenOpts(), *LLVMModule, c->getDiagnostics())); codeGenTypes.reset(new clang::CodeGen::CodeGenTypes(*CGM.get())); } bool Parser::SetupSourceFiles(const std::vector& SourceFiles, - std::vector& FileEntries) + std::vector& FileEntries) { // Check that the file is reachable. - clang::ConstSearchDirIterator *Dir = 0; + clang::ConstSearchDirIterator* Dir = 0; llvm::ArrayRef> Includers; for (const auto& SourceFile : SourceFiles) { auto FileEntry = c->getPreprocessor().getHeaderSearchInfo().LookupFile(SourceFile, - clang::SourceLocation(), /*isAngled*/true, - nullptr, Dir, Includers, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); + clang::SourceLocation(), /*isAngled*/ true, + nullptr, Dir, Includers, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); if (!FileEntry) return false; @@ -4563,7 +4619,8 @@ bool Parser::SetupSourceFiles(const std::vector& SourceFiles, return true; } -class SemaConsumer : public clang::SemaConsumer { +class SemaConsumer : public clang::SemaConsumer +{ public: SemaConsumer(Parser& parser, std::vector& entries) : Parser(parser) @@ -4630,7 +4687,7 @@ ParserResult* Parser::Parse(const std::vector& SourceFiles) HandleDiagnostics(res); - if(DiagClient->getNumErrors() != 0) + if (DiagClient->getNumErrors() != 0) { res->kind = ParserResultKind::Error; return res; @@ -4640,7 +4697,7 @@ ParserResult* Parser::Parse(const std::vector& SourceFiles) res->kind = ParserResultKind::Success; return res; - } +} ParserResultKind Parser::ParseArchive(const std::string& File, llvm::object::Archive* Archive, @@ -4663,23 +4720,23 @@ static ArchType ConvertArchType(unsigned int archType) { switch (archType) { - case llvm::Triple::ArchType::x86: - return ArchType::x86; - case llvm::Triple::ArchType::x86_64: - return ArchType::x86_64; - case llvm::Triple::ArchType::aarch64: - return ArchType::aarch64; - case llvm::Triple::ArchType::aarch64_be: - return ArchType::aarch64_be; - case llvm::Triple::ArchType::aarch64_32: - return ArchType::aarch64_32; - default: - assertm(0, "Unsupported architecture type!\n"); - return ArchType::UnknownArch; + case llvm::Triple::ArchType::x86: + return ArchType::x86; + case llvm::Triple::ArchType::x86_64: + return ArchType::x86_64; + case llvm::Triple::ArchType::aarch64: + return ArchType::aarch64; + case llvm::Triple::ArchType::aarch64_be: + return ArchType::aarch64_be; + case llvm::Triple::ArchType::aarch64_32: + return ArchType::aarch64_32; + default: + assertm(0, "Unsupported architecture type!\n"); + return ArchType::UnknownArch; } } -template +template static void ReadELFDependencies(const llvm::object::ELFFile& ELFFile, NativeLibrary*& NativeLib) { ELFDumper ELFDumper(&ELFFile); @@ -4798,7 +4855,7 @@ ParserResultKind Parser::ReadSymbols(llvm::StringRef File, llvm::raw_string_ostream SymStream(Sym); if (it->printName(SymStream)) - continue; + continue; SymStream.flush(); if (!Sym.empty()) @@ -4870,7 +4927,8 @@ ParserResult* Parser::ParseLibrary(const CppLinkerOptions* Opts) auto OwningBinary = std::move(BinaryOrErr.get()); auto Bin = OwningBinary.getBinary(); - if (auto Archive = llvm::dyn_cast(Bin)) { + if (auto Archive = llvm::dyn_cast(Bin)) + { res->kind = ParseArchive(FileName, Archive, res->Libraries); if (res->kind == ParserResultKind::Error) return res; @@ -4946,7 +5004,9 @@ ParserResult* ClangParser::ParseLibrary(CppLinkerOptions* Opts) } ParserResult* ClangParser::Build(CppParserOptions* Opts, - const CppLinkerOptions* LinkerOptions, const std::string& File, bool Last) + const CppLinkerOptions* LinkerOptions, + const std::string& File, + bool Last) { if (!Opts) return 0; @@ -4956,7 +5016,7 @@ ParserResult* ClangParser::Build(CppParserOptions* Opts, } ParserResult* ClangParser::Compile(CppParserOptions* Opts, - const std::string& File) + const std::string& File) { if (!Opts) return 0; @@ -4966,7 +5026,9 @@ ParserResult* ClangParser::Compile(CppParserOptions* Opts, } ParserResult* ClangParser::Link(CppParserOptions* Opts, - const CppLinkerOptions* LinkerOptions, const std::string& File, bool Last) + const CppLinkerOptions* LinkerOptions, + const std::string& File, + bool Last) { if (!Opts) return 0; @@ -5071,7 +5133,8 @@ ParserTargetInfo* Parser::GetTargetInfo() Declaration* Parser::GetDeclarationFromFriend(clang::NamedDecl* FriendDecl) { Declaration* Decl = WalkDeclarationDef(FriendDecl); - if (!Decl) return nullptr; + if (!Decl) + return nullptr; int MinLineNumberStart = std::numeric_limits::max(); int MinLineNumberEnd = std::numeric_limits::max(); diff --git a/src/CppParser/Parser.h b/src/CppParser/Parser.h index 8fb9338b..08f6e679 100644 --- a/src/CppParser/Parser.h +++ b/src/CppParser/Parser.h @@ -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 @@ #include 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& 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& SourceFiles, - std::vector& 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 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 - std::vector WalkTemplateArgumentList(const clang::TemplateArgumentList* TAL, TypeLoc* TSTL); - std::vector 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& NativeLibs); - static ParserResultKind ParseSharedLib(const std::string& File, - llvm::object::ObjectFile* ObjectFile, std::vector& NativeLibs); - ParserTargetInfo* GetTargetInfo(); - - bool LinkWindows(const CppLinkerOptions* LinkerOptions, std::vector& args, - const llvm::StringRef& Dir, llvm::StringRef& Stem, bool MinGW = false); - bool LinkELF(const CppLinkerOptions* LinkerOptions, std::vector& args, - llvm::StringRef& Dir, llvm::StringRef& Stem); - bool LinkMachO(const CppLinkerOptions* LinkerOptions, std::vector& args, - llvm::StringRef& Dir, llvm::StringRef& Stem); - - int index = 0; - std::unique_ptr c; - llvm::LLVMContext LLVMCtx; - std::unique_ptr NameMangler; - std::unique_ptr LLVMModule; - std::unique_ptr CGM; - std::unique_ptr codeGenTypes; - std::unordered_map walkedNamespaces; - std::unordered_map walkedTypeTemplateParameters; - std::unordered_map walkedTemplateTemplateParameters; - std::unordered_map walkedNonTypeTemplateParameters; - std::unordered_map walkedParameters; - std::unordered_set supportedStdTypes; - std::unordered_set supportedFunctionTemplates; -}; - -} } \ No newline at end of file + class Parser + { + friend class ASTNodeVisitor; + + public: + Parser(CppParserOptions* Opts); + + void Setup(bool Compile = false); + ParserResult* Parse(const std::vector& 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& SourceFiles, + std::vector& 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 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 + std::vector WalkTemplateArgumentList(const clang::TemplateArgumentList* TAL, TypeLoc* TSTL); + std::vector 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& NativeLibs); + static ParserResultKind ParseSharedLib(const std::string& File, + llvm::object::ObjectFile* ObjectFile, + std::vector& NativeLibs); + ParserTargetInfo* GetTargetInfo(); + + bool LinkWindows(const CppLinkerOptions* LinkerOptions, std::vector& args, const llvm::StringRef& Dir, llvm::StringRef& Stem, bool MinGW = false); + bool LinkELF(const CppLinkerOptions* LinkerOptions, std::vector& args, llvm::StringRef& Dir, llvm::StringRef& Stem); + bool LinkMachO(const CppLinkerOptions* LinkerOptions, std::vector& args, llvm::StringRef& Dir, llvm::StringRef& Stem); + + int index = 0; + std::unique_ptr c; + llvm::LLVMContext LLVMCtx; + std::unique_ptr NameMangler; + std::unique_ptr LLVMModule; + std::unique_ptr CGM; + std::unique_ptr codeGenTypes; + std::unordered_map walkedNamespaces; + std::unordered_map walkedTypeTemplateParameters; + std::unordered_map walkedTemplateTemplateParameters; + std::unordered_map walkedNonTypeTemplateParameters; + std::unordered_map walkedParameters; + std::unordered_set supportedStdTypes; + std::unordered_set supportedFunctionTemplates; + }; + +}} // namespace CppSharp::CppParser \ No newline at end of file diff --git a/src/CppParser/Sources.cpp b/src/CppParser/Sources.cpp index 66f49fce..506e1031 100644 --- a/src/CppParser/Sources.cpp +++ b/src/CppParser/Sources.cpp @@ -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 diff --git a/src/CppParser/Sources.h b/src/CppParser/Sources.h index e3a127e4..1c2941a4 100644 --- a/src/CppParser/Sources.h +++ b/src/CppParser/Sources.h @@ -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 @@ 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 diff --git a/src/CppParser/Target.cpp b/src/CppParser/Target.cpp index c4f135a0..f9d377e1 100644 --- a/src/CppParser/Target.cpp +++ b/src/CppParser/Target.cpp @@ -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() {} -} } \ No newline at end of file +}} // namespace CppSharp::CppParser \ No newline at end of file diff --git a/src/CppParser/Target.h b/src/CppParser/Target.h index b2734eb6..fabf99a6 100644 --- a/src/CppParser/Target.h +++ b/src/CppParser/Target.h @@ -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 @@ 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 diff --git a/src/CppParser/Types.h b/src/CppParser/Types.h index 69e11c00..e8a05f32 100644 --- a/src/CppParser/Types.h +++ b/src/CppParser/Types.h @@ -1,9 +1,9 @@ /************************************************************************ -* -* CppSharp -* Licensed under the MIT license. -* -************************************************************************/ + * + * CppSharp + * Licensed under the MIT license. + * + ************************************************************************/ #pragma once @@ -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 diff --git a/src/Generator.Tests/AST/TestAST.cs b/src/Generator.Tests/AST/TestAST.cs index 62a0f6d9..b1a4f00b 100644 --- a/src/Generator.Tests/AST/TestAST.cs +++ b/src/Generator.Tests/AST/TestAST.cs @@ -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 [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] diff --git a/src/Generator/Generators/QuickJS/Runtime/CppSharp_QuickJS.cpp b/src/Generator/Generators/QuickJS/Runtime/CppSharp_QuickJS.cpp index 4798f8dd..4c4b9768 100644 --- a/src/Generator/Generators/QuickJS/Runtime/CppSharp_QuickJS.cpp +++ b/src/Generator/Generators/QuickJS/Runtime/CppSharp_QuickJS.cpp @@ -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" diff --git a/src/Generator/Generators/QuickJS/Runtime/CppSharp_QuickJS.h b/src/Generator/Generators/QuickJS/Runtime/CppSharp_QuickJS.h index 5334b1c8..682bff17 100644 --- a/src/Generator/Generators/QuickJS/Runtime/CppSharp_QuickJS.h +++ b/src/Generator/Generators/QuickJS/Runtime/CppSharp_QuickJS.h @@ -12,253 +12,258 @@ extern "C" #include #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 #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 diff --git a/src/Generator/Generators/QuickJS/Runtime/CppSharp_QuickJS_Signal.cpp b/src/Generator/Generators/QuickJS/Runtime/CppSharp_QuickJS_Signal.cpp index 16de385a..8cc4264b 100644 --- a/src/Generator/Generators/QuickJS/Runtime/CppSharp_QuickJS_Signal.cpp +++ b/src/Generator/Generators/QuickJS/Runtime/CppSharp_QuickJS_Signal.cpp @@ -8,106 +8,104 @@ #include #include -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: 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" diff --git a/tests/Builtins.h b/tests/Builtins.h index e3f8acdd..154d82ed 100644 --- a/tests/Builtins.h +++ b/tests/Builtins.h @@ -3,62 +3,174 @@ #include #include -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; +} diff --git a/tests/Classes.h b/tests/Classes.h index 46c7ba18..7a43d8a1 100644 --- a/tests/Classes.h +++ b/tests/Classes.h @@ -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: class ClassWithExternalInheritance : public ClassFromAnotherUnit { - }; -//void FunctionPassClassByRef(Class* klass) { } -//Class* FunctionReturnsClassByRef() { return new Class(); } \ No newline at end of file +// void FunctionPassClassByRef(Class* klass) { } +// Class* FunctionReturnsClassByRef() { return new Class(); } \ No newline at end of file diff --git a/tests/Classes2.h b/tests/Classes2.h index d4bd0abe..a240fab0 100644 --- a/tests/Classes2.h +++ b/tests/Classes2.h @@ -2,5 +2,4 @@ class ClassFromAnotherUnit { - }; diff --git a/tests/Delegates.h b/tests/Delegates.h index 4c859af3..fada002e 100644 --- a/tests/Delegates.h +++ b/tests/Delegates.h @@ -9,7 +9,11 @@ class ClassWithDelegate public: ClassWithDelegate() {} FastDelegate OnEvent0; - void FireEvent0(int value) { if (OnEvent0) OnEvent0(value); } + void FireEvent0(int value) + { + if (OnEvent0) + OnEvent0(value); + } }; class ClassInheritsDelegate : public ClassWithDelegate diff --git a/tests/Enums.h b/tests/Enums.h index 5ca7a0f8..26079398 100644 --- a/tests/Enums.h +++ b/tests/Enums.h @@ -7,5 +7,11 @@ enum class Enum0 Item2 = 5 }; -Enum0 ReturnsEnum() { return Enum0::Item0; } -Enum0 PassAndReturnsEnum(Enum0 e) { return e; } \ No newline at end of file +Enum0 ReturnsEnum() +{ + return Enum0::Item0; +} +Enum0 PassAndReturnsEnum(Enum0 e) +{ + return e; +} \ No newline at end of file diff --git a/tests/Overloads.h b/tests/Overloads.h index d9523e83..673f7f0f 100644 --- a/tests/Overloads.h +++ b/tests/Overloads.h @@ -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; +} diff --git a/tests/dotnet/CSharp/AnonTypes.h b/tests/dotnet/CSharp/AnonTypes.h index 77b16f05..246fc45c 100644 --- a/tests/dotnet/CSharp/AnonTypes.h +++ b/tests/dotnet/CSharp/AnonTypes.h @@ -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" { } 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 diff --git a/tests/dotnet/CSharp/AnotherUnit.cpp b/tests/dotnet/CSharp/AnotherUnit.cpp index 1fef2ecd..407dd400 100644 --- a/tests/dotnet/CSharp/AnotherUnit.cpp +++ b/tests/dotnet/CSharp/AnotherUnit.cpp @@ -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 diff --git a/tests/dotnet/CSharp/AnotherUnit.h b/tests/dotnet/CSharp/AnotherUnit.h index 732de8bf..e333d802 100644 --- a/tests/dotnet/CSharp/AnotherUnit.h +++ b/tests/dotnet/CSharp/AnotherUnit.h @@ -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: ~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 diff --git a/tests/dotnet/CSharp/CSharp.cpp b/tests/dotnet/CSharp/CSharp.cpp index 4d8fd04b..f47dac84 100644 --- a/tests/dotnet/CSharp/CSharp.cpp +++ b/tests/dotnet/CSharp/CSharp.cpp @@ -4,7 +4,8 @@ Foo::Foo(const QString& name) { } -Foo::Foo(const char* name) : publicFieldMappedToEnum(TestFlag::Flag2) +Foo::Foo(const char* name) + : publicFieldMappedToEnum(TestFlag::Flag2) { A = 10; P = 50; @@ -14,7 +15,8 @@ Foo::Foo(const char* name) : publicFieldMappedToEnum(TestFlag::Flag2) } } -Foo::Foo(int a, int p) : publicFieldMappedToEnum(TestFlag::Flag2) +Foo::Foo(int a, int p) + : publicFieldMappedToEnum(TestFlag::Flag2) { A = a; P = p; @@ -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() 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 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) QColor::QColor(Qt::GlobalColor color) { - } Qux::Qux() @@ -206,7 +220,6 @@ int Qux::farAwayFunc() const void Qux::obsolete() { - } 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 return 0; } -Bar::Bar() : index(0) +Bar::Bar() + : index(0) { } @@ -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 return 1; } -Baz::Baz() : P(5), functionTypedef(0) {} +Baz::Baz() + : P(5) + , functionTypedef(0) +{ +} -Baz::Baz(Bar::Items item) : Baz() +Baz::Baz(Bar::Items item) + : Baz() { } @@ -342,18 +361,27 @@ int AbstractProprietor::parent() const return 0; } -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() return m_property + 100; } -ComplexType::ComplexType() : qFlags(QFlags(TestFlag::Flag2)) +ComplexType::ComplexType() + : qFlags(QFlags(TestFlag::Flag2)) { } -ComplexType::ComplexType(const QFlags f) : qFlags(f) +ComplexType::ComplexType(const QFlags f) + : qFlags(f) { } @@ -427,17 +457,14 @@ QFlags ComplexType::returnsQFlags() void ComplexType::takesQFlags(const QFlags 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) void P::parent(int i) { - } 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() void P::setIsBool(bool value) { - } 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 UsesPointerToEnumInParamOfVirtual::hasPointerToEnumInParam(const Q } QFlags UsesPointerToEnumInParamOfVirtual::callOverrideOfHasPointerToEnumInParam( - const UsesPointerToEnumInParamOfVirtual* object, const QFlags& pointerToEnum) + const UsesPointerToEnumInParamOfVirtual* object, + const QFlags& pointerToEnum) { return object->hasPointerToEnumInParam(pointerToEnum); } @@ -542,8 +574,8 @@ UntypedFlags operator|(UntypedFlags lhs, UntypedFlags rhs) return static_cast(static_cast(lhs) | static_cast(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() { } -void MethodsWithDefaultValues::defaultPointer(Foo *ptr1, Foo *ptr2) +void MethodsWithDefaultValues::defaultPointer(Foo* ptr1, Foo* ptr2) { } @@ -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) { } -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) { } -void MethodsWithDefaultValues::defaultRefTypeEnumImplicitCtor(const QColor &fillColor) +void MethodsWithDefaultValues::defaultRefTypeEnumImplicitCtor(const QColor& fillColor) { } @@ -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) 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) { } -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 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 { } -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() { } -QPaintDevice::QPaintDevice() : test(0) +QPaintDevice::QPaintDevice() + : test(0) { } @@ -1209,15 +1250,18 @@ InheritsFromHasSamePropertyInDerivedAbstractType::~InheritsFromHasSamePropertyIn { } -MultipleInheritanceFieldOffsetsSecondaryBase::MultipleInheritanceFieldOffsetsSecondaryBase() : secondary(2) +MultipleInheritanceFieldOffsetsSecondaryBase::MultipleInheritanceFieldOffsetsSecondaryBase() + : secondary(2) { } -MultipleInheritanceFieldOffsetsPrimaryBase::MultipleInheritanceFieldOffsetsPrimaryBase() : primary(1) +MultipleInheritanceFieldOffsetsPrimaryBase::MultipleInheritanceFieldOffsetsPrimaryBase() + : primary(1) { } -MultipleInheritanceFieldOffsets::MultipleInheritanceFieldOffsets() : own(3) +MultipleInheritanceFieldOffsets::MultipleInheritanceFieldOffsets() + : own(3) { } @@ -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() 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'; 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) 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) 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() { } -ImplementsAbstractsFromPrimaryAndSecondary::ImplementsAbstractsFromPrimaryAndSecondary() : field(200) +ImplementsAbstractsFromPrimaryAndSecondary::ImplementsAbstractsFromPrimaryAndSecondary() + : field(200) { } @@ -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) return s->i; } -ComplexArrayElement::ComplexArrayElement() : BoolField(false), IntField(0), FloatField(0) +ComplexArrayElement::ComplexArrayElement() + : BoolField(false) + , IntField(0) + , FloatField(0) { } -TestIndexedProperties::TestIndexedProperties() : field(0) +TestIndexedProperties::TestIndexedProperties() + : field(0) { } @@ -1531,8 +1590,7 @@ int TestArrays::takeArrays(Foo* arrayOfPointersToObjects[], int arrayOfPrimitive arrayOfObjects[0].A + arrayOfObjects[1].A; } -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 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) 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) 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] 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; diff --git a/tests/dotnet/CSharp/CSharp.h b/tests/dotnet/CSharp/CSharp.h index bc61b21b..137af2c0 100644 --- a/tests/dotnet/CSharp/CSharp.h +++ b/tests/dotnet/CSharp/CSharp.h @@ -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: 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 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: 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: Bar::Items itemsByValue() const; void setItemsByValue(Bar::Items value); + private: Bar::Items _items; Bar::Items _itemsByValue; @@ -238,6 +242,7 @@ public: int check(); QFlags returnsQFlags(); void takesQFlags(const QFlags f); + private: QFlags qFlags; }; @@ -293,6 +298,7 @@ public: void name(); void Name(); int property(); + protected: int _property; }; @@ -317,7 +323,8 @@ public: virtual ~UsesPointerToEnumInParamOfVirtual(); virtual QFlags hasPointerToEnumInParam(const QFlags& pointerToEnum) const; static QFlags callOverrideOfHasPointerToEnumInParam( - const UsesPointerToEnumInParamOfVirtual* object, const QFlags& pointerToEnum); + const UsesPointerToEnumInParamOfVirtual* object, + const QFlags& pointerToEnum); }; DLL_API Flags operator|(Flags lhs, Flags 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 #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: 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 { }; -class _ClassWithLeadingUnderscore { +class _ClassWithLeadingUnderscore +{ }; const int ConstFlag1 = 1; @@ -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: 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: 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 public: virtual ~HasPureVirtualWithDefaultArg() {} virtual void pureVirtualWithDefaultArg(Foo* foo = nullptr) = 0; + protected: HasPureVirtualWithDefaultArg() {} }; @@ -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 { public: void publicOverride(); + private: virtual void privateOverride(int i); }; @@ -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 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 public: IgnoredType ignoredType(); void setIgnoredType(const IgnoredType& value); + private: IgnoredType _ignoredType; }; @@ -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 }; public: - QMap(const QMap &other); + QMap(const QMap& other); class const_iterator; class iterator { public: - int test() { + int test() + { return 1; } friend class const_iterator; @@ -653,11 +669,32 @@ public: }; #define Q_PROCESSOR_WORDSIZE 8 -template 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 +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::Signed qregisterint; typedef QIntegerForSize::Unsigned qregisteruint; @@ -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: HasVirtualDtor2* getHasVirtualDtor2(); Bar* propertyWithNoVirtualDtor() const; void setPropertyWithNoVirtualDtor(Bar* bar); + private: HasVirtualDtor2* hasVirtualDtor2; Bar* bar; @@ -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()); class DLL_API TypeMappedWithOperator { public: - int operator |(int i); + int operator|(int i); }; class HasOverrideOfHasPropertyWithDerivedType; @@ -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 { }; -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 public: QWidget(); virtual void event(); + private: QObject child; }; @@ -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: virtual void protectedAbstractMethod(); virtual void protectedMethod(); virtual int protectedProperty(); + private: virtual int property(); }; @@ -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: 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: 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: 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 public: int makeMissingObjectOnVirtualCall(); void setMissingObjectOnVirtualCall(MissingObjectOnVirtualCall* value); + private: MissingObjectOnVirtualCall* stackOverflowOnVirtualCall; }; @@ -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 public: void setBaseSetter(int value); int baseSetter(); + protected: int field; }; @@ -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 #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[]; 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: }; -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: 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: int size(); void* get(int n); void setInterface(SimpleInterface* i); + private: SimpleInterface* interface; }; @@ -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 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 { 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 - struct list; +namespace CXXRecordDeclWithoutDefinition { +template +struct list; - template - struct it; +template +struct it; - template <> struct it> { }; - template <> struct it const> { }; -} +template <> +struct it> +{}; +template <> +struct it const> +{}; +} // namespace CXXRecordDeclWithoutDefinition -template +template struct TestVariableWithoutType { - template + template static constexpr int create(Args... args) { return {}; @@ -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 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 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 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 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 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 { 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*); class DLL_API PointerTester { int a; + public: PointerTester(); bool IsDefaultInstance(); @@ -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 { int DLL_API ValueTypeOutParameter(CS_OUT UnionTester* testerA, CS_OUT UnionTester* testerB); template -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& rhs) const { + inline bool operator==(const Optional& 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, Optional, - Optional, Optional, Optional) { } +inline void DLL_API InstantiateOptionalTemplate(Optional, Optional, Optional, Optional, Optional) {} -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; diff --git a/tests/dotnet/CSharp/CSharpTemplates.cpp b/tests/dotnet/CSharp/CSharpTemplates.cpp index 992e72d0..4c706e4a 100644 --- a/tests/dotnet/CSharp/CSharpTemplates.cpp +++ b/tests/dotnet/CSharp/CSharpTemplates.cpp @@ -1,6 +1,7 @@ #include "CSharpTemplates.h" -T2::T2() : field(0) +T2::T2() + : field(0) { } @@ -71,15 +72,15 @@ void TemplateSpecializer::completeSpecializationInParameter(DependentValueFields { } -void TemplateSpecializer::completeSpecializationInParameter(TwoTemplateArgs p1, - TwoTemplateArgs p2, - TwoTemplateArgs p3, - TwoTemplateArgs p4, +void TemplateSpecializer::completeSpecializationInParameter(TwoTemplateArgs p1, + TwoTemplateArgs p2, + TwoTemplateArgs p3, + TwoTemplateArgs p4, TwoTemplateArgs p5) { } -void TemplateSpecializer::completeSpecializationInParameter(TwoTemplateArgs::iterator p6, +void TemplateSpecializer::completeSpecializationInParameter(TwoTemplateArgs::iterator p6, TwoTemplateArgs::iterator p7) { } @@ -103,20 +104,7 @@ int ImplementAbstractTemplate::callFunction() return 65; } -void forceUseSpecializations(IndependentFields _1, IndependentFields _2, - IndependentFields _3, IndependentFields _4, - DependentValueFields _5, - VirtualTemplate _6, VirtualTemplate _7, - HasDefaultTemplateArgument _8, DerivedChangesTypeName _9, - TemplateWithIndexer _10, TemplateWithIndexer _11, - TemplateWithIndexer _12, TemplateWithIndexer _13, - TemplateDerivedFromRegularDynamic _14, - IndependentFields> _15, - DependentPointerFields _16, IndependentFields _17, - TemplateWithIndexer _18, IndependentFields _19, - TemplateWithIndexer _20, VirtualDependentValueFields _21, - VirtualDependentValueFields _22, VirtualDependentValueFields _23, - std::string s) +void forceUseSpecializations(IndependentFields _1, IndependentFields _2, IndependentFields _3, IndependentFields _4, DependentValueFields _5, VirtualTemplate _6, VirtualTemplate _7, HasDefaultTemplateArgument _8, DerivedChangesTypeName _9, TemplateWithIndexer _10, TemplateWithIndexer _11, TemplateWithIndexer _12, TemplateWithIndexer _13, TemplateDerivedFromRegularDynamic _14, IndependentFields> _15, DependentPointerFields _16, IndependentFields _17, TemplateWithIndexer _18, IndependentFields _19, TemplateWithIndexer _20, VirtualDependentValueFields _21, VirtualDependentValueFields _22, VirtualDependentValueFields _23, std::string s) { } diff --git a/tests/dotnet/CSharp/CSharpTemplates.h b/tests/dotnet/CSharp/CSharpTemplates.h index fd554417..7f872c21 100644 --- a/tests/dotnet/CSharp/CSharpTemplates.h +++ b/tests/dotnet/CSharp/CSharpTemplates.h @@ -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: virtual ~T2(); int getField() const; void setField(int value); + private: int field; }; -class DLL_API Ignored -{ -}; +class DLL_API Ignored{}; template class HasAbstractReturnPointer @@ -84,6 +79,7 @@ template class IndependentFields : public T1 { typedef T Type; + public: class Nested { @@ -97,7 +93,7 @@ public: IndependentFields(T2* t2); IndependentFields(float f); ~IndependentFields(); - explicit IndependentFields(const std::map &other); + explicit IndependentFields(const std::map& other); float getIndependent(); T getDependent(const T& t); Type property(); @@ -105,6 +101,7 @@ public: template void usesAdditionalDependentType(AdditionalDependentType additionalDependentType); static const int independentConst; + private: float independent; }; @@ -113,7 +110,8 @@ template const int IndependentFields::independentConst = 15; template -IndependentFields::IndependentFields() : independent(1) +IndependentFields::IndependentFields() + : independent(1) { } @@ -124,17 +122,20 @@ IndependentFields::IndependentFields(const IndependentFields& other) } template -IndependentFields::IndependentFields(const T& t) : independent(1) +IndependentFields::IndependentFields(const T& t) + : independent(1) { } template -IndependentFields::IndependentFields(T1* t1) : independent(1) +IndependentFields::IndependentFields(T1* t1) + : independent(1) { } template -IndependentFields::IndependentFields(T2* t2) : independent(1) +IndependentFields::IndependentFields(T2* t2) + : independent(1) { } @@ -145,7 +146,8 @@ IndependentFields::IndependentFields(float f) } template -IndependentFields::IndependentFields(const std::map &v) : independent(1) +IndependentFields::IndependentFields(const std::map& v) + : independent(1) { } @@ -266,15 +268,19 @@ public: HasAbstractReturnPointer* getAbstractReturnPointer(); typedef void (*DependentFunctionPointer)(T); DependentFunctionPointer dependentFunctionPointerField; + private: T field{}; - union { + union + { int unionField; }; }; template -DependentValueFields::DependentValueFields() : unionField(0), dependentFunctionPointerField(0) +DependentValueFields::DependentValueFields() + : unionField(0) + , dependentFunctionPointerField(0) { } @@ -284,7 +290,8 @@ DependentValueFields::~DependentValueFields() } template -DependentValueFields::DependentValueFields(IndependentFields i) : DependentValueFields() +DependentValueFields::DependentValueFields(IndependentFields i) + : DependentValueFields() { } @@ -363,7 +370,8 @@ public: }; template -DependentPointerFields::DependentPointerFields(T* t) : field(t) +DependentPointerFields::DependentPointerFields(T* t) + : field(t) { } @@ -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: bool operator==(const HasDefaultTemplateArgument& other); DependentValueFields returnTemplateWithRenamedTypeArg(const DependentValueFields& value); DependentValueFields propertyReturnsTemplateWithRenamedTypeArg(); + private: T field{}; static T staticField; @@ -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: T& operator[](int i); T& operator[](const T& key); T& operator[](const char* string); + private: T t[1]; HasDefaultTemplateArgument h; @@ -586,8 +598,7 @@ T& TemplateWithIndexer::operator[](const char* string) return t[0]; } -template +template class OptionalTemplateArgs { }; @@ -664,6 +675,7 @@ public: VirtualTemplate getVCopy(); void setV(VirtualTemplate* value); int function(); + private: VirtualTemplate* v; HasDefaultTemplateArgument explicitSpecialization; @@ -701,6 +713,7 @@ public: void completeSpecializationInParameter(TwoTemplateArgs::iterator p6, TwoTemplateArgs::iterator p7); VirtualTemplate returnSpecializedWithVoid(); + private: IndependentFields independentFields; DependentValueFields dependentValueFields; @@ -732,20 +745,33 @@ class PartiallySpecialized }; }; -template -class HasResultType { +template +class HasResultType +{ typedef char Yes; - typedef void *No; - template static Yes test(int, const typename U::result_type * = 0); - template static No test(double); + typedef void* No; + template + static Yes test(int, const typename U::result_type* = 0); + template + static No test(double); + public: - enum { Value = (sizeof(test(0)) == sizeof(Yes)) }; + enum + { + Value = (sizeof(test(0)) == sizeof(Yes)) + }; }; template ::Value> -struct LazyResultType { typedef typename Functor::result_type Type; }; +struct LazyResultType +{ + typedef typename Functor::result_type Type; +}; template -struct LazyResultType { typedef void Type; }; +struct LazyResultType +{ + typedef void Type; +}; template struct MapResultType @@ -765,7 +791,7 @@ public: virtual void virtualFunction(); }; -template +template class TemplateDerivedFromRegularDynamic : public RegularDynamic { public: @@ -773,12 +799,12 @@ public: ~TemplateDerivedFromRegularDynamic(); }; -template +template TemplateDerivedFromRegularDynamic::TemplateDerivedFromRegularDynamic() { } -template +template TemplateDerivedFromRegularDynamic::~TemplateDerivedFromRegularDynamic() { } @@ -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 -QFlags::QFlags(T t) : flag(Int(t)) +QFlags::QFlags(T t) + : flag(Int(t)) { } template -QFlags::QFlags(Zero) : flag(Int(0)) +QFlags::QFlags(Zero) + : flag(Int(0)) { } @@ -872,20 +902,7 @@ enum class TestFlag }; // we optimise specialisations so that only actually used ones are wrapped -void forceUseSpecializations(IndependentFields _1, IndependentFields _2, - IndependentFields _3, IndependentFields _4, - DependentValueFields _5, - VirtualTemplate _6, VirtualTemplate _7, - HasDefaultTemplateArgument _8, DerivedChangesTypeName _9, - TemplateWithIndexer _10, TemplateWithIndexer _11, - TemplateWithIndexer _12, TemplateWithIndexer _13, - TemplateDerivedFromRegularDynamic _14, - IndependentFields> _15, - DependentPointerFields _16, IndependentFields _17, - TemplateWithIndexer _18, IndependentFields _19, - TemplateWithIndexer _20, VirtualDependentValueFields _21, - VirtualDependentValueFields _22, VirtualDependentValueFields _23, - std::string s); +void forceUseSpecializations(IndependentFields _1, IndependentFields _2, IndependentFields _3, IndependentFields _4, DependentValueFields _5, VirtualTemplate _6, VirtualTemplate _7, HasDefaultTemplateArgument _8, DerivedChangesTypeName _9, TemplateWithIndexer _10, TemplateWithIndexer _11, TemplateWithIndexer _12, TemplateWithIndexer _13, TemplateDerivedFromRegularDynamic _14, IndependentFields> _15, DependentPointerFields _16, IndependentFields _17, TemplateWithIndexer _18, IndependentFields _19, TemplateWithIndexer _20, VirtualDependentValueFields _21, VirtualDependentValueFields _22, VirtualDependentValueFields _23, std::string s); void hasIgnoredParam(DependentValueFields> ii, Base _24); @@ -893,8 +910,10 @@ std::map usesValidSpecialisationOfIgnoredTemplate(); DLL_API DependentValueFields specialiseReturnOnly(); -template 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 +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) class TestForwardedClassInAnotherUnit; // Forward declaration of class as friend -template class ForwardTemplateFriendClassContainer; -template class ForwardTemplateFriendClass; +template +class ForwardTemplateFriendClassContainer; +template +class ForwardTemplateFriendClass; -template +template class ForwardTemplateFriendClassContainer { - template friend class ForwardTemplateFriendClass; + template + friend class ForwardTemplateFriendClass; }; -template +template class ForwardTemplateFriendClass { protected: - ForwardTemplateFriendClass() { } + ForwardTemplateFriendClass() {} }; class ForwardTemplateFriendClassUser : public ForwardTemplateFriendClass -{ }; +{}; -template +template class ClassWithNonTypeTemplateArgument { public: - ClassWithNonTypeTemplateArgument() { } + ClassWithNonTypeTemplateArgument() {} + private: union { @@ -935,19 +958,19 @@ private: }; class SpecializationOfClassWithNonTypeTemplateArgument : public ClassWithNonTypeTemplateArgument<0> -{ }; -template -class DLL_API FloatArrayF -{ -public: - template> - FloatArrayF(V... x) { } +{}; +template +class DLL_API FloatArrayF{ + public : + template > + FloatArrayF(V... x){} }; const FloatArrayF<6> I6{ 1., 1., 1., 0., 0., 0. }; template -DLL_API inline T FunctionTemplate(T value) { +DLL_API inline T FunctionTemplate(T value) +{ if (std::is_same::value) return 4.2 + value; else if (std::is_same::value) @@ -963,20 +986,21 @@ inline void FunctionTemplateInstantiation() } // KEEP ORDER OTHERWISE TEST WONT WORK -namespace IncompleteClassTemplatesTests -{ - template - struct StructSizeT {}; +namespace IncompleteClassTemplatesTests { +template +struct StructSizeT +{}; - template - struct StructT - { - template - struct Inc { }; - }; +template +struct StructT +{ + template + struct Inc + {}; +}; - struct Instantiation - { - StructT> st; - }; -} +struct Instantiation +{ + StructT> st; +}; +} // namespace IncompleteClassTemplatesTests diff --git a/tests/dotnet/CSharp/ExcludedUnit.hpp b/tests/dotnet/CSharp/ExcludedUnit.hpp index 4a7b38d8..63aaaead 100644 --- a/tests/dotnet/CSharp/ExcludedUnit.hpp +++ b/tests/dotnet/CSharp/ExcludedUnit.hpp @@ -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; + }; + }; }; diff --git a/tests/dotnet/Common/AnotherUnit.h b/tests/dotnet/Common/AnotherUnit.h index 1914985f..0ff233d2 100644 --- a/tests/dotnet/Common/AnotherUnit.h +++ b/tests/dotnet/Common/AnotherUnit.h @@ -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(); } diff --git a/tests/dotnet/Common/Common.cpp b/tests/dotnet/Common/Common.cpp index 47076a02..55c66b34 100644 --- a/tests/dotnet/Common/Common.cpp +++ b/tests/dotnet/Common/Common.cpp @@ -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) 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; 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() 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 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() 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) 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) } 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) 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() 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) _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) { } -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) 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) } 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) throw; } -InvokesInternalCtorAmbiguity::InvokesInternalCtorAmbiguity() : ptr(0) +InvokesInternalCtorAmbiguity::InvokesInternalCtorAmbiguity() + : ptr(0) { } @@ -835,7 +885,8 @@ DLL_API const HasFriend operator-(const HasFriend& f1, const HasFriend& f2) return HasFriend(f1.m - f2.m); } -DifferentConstOverloads::DifferentConstOverloads() : i(5) +DifferentConstOverloads::DifferentConstOverloads() + : i(5) { } @@ -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) { } -HasProblematicFields::HasProblematicFields() : b(false), c(0) +HasProblematicFields::HasProblematicFields() + : b(false) + , c(0) { } @@ -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) { } -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) 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() 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) TestArraysPointers::TestArraysPointers(MyEnum* values, int count) { - if (values && count) Value = values[0]; + if (values && count) + Value = values[0]; } -TestCopyConstructorRef::TestCopyConstructorRef() : A(0), B(0) +TestCopyConstructorRef::TestCopyConstructorRef() + : A(0) + , B(0) { } @@ -1243,20 +1329,36 @@ TestCopyConstructorRef::TestCopyConstructorRef(const TestCopyConstructorRef& oth } -SomeStruct::SomeStruct() : p(1) {} +SomeStruct::SomeStruct() + : p(1) +{ +} void SomeNamespace::NamespacedAbstractImpl::AbstractMethod() { } -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" { diff --git a/tests/dotnet/Common/Common.h b/tests/dotnet/Common/Common.h index ae35cea2..56e9c33e 100644 --- a/tests/dotnet/Common/Common.h +++ b/tests/dotnet/Common/Common.h @@ -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 private: int i; }; + private: int i; }; @@ -56,6 +57,7 @@ private: Value1, Value2 }; + public: enum { @@ -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 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: 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 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 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; 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: 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 }; // The Curiously Recurring Template Pattern (CRTP) -template +template class Base { // methods within Base can use template to access members of Derived @@ -314,9 +322,7 @@ class Derived : public Base }; // 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 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 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 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 { public: static TestNotStaticClass StaticFunction(); + private: TestNotStaticClass(); }; @@ -460,51 +462,54 @@ public: template 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: 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: 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: 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 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: class DLL_API TestArraysPointers { public: - TestArraysPointers(MyEnum *values, int count); + TestArraysPointers(MyEnum* values, int count); MyEnum Value; }; @@ -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)); DLL_API decltype(nullptr) TestNullPtrTypeRet(); // Tests dependent name types -template struct DependentType +template +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 public: InvokesInternalCtorAmbiguity(); InternalCtorAmbiguity* InvokeInternalCtor(); + private: InternalCtorAmbiguity* ptr; }; @@ -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 class FriendTemplate +template +class FriendTemplate { - template + template friend FriendTemplate func(const FriendTemplate&); - template + template friend class FriendTemplate; }; @@ -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); #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 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 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: 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: virtual int retInt(const Foo& foo); }; -namespace boost +namespace boost { +template +struct is_member_pointer_cv { - template struct is_member_pointer_cv { static const bool value = false; }; - template struct is_member_pointer_cv { static const bool value = true; }; + static const bool value = false; +}; +template +struct is_member_pointer_cv +{ + static const bool value = true; +}; - // all of this below tests corner cases with type locations - template - struct make_tuple_traits - { - typedef T type; +// all of this below tests corner cases with type locations +template +struct make_tuple_traits +{ + typedef T type; - // commented away, see below (JJ) - // typedef typename IF< - // boost::is_function::value, - // T&, - // T>::RET type; - }; + // commented away, see below (JJ) + // typedef typename IF< + // boost::is_function::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 - swallow_assign const& operator=(const T&) const; - }; + swallow_assign(ignore_t (*)(ignore_t)); + template + swallow_assign const& operator=(const T&) const; + }; - swallow_assign::swallow_assign(ignore_t (*)(ignore_t)) - { - } + swallow_assign::swallow_assign(ignore_t (*)(ignore_t)) + { + } - template - swallow_assign const& swallow_assign::operator=(const T&) const - { - return *this; - } + template + swallow_assign const& swallow_assign::operator=(const T&) const + { + return *this; + } - } // namespace detail +} // namespace detail - template<> - struct make_tuple_traits - { - typedef detail::swallow_assign type; - }; +template <> +struct make_tuple_traits +{ + typedef detail::swallow_assign type; +}; - template - struct is_class_or_union - { - template - static char is_class_or_union_tester(void(U::*)(void)); - }; -} +template +struct is_class_or_union +{ + template + static char is_class_or_union_tester(void (U::*)(void)); +}; +} // namespace boost template -struct build_index_impl : build_index_impl {}; +struct build_index_impl : build_index_impl +{}; template class AbstractTemplate @@ -1074,15 +1101,18 @@ public: ~NonTrivialDtor(); static bool getDtorCalled(); static void setDtorCalled(bool value); + private: static bool dtorCalled; }; -template class ForwardedTemplate; +template +class ForwardedTemplate; ForwardedTemplate returnsForwardedTemplate(); -template class ForwardedTemplate +template +class ForwardedTemplate { ForwardedTemplate functionInForwardedTemplate() const; }; @@ -1112,8 +1142,9 @@ void TemplateWithVirtual::v() } template -int FunctionTemplateWithDependentTypeDefaultExpr(size_t size = sizeof(T)) { - return size; +int FunctionTemplateWithDependentTypeDefaultExpr(size_t size = sizeof(T)) +{ + return size; } class DLL_API DerivedFromTemplateInstantiationWithVirtual : public TemplateWithVirtual @@ -1141,13 +1172,13 @@ protected: using custom_int_t = int; DLL_API void FuncWithTypeAlias(custom_int_t i); -template +template using TypeAliasTemplate = TemplateWithVirtual; DLL_API void FuncWithTemplateTypeAlias(TypeAliasTemplate i); struct TestsTypes { - int(*FunctionNoProto)(); + int (*FunctionNoProto)(); }; template @@ -1160,7 +1191,8 @@ private: template class SpecialisesVoidInUnion { - union { + union + { SpecialisesVoid* e; }* u; }; @@ -1181,16 +1213,16 @@ public: virtual bool operator==(const HasAbstractOperator& other) = 0; }; -template +template struct _Aligned; -template +template struct _Aligned<_Len, int> { typedef int type; }; -template +template struct _Aligned<_Len, char> { typedef typename _Aligned<_Len, int>::type type; @@ -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: HasCopyAndMoveConstructor(const HasCopyAndMoveConstructor& other); HasCopyAndMoveConstructor(HasCopyAndMoveConstructor&& other); int getField(); + private: int field; }; @@ -1354,18 +1395,16 @@ struct DLL_API NestedUnionWithNested }; }; -template void TemplatedFunction(T type) +template +void TemplatedFunction(T type) { - } -inline namespace InlineNamespace +inline namespace InlineNamespace { +void FunctionInsideInlineNamespace() { - void FunctionInsideInlineNamespace() - { - - } } +} // namespace InlineNamespace union { @@ -1383,20 +1422,19 @@ union } ProtocolSpecific; -template -using UsingTemplatePtr = _Other *; +template +using UsingTemplatePtr = _Other*; struct TemplateWithUsingTemplateMember { UsingTemplatePtr _Ref; }; -namespace hasUnnamedDecl +namespace hasUnnamedDecl { +extern "C" { - extern "C" - { - } } +} // namespace hasUnnamedDecl enum ItemsDifferByCase { @@ -1404,7 +1442,8 @@ enum ItemsDifferByCase Case_A }; -template struct MyListBase +template +struct MyListBase { protected: ~MyListBase() {} @@ -1414,27 +1453,32 @@ template class MyList : public MyListBase { public: - inline MyList() { } + inline MyList() {} }; -template <> struct MyListBase +template <> +struct MyListBase { }; class MyIntList : public MyList { - inline MyIntList(MyList &&l) { } + inline MyIntList(MyList&& l) {} }; -void MyFunc(MyList *list); +void MyFunc(MyList* list); -template using InvokeGenSeq = typename T::Type; +template +using InvokeGenSeq = typename T::Type; -template struct DerivedTypeAlias; -template using TypeAlias = InvokeGenSeq>; +template +struct DerivedTypeAlias; +template +using TypeAlias = InvokeGenSeq>; -template -struct DerivedTypeAlias : TypeAlias {}; +template +struct DerivedTypeAlias : TypeAlias +{}; DLL_API ImplementsAbstractFoo freeFunctionReturnsVirtualDtor(); DLL_API void integerOverload(int i); @@ -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); struct BaseCovariant; typedef std::unique_ptr 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 clone() const override { - return PtrCovariant(new DerivedCovariant()); - } + std::unique_ptr clone() const override + { + return PtrCovariant(new DerivedCovariant()); + } }; // Issue: https://github.com/mono/CppSharp/issues/1268 template -class AbstractClassTemplate { - public: +class AbstractClassTemplate +{ +public: virtual void func() = 0; }; -class DerivedClass: public AbstractClassTemplate { - public: +class DerivedClass : public AbstractClassTemplate +{ +public: void func() override {} }; @@ -1512,15 +1566,17 @@ class DerivedClass: public AbstractClassTemplate { #include template -class TemplateClassBase { - public: +class TemplateClassBase +{ +public: using XType = X; }; template -class TemplateClass : TemplateClassBase { - public: - using typename TemplateClassBase::XType; +class TemplateClass : TemplateClassBase +{ +public: + using typename TemplateClassBase::XType; using Func = std::function; explicit TemplateClass(Func function) {} }; @@ -1536,9 +1592,13 @@ public: }; template -struct dependentVariable { static const size_t var = alignof(T); }; +struct dependentVariable +{ + static const size_t var = alignof(T); +}; -class QObjectData { +class QObjectData +{ }; QScopedPointer d_ptr; @@ -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); diff --git a/tests/dotnet/Empty/Empty.h b/tests/dotnet/Empty/Empty.h index d6d93c8d..09f50129 100644 --- a/tests/dotnet/Empty/Empty.h +++ b/tests/dotnet/Empty/Empty.h @@ -1,2 +1 @@ #include "../Tests.h" - diff --git a/tests/dotnet/Encodings/Encodings.h b/tests/dotnet/Encodings/Encodings.h index 3fe2203d..b3f2abf8 100644 --- a/tests/dotnet/Encodings/Encodings.h +++ b/tests/dotnet/Encodings/Encodings.h @@ -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; diff --git a/tests/dotnet/NamespacesBase/NamespacesBase.cpp b/tests/dotnet/NamespacesBase/NamespacesBase.cpp index c6365348..1109ca87 100644 --- a/tests/dotnet/NamespacesBase/NamespacesBase.cpp +++ b/tests/dotnet/NamespacesBase/NamespacesBase.cpp @@ -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) { } diff --git a/tests/dotnet/NamespacesBase/NamespacesBase.h b/tests/dotnet/NamespacesBase/NamespacesBase.h index ed351e2b..e317ceda 100644 --- a/tests/dotnet/NamespacesBase/NamespacesBase.h +++ b/tests/dotnet/NamespacesBase/NamespacesBase.h @@ -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 public: T getField() const; void setField(const T& value); + private: union { @@ -79,6 +77,7 @@ public: private: T field; }; + private: union { @@ -96,6 +95,7 @@ public: }; Nested useDependentPointer(const T* t); const T& constField() const; + private: T* t = new T; Nested nested; diff --git a/tests/dotnet/NamespacesDerived/Independent.h b/tests/dotnet/NamespacesDerived/Independent.h index 90ca3d8b..cf651c18 100644 --- a/tests/dotnet/NamespacesDerived/Independent.h +++ b/tests/dotnet/NamespacesDerived/Independent.h @@ -1,3 +1,4 @@ class Derived; -template class DependentFields; +template +class DependentFields; typedef DependentFields ForwardedInIndependentHeader; \ No newline at end of file diff --git a/tests/dotnet/NamespacesDerived/NamespacesDerived.cpp b/tests/dotnet/NamespacesDerived/NamespacesDerived.cpp index d6aed0a9..ce413cac 100644 --- a/tests/dotnet/NamespacesDerived/NamespacesDerived.cpp +++ b/tests/dotnet/NamespacesDerived/NamespacesDerived.cpp @@ -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) return 0; } -void TestComments::glfwDestroyWindow(int *window) +void TestComments::glfwDestroyWindow(int* window) { } diff --git a/tests/dotnet/NamespacesDerived/NamespacesDerived.h b/tests/dotnet/NamespacesDerived/NamespacesDerived.h index f51cf417..96644256 100644 --- a/tests/dotnet/NamespacesDerived/NamespacesDerived.h +++ b/tests/dotnet/NamespacesDerived/NamespacesDerived.h @@ -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 { }; -template class TemplateClass; +template +class TemplateClass; class DLL_API Derived2 : public Base3 { @@ -66,6 +66,7 @@ public: typedef DependentFields LocalTypedefSpecialization; LocalTypedefSpecialization getLocalTypedefSpecialization(); Abstract* getAbstract(); + private: TemplateClass t; TemplateClass d; @@ -97,7 +98,7 @@ class DLL_API DerivedFromSecondaryBaseInDependency : public Derived, public Seco { }; -template +template class CustomAllocator { public: @@ -107,7 +108,8 @@ public: CustomAllocator() = default; template - CustomAllocator(const CustomAllocator&) noexcept { + CustomAllocator(const CustomAllocator&) noexcept + { } T* allocate(size_t cnt, const void* = 0) { return 0; } @@ -121,25 +123,24 @@ private: std::basic_string, CustomAllocator> customAllocatedString; }; -template> +template > using vector = ::std::vector; class DLL_API StdFields { private: - vector> customAllocatedVector; + vector> 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: 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); /** * */ - class LinphoneAddress {}; + class LinphoneAddress + {}; }; DLL_API void forceUseSpecializations(ForwardedInIndependentHeader value); diff --git a/tests/dotnet/Native/AST.h b/tests/dotnet/Native/AST.h index 1ec43910..04083360 100644 --- a/tests/dotnet/Native/AST.h +++ b/tests/dotnet/Native/AST.h @@ -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 +template class TestTemplateClass { public: @@ -45,12 +54,27 @@ public: class TestTemplateFunctions { public: - template T Identity(T x) { return x; } - template void Ignore() { }; - template void MethodTemplateWithTwoTypeParameter(T t, S s) { }; - template void Ignore(TestTemplateClass v) { }; - template T Valid(TestTemplateClass v, T x) { return x; }; - template T& Valid(TestTemplateClass v, T x) const { return x; } + template + T Identity(T x) + { + return x; + } + template + void Ignore() {}; + template + void MethodTemplateWithTwoTypeParameter(T t, S s) {}; + template + void Ignore(TestTemplateClass v) {}; + template + T Valid(TestTemplateClass v, T x) + { + return x; + }; + template + T& Valid(TestTemplateClass v, T x) const + { + return x; + } }; // Explicit instantiation @@ -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: 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); template 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); @@ -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; diff --git a/tests/dotnet/Native/Enums.h b/tests/dotnet/Native/Enums.h index 1043d58a..a37dc117 100644 --- a/tests/dotnet/Native/Enums.h +++ b/tests/dotnet/Native/Enums.h @@ -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 {}; \ No newline at end of file +struct TestUniqueNames +{}; \ No newline at end of file diff --git a/tests/dotnet/Native/Passes.h b/tests/dotnet/Native/Passes.h index e3b2b9b8..e9bdd32f 100644 --- a/tests/dotnet/Native/Passes.h +++ b/tests/dotnet/Native/Passes.h @@ -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 class Foo { - void toIgnore() { } + void toIgnore() {} }; void FooStart(Foo*, int); struct TestRename { - int lowerCaseMethod(); - int lowerCaseField; + int lowerCaseMethod(); + int lowerCaseField; }; /// A simple test. @@ -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 #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 #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 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 { diff --git a/tests/dotnet/Native/Templates.h b/tests/dotnet/Native/Templates.h index b7aa2728..127076ba 100644 --- a/tests/dotnet/Native/Templates.h +++ b/tests/dotnet/Native/Templates.h @@ -1,16 +1,16 @@ -template +template struct integral_constant { static constexpr T value = Value; }; -template +template using bool_constant = integral_constant; -template +template struct is_integral : integral_constant -{ }; +{}; -template +template struct is_arithmetic : bool_constant::value> -{ }; +{}; diff --git a/tests/dotnet/StandardLib/StandardLib.h b/tests/dotnet/StandardLib/StandardLib.h index 83102cd2..3e6fe713 100644 --- a/tests/dotnet/StandardLib/StandardLib.h +++ b/tests/dotnet/StandardLib/StandardLib.h @@ -19,7 +19,7 @@ struct DLL_API TestVectors TestVectors(); std::vector GetIntVector(); int SumIntVector(std::vector& vec); - + // Should get mapped to List std::vector IntVector; // Should get mapped to List diff --git a/tests/dotnet/Tests.h b/tests/dotnet/Tests.h index d72f03aa..830a12b7 100644 --- a/tests/dotnet/Tests.h +++ b/tests/dotnet/Tests.h @@ -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) diff --git a/tests/dotnet/VTables/VTables.cpp b/tests/dotnet/VTables/VTables.cpp index 688c23a6..afdf6721 100644 --- a/tests/dotnet/VTables/VTables.cpp +++ b/tests/dotnet/VTables/VTables.cpp @@ -60,4 +60,3 @@ int DerivedClassVirtual::retInt() { return 10; } - diff --git a/tests/dotnet/VTables/VTables.h b/tests/dotnet/VTables/VTables.h index f2860087..14ed396c 100644 --- a/tests/dotnet/VTables/VTables.h +++ b/tests/dotnet/VTables/VTables.h @@ -6,7 +6,6 @@ class DLL_API Foo public: class Vfoo { - }; virtual int vfoo();